From 61cb6c90769cfb040a30d8f4657f141d612c2fe5 Mon Sep 17 00:00:00 2001 From: Navdeep Parhar Date: Sun, 15 Aug 2010 20:34:51 +0000 Subject: [PATCH 0001/1624] wakeup is required if the adapter lock is released anywhere during init and not just for the may_sleep case. Pointed out by: Isilon MFC after: 3 days --- sys/dev/cxgb/cxgb_main.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sys/dev/cxgb/cxgb_main.c b/sys/dev/cxgb/cxgb_main.c index fc66d605dd4..2dd29ac65a7 100644 --- a/sys/dev/cxgb/cxgb_main.c +++ b/sys/dev/cxgb/cxgb_main.c @@ -1778,11 +1778,12 @@ cxgb_init_locked(struct port_info *p) struct adapter *sc = p->adapter; struct ifnet *ifp = p->ifp; struct cmac *mac = &p->mac; - int i, rc = 0, may_sleep = 0; + int i, rc = 0, may_sleep = 0, gave_up_lock = 0; ADAPTER_LOCK_ASSERT_OWNED(sc); while (!IS_DOOMED(p) && IS_BUSY(sc)) { + gave_up_lock = 1; if (mtx_sleep(&sc->flags, &sc->lock, PCATCH, "cxgbinit", 0)) { rc = EINTR; goto done; @@ -1802,6 +1803,7 @@ cxgb_init_locked(struct port_info *p) if (may_sleep) { SET_BUSY(sc); + gave_up_lock = 1; ADAPTER_UNLOCK(sc); } @@ -1849,8 +1851,9 @@ done: ADAPTER_LOCK(sc); KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__)); CLR_BUSY(sc); - wakeup_one(&sc->flags); } + if (gave_up_lock) + wakeup_one(&sc->flags); ADAPTER_UNLOCK(sc); return (rc); } From 3dd6d7570f985280992a191fd1fcc8926c7bfcd0 Mon Sep 17 00:00:00 2001 From: Navdeep Parhar Date: Sun, 15 Aug 2010 20:45:16 +0000 Subject: [PATCH 0002/1624] Always reset the XGMAC's XAUI PCS on a link up. MFC after: 3 days --- sys/dev/cxgb/common/cxgb_common.h | 1 + sys/dev/cxgb/common/cxgb_t3_hw.c | 38 ++++++++++++++++++++++--------- sys/dev/cxgb/common/cxgb_xgmac.c | 31 ++++++++++++++++++++++++- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/sys/dev/cxgb/common/cxgb_common.h b/sys/dev/cxgb/common/cxgb_common.h index 1501e16751e..3760bd6084b 100644 --- a/sys/dev/cxgb/common/cxgb_common.h +++ b/sys/dev/cxgb/common/cxgb_common.h @@ -745,6 +745,7 @@ int t3_mc7_bd_read(struct mc7 *mc7, unsigned int start, unsigned int n, int t3_mac_init(struct cmac *mac); void t3b_pcs_reset(struct cmac *mac); +void t3c_pcs_force_los(struct cmac *mac); void t3_mac_disable_exact_filters(struct cmac *mac); void t3_mac_enable_exact_filters(struct cmac *mac); int t3_mac_enable(struct cmac *mac, int which); diff --git a/sys/dev/cxgb/common/cxgb_t3_hw.c b/sys/dev/cxgb/common/cxgb_t3_hw.c index ce274075d0c..610a48186bb 100644 --- a/sys/dev/cxgb/common/cxgb_t3_hw.c +++ b/sys/dev/cxgb/common/cxgb_t3_hw.c @@ -1558,6 +1558,13 @@ void t3_link_changed(adapter_t *adapter, int port_id) pi->link_fault = LF_YES; } + if (uses_xaui(adapter)) { + if (adapter->params.rev >= T3_REV_C) + t3c_pcs_force_los(mac); + else + t3b_pcs_reset(mac); + } + /* Don't report link up */ link_ok = 0; } else { @@ -1584,12 +1591,20 @@ void t3_link_changed(adapter_t *adapter, int port_id) /* down -> up, or up -> up with changed settings */ if (adapter->params.rev > 0 && uses_xaui(adapter)) { + + if (adapter->params.rev >= T3_REV_C) + t3c_pcs_force_los(mac); + else + t3b_pcs_reset(mac); + t3_write_reg(adapter, A_XGM_XAUI_ACT_CTRL + mac->offset, F_TXACTENABLE | F_RXEN); } + /* disable TX FIFO drain */ t3_set_reg_field(adapter, A_XGM_TXFIFO_CFG + mac->offset, F_ENDROPPKT, 0); + t3_mac_enable(mac, MAC_DIRECTION_TX | MAC_DIRECTION_RX); t3_set_reg_field(adapter, A_XGM_STAT_CTRL + mac->offset, F_CLRSTATS, 1); @@ -1609,20 +1624,21 @@ void t3_link_changed(adapter_t *adapter, int port_id) t3_set_reg_field(adapter, A_XGM_INT_ENABLE + mac->offset, F_XGM_INT, 0); - } - if (!link_fault) t3_mac_disable(mac, MAC_DIRECTION_RX); - /* - * Make sure Tx FIFO continues to drain, even as rxen is left - * high to help detect and indicate remote faults. - */ - t3_set_reg_field(adapter, A_XGM_TXFIFO_CFG + mac->offset, 0, - F_ENDROPPKT); - t3_write_reg(adapter, A_XGM_RX_CTRL + mac->offset, 0); - t3_write_reg(adapter, A_XGM_TX_CTRL + mac->offset, F_TXEN); - t3_write_reg(adapter, A_XGM_RX_CTRL + mac->offset, F_RXEN); + /* + * Make sure Tx FIFO continues to drain, even as rxen is + * left high to help detect and indicate remote faults. + */ + t3_set_reg_field(adapter, + A_XGM_TXFIFO_CFG + mac->offset, 0, F_ENDROPPKT); + t3_write_reg(adapter, A_XGM_RX_CTRL + mac->offset, 0); + t3_write_reg(adapter, + A_XGM_TX_CTRL + mac->offset, F_TXEN); + t3_write_reg(adapter, + A_XGM_RX_CTRL + mac->offset, F_RXEN); + } } t3_os_link_changed(adapter, port_id, link_ok, speed, duplex, fc, diff --git a/sys/dev/cxgb/common/cxgb_xgmac.c b/sys/dev/cxgb/common/cxgb_xgmac.c index 853da35ddfe..3ee2bf09a31 100644 --- a/sys/dev/cxgb/common/cxgb_xgmac.c +++ b/sys/dev/cxgb/common/cxgb_xgmac.c @@ -97,11 +97,40 @@ void t3b_pcs_reset(struct cmac *mac) { t3_set_reg_field(mac->adapter, A_XGM_RESET_CTRL + mac->offset, F_PCS_RESET_, 0); - udelay(20); + + /* No delay required */ + t3_set_reg_field(mac->adapter, A_XGM_RESET_CTRL + mac->offset, 0, F_PCS_RESET_); } +void t3c_pcs_force_los(struct cmac *mac) +{ + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT0 + mac->offset, + F_LOWSIGFORCEEN0 | F_LOWSIGFORCEVALUE0, + F_LOWSIGFORCEEN0 | F_LOWSIGFORCEVALUE0); + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT1 + mac->offset, + F_LOWSIGFORCEEN1 | F_LOWSIGFORCEVALUE1, + F_LOWSIGFORCEEN1 | F_LOWSIGFORCEVALUE1); + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT2 + mac->offset, + F_LOWSIGFORCEEN2 | F_LOWSIGFORCEVALUE2, + F_LOWSIGFORCEEN2 | F_LOWSIGFORCEVALUE2); + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT3 + mac->offset, + F_LOWSIGFORCEEN3 | F_LOWSIGFORCEVALUE3, + F_LOWSIGFORCEEN3 | F_LOWSIGFORCEVALUE3); + + /* No delay required */ + + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT0 + mac->offset, + F_LOWSIGFORCEEN0, 0); + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT1 + mac->offset, + F_LOWSIGFORCEEN1, 0); + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT2 + mac->offset, + F_LOWSIGFORCEEN2, 0); + t3_set_reg_field(mac->adapter, A_XGM_SERDES_STAT3 + mac->offset, + F_LOWSIGFORCEEN3, 0); +} + /** * t3_mac_init - initialize a MAC * @mac: the MAC to initialize From 21d68a68bf7ad414c498808ba1a1d8accfa313f9 Mon Sep 17 00:00:00 2001 From: Navdeep Parhar Date: Sun, 15 Aug 2010 20:52:15 +0000 Subject: [PATCH 0003/1624] Fix tx pause quanta and timer calculations. MFC after: 3 days --- sys/dev/cxgb/common/cxgb_xgmac.c | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/sys/dev/cxgb/common/cxgb_xgmac.c b/sys/dev/cxgb/common/cxgb_xgmac.c index 3ee2bf09a31..ea4230e62d3 100644 --- a/sys/dev/cxgb/common/cxgb_xgmac.c +++ b/sys/dev/cxgb/common/cxgb_xgmac.c @@ -462,7 +462,7 @@ static int rx_fifo_hwm(int mtu) */ int t3_mac_set_mtu(struct cmac *mac, unsigned int mtu) { - int hwm, lwm, divisor; + int hwm, lwm; int ipg; unsigned int thres, v, reg; adapter_t *adap = mac->adapter; @@ -541,16 +541,6 @@ int t3_mac_set_mtu(struct cmac *mac, unsigned int mtu) t3_set_reg_field(adap, A_XGM_TXFIFO_CFG + mac->offset, V_TXFIFOTHRESH(M_TXFIFOTHRESH) | V_TXIPG(M_TXIPG), V_TXFIFOTHRESH(thres) | V_TXIPG(ipg)); - - /* Assuming a minimum drain rate of 2.5Gbps... - */ - if (adap->params.rev > 0) { - divisor = (adap->params.rev == T3_REV_C) ? 64 : 8; - t3_write_reg(adap, A_XGM_PAUSE_TIMER + mac->offset, - (hwm - lwm) * 4 / divisor); - } - t3_write_reg(adap, A_XGM_TX_PAUSE_QUANTA + mac->offset, - MAC_RXFIFO_SIZE * 4 * 8 / 512); return 0; } @@ -570,9 +560,17 @@ int t3_mac_set_speed_duplex_fc(struct cmac *mac, int speed, int duplex, int fc) u32 val; adapter_t *adap = mac->adapter; unsigned int oft = mac->offset; + unsigned int pause_bits; if (duplex >= 0 && duplex != DUPLEX_FULL) return -EINVAL; + + pause_bits = MAC_RXFIFO_SIZE * 4 * 8; + t3_write_reg(adap, A_XGM_TX_PAUSE_QUANTA + mac->offset, + pause_bits / 512); + t3_write_reg(adap, A_XGM_PAUSE_TIMER + mac->offset, + (pause_bits >> (adap->params.rev == T3_REV_C ? 10 : 7))); + if (mac->multiport) { u32 rx_max_pkt_size = G_RXMAXPKTSIZE(t3_read_reg(adap, @@ -581,9 +579,9 @@ int t3_mac_set_speed_duplex_fc(struct cmac *mac, int speed, int duplex, int fc) val &= ~V_RXFIFOPAUSEHWM(M_RXFIFOPAUSEHWM); val |= V_RXFIFOPAUSEHWM(rx_fifo_hwm(rx_max_pkt_size) / 8); t3_write_reg(adap, A_XGM_RXFIFO_CFG + oft, val); - t3_set_reg_field(adap, A_XGM_TX_CFG + oft, F_TXPAUSEEN, F_TXPAUSEEN); + return t3_vsc7323_set_speed_fc(adap, speed, fc, mac->ext_port); } if (speed >= 0) { From b0ee1e8ae66f9f8ebb6d86e6f6c2c37bb8834bc7 Mon Sep 17 00:00:00 2001 From: Christian Brueffer Date: Sun, 15 Aug 2010 20:56:13 +0000 Subject: [PATCH 0004/1624] Use our standard section 4 SYNOPSIS. While here, fixed markup whitespace and adapted an Xref. --- share/man/man4/tpm.4 | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/share/man/man4/tpm.4 b/share/man/man4/tpm.4 index 79252ab2762..76156098f73 100644 --- a/share/man/man4/tpm.4 +++ b/share/man/man4/tpm.4 @@ -15,14 +15,26 @@ .\" .\" $FreeBSD$ .\" -.Dd March 8, 2010 +.Dd August 15, 2010 .Dt TPM 4 .Os .Sh NAME .Nm tpm .Nd Trusted Platform Module .Sh SYNOPSIS +To compile this driver into the kernel, +place the following lines in your +kernel configuration file: +.Bd -ragged -offset indent .Cd "device tpm" +.Ed +.Pp +Alternatively, to load the driver as a +module at boot time, place the following line in +.Xr loader.conf 5 : +.Bd -literal -offset indent +tpm_load="YES" +.Ed .Pp In .Pa /boot/device.hints : @@ -62,7 +74,7 @@ interrupt vector in .Pa /boot/device.hints . .Sh SEE ALSO .Xr intro 4 , -.Xr files.conf 5, +.Xr device.hints 5 , .Xr config 8 .Sh AUTHORS .An -nosplit From ae7c0700dc721dce8d6cd71ae94078b547735a2f Mon Sep 17 00:00:00 2001 From: Jilles Tjoelker Date: Sun, 15 Aug 2010 21:06:53 +0000 Subject: [PATCH 0005/1624] sh: Fix break/continue/return sometimes not skipping the rest of dot script. In our implementation and most others, a break or continue in a dot script can break or continue a loop outside the dot script. This should cause all further commands in the dot script to be skipped. However, cmdloop() did not know about this and continued to parse and execute commands from the dot script. As described in the man page, a return in a dot script in a function returns from the function, not only from the dot script. There was a similar issue as with break and continue. In various other shells, the return appears to return from the dot script, but POSIX seems not very clear about this. --- bin/sh/main.c | 5 +++-- tools/regression/bin/sh/builtins/break1.0 | 16 ++++++++++++++++ tools/regression/bin/sh/builtins/return5.0 | 17 +++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 tools/regression/bin/sh/builtins/break1.0 create mode 100644 tools/regression/bin/sh/builtins/return5.0 diff --git a/bin/sh/main.c b/bin/sh/main.c index 15ee9e72e36..b9e44240013 100644 --- a/bin/sh/main.c +++ b/bin/sh/main.c @@ -232,8 +232,9 @@ cmdloop(int top) } popstackmark(&smark); setstackmark(&smark); - if (evalskip == SKIPFILE) { - evalskip = 0; + if (evalskip != 0) { + if (evalskip == SKIPFILE) + evalskip = 0; break; } } diff --git a/tools/regression/bin/sh/builtins/break1.0 b/tools/regression/bin/sh/builtins/break1.0 new file mode 100644 index 00000000000..ba0cbb4bd26 --- /dev/null +++ b/tools/regression/bin/sh/builtins/break1.0 @@ -0,0 +1,16 @@ +# $FreeBSD$ + +if [ "$1" != nested ]; then + while :; do + set -- nested + . "$0" + echo bad2 + exit 2 + done + exit 0 +fi +# To trigger the bug, the following commands must be at the top level, +# with newlines in between. +break +echo bad1 +exit 1 diff --git a/tools/regression/bin/sh/builtins/return5.0 b/tools/regression/bin/sh/builtins/return5.0 new file mode 100644 index 00000000000..6e4b7bd751a --- /dev/null +++ b/tools/regression/bin/sh/builtins/return5.0 @@ -0,0 +1,17 @@ +# $FreeBSD$ + +if [ "$1" != nested ]; then + f() { + set -- nested + . "$0" + # Allow return to return from the function or the dot script. + return 4 + } + f + exit $(($? ^ 4)) +fi +# To trigger the bug, the following commands must be at the top level, +# with newlines in between. +return 4 +echo bad +exit 1 From af2ec7ee6b6d68065c63d8fe4555322f5af5e78c Mon Sep 17 00:00:00 2001 From: Pawel Jakub Dawidek Date: Sun, 15 Aug 2010 21:19:42 +0000 Subject: [PATCH 0006/1624] More tests. --- tools/regression/fstest/tests/chown/00.t | 757 ++++++++++++----------- 1 file changed, 388 insertions(+), 369 deletions(-) diff --git a/tools/regression/fstest/tests/chown/00.t b/tools/regression/fstest/tests/chown/00.t index 9db37090189..36b1fe71db6 100644 --- a/tools/regression/fstest/tests/chown/00.t +++ b/tools/regression/fstest/tests/chown/00.t @@ -7,9 +7,9 @@ dir=`dirname $0` . ${dir}/../misc.sh if supported lchmod; then - echo "1..264" + echo "1..1349" else - echo "1..249" + echo "1..1323" fi n0=`namegen` @@ -21,419 +21,438 @@ cdir=`pwd` cd ${n2} # super-user can always modify ownership +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 123 456 -expect 123,456 lstat ${n0} uid,gid -expect 0 chown ${n0} 0 0 -expect 0,0 lstat ${n0} uid,gid -expect 0 unlink ${n0} + expect 0 chown ${n0} 123 456 + expect 123,456 lstat ${n0} uid,gid + expect 0 chown ${n0} 0 0 + expect 0,0 lstat ${n0} uid,gid -expect 0 mkfifo ${n0} 0644 -expect 0 chown ${n0} 123 456 -expect 123,456 lstat ${n0} uid,gid -expect 0 chown ${n0} 0 0 -expect 0,0 lstat ${n0} uid,gid -expect 0 unlink ${n0} + expect 0 symlink ${n0} ${n1} + uidgid=`${fstest} lstat ${n1} uid,gid` + expect 0 chown ${n1} 123 456 + expect 123,456 stat ${n1} uid,gid + expect 123,456 stat ${n0} uid,gid + expect ${uidgid} lstat ${n1} uid,gid + expect 0 unlink ${n1} -expect 0 mknod ${n0} b 0644 1 2 -expect 0 chown ${n0} 123 456 -expect 123,456 lstat ${n0} uid,gid -expect 0 chown ${n0} 0 0 -expect 0,0 lstat ${n0} uid,gid -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi -expect 0 mknod ${n0} c 0644 1 2 -expect 0 chown ${n0} 123 456 -expect 123,456 lstat ${n0} uid,gid -expect 0 chown ${n0} 0 0 -expect 0,0 lstat ${n0} uid,gid -expect 0 unlink ${n0} - -expect 0 bind ${n0} -expect 0 chown ${n0} 123 456 -expect 123,456 lstat ${n0} uid,gid -expect 0 chown ${n0} 0 0 -expect 0,0 lstat ${n0} uid,gid -expect 0 unlink ${n0} - -expect 0 mkdir ${n0} 0755 -expect 0 chown ${n0} 123 456 -expect 123,456 lstat ${n0} uid,gid -expect 0 chown ${n0} 0 0 -expect 0,0 lstat ${n0} uid,gid -expect 0 rmdir ${n0} - -expect 0 create ${n0} 0644 -expect 0 symlink ${n0} ${n1} -expect 0 chown ${n1} 123 456 -expect 123,456 stat ${n1} uid,gid -expect 123,456 stat ${n0} uid,gid -expect 0 lchown ${n1} 135 579 -expect 135,579 lstat ${n1} uid,gid -expect 123,456 stat ${n1} uid,gid -expect 123,456 stat ${n0} uid,gid -expect 0 unlink ${n0} -expect 0 unlink ${n1} + create_file ${type} ${n0} + expect 0 lchown ${n0} 123 456 + expect 123,456 lstat ${n0} uid,gid + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi +done # non-super-user can modify file group if he is owner of a file and # gid he is setting is in his groups list. +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -expect 0 -u 65534 -g 65532,65531 -- chown ${n0} -1 65532 -expect 65534,65532 lstat ${n0} uid,gid -expect 0 -u 65534 -g 65532,65531 chown ${n0} 65534 65531 -expect 65534,65531 lstat ${n0} uid,gid -expect 0 unlink ${n0} + expect 0 chown ${n0} 65534 65533 + expect 65534,65533 lstat ${n0} uid,gid + expect 0 -u 65534 -g 65532,65531 -- chown ${n0} -1 65532 + expect 65534,65532 lstat ${n0} uid,gid + expect 0 -u 65534 -g 65532,65531 chown ${n0} 65534 65531 + expect 65534,65531 lstat ${n0} uid,gid + + expect 0 symlink ${n0} ${n1} + uidgid=`${fstest} lstat ${n1} uid,gid` + expect 0 chown ${n1} 65534 65533 + expect 65534,65533 stat ${n0} uid,gid + expect 65534,65533 stat ${n1} uid,gid + expect ${uidgid} lstat ${n1} uid,gid + expect 0 -u 65534 -g 65532,65531 -- chown ${n1} -1 65532 + expect 65534,65532 stat ${n0} uid,gid + expect 65534,65532 stat ${n1} uid,gid + expect ${uidgid} lstat ${n1} uid,gid + expect 0 -u 65534 -g 65532,65531 chown ${n1} 65534 65531 + expect 65534,65531 stat ${n0} uid,gid + expect 65534,65531 stat ${n1} uid,gid + expect ${uidgid} lstat ${n1} uid,gid + expect 0 unlink ${n1} + + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi + + create_file ${type} ${n0} + expect 0 lchown ${n0} 65534 65533 + expect 65534,65533 lstat ${n0} uid,gid + expect 0 -u 65534 -g 65532,65531 -- lchown ${n0} -1 65532 + expect 65534,65532 lstat ${n0} uid,gid + expect 0 -u 65534 -g 65532,65531 lchown ${n0} 65534 65531 + expect 65534,65531 lstat ${n0} uid,gid + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi +done # chown(2) return 0 if user is not owner of a file, but chown(2) is called # with both uid and gid equal to -1. +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -expect 0 -u 65532 -g 65531 -- chown ${n0} -1 -1 -expect 0 unlink ${n0} + expect 0 chown ${n0} 65534 65533 + expect 0 -u 65532 -g 65531 -- chown ${n0} -1 -1 + expect 65534,65533 stat ${n0} uid,gid + + expect 0 symlink ${n0} ${n1} + uidgid=`${fstest} lstat ${n1} uid,gid` + expect 0 chown ${n1} 65534 65533 + expect 65534,65533 stat ${n0} uid,gid + expect 65534,65533 stat ${n1} uid,gid + expect ${uidgid} lstat ${n1} uid,gid + expect 0 -u 65532 -g 65531 -- chown ${n0} -1 -1 + expect 65534,65533 stat ${n0} uid,gid + expect 65534,65533 stat ${n1} uid,gid + expect ${uidgid} lstat ${n1} uid,gid + expect 0 unlink ${n1} + + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi + + create_file ${type} ${n0} + expect 0 lchown ${n0} 65534 65533 + expect 0 -u 65532 -g 65531 -- lchown ${n0} -1 -1 + expect 65534,65533 lstat ${n0} uid,gid + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi +done # when super-user calls chown(2), set-uid and set-gid bits may be removed. +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 chown ${n0} 65532 65531 -expect "06555|0555" lstat ${n0} mode -expect 0 unlink ${n0} + expect 0 chown ${n0} 65534 65533 + expect 0 chmod ${n0} 06555 + expect 06555,65534,65533 stat ${n0} mode,uid,gid + expect 0 chown ${n0} 65532 65531 + expect "(06555|0555),65532,65531" stat ${n0} mode,uid,gid + expect 0 chmod ${n0} 06555 + expect 06555,65532,65531 stat ${n0} mode,uid,gid + expect 0 chown ${n0} 0 0 + expect "(06555|0555),0,0" stat ${n0} mode,uid,gid -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 0 0 -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 chown ${n0} 65534 65533 -expect "06555|0555" lstat ${n0} mode -expect 0 unlink ${n0} + expect 0 symlink ${n0} ${n1} + expect 0 chown ${n1} 65534 65533 + expect 0 chmod ${n1} 06555 + expect 06555,65534,65533 stat ${n0} mode,uid,gid + expect 06555,65534,65533 stat ${n1} mode,uid,gid + expect 0 chown ${n1} 65532 65531 + expect "(06555|0555),65532,65531" stat ${n0} mode,uid,gid + expect "(06555|0555),65532,65531" stat ${n1} mode,uid,gid + expect 0 chmod ${n1} 06555 + expect 06555,65532,65531 stat ${n0} mode,uid,gid + expect 06555,65532,65531 stat ${n1} mode,uid,gid + expect 0 chown ${n1} 0 0 + expect "(06555|0555),0,0" stat ${n0} mode,uid,gid + expect "(06555|0555),0,0" stat ${n1} mode,uid,gid + expect 0 unlink ${n1} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 chown ${n0} 0 0 -expect "06555|0555" lstat ${n0} mode -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi + + if [ "${type}" != "symlink" ] || supported lchmod; then + create_file ${type} ${n0} + expect 0 lchown ${n0} 65534 65533 + if supported lchmod; then + expect 0 lchmod ${n0} 06555 + else + expect 0 chmod ${n0} 06555 + fi + expect 06555,65534,65533 lstat ${n0} mode,uid,gid + expect 0 lchown ${n0} 65532 65531 + expect "(06555|0555),65532,65531" lstat ${n0} mode,uid,gid + if supported lchmod; then + expect 0 lchmod ${n0} 06555 + else + expect 0 chmod ${n0} 06555 + fi + expect 06555,65532,65531 lstat ${n0} mode,uid,gid + expect 0 lchown ${n0} 0 0 + expect "(06555|0555),0,0" lstat ${n0} mode,uid,gid + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi +done # when non-super-user calls chown(2) successfully, set-uid and set-gid bits may # be removed, except when both uid and gid are equal to -1. +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 -u 65534 -g 65533,65532 chown ${n0} 65534 65532 -expect 0555,65534,65532 lstat ${n0} mode,uid,gid -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 -u 65534 -g 65533,65532 -- chown ${n0} -1 65533 -expect 0555,65534,65533 lstat ${n0} mode,uid,gid -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 -u 65534 -g 65533,65532 -- chown ${n0} -1 -1 -expect "06555,65534,65533|0555,65534,65533" lstat ${n0} mode,uid,gid -expect 0 unlink ${n0} + expect 0 chown ${n0} 65534 65533 + expect 0 chmod ${n0} 06555 + expect 06555,65534,65533 stat ${n0} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 chown ${n0} 65534 65532 + expect 0555,65534,65532 stat ${n0} mode,uid,gid + expect 0 chmod ${n0} 06555 + expect 06555,65534,65532 stat ${n0} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 -- chown ${n0} -1 65533 + expect 0555,65534,65533 stat ${n0} mode,uid,gid + expect 0 chmod ${n0} 06555 + expect 06555,65534,65533 stat ${n0} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 -- chown ${n0} -1 -1 + expect "(06555|0555),65534,65533" stat ${n0} mode,uid,gid -expect 0 mkdir ${n0} 0755 -expect 0 chown ${n0} 65534 65533 -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 -u 65534 -g 65533,65532 chown ${n0} 65534 65532 -expect "0555,65534,65532|06555,65534,65532" lstat ${n0} mode,uid,gid -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 -u 65534 -g 65533,65532 -- chown ${n0} -1 65533 -expect "0555,65534,65533|06555,65534,65533" lstat ${n0} mode,uid,gid -expect 0 chmod ${n0} 06555 -expect 06555 lstat ${n0} mode -expect 0 -u 65534 -g 65533,65532 -- chown ${n0} -1 -1 -expect 06555,65534,65533 lstat ${n0} mode,uid,gid -expect 0 rmdir ${n0} + expect 0 symlink ${n0} ${n1} + expect 0 chown ${n1} 65534 65533 + expect 0 chmod ${n1} 06555 + expect 06555,65534,65533 stat ${n0} mode,uid,gid + expect 06555,65534,65533 stat ${n1} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 chown ${n1} 65534 65532 + expect 0555,65534,65532 stat ${n0} mode,uid,gid + expect 0555,65534,65532 stat ${n1} mode,uid,gid + expect 0 chmod ${n1} 06555 + expect 06555,65534,65532 stat ${n0} mode,uid,gid + expect 06555,65534,65532 stat ${n1} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 -- chown ${n1} -1 65533 + expect 0555,65534,65533 stat ${n0} mode,uid,gid + expect 0555,65534,65533 stat ${n1} mode,uid,gid + expect 0 chmod ${n1} 06555 + expect 06555,65534,65533 stat ${n0} mode,uid,gid + expect 06555,65534,65533 stat ${n1} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 -- chown ${n1} -1 -1 + expect "(06555|0555),65534,65533" stat ${n0} mode,uid,gid + expect "(06555|0555),65534,65533" stat ${n1} mode,uid,gid + expect 0 unlink ${n1} -if supported lchmod; then - expect 0 symlink ${n1} ${n0} - expect 0 lchown ${n0} 65534 65533 - expect 0 lchmod ${n0} 06555 - expect 06555 lstat ${n0} mode - expect 0 -u 65534 -g 65533,65532 lchown ${n0} 65534 65532 - expect 0555,65534,65532 lstat ${n0} mode,uid,gid - expect 0 lchmod ${n0} 06555 - expect 06555 lstat ${n0} mode - expect 0 -u 65534 -g 65533,65532 -- lchown ${n0} -1 65533 - expect 0555,65534,65533 lstat ${n0} mode,uid,gid - expect 0 lchmod ${n0} 06555 - expect 06555 lstat ${n0} mode - expect 0 -u 65534 -g 65533,65532 -- lchown ${n0} -1 -1 - expect 06555,65534,65533 lstat ${n0} mode,uid,gid - expect 0 unlink ${n0} -fi + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi + + if [ "${type}" != "symlink" ] || supported lchmod; then + create_file ${type} ${n0} + + expect 0 lchown ${n0} 65534 65533 + if supported lchmod; then + expect 0 lchmod ${n0} 06555 + else + expect 0 chmod ${n0} 06555 + fi + expect 06555,65534,65533 lstat ${n0} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 lchown ${n0} 65534 65532 + expect 0555,65534,65532 lstat ${n0} mode,uid,gid + if supported lchmod; then + expect 0 lchmod ${n0} 06555 + else + expect 0 chmod ${n0} 06555 + fi + expect 06555,65534,65532 lstat ${n0} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 -- lchown ${n0} -1 65533 + expect 0555,65534,65533 lstat ${n0} mode,uid,gid + if supported lchmod; then + expect 0 lchmod ${n0} 06555 + else + expect 0 chmod ${n0} 06555 + fi + expect 06555,65534,65533 lstat ${n0} mode,uid,gid + expect 0 -u 65534 -g 65533,65532 -- lchown ${n0} -1 -1 + expect "(06555|0555),65534,65533" lstat ${n0} mode,uid,gid + + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi +done # successfull chown(2) call (except uid and gid equal to -1) updates ctime. +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + ctime1=`${fstest} stat ${n0} ctime` + sleep 1 + expect 0 chown ${n0} 65534 65533 + expect 65534,65533 stat ${n0} uid,gid + ctime2=`${fstest} stat ${n0} ctime` + test_check $ctime1 -lt $ctime2 + ctime1=`${fstest} stat ${n0} ctime` + sleep 1 + expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 + expect 65534,65532 stat ${n0} uid,gid + ctime2=`${fstest} stat ${n0} ctime` + test_check $ctime1 -lt $ctime2 -expect 0 mkdir ${n0} 0755 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 rmdir ${n0} + expect 0 symlink ${n0} ${n1} + ctime1=`${fstest} stat ${n1} ctime` + sleep 1 + expect 0 chown ${n1} 65533 65532 + expect 65533,65532 stat ${n1} uid,gid + ctime2=`${fstest} stat ${n1} ctime` + test_check $ctime1 -lt $ctime2 + ctime1=`${fstest} stat ${n1} ctime` + sleep 1 + expect 0 -u 65533 -g 65531 chown ${n1} 65533 65531 + expect 65533,65531 stat ${n1} uid,gid + ctime2=`${fstest} stat ${n1} ctime` + test_check $ctime1 -lt $ctime2 + expect 0 unlink ${n1} -expect 0 mkfifo ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi -expect 0 mknod ${n0} b 0644 1 2 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + create_file ${type} ${n0} -expect 0 mknod ${n0} c 0644 1 2 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + ctime1=`${fstest} lstat ${n0} ctime` + sleep 1 + expect 0 lchown ${n0} 65534 65533 + expect 65534,65533 lstat ${n0} uid,gid + ctime2=`${fstest} lstat ${n0} ctime` + test_check $ctime1 -lt $ctime2 + ctime1=`${fstest} lstat ${n0} ctime` + sleep 1 + expect 0 -u 65534 -g 65532 lchown ${n0} 65534 65532 + expect 65534,65532 lstat ${n0} uid,gid + ctime2=`${fstest} lstat ${n0} ctime` + test_check $ctime1 -lt $ctime2 -expect 0 bind ${n0} -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi +done -expect 0 symlink ${n1} ${n0} -ctime1=`${fstest} lstat ${n0} ctime` -sleep 1 -expect 0 lchown ${n0} 65534 65533 -expect 65534,65533 lstat ${n0} uid,gid -ctime2=`${fstest} lstat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + ctime1=`${fstest} stat ${n0} ctime` + sleep 1 + expect 0 -- chown ${n0} -1 -1 + ctime2=`${fstest} stat ${n0} ctime` + todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." + test_check $ctime1 -eq $ctime2 + expect 0,0 stat ${n0} uid,gid -expect 0 mkdir ${n0} 0755 -expect 0 chown ${n0} 65534 65533 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 rmdir ${n0} + expect 0 symlink ${n0} ${n1} + ctime1=`${fstest} stat ${n1} ctime` + sleep 1 + expect 0 -- chown ${n1} -1 -1 + ctime2=`${fstest} stat ${n1} ctime` + todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." + test_check $ctime1 -eq $ctime2 + expect 0,0 stat ${n1} uid,gid + expect 0 unlink ${n1} -expect 0 mkfifo ${n0} 0644 -expect 0 chown ${n0} 65534 65533 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi -expect 0 mknod ${n0} b 0644 1 2 -expect 0 chown ${n0} 65534 65533 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + create_file ${type} ${n0} -expect 0 mknod ${n0} c 0644 1 2 -expect 0 chown ${n0} 65534 65533 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} + ctime1=`${fstest} lstat ${n0} ctime` + sleep 1 + expect 0 -- lchown ${n0} -1 -1 + ctime2=`${fstest} lstat ${n0} ctime` + todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." + test_check $ctime1 -eq $ctime2 + expect 0,0 lstat ${n0} uid,gid -expect 0 bind ${n0} -expect 0 chown ${n0} 65534 65533 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 chown ${n0} 65534 65533 -expect 0 -u 65534 -g 65532 chown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} - -expect 0 symlink ${n1} ${n0} -expect 0 lchown ${n0} 65534 65533 -ctime1=`${fstest} lstat ${n0} ctime` -sleep 1 -expect 0 -u 65534 -g 65532 lchown ${n0} 65534 65532 -expect 65534,65532 lstat ${n0} uid,gid -ctime2=`${fstest} lstat ${n0} ctime` -test_check $ctime1 -lt $ctime2 -expect 0 unlink ${n0} - -expect 0 create ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -- chown ${n0} -1 -1 -ctime2=`${fstest} stat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} - -expect 0 mkdir ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -- chown ${n0} -1 -1 -ctime2=`${fstest} stat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 rmdir ${n0} - -expect 0 mkfifo ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -- chown ${n0} -1 -1 -ctime2=`${fstest} stat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} - -expect 0 mknod ${n0} b 0644 1 2 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -- chown ${n0} -1 -1 -ctime2=`${fstest} stat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} - -expect 0 mknod ${n0} c 0644 1 2 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -- chown ${n0} -1 -1 -ctime2=`${fstest} stat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} - -expect 0 bind ${n0} -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect 0 -- chown ${n0} -1 -1 -ctime2=`${fstest} stat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} - -expect 0 symlink ${n1} ${n0} -ctime1=`${fstest} lstat ${n0} ctime` -sleep 1 -expect 0 -- lchown ${n0} -1 -1 -ctime2=`${fstest} lstat ${n0} ctime` -todo Linux "According to POSIX: If both owner and group are -1, the times need not be updated." -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi +done # unsuccessful chown(2) does not update ctime. +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n0} -expect 0 create ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -- chown ${n0} 65534 -1 -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} + ctime1=`${fstest} stat ${n0} ctime` + sleep 1 + expect EPERM -u 65534 -- chown ${n0} 65534 -1 + expect EPERM -u 65534 -g 65534 -- chown ${n0} -1 65534 + expect EPERM -u 65534 -g 65534 chown ${n0} 65534 65534 + ctime2=`${fstest} stat ${n0} ctime` + test_check $ctime1 -eq $ctime2 + expect 0,0 stat ${n0} uid,gid -expect 0 mkdir ${n0} 0755 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -g 65534 -- chown ${n0} -1 65534 -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 rmdir ${n0} + expect 0 symlink ${n0} ${n1} + ctime1=`${fstest} stat ${n1} ctime` + sleep 1 + expect EPERM -u 65534 -- chown ${n1} 65534 -1 + expect EPERM -u 65534 -g 65534 -- chown ${n1} -1 65534 + expect EPERM -u 65534 -g 65534 chown ${n1} 65534 65534 + ctime2=`${fstest} stat ${n1} ctime` + test_check $ctime1 -eq $ctime2 + expect 0,0 stat ${n1} uid,gid + expect 0 unlink ${n1} -expect 0 mkfifo ${n0} 0644 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -g 65534 chown ${n0} 65534 65534 -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi + fi -expect 0 mknod ${n0} b 0644 1 2 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -g 65534 chown ${n0} 65534 65534 -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} + create_file ${type} ${n0} -expect 0 mknod ${n0} c 0644 1 2 -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -g 65534 chown ${n0} 65534 65534 -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} + ctime1=`${fstest} lstat ${n0} ctime` + sleep 1 + expect EPERM -u 65534 -- lchown ${n0} 65534 -1 + expect EPERM -u 65534 -g 65534 -- lchown ${n0} -1 65534 + expect EPERM -u 65534 -g 65534 lchown ${n0} 65534 65534 + ctime2=`${fstest} lstat ${n0} ctime` + test_check $ctime1 -eq $ctime2 + expect 0,0 lstat ${n0} uid,gid -expect 0 bind ${n0} -ctime1=`${fstest} stat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -g 65534 chown ${n0} 65534 65534 -ctime2=`${fstest} stat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} - -expect 0 symlink ${n1} ${n0} -ctime1=`${fstest} lstat ${n0} ctime` -sleep 1 -expect EPERM -u 65534 -g 65534 lchown ${n0} 65534 65534 -ctime2=`${fstest} lstat ${n0} ctime` -test_check $ctime1 -eq $ctime2 -expect 0 unlink ${n0} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n0} + else + expect 0 unlink ${n0} + fi +done cd ${cdir} expect 0 rmdir ${n2} From c6d1bc95b82d76f5f25d2c1d159838a32283e9e7 Mon Sep 17 00:00:00 2001 From: Pawel Jakub Dawidek Date: Sun, 15 Aug 2010 21:20:40 +0000 Subject: [PATCH 0007/1624] Update copyright years. --- tools/regression/fstest/LICENSE | 2 +- tools/regression/fstest/fstest.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/regression/fstest/LICENSE b/tools/regression/fstest/LICENSE index 0638aadfedf..972fc1de510 100644 --- a/tools/regression/fstest/LICENSE +++ b/tools/regression/fstest/LICENSE @@ -2,7 +2,7 @@ $FreeBSD$ License for all regression tests available with fstest: -Copyright (c) 2006-2007 Pawel Jakub Dawidek +Copyright (c) 2006-2010 Pawel Jakub Dawidek All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/tools/regression/fstest/fstest.c b/tools/regression/fstest/fstest.c index 0d0b22e3ba1..9d98c617ff2 100644 --- a/tools/regression/fstest/fstest.c +++ b/tools/regression/fstest/fstest.c @@ -1,5 +1,5 @@ /*- - * Copyright (c) 2006-2007 Pawel Jakub Dawidek + * Copyright (c) 2006-2010 Pawel Jakub Dawidek * All rights reserved. * * Redistribution and use in source and binary forms, with or without From 5a311552153d8e36740ab9519b04f536ca5431b2 Mon Sep 17 00:00:00 2001 From: Pawel Jakub Dawidek Date: Sun, 15 Aug 2010 21:24:17 +0000 Subject: [PATCH 0008/1624] Give fstest a more unique name: pjdfstest. It is released from time to time and used outside FreeBSD, so it is good to have a name one can google. --- tools/regression/{fstest => pjdfstest}/LICENSE | 0 tools/regression/{fstest => pjdfstest}/Makefile | 0 tools/regression/{fstest => pjdfstest}/README | 0 tools/regression/{fstest => pjdfstest}/fstest.c | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/chflags/13.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/chmod/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/chown/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/conf | 0 tools/regression/{fstest => pjdfstest}/tests/granular/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/granular/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/granular/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/granular/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/granular/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/granular/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/13.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/14.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/15.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/16.t | 0 tools/regression/{fstest => pjdfstest}/tests/link/17.t | 0 tools/regression/{fstest => pjdfstest}/tests/misc.sh | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkdir/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/mkfifo/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/mknod/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/13.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/14.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/15.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/16.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/17.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/18.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/19.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/20.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/21.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/22.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/23.t | 0 tools/regression/{fstest => pjdfstest}/tests/open/24.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/13.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/14.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/15.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/16.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/17.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/18.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/19.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/20.t | 0 tools/regression/{fstest => pjdfstest}/tests/rename/21.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/13.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/14.t | 0 tools/regression/{fstest => pjdfstest}/tests/rmdir/15.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/symlink/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/13.t | 0 tools/regression/{fstest => pjdfstest}/tests/truncate/14.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/00.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/01.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/02.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/03.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/04.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/05.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/06.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/07.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/08.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/09.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/10.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/11.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/12.t | 0 tools/regression/{fstest => pjdfstest}/tests/unlink/13.t | 0 211 files changed, 0 insertions(+), 0 deletions(-) rename tools/regression/{fstest => pjdfstest}/LICENSE (100%) rename tools/regression/{fstest => pjdfstest}/Makefile (100%) rename tools/regression/{fstest => pjdfstest}/README (100%) rename tools/regression/{fstest => pjdfstest}/fstest.c (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chflags/13.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chmod/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/chown/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/conf (100%) rename tools/regression/{fstest => pjdfstest}/tests/granular/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/granular/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/granular/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/granular/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/granular/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/granular/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/13.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/14.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/15.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/16.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/link/17.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/misc.sh (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkdir/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mkfifo/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/mknod/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/13.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/14.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/15.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/16.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/17.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/18.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/19.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/20.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/21.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/22.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/23.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/open/24.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/13.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/14.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/15.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/16.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/17.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/18.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/19.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/20.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rename/21.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/13.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/14.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/rmdir/15.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/symlink/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/13.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/truncate/14.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/00.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/01.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/02.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/03.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/04.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/05.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/06.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/07.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/08.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/09.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/10.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/11.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/12.t (100%) rename tools/regression/{fstest => pjdfstest}/tests/unlink/13.t (100%) diff --git a/tools/regression/fstest/LICENSE b/tools/regression/pjdfstest/LICENSE similarity index 100% rename from tools/regression/fstest/LICENSE rename to tools/regression/pjdfstest/LICENSE diff --git a/tools/regression/fstest/Makefile b/tools/regression/pjdfstest/Makefile similarity index 100% rename from tools/regression/fstest/Makefile rename to tools/regression/pjdfstest/Makefile diff --git a/tools/regression/fstest/README b/tools/regression/pjdfstest/README similarity index 100% rename from tools/regression/fstest/README rename to tools/regression/pjdfstest/README diff --git a/tools/regression/fstest/fstest.c b/tools/regression/pjdfstest/fstest.c similarity index 100% rename from tools/regression/fstest/fstest.c rename to tools/regression/pjdfstest/fstest.c diff --git a/tools/regression/fstest/tests/chflags/00.t b/tools/regression/pjdfstest/tests/chflags/00.t similarity index 100% rename from tools/regression/fstest/tests/chflags/00.t rename to tools/regression/pjdfstest/tests/chflags/00.t diff --git a/tools/regression/fstest/tests/chflags/01.t b/tools/regression/pjdfstest/tests/chflags/01.t similarity index 100% rename from tools/regression/fstest/tests/chflags/01.t rename to tools/regression/pjdfstest/tests/chflags/01.t diff --git a/tools/regression/fstest/tests/chflags/02.t b/tools/regression/pjdfstest/tests/chflags/02.t similarity index 100% rename from tools/regression/fstest/tests/chflags/02.t rename to tools/regression/pjdfstest/tests/chflags/02.t diff --git a/tools/regression/fstest/tests/chflags/03.t b/tools/regression/pjdfstest/tests/chflags/03.t similarity index 100% rename from tools/regression/fstest/tests/chflags/03.t rename to tools/regression/pjdfstest/tests/chflags/03.t diff --git a/tools/regression/fstest/tests/chflags/04.t b/tools/regression/pjdfstest/tests/chflags/04.t similarity index 100% rename from tools/regression/fstest/tests/chflags/04.t rename to tools/regression/pjdfstest/tests/chflags/04.t diff --git a/tools/regression/fstest/tests/chflags/05.t b/tools/regression/pjdfstest/tests/chflags/05.t similarity index 100% rename from tools/regression/fstest/tests/chflags/05.t rename to tools/regression/pjdfstest/tests/chflags/05.t diff --git a/tools/regression/fstest/tests/chflags/06.t b/tools/regression/pjdfstest/tests/chflags/06.t similarity index 100% rename from tools/regression/fstest/tests/chflags/06.t rename to tools/regression/pjdfstest/tests/chflags/06.t diff --git a/tools/regression/fstest/tests/chflags/07.t b/tools/regression/pjdfstest/tests/chflags/07.t similarity index 100% rename from tools/regression/fstest/tests/chflags/07.t rename to tools/regression/pjdfstest/tests/chflags/07.t diff --git a/tools/regression/fstest/tests/chflags/08.t b/tools/regression/pjdfstest/tests/chflags/08.t similarity index 100% rename from tools/regression/fstest/tests/chflags/08.t rename to tools/regression/pjdfstest/tests/chflags/08.t diff --git a/tools/regression/fstest/tests/chflags/09.t b/tools/regression/pjdfstest/tests/chflags/09.t similarity index 100% rename from tools/regression/fstest/tests/chflags/09.t rename to tools/regression/pjdfstest/tests/chflags/09.t diff --git a/tools/regression/fstest/tests/chflags/10.t b/tools/regression/pjdfstest/tests/chflags/10.t similarity index 100% rename from tools/regression/fstest/tests/chflags/10.t rename to tools/regression/pjdfstest/tests/chflags/10.t diff --git a/tools/regression/fstest/tests/chflags/11.t b/tools/regression/pjdfstest/tests/chflags/11.t similarity index 100% rename from tools/regression/fstest/tests/chflags/11.t rename to tools/regression/pjdfstest/tests/chflags/11.t diff --git a/tools/regression/fstest/tests/chflags/12.t b/tools/regression/pjdfstest/tests/chflags/12.t similarity index 100% rename from tools/regression/fstest/tests/chflags/12.t rename to tools/regression/pjdfstest/tests/chflags/12.t diff --git a/tools/regression/fstest/tests/chflags/13.t b/tools/regression/pjdfstest/tests/chflags/13.t similarity index 100% rename from tools/regression/fstest/tests/chflags/13.t rename to tools/regression/pjdfstest/tests/chflags/13.t diff --git a/tools/regression/fstest/tests/chmod/00.t b/tools/regression/pjdfstest/tests/chmod/00.t similarity index 100% rename from tools/regression/fstest/tests/chmod/00.t rename to tools/regression/pjdfstest/tests/chmod/00.t diff --git a/tools/regression/fstest/tests/chmod/01.t b/tools/regression/pjdfstest/tests/chmod/01.t similarity index 100% rename from tools/regression/fstest/tests/chmod/01.t rename to tools/regression/pjdfstest/tests/chmod/01.t diff --git a/tools/regression/fstest/tests/chmod/02.t b/tools/regression/pjdfstest/tests/chmod/02.t similarity index 100% rename from tools/regression/fstest/tests/chmod/02.t rename to tools/regression/pjdfstest/tests/chmod/02.t diff --git a/tools/regression/fstest/tests/chmod/03.t b/tools/regression/pjdfstest/tests/chmod/03.t similarity index 100% rename from tools/regression/fstest/tests/chmod/03.t rename to tools/regression/pjdfstest/tests/chmod/03.t diff --git a/tools/regression/fstest/tests/chmod/04.t b/tools/regression/pjdfstest/tests/chmod/04.t similarity index 100% rename from tools/regression/fstest/tests/chmod/04.t rename to tools/regression/pjdfstest/tests/chmod/04.t diff --git a/tools/regression/fstest/tests/chmod/05.t b/tools/regression/pjdfstest/tests/chmod/05.t similarity index 100% rename from tools/regression/fstest/tests/chmod/05.t rename to tools/regression/pjdfstest/tests/chmod/05.t diff --git a/tools/regression/fstest/tests/chmod/06.t b/tools/regression/pjdfstest/tests/chmod/06.t similarity index 100% rename from tools/regression/fstest/tests/chmod/06.t rename to tools/regression/pjdfstest/tests/chmod/06.t diff --git a/tools/regression/fstest/tests/chmod/07.t b/tools/regression/pjdfstest/tests/chmod/07.t similarity index 100% rename from tools/regression/fstest/tests/chmod/07.t rename to tools/regression/pjdfstest/tests/chmod/07.t diff --git a/tools/regression/fstest/tests/chmod/08.t b/tools/regression/pjdfstest/tests/chmod/08.t similarity index 100% rename from tools/regression/fstest/tests/chmod/08.t rename to tools/regression/pjdfstest/tests/chmod/08.t diff --git a/tools/regression/fstest/tests/chmod/09.t b/tools/regression/pjdfstest/tests/chmod/09.t similarity index 100% rename from tools/regression/fstest/tests/chmod/09.t rename to tools/regression/pjdfstest/tests/chmod/09.t diff --git a/tools/regression/fstest/tests/chmod/10.t b/tools/regression/pjdfstest/tests/chmod/10.t similarity index 100% rename from tools/regression/fstest/tests/chmod/10.t rename to tools/regression/pjdfstest/tests/chmod/10.t diff --git a/tools/regression/fstest/tests/chmod/11.t b/tools/regression/pjdfstest/tests/chmod/11.t similarity index 100% rename from tools/regression/fstest/tests/chmod/11.t rename to tools/regression/pjdfstest/tests/chmod/11.t diff --git a/tools/regression/fstest/tests/chmod/12.t b/tools/regression/pjdfstest/tests/chmod/12.t similarity index 100% rename from tools/regression/fstest/tests/chmod/12.t rename to tools/regression/pjdfstest/tests/chmod/12.t diff --git a/tools/regression/fstest/tests/chown/00.t b/tools/regression/pjdfstest/tests/chown/00.t similarity index 100% rename from tools/regression/fstest/tests/chown/00.t rename to tools/regression/pjdfstest/tests/chown/00.t diff --git a/tools/regression/fstest/tests/chown/01.t b/tools/regression/pjdfstest/tests/chown/01.t similarity index 100% rename from tools/regression/fstest/tests/chown/01.t rename to tools/regression/pjdfstest/tests/chown/01.t diff --git a/tools/regression/fstest/tests/chown/02.t b/tools/regression/pjdfstest/tests/chown/02.t similarity index 100% rename from tools/regression/fstest/tests/chown/02.t rename to tools/regression/pjdfstest/tests/chown/02.t diff --git a/tools/regression/fstest/tests/chown/03.t b/tools/regression/pjdfstest/tests/chown/03.t similarity index 100% rename from tools/regression/fstest/tests/chown/03.t rename to tools/regression/pjdfstest/tests/chown/03.t diff --git a/tools/regression/fstest/tests/chown/04.t b/tools/regression/pjdfstest/tests/chown/04.t similarity index 100% rename from tools/regression/fstest/tests/chown/04.t rename to tools/regression/pjdfstest/tests/chown/04.t diff --git a/tools/regression/fstest/tests/chown/05.t b/tools/regression/pjdfstest/tests/chown/05.t similarity index 100% rename from tools/regression/fstest/tests/chown/05.t rename to tools/regression/pjdfstest/tests/chown/05.t diff --git a/tools/regression/fstest/tests/chown/06.t b/tools/regression/pjdfstest/tests/chown/06.t similarity index 100% rename from tools/regression/fstest/tests/chown/06.t rename to tools/regression/pjdfstest/tests/chown/06.t diff --git a/tools/regression/fstest/tests/chown/07.t b/tools/regression/pjdfstest/tests/chown/07.t similarity index 100% rename from tools/regression/fstest/tests/chown/07.t rename to tools/regression/pjdfstest/tests/chown/07.t diff --git a/tools/regression/fstest/tests/chown/08.t b/tools/regression/pjdfstest/tests/chown/08.t similarity index 100% rename from tools/regression/fstest/tests/chown/08.t rename to tools/regression/pjdfstest/tests/chown/08.t diff --git a/tools/regression/fstest/tests/chown/09.t b/tools/regression/pjdfstest/tests/chown/09.t similarity index 100% rename from tools/regression/fstest/tests/chown/09.t rename to tools/regression/pjdfstest/tests/chown/09.t diff --git a/tools/regression/fstest/tests/chown/10.t b/tools/regression/pjdfstest/tests/chown/10.t similarity index 100% rename from tools/regression/fstest/tests/chown/10.t rename to tools/regression/pjdfstest/tests/chown/10.t diff --git a/tools/regression/fstest/tests/conf b/tools/regression/pjdfstest/tests/conf similarity index 100% rename from tools/regression/fstest/tests/conf rename to tools/regression/pjdfstest/tests/conf diff --git a/tools/regression/fstest/tests/granular/00.t b/tools/regression/pjdfstest/tests/granular/00.t similarity index 100% rename from tools/regression/fstest/tests/granular/00.t rename to tools/regression/pjdfstest/tests/granular/00.t diff --git a/tools/regression/fstest/tests/granular/01.t b/tools/regression/pjdfstest/tests/granular/01.t similarity index 100% rename from tools/regression/fstest/tests/granular/01.t rename to tools/regression/pjdfstest/tests/granular/01.t diff --git a/tools/regression/fstest/tests/granular/02.t b/tools/regression/pjdfstest/tests/granular/02.t similarity index 100% rename from tools/regression/fstest/tests/granular/02.t rename to tools/regression/pjdfstest/tests/granular/02.t diff --git a/tools/regression/fstest/tests/granular/03.t b/tools/regression/pjdfstest/tests/granular/03.t similarity index 100% rename from tools/regression/fstest/tests/granular/03.t rename to tools/regression/pjdfstest/tests/granular/03.t diff --git a/tools/regression/fstest/tests/granular/04.t b/tools/regression/pjdfstest/tests/granular/04.t similarity index 100% rename from tools/regression/fstest/tests/granular/04.t rename to tools/regression/pjdfstest/tests/granular/04.t diff --git a/tools/regression/fstest/tests/granular/05.t b/tools/regression/pjdfstest/tests/granular/05.t similarity index 100% rename from tools/regression/fstest/tests/granular/05.t rename to tools/regression/pjdfstest/tests/granular/05.t diff --git a/tools/regression/fstest/tests/link/00.t b/tools/regression/pjdfstest/tests/link/00.t similarity index 100% rename from tools/regression/fstest/tests/link/00.t rename to tools/regression/pjdfstest/tests/link/00.t diff --git a/tools/regression/fstest/tests/link/01.t b/tools/regression/pjdfstest/tests/link/01.t similarity index 100% rename from tools/regression/fstest/tests/link/01.t rename to tools/regression/pjdfstest/tests/link/01.t diff --git a/tools/regression/fstest/tests/link/02.t b/tools/regression/pjdfstest/tests/link/02.t similarity index 100% rename from tools/regression/fstest/tests/link/02.t rename to tools/regression/pjdfstest/tests/link/02.t diff --git a/tools/regression/fstest/tests/link/03.t b/tools/regression/pjdfstest/tests/link/03.t similarity index 100% rename from tools/regression/fstest/tests/link/03.t rename to tools/regression/pjdfstest/tests/link/03.t diff --git a/tools/regression/fstest/tests/link/04.t b/tools/regression/pjdfstest/tests/link/04.t similarity index 100% rename from tools/regression/fstest/tests/link/04.t rename to tools/regression/pjdfstest/tests/link/04.t diff --git a/tools/regression/fstest/tests/link/05.t b/tools/regression/pjdfstest/tests/link/05.t similarity index 100% rename from tools/regression/fstest/tests/link/05.t rename to tools/regression/pjdfstest/tests/link/05.t diff --git a/tools/regression/fstest/tests/link/06.t b/tools/regression/pjdfstest/tests/link/06.t similarity index 100% rename from tools/regression/fstest/tests/link/06.t rename to tools/regression/pjdfstest/tests/link/06.t diff --git a/tools/regression/fstest/tests/link/07.t b/tools/regression/pjdfstest/tests/link/07.t similarity index 100% rename from tools/regression/fstest/tests/link/07.t rename to tools/regression/pjdfstest/tests/link/07.t diff --git a/tools/regression/fstest/tests/link/08.t b/tools/regression/pjdfstest/tests/link/08.t similarity index 100% rename from tools/regression/fstest/tests/link/08.t rename to tools/regression/pjdfstest/tests/link/08.t diff --git a/tools/regression/fstest/tests/link/09.t b/tools/regression/pjdfstest/tests/link/09.t similarity index 100% rename from tools/regression/fstest/tests/link/09.t rename to tools/regression/pjdfstest/tests/link/09.t diff --git a/tools/regression/fstest/tests/link/10.t b/tools/regression/pjdfstest/tests/link/10.t similarity index 100% rename from tools/regression/fstest/tests/link/10.t rename to tools/regression/pjdfstest/tests/link/10.t diff --git a/tools/regression/fstest/tests/link/11.t b/tools/regression/pjdfstest/tests/link/11.t similarity index 100% rename from tools/regression/fstest/tests/link/11.t rename to tools/regression/pjdfstest/tests/link/11.t diff --git a/tools/regression/fstest/tests/link/12.t b/tools/regression/pjdfstest/tests/link/12.t similarity index 100% rename from tools/regression/fstest/tests/link/12.t rename to tools/regression/pjdfstest/tests/link/12.t diff --git a/tools/regression/fstest/tests/link/13.t b/tools/regression/pjdfstest/tests/link/13.t similarity index 100% rename from tools/regression/fstest/tests/link/13.t rename to tools/regression/pjdfstest/tests/link/13.t diff --git a/tools/regression/fstest/tests/link/14.t b/tools/regression/pjdfstest/tests/link/14.t similarity index 100% rename from tools/regression/fstest/tests/link/14.t rename to tools/regression/pjdfstest/tests/link/14.t diff --git a/tools/regression/fstest/tests/link/15.t b/tools/regression/pjdfstest/tests/link/15.t similarity index 100% rename from tools/regression/fstest/tests/link/15.t rename to tools/regression/pjdfstest/tests/link/15.t diff --git a/tools/regression/fstest/tests/link/16.t b/tools/regression/pjdfstest/tests/link/16.t similarity index 100% rename from tools/regression/fstest/tests/link/16.t rename to tools/regression/pjdfstest/tests/link/16.t diff --git a/tools/regression/fstest/tests/link/17.t b/tools/regression/pjdfstest/tests/link/17.t similarity index 100% rename from tools/regression/fstest/tests/link/17.t rename to tools/regression/pjdfstest/tests/link/17.t diff --git a/tools/regression/fstest/tests/misc.sh b/tools/regression/pjdfstest/tests/misc.sh similarity index 100% rename from tools/regression/fstest/tests/misc.sh rename to tools/regression/pjdfstest/tests/misc.sh diff --git a/tools/regression/fstest/tests/mkdir/00.t b/tools/regression/pjdfstest/tests/mkdir/00.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/00.t rename to tools/regression/pjdfstest/tests/mkdir/00.t diff --git a/tools/regression/fstest/tests/mkdir/01.t b/tools/regression/pjdfstest/tests/mkdir/01.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/01.t rename to tools/regression/pjdfstest/tests/mkdir/01.t diff --git a/tools/regression/fstest/tests/mkdir/02.t b/tools/regression/pjdfstest/tests/mkdir/02.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/02.t rename to tools/regression/pjdfstest/tests/mkdir/02.t diff --git a/tools/regression/fstest/tests/mkdir/03.t b/tools/regression/pjdfstest/tests/mkdir/03.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/03.t rename to tools/regression/pjdfstest/tests/mkdir/03.t diff --git a/tools/regression/fstest/tests/mkdir/04.t b/tools/regression/pjdfstest/tests/mkdir/04.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/04.t rename to tools/regression/pjdfstest/tests/mkdir/04.t diff --git a/tools/regression/fstest/tests/mkdir/05.t b/tools/regression/pjdfstest/tests/mkdir/05.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/05.t rename to tools/regression/pjdfstest/tests/mkdir/05.t diff --git a/tools/regression/fstest/tests/mkdir/06.t b/tools/regression/pjdfstest/tests/mkdir/06.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/06.t rename to tools/regression/pjdfstest/tests/mkdir/06.t diff --git a/tools/regression/fstest/tests/mkdir/07.t b/tools/regression/pjdfstest/tests/mkdir/07.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/07.t rename to tools/regression/pjdfstest/tests/mkdir/07.t diff --git a/tools/regression/fstest/tests/mkdir/08.t b/tools/regression/pjdfstest/tests/mkdir/08.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/08.t rename to tools/regression/pjdfstest/tests/mkdir/08.t diff --git a/tools/regression/fstest/tests/mkdir/09.t b/tools/regression/pjdfstest/tests/mkdir/09.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/09.t rename to tools/regression/pjdfstest/tests/mkdir/09.t diff --git a/tools/regression/fstest/tests/mkdir/10.t b/tools/regression/pjdfstest/tests/mkdir/10.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/10.t rename to tools/regression/pjdfstest/tests/mkdir/10.t diff --git a/tools/regression/fstest/tests/mkdir/11.t b/tools/regression/pjdfstest/tests/mkdir/11.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/11.t rename to tools/regression/pjdfstest/tests/mkdir/11.t diff --git a/tools/regression/fstest/tests/mkdir/12.t b/tools/regression/pjdfstest/tests/mkdir/12.t similarity index 100% rename from tools/regression/fstest/tests/mkdir/12.t rename to tools/regression/pjdfstest/tests/mkdir/12.t diff --git a/tools/regression/fstest/tests/mkfifo/00.t b/tools/regression/pjdfstest/tests/mkfifo/00.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/00.t rename to tools/regression/pjdfstest/tests/mkfifo/00.t diff --git a/tools/regression/fstest/tests/mkfifo/01.t b/tools/regression/pjdfstest/tests/mkfifo/01.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/01.t rename to tools/regression/pjdfstest/tests/mkfifo/01.t diff --git a/tools/regression/fstest/tests/mkfifo/02.t b/tools/regression/pjdfstest/tests/mkfifo/02.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/02.t rename to tools/regression/pjdfstest/tests/mkfifo/02.t diff --git a/tools/regression/fstest/tests/mkfifo/03.t b/tools/regression/pjdfstest/tests/mkfifo/03.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/03.t rename to tools/regression/pjdfstest/tests/mkfifo/03.t diff --git a/tools/regression/fstest/tests/mkfifo/04.t b/tools/regression/pjdfstest/tests/mkfifo/04.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/04.t rename to tools/regression/pjdfstest/tests/mkfifo/04.t diff --git a/tools/regression/fstest/tests/mkfifo/05.t b/tools/regression/pjdfstest/tests/mkfifo/05.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/05.t rename to tools/regression/pjdfstest/tests/mkfifo/05.t diff --git a/tools/regression/fstest/tests/mkfifo/06.t b/tools/regression/pjdfstest/tests/mkfifo/06.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/06.t rename to tools/regression/pjdfstest/tests/mkfifo/06.t diff --git a/tools/regression/fstest/tests/mkfifo/07.t b/tools/regression/pjdfstest/tests/mkfifo/07.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/07.t rename to tools/regression/pjdfstest/tests/mkfifo/07.t diff --git a/tools/regression/fstest/tests/mkfifo/08.t b/tools/regression/pjdfstest/tests/mkfifo/08.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/08.t rename to tools/regression/pjdfstest/tests/mkfifo/08.t diff --git a/tools/regression/fstest/tests/mkfifo/09.t b/tools/regression/pjdfstest/tests/mkfifo/09.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/09.t rename to tools/regression/pjdfstest/tests/mkfifo/09.t diff --git a/tools/regression/fstest/tests/mkfifo/10.t b/tools/regression/pjdfstest/tests/mkfifo/10.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/10.t rename to tools/regression/pjdfstest/tests/mkfifo/10.t diff --git a/tools/regression/fstest/tests/mkfifo/11.t b/tools/regression/pjdfstest/tests/mkfifo/11.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/11.t rename to tools/regression/pjdfstest/tests/mkfifo/11.t diff --git a/tools/regression/fstest/tests/mkfifo/12.t b/tools/regression/pjdfstest/tests/mkfifo/12.t similarity index 100% rename from tools/regression/fstest/tests/mkfifo/12.t rename to tools/regression/pjdfstest/tests/mkfifo/12.t diff --git a/tools/regression/fstest/tests/mknod/00.t b/tools/regression/pjdfstest/tests/mknod/00.t similarity index 100% rename from tools/regression/fstest/tests/mknod/00.t rename to tools/regression/pjdfstest/tests/mknod/00.t diff --git a/tools/regression/fstest/tests/mknod/01.t b/tools/regression/pjdfstest/tests/mknod/01.t similarity index 100% rename from tools/regression/fstest/tests/mknod/01.t rename to tools/regression/pjdfstest/tests/mknod/01.t diff --git a/tools/regression/fstest/tests/mknod/02.t b/tools/regression/pjdfstest/tests/mknod/02.t similarity index 100% rename from tools/regression/fstest/tests/mknod/02.t rename to tools/regression/pjdfstest/tests/mknod/02.t diff --git a/tools/regression/fstest/tests/mknod/03.t b/tools/regression/pjdfstest/tests/mknod/03.t similarity index 100% rename from tools/regression/fstest/tests/mknod/03.t rename to tools/regression/pjdfstest/tests/mknod/03.t diff --git a/tools/regression/fstest/tests/mknod/04.t b/tools/regression/pjdfstest/tests/mknod/04.t similarity index 100% rename from tools/regression/fstest/tests/mknod/04.t rename to tools/regression/pjdfstest/tests/mknod/04.t diff --git a/tools/regression/fstest/tests/mknod/05.t b/tools/regression/pjdfstest/tests/mknod/05.t similarity index 100% rename from tools/regression/fstest/tests/mknod/05.t rename to tools/regression/pjdfstest/tests/mknod/05.t diff --git a/tools/regression/fstest/tests/mknod/06.t b/tools/regression/pjdfstest/tests/mknod/06.t similarity index 100% rename from tools/regression/fstest/tests/mknod/06.t rename to tools/regression/pjdfstest/tests/mknod/06.t diff --git a/tools/regression/fstest/tests/mknod/07.t b/tools/regression/pjdfstest/tests/mknod/07.t similarity index 100% rename from tools/regression/fstest/tests/mknod/07.t rename to tools/regression/pjdfstest/tests/mknod/07.t diff --git a/tools/regression/fstest/tests/mknod/08.t b/tools/regression/pjdfstest/tests/mknod/08.t similarity index 100% rename from tools/regression/fstest/tests/mknod/08.t rename to tools/regression/pjdfstest/tests/mknod/08.t diff --git a/tools/regression/fstest/tests/mknod/09.t b/tools/regression/pjdfstest/tests/mknod/09.t similarity index 100% rename from tools/regression/fstest/tests/mknod/09.t rename to tools/regression/pjdfstest/tests/mknod/09.t diff --git a/tools/regression/fstest/tests/mknod/10.t b/tools/regression/pjdfstest/tests/mknod/10.t similarity index 100% rename from tools/regression/fstest/tests/mknod/10.t rename to tools/regression/pjdfstest/tests/mknod/10.t diff --git a/tools/regression/fstest/tests/mknod/11.t b/tools/regression/pjdfstest/tests/mknod/11.t similarity index 100% rename from tools/regression/fstest/tests/mknod/11.t rename to tools/regression/pjdfstest/tests/mknod/11.t diff --git a/tools/regression/fstest/tests/open/00.t b/tools/regression/pjdfstest/tests/open/00.t similarity index 100% rename from tools/regression/fstest/tests/open/00.t rename to tools/regression/pjdfstest/tests/open/00.t diff --git a/tools/regression/fstest/tests/open/01.t b/tools/regression/pjdfstest/tests/open/01.t similarity index 100% rename from tools/regression/fstest/tests/open/01.t rename to tools/regression/pjdfstest/tests/open/01.t diff --git a/tools/regression/fstest/tests/open/02.t b/tools/regression/pjdfstest/tests/open/02.t similarity index 100% rename from tools/regression/fstest/tests/open/02.t rename to tools/regression/pjdfstest/tests/open/02.t diff --git a/tools/regression/fstest/tests/open/03.t b/tools/regression/pjdfstest/tests/open/03.t similarity index 100% rename from tools/regression/fstest/tests/open/03.t rename to tools/regression/pjdfstest/tests/open/03.t diff --git a/tools/regression/fstest/tests/open/04.t b/tools/regression/pjdfstest/tests/open/04.t similarity index 100% rename from tools/regression/fstest/tests/open/04.t rename to tools/regression/pjdfstest/tests/open/04.t diff --git a/tools/regression/fstest/tests/open/05.t b/tools/regression/pjdfstest/tests/open/05.t similarity index 100% rename from tools/regression/fstest/tests/open/05.t rename to tools/regression/pjdfstest/tests/open/05.t diff --git a/tools/regression/fstest/tests/open/06.t b/tools/regression/pjdfstest/tests/open/06.t similarity index 100% rename from tools/regression/fstest/tests/open/06.t rename to tools/regression/pjdfstest/tests/open/06.t diff --git a/tools/regression/fstest/tests/open/07.t b/tools/regression/pjdfstest/tests/open/07.t similarity index 100% rename from tools/regression/fstest/tests/open/07.t rename to tools/regression/pjdfstest/tests/open/07.t diff --git a/tools/regression/fstest/tests/open/08.t b/tools/regression/pjdfstest/tests/open/08.t similarity index 100% rename from tools/regression/fstest/tests/open/08.t rename to tools/regression/pjdfstest/tests/open/08.t diff --git a/tools/regression/fstest/tests/open/09.t b/tools/regression/pjdfstest/tests/open/09.t similarity index 100% rename from tools/regression/fstest/tests/open/09.t rename to tools/regression/pjdfstest/tests/open/09.t diff --git a/tools/regression/fstest/tests/open/10.t b/tools/regression/pjdfstest/tests/open/10.t similarity index 100% rename from tools/regression/fstest/tests/open/10.t rename to tools/regression/pjdfstest/tests/open/10.t diff --git a/tools/regression/fstest/tests/open/11.t b/tools/regression/pjdfstest/tests/open/11.t similarity index 100% rename from tools/regression/fstest/tests/open/11.t rename to tools/regression/pjdfstest/tests/open/11.t diff --git a/tools/regression/fstest/tests/open/12.t b/tools/regression/pjdfstest/tests/open/12.t similarity index 100% rename from tools/regression/fstest/tests/open/12.t rename to tools/regression/pjdfstest/tests/open/12.t diff --git a/tools/regression/fstest/tests/open/13.t b/tools/regression/pjdfstest/tests/open/13.t similarity index 100% rename from tools/regression/fstest/tests/open/13.t rename to tools/regression/pjdfstest/tests/open/13.t diff --git a/tools/regression/fstest/tests/open/14.t b/tools/regression/pjdfstest/tests/open/14.t similarity index 100% rename from tools/regression/fstest/tests/open/14.t rename to tools/regression/pjdfstest/tests/open/14.t diff --git a/tools/regression/fstest/tests/open/15.t b/tools/regression/pjdfstest/tests/open/15.t similarity index 100% rename from tools/regression/fstest/tests/open/15.t rename to tools/regression/pjdfstest/tests/open/15.t diff --git a/tools/regression/fstest/tests/open/16.t b/tools/regression/pjdfstest/tests/open/16.t similarity index 100% rename from tools/regression/fstest/tests/open/16.t rename to tools/regression/pjdfstest/tests/open/16.t diff --git a/tools/regression/fstest/tests/open/17.t b/tools/regression/pjdfstest/tests/open/17.t similarity index 100% rename from tools/regression/fstest/tests/open/17.t rename to tools/regression/pjdfstest/tests/open/17.t diff --git a/tools/regression/fstest/tests/open/18.t b/tools/regression/pjdfstest/tests/open/18.t similarity index 100% rename from tools/regression/fstest/tests/open/18.t rename to tools/regression/pjdfstest/tests/open/18.t diff --git a/tools/regression/fstest/tests/open/19.t b/tools/regression/pjdfstest/tests/open/19.t similarity index 100% rename from tools/regression/fstest/tests/open/19.t rename to tools/regression/pjdfstest/tests/open/19.t diff --git a/tools/regression/fstest/tests/open/20.t b/tools/regression/pjdfstest/tests/open/20.t similarity index 100% rename from tools/regression/fstest/tests/open/20.t rename to tools/regression/pjdfstest/tests/open/20.t diff --git a/tools/regression/fstest/tests/open/21.t b/tools/regression/pjdfstest/tests/open/21.t similarity index 100% rename from tools/regression/fstest/tests/open/21.t rename to tools/regression/pjdfstest/tests/open/21.t diff --git a/tools/regression/fstest/tests/open/22.t b/tools/regression/pjdfstest/tests/open/22.t similarity index 100% rename from tools/regression/fstest/tests/open/22.t rename to tools/regression/pjdfstest/tests/open/22.t diff --git a/tools/regression/fstest/tests/open/23.t b/tools/regression/pjdfstest/tests/open/23.t similarity index 100% rename from tools/regression/fstest/tests/open/23.t rename to tools/regression/pjdfstest/tests/open/23.t diff --git a/tools/regression/fstest/tests/open/24.t b/tools/regression/pjdfstest/tests/open/24.t similarity index 100% rename from tools/regression/fstest/tests/open/24.t rename to tools/regression/pjdfstest/tests/open/24.t diff --git a/tools/regression/fstest/tests/rename/00.t b/tools/regression/pjdfstest/tests/rename/00.t similarity index 100% rename from tools/regression/fstest/tests/rename/00.t rename to tools/regression/pjdfstest/tests/rename/00.t diff --git a/tools/regression/fstest/tests/rename/01.t b/tools/regression/pjdfstest/tests/rename/01.t similarity index 100% rename from tools/regression/fstest/tests/rename/01.t rename to tools/regression/pjdfstest/tests/rename/01.t diff --git a/tools/regression/fstest/tests/rename/02.t b/tools/regression/pjdfstest/tests/rename/02.t similarity index 100% rename from tools/regression/fstest/tests/rename/02.t rename to tools/regression/pjdfstest/tests/rename/02.t diff --git a/tools/regression/fstest/tests/rename/03.t b/tools/regression/pjdfstest/tests/rename/03.t similarity index 100% rename from tools/regression/fstest/tests/rename/03.t rename to tools/regression/pjdfstest/tests/rename/03.t diff --git a/tools/regression/fstest/tests/rename/04.t b/tools/regression/pjdfstest/tests/rename/04.t similarity index 100% rename from tools/regression/fstest/tests/rename/04.t rename to tools/regression/pjdfstest/tests/rename/04.t diff --git a/tools/regression/fstest/tests/rename/05.t b/tools/regression/pjdfstest/tests/rename/05.t similarity index 100% rename from tools/regression/fstest/tests/rename/05.t rename to tools/regression/pjdfstest/tests/rename/05.t diff --git a/tools/regression/fstest/tests/rename/06.t b/tools/regression/pjdfstest/tests/rename/06.t similarity index 100% rename from tools/regression/fstest/tests/rename/06.t rename to tools/regression/pjdfstest/tests/rename/06.t diff --git a/tools/regression/fstest/tests/rename/07.t b/tools/regression/pjdfstest/tests/rename/07.t similarity index 100% rename from tools/regression/fstest/tests/rename/07.t rename to tools/regression/pjdfstest/tests/rename/07.t diff --git a/tools/regression/fstest/tests/rename/08.t b/tools/regression/pjdfstest/tests/rename/08.t similarity index 100% rename from tools/regression/fstest/tests/rename/08.t rename to tools/regression/pjdfstest/tests/rename/08.t diff --git a/tools/regression/fstest/tests/rename/09.t b/tools/regression/pjdfstest/tests/rename/09.t similarity index 100% rename from tools/regression/fstest/tests/rename/09.t rename to tools/regression/pjdfstest/tests/rename/09.t diff --git a/tools/regression/fstest/tests/rename/10.t b/tools/regression/pjdfstest/tests/rename/10.t similarity index 100% rename from tools/regression/fstest/tests/rename/10.t rename to tools/regression/pjdfstest/tests/rename/10.t diff --git a/tools/regression/fstest/tests/rename/11.t b/tools/regression/pjdfstest/tests/rename/11.t similarity index 100% rename from tools/regression/fstest/tests/rename/11.t rename to tools/regression/pjdfstest/tests/rename/11.t diff --git a/tools/regression/fstest/tests/rename/12.t b/tools/regression/pjdfstest/tests/rename/12.t similarity index 100% rename from tools/regression/fstest/tests/rename/12.t rename to tools/regression/pjdfstest/tests/rename/12.t diff --git a/tools/regression/fstest/tests/rename/13.t b/tools/regression/pjdfstest/tests/rename/13.t similarity index 100% rename from tools/regression/fstest/tests/rename/13.t rename to tools/regression/pjdfstest/tests/rename/13.t diff --git a/tools/regression/fstest/tests/rename/14.t b/tools/regression/pjdfstest/tests/rename/14.t similarity index 100% rename from tools/regression/fstest/tests/rename/14.t rename to tools/regression/pjdfstest/tests/rename/14.t diff --git a/tools/regression/fstest/tests/rename/15.t b/tools/regression/pjdfstest/tests/rename/15.t similarity index 100% rename from tools/regression/fstest/tests/rename/15.t rename to tools/regression/pjdfstest/tests/rename/15.t diff --git a/tools/regression/fstest/tests/rename/16.t b/tools/regression/pjdfstest/tests/rename/16.t similarity index 100% rename from tools/regression/fstest/tests/rename/16.t rename to tools/regression/pjdfstest/tests/rename/16.t diff --git a/tools/regression/fstest/tests/rename/17.t b/tools/regression/pjdfstest/tests/rename/17.t similarity index 100% rename from tools/regression/fstest/tests/rename/17.t rename to tools/regression/pjdfstest/tests/rename/17.t diff --git a/tools/regression/fstest/tests/rename/18.t b/tools/regression/pjdfstest/tests/rename/18.t similarity index 100% rename from tools/regression/fstest/tests/rename/18.t rename to tools/regression/pjdfstest/tests/rename/18.t diff --git a/tools/regression/fstest/tests/rename/19.t b/tools/regression/pjdfstest/tests/rename/19.t similarity index 100% rename from tools/regression/fstest/tests/rename/19.t rename to tools/regression/pjdfstest/tests/rename/19.t diff --git a/tools/regression/fstest/tests/rename/20.t b/tools/regression/pjdfstest/tests/rename/20.t similarity index 100% rename from tools/regression/fstest/tests/rename/20.t rename to tools/regression/pjdfstest/tests/rename/20.t diff --git a/tools/regression/fstest/tests/rename/21.t b/tools/regression/pjdfstest/tests/rename/21.t similarity index 100% rename from tools/regression/fstest/tests/rename/21.t rename to tools/regression/pjdfstest/tests/rename/21.t diff --git a/tools/regression/fstest/tests/rmdir/00.t b/tools/regression/pjdfstest/tests/rmdir/00.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/00.t rename to tools/regression/pjdfstest/tests/rmdir/00.t diff --git a/tools/regression/fstest/tests/rmdir/01.t b/tools/regression/pjdfstest/tests/rmdir/01.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/01.t rename to tools/regression/pjdfstest/tests/rmdir/01.t diff --git a/tools/regression/fstest/tests/rmdir/02.t b/tools/regression/pjdfstest/tests/rmdir/02.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/02.t rename to tools/regression/pjdfstest/tests/rmdir/02.t diff --git a/tools/regression/fstest/tests/rmdir/03.t b/tools/regression/pjdfstest/tests/rmdir/03.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/03.t rename to tools/regression/pjdfstest/tests/rmdir/03.t diff --git a/tools/regression/fstest/tests/rmdir/04.t b/tools/regression/pjdfstest/tests/rmdir/04.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/04.t rename to tools/regression/pjdfstest/tests/rmdir/04.t diff --git a/tools/regression/fstest/tests/rmdir/05.t b/tools/regression/pjdfstest/tests/rmdir/05.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/05.t rename to tools/regression/pjdfstest/tests/rmdir/05.t diff --git a/tools/regression/fstest/tests/rmdir/06.t b/tools/regression/pjdfstest/tests/rmdir/06.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/06.t rename to tools/regression/pjdfstest/tests/rmdir/06.t diff --git a/tools/regression/fstest/tests/rmdir/07.t b/tools/regression/pjdfstest/tests/rmdir/07.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/07.t rename to tools/regression/pjdfstest/tests/rmdir/07.t diff --git a/tools/regression/fstest/tests/rmdir/08.t b/tools/regression/pjdfstest/tests/rmdir/08.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/08.t rename to tools/regression/pjdfstest/tests/rmdir/08.t diff --git a/tools/regression/fstest/tests/rmdir/09.t b/tools/regression/pjdfstest/tests/rmdir/09.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/09.t rename to tools/regression/pjdfstest/tests/rmdir/09.t diff --git a/tools/regression/fstest/tests/rmdir/10.t b/tools/regression/pjdfstest/tests/rmdir/10.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/10.t rename to tools/regression/pjdfstest/tests/rmdir/10.t diff --git a/tools/regression/fstest/tests/rmdir/11.t b/tools/regression/pjdfstest/tests/rmdir/11.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/11.t rename to tools/regression/pjdfstest/tests/rmdir/11.t diff --git a/tools/regression/fstest/tests/rmdir/12.t b/tools/regression/pjdfstest/tests/rmdir/12.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/12.t rename to tools/regression/pjdfstest/tests/rmdir/12.t diff --git a/tools/regression/fstest/tests/rmdir/13.t b/tools/regression/pjdfstest/tests/rmdir/13.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/13.t rename to tools/regression/pjdfstest/tests/rmdir/13.t diff --git a/tools/regression/fstest/tests/rmdir/14.t b/tools/regression/pjdfstest/tests/rmdir/14.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/14.t rename to tools/regression/pjdfstest/tests/rmdir/14.t diff --git a/tools/regression/fstest/tests/rmdir/15.t b/tools/regression/pjdfstest/tests/rmdir/15.t similarity index 100% rename from tools/regression/fstest/tests/rmdir/15.t rename to tools/regression/pjdfstest/tests/rmdir/15.t diff --git a/tools/regression/fstest/tests/symlink/00.t b/tools/regression/pjdfstest/tests/symlink/00.t similarity index 100% rename from tools/regression/fstest/tests/symlink/00.t rename to tools/regression/pjdfstest/tests/symlink/00.t diff --git a/tools/regression/fstest/tests/symlink/01.t b/tools/regression/pjdfstest/tests/symlink/01.t similarity index 100% rename from tools/regression/fstest/tests/symlink/01.t rename to tools/regression/pjdfstest/tests/symlink/01.t diff --git a/tools/regression/fstest/tests/symlink/02.t b/tools/regression/pjdfstest/tests/symlink/02.t similarity index 100% rename from tools/regression/fstest/tests/symlink/02.t rename to tools/regression/pjdfstest/tests/symlink/02.t diff --git a/tools/regression/fstest/tests/symlink/03.t b/tools/regression/pjdfstest/tests/symlink/03.t similarity index 100% rename from tools/regression/fstest/tests/symlink/03.t rename to tools/regression/pjdfstest/tests/symlink/03.t diff --git a/tools/regression/fstest/tests/symlink/04.t b/tools/regression/pjdfstest/tests/symlink/04.t similarity index 100% rename from tools/regression/fstest/tests/symlink/04.t rename to tools/regression/pjdfstest/tests/symlink/04.t diff --git a/tools/regression/fstest/tests/symlink/05.t b/tools/regression/pjdfstest/tests/symlink/05.t similarity index 100% rename from tools/regression/fstest/tests/symlink/05.t rename to tools/regression/pjdfstest/tests/symlink/05.t diff --git a/tools/regression/fstest/tests/symlink/06.t b/tools/regression/pjdfstest/tests/symlink/06.t similarity index 100% rename from tools/regression/fstest/tests/symlink/06.t rename to tools/regression/pjdfstest/tests/symlink/06.t diff --git a/tools/regression/fstest/tests/symlink/07.t b/tools/regression/pjdfstest/tests/symlink/07.t similarity index 100% rename from tools/regression/fstest/tests/symlink/07.t rename to tools/regression/pjdfstest/tests/symlink/07.t diff --git a/tools/regression/fstest/tests/symlink/08.t b/tools/regression/pjdfstest/tests/symlink/08.t similarity index 100% rename from tools/regression/fstest/tests/symlink/08.t rename to tools/regression/pjdfstest/tests/symlink/08.t diff --git a/tools/regression/fstest/tests/symlink/09.t b/tools/regression/pjdfstest/tests/symlink/09.t similarity index 100% rename from tools/regression/fstest/tests/symlink/09.t rename to tools/regression/pjdfstest/tests/symlink/09.t diff --git a/tools/regression/fstest/tests/symlink/10.t b/tools/regression/pjdfstest/tests/symlink/10.t similarity index 100% rename from tools/regression/fstest/tests/symlink/10.t rename to tools/regression/pjdfstest/tests/symlink/10.t diff --git a/tools/regression/fstest/tests/symlink/11.t b/tools/regression/pjdfstest/tests/symlink/11.t similarity index 100% rename from tools/regression/fstest/tests/symlink/11.t rename to tools/regression/pjdfstest/tests/symlink/11.t diff --git a/tools/regression/fstest/tests/symlink/12.t b/tools/regression/pjdfstest/tests/symlink/12.t similarity index 100% rename from tools/regression/fstest/tests/symlink/12.t rename to tools/regression/pjdfstest/tests/symlink/12.t diff --git a/tools/regression/fstest/tests/truncate/00.t b/tools/regression/pjdfstest/tests/truncate/00.t similarity index 100% rename from tools/regression/fstest/tests/truncate/00.t rename to tools/regression/pjdfstest/tests/truncate/00.t diff --git a/tools/regression/fstest/tests/truncate/01.t b/tools/regression/pjdfstest/tests/truncate/01.t similarity index 100% rename from tools/regression/fstest/tests/truncate/01.t rename to tools/regression/pjdfstest/tests/truncate/01.t diff --git a/tools/regression/fstest/tests/truncate/02.t b/tools/regression/pjdfstest/tests/truncate/02.t similarity index 100% rename from tools/regression/fstest/tests/truncate/02.t rename to tools/regression/pjdfstest/tests/truncate/02.t diff --git a/tools/regression/fstest/tests/truncate/03.t b/tools/regression/pjdfstest/tests/truncate/03.t similarity index 100% rename from tools/regression/fstest/tests/truncate/03.t rename to tools/regression/pjdfstest/tests/truncate/03.t diff --git a/tools/regression/fstest/tests/truncate/04.t b/tools/regression/pjdfstest/tests/truncate/04.t similarity index 100% rename from tools/regression/fstest/tests/truncate/04.t rename to tools/regression/pjdfstest/tests/truncate/04.t diff --git a/tools/regression/fstest/tests/truncate/05.t b/tools/regression/pjdfstest/tests/truncate/05.t similarity index 100% rename from tools/regression/fstest/tests/truncate/05.t rename to tools/regression/pjdfstest/tests/truncate/05.t diff --git a/tools/regression/fstest/tests/truncate/06.t b/tools/regression/pjdfstest/tests/truncate/06.t similarity index 100% rename from tools/regression/fstest/tests/truncate/06.t rename to tools/regression/pjdfstest/tests/truncate/06.t diff --git a/tools/regression/fstest/tests/truncate/07.t b/tools/regression/pjdfstest/tests/truncate/07.t similarity index 100% rename from tools/regression/fstest/tests/truncate/07.t rename to tools/regression/pjdfstest/tests/truncate/07.t diff --git a/tools/regression/fstest/tests/truncate/08.t b/tools/regression/pjdfstest/tests/truncate/08.t similarity index 100% rename from tools/regression/fstest/tests/truncate/08.t rename to tools/regression/pjdfstest/tests/truncate/08.t diff --git a/tools/regression/fstest/tests/truncate/09.t b/tools/regression/pjdfstest/tests/truncate/09.t similarity index 100% rename from tools/regression/fstest/tests/truncate/09.t rename to tools/regression/pjdfstest/tests/truncate/09.t diff --git a/tools/regression/fstest/tests/truncate/10.t b/tools/regression/pjdfstest/tests/truncate/10.t similarity index 100% rename from tools/regression/fstest/tests/truncate/10.t rename to tools/regression/pjdfstest/tests/truncate/10.t diff --git a/tools/regression/fstest/tests/truncate/11.t b/tools/regression/pjdfstest/tests/truncate/11.t similarity index 100% rename from tools/regression/fstest/tests/truncate/11.t rename to tools/regression/pjdfstest/tests/truncate/11.t diff --git a/tools/regression/fstest/tests/truncate/12.t b/tools/regression/pjdfstest/tests/truncate/12.t similarity index 100% rename from tools/regression/fstest/tests/truncate/12.t rename to tools/regression/pjdfstest/tests/truncate/12.t diff --git a/tools/regression/fstest/tests/truncate/13.t b/tools/regression/pjdfstest/tests/truncate/13.t similarity index 100% rename from tools/regression/fstest/tests/truncate/13.t rename to tools/regression/pjdfstest/tests/truncate/13.t diff --git a/tools/regression/fstest/tests/truncate/14.t b/tools/regression/pjdfstest/tests/truncate/14.t similarity index 100% rename from tools/regression/fstest/tests/truncate/14.t rename to tools/regression/pjdfstest/tests/truncate/14.t diff --git a/tools/regression/fstest/tests/unlink/00.t b/tools/regression/pjdfstest/tests/unlink/00.t similarity index 100% rename from tools/regression/fstest/tests/unlink/00.t rename to tools/regression/pjdfstest/tests/unlink/00.t diff --git a/tools/regression/fstest/tests/unlink/01.t b/tools/regression/pjdfstest/tests/unlink/01.t similarity index 100% rename from tools/regression/fstest/tests/unlink/01.t rename to tools/regression/pjdfstest/tests/unlink/01.t diff --git a/tools/regression/fstest/tests/unlink/02.t b/tools/regression/pjdfstest/tests/unlink/02.t similarity index 100% rename from tools/regression/fstest/tests/unlink/02.t rename to tools/regression/pjdfstest/tests/unlink/02.t diff --git a/tools/regression/fstest/tests/unlink/03.t b/tools/regression/pjdfstest/tests/unlink/03.t similarity index 100% rename from tools/regression/fstest/tests/unlink/03.t rename to tools/regression/pjdfstest/tests/unlink/03.t diff --git a/tools/regression/fstest/tests/unlink/04.t b/tools/regression/pjdfstest/tests/unlink/04.t similarity index 100% rename from tools/regression/fstest/tests/unlink/04.t rename to tools/regression/pjdfstest/tests/unlink/04.t diff --git a/tools/regression/fstest/tests/unlink/05.t b/tools/regression/pjdfstest/tests/unlink/05.t similarity index 100% rename from tools/regression/fstest/tests/unlink/05.t rename to tools/regression/pjdfstest/tests/unlink/05.t diff --git a/tools/regression/fstest/tests/unlink/06.t b/tools/regression/pjdfstest/tests/unlink/06.t similarity index 100% rename from tools/regression/fstest/tests/unlink/06.t rename to tools/regression/pjdfstest/tests/unlink/06.t diff --git a/tools/regression/fstest/tests/unlink/07.t b/tools/regression/pjdfstest/tests/unlink/07.t similarity index 100% rename from tools/regression/fstest/tests/unlink/07.t rename to tools/regression/pjdfstest/tests/unlink/07.t diff --git a/tools/regression/fstest/tests/unlink/08.t b/tools/regression/pjdfstest/tests/unlink/08.t similarity index 100% rename from tools/regression/fstest/tests/unlink/08.t rename to tools/regression/pjdfstest/tests/unlink/08.t diff --git a/tools/regression/fstest/tests/unlink/09.t b/tools/regression/pjdfstest/tests/unlink/09.t similarity index 100% rename from tools/regression/fstest/tests/unlink/09.t rename to tools/regression/pjdfstest/tests/unlink/09.t diff --git a/tools/regression/fstest/tests/unlink/10.t b/tools/regression/pjdfstest/tests/unlink/10.t similarity index 100% rename from tools/regression/fstest/tests/unlink/10.t rename to tools/regression/pjdfstest/tests/unlink/10.t diff --git a/tools/regression/fstest/tests/unlink/11.t b/tools/regression/pjdfstest/tests/unlink/11.t similarity index 100% rename from tools/regression/fstest/tests/unlink/11.t rename to tools/regression/pjdfstest/tests/unlink/11.t diff --git a/tools/regression/fstest/tests/unlink/12.t b/tools/regression/pjdfstest/tests/unlink/12.t similarity index 100% rename from tools/regression/fstest/tests/unlink/12.t rename to tools/regression/pjdfstest/tests/unlink/12.t diff --git a/tools/regression/fstest/tests/unlink/13.t b/tools/regression/pjdfstest/tests/unlink/13.t similarity index 100% rename from tools/regression/fstest/tests/unlink/13.t rename to tools/regression/pjdfstest/tests/unlink/13.t From 6a8d8aa19323a7a0d8514a84ca418e44edd09e7a Mon Sep 17 00:00:00 2001 From: Christian Brueffer Date: Sun, 15 Aug 2010 21:25:52 +0000 Subject: [PATCH 0009/1624] Tie up some loose ends r88509 left behind: - chooseproc() is long gone, MLINK choosethread instead - Update NAME section for choosethread - Mark chooseproc.9 for removal PR: 149549 Submitted by: pluknet MFC after: 1 week --- ObsoleteFiles.inc | 2 ++ share/man/man9/Makefile | 2 +- share/man/man9/runqueue.9 | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/ObsoleteFiles.inc b/ObsoleteFiles.inc index cff830395dc..1e9c9d68adf 100644 --- a/ObsoleteFiles.inc +++ b/ObsoleteFiles.inc @@ -14,6 +14,8 @@ # The file is partitioned: OLD_FILES first, then OLD_LIBS and OLD_DIRS last. # +# 20100815: retired last traces of chooseproc(9) +OLD_FILES+=usr/share/man/man9/chooseproc.9.gz # 20100806: removal of unused libcompat routines OLD_FILES+=usr/share/man/man3/ascftime.3.gz OLD_FILES+=usr/share/man/man3/cfree.3.gz diff --git a/share/man/man9/Makefile b/share/man/man9/Makefile index 7b3dc5024a5..f8dec172838 100644 --- a/share/man/man9/Makefile +++ b/share/man/man9/Makefile @@ -994,7 +994,7 @@ MLINKS+=rtalloc.9 rtalloc1.9 \ rtalloc.9 rtalloc_ign.9 \ rtalloc.9 RTFREE.9 \ rtalloc.9 rtfree.9 -MLINKS+=runqueue.9 chooseproc.9 \ +MLINKS+=runqueue.9 choosethread.9 \ runqueue.9 procrunnable.9 \ runqueue.9 remrunqueue.9 \ runqueue.9 setrunqueue.9 diff --git a/share/man/man9/runqueue.9 b/share/man/man9/runqueue.9 index 09b46d4a10b..453ac9b9569 100644 --- a/share/man/man9/runqueue.9 +++ b/share/man/man9/runqueue.9 @@ -23,11 +23,11 @@ .\" .\" $FreeBSD$ .\" -.Dd November 3, 2000 +.Dd August 15, 2010 .Dt RUNQUEUE 9 .Os .Sh NAME -.Nm chooseproc , +.Nm choosethread , .Nm procrunnable , .Nm remrunqueue , .Nm setrunqueue From 3618f38566be6551a75c403448c0a4cad961f39e Mon Sep 17 00:00:00 2001 From: Pawel Jakub Dawidek Date: Sun, 15 Aug 2010 21:29:03 +0000 Subject: [PATCH 0010/1624] Finish renaming fstest to pjdfstest. --- tools/regression/pjdfstest/LICENSE | 2 +- tools/regression/pjdfstest/Makefile | 2 +- tools/regression/pjdfstest/README | 8 ++++---- tools/regression/pjdfstest/{fstest.c => pjdfstest.c} | 2 +- tools/regression/pjdfstest/tests/conf | 2 +- tools/regression/pjdfstest/tests/misc.sh | 6 +++--- 6 files changed, 11 insertions(+), 11 deletions(-) rename tools/regression/pjdfstest/{fstest.c => pjdfstest.c} (99%) diff --git a/tools/regression/pjdfstest/LICENSE b/tools/regression/pjdfstest/LICENSE index 972fc1de510..bde2232c223 100644 --- a/tools/regression/pjdfstest/LICENSE +++ b/tools/regression/pjdfstest/LICENSE @@ -1,6 +1,6 @@ $FreeBSD$ -License for all regression tests available with fstest: +License for all regression tests available with pjdfstest: Copyright (c) 2006-2010 Pawel Jakub Dawidek All rights reserved. diff --git a/tools/regression/pjdfstest/Makefile b/tools/regression/pjdfstest/Makefile index 7c363ccd155..3764aa9e1fd 100644 --- a/tools/regression/pjdfstest/Makefile +++ b/tools/regression/pjdfstest/Makefile @@ -1,6 +1,6 @@ # $FreeBSD$ -PROG= fstest +PROG= pjdfstest ${PROG}: ${PROG}.c @OSTYPE=`uname`; \ diff --git a/tools/regression/pjdfstest/README b/tools/regression/pjdfstest/README index 841ed402bd2..fb1cda52ab6 100644 --- a/tools/regression/pjdfstest/README +++ b/tools/regression/pjdfstest/README @@ -1,17 +1,17 @@ $FreeBSD$ -Few notes on how to use fstest in short steps: +Few notes on how to use pjdfstest in short steps: - # cd fstest + # cd pjdfstest # vi tests/conf Change 'fs' to file system type you want to test (UFS or ZFS). # vi Makefile You need to manually tweak few things by editing CFLAGS lines at the top of the file. # make - It will compile fstest utility which is used by regression tests. + It will compile pjdfstest utility which is used by regression tests. # cd /path/to/file/system/you/want/to/test/ - # prove -r /path/to/fstest/ + # prove -r /path/to/pjdfstest/tests That's all. Enjoy. diff --git a/tools/regression/pjdfstest/fstest.c b/tools/regression/pjdfstest/pjdfstest.c similarity index 99% rename from tools/regression/pjdfstest/fstest.c rename to tools/regression/pjdfstest/pjdfstest.c index 9d98c617ff2..b6a3c09dd2b 100644 --- a/tools/regression/pjdfstest/fstest.c +++ b/tools/regression/pjdfstest/pjdfstest.c @@ -264,7 +264,7 @@ static void usage(void) { - fprintf(stderr, "usage: fstest [-U umask] [-u uid] [-g gid1[,gid2[...]]] syscall args ...\n"); + fprintf(stderr, "usage: pjdfstest [-U umask] [-u uid] [-g gid1[,gid2[...]]] syscall args ...\n"); exit(1); } diff --git a/tools/regression/pjdfstest/tests/conf b/tools/regression/pjdfstest/tests/conf index 6ec8d4bdd3c..f914941482a 100644 --- a/tools/regression/pjdfstest/tests/conf +++ b/tools/regression/pjdfstest/tests/conf @@ -1,5 +1,5 @@ # $FreeBSD$ -# fstest configuration file +# pjdfstest configuration file # Supported operating systems: FreeBSD, Darwin, SunOS, Linux os=`uname` diff --git a/tools/regression/pjdfstest/tests/misc.sh b/tools/regression/pjdfstest/tests/misc.sh index 879c22a8cd9..0d3ce3582e9 100644 --- a/tools/regression/pjdfstest/tests/misc.sh +++ b/tools/regression/pjdfstest/tests/misc.sh @@ -10,7 +10,7 @@ case "${dir}" in maindir="`pwd`/${dir}/../.." ;; esac -fstest="${maindir}/fstest" +fstest="${maindir}/pjdfstest" . ${maindir}/tests/conf expect() @@ -42,7 +42,7 @@ jexpect() d="${2}" e="${3}" shift 3 - r=`jail -s ${s} / fstest 127.0.0.1 /bin/sh -c "cd ${d} && ${fstest} $* 2>/dev/null" | tail -1` + r=`jail -s ${s} / pjdfstest 127.0.0.1 /bin/sh -c "cd ${d} && ${fstest} $* 2>/dev/null" | tail -1` echo "${r}" | ${GREP} -Eq '^'${e}'$' if [ $? -eq 0 ]; then if [ -z "${todomsg}" ]; then @@ -89,7 +89,7 @@ todo() namegen() { - echo "fstest_`dd if=/dev/urandom bs=1k count=1 2>/dev/null | openssl md5`" + echo "pjdfstest_`dd if=/dev/urandom bs=1k count=1 2>/dev/null | openssl md5`" } namegen_len() From cd64d3f2f075a73500f4cac516a6111c2d60e3b4 Mon Sep 17 00:00:00 2001 From: Christian Brueffer Date: Sun, 15 Aug 2010 21:34:50 +0000 Subject: [PATCH 0011/1624] Fixed a typo and added a comma. PR: 148681 Submitted by: Glen Barber MFC after: 1 week --- share/man/man4/ng_atm.4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/share/man/man4/ng_atm.4 b/share/man/man4/ng_atm.4 index df4c2e341ef..aad0224f3eb 100644 --- a/share/man/man4/ng_atm.4 +++ b/share/man/man4/ng_atm.4 @@ -138,7 +138,7 @@ Hooks for dynamically initiated VCIs can have whatever name is allowed by .Xr netgraph 4 as long as the name does not collide with one of the three predefined names. .Pp -To initiate packet sending an receiving on a dynamic hook one has to issue +To initiate packet sending and receiving on a dynamic hook, one has to issue a .Dv NGM_ATM_CPCS_INIT control message. From 0f7e2491924be07f90f994db40d659cc49d2e413 Mon Sep 17 00:00:00 2001 From: Christian Brueffer Date: Sun, 15 Aug 2010 21:37:30 +0000 Subject: [PATCH 0012/1624] Fixed a typo. PR: 148701 Submitted by: Glen Barber MFC after: 1 week --- share/man/man9/crypto.9 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/share/man/man9/crypto.9 b/share/man/man9/crypto.9 index ed2a0cf9a90..ba13254f2f4 100644 --- a/share/man/man9/crypto.9 +++ b/share/man/man9/crypto.9 @@ -143,7 +143,7 @@ not The same holds for the framework. Thus, a callback mechanism is used to notify a consumer that a request has been completed (the -callback is specified by the consumer on an per-request basis). +callback is specified by the consumer on a per-request basis). The callback is invoked by the framework whether the request was successfully completed or not. An error indication is provided in the latter case. From 59218eb770e61b578f0ab296afbbfb381c211939 Mon Sep 17 00:00:00 2001 From: Gabor Kovesdan Date: Sun, 15 Aug 2010 22:15:04 +0000 Subject: [PATCH 0013/1624] - Revert strlcpy() changes to memcpy() because it's more efficient and former may be safer but in this case it doesn't add extra safety [1] - Fix -w option [2] - Fix handling of GREP_OPTIONS [3] - Fix --line-buffered - Make stdin input imply --line-buffered so that tail -f can be piped to grep [4] - Imply -h if single file is grepped, this is the GNU behaviour - Reduce locking overhead to gain some more performance [5] - Inline some functions to help the compiler better optimize the code - Use shortcut for empty files [6] PR: bin/149425 [6] Prodded by: jilles [1] Reported by: Alex Kozlov [2] [3], swell.k@gmail.com [2], poyopoyo@puripuri.plala.or.jp [4] Submitted by: scf [5], Shuichi KITAGUCHI [6] Approved by: delphij (mentor) --- usr.bin/grep/fastgrep.c | 8 +++---- usr.bin/grep/file.c | 25 ++++++++++++++++----- usr.bin/grep/grep.c | 49 ++++++++++++++++++++--------------------- usr.bin/grep/grep.h | 5 +---- usr.bin/grep/queue.c | 2 +- usr.bin/grep/util.c | 43 ++++++++++++++---------------------- 6 files changed, 66 insertions(+), 66 deletions(-) diff --git a/usr.bin/grep/fastgrep.c b/usr.bin/grep/fastgrep.c index 5239a0e1033..c66f0a7ae2f 100644 --- a/usr.bin/grep/fastgrep.c +++ b/usr.bin/grep/fastgrep.c @@ -46,8 +46,8 @@ __FBSDID("$FreeBSD$"); #include "grep.h" -static int grep_cmp(const unsigned char *, const unsigned char *, size_t); -static void grep_revstr(unsigned char *, int); +static inline int grep_cmp(const unsigned char *, const unsigned char *, size_t); +static inline void grep_revstr(unsigned char *, int); void fgrepcomp(fastgrep_t *fg, const char *pat) @@ -273,7 +273,7 @@ grep_search(fastgrep_t *fg, unsigned char *data, size_t len, regmatch_t *pmatch) * Returns: i >= 0 on failure (position that it failed) * -1 on success */ -static int +static inline int grep_cmp(const unsigned char *pat, const unsigned char *data, size_t len) { size_t size; @@ -318,7 +318,7 @@ grep_cmp(const unsigned char *pat, const unsigned char *data, size_t len) return (-1); } -static void +static inline void grep_revstr(unsigned char *str, int len) { int i; diff --git a/usr.bin/grep/file.c b/usr.bin/grep/file.c index c4de7db6acc..1872d0eff3d 100644 --- a/usr.bin/grep/file.c +++ b/usr.bin/grep/file.c @@ -67,14 +67,14 @@ static int bzerr; * Returns a single character according to the file type. * Returns -1 on failure. */ -int +static inline int grep_fgetc(struct file *f) { unsigned char c; switch (filebehave) { case FILE_STDIO: - return (fgetc(f->f)); + return (getc_unlocked(f->f)); case FILE_GZIP: return (gzgetc(f->gzf)); case FILE_BZIP: @@ -92,13 +92,13 @@ grep_fgetc(struct file *f) * Returns true if the file position is a EOF, returns false * otherwise. */ -int +static inline int grep_feof(struct file *f) { switch (filebehave) { case FILE_STDIO: - return (feof(f->f)); + return (feof_unlocked(f->f)); case FILE_GZIP: return (gzeof(f->gzf)); case FILE_BZIP: @@ -131,6 +131,9 @@ grep_fgetln(struct file *f, size_t *len) st.st_size = MAXBUFSIZ; else if (stat(fname, &st) != 0) err(2, NULL); + /* no need to allocate buffer. */ + if (st.st_size == 0) + return (NULL); bufsiz = (MAXBUFSIZ > (st.st_size * PREREAD_M)) ? (st.st_size / 2) : MAXBUFSIZ; @@ -142,6 +145,8 @@ grep_fgetln(struct file *f, size_t *len) if (ch == EOF) break; binbuf[i++] = ch; + if ((ch == '\n') && lbflag) + break; } f->binary = memchr(binbuf, (filebehave != FILE_GZIP) ? @@ -184,11 +189,16 @@ grep_stdin_open(void) { struct file *f; + /* Processing stdin implies --line-buffered for tail -f to work. */ + lbflag = true; + snprintf(fname, sizeof fname, "%s", getstr(1)); f = grep_malloc(sizeof *f); + binbuf = NULL; if ((f->f = fdopen(STDIN_FILENO, "r")) != NULL) { + flockfile(f->f); f->stdin = true; return (f); } @@ -209,11 +219,14 @@ grep_open(const char *path) f = grep_malloc(sizeof *f); + binbuf = NULL; f->stdin = false; switch (filebehave) { case FILE_STDIO: - if ((f->f = fopen(path, "r")) != NULL) + if ((f->f = fopen(path, "r")) != NULL) { + flockfile(f->f); return (f); + } break; case FILE_GZIP: if ((f->gzf = gzopen(fname, "r")) != NULL) @@ -238,6 +251,7 @@ grep_close(struct file *f) switch (filebehave) { case FILE_STDIO: + funlockfile(f->f); fclose(f->f); break; case FILE_GZIP: @@ -251,5 +265,4 @@ grep_close(struct file *f) /* Reset read buffer for the file we are closing */ binbufptr = NULL; free(binbuf); - } diff --git a/usr.bin/grep/grep.c b/usr.bin/grep/grep.c index 3dc1a1cc023..12217850865 100644 --- a/usr.bin/grep/grep.c +++ b/usr.bin/grep/grep.c @@ -121,8 +121,8 @@ int devbehave = DEV_READ; /* -D: handling of devices */ int dirbehave = DIR_READ; /* -dRr: handling of directories */ int linkbehave = LINK_READ; /* -OpS: handling of symlinks */ -bool dexclude, dinclude; /* --exclude amd --include */ -bool fexclude, finclude; /* --exclude-dir and --include-dir */ +bool dexclude, dinclude; /* --exclude-dir and --include-dir */ +bool fexclude, finclude; /* --exclude and --include */ enum { BIN_OPT = CHAR_MAX + 1, @@ -236,7 +236,8 @@ add_pattern(char *pat, size_t len) --len; /* pat may not be NUL-terminated */ pattern[patterns] = grep_malloc(len + 1); - strlcpy(pattern[patterns], pat, len + 1); + memcpy(pattern[patterns], pat, len); + pattern[patterns][len] = '\0'; ++patterns; } @@ -355,38 +356,33 @@ main(int argc, char *argv[]) eopts = getenv("GREP_OPTIONS"); - eargc = 1; + /* support for extra arguments in GREP_OPTIONS */ + eargc = 0; if (eopts != NULL) { char *str; - for(i = 0; i < strlen(eopts); i++) - if (eopts[i] == ' ') + /* make an estimation of how many extra arguments we have */ + for (unsigned int j = 0; j < strlen(eopts); j++) + if (eopts[j] == ' ') eargc++; eargv = (char **)grep_malloc(sizeof(char *) * (eargc + 1)); - str = strtok(eopts, " "); eargc = 0; - - while(str != NULL) { - eargv[++eargc] = (char *)grep_malloc(sizeof(char) * - (strlen(str) + 1)); - strlcpy(eargv[eargc], str, strlen(str) + 1); - str = strtok(NULL, " "); - } - eargv[++eargc] = NULL; + /* parse extra arguments */ + while ((str = strsep(&eopts, " ")) != NULL) + eargv[eargc++] = grep_strdup(str); aargv = (char **)grep_calloc(eargc + argc + 1, sizeof(char *)); + aargv[0] = argv[0]; + for (i = 0; i < eargc; i++) + aargv[i + 1] = eargv[i]; + for (int j = 1; j < argc; j++, i++) + aargv[i + 1] = argv[j]; - for(i = 1; i < eargc; i++) - aargv[i] = eargv[i]; - for(int j = 1; j < argc; j++) - aargv[i++] = argv[j]; - - aargc = eargc + argc - 1; - + aargc = eargc + argc; } else { aargv = argv; aargc = argc; @@ -609,11 +605,11 @@ main(int argc, char *argv[]) add_fpattern(optarg, EXCL_PAT); break; case R_DINCLUDE_OPT: - dexclude = true; + dinclude = true; add_dpattern(optarg, INCL_PAT); break; case R_DEXCLUDE_OPT: - dinclude = true; + dexclude = true; add_dpattern(optarg, EXCL_PAT); break; case HELP_OPT: @@ -685,12 +681,15 @@ main(int argc, char *argv[]) if (dirbehave == DIR_RECURSE) c = grep_tree(aargv); - else + else { + if (aargc == 1) + hflag = true; for (c = 0; aargc--; ++aargv) { if ((finclude || fexclude) && !file_matching(*aargv)) continue; c+= procfile(*aargv); } + } #ifndef WITHOUT_NLS catclose(catalog); diff --git a/usr.bin/grep/grep.h b/usr.bin/grep/grep.h index bb5e5f96592..2f743e48142 100644 --- a/usr.bin/grep/grep.h +++ b/usr.bin/grep/grep.h @@ -115,7 +115,7 @@ extern int cflags, eflags; extern bool Eflag, Fflag, Gflag, Hflag, Lflag, bflag, cflag, hflag, iflag, lflag, mflag, nflag, oflag, qflag, sflag, vflag, wflag, xflag; -extern bool dexclude, dinclude, fexclude, finclude, nullflag; +extern bool dexclude, dinclude, fexclude, finclude, lbflag, nullflag; extern unsigned long long Aflag, Bflag, mcount; extern char *label; extern const char *color; @@ -134,7 +134,6 @@ extern fastgrep_t *fg_pattern; extern char re_error[RE_ERROR_BUF + 1]; /* Seems big enough */ /* util.c */ -bool dir_matching(const char *dname); bool file_matching(const char *fname); int procfile(const char *fn); int grep_tree(char **argv); @@ -153,8 +152,6 @@ void clearqueue(void); void grep_close(struct file *f); struct file *grep_stdin_open(void); struct file *grep_open(const char *path); -int grep_feof(struct file *f); -int grep_fgetc(struct file *f); char *grep_fgetln(struct file *f, size_t *len); /* fastgrep.c */ diff --git a/usr.bin/grep/queue.c b/usr.bin/grep/queue.c index 29a6c2f6b43..dcef7f8fd43 100644 --- a/usr.bin/grep/queue.c +++ b/usr.bin/grep/queue.c @@ -60,7 +60,7 @@ enqueue(struct str *x) item->data.len = x->len; item->data.line_no = x->line_no; item->data.off = x->off; - strcpy(item->data.dat, x->dat); + memcpy(item->data.dat, x->dat, x->len); item->data.file = x->file; STAILQ_INSERT_TAIL(&queue, item, list); diff --git a/usr.bin/grep/util.c b/usr.bin/grep/util.c index 9618dea61b9..f084c3da09e 100644 --- a/usr.bin/grep/util.c +++ b/usr.bin/grep/util.c @@ -72,7 +72,7 @@ file_matching(const char *fname) return (ret); } -bool +static inline bool dir_matching(const char *dname) { bool ret; @@ -144,9 +144,10 @@ grep_tree(char **argv) if (dexclude || dinclude) { if ((d = strrchr(p->fts_path, '/')) != NULL) { dir = grep_malloc(sizeof(char) * - (d - p->fts_path + 2)); - strlcpy(dir, p->fts_path, (d - p->fts_path + 1)); + memcpy(dir, p->fts_path, + d - p->fts_path); + dir[d - p->fts_path] = '\0'; } ok = dir_matching(dir); free(dir); @@ -276,7 +277,7 @@ procfile(const char *fn) * matches. The matching lines are passed to printline() to display the * appropriate output. */ -static int +static inline int procline(struct str *l, int nottext) { regmatch_t matches[MAX_LINE_MATCHES]; @@ -317,30 +318,20 @@ procline(struct str *l, int nottext) (size_t)pmatch.rm_eo != l->len) r = REG_NOMATCH; /* Check for whole word match */ - if (r == 0 && wflag && pmatch.rm_so != 0 && - (size_t)pmatch.rm_eo != l->len) { - wchar_t *wbegin; - wint_t wend; - size_t size; + if (r == 0 && wflag && pmatch.rm_so != 0) { + wint_t wbegin, wend; - size = mbstowcs(NULL, l->dat, - pmatch.rm_so); - - if (size == ((size_t) - 1)) + wbegin = wend = L' '; + if (pmatch.rm_so != 0 && + sscanf(&l->dat[pmatch.rm_so - 1], + "%lc", &wbegin) != 1) + r = REG_NOMATCH; + else if ((size_t)pmatch.rm_eo != l->len && + sscanf(&l->dat[pmatch.rm_eo], + "%lc", &wend) != 1) + r = REG_NOMATCH; + else if (iswword(wbegin) || iswword(wend)) r = REG_NOMATCH; - else { - wbegin = grep_malloc(size); - if (mbstowcs(wbegin, l->dat, - pmatch.rm_so) == ((size_t) - 1)) - r = REG_NOMATCH; - else if (sscanf(&l->dat[pmatch.rm_eo], - "%lc", &wend) != 1) - r = REG_NOMATCH; - else if (iswword(wbegin[wcslen(wbegin)]) || - iswword(wend)) - r = REG_NOMATCH; - free(wbegin); - } } if (r == 0) { if (m == 0) From f4fda7679a0aafd5872bf6be0f80784f66fb510f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= Date: Mon, 16 Aug 2010 11:22:12 +0000 Subject: [PATCH 0014/1624] Old patch I had lying around: clean up and use stpcpy(3) instead of sprintf(3). --- lib/libutil/pw_util.c | 61 ++++++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 27 deletions(-) diff --git a/lib/libutil/pw_util.c b/lib/libutil/pw_util.c index 75459e338b1..5eae280e583 100644 --- a/lib/libutil/pw_util.c +++ b/lib/libutil/pw_util.c @@ -67,7 +67,7 @@ static const char rcsid[] = #include #include -#include +#include "libutil.h" static pid_t editpid = -1; static int lockfd = -1; @@ -557,43 +557,50 @@ pw_tempname(void) struct passwd * pw_dup(const struct passwd *pw) { + char *dst; struct passwd *npw; ssize_t len; - len = sizeof(*npw) + - (pw->pw_name ? strlen(pw->pw_name) + 1 : 0) + - (pw->pw_passwd ? strlen(pw->pw_passwd) + 1 : 0) + - (pw->pw_class ? strlen(pw->pw_class) + 1 : 0) + - (pw->pw_gecos ? strlen(pw->pw_gecos) + 1 : 0) + - (pw->pw_dir ? strlen(pw->pw_dir) + 1 : 0) + - (pw->pw_shell ? strlen(pw->pw_shell) + 1 : 0); + len = sizeof(*npw); + if (pw->pw_name != NULL) + len += strlen(pw->pw_name) + 1; + if (pw->pw_passwd != NULL) + len += strlen(pw->pw_passwd) + 1; + if (pw->pw_class != NULL) + len += strlen(pw->pw_class) + 1; + if (pw->pw_gecos != NULL) + len += strlen(pw->pw_gecos) + 1; + if (pw->pw_dir != NULL) + len += strlen(pw->pw_dir) + 1; + if (pw->pw_shell != NULL) + len += strlen(pw->pw_shell) + 1; if ((npw = malloc((size_t)len)) == NULL) return (NULL); memcpy(npw, pw, sizeof(*npw)); - len = sizeof(*npw); - if (pw->pw_name) { - npw->pw_name = ((char *)npw) + len; - len += sprintf(npw->pw_name, "%s", pw->pw_name) + 1; + dst = (char *)npw + sizeof(*npw); + if (pw->pw_name != NULL) { + npw->pw_name = dst; + dst = stpcpy(npw->pw_name, pw->pw_name) + 1; } - if (pw->pw_passwd) { - npw->pw_passwd = ((char *)npw) + len; - len += sprintf(npw->pw_passwd, "%s", pw->pw_passwd) + 1; + if (pw->pw_passwd != NULL) { + npw->pw_passwd = dst; + dst = stpcpy(npw->pw_passwd, pw->pw_passwd) + 1; } - if (pw->pw_class) { - npw->pw_class = ((char *)npw) + len; - len += sprintf(npw->pw_class, "%s", pw->pw_class) + 1; + if (pw->pw_class != NULL) { + npw->pw_class = dst; + dst = stpcpy(npw->pw_class, pw->pw_class) + 1; } - if (pw->pw_gecos) { - npw->pw_gecos = ((char *)npw) + len; - len += sprintf(npw->pw_gecos, "%s", pw->pw_gecos) + 1; + if (pw->pw_gecos != NULL) { + npw->pw_gecos = dst; + dst = stpcpy(npw->pw_gecos, pw->pw_gecos) + 1; } - if (pw->pw_dir) { - npw->pw_dir = ((char *)npw) + len; - len += sprintf(npw->pw_dir, "%s", pw->pw_dir) + 1; + if (pw->pw_dir != NULL) { + npw->pw_dir = dst; + dst = stpcpy(npw->pw_dir, pw->pw_dir) + 1; } - if (pw->pw_shell) { - npw->pw_shell = ((char *)npw) + len; - len += sprintf(npw->pw_shell, "%s", pw->pw_shell) + 1; + if (pw->pw_shell != NULL) { + npw->pw_shell = dst; + dst = stpcpy(npw->pw_shell, pw->pw_shell) + 1; } return (npw); } From 35305a8dc114c2be95dfa0d14557034c3341462a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= Date: Mon, 16 Aug 2010 11:32:20 +0000 Subject: [PATCH 0015/1624] In setusercontext(), do not apply user settings unless running as the user in question (usually but not necessarily because we were called with LOGIN_SETUSER). This plugs a hole where users could raise their resource limits and expand their CPU mask. MFC after: 3 weeks --- lib/libutil/login_class.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/libutil/login_class.c b/lib/libutil/login_class.c index d54b30140e0..d952940f600 100644 --- a/lib/libutil/login_class.c +++ b/lib/libutil/login_class.c @@ -525,7 +525,7 @@ setusercontext(login_cap_t *lc, const struct passwd *pwd, uid_t uid, unsigned in /* * Now, we repeat some of the above for the user's private entries */ - if ((lc = login_getuserclass(pwd)) != NULL) { + if (getuid() == uid && (lc = login_getuserclass(pwd)) != NULL) { mymask = setlogincontext(lc, pwd, mymask, flags); login_close(lc); } From e8efeec6c53cb3c97db41a1cc04296e18ddb41fe Mon Sep 17 00:00:00 2001 From: Ed Schouten Date: Mon, 16 Aug 2010 12:19:36 +0000 Subject: [PATCH 0016/1624] Mark functions and variables as static. All these functions and variables are local to this compilation unit, so there is no reason why we shouldn't mark them static. This slightly reduces the binary size. --- usr.bin/script/script.c | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/usr.bin/script/script.c b/usr.bin/script/script.c index a21785abbc4..64ca486d063 100644 --- a/usr.bin/script/script.c +++ b/usr.bin/script/script.c @@ -63,19 +63,18 @@ static const char sccsid[] = "@(#)script.c 8.1 (Berkeley) 6/6/93"; #include #include -FILE *fscript; -int master, slave; -int child; -const char *fname; -int qflg, ttyflg; +static FILE *fscript; +static int master, slave; +static int child; +static const char *fname; +static int qflg, ttyflg; -struct termios tt; +static struct termios tt; -void done(int) __dead2; -void dooutput(void); -void doshell(char **); -void fail(void); -void finish(void); +static void done(int) __dead2; +static void doshell(char **); +static void fail(void); +static void finish(void); static void usage(void); int @@ -216,7 +215,7 @@ usage(void) exit(1); } -void +static void finish(void) { int e, status; @@ -232,7 +231,7 @@ finish(void) } } -void +static void doshell(char **av) { const char *shell; @@ -254,14 +253,14 @@ doshell(char **av) fail(); } -void +static void fail(void) { (void)kill(0, SIGTERM); done(1); } -void +static void done(int eno) { time_t tvec; From 13852a6e15a94646e958471b91ea96a78b8b658c Mon Sep 17 00:00:00 2001 From: Joel Dahl Date: Mon, 16 Aug 2010 12:37:17 +0000 Subject: [PATCH 0017/1624] Fix .Dd from last commit. Submitted by Nobuyuki Koganemaru --- share/man/man4/bwi.4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/share/man/man4/bwi.4 b/share/man/man4/bwi.4 index 07b6ffb4666..2f286568100 100644 --- a/share/man/man4/bwi.4 +++ b/share/man/man4/bwi.4 @@ -24,7 +24,7 @@ .\" .\" $FreeBSD$ .\" -.Dd June 30, 2009 +.Dd June 30, 2010 .Dt BWI 4 .Os .Sh NAME From e49471b04b4bf0bfc58e2feeb0dd4208ea8f7c0d Mon Sep 17 00:00:00 2001 From: Andre Oppermann Date: Mon, 16 Aug 2010 14:24:00 +0000 Subject: [PATCH 0018/1624] Add uma_zone_get_max() to obtain the effective limit after a call to uma_zone_set_max(). The UMA zone limit is not exactly set to the value supplied but rounded up to completely fill the backing store increment (a page normally). This can lead to surprising situations where the number of elements allocated from UMA is higher than the supplied limit value. The new get function reads back the effective value so that the supplied limit value can be adjusted to the real limit. Reviewed by: jeffr MFC after: 1 week --- sys/vm/uma.h | 12 ++++++++++++ sys/vm/uma_core.c | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/sys/vm/uma.h b/sys/vm/uma.h index 2076d3bd0b6..f0522b01631 100644 --- a/sys/vm/uma.h +++ b/sys/vm/uma.h @@ -458,6 +458,18 @@ int uma_zone_set_obj(uma_zone_t zone, struct vm_object *obj, int size); */ void uma_zone_set_max(uma_zone_t zone, int nitems); +/* + * Obtains the effective limit on the number of items in a zone + * + * Arguments: + * zone The zone to obtain the effective limit from + * + * Return: + * 0 No limit + * int The effective limit of the zone + */ +int uma_zone_get_max(uma_zone_t zone); + /* * The following two routines (uma_zone_set_init/fini) * are used to set the backend init/fini pair which acts on an diff --git a/sys/vm/uma_core.c b/sys/vm/uma_core.c index 2dcd14fdd1a..558b4c727e7 100644 --- a/sys/vm/uma_core.c +++ b/sys/vm/uma_core.c @@ -2796,6 +2796,24 @@ uma_zone_set_max(uma_zone_t zone, int nitems) ZONE_UNLOCK(zone); } +/* See uma.h */ +int +uma_zone_get_max(uma_zone_t zone) +{ + int nitems; + uma_keg_t keg; + + ZONE_LOCK(zone); + keg = zone_first_keg(zone); + if (keg->uk_maxpages) + nitems = keg->uk_maxpages * keg->uk_ipers; + else + nitems = 0; + ZONE_UNLOCK(zone); + + return (nitems); +} + /* See uma.h */ void uma_zone_set_init(uma_zone_t zone, uma_init uminit) From c2025a76606b44c4d5367b7509fbc0285ae1e7f8 Mon Sep 17 00:00:00 2001 From: Joel Dahl Date: Mon, 16 Aug 2010 15:18:30 +0000 Subject: [PATCH 0019/1624] Fix typos, spelling, formatting and mdoc mistakes found by Nobuyuki while translating these manual pages. Minor corrections by me. Submitted by: Nobuyuki Koganemaru --- lib/libbluetooth/bluetooth.3 | 2 +- lib/libc/gen/dlopen.3 | 2 +- lib/libc/net/inet6_rth_space.3 | 3 ++- lib/libc/net/sctp_send.3 | 2 +- lib/libc/net/sctp_sendmsg.3 | 4 ++-- lib/libc/stdlib/getopt_long.3 | 4 ++-- lib/libc/sys/getfh.2 | 2 +- lib/libc/sys/kldstat.2 | 2 +- lib/libc/sys/ntp_adjtime.2 | 2 +- lib/libc/sys/open.2 | 4 ++-- lib/libc/sys/shm_open.2 | 2 +- lib/libedit/editline.3 | 2 +- lib/libelf/elf.3 | 4 ++-- lib/libgeom/libgeom.3 | 2 +- lib/libgpib/gpib.3 | 2 +- lib/libgssapi/gss_accept_sec_context.3 | 2 +- lib/libgssapi/gss_acquire_cred.3 | 2 +- lib/libgssapi/gssapi.3 | 2 +- lib/libpmc/pmc.3 | 2 +- lib/libpmc/pmc.corei7.3 | 2 +- lib/libpmc/pmc.corei7uc.3 | 2 +- lib/libpmc/pmc.westmere.3 | 2 +- lib/libpmc/pmc.westmereuc.3 | 2 +- lib/libpmc/pmc_event_names_of_class.3 | 2 +- lib/libpmc/pmc_read.3 | 2 +- lib/libradius/libradius.3 | 2 +- lib/librpcsec_gss/rpcsec_gss.3 | 2 +- lib/libsdp/sdp.3 | 2 +- lib/libusb/libusb20.3 | 2 +- lib/libutil/quotafile.3 | 4 ++-- lib/msun/man/fdim.3 | 2 +- sbin/devd/devd.conf.5 | 2 +- sbin/fsck_ffs/fsck_ffs.8 | 2 +- sbin/geom/core/geom.8 | 2 +- sbin/hastctl/hastctl.8 | 2 +- sbin/hastd/hast.conf.5 | 2 +- sbin/ifconfig/ifconfig.8 | 10 +++++----- sbin/ipfw/ipfw.8 | 4 ++-- share/man/man4/bktr.4 | 2 +- share/man/man4/bt.4 | 2 +- share/man/man4/gbde.4 | 2 +- share/man/man4/hwpmc.4 | 2 +- share/man/man4/ip.4 | 2 +- share/man/man4/lmc.4 | 2 +- share/man/man4/mac_lomac.4 | 2 +- share/man/man4/man4.i386/glxsb.4 | 2 +- share/man/man4/meteor.4 | 2 +- share/man/man4/mk48txx.4 | 2 +- share/man/man4/net80211.4 | 10 +++++----- share/man/man4/netgraph.4 | 2 +- share/man/man4/ng_btsocket.4 | 2 +- share/man/man4/ngatmbase.4 | 2 +- share/man/man4/pcm.4 | 2 +- share/man/man4/sctp.4 | 8 ++++---- share/man/man4/termios.4 | 2 +- share/man/man4/u3g.4 | 2 +- share/man/man5/mqueuefs.5 | 2 +- share/man/man5/periodic.conf.5 | 2 +- share/man/man7/bsd.snmpmod.mk.7 | 2 +- share/man/man9/DEVICE_PROBE.9 | 2 +- share/man/man9/VOP_LISTEXTATTR.9 | 2 +- share/man/man9/VOP_VPTOCNP.9 | 2 +- share/man/man9/g_geom.9 | 4 ++-- share/man/man9/g_wither_geom.9 | 2 +- share/man/man9/ieee80211.9 | 12 ++++++------ share/man/man9/kproc.9 | 4 ++-- share/man/man9/netisr.9 | 4 ++-- share/man/man9/vm_page_bits.9 | 2 +- usr.bin/cpio/bsdcpio.1 | 2 +- usr.bin/systat/systat.1 | 2 +- usr.sbin/bsnmpd/modules/snmp_bridge/snmp_bridge.3 | 4 ++-- usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 | 2 +- usr.sbin/freebsd-update/freebsd-update.8 | 2 +- usr.sbin/i2c/i2c.8 | 2 +- usr.sbin/lmcconfig/lmcconfig.8 | 6 +++--- usr.sbin/nfscbd/nfscbd.8 | 2 +- usr.sbin/nfsd/nfsv4.4 | 2 +- usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.8 | 4 ++-- usr.sbin/pciconf/pciconf.8 | 2 +- usr.sbin/portsnap/portsnap/portsnap.8 | 2 +- 80 files changed, 110 insertions(+), 109 deletions(-) diff --git a/lib/libbluetooth/bluetooth.3 b/lib/libbluetooth/bluetooth.3 index d3faaf12389..cf7e3edbfb4 100644 --- a/lib/libbluetooth/bluetooth.3 +++ b/lib/libbluetooth/bluetooth.3 @@ -545,7 +545,7 @@ function performs Bluetooth inquiry. The .Fa devname parameter specifies which local Bluetooth device should perform an inquiry. -If not secified, i.e. +If not specified, i.e. .Dv NULL , then first available device will be used. The diff --git a/lib/libc/gen/dlopen.3 b/lib/libc/gen/dlopen.3 index 45b01397468..3da9b6e923d 100644 --- a/lib/libc/gen/dlopen.3 +++ b/lib/libc/gen/dlopen.3 @@ -149,7 +149,7 @@ The same behaviour may be requested by option of the static linker .Xr ld 1 . .It Dv RTLD_NOLOAD -Ony return valid handle for the object if it is already loaded in +Only return valid handle for the object if it is already loaded in the process address space, otherwise .Dv NULL is returned. diff --git a/lib/libc/net/inet6_rth_space.3 b/lib/libc/net/inet6_rth_space.3 index 2750170d33c..a3db7942c6c 100644 --- a/lib/libc/net/inet6_rth_space.3 +++ b/lib/libc/net/inet6_rth_space.3 @@ -101,7 +101,8 @@ The .Fn inet6_rth_init function initializes the pre-allocated buffer pointed to by .Fa bp -to contain a routing header of the specified type The +to contain a routing header of the specified type. +The .Fa bp_len argument is used to verify that the buffer is large enough. The caller must allocate the buffer pointed to by bp. diff --git a/lib/libc/net/sctp_send.3 b/lib/libc/net/sctp_send.3 index 20344afbbe9..9acb616be5b 100644 --- a/lib/libc/net/sctp_send.3 +++ b/lib/libc/net/sctp_send.3 @@ -187,7 +187,7 @@ The .Fa sinfo->sinfo_timetolive argument is then a number of milliseconds for which the data is attempted to be transmitted. -If that many milliseconds ellapse +If that many milliseconds elapse and the peer has not acknowledged the data, the data will be skipped and no longer transmitted. Note that this policy does diff --git a/lib/libc/net/sctp_sendmsg.3 b/lib/libc/net/sctp_sendmsg.3 index 42193e24781..ddd88b43c9f 100644 --- a/lib/libc/net/sctp_sendmsg.3 +++ b/lib/libc/net/sctp_sendmsg.3 @@ -180,7 +180,7 @@ to find the association but also as the actual address to send to. .Pp For a one-to-many type (SOCK_SEQPACKET) socket the flag .Dv SCTP_SENDALL -can be used as a convient way to make one send call and have +can be used as a convenient way to make one send call and have all associations that are under the socket get a copy of the message. Note that this mechanism is quite efficient and makes only one actual copy of the data which is shared by all the associations for sending. @@ -199,7 +199,7 @@ The .Fa timetolive argument is then a number of milliseconds for which the data is attempted to be transmitted. -If that many milliseconds ellapse +If that many milliseconds elapse and the peer has not acknowledged the data, the data will be skipped and no longer transmitted. Note that this policy does diff --git a/lib/libc/stdlib/getopt_long.3 b/lib/libc/stdlib/getopt_long.3 index 352af083f92..72f653450b2 100644 --- a/lib/libc/stdlib/getopt_long.3 +++ b/lib/libc/stdlib/getopt_long.3 @@ -469,9 +469,9 @@ The .Fn getopt_long and .Fn getopt_long_only -functions first appeared in +functions first appeared in the .Tn GNU -libiberty. +libiberty library. The first .Bx implementation of diff --git a/lib/libc/sys/getfh.2 b/lib/libc/sys/getfh.2 index 14881966a70..c8f6d9d01ce 100644 --- a/lib/libc/sys/getfh.2 +++ b/lib/libc/sys/getfh.2 @@ -69,7 +69,7 @@ These system calls are restricted to the superuser. The .Fn getfh and -.Fn lgetfgh +.Fn lgetfh system calls fail if one or more of the following are true: .Bl -tag -width Er diff --git a/lib/libc/sys/kldstat.2 b/lib/libc/sys/kldstat.2 index eb09a23dd7d..88f3781f482 100644 --- a/lib/libc/sys/kldstat.2 +++ b/lib/libc/sys/kldstat.2 @@ -129,6 +129,6 @@ The interface first appeared in .Fx 3.0 . .Sh BUGS -The pathname many not be accurate if the file system mounts have +The pathname may not be accurate if the file system mounts have changed since the module was loaded, or if this function is called within a chrooted environment. diff --git a/lib/libc/sys/ntp_adjtime.2 b/lib/libc/sys/ntp_adjtime.2 index 65ff8a3f0df..8ce78e7fb86 100644 --- a/lib/libc/sys/ntp_adjtime.2 +++ b/lib/libc/sys/ntp_adjtime.2 @@ -284,7 +284,7 @@ At the end of the day, second 23:59:59 will be skipped. .It TIME_OOP Leap second in progress. .It TIME_WAIT -Leap second has occurred within the last few seconds.. +Leap second has occurred within the last few seconds. .It TIME_ERROR Clock not synchronized. .El diff --git a/lib/libc/sys/open.2 b/lib/libc/sys/open.2 index 04fa0fe7ace..deca8bcda17 100644 --- a/lib/libc/sys/open.2 +++ b/lib/libc/sys/open.2 @@ -296,9 +296,9 @@ created has its immutable flag set, see the .Xr chflags 2 manual page for more information. .It Bq Er EPERM -.Dv The named file has its immutable flag set and the file is to be modified. +The named file has its immutable flag set and the file is to be modified. .It Bq Er EPERM -.Dv The named file has its append-only flag set, the file is to be modified, and +The named file has its append-only flag set, the file is to be modified, and .Dv O_TRUNC is specified or .Dv O_APPEND diff --git a/lib/libc/sys/shm_open.2 b/lib/libc/sys/shm_open.2 index a586fe33199..a2fa502ce9a 100644 --- a/lib/libc/sys/shm_open.2 +++ b/lib/libc/sys/shm_open.2 @@ -231,7 +231,7 @@ is specified and the named shared memory object does not exist. .Dv O_CREAT and .Dv O_EXCL -are specified and the named shared memory object dies exist. +are specified and the named shared memory object does exist. .It Bq Er EACCES The required permissions (for reading or reading and writing) are denied. .El diff --git a/lib/libedit/editline.3 b/lib/libedit/editline.3 index 9794649a56e..9661d66d2db 100644 --- a/lib/libedit/editline.3 +++ b/lib/libedit/editline.3 @@ -738,7 +738,7 @@ and before a new line is to be tokenized. .It Fn tok_line Tokenize .Fa li , -If successful, modify: +if successful, modify .Fa argv to contain the words, .Fa argc diff --git a/lib/libelf/elf.3 b/lib/libelf/elf.3 index d852de16a45..e3e01bc7ac2 100644 --- a/lib/libelf/elf.3 +++ b/lib/libelf/elf.3 @@ -463,7 +463,7 @@ Close an ELF descriptor and release all its resources. .It Fn elf_memory Opens an .Xr ar 1 -archive or ELF object present in a memory arena. +archive or ELF object present in a memory area. .It Fn elf_version Sets the operating version. .El @@ -563,7 +563,7 @@ descriptor and can set the member of the descriptor to point to a region of memory allocated using .Xr malloc 3 . -It is the applications responsibility to free this arena, though the +It is the applications responsibility to free this area, though the library will reclaim the space used by the .Vt Elf_Data descriptor itself. diff --git a/lib/libgeom/libgeom.3 b/lib/libgeom/libgeom.3 index d5682ab1d5a..04cf2fc1979 100644 --- a/lib/libgeom/libgeom.3 +++ b/lib/libgeom/libgeom.3 @@ -392,4 +392,4 @@ library appeared in .Sh AUTHORS .An Poul-Henning Kamp Aq phk@FreeBSD.org .An Lukas Ertl Aq le@FreeBSD.org -.An Pawel Jakub Dawidek pjd@FreeBSD.org +.An Pawel Jakub Dawidek Aq pjd@FreeBSD.org diff --git a/lib/libgpib/gpib.3 b/lib/libgpib/gpib.3 index 2b9072e73ff..b587da6682b 100644 --- a/lib/libgpib/gpib.3 +++ b/lib/libgpib/gpib.3 @@ -524,7 +524,7 @@ is used to configure the parallel poll response to .Fa v . .Em This function is currently not implemented. .Pp -The fucntion +The function .Fn ibrd is used to receive .Fa cnt diff --git a/lib/libgssapi/gss_accept_sec_context.3 b/lib/libgssapi/gss_accept_sec_context.3 index a4c219c164e..cd80db69d01 100644 --- a/lib/libgssapi/gss_accept_sec_context.3 +++ b/lib/libgssapi/gss_accept_sec_context.3 @@ -121,7 +121,7 @@ following restrictions apply to the output parameters: .Pp The value returned via the .Fa time_rec -parameter is undefined Unless the +parameter is undefined unless the accompanying .Fa ret_flags parameter contains the bit diff --git a/lib/libgssapi/gss_acquire_cred.3 b/lib/libgssapi/gss_acquire_cred.3 index 5de9ea0362a..4b683e7c579 100644 --- a/lib/libgssapi/gss_acquire_cred.3 +++ b/lib/libgssapi/gss_acquire_cred.3 @@ -184,7 +184,7 @@ Type contained within desired_name parameter is not supported. .It GSS_S_BAD_NAME Value supplied for desired_name parameter is ill formed. .It GSS_S_CREDENTIALS_EXPIRED -The credentials could not be acquired Because they have expired. +The credentials could not be acquired because they have expired. .It GSS_S_NO_CRED No credentials were found for the specified name. .El diff --git a/lib/libgssapi/gssapi.3 b/lib/libgssapi/gssapi.3 index 2ed54a9b3c8..f92da590dfd 100644 --- a/lib/libgssapi/gssapi.3 +++ b/lib/libgssapi/gssapi.3 @@ -139,7 +139,7 @@ GSS-API Context-Level Routines: .It gss_init_sec_context Initiate a security context with a peer application .It gss_accept_sec_context - Accept a security context initiated by a peer application +Accept a security context initiated by a peer application .It gss_delete_sec_context Discard a security context .It gss_process_context_token diff --git a/lib/libpmc/pmc.3 b/lib/libpmc/pmc.3 index 5e3236baf9b..2403e64686b 100644 --- a/lib/libpmc/pmc.3 +++ b/lib/libpmc/pmc.3 @@ -48,7 +48,7 @@ Performance monitoring counters (PMCs) are represented by the library using a software abstraction. These .Dq abstract -PMCs can have one two scopes: +PMCs can have two scopes: .Bl -bullet .It System scope. diff --git a/lib/libpmc/pmc.corei7.3 b/lib/libpmc/pmc.corei7.3 index ba973b7821a..679313f218c 100644 --- a/lib/libpmc/pmc.corei7.3 +++ b/lib/libpmc/pmc.corei7.3 @@ -993,7 +993,7 @@ Counting: Faulting executions of GETSEC/VM entry/VM Exit/MWait will not count as retired instructions. .It Li INST_RETIRED.X87 .Pq Event C0H , Umask 02H -Counts the number of MMX instructions retired:. +Counts the number of MMX instructions retired. .It Li INST_RETIRED.MMX .Pq Event C0H , Umask 04H Counts the number of floating point computational operations retired: diff --git a/lib/libpmc/pmc.corei7uc.3 b/lib/libpmc/pmc.corei7uc.3 index 2777c8e92cf..a69eab77588 100644 --- a/lib/libpmc/pmc.corei7uc.3 +++ b/lib/libpmc/pmc.corei7uc.3 @@ -434,7 +434,7 @@ Counts cycles all the entries in the DRAM channel 0 high priority queue are occupied with isochronous read requests. .It Li QMC_ISOC_FULL.READ.CH1 .Pq Event 28H , Umask 02H -Counts cycles all the entries in the DRAM channel 1high priority queue are +Counts cycles all the entries in the DRAM channel 1 high priority queue are occupied with isochronous read requests. .It Li QMC_ISOC_FULL.READ.CH2 .Pq Event 28H , Umask 04H diff --git a/lib/libpmc/pmc.westmere.3 b/lib/libpmc/pmc.westmere.3 index af7838fbd68..bd0244ead24 100644 --- a/lib/libpmc/pmc.westmere.3 +++ b/lib/libpmc/pmc.westmere.3 @@ -975,7 +975,7 @@ Counting: Faulting executions of GETSEC/VM entry/VM Exit/MWait will not count as retired instructions. .It Li INST_RETIRED.X87 .Pq Event C0H , Umask 02H -Counts the number of floating point computational operations retired: +Counts the number of floating point computational operations retired floating point computational operations executed by the assist handler and sub-operations of complex floating point instructions like transcendental instructions. diff --git a/lib/libpmc/pmc.westmereuc.3 b/lib/libpmc/pmc.westmereuc.3 index d8a4cefabd1..c768daa039e 100644 --- a/lib/libpmc/pmc.westmereuc.3 +++ b/lib/libpmc/pmc.westmereuc.3 @@ -464,7 +464,7 @@ Counts cycles all the entries in the DRAM channel 0 high priority queue are occupied with isochronous read requests. .It Li QMC_ISOC_FULL.READ.CH1 .Pq Event 28H , Umask 02H -Counts cycles all the entries in the DRAM channel 1high priority queue are +Counts cycles all the entries in the DRAM channel 1 high priority queue are occupied with isochronous read requests. .It Li QMC_ISOC_FULL.READ.CH2 .Pq Event 28H , Umask 04H diff --git a/lib/libpmc/pmc_event_names_of_class.3 b/lib/libpmc/pmc_event_names_of_class.3 index 5b2c89d1b80..183f03f8967 100644 --- a/lib/libpmc/pmc_event_names_of_class.3 +++ b/lib/libpmc/pmc_event_names_of_class.3 @@ -68,7 +68,7 @@ Argument .Fa cl was invalid. .It Bq Er ENOMEM -Allocation of a memory arena to hold the result failed. +Allocation of a memory area to hold the result failed. .El .Sh SEE ALSO .Xr pmc 3 , diff --git a/lib/libpmc/pmc_read.3 b/lib/libpmc/pmc_read.3 index 8d718ca3fd1..d091716936a 100644 --- a/lib/libpmc/pmc_read.3 +++ b/lib/libpmc/pmc_read.3 @@ -46,7 +46,7 @@ These functions read and write the current value of a PMC. .Pp Function .Fn pmc_read -with read the current value of the PMC specified by argument +will read the current value of the PMC specified by argument .Fa pmc and write it to the location specified by argument .Fa value . diff --git a/lib/libradius/libradius.3 b/lib/libradius/libradius.3 index 9a71521d892..7fc11625f11 100644 --- a/lib/libradius/libradius.3 +++ b/lib/libradius/libradius.3 @@ -464,7 +464,7 @@ subsequent library calls using the same handle. To free the resources used by the RADIUS library, call .Fn rad_close . .Ss Server operation -Server mode operates much alike to client mode, except packet send and receieve +Server mode operates much alike to client mode, except packet send and receive steps are swapped. To operate as server you should obtain server context with .Fn rad_server_open function, passing opened and bound UDP socket file descriptor as argument. diff --git a/lib/librpcsec_gss/rpcsec_gss.3 b/lib/librpcsec_gss/rpcsec_gss.3 index 9b86f3eacfe..bcbef7cac06 100644 --- a/lib/librpcsec_gss/rpcsec_gss.3 +++ b/lib/librpcsec_gss/rpcsec_gss.3 @@ -68,7 +68,7 @@ typedef enum { .Ed .It Vt rpc_gss_options_ret_t This structure contains various optional values which are used while -creating a security contect. +creating a security context. .Bd -literal typedef struct { int req_flags; /* GSS request bits */ diff --git a/lib/libsdp/sdp.3 b/lib/libsdp/sdp.3 index c51b6f9e2e6..de115344e83 100644 --- a/lib/libsdp/sdp.3 +++ b/lib/libsdp/sdp.3 @@ -270,7 +270,7 @@ Note: attributes are returned in the order they appear in the Service Search Attribute Response. SDP server could return several attributes for the same record. In this case the order of the attributes will be: all attributes for the first -records, then all attributes for the secord record etc. +records, then all attributes for the second record etc. .Pp The .Fn sdp_attr2desc diff --git a/lib/libusb/libusb20.3 b/lib/libusb/libusb20.3 index 7896e8f0109..a7a39add2c0 100644 --- a/lib/libusb/libusb20.3 +++ b/lib/libusb/libusb20.3 @@ -524,7 +524,7 @@ returns a zero terminated string describing the backend used. .Pp . .Fn libusb20_dev_get_info -retrives the BSD specific usb_device_info structure into the memory location given by +retrieves the BSD specific usb_device_info structure into the memory location given by .Fa pinfo . The USB device given by .Fa pdev diff --git a/lib/libutil/quotafile.3 b/lib/libutil/quotafile.3 index 5702cec9076..8a78cd33c62 100644 --- a/lib/libutil/quotafile.3 +++ b/lib/libutil/quotafile.3 @@ -121,7 +121,7 @@ The .Fn quota_on function enables quotas for the filesystem associated with its .Va qf -argument which may have been opened +argument which may have been opened with .Dv O_RDONLY or .Dv O_RDWR . @@ -138,7 +138,7 @@ The .Fn quota_off function disables quotas for the filesystem associated with its .Va qf -argument which may have been opened +argument which may have been opened with .Dv O_RDONLY or .Dv O_RDWR . diff --git a/lib/msun/man/fdim.3 b/lib/msun/man/fdim.3 index 2de2e320ab4..b96ba56433f 100644 --- a/lib/msun/man/fdim.3 +++ b/lib/msun/man/fdim.3 @@ -65,7 +65,7 @@ is an \*(Na, then an \*(Na is returned. Otherwise, the result is .Li +0.0 . .Pp -Overflow or underflow may occur iff the exact result is not +Overflow or underflow may occur if the exact result is not representable in the return type. No other exceptions are raised. .Sh SEE ALSO diff --git a/sbin/devd/devd.conf.5 b/sbin/devd/devd.conf.5 index 17c5e099b56..41e7f5dd1e1 100644 --- a/sbin/devd/devd.conf.5 +++ b/sbin/devd/devd.conf.5 @@ -380,7 +380,7 @@ USB device is detached from the system. .Bl -tag -width ".Li DETACH" -compact .It Sy Type .It Li ATTACH -USB interface is attached from a device. +USB interface is attached to a device. .It Li DETACH USB interface is detached from a device. .El diff --git a/sbin/fsck_ffs/fsck_ffs.8 b/sbin/fsck_ffs/fsck_ffs.8 index d88689b1fa8..f60e5e2686a 100644 --- a/sbin/fsck_ffs/fsck_ffs.8 +++ b/sbin/fsck_ffs/fsck_ffs.8 @@ -179,7 +179,7 @@ and block 160 for UFS2. Check if file system was dismounted cleanly. If so, skip file system checks (like "preen"). However, if the file system was not cleanly dismounted, do full checks, -is if +as if .Nm was invoked without .Fl C . diff --git a/sbin/geom/core/geom.8 b/sbin/geom/core/geom.8 index 8c35aa3ee0a..e745a3f0a96 100644 --- a/sbin/geom/core/geom.8 +++ b/sbin/geom/core/geom.8 @@ -84,7 +84,7 @@ Load the kernel module that implements the given class. This command is only available if the class does not yet exist in the kernel and the file .Pa geom_ Ns Ao Ar class Ac Ns Pa .ko -can be found in one of the directories specifed in +can be found in one of the directories specified in .Va kern.module_path sysctl. .It Cm unload diff --git a/sbin/hastctl/hastctl.8 b/sbin/hastctl/hastctl.8 index c837353723b..727f54b3587 100644 --- a/sbin/hastctl/hastctl.8 +++ b/sbin/hastctl/hastctl.8 @@ -105,7 +105,7 @@ The default extent size is Maximum number of dirty extents to keep dirty all the time. Most recently used extents are kept dirty to reduce number of metadata updates. -The default numer of most recently used extents which will be kept +The default number of most recently used extents which will be kept dirty is .Va 64 . .It Fl m Ar mediasize diff --git a/sbin/hastd/hast.conf.5 b/sbin/hastd/hast.conf.5 index f1bd7cf6082..11f7244e21e 100644 --- a/sbin/hastd/hast.conf.5 +++ b/sbin/hastd/hast.conf.5 @@ -34,7 +34,7 @@ .Nm hast.conf .Nd configuration file for the .Xr hastd 8 -deamon and the +daemon and the .Xr hastctl 8 utility. .Sh DESCRIPTION diff --git a/sbin/ifconfig/ifconfig.8 b/sbin/ifconfig/ifconfig.8 index e3a5a948882..a7735d599c9 100644 --- a/sbin/ifconfig/ifconfig.8 +++ b/sbin/ifconfig/ifconfig.8 @@ -939,7 +939,7 @@ should be used by specifying ``6:g''. Similarly the channel width can be specified by appending it with ``/''; e.g. ``6/40'' specifies a 40MHz wide channel, These attributes can be combined as in: ``6:ht/40''. -The full set of flags specified following a `:'' are: +The full set of flags specified following a ``:'' are: .Cm a (802.11a), .Cm b @@ -966,7 +966,7 @@ The full set of channel widths following a '/' are: (20MHz mostly for use in specifying ht20), and .Cm 40 -(40MHz mostly for use in specifying ht40), +(40MHz mostly for use in specifying ht40). In addition, a 40MHz HT channel specification may include the location of the extension channel by appending ``+'' or ``-'' for above and below, @@ -999,7 +999,7 @@ according to a least-congested criteria. DFS support is mandatory for some 5Ghz frequencies in certain locales (e.g. ETSI). By default DFS is enabled according to the regulatory definitions -specified in /etc/regdomain.xml and the curent country code, regdomain, +specified in /etc/regdomain.xml and the current country code, regdomain, and channel. Note the underlying device (and driver) must support radar detection for full DFS support to work. @@ -1719,7 +1719,7 @@ If an .Ar index is not given, key 1 is set. A WEP key will be either 5 or 13 -characters (40 or 104 bits) depending of the local network and the +characters (40 or 104 bits) depending on the local network and the capabilities of the adaptor. It may be specified either as a plain string or as a string of hexadecimal digits preceded by @@ -1942,7 +1942,7 @@ Nodes on the mesh without a path to this root mesh station with try to discover a path to us. .It Cm PROACTIVE Send broadcast path requests every two seconds and every node must reply with -with a path reply even if it already has a path to this root mesh station, +with a path reply even if it already has a path to this root mesh station. .It Cm RANN Send broadcast root announcement (RANN) frames. Nodes on the mesh without a path to this root mesh station with try to diff --git a/sbin/ipfw/ipfw.8 b/sbin/ipfw/ipfw.8 index 2895170411a..b8e94f5acb0 100644 --- a/sbin/ipfw/ipfw.8 +++ b/sbin/ipfw/ipfw.8 @@ -1917,7 +1917,7 @@ and .Pp The SCHED_MASK is used to assign flows to one or more scheduler instances, one for each -value of the packet's 5-fuple after applying SCHED_MASK. +value of the packet's 5-tuple after applying SCHED_MASK. As an example, using ``src-ip 0xffffff00'' creates one instance for each /24 destination subnet. .Pp @@ -2098,7 +2098,7 @@ with either delay or probability first, according to the chosen format. The unit for delay is milliseconds. Data points do not need to be sorted. -Also, tne number of actual lines can be different +Also, the number of actual lines can be different from the value of the "samples" parameter: .Nm utility will sort and interpolate diff --git a/share/man/man4/bktr.4 b/share/man/man4/bktr.4 index 32baf3a33ac..59136bff593 100644 --- a/share/man/man4/bktr.4 +++ b/share/man/man4/bktr.4 @@ -128,7 +128,7 @@ is set to an integer from 1 to 23 taken from the following table: .Em sysctl hw.bt848.tuner=nnnn This can be used to override the tuner make which was detected at boot time. .Ql nnnn -is set to an integer from 1 to 16 taken from the following table: +is set to an integer from 0 to 16 taken from the following table: .Pp .Bl -tag -compact -width 22n .It NO_TUNER diff --git a/share/man/man4/bt.4 b/share/man/man4/bt.4 index d684ee6947d..be198195616 100644 --- a/share/man/man4/bt.4 +++ b/share/man/man4/bt.4 @@ -57,7 +57,7 @@ MultiMaster "W" Series Host Adapters: .Pp .Em "Adapter Bus Commands Description" BT-948 PCI 192 Ultra SCSI-3 -BT-958 PCI 192 Wide ULtra SCSI-3 +BT-958 PCI 192 Wide Ultra SCSI-3 BT-958D PCI 192 Wide Differential Ultra SCSI-3 .El .Bl -column "BT-956CD " "ISA " "Commands " Description diff --git a/share/man/man4/gbde.4 b/share/man/man4/gbde.4 index edac1a07316..2b868e55548 100644 --- a/share/man/man4/gbde.4 +++ b/share/man/man4/gbde.4 @@ -127,7 +127,7 @@ a very impossible task. .Pp Armed with one or more sector keys, our patient attacker will then go through essentially the same exercise, using the sector key and the -encrypted sector key to find the key used to encrypt the sectorkey. +encrypted sector key to find the key used to encrypt the sector key. .Pp Armed with one or more of these .Dq kkeys , diff --git a/share/man/man4/hwpmc.4 b/share/man/man4/hwpmc.4 index 6264bd01ef1..f65e8c40690 100644 --- a/share/man/man4/hwpmc.4 +++ b/share/man/man4/hwpmc.4 @@ -81,7 +81,7 @@ Some architectures offer faster methods of reading these counts. .It Em Sampling In sampling modes, the PMCs are configured to sample the CPU instruction pointer (and optionally to capture the call chain leading -upto the sampled instruction pointer) after a configurable number of +up to the sampled instruction pointer) after a configurable number of hardware events have been observed. Instruction pointer samples and call chain records are usually directed to a log file for subsequent analysis. diff --git a/share/man/man4/ip.4 b/share/man/man4/ip.4 index 9bf91400ee3..ea9172bb3db 100644 --- a/share/man/man4/ip.4 +++ b/share/man/man4/ip.4 @@ -757,7 +757,7 @@ and .Va ip_off fields .Em must -be provided in host byte order . +be provided in host byte order. All other fields must be provided in network byte order. See .Xr byteorder 3 diff --git a/share/man/man4/lmc.4 b/share/man/man4/lmc.4 index dc8e47b10ea..073f9b10921 100644 --- a/share/man/man4/lmc.4 +++ b/share/man/man4/lmc.4 @@ -517,7 +517,7 @@ packets occasionally. .Ss Device Polling .\" A T3 receiver can generate over 100K interrupts per second, -This can cause a system to +this can cause a system to .Dq live-lock : spend all of its time servicing interrupts. diff --git a/share/man/man4/mac_lomac.4 b/share/man/man4/mac_lomac.4 index 8ae8875acb4..e82513705c7 100644 --- a/share/man/man4/mac_lomac.4 +++ b/share/man/man4/mac_lomac.4 @@ -63,7 +63,7 @@ which protects the integrity of system objects and subjects by means of an information flow policy coupled with the subject demotion via floating labels. In LOMAC, all system subjects and objects are assigned integrity labels, made -up of one or more hierarchal grades, depending on the their types. +up of one or more hierarchial grades, depending on the their types. Together, these label elements permit all labels to be placed in a partial order, with information flow protections and demotion decisions based on a dominance operator diff --git a/share/man/man4/man4.i386/glxsb.4 b/share/man/man4/man4.i386/glxsb.4 index 051956992ac..c7bef274d4f 100644 --- a/share/man/man4/man4.i386/glxsb.4 +++ b/share/man/man4/man4.i386/glxsb.4 @@ -94,4 +94,4 @@ by It was ported to .Fx by -.An Patrick Lamaiziere Aq patfbsd@davenulle.org +.An Patrick Lamaiziere Aq patfbsd@davenulle.org . diff --git a/share/man/man4/meteor.4 b/share/man/man4/meteor.4 index f52d6538163..860e08e65f4 100644 --- a/share/man/man4/meteor.4 +++ b/share/man/man4/meteor.4 @@ -525,7 +525,7 @@ The .Dv METEORSETGEO will also attempt to reallocate a new contiguous kernel buffer if the new geometry exceeds the old geometry. -On +On the other hand, if the new geometry will fit in the existing buffer, the existing buffer is used. .Pp diff --git a/share/man/man4/mk48txx.4 b/share/man/man4/mk48txx.4 index 5706924bfcf..d1ed5631346 100644 --- a/share/man/man4/mk48txx.4 +++ b/share/man/man4/mk48txx.4 @@ -158,7 +158,7 @@ When this flag is set, the .Nm driver will register as a watchdog via the interface defined in -.Xr 9 watchdog +.Xr watchdog 9 if supported by the specific chip model. .It Dv MK48TXX_WDOG_ENABLE_WDS When this flag is set, diff --git a/share/man/man4/net80211.4 b/share/man/man4/net80211.4 index 6227b881d3f..693f6b92f2e 100644 --- a/share/man/man4/net80211.4 +++ b/share/man/man4/net80211.4 @@ -230,7 +230,7 @@ Return the MAC address for the current BSS identifier via .Va i_data . When the interface is running, the bssid is either the value configured locally (e.g. for an IBSS network started by the local station) -or the value adopted when joing an existing network. +or the value adopted when joining an existing network. For WDS interfaces this value is the address of the remote station. When the interface is not running, the bssid returned is the desired bssid, if any, that has been configured. @@ -485,12 +485,12 @@ and .It Dv IEEE80211_IOC_PUREG Return whether ``pure 11g'' mode is enabled in .Va i_val . -This setting is meaningful only for acces point operation; +This setting is meaningful only for access point operation; when non-zero, 802.11b stations will not be allowed to associate. .It Dv IEEE80211_IOC_PUREN Return whether ``pure 11n'' mode is enabled in .Va i_val . -This setting is meaningful only for acces point operation; +This setting is meaningful only for access point operation; when non-zero, legacy (non-11n capable) stations will not be allowed to associate. .It Dv IEEE80211_IOC_REGDOMAIN @@ -595,7 +595,7 @@ Return whether Atheros Dynamic Turbo mode is enabled in Dynamic Turbo mode is a non-standard protocol extension available only on Atheros devices where channel width is dynamically changed between 20MHz and 40MHz. -Note tht enabling Dynamic Turbo mode support does not guarantee use; +Note that enabling Dynamic Turbo mode support does not guarantee use; both client and access point must use Atheros devices and support must be enabled on both sides. .It Dv IEEE80211_IOC_TXPARAMS @@ -654,7 +654,7 @@ together with an optional IEEE80211_WMEPARAM_BSS flag to indicate if the parameter for the BSS or the channel is desired. If WME is not supported then .Er EINVAL -wil be returned. +will be returned. .It Dv IEEE80211_IOC_WME_CWMAX Return the WME CWmax setting (log2) for the specified Access Class (AC) in .Va i_val . diff --git a/share/man/man4/netgraph.4 b/share/man/man4/netgraph.4 index 74992156773..db5f3ffb566 100644 --- a/share/man/man4/netgraph.4 +++ b/share/man/man4/netgraph.4 @@ -531,7 +531,7 @@ The message can be examined using the macro, or completely extracted from the item using the .Fn NGI_GET_MSG which also removes the reference within the item. -If the Item still holds a reference to the message when it is freed +If the item still holds a reference to the message when it is freed (using the .Fn NG_FREE_ITEM macro), then the message will also be freed appropriately. diff --git a/share/man/man4/ng_btsocket.4 b/share/man/man4/ng_btsocket.4 index 5146d1507ea..7db8178b162 100644 --- a/share/man/man4/ng_btsocket.4 +++ b/share/man/man4/ng_btsocket.4 @@ -69,7 +69,7 @@ struct sockaddr_hci { }; .Ed .Pp -Raw HCI sockets support number of +Raw HCI sockets support a number of .Xr ioctl 2 requests such as: .Bl -tag -width indent diff --git a/share/man/man4/ngatmbase.4 b/share/man/man4/ngatmbase.4 index abee6d8762b..fd885ee5179 100644 --- a/share/man/man4/ngatmbase.4 +++ b/share/man/man4/ngatmbase.4 @@ -110,7 +110,7 @@ The list of pieces must be terminated by The .Fn uni_msg_destroy function -destroyes the messages and frees all the messages's memory. +destroys the messages and frees all the messages's memory. .Pp The .Fn uni_msg_unpack_mbuf diff --git a/share/man/man4/pcm.4 b/share/man/man4/pcm.4 index 1ea921d2a0e..710ec13340c 100644 --- a/share/man/man4/pcm.4 +++ b/share/man/man4/pcm.4 @@ -341,7 +341,7 @@ The sound system will dynamically create up to this many Set to .Dq 0 if no -.Tn VCHANS +.Tn VCHANs are desired. Maximum value is 256. .It Va hw.snd.report_soft_formats diff --git a/share/man/man4/sctp.4 b/share/man/man4/sctp.4 index 45a252100dc..8547428a10c 100644 --- a/share/man/man4/sctp.4 +++ b/share/man/man4/sctp.4 @@ -203,7 +203,7 @@ association. .It Dv SCTP_INITMSG This option allows you to get or set the default sending parameters when an association is implicitly setup. -It allows you to change such things as the maxium number of +It allows you to change such things as the maximum number of streams allowed inbound and the number of streams requested of the peer. .It Dv SCTP_AUTOCLOSE @@ -278,7 +278,7 @@ By default, when opening an IPV6 socket, when data arrives on the socket from a peer's V4 address the V4 address will be presented with an address family of AF_INET. -If this is undesireable, then this option +If this is undesirable, then this option can be enabled which will then convert all V4 addresses into mapped V6 representations. .It Dv SCTP_MAXSEG @@ -338,8 +338,8 @@ a peer. This option will let you get or set the list of HMAC algorithms used to authenticate peers. Note that the HMAC values are in priority order where -the first HMAC identifier is the most prefered -and the last is the least prefered. +the first HMAC identifier is the most preferred +and the last is the least preferred. .It Dv SCTP_AUTH_ACTIVE_KEY This option allows you to make a key active for the generation of authentication information. diff --git a/share/man/man4/termios.4 b/share/man/man4/termios.4 index 5e589b102ff..2a69d7b508c 100644 --- a/share/man/man4/termios.4 +++ b/share/man/man4/termios.4 @@ -1053,7 +1053,7 @@ overflowing the input queue. The precise conditions under which .Dv STOP and -START +.Dv START characters are transmitted are implementation defined. .Pp If diff --git a/share/man/man4/u3g.4 b/share/man/man4/u3g.4 index ad97b916851..eb192f9dffa 100644 --- a/share/man/man4/u3g.4 +++ b/share/man/man4/u3g.4 @@ -90,7 +90,7 @@ additional commands to switch it to modem mode. The .Xr u3gstub 4 device will attach temporarily to a 3G device with a mass storage device and -force it to switch to modem mode, +force it to switch to modem mode. The attach and detach of .Xr u3gstub and any driver disk device present on the 3G device is hidden, unless the diff --git a/share/man/man5/mqueuefs.5 b/share/man/man5/mqueuefs.5 index d5de933885f..2431267a8e3 100644 --- a/share/man/man5/mqueuefs.5 +++ b/share/man/man5/mqueuefs.5 @@ -36,7 +36,7 @@ .Sh SYNOPSIS To link into kernel: .Pp -.D1 Cd "options P1003_1B_MQUEUE" +.Cd "options P1003_1B_MQUEUE" .Pp To load as a kernel loadable module: .Pp diff --git a/share/man/man5/periodic.conf.5 b/share/man/man5/periodic.conf.5 index 7947a59626c..a3775d88c45 100644 --- a/share/man/man5/periodic.conf.5 +++ b/share/man/man5/periodic.conf.5 @@ -629,7 +629,7 @@ The default value if no value is set is 30. The same as .Va daily_scrub_zfs_default_threshold but specific to the pool -.Va Ns Ao Ar poolname Ac Ns . +.Ao Ar poolname Ac Ns . .It Va daily_local .Pq Vt str Set to a list of extra scripts that should be run after all other diff --git a/share/man/man7/bsd.snmpmod.mk.7 b/share/man/man7/bsd.snmpmod.mk.7 index 30cf20d4645..299daf227e1 100644 --- a/share/man/man7/bsd.snmpmod.mk.7 +++ b/share/man/man7/bsd.snmpmod.mk.7 @@ -67,7 +67,7 @@ A list of extra MIB definition files for .Xr gensnmptree 1 . This is optional. This file list is given to both calls to -.Xr gensnmptree 1 \(em +.Xr gensnmptree 1 No \(em the one that extracts the symbols in .Va XSYM from the MIB definitions and the one that diff --git a/share/man/man9/DEVICE_PROBE.9 b/share/man/man9/DEVICE_PROBE.9 index 8c38fc0a8bd..bf592c5affe 100644 --- a/share/man/man9/DEVICE_PROBE.9 +++ b/share/man/man9/DEVICE_PROBE.9 @@ -91,7 +91,7 @@ magical about them. .Bl -tag -width BUS_PROBE_NOWILDCARD .It BUS_PROBE_SPECIFIC The device that cannot be reprobed, and that no -possible other driver may exist (typically legacy drivers who don't fallow +possible other driver may exist (typically legacy drivers who don't follow all the rules, or special needs drivers). .It BUS_PROBE_VENDOR The device is supported by a vendor driver. diff --git a/share/man/man9/VOP_LISTEXTATTR.9 b/share/man/man9/VOP_LISTEXTATTR.9 index cca875d68ee..0900099b1d6 100644 --- a/share/man/man9/VOP_LISTEXTATTR.9 +++ b/share/man/man9/VOP_LISTEXTATTR.9 @@ -78,7 +78,7 @@ will be .Dv NULL when .Fa size -is not, and vise versa. +is not, and vice versa. .It Fa cred The user credentials to use in authorizing the request. .It Fa td diff --git a/share/man/man9/VOP_VPTOCNP.9 b/share/man/man9/VOP_VPTOCNP.9 index 794d6e57606..6bcbd25d3a9 100644 --- a/share/man/man9/VOP_VPTOCNP.9 +++ b/share/man/man9/VOP_VPTOCNP.9 @@ -42,7 +42,7 @@ .Sh DESCRIPTION This translates a vnode into its component name, and writes that name to the head of the buffer specified by -.Fa buf +.Fa buf . .Bl -tag -width buflen .It Fa vp The vnode to translate. diff --git a/share/man/man9/g_geom.9 b/share/man/man9/g_geom.9 index 19c49109801..2f4599d60ba 100644 --- a/share/man/man9/g_geom.9 +++ b/share/man/man9/g_geom.9 @@ -109,9 +109,9 @@ The topology lock has to be held. .Fn g_destroy_geom : .Bl -item -offset indent .It -The geom cannot posses any providers. +The geom cannot possess any providers. .It -The geom cannot posses any consumers. +The geom cannot possess any consumers. .It The topology lock has to be held. .El diff --git a/share/man/man9/g_wither_geom.9 b/share/man/man9/g_wither_geom.9 index 2c4b10eeaa3..8ced94948dd 100644 --- a/share/man/man9/g_wither_geom.9 +++ b/share/man/man9/g_wither_geom.9 @@ -54,7 +54,7 @@ This is an automatic to avoid duplicated code in all classes. Before it is called, field .Va softc -should be disposed off and set to +should be disposed of and set to .Dv NULL . Note that the .Fn g_wither_geom diff --git a/share/man/man9/ieee80211.9 b/share/man/man9/ieee80211.9 index 8fd6e0da655..30affc9b8a7 100644 --- a/share/man/man9/ieee80211.9 +++ b/share/man/man9/ieee80211.9 @@ -205,11 +205,11 @@ method. Transmit a raw 802.11 frame. The default method drops the frame and generates a message on the console. .It Dv ic_updateslot -Update hardware state after an 802.11 IFS slot time change, +Update hardware state after an 802.11 IFS slot time change. There is no default method; the pointer may be NULL in which case it will not be used. .It Dv ic_update_mcast -Update hardware for a change in the multicast packet filter, +Update hardware for a change in the multicast packet filter. The default method prints a console message. .It Dv ic_update_promisc Update hardware for a change in the promiscuous mode setting. @@ -261,13 +261,13 @@ The default method ages frames on the power-save queue (in AP mode) and pending frames in the receive reorder queues (for stations using A-MPDU). .It Dv ic_node_drain Reclaim all optional resources associated with a node. -This call is used to free up resources when they are in short supply, +This call is used to free up resources when they are in short supply. .It Dv ic_node_getrssi Return the Receive Signal Strength Indication (RSSI) in .5 dBm units for the specified node. This interface returns a subset of the information returned by -.Dv ic_node_getsignal , +.Dv ic_node_getsignal . The default method calculates a filtered average over the last ten samples passed in to .Xr ieee80211_input 9 @@ -341,7 +341,7 @@ Drivers may interpose this method if they need to setup private state for handling transmit A-MPDU. .It Dv ic_addb_response Process a received ADDBA Response Action frame and setup resources as -needed for doing transmit A-MPDU, +needed for doing transmit A-MPDU. .It Dv ic_addb_stop Shutdown an A-MPDU transmit stream for the specified station and AC. The default method reclaims local state after sending a DelBA Action frame. @@ -490,7 +490,7 @@ Devices supports hardware CKIP cipher. The follow general 802.11n capabilities are defined. The first capabilities are defined exactly as they appear in the 802.11n specification. -Capabilities beginning with IEEE80211_HTC_AMPDU are used soley by the +Capabilities beginning with IEEE80211_HTC_AMPDU are used solely by the .Nm layer. .Bl -tag -width IEEE80211_C_8023ENCAP diff --git a/share/man/man9/kproc.9 b/share/man/man9/kproc.9 index 69b58b01e4b..a20ab709b1c 100644 --- a/share/man/man9/kproc.9 +++ b/share/man/man9/kproc.9 @@ -244,7 +244,7 @@ when it is called by the new process. The .Fa procptr pointer points to a -.Vt "struct proc " +.Vt "struct proc" pointer that is the location to be updated with the new proc pointer if a new process is created, or if not .Dv NULL , @@ -255,7 +255,7 @@ then a new process is created and the field updated. If not NULL, the .Fa tdptr pointer points to a -.Vt "struct thread " +.Vt "struct thread" pointer that is the location to be updated with the new thread pointer. The .Fa flags diff --git a/share/man/man9/netisr.9 b/share/man/man9/netisr.9 index c6d5eadd916..ee6fbedf4d7 100644 --- a/share/man/man9/netisr.9 +++ b/share/man/man9/netisr.9 @@ -103,7 +103,7 @@ If the protocol implements .Va nh_m2flow , then .Nm -will query the protocol in the evet that the +will query the protocol in the event that the .Vt mbuf doesn't have a flow ID, falling back on source ordering. .It NETISR_POLICY_CPU @@ -120,7 +120,7 @@ whose fields are defined as follows: .Bl -tag -width "netisr_handler_t nh_handler" .It Vt "const char *" Va nh_name Unique character string name of the protocol, which may be included in -.Xr 2 sysctl +.Xr sysctl 2 MIB names, so should not contain whitespace. .It Vt netisr_handler_t Va nh_handler Protocol handler function that will be invoked on each packet received for diff --git a/share/man/man9/vm_page_bits.9 b/share/man/man9/vm_page_bits.9 index fdee5afd295..79d568552cc 100644 --- a/share/man/man9/vm_page_bits.9 +++ b/share/man/man9/vm_page_bits.9 @@ -84,7 +84,7 @@ The range is expected to be .Dv DEV_BSIZE aligned and no larger than .Dv PAGE_SIZE . -If it is not properly aligned, any unaligned chucks of the +If it is not properly aligned, any unaligned chunks of the .Dv DEV_BSIZE blocks at the beginning and end of the range will be zeroed. .Pp diff --git a/usr.bin/cpio/bsdcpio.1 b/usr.bin/cpio/bsdcpio.1 index 79b6997ef4a..bb69fd1578d 100644 --- a/usr.bin/cpio/bsdcpio.1 +++ b/usr.bin/cpio/bsdcpio.1 @@ -295,7 +295,7 @@ for more information. .Sh EXAMPLES The .Nm -command is traditionally used to copy file heirarchies in conjunction +command is traditionally used to copy file hierarchies in conjunction with the .Xr find 1 command. diff --git a/usr.bin/systat/systat.1 b/usr.bin/systat/systat.1 index 9d392d9e0d4..1a18f2f4e0d 100644 --- a/usr.bin/systat/systat.1 +++ b/usr.bin/systat/systat.1 @@ -225,7 +225,7 @@ Like the display, except that it displays .Tn IPv6 -statics. +statistics. It does not display .Tn UDP statistics. .It Ic tcp diff --git a/usr.sbin/bsnmpd/modules/snmp_bridge/snmp_bridge.3 b/usr.sbin/bsnmpd/modules/snmp_bridge/snmp_bridge.3 index 78d63e13260..ebcf286ed49 100644 --- a/usr.sbin/bsnmpd/modules/snmp_bridge/snmp_bridge.3 +++ b/usr.sbin/bsnmpd/modules/snmp_bridge/snmp_bridge.3 @@ -30,7 +30,7 @@ .Os .Sh NAME .Nm snmp_bridge -.Nd "bridge module for snmpd. +.Nd "bridge module for snmpd" .Sh LIBRARY .Pq begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" .Sh DESCRIPTION @@ -46,7 +46,7 @@ MIB also defines additional objects which make the functionality of similar to .Xr ifconfig 8 for configuring bridge interfaces. -Therefore one should consider adding write comminities or loading the +Therefore one should consider adding write communities or loading the .Nm module on systems where security is crucial. .Sh IMPLEMENTATION NOTES diff --git a/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 b/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 index 828a64df975..9f366f1c79d 100644 --- a/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 +++ b/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 @@ -45,7 +45,7 @@ management of virtual wireless interfaces. The MIB defines objects similar to th state data and configuration capabilities of .Xr ifconfig 8 for configuring virtual wireless interfaces. -Therefore one should consider adding write comminities or loading the +Therefore one should consider adding write communities or loading the .Nm module on systems where security is crucial. .Sh IMPLEMENTATION NOTES diff --git a/usr.sbin/freebsd-update/freebsd-update.8 b/usr.sbin/freebsd-update/freebsd-update.8 index 08a46332d40..6741f422ca9 100644 --- a/usr.sbin/freebsd-update/freebsd-update.8 +++ b/usr.sbin/freebsd-update/freebsd-update.8 @@ -56,7 +56,7 @@ Release Engineering Team, e.g., .Fx 7.3-RELEASE and .Fx -8.0, but not +8.0-RELEASE, but not .Fx 6.3-STABLE or .Fx diff --git a/usr.sbin/i2c/i2c.8 b/usr.sbin/i2c/i2c.8 index 3788d167381..ac560a490d2 100644 --- a/usr.sbin/i2c/i2c.8 +++ b/usr.sbin/i2c/i2c.8 @@ -78,7 +78,7 @@ transfer has been written to the device and before the actual read/write operation. rs - repeated start; ss - stop start; no - none. .It Fl n Ar skip_addr skip address - address(es) to be skipped during bus scan. -The are two ways to specify addresses to ignore: by range 'a..b' or +There are two ways to specify addresses to ignore: by range 'a..b' or using selected addresses 'a:b:c'. This option is available only when "-s" is used. .It Fl o Ar offset diff --git a/usr.sbin/lmcconfig/lmcconfig.8 b/usr.sbin/lmcconfig/lmcconfig.8 index ad3ef277328..9a608e4f3bb 100644 --- a/usr.sbin/lmcconfig/lmcconfig.8 +++ b/usr.sbin/lmcconfig/lmcconfig.8 @@ -108,7 +108,7 @@ All parameters after this apply to the T1E1 card. All parameters after this apply to the T3 card. .El .Ss Commands for all cards -The following parameters apply to more then one card type. +The following parameters apply to more than one card type. .Bl -tag -width indent .It Fl a Ar number Set Transmitter clock source to @@ -281,7 +281,7 @@ Select RAWIP mode \[em] bypass line protocol code. .It Fl X Select line protocol code rather than RAWIP mode. .It Fl y -Disable SPPP keep-alive packets, +Disable SPPP keep-alive packets. .It Fl Y Enable SPPP keep-alive packets. .It Fl z @@ -512,7 +512,7 @@ Print the status of the on-board T3 DSU \[em] see the .Sx EXAMPLES section. .It Fl S Ar number -Set payload scrambler polynominal to +Set payload scrambler polynomial to .Ar number : .Pp .Bl -column "9" -offset 1m -compact diff --git a/usr.sbin/nfscbd/nfscbd.8 b/usr.sbin/nfscbd/nfscbd.8 index f421d0efd59..e8efd552e7c 100644 --- a/usr.sbin/nfscbd/nfscbd.8 +++ b/usr.sbin/nfscbd/nfscbd.8 @@ -76,7 +76,7 @@ defined by NFSV4_CBPORT in /usr/include/fs/nfs/nfs.h, unless has been specified. For more information on what callbacks and Open Delegations do, see .%T "Network File System (NFS) Version 4 Protocol" , -RFC3530 . +RFC3530. .Pp The .Nm diff --git a/usr.sbin/nfsd/nfsv4.4 b/usr.sbin/nfsd/nfsv4.4 index fc93104f23c..22308830482 100644 --- a/usr.sbin/nfsd/nfsv4.4 +++ b/usr.sbin/nfsd/nfsv4.4 @@ -327,5 +327,5 @@ NFS V4 stable restart file At this time, there is no recall of delegations for local file system operations. As such, delegations should only be enabled for file systems -that are being used soley as NFS export volumes and are not being accessed +that are being used solely as NFS export volumes and are not being accessed via local system calls nor services such as Samba. diff --git a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.8 b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.8 index 15cece24110..2a37292fcdb 100644 --- a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.8 +++ b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.8 @@ -58,7 +58,7 @@ can be any one of the following: .It help Display a list of all commands. .It help Ar command -Dispay the help data for the specified command. +Display the help data for the specified command. .It disk-list Provide a listing of the storage devices detected on this system. .It disk-part Ar disk @@ -117,4 +117,4 @@ first appeared in This utility was written to install PC-BSD and has seen limited use as an installer for FreeBSD. It's likely that usage to install FreeBSD will expose edge cases that PC-BSD doesn't, as well as generate feature requests based -on unforseen needs. +on unforeseen needs. diff --git a/usr.sbin/pciconf/pciconf.8 b/usr.sbin/pciconf/pciconf.8 index 7492b5d613e..e1a59fe6d24 100644 --- a/usr.sbin/pciconf/pciconf.8 +++ b/usr.sbin/pciconf/pciconf.8 @@ -172,7 +172,7 @@ of the form Ns Va function Ns , .Li pci Ns Va bus Ns \&: Ns Va device Ns \&: Ns Va function Ns , or .Li pci Ns Va bus Ns \&: Ns Va device Ns . -In case of an abrigded form, omitted selector components are assumed to be 0. +In case of an abridged form, omitted selector components are assumed to be 0. An optional leading device name followed by @ and an optional final colon will be ignored; this is so that the first column in the output of .Nm diff --git a/usr.sbin/portsnap/portsnap/portsnap.8 b/usr.sbin/portsnap/portsnap/portsnap.8 index 3bbe333c51c..b04171a5bd3 100644 --- a/usr.sbin/portsnap/portsnap/portsnap.8 +++ b/usr.sbin/portsnap/portsnap/portsnap.8 @@ -97,7 +97,7 @@ operate on the directory or as given in the configuration file.) .It Fl s Ar server Fetch files from the specified server or server pool. -(default: portsnap.FreeBSD.org , or as given in the +(default: portsnap.FreeBSD.org, or as given in the configuration file.) .It path For From c06336d428ecfdbb370c367b7a912f19153b5eff Mon Sep 17 00:00:00 2001 From: Jilles Tjoelker Date: Mon, 16 Aug 2010 17:18:08 +0000 Subject: [PATCH 0020/1624] sh: Get rid of unnecessary non-standard empty lists. POSIX does not allow constructs like: if cmd; then fi { } Add a colon dummy command, except in a test that verifies that such empty lists do not cause crashes when used as a function definition. --- tools/regression/bin/sh/builtins/command3.0 | 1 + tools/regression/bin/sh/builtins/command5.0 | 1 + tools/regression/bin/sh/builtins/command6.0 | 1 + tools/regression/bin/sh/execution/func2.0 | 1 + tools/regression/bin/sh/set-e/elif1.0 | 2 ++ tools/regression/bin/sh/set-e/elif2.0 | 2 ++ tools/regression/bin/sh/set-e/if1.0 | 1 + tools/regression/bin/sh/set-e/if3.0 | 1 + tools/regression/bin/sh/set-e/while1.0 | 1 + tools/regression/bin/sh/set-e/while2.0 | 1 + 10 files changed, 12 insertions(+) diff --git a/tools/regression/bin/sh/builtins/command3.0 b/tools/regression/bin/sh/builtins/command3.0 index f4ca12090fa..9d4ae89e0e2 100644 --- a/tools/regression/bin/sh/builtins/command3.0 +++ b/tools/regression/bin/sh/builtins/command3.0 @@ -4,6 +4,7 @@ command -v true command -v /bin/ls fun() { + : } command -v fun command -v break diff --git a/tools/regression/bin/sh/builtins/command5.0 b/tools/regression/bin/sh/builtins/command5.0 index d94d2f46343..13b3fe1fe3f 100644 --- a/tools/regression/bin/sh/builtins/command5.0 +++ b/tools/regression/bin/sh/builtins/command5.0 @@ -4,6 +4,7 @@ command -V true command -V /bin/ls fun() { + : } command -V fun command -V break diff --git a/tools/regression/bin/sh/builtins/command6.0 b/tools/regression/bin/sh/builtins/command6.0 index 2ba836e58a2..0e6b5eea40e 100644 --- a/tools/regression/bin/sh/builtins/command6.0 +++ b/tools/regression/bin/sh/builtins/command6.0 @@ -5,6 +5,7 @@ command -pV true command -pV /bin/ls fun() { + : } command -pV fun command -pV break diff --git a/tools/regression/bin/sh/execution/func2.0 b/tools/regression/bin/sh/execution/func2.0 index affa802a5e2..9830b5e8a7c 100644 --- a/tools/regression/bin/sh/execution/func2.0 +++ b/tools/regression/bin/sh/execution/func2.0 @@ -1,4 +1,5 @@ # $FreeBSD$ +# The empty pairs of braces here are to test that this does not cause a crash. f() { } f diff --git a/tools/regression/bin/sh/set-e/elif1.0 b/tools/regression/bin/sh/set-e/elif1.0 index 80c7af6424a..6a5937d496a 100644 --- a/tools/regression/bin/sh/set-e/elif1.0 +++ b/tools/regression/bin/sh/set-e/elif1.0 @@ -1,5 +1,7 @@ # $FreeBSD$ set -e if false; then + : elif false; then + : fi diff --git a/tools/regression/bin/sh/set-e/elif2.0 b/tools/regression/bin/sh/set-e/elif2.0 index 028938b8183..9dbb4bf514a 100644 --- a/tools/regression/bin/sh/set-e/elif2.0 +++ b/tools/regression/bin/sh/set-e/elif2.0 @@ -1,5 +1,7 @@ # $FreeBSD$ set -e if false; then + : elif false; false; then + : fi diff --git a/tools/regression/bin/sh/set-e/if1.0 b/tools/regression/bin/sh/set-e/if1.0 index 0be254bb28b..36aa4bdcbcd 100644 --- a/tools/regression/bin/sh/set-e/if1.0 +++ b/tools/regression/bin/sh/set-e/if1.0 @@ -1,4 +1,5 @@ # $FreeBSD$ set -e if false; then + : fi diff --git a/tools/regression/bin/sh/set-e/if3.0 b/tools/regression/bin/sh/set-e/if3.0 index b23d5ba02cb..a4916a84266 100644 --- a/tools/regression/bin/sh/set-e/if3.0 +++ b/tools/regression/bin/sh/set-e/if3.0 @@ -1,4 +1,5 @@ # $FreeBSD$ set -e if false; false; then + : fi diff --git a/tools/regression/bin/sh/set-e/while1.0 b/tools/regression/bin/sh/set-e/while1.0 index e4c89389572..371c94a0440 100644 --- a/tools/regression/bin/sh/set-e/while1.0 +++ b/tools/regression/bin/sh/set-e/while1.0 @@ -1,4 +1,5 @@ # $FreeBSD$ set -e while false; do + : done diff --git a/tools/regression/bin/sh/set-e/while2.0 b/tools/regression/bin/sh/set-e/while2.0 index a331237ab3e..124966ca59e 100644 --- a/tools/regression/bin/sh/set-e/while2.0 +++ b/tools/regression/bin/sh/set-e/while2.0 @@ -1,4 +1,5 @@ # $FreeBSD$ set -e while false; false; do + : done From 9b1f97079c5255ef7ea87fa302faccaf93b4bd2a Mon Sep 17 00:00:00 2001 From: Pyun YongHyeon Date: Mon, 16 Aug 2010 17:48:55 +0000 Subject: [PATCH 0021/1624] Remove unnecessary clean target in em(4), igb(4) and ixgbe(4). While here also remove man target in igb(4). Reviewed by: jfv --- sys/modules/em/Makefile | 6 ------ sys/modules/igb/Makefile | 10 ---------- sys/modules/ixgbe/Makefile | 5 ----- 3 files changed, 21 deletions(-) diff --git a/sys/modules/em/Makefile b/sys/modules/em/Makefile index 1fac033d55b..b74ddf101f9 100644 --- a/sys/modules/em/Makefile +++ b/sys/modules/em/Makefile @@ -18,10 +18,4 @@ CFLAGS += -I${.CURDIR}/../../dev/e1000 # DEVICE_POLLING for a non-interrupt-driven method #CFLAGS += -DDEVICE_POLLING -clean: - rm -f device_if.h bus_if.h pci_if.h setdef* - rm -f *.o *.kld *.ko - rm -f @ machine - rm -f ${CLEANFILES} - .include diff --git a/sys/modules/igb/Makefile b/sys/modules/igb/Makefile index 4d375e59d4f..a66c32a40dc 100644 --- a/sys/modules/igb/Makefile +++ b/sys/modules/igb/Makefile @@ -14,14 +14,4 @@ CFLAGS += -I${.CURDIR}/../../dev/e1000 -DSMP # not advisable since MSIX gives better results #CFLAGS += -DDEVICE_POLLING -clean: - rm -f device_if.h bus_if.h pci_if.h setdef* - rm -f *.o *.kld *.ko - rm -f @ machine - rm -f ${CLEANFILES} - -man: - mv /usr/share/man/man4/igb.4.gz /usr/share/man/man4/igbSAVE.4.gz - cp igb.4 /usr/share/man/man4/ - .include diff --git a/sys/modules/ixgbe/Makefile b/sys/modules/ixgbe/Makefile index 2de7549a581..56c39eda268 100644 --- a/sys/modules/ixgbe/Makefile +++ b/sys/modules/ixgbe/Makefile @@ -8,9 +8,4 @@ SRCS += ixgbe_common.c ixgbe_api.c ixgbe_phy.c SRCS += ixgbe_82599.c ixgbe_82598.c CFLAGS+= -I${.CURDIR}/../../dev/ixgbe -DSMP -DIXGBE_FDIR -clean: - rm -f device_if.h bus_if.h pci_if.h setdef* *_StripErr - rm -f *.o *.kld *.ko - rm -f @ machine - .include From e5cce4162a6f34486c8bfc54f4437cc7e587b224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ulrich=20Sp=C3=B6rlein?= Date: Mon, 16 Aug 2010 18:47:35 +0000 Subject: [PATCH 0022/1624] Wordsmithing of bsnmpd.1 PR: docs/149157 Submitted by: Warren Block MFC after: 1 week --- contrib/bsnmp/snmpd/bsnmpd.1 | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/contrib/bsnmp/snmpd/bsnmpd.1 b/contrib/bsnmp/snmpd/bsnmpd.1 index 323c962e04c..6339358dba7 100644 --- a/contrib/bsnmp/snmpd/bsnmpd.1 +++ b/contrib/bsnmp/snmpd/bsnmpd.1 @@ -49,7 +49,7 @@ .Sh DESCRIPTION The .Nm -daemon server the internet SNMP (Simple Network Management Protocol). +daemon serves the internet SNMP (Simple Network Management Protocol). It is intended to serve only the absolute basic MIBs and implement all other MIBs through loadable modules. In this way the @@ -59,11 +59,10 @@ can be used in unexpected ways. The options are as follows: .Bl -tag -width ".It Fl D Ar options" .It Fl d -This option is used for debugging -.Nm -and causes it not to daemonize itself. +Do not daemonize. +Used for debugging. .It Fl h -This option prints a short usage message. +Print a short usage message. .It Fl c Ar file Use .Ar file @@ -75,33 +74,32 @@ flag followed by a comma separated string of options. The following options are available. .Bl -tag -width ".It Cm trace Ns Cm = Ns Cm level" .It Cm dump -This option causes all sent and received PDUs to be dumped to the terminal. +Dump all sent and received PDUs to the terminal. .It Cm events -This causes the debugging level of the event library (see +Set the debugging level of the event library (see .Xr eventlib 3 ) -to be set to 10. +to 10. .It Cm trace Ns Cm = Ns Cm level -This option causes the snmp library trace flag to be set to the specified +Set the snmp library trace flag to the specified value. The value can be specified in the usual C-syntax for numbers. .El .It Fl I Ar paths -This option specifies a colon separated list of directories to search for -configuration include files. +Specify a colon separated list of directories to search for configuration +include files. The default is .Pa /etc:/usr/etc/:/usr/local/etc . These paths are only searched for include specified within <> parentheses. .It Fl l Ar prefix -The +Use .Ar prefix -is used as the default basename for the pid and the configuration files. +as the default basename for the pid and the configuration files. .It Fl m Ar variable Ns Op = Ns Ar value Define a configuration variable. .It Fl p Ar file Specify an alternate pid file instead of the default one. .El .Sh CONFIGURATION -The .Nm reads its configuration from either the default or the user specified configuration file. @@ -218,7 +216,7 @@ If the element is a hostname, the IP address of the host is looked up and the four elements of the IP address are appended to the oid. .Pp -For example a oid of +For example, an oid of .Bd -unfilled -offset indent myvariable.27.foooll.[localhost]."&^!" .Ed @@ -253,13 +251,13 @@ is .It Pa /var/run/ Ns Ao Ar prefix Ac Ns \&.pid Default pid file. .It Pa /etc:/usr/etc/:/usr/local/etc -This is the default search path for system include files. +Default search path for system include files. .It Pa @MIBSPATH@FOKUS-MIB.txt .It Pa @MIBSPATH@BEGEMOT-MIB.txt .It Pa @MIBSPATH@BEGEMOT-SNMPD.txt -The definitions for the MIBs implemented in the daemon. +Definitions for the MIBs implemented in the daemon. .It Pa /etc/hosts.allow, /etc/hosts.deny -Access controls that should be enforced by TCP wrappers should be defined here. +Access controls that should be enforced by TCP wrappers are defined here. Further details are described in .Xr hosts_access 5 . .El From f239d44ec133a8a584c0ca65a96dc9bcd89c399b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ulrich=20Sp=C3=B6rlein?= Date: Mon, 16 Aug 2010 19:05:10 +0000 Subject: [PATCH 0023/1624] Bump document date after content changes. Pointy hat to: uqs --- contrib/bsnmp/snmpd/bsnmpd.1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/bsnmp/snmpd/bsnmpd.1 b/contrib/bsnmp/snmpd/bsnmpd.1 index 6339358dba7..06966f06ae6 100644 --- a/contrib/bsnmp/snmpd/bsnmpd.1 +++ b/contrib/bsnmp/snmpd/bsnmpd.1 @@ -31,7 +31,7 @@ .\" .\" $Begemot: bsnmp/snmpd/bsnmpd.1,v 1.12 2006/02/27 09:50:03 brandt_h Exp $ .\" -.Dd February 27, 2006 +.Dd August 16, 2010 .Dt BSNMPD 1 .Os .Sh NAME From 54be88c948f72d267f13930bcb67bbaef24fffd1 Mon Sep 17 00:00:00 2001 From: Joel Dahl Date: Mon, 16 Aug 2010 21:12:26 +0000 Subject: [PATCH 0024/1624] Fix two minor typos. --- contrib/bsnmp/snmpd/snmpmod.3 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/bsnmp/snmpd/snmpmod.3 b/contrib/bsnmp/snmpd/snmpmod.3 index 761fcc3a0ac..6bea4031010 100644 --- a/contrib/bsnmp/snmpd/snmpmod.3 +++ b/contrib/bsnmp/snmpd/snmpmod.3 @@ -558,7 +558,7 @@ For modules that implement SNMP client functions besides SNMP agent functions it may be necessary to identify SNMP requests by their identifier to allow easier routing of responses to the correct sub-system. Request id ranges -provide a way to aquire globally non-overlapping sub-ranges of the entire +provide a way to acquire globally non-overlapping sub-ranges of the entire 31-bit id range. .Pp A request id range is allocated with @@ -586,7 +586,7 @@ The function .Fn reqid_istype checks whether the request id .Fa reqid -is withing the range identified by +is within the range identified by .Fa type . The function .Fn reqid_type From 2070b57f64a47c7481f7ad2ce3266da99ee3592c Mon Sep 17 00:00:00 2001 From: Jilles Tjoelker Date: Mon, 16 Aug 2010 21:14:49 +0000 Subject: [PATCH 0025/1624] sh: Split off a more dubious test from parser/heredoc2.0. --- tools/regression/bin/sh/parser/heredoc2.0 | 5 ----- tools/regression/bin/sh/parser/heredoc8.0 | 20 ++++++++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 tools/regression/bin/sh/parser/heredoc8.0 diff --git a/tools/regression/bin/sh/parser/heredoc2.0 b/tools/regression/bin/sh/parser/heredoc2.0 index b2395202a3d..4bb85ad80c1 100644 --- a/tools/regression/bin/sh/parser/heredoc2.0 +++ b/tools/regression/bin/sh/parser/heredoc2.0 @@ -16,11 +16,6 @@ ${s} EOF )" = "ast*que?non"' -check '"$(cat < Date: Mon, 16 Aug 2010 21:26:47 +0000 Subject: [PATCH 0026/1624] Put parentheses around a few macros to prevent mdoc warnings. --- share/man/man4/enc.4 | 8 ++++---- share/man/man4/ipsec.4 | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/share/man/man4/enc.4 b/share/man/man4/enc.4 index 4b05e574005..edbc488c83f 100644 --- a/share/man/man4/enc.4 +++ b/share/man/man4/enc.4 @@ -82,10 +82,10 @@ framework can be independently controlled using the following variables: .Bl -column net.enc.out.ipsec_filter_mask 0x00000000 0x00000000 .It Sy "Name Defaults Suggested" -.It "net.enc.out.ipsec_bpf_mask" 0x00000003 0x00000001 -.It "net.enc.out.ipsec_filter_mask" 0x00000001 0x00000001 -.It "net.enc.in.ipsec_bpf_mask" 0x00000001 0x00000002 -.It "net.enc.in.ipsec_filter_mask" 0x00000001 0x00000002 +.It "net.enc.out.ipsec_bpf_mask 0x00000003 0x00000001" +.It "net.enc.out.ipsec_filter_mask 0x00000001 0x00000001" +.It "net.enc.in.ipsec_bpf_mask 0x00000001 0x00000002" +.It "net.enc.in.ipsec_filter_mask 0x00000001 0x00000002" .El .Pp For the incoming path a value of diff --git a/share/man/man4/ipsec.4 b/share/man/man4/ipsec.4 index 112fadb9522..d5f8b8f0f6c 100644 --- a/share/man/man4/ipsec.4 +++ b/share/man/man4/ipsec.4 @@ -90,8 +90,8 @@ To properly filter on the inner packets of an tunnel with firewalls, you can change the values of the following sysctls .Bl -column net.inet6.ipsec6.filtertunnel default enable .It Sy "Name Default Enable" -.It net.inet.ipsec.filtertunnel 0 1 -.It net.inet6.ipsec6.filtertunnel 0 1 +.It "net.inet.ipsec.filtertunnel 0 1" +.It "net.inet6.ipsec6.filtertunnel 0 1" .El .\" .Ss Kernel interface From 471bb0991423f373bb0cacd5c8a4e64f90305583 Mon Sep 17 00:00:00 2001 From: Pawel Jakub Dawidek Date: Mon, 16 Aug 2010 21:59:56 +0000 Subject: [PATCH 0027/1624] The 'size' variable is there to limit how many bytes we want to copy from 'addr'. It is very likely that size of 'addr' is larger than 'size', so checking strlcpy() return value is bogus. MFC after: 3 weeks --- sbin/hastd/proto_tcp4.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sbin/hastd/proto_tcp4.c b/sbin/hastd/proto_tcp4.c index 8415872d801..bfbae8c1c1e 100644 --- a/sbin/hastd/proto_tcp4.c +++ b/sbin/hastd/proto_tcp4.c @@ -156,8 +156,7 @@ tcp4_addr(const char *addr, struct sockaddr_in *sinp) size = (size_t)(pp - addr + 1); if (size > sizeof(iporhost)) return (ENAMETOOLONG); - if (strlcpy(iporhost, addr, size) >= size) - return (ENAMETOOLONG); + (void)strlcpy(iporhost, addr, size); } /* Convert string (IP address or host name) to in_addr_t. */ ip = str2ip(iporhost); From 7ba25e6e69cba5eff776e7edaf5b3d04ba28c36d Mon Sep 17 00:00:00 2001 From: Jilles Tjoelker Date: Mon, 16 Aug 2010 22:23:19 +0000 Subject: [PATCH 0028/1624] sh: Reduce unnecessary testsuite failures with other shells. --- tools/regression/bin/sh/builtins/fc1.0 | 2 +- tools/regression/bin/sh/builtins/fc2.0 | 2 +- tools/regression/bin/sh/execution/redir1.0 | 4 ++-- tools/regression/bin/sh/execution/redir2.0 | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/regression/bin/sh/builtins/fc1.0 b/tools/regression/bin/sh/builtins/fc1.0 index 7cf0d943a13..59d10ef6d2e 100644 --- a/tools/regression/bin/sh/builtins/fc1.0 +++ b/tools/regression/bin/sh/builtins/fc1.0 @@ -1,6 +1,6 @@ # $FreeBSD$ set -e -trap 'echo Broken pipe -- test failed' pipe +trap 'echo Broken pipe -- test failed' PIPE P=${TMPDIR:-/tmp} cd $P diff --git a/tools/regression/bin/sh/builtins/fc2.0 b/tools/regression/bin/sh/builtins/fc2.0 index dc4b6de847b..4f696d480be 100644 --- a/tools/regression/bin/sh/builtins/fc2.0 +++ b/tools/regression/bin/sh/builtins/fc2.0 @@ -1,6 +1,6 @@ # $FreeBSD$ set -e -trap 'echo Broken pipe -- test failed' pipe +trap 'echo Broken pipe -- test failed' PIPE P=${TMPDIR:-/tmp} cd $P diff --git a/tools/regression/bin/sh/execution/redir1.0 b/tools/regression/bin/sh/execution/redir1.0 index cc5cc49318f..dd0011f064b 100644 --- a/tools/regression/bin/sh/execution/redir1.0 +++ b/tools/regression/bin/sh/execution/redir1.0 @@ -1,5 +1,5 @@ # $FreeBSD$ -trap ': $((brokenpipe+=1))' pipe +trap ': $((brokenpipe+=1))' PIPE P=${TMPDIR:-/tmp} cd $P @@ -17,7 +17,7 @@ if [ $brokenpipe -ne 0 ]; then rc=3 fi wait -echo dummy >&4 +echo dummy >&4 2>/dev/null if [ $brokenpipe -eq 1 ]; then : ${rc:=0} fi diff --git a/tools/regression/bin/sh/execution/redir2.0 b/tools/regression/bin/sh/execution/redir2.0 index 079ee82f533..697662470d4 100644 --- a/tools/regression/bin/sh/execution/redir2.0 +++ b/tools/regression/bin/sh/execution/redir2.0 @@ -1,5 +1,5 @@ # $FreeBSD$ -trap ': $((brokenpipe+=1))' pipe +trap ': $((brokenpipe+=1))' PIPE P=${TMPDIR:-/tmp} cd $P @@ -17,7 +17,7 @@ mkfifo fifo1 fifo2 exec 4>fifo2 exec 3>fifo1 -echo dummy >&4 +echo dummy >&4 2>/dev/null if [ $brokenpipe -eq 1 ]; then : ${rc:=0} fi From cdcffc3f1ca65ddc5d0b30afa493654afd7e895a Mon Sep 17 00:00:00 2001 From: David Xu Date: Tue, 17 Aug 2010 02:50:12 +0000 Subject: [PATCH 0029/1624] Tweak code a bit to be POSIX compatible, when a cancellation request is acted upon, or when a thread calls pthread_exit(), the thread first disables cancellation by setting its cancelability state to PTHREAD_CANCEL_DISABLE and its cancelability type to PTHREAD_CANCEL_DEFERRED. The cancelability state remains set to PTHREAD_CANCEL_DISABLE until the thread has terminated. It has no effect if a cancellation cleanup handler or thread-specific data destructor routine changes the cancelability state to PTHREAD_CANCEL_ENABLE. --- lib/libthr/thread/thr_exit.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/libthr/thread/thr_exit.c b/lib/libthr/thread/thr_exit.c index 33a2451a45a..a875d14a27c 100644 --- a/lib/libthr/thread/thr_exit.c +++ b/lib/libthr/thread/thr_exit.c @@ -81,6 +81,8 @@ _pthread_exit(void *status) /* Flag this thread as exiting. */ curthread->cancelling = 1; + curthread->cancel_enable = 0; + curthread->cancel_async = 0; _thr_exit_cleanup(); From 385cae0f8ef850729962c9733e14374c9e23a0cd Mon Sep 17 00:00:00 2001 From: Pawel Jakub Dawidek Date: Tue, 17 Aug 2010 06:08:09 +0000 Subject: [PATCH 0030/1624] More tests, especially for lchown(2). --- tools/regression/pjdfstest/tests/chown/01.t | 3 +- tools/regression/pjdfstest/tests/chown/04.t | 8 ++++- tools/regression/pjdfstest/tests/chown/05.t | 7 ++-- tools/regression/pjdfstest/tests/chown/06.t | 6 +++- tools/regression/pjdfstest/tests/chown/07.t | 39 +++++++++++++++++---- tools/regression/pjdfstest/tests/chown/10.t | 4 ++- 6 files changed, 54 insertions(+), 13 deletions(-) diff --git a/tools/regression/pjdfstest/tests/chown/01.t b/tools/regression/pjdfstest/tests/chown/01.t index 9559e6e586e..d410f5dff70 100644 --- a/tools/regression/pjdfstest/tests/chown/01.t +++ b/tools/regression/pjdfstest/tests/chown/01.t @@ -6,7 +6,7 @@ desc="chown returns ENOTDIR if a component of the path prefix is not a directory dir=`dirname $0` . ${dir}/../misc.sh -echo "1..5" +echo "1..6" n0=`namegen` n1=`namegen` @@ -14,5 +14,6 @@ n1=`namegen` expect 0 mkdir ${n0} 0755 expect 0 create ${n0}/${n1} 0644 expect ENOTDIR chown ${n0}/${n1}/test 65534 65534 +expect ENOTDIR lchown ${n0}/${n1}/test 65534 65534 expect 0 unlink ${n0}/${n1} expect 0 rmdir ${n0} diff --git a/tools/regression/pjdfstest/tests/chown/04.t b/tools/regression/pjdfstest/tests/chown/04.t index 8575de7a9b7..e66d936ed5c 100644 --- a/tools/regression/pjdfstest/tests/chown/04.t +++ b/tools/regression/pjdfstest/tests/chown/04.t @@ -6,12 +6,18 @@ desc="chown returns ENOENT if the named file does not exist" dir=`dirname $0` . ${dir}/../misc.sh -echo "1..4" +echo "1..9" n0=`namegen` n1=`namegen` +n2=`namegen` expect 0 mkdir ${n0} 0755 expect ENOENT chown ${n0}/${n1}/test 65534 65534 expect ENOENT chown ${n0}/${n1} 65534 65534 +expect ENOENT lchown ${n0}/${n1}/test 65534 65534 +expect ENOENT lchown ${n0}/${n1} 65534 65534 +expect 0 symlink ${n2} ${n0}/${n1} +expect ENOENT chown ${n0}/${n1} 65534 65534 +expect 0 unlink ${n0}/${n1} expect 0 rmdir ${n0} diff --git a/tools/regression/pjdfstest/tests/chown/05.t b/tools/regression/pjdfstest/tests/chown/05.t index 6017f2d10ee..ec7cd5ccece 100644 --- a/tools/regression/pjdfstest/tests/chown/05.t +++ b/tools/regression/pjdfstest/tests/chown/05.t @@ -6,7 +6,7 @@ desc="chown returns EACCES when search permission is denied for a component of t dir=`dirname $0` . ${dir}/../misc.sh -echo "1..15" +echo "1..18" n0=`namegen` n1=`namegen` @@ -22,11 +22,14 @@ expect 0 -u 65534 -g 65533,65534 -- chown ${n1}/${n2} -1 65533 expect 65534,65533 -u 65534 -g 65534 stat ${n1}/${n2} uid,gid expect 0 chmod ${n1} 0644 expect EACCES -u 65534 -g 65533,65534 -- chown ${n1}/${n2} -1 65534 +expect EACCES -u 65534 -g 65533,65534 -- lchown ${n1}/${n2} -1 65534 expect 0 chmod ${n1} 0755 expect 65534,65533 -u 65534 -g 65534 stat ${n1}/${n2} uid,gid expect 0 -u 65534 -g 65533,65534 -- chown ${n1}/${n2} -1 65534 expect 65534,65534 -u 65534 -g 65534 stat ${n1}/${n2} uid,gid -expect 0 -u 65534 -g 65534 unlink ${n1}/${n2} +expect 0 -u 65534 -g 65533,65534 -- lchown ${n1}/${n2} -1 65533 +expect 65534,65533 -u 65534 -g 65533 stat ${n1}/${n2} uid,gid +expect 0 unlink ${n1}/${n2} expect 0 rmdir ${n1} cd ${cdir} expect 0 rmdir ${n0} diff --git a/tools/regression/pjdfstest/tests/chown/06.t b/tools/regression/pjdfstest/tests/chown/06.t index 8e6d2cc6389..39ccac68e87 100644 --- a/tools/regression/pjdfstest/tests/chown/06.t +++ b/tools/regression/pjdfstest/tests/chown/06.t @@ -6,14 +6,18 @@ desc="chown returns ELOOP if too many symbolic links were encountered in transla dir=`dirname $0` . ${dir}/../misc.sh -echo "1..6" +echo "1..10" n0=`namegen` n1=`namegen` expect 0 symlink ${n0} ${n1} expect 0 symlink ${n1} ${n0} +expect ELOOP chown ${n0} 65534 65534 +expect ELOOP chown ${n1} 65534 65534 expect ELOOP chown ${n0}/test 65534 65534 expect ELOOP chown ${n1}/test 65534 65534 +expect ELOOP lchown ${n0}/test 65534 65534 +expect ELOOP lchown ${n1}/test 65534 65534 expect 0 unlink ${n0} expect 0 unlink ${n1} diff --git a/tools/regression/pjdfstest/tests/chown/07.t b/tools/regression/pjdfstest/tests/chown/07.t index 3fd4437b4bc..7f73cbe0ec0 100644 --- a/tools/regression/pjdfstest/tests/chown/07.t +++ b/tools/regression/pjdfstest/tests/chown/07.t @@ -6,23 +6,48 @@ desc="chown returns EPERM if the operation would change the ownership, but the e dir=`dirname $0` . ${dir}/../misc.sh -echo "1..11" +echo "1..132" n0=`namegen` n1=`namegen` n2=`namegen` +n3=`namegen` expect 0 mkdir ${n0} 0755 cdir=`pwd` cd ${n0} expect 0 mkdir ${n1} 0755 expect 0 chown ${n1} 65534 65534 -expect 0 -u 65534 -g 65534 create ${n1}/${n2} 0644 -expect EPERM -u 65534 -g 65534 chown ${n1}/${n2} 65533 65533 -expect EPERM -u 65533 -g 65533 chown ${n1}/${n2} 65534 65534 -expect EPERM -u 65533 -g 65533 chown ${n1}/${n2} 65533 65533 -expect EPERM -u 65534 -g 65534 -- chown ${n1}/${n2} -1 65533 -expect 0 unlink ${n1}/${n2} +for type in regular dir fifo block char socket symlink; do + if [ "${type}" != "symlink" ]; then + create_file ${type} ${n1}/${n2} 65534 65534 + expect EPERM -u 65534 -g 65534 chown ${n1}/${n2} 65533 65533 + expect EPERM -u 65533 -g 65533 chown ${n1}/${n2} 65534 65534 + expect EPERM -u 65533 -g 65533 chown ${n1}/${n2} 65533 65533 + expect EPERM -u 65534 -g 65534 -- chown ${n1}/${n2} -1 65533 + expect 0 -u 65534 -g 65534 symlink ${n2} ${n1}/${n3} + expect EPERM -u 65534 -g 65534 chown ${n1}/${n3} 65533 65533 + expect EPERM -u 65533 -g 65533 chown ${n1}/${n3} 65534 65534 + expect EPERM -u 65533 -g 65533 chown ${n1}/${n3} 65533 65533 + expect EPERM -u 65534 -g 65534 -- chown ${n1}/${n3} -1 65533 + expect 0 unlink ${n1}/${n3} + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n1}/${n2} + else + expect 0 unlink ${n1}/${n2} + fi + fi + create_file ${type} ${n1}/${n2} 65534 65534 + expect EPERM -u 65534 -g 65534 lchown ${n1}/${n2} 65533 65533 + expect EPERM -u 65533 -g 65533 lchown ${n1}/${n2} 65534 65534 + expect EPERM -u 65533 -g 65533 lchown ${n1}/${n2} 65533 65533 + expect EPERM -u 65534 -g 65534 -- lchown ${n1}/${n2} -1 65533 + if [ "${type}" = "dir" ]; then + expect 0 rmdir ${n1}/${n2} + else + expect 0 unlink ${n1}/${n2} + fi +done expect 0 rmdir ${n1} cd ${cdir} expect 0 rmdir ${n0} diff --git a/tools/regression/pjdfstest/tests/chown/10.t b/tools/regression/pjdfstest/tests/chown/10.t index 1ef6f850f7a..961a5be27a7 100644 --- a/tools/regression/pjdfstest/tests/chown/10.t +++ b/tools/regression/pjdfstest/tests/chown/10.t @@ -6,7 +6,9 @@ desc="chown returns EFAULT if the path argument points outside the process's all dir=`dirname $0` . ${dir}/../misc.sh -echo "1..2" +echo "1..4" expect EFAULT chown NULL 65534 65534 expect EFAULT chown DEADCODE 65534 65534 +expect EFAULT lchown NULL 65534 65534 +expect EFAULT lchown DEADCODE 65534 65534 From ee235befcb8253fab9beea27b916f1bc46b33147 Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Tue, 17 Aug 2010 08:55:45 +0000 Subject: [PATCH 0031/1624] Supply some useful information to the started image using ELF aux vectors. In particular, provide pagesize and pagesizes array, the canary value for SSP use, number of host CPUs and osreldate. Tested by: marius (sparc64) MFC after: 1 month --- sys/amd64/include/elf.h | 8 ++++++- sys/arm/include/elf.h | 8 ++++++- sys/compat/freebsd32/freebsd32_misc.c | 29 ++++++++++++++++++++++--- sys/i386/include/elf.h | 8 ++++++- sys/ia64/include/elf.h | 8 ++++++- sys/kern/imgact_elf.c | 11 ++++++++++ sys/kern/kern_exec.c | 31 ++++++++++++++++++++++++--- sys/mips/include/elf.h | 8 ++++++- sys/powerpc/include/elf.h | 8 ++++++- sys/sparc64/include/elf.h | 8 ++++++- sys/sun4v/include/elf.h | 8 ++++++- sys/sys/imgact.h | 4 ++++ 12 files changed, 125 insertions(+), 14 deletions(-) diff --git a/sys/amd64/include/elf.h b/sys/amd64/include/elf.h index 678f5d3ba0f..1f5c754d663 100644 --- a/sys/amd64/include/elf.h +++ b/sys/amd64/include/elf.h @@ -88,8 +88,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ /* * Relocation types. diff --git a/sys/arm/include/elf.h b/sys/arm/include/elf.h index 0660ba6bea6..4cb2ae35a0f 100644 --- a/sys/arm/include/elf.h +++ b/sys/arm/include/elf.h @@ -76,8 +76,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ #define R_ARM_COUNT 33 /* Count of defined relocation types. */ diff --git a/sys/compat/freebsd32/freebsd32_misc.c b/sys/compat/freebsd32/freebsd32_misc.c index 579d81b28ba..8da38335983 100644 --- a/sys/compat/freebsd32/freebsd32_misc.c +++ b/sys/compat/freebsd32/freebsd32_misc.c @@ -2525,11 +2525,13 @@ syscall32_helper_unregister(struct syscall_helper_data *sd) register_t * freebsd32_copyout_strings(struct image_params *imgp) { - int argc, envc; + int argc, envc, i; u_int32_t *vectp; char *stringp, *destp; u_int32_t *stack_base; struct freebsd32_ps_strings *arginfo; + char canary[sizeof(long) * 8]; + int32_t pagesizes32[MAXPAGESIZES]; size_t execpath_len; int szsigcode; @@ -2545,8 +2547,10 @@ freebsd32_copyout_strings(struct image_params *imgp) sv_psstrings; szsigcode = *(imgp->proc->p_sysent->sv_szsigcode); destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE - - roundup(execpath_len, sizeof(char *)) - - roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *)); + roundup(execpath_len, sizeof(char *)) - + roundup(sizeof(canary), sizeof(char *)) - + roundup(sizeof(pagesizes32), sizeof(char *)) - + roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *)); /* * install sigcode @@ -2564,6 +2568,25 @@ freebsd32_copyout_strings(struct image_params *imgp) execpath_len); } + /* + * Prepare the canary for SSP. + */ + arc4rand(canary, sizeof(canary), 0); + imgp->canary = (uintptr_t)arginfo - szsigcode - execpath_len - + sizeof(canary); + copyout(canary, (void *)imgp->canary, sizeof(canary)); + imgp->canarylen = sizeof(canary); + + /* + * Prepare the pagesizes array. + */ + for (i = 0; i < MAXPAGESIZES; i++) + pagesizes32[i] = (uint32_t)pagesizes[i]; + imgp->pagesizes = (uintptr_t)arginfo - szsigcode - execpath_len - + roundup(sizeof(canary), sizeof(char *)) - sizeof(pagesizes32); + copyout(pagesizes32, (void *)imgp->pagesizes, sizeof(pagesizes32)); + imgp->pagesizeslen = sizeof(pagesizes32); + /* * If we have a valid auxargs ptr, prepare some room * on the stack. diff --git a/sys/i386/include/elf.h b/sys/i386/include/elf.h index 37ee279c167..6490f2af631 100644 --- a/sys/i386/include/elf.h +++ b/sys/i386/include/elf.h @@ -90,8 +90,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP. */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ /* * Relocation types. diff --git a/sys/ia64/include/elf.h b/sys/ia64/include/elf.h index 27182dbcae9..ab7706bb299 100644 --- a/sys/ia64/include/elf.h +++ b/sys/ia64/include/elf.h @@ -89,8 +89,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ /* * Values for e_flags. diff --git a/sys/kern/imgact_elf.c b/sys/kern/imgact_elf.c index c48e0f5f471..e29ddfa0ee5 100644 --- a/sys/kern/imgact_elf.c +++ b/sys/kern/imgact_elf.c @@ -51,6 +51,7 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include #include #include @@ -972,6 +973,16 @@ __elfN(freebsd_fixup)(register_t **stack_base, struct image_params *imgp) AUXARGS_ENTRY(pos, AT_BASE, args->base); if (imgp->execpathp != 0) AUXARGS_ENTRY(pos, AT_EXECPATH, imgp->execpathp); + AUXARGS_ENTRY(pos, AT_OSRELDATE, osreldate); + if (imgp->canary != 0) { + AUXARGS_ENTRY(pos, AT_CANARY, imgp->canary); + AUXARGS_ENTRY(pos, AT_CANARYLEN, imgp->canarylen); + } + AUXARGS_ENTRY(pos, AT_NCPUS, mp_ncpus); + if (imgp->pagesizes != 0) { + AUXARGS_ENTRY(pos, AT_PAGESIZES, imgp->pagesizes); + AUXARGS_ENTRY(pos, AT_PAGESIZESLEN, imgp->pagesizeslen); + } AUXARGS_ENTRY(pos, AT_NULL, 0); free(imgp->auxargs, M_TEMP); diff --git a/sys/kern/kern_exec.c b/sys/kern/kern_exec.c index c60e3294dd9..c4bdb91c7e4 100644 --- a/sys/kern/kern_exec.c +++ b/sys/kern/kern_exec.c @@ -385,6 +385,10 @@ do_execve(td, args, mac_p) imgp->args = args; imgp->execpath = imgp->freepath = NULL; imgp->execpathp = 0; + imgp->canary = 0; + imgp->canarylen = 0; + imgp->pagesizes = 0; + imgp->pagesizeslen = 0; #ifdef MAC error = mac_execve_enter(imgp, mac_p); @@ -1197,8 +1201,10 @@ exec_copyout_strings(imgp) struct ps_strings *arginfo; struct proc *p; size_t execpath_len; - int szsigcode; + int szsigcode, szps; + char canary[sizeof(long) * 8]; + szps = sizeof(pagesizes[0]) * MAXPAGESIZES; /* * Calculate string base and vector table pointers. * Also deal with signal trampoline code for this exec type. @@ -1214,6 +1220,8 @@ exec_copyout_strings(imgp) szsigcode = *(p->p_sysent->sv_szsigcode); destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE - roundup(execpath_len, sizeof(char *)) - + roundup(sizeof(canary), sizeof(char *)) - + roundup(szps, sizeof(char *)) - roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *)); /* @@ -1232,6 +1240,23 @@ exec_copyout_strings(imgp) execpath_len); } + /* + * Prepare the canary for SSP. + */ + arc4rand(canary, sizeof(canary), 0); + imgp->canary = (uintptr_t)arginfo - szsigcode - execpath_len - + sizeof(canary); + copyout(canary, (void *)imgp->canary, sizeof(canary)); + imgp->canarylen = sizeof(canary); + + /* + * Prepare the pagesizes array. + */ + imgp->pagesizes = (uintptr_t)arginfo - szsigcode - execpath_len - + roundup(sizeof(canary), sizeof(char *)) - szps; + copyout(pagesizes, (void *)imgp->pagesizes, szps); + imgp->pagesizeslen = szps; + /* * If we have a valid auxargs ptr, prepare some room * on the stack. @@ -1249,8 +1274,8 @@ exec_copyout_strings(imgp) * for argument of Runtime loader. */ vectp = (char **)(destp - (imgp->args->argc + - imgp->args->envc + 2 + imgp->auxarg_size + execpath_len) * - sizeof(char *)); + imgp->args->envc + 2 + imgp->auxarg_size) + * sizeof(char *)); } else { /* * The '+ 2' is for the null pointers at the end of each of diff --git a/sys/mips/include/elf.h b/sys/mips/include/elf.h index 2d6ca3e9038..2646181ca04 100644 --- a/sys/mips/include/elf.h +++ b/sys/mips/include/elf.h @@ -251,8 +251,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ #define ET_DYN_LOAD_ADDR 0x0120000 diff --git a/sys/powerpc/include/elf.h b/sys/powerpc/include/elf.h index 25c25063f9f..e1a5bc8c864 100644 --- a/sys/powerpc/include/elf.h +++ b/sys/powerpc/include/elf.h @@ -99,8 +99,14 @@ __ElfType(Auxinfo); #define AT_ICACHEBSIZE 11 /* Instruction cache block size for the uP. */ #define AT_UCACHEBSIZE 12 /* Cache block size, or `0' if cache not unified. */ #define AT_EXECPATH 13 /* Path to the executable. */ +#define AT_CANARY 14 /* Canary for SSP */ +#define AT_CANARYLEN 15 /* Length of the canary. */ +#define AT_OSRELDATE 16 /* OSRELDATE. */ +#define AT_NCPUS 17 /* Number of CPUs. */ +#define AT_PAGESIZES 18 /* Pagesizes. */ +#define AT_PAGESIZESLEN 19 /* Number of pagesizes. */ -#define AT_COUNT 14 /* Count of defined aux entry types. */ +#define AT_COUNT 20 /* Count of defined aux entry types. */ /* * Relocation types. diff --git a/sys/sparc64/include/elf.h b/sys/sparc64/include/elf.h index 2a666705d0f..0618434231b 100644 --- a/sys/sparc64/include/elf.h +++ b/sys/sparc64/include/elf.h @@ -84,8 +84,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ /* Define "machine" characteristics */ #if __ELF_WORD_SIZE == 32 diff --git a/sys/sun4v/include/elf.h b/sys/sun4v/include/elf.h index 2a666705d0f..0618434231b 100644 --- a/sys/sun4v/include/elf.h +++ b/sys/sun4v/include/elf.h @@ -84,8 +84,14 @@ __ElfType(Auxinfo); #define AT_GID 13 /* Real gid. */ #define AT_EGID 14 /* Effective gid. */ #define AT_EXECPATH 15 /* Path to the executable. */ +#define AT_CANARY 16 /* Canary for SSP */ +#define AT_CANARYLEN 17 /* Length of the canary. */ +#define AT_OSRELDATE 18 /* OSRELDATE. */ +#define AT_NCPUS 19 /* Number of CPUs. */ +#define AT_PAGESIZES 20 /* Pagesizes. */ +#define AT_PAGESIZESLEN 21 /* Number of pagesizes. */ -#define AT_COUNT 16 /* Count of defined aux entry types. */ +#define AT_COUNT 22 /* Count of defined aux entry types. */ /* Define "machine" characteristics */ #if __ELF_WORD_SIZE == 32 diff --git a/sys/sys/imgact.h b/sys/sys/imgact.h index 8c183ad70cb..b54815fc62c 100644 --- a/sys/sys/imgact.h +++ b/sys/sys/imgact.h @@ -71,6 +71,10 @@ struct image_params { char *execpath; unsigned long execpathp; char *freepath; + unsigned long canary; + int canarylen; + unsigned long pagesizes; + int pagesizeslen; }; #ifdef _KERNEL From d59a6353d7e825b2f97f4eea68956725635c4383 Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Tue, 17 Aug 2010 09:05:39 +0000 Subject: [PATCH 0032/1624] Use the newly provided aux vectors to get pagesize and osreldate information. Use local version of getpagesize(), rtld_getpagesize() in private allocator. Override the __getosreldate() previously fetched from libc_pic.a with local version that uses aux value if present. Note that __getosreldate() is used by rtld indirectly, by mmap(2) libc wrapper. To be able to utilize aux, split digest_dynamic() for use by init_rtld() into two parts, where the first one does not call malloc(), and the second part uses it. init_rtld() is able to initialize global variables before digest_dynamic2() calls. In particular, pagesize and osreldate are set up from the aux values. Now, rtld avoids (two) sysctl calls in startup. Tested by: marius (sparc64) MFC after: 1 month --- libexec/rtld-elf/malloc.c | 23 ++++++++++++- libexec/rtld-elf/rtld.c | 71 ++++++++++++++++++++++++++++++++++----- 2 files changed, 84 insertions(+), 10 deletions(-) diff --git a/libexec/rtld-elf/malloc.c b/libexec/rtld-elf/malloc.c index 3da5bee3b7f..38ae89af726 100644 --- a/libexec/rtld-elf/malloc.c +++ b/libexec/rtld-elf/malloc.c @@ -48,6 +48,7 @@ static char *rcsid = "$FreeBSD$"; */ #include +#include #include #include #include @@ -152,6 +153,26 @@ botch(s) static void xprintf(const char *, ...); #define TRACE() xprintf("TRACE %s:%d\n", __FILE__, __LINE__) +extern int pagesize; + +static int +rtld_getpagesize(void) +{ + int mib[2]; + size_t size; + + if (pagesize != 0) + return (pagesize); + + mib[0] = CTL_HW; + mib[1] = HW_PAGESIZE; + size = sizeof(pagesize); + if (sysctl(mib, 2, &pagesize, &size, NULL, 0) == -1) + return (-1); + return (pagesize); + +} + void * malloc(nbytes) size_t nbytes; @@ -166,7 +187,7 @@ malloc(nbytes) * align break pointer so all data will be page aligned. */ if (pagesz == 0) { - pagesz = n = getpagesize(); + pagesz = n = rtld_getpagesize(); if (morepages(NPOOLPAGES) == 0) return NULL; op = (union overhead *)(pagepool_start); diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c index 8082656657d..a7bf91449ef 100644 --- a/libexec/rtld-elf/rtld.c +++ b/libexec/rtld-elf/rtld.c @@ -40,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -84,6 +85,9 @@ typedef struct Struct_DoneList { */ static const char *basename(const char *); static void die(void) __dead2; +static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **, + const Elf_Dyn **); +static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *); static void digest_dynamic(Obj_Entry *, int); static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *); static Obj_Entry *dlcheck(void *); @@ -97,7 +101,7 @@ static char *find_library(const char *, const Obj_Entry *); static const char *gethints(void); static void init_dag(Obj_Entry *); static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *); -static void init_rtld(caddr_t); +static void init_rtld(caddr_t, Elf_Auxinfo **); static void initlist_add_neededs(Needed_Entry *, Objlist *); static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *); static bool is_exported(const Elf_Sym *); @@ -188,6 +192,8 @@ extern Elf_Dyn _DYNAMIC; #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL) #endif +int osreldate, pagesize; + /* * These are the functions the dynamic linker exports to application * programs. They are the only symbols the dynamic linker is willing @@ -350,7 +356,7 @@ _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) /* Initialize and relocate ourselves. */ assert(aux_info[AT_BASE] != NULL); - init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr); + init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info); __progname = obj_rtld.path; argv0 = argv[0] != NULL ? argv[0] : "(null)"; @@ -737,14 +743,16 @@ die(void) * information in its Obj_Entry structure. */ static void -digest_dynamic(Obj_Entry *obj, int early) +digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath, + const Elf_Dyn **dyn_soname) { const Elf_Dyn *dynp; Needed_Entry **needed_tail = &obj->needed; - const Elf_Dyn *dyn_rpath = NULL; - const Elf_Dyn *dyn_soname = NULL; int plttype = DT_REL; + *dyn_rpath = NULL; + *dyn_soname = NULL; + obj->bind_now = false; for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) { switch (dynp->d_tag) { @@ -868,11 +876,11 @@ digest_dynamic(Obj_Entry *obj, int early) * We have to wait until later to process this, because we * might not have gotten the address of the string table yet. */ - dyn_rpath = dynp; + *dyn_rpath = dynp; break; case DT_SONAME: - dyn_soname = dynp; + *dyn_soname = dynp; break; case DT_INIT: @@ -961,6 +969,12 @@ digest_dynamic(Obj_Entry *obj, int early) obj->pltrelasize = obj->pltrelsize; obj->pltrelsize = 0; } +} + +static void +digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath, + const Elf_Dyn *dyn_soname) +{ if (obj->z_origin && obj->origin_path == NULL) { obj->origin_path = xmalloc(PATH_MAX); @@ -978,6 +992,16 @@ digest_dynamic(Obj_Entry *obj, int early) object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val); } +static void +digest_dynamic(Obj_Entry *obj, int early) +{ + const Elf_Dyn *dyn_rpath; + const Elf_Dyn *dyn_soname; + + digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname); + digest_dynamic2(obj, dyn_rpath, dyn_soname); +} + /* * Process a shared object's program header. This is used only for the * main program, when the kernel has already loaded the main program @@ -1304,9 +1328,11 @@ init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp) * this function is to relocate the dynamic linker. */ static void -init_rtld(caddr_t mapbase) +init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info) { Obj_Entry objtmp; /* Temporary rtld object */ + const Elf_Dyn *dyn_rpath; + const Elf_Dyn *dyn_soname; /* * Conjure up an Obj_Entry structure for the dynamic linker. @@ -1323,7 +1349,7 @@ init_rtld(caddr_t mapbase) #endif if (RTLD_IS_DYNAMIC()) { objtmp.dynamic = rtld_dynamic(&objtmp); - digest_dynamic(&objtmp, 1); + digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname); assert(objtmp.needed == NULL); #if !defined(__mips__) /* MIPS and SH{3,5} have a bogus DT_TEXTREL. */ @@ -1344,6 +1370,13 @@ init_rtld(caddr_t mapbase) /* Now that non-local variables can be accesses, copy out obj_rtld. */ memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld)); + if (aux_info[AT_PAGESZ] != NULL) + pagesize = aux_info[AT_PAGESZ]->a_un.a_val; + if (aux_info[AT_OSRELDATE] != NULL) + osreldate = aux_info[AT_OSRELDATE]->a_un.a_val; + + digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname); + /* Replace the path with a dynamically allocated copy. */ obj_rtld.path = xstrdup(PATH_RTLD); @@ -3630,3 +3663,23 @@ fetch_ventry(const Obj_Entry *obj, unsigned long symnum) } return NULL; } + +int +__getosreldate(void) +{ + size_t len; + int oid[2]; + int error, osrel; + + if (osreldate != 0) + return (osreldate); + + oid[0] = CTL_KERN; + oid[1] = KERN_OSRELDATE; + osrel = 0; + len = sizeof(osrel); + error = sysctl(oid, 2, &osrel, &len, NULL, 0); + if (error == 0 && osrel > 0 && len == sizeof(osrel)) + osreldate = osrel; + return (osreldate); +} From 8fc48522522b62e7d812b07a3305535ebdfeddcc Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Tue, 17 Aug 2010 09:08:28 +0000 Subject: [PATCH 0033/1624] Provide the starting image with the pointer to ELF aux vector. It is written into the __elf_aux_vector variable, if the symbol is present. Idea from: kan Tested by: marius (sparc64) MFC after: 1 month --- libexec/rtld-elf/rtld.c | 1 + 1 file changed, 1 insertion(+) diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c index a7bf91449ef..a13ecb7b94a 100644 --- a/libexec/rtld-elf/rtld.c +++ b/libexec/rtld-elf/rtld.c @@ -541,6 +541,7 @@ _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) dbg("initializing key program variables"); set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : ""); set_program_var("environ", env); + set_program_var("__elf_aux_vector", aux); dbg("initializing thread locks"); lockdflt_init(); From cf2280aca702edef4dbccf8d1e1a8ac01c8565e7 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 17 Aug 2010 09:11:38 +0000 Subject: [PATCH 0034/1624] Add -m and -M options to control the minimum and maximum frequency. PR: bin/145063 Submitted by: Boris Kochergin Reviewed by: cperciva Approved by: rrs (mentor) MFC after: 2 weeks --- usr.sbin/powerd/powerd.8 | 6 +++ usr.sbin/powerd/powerd.c | 90 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 88 insertions(+), 8 deletions(-) diff --git a/usr.sbin/powerd/powerd.8 b/usr.sbin/powerd/powerd.8 index 2d6acffd22a..0991bce1105 100644 --- a/usr.sbin/powerd/powerd.8 +++ b/usr.sbin/powerd/powerd.8 @@ -35,6 +35,8 @@ .Op Fl a Ar mode .Op Fl b Ar mode .Op Fl i Ar percent +.Op Fl m Ar freq +.Op Fl M Ar freq .Op Fl n Ar mode .Op Fl p Ar ival .Op Fl P Ar pidfile @@ -79,6 +81,10 @@ to use while on battery power. Specifies the CPU load percent level when adaptive mode should begin to degrade performance to save power. The default is 50% or lower. +.It Fl m Ar freq +Specifies the minimum frequency to throttle down to. +.It Fl M Ar freq +Specifies the maximum frequency to throttle up to. .It Fl n Ar mode Selects the .Ar mode diff --git a/usr.sbin/powerd/powerd.c b/usr.sbin/powerd/powerd.c index 7192bddbbe9..a1a5126223a 100644 --- a/usr.sbin/powerd/powerd.c +++ b/usr.sbin/powerd/powerd.c @@ -84,7 +84,8 @@ const char *modes[] = { #define DEVCTL_MAXBUF 1024 static int read_usage_times(int *load); -static int read_freqs(int *numfreqs, int **freqs, int **power); +static int read_freqs(int *numfreqs, int **freqs, int **power, + int minfreq, int maxfreq); static int set_freq(int freq); static void acline_init(void); static void acline_read(void); @@ -174,10 +175,10 @@ read_usage_times(int *load) } static int -read_freqs(int *numfreqs, int **freqs, int **power) +read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq) { char *freqstr, *p, *q; - int i; + int i, j; size_t len = 0; if (sysctl(levels_mib, 4, NULL, &len, NULL, 0)) @@ -201,19 +202,30 @@ read_freqs(int *numfreqs, int **freqs, int **power) free(*freqs); return (-1); } - for (i = 0, p = freqstr; i < *numfreqs; i++) { + for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) { q = strchr(p, ' '); if (q != NULL) *q = '\0'; - if (sscanf(p, "%d/%d", &(*freqs)[i], &(*power)[i]) != 2) { + if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) { free(freqstr); free(*freqs); free(*power); return (-1); } + if (((*freqs)[j] >= minfreq || minfreq == -1) && + ((*freqs)[j] <= maxfreq || maxfreq == -1)) + j++; p = q + 1; } + *numfreqs = j; + if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) { + free(freqstr); + free(*freqs); + free(*power); + return (-1); + } + free(freqstr); return (0); } @@ -422,7 +434,7 @@ usage(void) { fprintf(stderr, -"usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-n mode] [-p ival] [-r %%] [-P pidfile]\n"); +"usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n"); exit(1); } @@ -435,6 +447,7 @@ main(int argc, char * argv[]) struct pidfh *pfh = NULL; const char *pidfile = NULL; int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load; + int minfreq = -1, maxfreq = -1; int ch, mode, mode_ac, mode_battery, mode_none, idle, to; uint64_t mjoules_used; size_t len; @@ -452,7 +465,7 @@ main(int argc, char * argv[]) if (geteuid() != 0) errx(1, "must be root to run"); - while ((ch = getopt(argc, argv, "a:b:i:n:p:P:r:v")) != -1) + while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1) switch (ch) { case 'a': parse_mode(optarg, &mode_ac, ch); @@ -468,6 +481,22 @@ main(int argc, char * argv[]) usage(); } break; + case 'm': + minfreq = atoi(optarg); + if (minfreq < 0) { + warnx("%d is not a valid CPU frequency", + minfreq); + usage(); + } + break; + case 'M': + maxfreq = atoi(optarg); + if (maxfreq < 0) { + warnx("%d is not a valid CPU frequency", + maxfreq); + usage(); + } + break; case 'n': parse_mode(optarg, &mode_none, ch); break; @@ -515,8 +544,10 @@ main(int argc, char * argv[]) /* Check if we can read the load and supported freqs. */ if (read_usage_times(NULL)) err(1, "read_usage_times"); - if (read_freqs(&numfreqs, &freqs, &mwatts)) + if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq)) err(1, "error reading supported CPU frequencies"); + if (numfreqs == 0) + errx(1, "no CPU frequencies in user-specified range"); /* Run in the background unless in verbose mode. */ if (!vflag) { @@ -552,6 +583,49 @@ main(int argc, char * argv[]) i = get_freq_id(curfreq, freqs, numfreqs); if (freq < 1) freq = 1; + + /* + * If we are in adaptive mode and the current frequency is outside the + * user-defined range, adjust it to be within the user-defined range. + */ + acline_read(); + if (acline_status > SRC_UNKNOWN) + errx(1, "invalid AC line status %d", acline_status); + if ((acline_status == SRC_AC && + (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) || + (acline_status == SRC_BATTERY && + (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) || + (acline_status == SRC_UNKNOWN && + (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) { + /* Read the current frequency. */ + len = sizeof(curfreq); + if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) { + if (vflag) + warn("error reading current CPU frequency"); + } + if (curfreq < freqs[numfreqs - 1]) { + if (vflag) { + printf("CPU frequency is below user-defined " + "minimum; changing frequency to %d " + "MHz\n", freqs[numfreqs - 1]); + } + if (set_freq(freqs[numfreqs - 1]) != 0) { + warn("error setting CPU freq %d", + freqs[numfreqs - 1]); + } + } else if (curfreq > freqs[0]) { + if (vflag) { + printf("CPU frequency is above user-defined " + "maximum; changing frequency to %d " + "MHz\n", freqs[0]); + } + if (set_freq(freqs[0]) != 0) { + warn("error setting CPU freq %d", + freqs[0]); + } + } + } + idle = 0; /* Main loop. */ for (;;) { From 2793b018446552e71e9125dc39366f9dbf9042ba Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Tue, 17 Aug 2010 09:13:26 +0000 Subject: [PATCH 0035/1624] Use aux vector to get values for SSP canary, pagesize, pagesizes array, number of host CPUs and osreldate. This eliminates the last sysctl(2) calls from the dynamically linked image startup. No objections from: kan Tested by: marius (sparc64) MFC after: 1 month --- lib/libc/gen/Makefile.inc | 2 +- lib/libc/gen/Symbol.map | 2 + lib/libc/gen/__getosreldate.c | 9 +- lib/libc/gen/aux.c | 146 ++++++++++++++++++++++++++++++++ lib/libc/gen/getosreldate.c | 9 +- lib/libc/gen/getpagesize.c | 25 ++++-- lib/libc/gen/getpagesizes.c | 13 ++- lib/libc/include/libc_private.h | 2 + lib/libc/stdlib/malloc.c | 21 +++-- lib/libc/sys/stack_protector.c | 8 ++ 10 files changed, 216 insertions(+), 21 deletions(-) create mode 100644 lib/libc/gen/aux.c diff --git a/lib/libc/gen/Makefile.inc b/lib/libc/gen/Makefile.inc index 0db5911f9c4..2c3d3920dfe 100644 --- a/lib/libc/gen/Makefile.inc +++ b/lib/libc/gen/Makefile.inc @@ -7,7 +7,7 @@ SRCS+= __getosreldate.c __xuname.c \ _once_stub.c _pthread_stubs.c _rand48.c _spinlock_stub.c \ _thread_init.c \ - alarm.c arc4random.c assert.c basename.c check_utility_compat.c \ + alarm.c arc4random.c assert.c aux.c basename.c check_utility_compat.c \ clock.c closedir.c confstr.c \ crypt.c ctermid.c daemon.c devname.c dirname.c disklabel.c \ dlfcn.c drand48.c erand48.c err.c errlst.c errno.c \ diff --git a/lib/libc/gen/Symbol.map b/lib/libc/gen/Symbol.map index 42404bcc277..5ba18604db6 100644 --- a/lib/libc/gen/Symbol.map +++ b/lib/libc/gen/Symbol.map @@ -492,4 +492,6 @@ FBSDprivate_1.0 { _libc_sem_timedwait_compat; _libc_sem_post_compat; _libc_sem_getvalue_compat; + + __elf_aux_vector; }; diff --git a/lib/libc/gen/__getosreldate.c b/lib/libc/gen/__getosreldate.c index 7e26845d9e6..980f9ef1fc5 100644 --- a/lib/libc/gen/__getosreldate.c +++ b/lib/libc/gen/__getosreldate.c @@ -29,6 +29,9 @@ __FBSDID("$FreeBSD$"); #include #include +#include +#include +#include "libc_private.h" int __getosreldate(void); @@ -51,7 +54,11 @@ __getosreldate(void) if (osreldate != 0) return (osreldate); - + + error = _elf_aux_info(AT_OSRELDATE, &osreldate, sizeof(osreldate)); + if (error == 0 && osreldate != 0) + return (osreldate); + oid[0] = CTL_KERN; oid[1] = KERN_OSRELDATE; osrel = 0; diff --git a/lib/libc/gen/aux.c b/lib/libc/gen/aux.c new file mode 100644 index 00000000000..b5c079bfde5 --- /dev/null +++ b/lib/libc/gen/aux.c @@ -0,0 +1,146 @@ +/*- + * Copyright 2010 Konstantin Belousov . + * 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. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + * + */ + +#include +__FBSDID("$FreeBSD$"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include "libc_private.h" + +Elf_Auxinfo *__elf_aux_vector; + +static pthread_once_t aux_once = PTHREAD_ONCE_INIT; + +static int pagesize, osreldate, canary_len, ncpus, pagesizes_len; +static char *canary, *pagesizes; + +static void +init_aux(void) +{ + Elf_Auxinfo *aux; + + for (aux = __elf_aux_vector; aux->a_type != AT_NULL; aux++) { + switch (aux->a_type) { + case AT_CANARY: + canary = (char *)(aux->a_un.a_ptr); + break; + + case AT_CANARYLEN: + canary_len = aux->a_un.a_val; + break; + + case AT_PAGESIZES: + pagesizes = (char *)(aux->a_un.a_ptr); + break; + + case AT_PAGESIZESLEN: + pagesizes_len = aux->a_un.a_val; + break; + + case AT_PAGESZ: + pagesize = aux->a_un.a_val; + break; + + case AT_OSRELDATE: + osreldate = aux->a_un.a_val; + break; + + case AT_NCPUS: + ncpus = aux->a_un.a_val; + break; + } + } +} + +int +_elf_aux_info(int aux, void *buf, int buflen) +{ + int res; + + if (__elf_aux_vector == NULL) + return (ENOSYS); + _once(&aux_once, init_aux); + + switch (aux) { + case AT_CANARY: + if (canary != NULL && canary_len >= buflen) { + memcpy(buf, canary, buflen); + memset(canary, 0, canary_len); + canary = NULL; + res = 0; + } else + res = ENOENT; + break; + case AT_PAGESIZES: + if (pagesizes != NULL && pagesizes_len >= buflen) { + memcpy(buf, pagesizes, buflen); + res = 0; + } else + res = ENOENT; + break; + + case AT_PAGESZ: + if (buflen == sizeof(int)) { + if (pagesize != 0) { + *(int *)buf = pagesize; + res = 0; + } else + res = ENOENT; + } else + res = EINVAL; + break; + case AT_OSRELDATE: + if (buflen == sizeof(int)) { + if (osreldate != 0) { + *(int *)buf = osreldate; + res = 0; + } else + res = ENOENT; + } else + res = EINVAL; + break; + case AT_NCPUS: + if (buflen == sizeof(int)) { + if (ncpus != 0) { + *(int *)buf = ncpus; + res = 0; + } else + res = ENOENT; + } else + res = EINVAL; + break; + default: + res = ENOENT; + break; + } + return (res); +} diff --git a/lib/libc/gen/getosreldate.c b/lib/libc/gen/getosreldate.c index 086da6a7033..83bdc85aa26 100644 --- a/lib/libc/gen/getosreldate.c +++ b/lib/libc/gen/getosreldate.c @@ -35,6 +35,7 @@ __FBSDID("$FreeBSD$"); #include #include +#include #include #include @@ -45,15 +46,17 @@ getosreldate(void) int mib[2]; size_t size; int value; - char *temp; + if ((temp = getenv("OSVERSION"))) { + value = atoi(temp); + return (value); + } + mib[0] = CTL_KERN; mib[1] = KERN_OSRELDATE; size = sizeof value; if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) return (-1); - if ((temp = getenv("OSVERSION"))) - value = atoi(temp); return (value); } diff --git a/lib/libc/gen/getpagesize.c b/lib/libc/gen/getpagesize.c index d796b9d77a0..f4b812861d7 100644 --- a/lib/libc/gen/getpagesize.c +++ b/lib/libc/gen/getpagesize.c @@ -36,8 +36,12 @@ __FBSDID("$FreeBSD$"); #include #include +#include +#include #include +#include "libc_private.h" + /* * This is unlikely to change over the running time of any * program, so we cache the result to save some syscalls. @@ -52,13 +56,20 @@ getpagesize() int mib[2]; static int value; size_t size; + int error; + + if (value != 0) + return (value); + + error = _elf_aux_info(AT_PAGESZ, &value, sizeof(value)); + if (error == 0 && value != 0) + return (value); + + mib[0] = CTL_HW; + mib[1] = HW_PAGESIZE; + size = sizeof value; + if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) + return (-1); - if (!value) { - mib[0] = CTL_HW; - mib[1] = HW_PAGESIZE; - size = sizeof value; - if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) - return (-1); - } return (value); } diff --git a/lib/libc/gen/getpagesizes.c b/lib/libc/gen/getpagesizes.c index b0de9390f88..534fe9e1fef 100644 --- a/lib/libc/gen/getpagesizes.c +++ b/lib/libc/gen/getpagesizes.c @@ -32,6 +32,9 @@ __FBSDID("$FreeBSD$"); #include #include +#include + +#include "libc_private.h" /* * Retrieves page size information from the system. Specifically, returns the @@ -51,7 +54,7 @@ getpagesizes(size_t pagesize[], int nelem) static u_long ps[MAXPAGESIZES]; static int nops; size_t size; - int i; + int error, i; if (nelem < 0 || (nelem > 0 && pagesize == NULL)) { errno = EINVAL; @@ -59,9 +62,13 @@ getpagesizes(size_t pagesize[], int nelem) } /* Cache the result of the sysctl(2). */ if (nops == 0) { + error = _elf_aux_info(AT_PAGESIZES, ps, sizeof(ps)); size = sizeof(ps); - if (sysctlbyname("hw.pagesizes", ps, &size, NULL, 0) == -1) - return (-1); + if (error != 0 || ps[0] == 0) { + if (sysctlbyname("hw.pagesizes", ps, &size, NULL, 0) + == -1) + return (-1); + } /* Count the number of page sizes that are supported. */ nops = size / sizeof(ps[0]); while (nops > 0 && ps[nops - 1] == 0) diff --git a/lib/libc/include/libc_private.h b/lib/libc/include/libc_private.h index cb0b40740f4..570441b1f6f 100644 --- a/lib/libc/include/libc_private.h +++ b/lib/libc/include/libc_private.h @@ -213,4 +213,6 @@ extern int __sys_fcntl(int, int, ...); /* execve() with PATH processing to implement posix_spawnp() */ int _execvpe(const char *, char * const *, char * const *); +int _elf_aux_info(int aux, void *buf, int buflen); + #endif /* _LIBC_PRIVATE_H_ */ diff --git a/lib/libc/stdlib/malloc.c b/lib/libc/stdlib/malloc.c index 1b581d41327..f1a13efd3a9 100644 --- a/lib/libc/stdlib/malloc.c +++ b/lib/libc/stdlib/malloc.c @@ -180,6 +180,7 @@ __FBSDID("$FreeBSD$"); #include #include +#include #include #include #include @@ -194,6 +195,8 @@ __FBSDID("$FreeBSD$"); #include "un-namespace.h" +#include "libc_private.h" + #define RB_COMPACT #include "rb.h" #if (defined(MALLOC_TCACHE) && defined(MALLOC_STATS)) @@ -5353,14 +5356,20 @@ small_size2bin_init_hard(void) static unsigned malloc_ncpus(void) { + int mib[2]; unsigned ret; - size_t retlen = sizeof(ret); - int mib[] = {CTL_HW, HW_NCPU}; + int error; + size_t len; - if (sysctl(mib, sizeof(mib) / sizeof(int), &ret, &retlen, - (void *)0, 0) == -1) { - /* Error. */ - ret = 1; + error = _elf_aux_info(AT_NCPUS, &ret, sizeof(ret)); + if (error != 0 || ret == 0) { + mib[0] = CTL_HW; + mib[1] = HW_NCPU; + len = sizeof(ret); + if (sysctl(mib, 2, &ret, &len, (void *)NULL, 0) == -1) { + /* Error. */ + ret = 1; + } } return (ret); diff --git a/lib/libc/sys/stack_protector.c b/lib/libc/sys/stack_protector.c index 14c20eb4f0b..b0108f9ff7a 100644 --- a/lib/libc/sys/stack_protector.c +++ b/lib/libc/sys/stack_protector.c @@ -34,10 +34,13 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include +#include #include #include #include #include +#include "libc_private.h" extern int __sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp, size_t newlen); @@ -54,9 +57,14 @@ __guard_setup(void) { int mib[2]; size_t len; + int error; if (__stack_chk_guard[0] != 0) return; + error = _elf_aux_info(AT_CANARY, __stack_chk_guard, + sizeof(__stack_chk_guard)); + if (error == 0 && __stack_chk_guard[0] != 0) + return; mib[0] = CTL_KERN; mib[1] = KERN_ARND; From 3affea8f990e70e79b8a8582e7f9c4b011c0fa7c Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 17 Aug 2010 09:39:06 +0000 Subject: [PATCH 0036/1624] To restart, sysinstall calls execl. Since it will create a new process, we can't check to see if sysinstall is running as init just by checking if the PID is 0. Introduce a new option that sets the RunningAsInit flag, and update the code to check RunningAsInit intstead of getpid(). PR: bin/38854 Submitted by: Peter Sedeffow Approved by: rrs (mentor) MFC after: 1 month --- usr.sbin/sysinstall/globals.c | 3 -- usr.sbin/sysinstall/install.c | 2 +- usr.sbin/sysinstall/main.c | 58 +++++++++++++++++++++++------------ usr.sbin/sysinstall/msg.c | 2 +- usr.sbin/sysinstall/system.c | 12 ++++++-- usr.sbin/sysinstall/termcap.c | 2 +- 6 files changed, 51 insertions(+), 28 deletions(-) diff --git a/usr.sbin/sysinstall/globals.c b/usr.sbin/sysinstall/globals.c index 9119c15b249..6c98b069454 100644 --- a/usr.sbin/sysinstall/globals.c +++ b/usr.sbin/sysinstall/globals.c @@ -76,13 +76,10 @@ globalsInit(void) { DebugFD = -1; ColorDisplay = FALSE; - Fake = FALSE; - Restarting = FALSE; OnVTY = FALSE; DialogActive = FALSE; VarHead = NULL; mediaDevice = NULL; - RunningAsInit = FALSE; HomeChunk = NULL; RootChunk = NULL; diff --git a/usr.sbin/sysinstall/install.c b/usr.sbin/sysinstall/install.c index cd43e94ff7c..07a16d17dd6 100644 --- a/usr.sbin/sysinstall/install.c +++ b/usr.sbin/sysinstall/install.c @@ -1274,7 +1274,7 @@ installVarDefaults(dialogMenuItem *self) variable_set2(VAR_FIXIT_TTY, "serial", 0); variable_set2(VAR_PKG_TMPDIR, "/var/tmp", 0); variable_set2(VAR_MEDIA_TIMEOUT, itoa(MEDIA_TIMEOUT), 0); - if (getpid() != 1) + if (!RunningAsInit) variable_set2(SYSTEM_STATE, "update", 0); else variable_set2(SYSTEM_STATE, "init", 0); diff --git a/usr.sbin/sysinstall/main.c b/usr.sbin/sysinstall/main.c index 47cbbcd2bc1..3f9164a0d69 100644 --- a/usr.sbin/sysinstall/main.c +++ b/usr.sbin/sysinstall/main.c @@ -56,12 +56,42 @@ main(int argc, char **argv) int choice, scroll, curr, max, status; char titlestr[80], *arch, *osrel, *ostype; struct rlimit rlim; - + char *arg; + int i; + int optionArgs = 0; + /* Record name to be able to restart */ StartName = argv[0]; + Restarting = FALSE; + RunningAsInit = FALSE; + Fake = FALSE; + + for (i = 1; i < argc; i++) { + arg = argv[i]; + + if (arg[0] != '-') + break; + + optionArgs++; + + if (!strcmp(arg, "-fake")) { + variable_set2(VAR_DEBUG, "YES", 0); + Fake = TRUE; + } else if (!strcmp(arg, "-restart")) { + Restarting = TRUE; + } else if (!strcmp(arg, "-fakeInit")) { + RunningAsInit = TRUE; + } + + arg = argv[optionArgs+1]; + } + + if (getpid() == 1) + RunningAsInit = TRUE; + /* Catch fatal signals and complain about them if running as init */ - if (getpid() == 1) { + if (RunningAsInit) { signal(SIGBUS, screech); signal(SIGSEGV, screech); } @@ -105,13 +135,8 @@ main(int argc, char **argv) if (!RunningAsInit) installEnvironment(); - if (argc > 1 && !strcmp(argv[1], "-fake")) { - variable_set2(VAR_DEBUG, "YES", 0); - Fake = TRUE; + if (Fake) msgConfirm("I'll be just faking it from here on out, OK?"); - } - if (argc > 1 && !strcmp(argv[1], "-restart")) - Restarting = TRUE; /* Try to preserve our scroll-back buffer */ if (OnVTY) { @@ -140,19 +165,14 @@ main(int argc, char **argv) /* First, see if we have any arguments to process (and argv[0] counts if it's not "sysinstall") */ if (!RunningAsInit) { - int i, start_arg; - - if (!strstr(argv[0], "sysinstall")) - start_arg = 0; - else if (Fake || Restarting) - start_arg = 2; - else - start_arg = 1; - for (i = start_arg; i < argc; i++) { + for (i = optionArgs+1; i < argc; i++) { if (DITEM_STATUS(dispatchCommand(argv[i])) != DITEM_SUCCESS) systemShutdown(1); } - if (argc > start_arg) + + /* If we were given commands to process on the command line, just exit + * now */ + if (argc > optionArgs+1) systemShutdown(0); } else @@ -187,7 +207,7 @@ main(int argc, char **argv) while (1) { choice = scroll = curr = max = 0; dmenuOpen(&MenuInitial, &choice, &scroll, &curr, &max, TRUE); - if (getpid() != 1 + if (!RunningAsInit #if defined(__sparc64__) || !msgNoYes("Are you sure you wish to exit? The system will halt.") #else diff --git a/usr.sbin/sysinstall/msg.c b/usr.sbin/sysinstall/msg.c index f11c72b17fc..6e20c60ae5a 100644 --- a/usr.sbin/sysinstall/msg.c +++ b/usr.sbin/sysinstall/msg.c @@ -233,7 +233,7 @@ msgFatal(char *fmt, ...) mvaddstr(StatusLine, 0, errstr); addstr(" - "); addstr("PRESS ANY KEY TO "); - if (getpid() == 1) + if (RunningAsInit) addstr("REBOOT"); else addstr("QUIT"); diff --git a/usr.sbin/sysinstall/system.c b/usr.sbin/sysinstall/system.c index ce1aa4b61b2..91ea2b21782 100644 --- a/usr.sbin/sysinstall/system.c +++ b/usr.sbin/sysinstall/system.c @@ -59,13 +59,20 @@ static int intr_restart(dialogMenuItem *self) { int ret, fd, fdmax; + char *arg; mediaClose(); free_variables(); fdmax = getdtablesize(); for (fd = 3; fd < fdmax; fd++) close(fd); - ret = execl(StartName, StartName, "-restart", (char *)NULL); + + if (RunningAsInit) + arg = "-restart -fakeInit"; + else + arg = "-restart"; + + ret = execl(StartName, StartName, arg, NULL); msgDebug("execl failed (%s)\n", strerror(errno)); /* NOTREACHED */ return -1; @@ -148,11 +155,10 @@ systemInitialize(int argc, char **argv) variable_set2(VAR_DEBUG, "YES", 0); /* Are we running as init? */ - if (getpid() == 1) { + if (RunningAsInit) { struct ufs_args ufs_args; int fd; - RunningAsInit = 1; setsid(); close(0); fd = open("/dev/ttyv0", O_RDWR); diff --git a/usr.sbin/sysinstall/termcap.c b/usr.sbin/sysinstall/termcap.c index 4f2b2e90cd9..4dc36c2ce48 100644 --- a/usr.sbin/sysinstall/termcap.c +++ b/usr.sbin/sysinstall/termcap.c @@ -105,7 +105,7 @@ set_termcap(void) else { int i, on; - if (getpid() == 1) { + if (RunningAsInit) { DebugFD = open("/dev/ttyv1", O_WRONLY); if (DebugFD != -1) { on = 1; From 7ac7ad63d881c9da37c4e52ec7396698a84a0b6d Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Tue, 17 Aug 2010 09:42:50 +0000 Subject: [PATCH 0037/1624] Add simple test to check the functioning of retrieval of pagesize()/pagesizes() after change to use aux vector. Note that public function getosreldate() is different from libc-internal __getosreldate() and does not use aux to fetch osreldate value. MFC after: 1 month --- tools/test/auxinfo/Makefile | 7 +++++ tools/test/auxinfo/auxinfo.c | 58 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 tools/test/auxinfo/Makefile create mode 100644 tools/test/auxinfo/auxinfo.c diff --git a/tools/test/auxinfo/Makefile b/tools/test/auxinfo/Makefile new file mode 100644 index 00000000000..e6e57685db6 --- /dev/null +++ b/tools/test/auxinfo/Makefile @@ -0,0 +1,7 @@ +# $FreeBSD$ + +PROG= auxinfo +NO_MAN= +WARNS?= 6 + +.include diff --git a/tools/test/auxinfo/auxinfo.c b/tools/test/auxinfo/auxinfo.c new file mode 100644 index 00000000000..374bed8b429 --- /dev/null +++ b/tools/test/auxinfo/auxinfo.c @@ -0,0 +1,58 @@ +/* + * This file is in public domain. + * Written by Konstantin Belousov + * + * $FreeBSD$ + */ + +#include +#include +#include +#include +#include +#include + +static void +test_pagesizes(void) +{ + size_t *ps; + int i, nelem; + + nelem = getpagesizes(NULL, 0); + if (nelem == -1) + err(1, "getpagesizes(NULL, 0)"); + ps = malloc(nelem * sizeof(size_t)); + if (ps == NULL) + err(1, "malloc"); + nelem = getpagesizes(ps, nelem); + if (nelem == -1) + err(1, "getpagesizes"); + printf("Supported page sizes:"); + for (i = 0; i < nelem; i++) + printf(" %jd", (intmax_t)ps[i]); + printf("\n"); +} + +static void +test_pagesize(void) +{ + + printf("Pagesize: %d\n", getpagesize()); +} + +static void +test_osreldate(void) +{ + + printf("OSRELDATE: %d\n", getosreldate()); +} + +int +main(int argc __unused, char *argv[] __unused) +{ + + test_pagesizes(); + test_pagesize(); + test_osreldate(); + return (0); +} From 2ab8e45eb85894f7a861849be625ee97be078da1 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 17 Aug 2010 09:51:08 +0000 Subject: [PATCH 0038/1624] Since top displays the uptime including seconds, there is no need to add 30 onto it, which may have been used for rounding purposes in other utilities. PR: bin/147934 Submitted by: Janne Snabb Approved by: rrs (mentor) MFC after: 2 weeks --- contrib/top/display.c | 1 - 1 file changed, 1 deletion(-) diff --git a/contrib/top/display.c b/contrib/top/display.c index 3fca57b5fdc..94765302dfb 100644 --- a/contrib/top/display.c +++ b/contrib/top/display.c @@ -1273,7 +1273,6 @@ time_t *tod; if (bt->tv_sec != -1) { uptime = *tod - bt->tv_sec; - uptime += 30; days = uptime / 86400; uptime %= 86400; hrs = uptime / 3600; From 8b03dbf71f6d77f896f4970fd7f20e461e96d68d Mon Sep 17 00:00:00 2001 From: Edwin Groothuis Date: Tue, 17 Aug 2010 12:04:17 +0000 Subject: [PATCH 0039/1624] Vendor import of tzdata2010l - Fix start times of DST for Egypt. - clocks were set back one hour at 2010-08-11 00:00:00 local time in Gaza and the West Bank. Obtained from: ftp://elsie.nci.nih.gov/pub/ --- africa | 6 +++--- asia | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/africa b/africa index 0c37506a2f6..481bc264bcb 100644 --- a/africa +++ b/africa @@ -1,5 +1,5 @@ #
-# @(#)africa	8.27
+# @(#)africa	8.28
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -311,8 +311,8 @@ Rule	Egypt	2007	only	-	Sep	Thu>=1	23:00s	0	-
 
 Rule	Egypt	2008	only	-	Aug	lastThu	23:00s	0	-
 Rule	Egypt	2009	only	-	Aug	20	23:00s	0	-
-Rule	Egypt	2010	only	-	Aug	10	23:00s	0	-
-Rule	Egypt	2010	only	-	Sep	9	0:00s	1:00	S
+Rule	Egypt	2010	only	-	Aug	11	0:00	0	-
+Rule	Egypt	2010	only	-	Sep	10	0:00	1:00	S
 Rule	Egypt	2010	max	-	Sep	lastThu	23:00s	0	-
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
diff --git a/asia b/asia
index 78ff2ffedcf..09158b669d3 100644
--- a/asia
+++ b/asia
@@ -1,4 +1,4 @@
-# @(#)asia	8.60
+# @(#)asia	8.61
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -2178,6 +2178,18 @@ Zone	Asia/Karachi	4:28:12 -	LMT	1907
 # "At 12:01am Friday, clocks in Israel and the West Bank will change to
 # 1:01am, while Gaza clocks will change at 12:01am Saturday morning."
 
+# From Steffen Thorsen (2010-08-11):
+# According to several sources, including
+# 
+# http://www.maannews.net/eng/ViewDetails.aspx?ID=306795
+# 
+# the clocks were set back one hour at 2010-08-11 00:00:00 local time in 
+# Gaza and the West Bank.
+# Some more background info:
+# 
+# http://www.timeanddate.com/news/time/westbank-gaza-end-dst-2010.html
+# 
+
 # The rules for Egypt are stolen from the `africa' file.
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule EgyptAsia	1957	only	-	May	10	0:00	1:00	S
@@ -2198,6 +2210,7 @@ Rule Palestine	2008	only	-	Aug	lastFri	2:00	0	-
 Rule Palestine	2009	only	-	Mar	lastFri	0:00	1:00	S
 Rule Palestine	2010	max	-	Mar	lastSat	0:01	1:00	S
 Rule Palestine	2009	max	-	Sep	Fri>=1	2:00	0	-
+Rule Palestine	2010	only	-	Aug	11	0:00	0	-
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Gaza	2:17:52	-	LMT	1900 Oct

From e0e08e6a6032cdfa92978fa8b8543e9f31ecb31a Mon Sep 17 00:00:00 2001
From: Pietro Cerutti 
Date: Tue, 17 Aug 2010 12:17:24 +0000
Subject: [PATCH 0040/1624] - The iMac9,1 needs the PAT workaround as well

Approved by:	cognet
---
 sys/amd64/amd64/pmap.c | 3 ++-
 sys/i386/i386/pmap.c   | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/sys/amd64/amd64/pmap.c b/sys/amd64/amd64/pmap.c
index ca575085f65..665c625d844 100644
--- a/sys/amd64/amd64/pmap.c
+++ b/sys/amd64/amd64/pmap.c
@@ -620,7 +620,8 @@ pmap_init_pat(void)
 		if (sysenv != NULL) {
 			if (strncmp(sysenv, "MacBook5,1", 10) == 0 ||
 			    strncmp(sysenv, "MacBookPro5,5", 13) == 0 ||
-			    strncmp(sysenv, "Macmini3,1", 10) == 0)
+			    strncmp(sysenv, "Macmini3,1", 10) == 0 ||
+			    strncmp(sysenv, "iMac9,1", 7) == 0)
 				pat_works = 0;
 			freeenv(sysenv);
 		}
diff --git a/sys/i386/i386/pmap.c b/sys/i386/i386/pmap.c
index f8c52a0e0b3..5c2c69614c0 100644
--- a/sys/i386/i386/pmap.c
+++ b/sys/i386/i386/pmap.c
@@ -518,7 +518,8 @@ pmap_init_pat(void)
 			if (sysenv != NULL) {
 				if (strncmp(sysenv, "MacBook5,1", 10) == 0 ||
 				    strncmp(sysenv, "MacBookPro5,5", 13) == 0 ||
-				    strncmp(sysenv, "Macmini3,1", 10) == 0)
+				    strncmp(sysenv, "Macmini3,1", 10) == 0 ||
+				    strncmp(sysenv, "iMac9,1", 7) == 0)
 					pat_works = 0;
 				freeenv(sysenv);
 			}

From efdcc3d8d8017692609360dcd1b41121bbea6601 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 17 Aug 2010 13:02:08 +0000
Subject: [PATCH 0041/1624] Make sure any -U CFLAGS are not filtered out when
 calling mkdep, as gnu/usr.bin/cc/libiberty first defines the PREFIX macro,
 and then undefines it again, so mkdep with clang complains.

Submitted by:	Dimitry Andric 
Reviewed by:	ru
---
 share/mk/bsd.dep.mk | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/share/mk/bsd.dep.mk b/share/mk/bsd.dep.mk
index 7711d80ed0b..a683a097d8e 100644
--- a/share/mk/bsd.dep.mk
+++ b/share/mk/bsd.dep.mk
@@ -126,13 +126,13 @@ depend: beforedepend ${DEPENDFILE} afterdepend
 # Different types of sources are compiled with slightly different flags.
 # Split up the sources, and filter out headers and non-applicable flags.
 .if ${CC} == "icc"
-MKDEP_CFLAGS=	${CFLAGS:M-X*} ${CFLAGS:M-[BID]*}
-MKDEP_CXXFLAGS=	${CXXFLAGS:M-X*} ${CXXFLAGS:M-[BID]*}
-MKDEP_OBJCFLAGS=${OBJCFLAGS:M-X*} ${OBJCFLAGS:M-[BID]*}
+MKDEP_CFLAGS=	${CFLAGS:M-X*} ${CFLAGS:M-[BIDU]*}
+MKDEP_CXXFLAGS=	${CXXFLAGS:M-X*} ${CXXFLAGS:M-[BIDU]*}
+MKDEP_OBJCFLAGS=${OBJCFLAGS:M-X*} ${OBJCFLAGS:M-[BIDU]*}
 .else
-MKDEP_CFLAGS=	${CFLAGS:M-nostdinc*} ${CFLAGS:M-[BID]*}
-MKDEP_CXXFLAGS=	${CXXFLAGS:M-nostdinc*} ${CXXFLAGS:M-[BID]*}
-MKDEP_OBJCFLAGS=${OBJCFLAGS:M-nostdinc*} ${OBJCFLAGS:M-[BID]*} ${OBJCFLAGS:M-Wno-import*}
+MKDEP_CFLAGS=	${CFLAGS:M-nostdinc*} ${CFLAGS:M-[BIDU]*}
+MKDEP_CXXFLAGS=	${CXXFLAGS:M-nostdinc*} ${CXXFLAGS:M-[BIDU]*}
+MKDEP_OBJCFLAGS=${OBJCFLAGS:M-nostdinc*} ${OBJCFLAGS:M-[BIDU]*} ${OBJCFLAGS:M-Wno-import*}
 .endif
 
 DPSRCS+= ${SRCS}

From 62508c531e0f19a9154670a3cd820164c486131f Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Tue, 17 Aug 2010 15:44:52 +0000
Subject: [PATCH 0042/1624] Add a new method to the PCI bridge interface,
 PCIB_POWER_FOR_SLEEP().  This method is used by the PCI bus driver to query
 the power management system to determine the proper device state to be used
 for a device during suspend and resume.  For the ACPI PCI bridge drivers this
 calls acpi_device_pwr_for_sleep().  This removes ACPI-specific knowledge from
 the PCI and PCI-PCI bridge drivers.

Reviewed by:	jkim
---
 sys/dev/acpica/acpi.c           |  4 +--
 sys/dev/acpica/acpi_pcib.c      | 11 +++++++
 sys/dev/acpica/acpi_pcib_acpi.c |  1 +
 sys/dev/acpica/acpi_pcib_pci.c  |  1 +
 sys/dev/acpica/acpi_pcibvar.h   |  2 ++
 sys/dev/acpica/acpivar.h        |  2 ++
 sys/dev/pci/pci.c               | 53 +++++++++++++--------------------
 sys/dev/pci/pci_pci.c           | 41 ++++++++++++-------------
 sys/dev/pci/pci_private.h       |  2 ++
 sys/dev/pci/pcib_if.m           | 10 +++++++
 10 files changed, 72 insertions(+), 55 deletions(-)

diff --git a/sys/dev/acpica/acpi.c b/sys/dev/acpica/acpi.c
index f173dc34eb7..feef2cc3fdd 100644
--- a/sys/dev/acpica/acpi.c
+++ b/sys/dev/acpica/acpi.c
@@ -129,8 +129,6 @@ static char	*acpi_device_id_probe(device_t bus, device_t dev, char **ids);
 static ACPI_STATUS acpi_device_eval_obj(device_t bus, device_t dev,
 		    ACPI_STRING pathname, ACPI_OBJECT_LIST *parameters,
 		    ACPI_BUFFER *ret);
-static int	acpi_device_pwr_for_sleep(device_t bus, device_t dev,
-		    int *dstate);
 static ACPI_STATUS acpi_device_scan_cb(ACPI_HANDLE h, UINT32 level,
 		    void *context, void **retval);
 static ACPI_STATUS acpi_device_scan_children(device_t bus, device_t dev,
@@ -1415,7 +1413,7 @@ acpi_device_eval_obj(device_t bus, device_t dev, ACPI_STRING pathname,
     return (AcpiEvaluateObject(h, pathname, parameters, ret));
 }
 
-static int
+int
 acpi_device_pwr_for_sleep(device_t bus, device_t dev, int *dstate)
 {
     struct acpi_softc *sc;
diff --git a/sys/dev/acpica/acpi_pcib.c b/sys/dev/acpica/acpi_pcib.c
index 65996f5b066..1b26b4f6a1f 100644
--- a/sys/dev/acpica/acpi_pcib.c
+++ b/sys/dev/acpica/acpi_pcib.c
@@ -275,3 +275,14 @@ out:
 
     return_VALUE (interrupt);
 }
+
+int
+acpi_pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
+{
+    device_t acpi_dev;
+
+    acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
+    acpi_device_pwr_for_sleep(acpi_dev, dev, pstate);
+    return (0);
+}
+
diff --git a/sys/dev/acpica/acpi_pcib_acpi.c b/sys/dev/acpica/acpi_pcib_acpi.c
index 72753303cc1..2ea9f2c1e1c 100644
--- a/sys/dev/acpica/acpi_pcib_acpi.c
+++ b/sys/dev/acpica/acpi_pcib_acpi.c
@@ -116,6 +116,7 @@ static device_method_t acpi_pcib_acpi_methods[] = {
     DEVMETHOD(pcib_alloc_msix,		acpi_pcib_alloc_msix),
     DEVMETHOD(pcib_release_msix,	pcib_release_msix),
     DEVMETHOD(pcib_map_msi,		acpi_pcib_map_msi),
+    DEVMETHOD(pcib_power_for_sleep,	acpi_pcib_power_for_sleep),
 
     {0, 0}
 };
diff --git a/sys/dev/acpica/acpi_pcib_pci.c b/sys/dev/acpica/acpi_pcib_pci.c
index 2196940c721..a76698141f0 100644
--- a/sys/dev/acpica/acpi_pcib_pci.c
+++ b/sys/dev/acpica/acpi_pcib_pci.c
@@ -80,6 +80,7 @@ static device_method_t acpi_pcib_pci_methods[] = {
 
     /* pcib interface */
     DEVMETHOD(pcib_route_interrupt,	acpi_pcib_pci_route_interrupt),
+    DEVMETHOD(pcib_power_for_sleep,	acpi_pcib_power_for_sleep),
 
     {0, 0}
 };
diff --git a/sys/dev/acpica/acpi_pcibvar.h b/sys/dev/acpica/acpi_pcibvar.h
index 00e03fa16bf..9a4be077f58 100644
--- a/sys/dev/acpica/acpi_pcibvar.h
+++ b/sys/dev/acpica/acpi_pcibvar.h
@@ -38,6 +38,8 @@ int	acpi_pci_link_route_interrupt(device_t dev, int index);
 int	acpi_pcib_attach(device_t bus, ACPI_BUFFER *prt, int busno);
 int	acpi_pcib_route_interrupt(device_t pcib, device_t dev, int pin,
     ACPI_BUFFER *prtbuf);
+int	acpi_pcib_power_for_sleep(device_t pcib, device_t dev,
+    int *pstate);
 
 #endif /* _KERNEL */
 
diff --git a/sys/dev/acpica/acpivar.h b/sys/dev/acpica/acpivar.h
index adc9d6ea66c..34284d5d8e1 100644
--- a/sys/dev/acpica/acpivar.h
+++ b/sys/dev/acpica/acpivar.h
@@ -393,6 +393,8 @@ EVENTHANDLER_DECLARE(acpi_wakeup_event, acpi_event_handler_t);
 /* Device power control. */
 ACPI_STATUS	acpi_pwr_wake_enable(ACPI_HANDLE consumer, int enable);
 ACPI_STATUS	acpi_pwr_switch_consumer(ACPI_HANDLE consumer, int state);
+int		acpi_device_pwr_for_sleep(device_t bus, device_t dev,
+		    int *dstate);
 
 /* Misc. */
 static __inline struct acpi_softc *
diff --git a/sys/dev/pci/pci.c b/sys/dev/pci/pci.c
index e1c7645821b..071f257e628 100644
--- a/sys/dev/pci/pci.c
+++ b/sys/dev/pci/pci.c
@@ -69,13 +69,6 @@ __FBSDID("$FreeBSD$");
 #include "pcib_if.h"
 #include "pci_if.h"
 
-#ifdef __HAVE_ACPI
-#include 
-#include "acpi_if.h"
-#else
-#define	ACPI_PWR_FOR_SLEEP(x, y, z)
-#endif
-
 static pci_addr_t	pci_mapbase(uint64_t mapreg);
 static const char	*pci_maptype(uint64_t mapreg);
 static int		pci_mapsize(uint64_t testval);
@@ -2914,16 +2907,13 @@ int
 pci_suspend(device_t dev)
 {
 	int dstate, error, i, numdevs;
-	device_t acpi_dev, child, *devlist;
+	device_t child, *devlist, pcib;
 	struct pci_devinfo *dinfo;
 
 	/*
 	 * Save the PCI configuration space for each child and set the
 	 * device in the appropriate power state for this sleep state.
 	 */
-	acpi_dev = NULL;
-	if (pci_do_power_resume)
-		acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
 	if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
 		return (error);
 	for (i = 0; i < numdevs; i++) {
@@ -2940,22 +2930,23 @@ pci_suspend(device_t dev)
 	}
 
 	/*
-	 * Always set the device to D3.  If ACPI suggests a different
-	 * power state, use it instead.  If ACPI is not present, the
-	 * firmware is responsible for managing device power.  Skip
-	 * children who aren't attached since they are powered down
-	 * separately.  Only manage type 0 devices for now.
+	 * Always set the device to D3.  If the firmware suggests a
+	 * different power state, use it instead.  If power management
+	 * is not present, the firmware is responsible for managing
+	 * device power.  Skip children who aren't attached since they
+	 * are powered down separately.  Only manage type 0 devices
+	 * for now.
 	 */
-	for (i = 0; acpi_dev && i < numdevs; i++) {
+	pcib = device_get_parent(dev);
+	for (i = 0; pci_do_power_resume && i < numdevs; i++) {
 		child = devlist[i];
 		dinfo = (struct pci_devinfo *) device_get_ivars(child);
+		dstate = PCI_POWERSTATE_D3;
 		if (device_is_attached(child) &&
 		    (dinfo->cfg.hdrtype & PCIM_HDRTYPE) ==
-		    PCIM_HDRTYPE_NORMAL) {
-			dstate = PCI_POWERSTATE_D3;
-			ACPI_PWR_FOR_SLEEP(acpi_dev, child, &dstate);
+		    PCIM_HDRTYPE_NORMAL &&
+		    PCIB_POWER_FOR_SLEEP(pcib, dev, &dstate) == 0)
 			pci_set_powerstate(child, dstate);
-		}
 	}
 	free(devlist, M_TEMP);
 	return (0);
@@ -2965,31 +2956,29 @@ int
 pci_resume(device_t dev)
 {
 	int i, numdevs, error;
-	device_t acpi_dev, child, *devlist;
+	device_t child, *devlist, pcib;
 	struct pci_devinfo *dinfo;
 
 	/*
 	 * Set each child to D0 and restore its PCI configuration space.
 	 */
-	acpi_dev = NULL;
-	if (pci_do_power_resume)
-		acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
 	if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
 		return (error);
+	pcib = device_get_parent(dev);
 	for (i = 0; i < numdevs; i++) {
 		/*
-		 * Notify ACPI we're going to D0 but ignore the result.  If
-		 * ACPI is not present, the firmware is responsible for
-		 * managing device power.  Only manage type 0 devices for now.
+		 * Notify power managment we're going to D0 but ignore
+		 * the result.  If power management is not present,
+		 * the firmware is responsible for managing device
+		 * power.  Only manage type 0 devices for now.
 		 */
 		child = devlist[i];
 		dinfo = (struct pci_devinfo *) device_get_ivars(child);
-		if (acpi_dev && device_is_attached(child) &&
+		if (device_is_attached(child) &&
 		    (dinfo->cfg.hdrtype & PCIM_HDRTYPE) ==
-		    PCIM_HDRTYPE_NORMAL) {
-			ACPI_PWR_FOR_SLEEP(acpi_dev, child, NULL);
+		    PCIM_HDRTYPE_NORMAL &&
+		    PCIB_POWER_FOR_SLEEP(pcib, dev, NULL) == 0)
 			pci_set_powerstate(child, PCI_POWERSTATE_D0);
-		}
 
 		/* Now the device is powered up, restore its config space. */
 		pci_cfg_restore(child, dinfo);
diff --git a/sys/dev/pci/pci_pci.c b/sys/dev/pci/pci_pci.c
index 996d2745527..9992b8119df 100644
--- a/sys/dev/pci/pci_pci.c
+++ b/sys/dev/pci/pci_pci.c
@@ -48,22 +48,16 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #include 
+#include 
 #include 
 
 #include "pcib_if.h"
 
-#ifdef __HAVE_ACPI
-#include 
-#include "acpi_if.h"
-#else
-#define	ACPI_PWR_FOR_SLEEP(x, y, z)
-#endif
-
-extern int		pci_do_power_resume;
-
 static int		pcib_probe(device_t dev);
 static int		pcib_suspend(device_t dev);
 static int		pcib_resume(device_t dev);
+static int		pcib_power_for_sleep(device_t pcib, device_t dev,
+			    int *pstate);
 
 static device_method_t pcib_methods[] = {
     /* Device interface */
@@ -95,6 +89,7 @@ static device_method_t pcib_methods[] = {
     DEVMETHOD(pcib_alloc_msix,		pcib_alloc_msix),
     DEVMETHOD(pcib_release_msix,	pcib_release_msix),
     DEVMETHOD(pcib_map_msi,		pcib_map_msi),
+    DEVMETHOD(pcib_power_for_sleep,	pcib_power_for_sleep),
 
     { 0, 0 }
 };
@@ -447,18 +442,16 @@ pcib_attach(device_t dev)
 int
 pcib_suspend(device_t dev)
 {
-	device_t	acpi_dev;
+	device_t	pcib;
 	int		dstate, error;
 
 	pcib_cfg_save(device_get_softc(dev));
 	error = bus_generic_suspend(dev);
 	if (error == 0 && pci_do_power_resume) {
-		acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
-		if (acpi_dev != NULL) {
-			dstate = PCI_POWERSTATE_D3;
-			ACPI_PWR_FOR_SLEEP(acpi_dev, dev, &dstate);
+		dstate = PCI_POWERSTATE_D3;
+		pcib = device_get_parent(device_get_parent(dev));
+		if (PCIB_POWER_FOR_SLEEP(pcib, dev, &dstate) == 0)
 			pci_set_powerstate(dev, dstate);
-		}
 	}
 	return (error);
 }
@@ -466,14 +459,12 @@ pcib_suspend(device_t dev)
 int
 pcib_resume(device_t dev)
 {
-	device_t	acpi_dev;
+	device_t	pcib;
 
 	if (pci_do_power_resume) {
-		acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
-		if (acpi_dev != NULL) {
-			ACPI_PWR_FOR_SLEEP(acpi_dev, dev, NULL);
+		pcib = device_get_parent(device_get_parent(dev));
+		if (PCIB_POWER_FOR_SLEEP(pcib, dev, NULL) == 0)
 			pci_set_powerstate(dev, PCI_POWERSTATE_D0);
-		}
 	}
 	pcib_cfg_restore(device_get_softc(dev));
 	return (bus_generic_resume(dev));
@@ -790,6 +781,16 @@ pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
 	return (0);
 }
 
+/* Pass request for device power state up to parent bridge. */
+int
+pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
+{
+	device_t bus;
+
+	bus = device_get_parent(pcib);
+	return (PCIB_POWER_FOR_SLEEP(bus, dev, pstate));
+}
+
 /*
  * Try to read the bus number of a host-PCI bridge using appropriate config
  * registers.
diff --git a/sys/dev/pci/pci_private.h b/sys/dev/pci/pci_private.h
index 2240b4f2c0d..70d887b3232 100644
--- a/sys/dev/pci/pci_private.h
+++ b/sys/dev/pci/pci_private.h
@@ -38,6 +38,8 @@
  */
 DECLARE_CLASS(pci_driver);
 
+extern int 	pci_do_power_resume;
+
 void		pci_add_children(device_t dev, int domain, int busno,
 		    size_t dinfo_size);
 void		pci_add_child(device_t bus, struct pci_devinfo *dinfo);
diff --git a/sys/dev/pci/pcib_if.m b/sys/dev/pci/pcib_if.m
index 0b7e8bc62c9..b946c0f0541 100644
--- a/sys/dev/pci/pcib_if.m
+++ b/sys/dev/pci/pcib_if.m
@@ -144,3 +144,13 @@ METHOD int map_msi {
 	uint64_t	*addr;
 	uint32_t	*data;
 };
+
+#
+# Return the device power state to be used during a system sleep state
+# transition such as suspend and resume.
+#
+METHOD int power_for_sleep {
+	device_t	pcib;
+	device_t	dev;
+	int		*pstate;
+};

From a122fea4ff5aef851b20383d0d5776c38e2422ff Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Tue, 17 Aug 2010 16:27:13 +0000
Subject: [PATCH 0043/1624] Add s25sl064a, an 8mb SPI flash part.

---
 sys/dev/flash/mx25l.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/dev/flash/mx25l.c b/sys/dev/flash/mx25l.c
index 98b3bb37980..71e2eb04ab0 100644
--- a/sys/dev/flash/mx25l.c
+++ b/sys/dev/flash/mx25l.c
@@ -93,6 +93,7 @@ struct mx25l_flash_ident flash_devices[] = {
 	{ "mx25ll64",  0xc2, 0x2017, 64 * 1024, 128, FL_NONE },
 	{ "mx25ll128", 0xc2, 0x2018, 64 * 1024, 256, FL_ERASE_4K | FL_ERASE_32K },
 	{ "s25fl128",  0x01, 0x2018, 64 * 1024, 256, FL_NONE },
+	{ "s25sl064a", 0x01, 0x0216, 64 * 1024, 128, FL_NONE },
 };
 
 static uint8_t

From c007b96a78972be20a2f1970e4a6f283b0e434b7 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Tue, 17 Aug 2010 16:41:16 +0000
Subject: [PATCH 0044/1624] Ensure a minimum "slop" of 10 extra pcb structures
 when providing a memory size estimate to userland for pcb list sysctls.  The
 previous behavior of a "slop" of n/8 does not work well for small values of n
 (e.g. no slop at all if you have less than 8 open UDP connections).

Reviewed by:	bz
MFC after:	1 week
---
 sys/netinet/ip_divert.c  | 4 ++--
 sys/netinet/raw_ip.c     | 4 ++--
 sys/netinet/tcp_subr.c   | 5 +++--
 sys/netinet/udp_usrreq.c | 4 ++--
 4 files changed, 9 insertions(+), 8 deletions(-)

diff --git a/sys/netinet/ip_divert.c b/sys/netinet/ip_divert.c
index acee34112a2..0837d2e2529 100644
--- a/sys/netinet/ip_divert.c
+++ b/sys/netinet/ip_divert.c
@@ -592,8 +592,8 @@ div_pcblist(SYSCTL_HANDLER_ARGS)
 	 */
 	if (req->oldptr == 0) {
 		n = V_divcbinfo.ipi_count;
-		req->oldidx = 2 * (sizeof xig)
-			+ (n + n/8) * sizeof(struct xinpcb);
+		n += imax(n / 8, 10);
+		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
 		return 0;
 	}
 
diff --git a/sys/netinet/raw_ip.c b/sys/netinet/raw_ip.c
index 0b77b5b8496..d6b426c9a48 100644
--- a/sys/netinet/raw_ip.c
+++ b/sys/netinet/raw_ip.c
@@ -993,8 +993,8 @@ rip_pcblist(SYSCTL_HANDLER_ARGS)
 	 */
 	if (req->oldptr == 0) {
 		n = V_ripcbinfo.ipi_count;
-		req->oldidx = 2 * (sizeof xig)
-		    + (n + n/8) * sizeof(struct xinpcb);
+		n += imax(n / 8, 10);
+		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
 		return (0);
 	}
 
diff --git a/sys/netinet/tcp_subr.c b/sys/netinet/tcp_subr.c
index da478b3116b..bfa3e663f00 100644
--- a/sys/netinet/tcp_subr.c
+++ b/sys/netinet/tcp_subr.c
@@ -1022,8 +1022,9 @@ tcp_pcblist(SYSCTL_HANDLER_ARGS)
 	if (req->oldptr == NULL) {
 		m = syncache_pcbcount();
 		n = V_tcbinfo.ipi_count;
-		req->oldidx = 2 * (sizeof xig)
-			+ ((m + n) + n/8) * sizeof(struct xtcpcb);
+		n += imax(n / 8, 10);
+		req->oldidx = 2 * (sizeof xig) +
+		    (m + n) * sizeof(struct xtcpcb);
 		return (0);
 	}
 
diff --git a/sys/netinet/udp_usrreq.c b/sys/netinet/udp_usrreq.c
index 45410387c17..adb11c4ea80 100644
--- a/sys/netinet/udp_usrreq.c
+++ b/sys/netinet/udp_usrreq.c
@@ -707,8 +707,8 @@ udp_pcblist(SYSCTL_HANDLER_ARGS)
 	 */
 	if (req->oldptr == 0) {
 		n = V_udbinfo.ipi_count;
-		req->oldidx = 2 * (sizeof xig)
-			+ (n + n/8) * sizeof(struct xinpcb);
+		n += imax(n / 8, 10);
+		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
 		return (0);
 	}
 

From c9c87edbc3c0dbc2964c6c77ecfa9c52f639542f Mon Sep 17 00:00:00 2001
From: Matt Jacob 
Date: Tue, 17 Aug 2010 17:11:15 +0000
Subject: [PATCH 0045/1624] Now is as good a time as any to find out if we
 induce breakage by issueing aborts for any pending commands when we're
 decommssioning a disk.

MFC after:	3 months
---
 sys/cam/scsi/scsi_da.c | 20 ++++++++++++++++++--
 1 file changed, 18 insertions(+), 2 deletions(-)

diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c
index 8f643611c0c..0bf175adc82 100644
--- a/sys/cam/scsi/scsi_da.c
+++ b/sys/cam/scsi/scsi_da.c
@@ -958,6 +958,8 @@ dainit(void)
 static void
 daoninvalidate(struct cam_periph *periph)
 {
+	struct ccb_abort cab;
+	struct ccb_hdr *ccb_h, *ccb_h_t;
 	struct da_softc *softc;
 
 	softc = (struct da_softc *)periph->softc;
@@ -967,15 +969,29 @@ daoninvalidate(struct cam_periph *periph)
 	 */
 	xpt_register_async(0, daasync, periph, periph->path);
 
+	/*
+	 * Invalidate the pack label
+	 */
 	softc->flags |= DA_FLAG_PACK_INVALID;
 
 	/*
 	 * Return all queued I/O with ENXIO.
-	 * XXX Handle any transactions queued to the card
-	 *     with XPT_ABORT_CCB.
 	 */
 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
 
+	/*
+	 * Issue aborts for any pending commands.
+	 */
+	xpt_setup_ccb(&cab.ccb_h, periph->path, CAM_PRIORITY_NORMAL+1);
+	cab.ccb_h.func_code = XPT_ABORT;
+	LIST_FOREACH_SAFE(ccb_h, &softc->pending_ccbs, periph_links.le, ccb_h_t) {
+		cab.abort_ccb = (union ccb *)ccb_h;
+		xpt_action((union ccb *)&cab);
+	}
+
+	/*
+	 * This disk is *history*....
+	 */
 	disk_gone(softc->disk);
 	xpt_print(periph->path, "lost device\n");
 }

From 388288b2025af5c70ba53c91fd863981d7895112 Mon Sep 17 00:00:00 2001
From: Hajimu UMEMOTO 
Date: Tue, 17 Aug 2010 17:30:56 +0000
Subject: [PATCH 0046/1624] Make `ping6 -I' work with
 net.inet6.ip6.use_defaultzone=1.

MFC after:	2 weeks
---
 sys/netinet6/raw_ip6.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/sys/netinet6/raw_ip6.c b/sys/netinet6/raw_ip6.c
index 0e18fb4a830..936536087f6 100644
--- a/sys/netinet6/raw_ip6.c
+++ b/sys/netinet6/raw_ip6.c
@@ -401,6 +401,7 @@ rip6_output(m, va_alist)
 	struct ifnet *oifp = NULL;
 	int type = 0, code = 0;		/* for ICMPv6 output statistics only */
 	int scope_ambiguous = 0;
+	int use_defzone = 0;
 	struct in6_addr in6a;
 	va_list ap;
 
@@ -430,9 +431,11 @@ rip6_output(m, va_alist)
 	 * XXX: we may still need to determine the zone later.
 	 */
 	if (!(so->so_state & SS_ISCONNECTED)) {
-		if (dstsock->sin6_scope_id == 0 && !V_ip6_use_defzone)
+		if (!optp->ip6po_pktinfo || !optp->ip6po_pktinfo->ipi6_ifindex)
+			use_defzone = V_ip6_use_defzone;
+		if (dstsock->sin6_scope_id == 0 && !use_defzone)
 			scope_ambiguous = 1;
-		if ((error = sa6_embedscope(dstsock, V_ip6_use_defzone)) != 0)
+		if ((error = sa6_embedscope(dstsock, use_defzone)) != 0)
 			goto bad;
 	}
 

From d350d2cd949d44824a1280207cdb40d9205f1edc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Tue, 17 Aug 2010 20:26:17 +0000
Subject: [PATCH 0047/1624] Split kernel stage 3.2 (build everything) into 3.2
 (build the kernel) and 3.3 (build the modules).  IMHO, this makes it a little
 easier to track the progress of a kernel build using whereintheworld et al.

MFC after:	3 weeks
---
 Makefile.inc1 | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index d2581c573ec..8263be03579 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -814,9 +814,16 @@ buildkernel:
 .endif
 	@echo
 	@echo "--------------------------------------------------------------"
-	@echo ">>> stage 3.2: building everything"
+	@echo ">>> stage 3.2: building the kernel"
 	@echo "--------------------------------------------------------------"
-	cd ${KRNLOBJDIR}/${_kernel}; ${KMAKE} all -DNO_MODULES_OBJ
+	cd ${KRNLOBJDIR}/${_kernel}; ${KMAKE} kernel-all -DNO_MODULES_OBJ
+	@echo
+.if !defined(MODULES_WITH_WORLD) && !defined(NO_MODULES) && exists(${KERNSRCDIR}/modules)
+	@echo "--------------------------------------------------------------"
+	@echo ">>> stage 3.3: building the modules"
+	@echo "--------------------------------------------------------------"
+	cd ${KRNLOBJDIR}/${_kernel}; ${KMAKE} modules-all -DNO_MODULES_OBJ
+.endif
 	@echo "--------------------------------------------------------------"
 	@echo ">>> Kernel build for ${_kernel} completed on `LC_ALL=C date`"
 	@echo "--------------------------------------------------------------"

From 187278cadc31ff1d26eeb0205f808f54ddc23963 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 17 Aug 2010 20:39:28 +0000
Subject: [PATCH 0048/1624] For every instance of '.if ${CC} == "foo"' or '.if
 ${CC} != "foo"' in Makefiles or *.mk files, use ${CC:T:Mfoo} instead, so only
 the basename of the compiler command (excluding any arguments) is considered.

This allows you to use, for example, CC="/nondefault/path/clang -xxx",
and still have the various tests in bsd.*.mk identify your compiler as
clang correctly.

ICC if cases were also changed.

Submitted by:	Dimitry Andric 
---
 share/mk/bsd.dep.mk             |  2 +-
 share/mk/bsd.lib.mk             |  2 +-
 share/mk/bsd.sys.mk             |  6 +++---
 sys/conf/kern.mk                | 12 ++++++------
 sys/conf/kern.pre.mk            | 10 +++++-----
 sys/conf/kmod.mk                |  8 ++++----
 sys/dev/aic7xxx/aicasm/Makefile |  2 +-
 sys/i386/acpica/Makefile        |  2 +-
 8 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/share/mk/bsd.dep.mk b/share/mk/bsd.dep.mk
index a683a097d8e..7921ea74662 100644
--- a/share/mk/bsd.dep.mk
+++ b/share/mk/bsd.dep.mk
@@ -125,7 +125,7 @@ depend: beforedepend ${DEPENDFILE} afterdepend
 
 # Different types of sources are compiled with slightly different flags.
 # Split up the sources, and filter out headers and non-applicable flags.
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 MKDEP_CFLAGS=	${CFLAGS:M-X*} ${CFLAGS:M-[BIDU]*}
 MKDEP_CXXFLAGS=	${CXXFLAGS:M-X*} ${CXXFLAGS:M-[BIDU]*}
 MKDEP_OBJCFLAGS=${OBJCFLAGS:M-X*} ${OBJCFLAGS:M-[BIDU]*}
diff --git a/share/mk/bsd.lib.mk b/share/mk/bsd.lib.mk
index 80c4264978e..94d918b4879 100644
--- a/share/mk/bsd.lib.mk
+++ b/share/mk/bsd.lib.mk
@@ -65,7 +65,7 @@ PICFLAG=-fpic
 .endif
 .endif
 
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 PO_FLAG=-p
 .else
 PO_FLAG=-pg
diff --git a/share/mk/bsd.sys.mk b/share/mk/bsd.sys.mk
index 97860f2bd85..3559a267f2b 100644
--- a/share/mk/bsd.sys.mk
+++ b/share/mk/bsd.sys.mk
@@ -11,7 +11,7 @@
 # the default is gnu99 for now
 CSTD		?= gnu99
 
-.if ${CC} != "icc"
+.if ${CC:T:Micc} != "icc"
 . if ${CSTD} == "k&r"
 CFLAGS		+= -traditional
 . elif ${CSTD} == "c89" || ${CSTD} == "c90"
@@ -24,7 +24,7 @@ CFLAGS		+= -std=iso9899:1999
 CFLAGS		+= -std=${CSTD}
 . endif
 .endif
-.if !defined(NO_WARNS) && ${CC} != "icc"
+.if !defined(NO_WARNS) && ${CC:T:Micc} != "icc"
 # -pedantic is problematic because it also imposes namespace restrictions
 #CFLAGS		+= -pedantic
 . if defined(WARNS)
@@ -79,7 +79,7 @@ CWARNFLAGS	+=	-Werror
 CWARNFLAGS	+=	-Wno-unknown-pragmas
 .endif
 
-.if ${MK_SSP} != "no" && ${CC} != "icc" && ${MACHINE_ARCH} != "ia64" && \
+.if ${MK_SSP} != "no" && ${CC:T:Micc} != "icc" && ${MACHINE_ARCH} != "ia64" && \
 	${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
 # Don't use -Wstack-protector as it breaks world with -Werror.
 SSP_CFLAGS	?=	-fstack-protector
diff --git a/sys/conf/kern.mk b/sys/conf/kern.mk
index 5676057d3d4..32b71689a4f 100644
--- a/sys/conf/kern.mk
+++ b/sys/conf/kern.mk
@@ -6,7 +6,7 @@
 # Note that the newly added -Wcast-qual is responsible for generating 
 # most of the remaining warnings.  Warnings introduced with -Wall will
 # also pop up, but are easier to fix.
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 #CWARNFLAGS=	-w2	# use this if you are terribly bored
 CWARNFLAGS=
 .else
@@ -29,8 +29,8 @@ CWARNFLAGS?=	-Wall -Wredundant-decls -Wnested-externs -Wstrict-prototypes \
 # operations inside the kernel itself.  These operations are exclusively
 # reserved for user applications.
 #
-.if ${MACHINE_ARCH} == "i386" && ${CC} != "icc"
-.if ${CC} != "clang"
+.if ${MACHINE_ARCH} == "i386" && ${CC:T:Micc} != "icc"
+.if ${CC:T:Mclang} != "clang"
 CFLAGS+=	-mno-align-long-strings -mpreferred-stack-boundary=2
 .endif
 CFLAGS+=	-mno-mmx -mno-3dnow -mno-sse -mno-sse2 -mno-sse3
@@ -93,20 +93,20 @@ INLINE_LIMIT?=	8000
 # GCC 3.0 and above like to do certain optimizations based on the
 # assumption that the program is linked against libc.  Stop this.
 #
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 CFLAGS+=	-nolib_inline
 .else
 CFLAGS+=	-ffreestanding
 .endif
 
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 CFLAGS+=	-restrict
 .endif
 
 #
 # GCC SSP support.
 #
-.if ${MK_SSP} != "no" && ${CC} != "icc" && ${MACHINE_ARCH} != "ia64" && \
+.if ${MK_SSP} != "no" && ${CC:T:Micc} != "icc" && ${MACHINE_ARCH} != "ia64" && \
 	${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
 CFLAGS+=	-fstack-protector
 .endif
diff --git a/sys/conf/kern.pre.mk b/sys/conf/kern.pre.mk
index 7642fca5258..b61113e7e50 100644
--- a/sys/conf/kern.pre.mk
+++ b/sys/conf/kern.pre.mk
@@ -23,7 +23,7 @@ NM?=		nm
 OBJCOPY?=	objcopy
 SIZE?=		size
 
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 COPTFLAGS?=	-O
 .else
 . if defined(DEBUG)
@@ -48,7 +48,7 @@ COPTFLAGS+= ${_ICC_CPUCFLAGS:C/(-x[^M^K^W]+)[MKW]+|-x[MKW]+/\1/}
 COPTFLAGS+= ${_CPUCFLAGS}
 . endif
 .endif
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 C_DIALECT=
 NOSTDINC= -X
 .else
@@ -92,8 +92,8 @@ INCLUDES+= -I$S/dev/cxgb
 
 CFLAGS=	${COPTFLAGS} ${C_DIALECT} ${DEBUG} ${CWARNFLAGS}
 CFLAGS+= ${INCLUDES} -D_KERNEL -DHAVE_KERNEL_OPTION_HEADERS -include opt_global.h
-.if ${CC} != "icc"
-.if ${CC} != "clang"
+.if ${CC:T:Micc} != "icc"
+.if ${CC:T:Mclang} != "clang"
 CFLAGS+= -fno-common -finline-limit=${INLINE_LIMIT}
 .if ${MACHINE_CPUARCH} != "mips"
 CFLAGS+= --param inline-unit-growth=100
@@ -111,7 +111,7 @@ WERROR?= -Werror
 ASM_CFLAGS= -x assembler-with-cpp -DLOCORE ${CFLAGS}
 
 .if defined(PROFLEVEL) && ${PROFLEVEL} >= 1
-.if ${CC} == "icc" || ${CC} == "clang"
+.if ${CC:T:Micc} == "icc" || ${CC:T:Mclang} == "clang"
 .error "Profiling doesn't work with icc or clang yet"
 .endif
 CFLAGS+=	-DGPROF -falign-functions=16
diff --git a/sys/conf/kmod.mk b/sys/conf/kmod.mk
index 76425206171..63f47486ec3 100644
--- a/sys/conf/kmod.mk
+++ b/sys/conf/kmod.mk
@@ -81,7 +81,7 @@ OBJCOPY?=	objcopy
 
 .SUFFIXES: .out .o .c .cc .cxx .C .y .l .s .S
 
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 CFLAGS:=	${CFLAGS:C/(-x[^M^K^W]+)[MKW]+|-x[MKW]+/\1/}
 .else
 . if !empty(CFLAGS:M-O[23s]) && empty(CFLAGS:M-fno-strict-aliasing)
@@ -94,7 +94,7 @@ CFLAGS+=	-D_KERNEL
 CFLAGS+=	-DKLD_MODULE
 
 # Don't use any standard or source-relative include directories.
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 NOSTDINC=	-X
 .else
 CSTD=		c99
@@ -114,7 +114,7 @@ CFLAGS+=	-I. -I@
 # for example.
 CFLAGS+=	-I@/contrib/altq
 
-.if ${CC} != "icc" && ${CC} != "clang"
+.if ${CC:T:Micc} != "icc" && ${CC:T:Mclang} != "clang"
 CFLAGS+=	-finline-limit=${INLINE_LIMIT}
 CFLAGS+= --param inline-unit-growth=100
 CFLAGS+= --param large-function-growth=1000
@@ -122,7 +122,7 @@ CFLAGS+= --param large-function-growth=1000
 
 # Disallow common variables, and if we end up with commons from
 # somewhere unexpected, allocate storage for them in the module itself.
-.if ${CC} != "icc"
+.if ${CC:T:Micc} != "icc"
 CFLAGS+=	-fno-common
 .endif
 LDFLAGS+=	-d -warn-common
diff --git a/sys/dev/aic7xxx/aicasm/Makefile b/sys/dev/aic7xxx/aicasm/Makefile
index 9c7349390f0..c07728544ad 100644
--- a/sys/dev/aic7xxx/aicasm/Makefile
+++ b/sys/dev/aic7xxx/aicasm/Makefile
@@ -24,7 +24,7 @@ WARNS?=	5
 DEPENDFILE=	.depend_aicasm
 .endif
 
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 CFLAGS+=	-restrict
 NOSTDINC=	-X
 .else
diff --git a/sys/i386/acpica/Makefile b/sys/i386/acpica/Makefile
index 48d65eaa1aa..87061d67247 100644
--- a/sys/i386/acpica/Makefile
+++ b/sys/i386/acpica/Makefile
@@ -9,7 +9,7 @@ DEPENDFILE=
 MAKESRCPATH= ${.CURDIR}
 CLEANFILES= acpi_wakecode.h acpi_wakecode.bin acpi_wakecode.o
 .endif
-.if ${CC} == "icc"
+.if ${CC:T:Micc} == "icc"
 CFLAGS+=	-restrict
 NOSTDINC=	-X
 .else

From fe41d17ab2e31acf7e76ba2f70bf247e51c27d9d Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Tue, 17 Aug 2010 21:34:19 +0000
Subject: [PATCH 0049/1624] Keep the process locked when calling ktrops() or
 ktrsetchildren() instead of dropping the lock only to immediately reacquire
 it.

---
 sys/kern/kern_ktrace.c | 25 +++++++++++++------------
 1 file changed, 13 insertions(+), 12 deletions(-)

diff --git a/sys/kern/kern_ktrace.c b/sys/kern/kern_ktrace.c
index d5eb4e1cb5a..26584379f5e 100644
--- a/sys/kern/kern_ktrace.c
+++ b/sys/kern/kern_ktrace.c
@@ -741,7 +741,6 @@ ktrace(td, uap)
 				PROC_UNLOCK(p); 
 				continue;
 			}
-			PROC_UNLOCK(p); 
 			nfound++;
 			if (descend)
 				ret |= ktrsetchildren(td, p, ops, facs, vp);
@@ -758,18 +757,13 @@ ktrace(td, uap)
 		 * by pid
 		 */
 		p = pfind(uap->pid);
-		if (p == NULL) {
-			sx_sunlock(&proctree_lock);
+		if (p == NULL)
 			error = ESRCH;
-			goto done;
-		}
-		error = p_cansee(td, p);
-		/*
-		 * The slock of the proctree lock will keep this process
-		 * from going away, so unlocking the proc here is ok.
-		 */
-		PROC_UNLOCK(p);
+		else
+			error = p_cansee(td, p);
 		if (error) {
+			if (p != NULL)
+				PROC_UNLOCK(p);
 			sx_sunlock(&proctree_lock);
 			goto done;
 		}
@@ -841,11 +835,16 @@ ktrops(td, p, ops, facs, vp)
 	struct vnode *tracevp = NULL;
 	struct ucred *tracecred = NULL;
 
-	PROC_LOCK(p);
+	PROC_LOCK_ASSERT(p, MA_OWNED);
 	if (!ktrcanset(td, p)) {
 		PROC_UNLOCK(p);
 		return (0);
 	}
+	if (p->p_flag & P_WEXIT) {
+		/* If the process is exiting, just ignore it. */
+		PROC_UNLOCK(p);
+		return (1);
+	}
 	mtx_lock(&ktrace_mtx);
 	if (ops == KTROP_SET) {
 		if (p->p_tracevp != vp) {
@@ -900,6 +899,7 @@ ktrsetchildren(td, top, ops, facs, vp)
 	register int ret = 0;
 
 	p = top;
+	PROC_LOCK_ASSERT(p, MA_OWNED);
 	sx_assert(&proctree_lock, SX_LOCKED);
 	for (;;) {
 		ret |= ktrops(td, p, ops, facs, vp);
@@ -919,6 +919,7 @@ ktrsetchildren(td, top, ops, facs, vp)
 			}
 			p = p->p_pptr;
 		}
+		PROC_LOCK(p);
 	}
 	/*NOTREACHED*/
 }

From 7f8184068f93eede5ba3d83107c04e3a8b34659c Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Wed, 18 Aug 2010 00:26:14 +0000
Subject: [PATCH 0050/1624] Import initial AR91XX and AR724X CPU register
 definitions.

Obtained from:	Linux
---
 sys/mips/atheros/ar724xreg.h | 81 +++++++++++++++++++++++++++++++++++
 sys/mips/atheros/ar91xxreg.h | 83 ++++++++++++++++++++++++++++++++++++
 2 files changed, 164 insertions(+)
 create mode 100644 sys/mips/atheros/ar724xreg.h
 create mode 100644 sys/mips/atheros/ar91xxreg.h

diff --git a/sys/mips/atheros/ar724xreg.h b/sys/mips/atheros/ar724xreg.h
new file mode 100644
index 00000000000..53faa78294b
--- /dev/null
+++ b/sys/mips/atheros/ar724xreg.h
@@ -0,0 +1,81 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR72XX_REG_H__
+#define	__AR72XX_REG_H__
+
+#define	AR724X_PLL_REG_CPU_CONFIG	AR71XX_PLL_CPU_BASE + 0x00
+#define	AR724X_PLL_REG_PCIE_CONFIG	AR71XX_PLL_CPU_BASE + 0x18
+
+#define	AR724X_PLL_DIV_SHIFT		0
+#define	AR724X_PLL_DIV_MASK		0x3ff
+#define	AR724X_PLL_REF_DIV_SHIFT	10
+#define	AR724X_PLL_REF_DIV_MASK		0xf
+#define	AR724X_AHB_DIV_SHIFT		19
+#define	AR724X_AHB_DIV_MASK		0x1
+#define	AR724X_DDR_DIV_SHIFT		22
+#define	AR724X_DDR_DIV_MASK		0x3
+
+#define	AR724X_PLL_VAL_1000		0x00110000
+#define	AR724X_PLL_VAL_100		0x00001099
+#define	AR724X_PLL_VAL_10		0x00991099
+
+#define	AR724X_BASE_FREQ		5000000
+
+/* XXX so USB requires different init code? -adrian */
+#define	AR7240_OHCI_BASE		0x1b000000
+#define	AR7240_OHCI_SIZE		0x01000000
+#define	AR724X_DDR_REG_FLUSH_USB	(AR71XX_DDR_CONFIG + 0x84)
+
+#define	AR724X_PCI_CRP_BASE		(AR71XX_APB_BASE + 0x000C0000)
+#define	AR724X_PCI_CRP_SIZE		0x100
+
+#define	AR724X_PCI_CTRL_BASE		(AR71XX_APB_BASE + 0x000F0000)
+#define	AR724X_PCI_CTRL_SIZE		0x100
+
+#define	AR724X_GPIO_FUNC_GE0_MII_CLK_EN		(1 >> 19)
+#define	AR724X_GPIO_FUNC_SPI_EN			(1 >> 18)
+#define	AR724X_GPIO_FUNC_SPI_CS_EN2		(1 >> 14)
+#define	AR724X_GPIO_FUNC_SPI_CS_EN1		(1 >> 13)
+#define	AR724X_GPIO_FUNC_CLK_OBS5_EN		(1 >> 12)
+#define	AR724X_GPIO_FUNC_CLK_OBS4_EN		(1 >> 11)
+#define	AR724X_GPIO_FUNC_CLK_OBS3_EN		(1 >> 10)
+#define	AR724X_GPIO_FUNC_CLK_OBS2_EN		(1 >> 9)
+#define	AR724X_GPIO_FUNC_CLK_OBS1_EN		(1 >> 8)
+#define	AR724X_GPIO_FUNC_ETH_SWITCH_LED4_EN	(1 >> 7)
+#define	AR724X_GPIO_FUNC_ETH_SWITCH_LED3_EN	(1 >> 6)
+#define	AR724X_GPIO_FUNC_ETH_SWITCH_LED2_EN	(1 >> 5)
+#define	AR724X_GPIO_FUNC_ETH_SWITCH_LED1_EN	(1 >> 4)
+#define	AR724X_GPIO_FUNC_ETH_SWITCH_LED0_EN	(1 >> 3)
+#define	AR724X_GPIO_FUNC_UART_RTS_CTS_EN	(1 >> 2)
+#define	AR724X_GPIO_FUNC_UART_EN		(1 >> 1)
+#define	AR724X_GPIO_FUNC_JTAG_DISABLE		(1 >> 0)
+
+#define	AR724X_GPIO_COUNT		18
+
+#endif
diff --git a/sys/mips/atheros/ar91xxreg.h b/sys/mips/atheros/ar91xxreg.h
new file mode 100644
index 00000000000..35319f12453
--- /dev/null
+++ b/sys/mips/atheros/ar91xxreg.h
@@ -0,0 +1,83 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR91XX_REG_H__
+#define	__AR91XX_REG_H__
+
+#define	AR91XX_BASE_FREQ		5000000
+
+/* reset block */
+#define	AR91XX_RESET_REG_RESET_MODULE	AR71XX_RST_BLOCK_BASE + 0x1c
+
+/* PLL block */
+#define	AR91XX_PLL_REG_CPU_CONFIG       AR71XX_PLL_CPU_BASE + 0x00
+#define	AR91XX_PLL_REG_ETH_CONFIG       AR71XX_PLL_CPU_BASE + 0x04
+#define	AR91XX_PLL_REG_ETH0_INT_CLOCK   AR71XX_PLL_CPU_BASE + 0x14
+#define	AR91XX_PLL_REG_ETH1_INT_CLOCK   AR71XX_PLL_CPU_BASE + 0x18
+
+#define	AR91XX_PLL_DIV_SHIFT		0
+#define	AR91XX_PLL_DIV_MASK		0x3ff
+#define	AR91XX_DDR_DIV_SHIFT		22
+#define	AR91XX_DDR_DIV_MASK		0x3
+#define	AR91XX_AHB_DIV_SHIFT		19
+#define	AR91XX_AHB_DIV_MASK		0x1
+
+#define	AR91XX_ETH0_PLL_SHIFT		20
+#define	AR91XX_ETH1_PLL_SHIFT		22
+
+#define	AR91XX_PLL_VAL_1000		0x1a000000
+#define	AR91XX_PLL_VAL_100		0x13000a44
+#define	AR91XX_PLL_VAL_10		0x00441099
+
+/* DDR block */
+#define	AR91XX_DDR_CTRLBASE		(AR71XX_APB_BASE + 0)
+#define	AR91XX_DDR_CTRL_SIZE		0x10000
+#define	AR91XX_DDR_REG_FLUSH_GE0	AR91XX_DDR_CTRLBASE + 0x7c
+#define	AR91XX_DDR_REG_FLUSH_GE1	AR91XX_DDR_CTRLBASE + 0x80
+#define	AR91XX_DDR_REG_FLUSH_USB	AR91XX_DDR_CTRLBASE + 0x84
+#define	AR91XX_DDR_REG_FLUSH_WMAC	AR91XX_DDR_CTRLBASE + 0x88
+
+/* WMAC stuff */
+#define	AR91XX_WMAC_BASE		(AR71XX_APB_BASE + 0x000C0000)
+#define	AR91XX_WMAC_SIZE		0x30000
+
+/* GPIO stuff */
+#define	AR91XX_GPIO_FUNC_WMAC_LED_EN	(1 << 22)
+#define	AR91XX_GPIO_FUNC_EXP_PORT_CS_EN	(1 << 21)
+#define	AR91XX_GPIO_FUNC_I2S_REFCLKEN	(1 << 20)
+#define	AR91XX_GPIO_FUNC_I2S_MCKEN	(1 << 19)
+#define	AR91XX_GPIO_FUNC_I2S1_EN	(1 << 18)
+#define	AR91XX_GPIO_FUNC_I2S0_EN	(1 << 17)
+#define	AR91XX_GPIO_FUNC_SLIC_EN	(1 << 16)
+#define	AR91XX_GPIO_FUNC_UART_RTSCTS_EN	(1 << 9)
+#define	AR91XX_GPIO_FUNC_UART_EN	(1 << 8)
+#define	AR91XX_GPIO_FUNC_USB_CLK_EN	(1 << 4)
+
+#define	AR91XX_GPIO_COUNT		22
+
+#endif

From e792023fe1822e6136ebfe02891a938f7bc975c8 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 18 Aug 2010 07:38:13 +0000
Subject: [PATCH 0051/1624] Make return statements style(9) compliant in MIPS
 pmap.c

Reported by: neel

Reviewed by:	neel (earlier version)
---
 sys/mips/mips/pmap.c | 27 +++++++++++++++------------
 1 file changed, 15 insertions(+), 12 deletions(-)

diff --git a/sys/mips/mips/pmap.c b/sys/mips/mips/pmap.c
index de191f7c3d2..1b2d372e327 100644
--- a/sys/mips/mips/pmap.c
+++ b/sys/mips/mips/pmap.c
@@ -267,6 +267,7 @@ static struct local_sysmaps sysmap_lmem[MAXCPU];
 static __inline pd_entry_t *
 pmap_segmap(pmap_t pmap, vm_offset_t va)
 {
+
 	return (&pmap->pm_segtab[pmap_seg_index(va)]);
 }
 
@@ -295,13 +296,15 @@ pmap_pde(pmap_t pmap, vm_offset_t va)
 static __inline pd_entry_t *
 pmap_pdpe_to_pde(pd_entry_t *pdpe, vm_offset_t va)
 {
-	return pdpe;
+
+	return (pdpe);
 }
 
 static __inline 
 pd_entry_t *pmap_pde(pmap_t pmap, vm_offset_t va)
 {
-	return pmap_segmap(pmap, va);
+
+	return (pmap_segmap(pmap, va));
 }
 #endif
 
@@ -356,7 +359,7 @@ pmap_steal_memory(vm_size_t size)
 	}
 	va = MIPS_PHYS_TO_KSEG0(pa);
 	bzero((caddr_t)va, size);
-	return va;
+	return (va);
 }
 
 /*
@@ -750,7 +753,7 @@ pmap_extract(pmap_t pmap, vm_offset_t va)
 		retval = TLBLO_PTE_TO_PA(*pte) | (va & PAGE_MASK);
 	}
 	PMAP_UNLOCK(pmap);
-	return retval;
+	return (retval);
 }
 
 /*
@@ -1007,7 +1010,7 @@ pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
 			pmap->pm_ptphint = mpte;
 		}
 	}
-	return pmap_unwire_pte_hold(pmap, va, mpte);
+	return (pmap_unwire_pte_hold(pmap, va, mpte));
 }
 
 void
@@ -1561,7 +1564,7 @@ pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, vm_offset_t va)
 
 		pmap_remove_entry(pmap, m, va);
 	}
-	return pmap_unuse_pt(pmap, va, NULL);
+	return (pmap_unuse_pt(pmap, va, NULL));
 }
 
 /*
@@ -2609,10 +2612,10 @@ pmap_testbit(vm_page_t m, int bit)
 	boolean_t rv = FALSE;
 
 	if (m->flags & PG_FICTITIOUS)
-		return rv;
+		return (rv);
 
 	if (TAILQ_FIRST(&m->md.pv_list) == NULL)
-		return rv;
+		return (rv);
 
 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
@@ -2933,7 +2936,7 @@ pmap_mapdev(vm_offset_t pa, vm_size_t size)
 	 * pa > 0x20000000 we should make proper mapping * using pmap_kenter.
 	 */
 	if ((pa + size - 1) < MIPS_KSEG0_LARGEST_PHYS)
-		return (void *)MIPS_PHYS_TO_KSEG1(pa);
+		return ((void *)MIPS_PHYS_TO_KSEG1(pa));
 	else {
 		offset = pa & PAGE_MASK;
 		size = roundup(size + offset, PAGE_SIZE);
@@ -3239,11 +3242,11 @@ page_is_managed(vm_offset_t pa)
 
 		m = PHYS_TO_VM_PAGE(pa);
 		if (m == NULL)
-			return 0;
+			return (0);
 		if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0)
-			return 1;
+			return (1);
 	}
-	return 0;
+	return (0);
 }
 
 static int

From 4d843b15ca9ba9c6aaf2fe90d702dc0794f8914c Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Wed, 18 Aug 2010 08:22:09 +0000
Subject: [PATCH 0052/1624] Bring over the first cut of the Atheros-specific
 SoC operations.

Each of these SoCs have different devices, different hardware initialisation
methods and, quite likely, different quirks. These functions will abstract
out the SoC differences and keep these differences out of the drivers (eg
USB init, if_arge, etc.)
---
 sys/mips/atheros/ar71xx_cpudef.h | 108 +++++++++++++++++++++++++++++++
 1 file changed, 108 insertions(+)
 create mode 100644 sys/mips/atheros/ar71xx_cpudef.h

diff --git a/sys/mips/atheros/ar71xx_cpudef.h b/sys/mips/atheros/ar71xx_cpudef.h
new file mode 100644
index 00000000000..4a29c8f6dd9
--- /dev/null
+++ b/sys/mips/atheros/ar71xx_cpudef.h
@@ -0,0 +1,108 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR71XX_CPUDEF_H__
+#define	__AR71XX_CPUDEF_H__
+
+struct ar71xx_cpu_def {
+	void (* detect_mem_size) (void);
+	void (* detect_sys_frequency) (void);
+	void (* ar71xx_chip_device_stop) (uint32_t);
+	void (* ar71xx_chip_device_start) (uint32_t);
+	int (* ar71xx_chip_device_stopped) (uint32_t);
+	void (* ar71xx_chip_set_pll_ge0) (int);
+	void (* ar71xx_chip_set_pll_ge1) (int);
+	void (* ar71xx_chip_ddr_flush_ge0) (void);
+	void (* ar71xx_chip_ddr_flush_ge1) (void);
+	uint32_t (* ar71xx_chip_get_eth_pll) (unsigned int, int);
+
+	/*
+	 * From Linux - Handling this IRQ is a bit special.
+	 * AR71xx - AR71XX_DDR_REG_FLUSH_PCI
+	 * AR724x - AR724X_DDR_REG_FLUSH_PCIE
+	 * AR91xx - AR91XX_DDR_REG_FLUSH_WMAC
+	 *
+	 * These are set when STATUSF_IP2 is set in regiser c0.
+	 * This flush is done before the IRQ is handled to make
+	 * sure the driver correctly sees any memory updates.
+	 */
+	void (* ar71xx_chip_irq_flush_ip2) (void);
+	/*
+	 * The USB peripheral init code is subtly different for
+	 * each chip.
+	 */
+	void (* ar71xx_chip_init_usb_peripheral) (void);
+};
+
+extern struct ar71xx_cpu_def * ar71xx_cpu_ops;
+
+static inline void ar71xx_detect_sys_frequency(void)
+{
+	ar71xx_cpu_ops->detect_sys_frequency();
+}
+
+static inline void ar71xx_device_stop(uint32_t mask)
+{
+	ar71xx_cpu_ops->ar71xx_chip_device_stop(mask);
+}
+
+static inline void ar71xx_device_start(uint32_t mask)
+{
+	ar71xx_cpu_ops->ar71xx_chip_device_start(mask);
+}
+
+static inline int ar71xx_device_stopped(uint32_t mask)
+{
+	return ar71xx_cpu_ops->ar71xx_chip_device_stopped(mask);
+}
+
+static inline void ar71xx_device_flush_ddr_ge0(void)
+{
+	ar71xx_cpu_ops->ar71xx_chip_ddr_flush_ge0();
+}
+
+static inline void ar71xx_device_flush_ddr_ge1(void)
+{
+	ar71xx_cpu_ops->ar71xx_chip_ddr_flush_ge1();
+}
+
+static inline void ar71xx_init_usb_peripheral(void)
+{
+	ar71xx_cpu_ops->ar71xx_chip_init_usb_peripheral();
+}
+
+/* XXX shouldn't be here! */
+extern uint32_t u_ar71xx_cpu_freq;
+extern uint32_t u_ar71xx_ahb_freq;
+extern uint32_t u_ar71xx_ddr_freq;
+
+static inline uint64_t ar71xx_cpu_freq(void) { return u_ar71xx_cpu_freq; }
+static inline uint64_t ar71xx_ahb_freq(void) { return u_ar71xx_ahb_freq; }
+static inline uint64_t ar71xx_ddr_freq(void) { return u_ar71xx_ddr_freq; }
+ 
+#endif

From 3692b33ce3dea95cd6609cff58bdd973c80d1333 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Wed, 18 Aug 2010 08:22:58 +0000
Subject: [PATCH 0053/1624] Add a further register definition for USB device
 initialisation.

Obtained from:	Linux
---
 sys/mips/atheros/ar91xxreg.h | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/mips/atheros/ar91xxreg.h b/sys/mips/atheros/ar91xxreg.h
index 35319f12453..8fecddff071 100644
--- a/sys/mips/atheros/ar91xxreg.h
+++ b/sys/mips/atheros/ar91xxreg.h
@@ -34,6 +34,8 @@
 /* reset block */
 #define	AR91XX_RESET_REG_RESET_MODULE	AR71XX_RST_BLOCK_BASE + 0x1c
 
+#define	AR91XX_RST_RESET_MODULE_USBSUS_OVERRIDE	(1 << 10)
+
 /* PLL block */
 #define	AR91XX_PLL_REG_CPU_CONFIG       AR71XX_PLL_CPU_BASE + 0x00
 #define	AR91XX_PLL_REG_ETH_CONFIG       AR71XX_PLL_CPU_BASE + 0x04

From 5429211e0acefeecc16a045bbda99be9f1aaaf37 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Wed, 18 Aug 2010 09:11:45 +0000
Subject: [PATCH 0054/1624] Add a DDR flush function, inspired by both Linux
 and if_arge.c.

---
 sys/mips/atheros/ar71xxreg.h | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/sys/mips/atheros/ar71xxreg.h b/sys/mips/atheros/ar71xxreg.h
index a87151f6242..e6b7b8e8ac5 100644
--- a/sys/mips/atheros/ar71xxreg.h
+++ b/sys/mips/atheros/ar71xxreg.h
@@ -491,5 +491,15 @@ ar71xx_ahb_freq(void)
 	return (freq);
 }
 
+static inline void
+ar71xx_ddr_flush(uint32_t reg)
+{ 
+	ATH_WRITE_REG(reg, 1);
+	while ((ATH_READ_REG(reg) & 0x1))
+		;
+	ATH_WRITE_REG(reg, 1);
+	while ((ATH_READ_REG(reg) & 0x1))
+		;
+} 
 
 #endif /* _AR71XX_REG_H_ */

From 50e2303d9257cc5a4cf0be787a18119cbc95eaa1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Wed, 18 Aug 2010 09:18:37 +0000
Subject: [PATCH 0055/1624] Revert r211436; it was a good idea, but not fully
 thought out.

---
 Makefile.inc1 | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index 8263be03579..d2581c573ec 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -814,16 +814,9 @@ buildkernel:
 .endif
 	@echo
 	@echo "--------------------------------------------------------------"
-	@echo ">>> stage 3.2: building the kernel"
+	@echo ">>> stage 3.2: building everything"
 	@echo "--------------------------------------------------------------"
-	cd ${KRNLOBJDIR}/${_kernel}; ${KMAKE} kernel-all -DNO_MODULES_OBJ
-	@echo
-.if !defined(MODULES_WITH_WORLD) && !defined(NO_MODULES) && exists(${KERNSRCDIR}/modules)
-	@echo "--------------------------------------------------------------"
-	@echo ">>> stage 3.3: building the modules"
-	@echo "--------------------------------------------------------------"
-	cd ${KRNLOBJDIR}/${_kernel}; ${KMAKE} modules-all -DNO_MODULES_OBJ
-.endif
+	cd ${KRNLOBJDIR}/${_kernel}; ${KMAKE} all -DNO_MODULES_OBJ
 	@echo "--------------------------------------------------------------"
 	@echo ">>> Kernel build for ${_kernel} completed on `LC_ALL=C date`"
 	@echo "--------------------------------------------------------------"

From 2278f9927d4bda9fefe1911bca7448a949130652 Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Wed, 18 Aug 2010 09:28:12 +0000
Subject: [PATCH 0056/1624] When calculating the expected memory size for
 userspace, also take the number of syncache entries into account for the
 surplus we add to account for a possible increase of records in the re-entry
 window.

Discussed with:		jhb, silby
MFC after:		1 week
---
 sys/netinet/tcp_subr.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/netinet/tcp_subr.c b/sys/netinet/tcp_subr.c
index bfa3e663f00..f23a5404912 100644
--- a/sys/netinet/tcp_subr.c
+++ b/sys/netinet/tcp_subr.c
@@ -1022,7 +1022,7 @@ tcp_pcblist(SYSCTL_HANDLER_ARGS)
 	if (req->oldptr == NULL) {
 		m = syncache_pcbcount();
 		n = V_tcbinfo.ipi_count;
-		n += imax(n / 8, 10);
+		n += imax((m + n) / 8, 10);
 		req->oldidx = 2 * (sizeof xig) +
 		    (m + n) * sizeof(struct xtcpcb);
 		return (0);

From 28df1f238a397ecad6861cf48049910857c649e2 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 18 Aug 2010 12:09:27 +0000
Subject: [PATCH 0057/1624] For some setups sending data in 128kB chunks makes
 communication very slow. No idea why. 32kB on the other hand seems to work
 properly everywhere.

Reported by:	Thomas Steen Rasmussen 
MFC after:	3 weeks
---
 sbin/hastd/proto_common.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/sbin/hastd/proto_common.c b/sbin/hastd/proto_common.c
index 131d30e19ef..84680c2bfdb 100644
--- a/sbin/hastd/proto_common.c
+++ b/sbin/hastd/proto_common.c
@@ -42,8 +42,7 @@ __FBSDID("$FreeBSD$");
 
 /* Maximum size of packet we want to use when sending data. */
 #ifndef MAX_SEND_SIZE
-//#define	MAX_SEND_SIZE	32768
-#define	MAX_SEND_SIZE	131072
+#define	MAX_SEND_SIZE	32768
 #endif
 
 int

From 8eec5e8f9c808d163b868853fc8d191a3419037f Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 18 Aug 2010 12:52:21 +0000
Subject: [PATCH 0058/1624] MIPS n64 support - continued...

1. On n64, use XKPHYS to map page table pages instead of KSEG0. Maintain
   just one freepages list on n64.

   The changes are mainly to introduce MIPS_PHYS_TO_DIRECT(pa),
   MIPS_DIRECT_TO_PHYS(), which will use KSEG0 in 32 bit compilation
   and XKPHYS in 64 bit compilation.

2. Change macro based PMAP_LMEM_MAP1(), PMAP_LMEM_MAP2(), PMAP_LMEM_UNMAP()
  to inline functions.

3. Introduce MIPS_DIRECT_MAPPABLE(pa), which will further reduce the cases
   in which we will need to have a special case for 64 bit compilation.

4. Update CP0 hazard definitions for CPU_RMI - the cpu does not need any
   nops

Reviewed by:	neel
---
 sys/mips/include/cpuregs.h |  32 ++-
 sys/mips/include/vmparam.h |   4 +-
 sys/mips/mips/exception.S  |   2 +-
 sys/mips/mips/pmap.c       | 410 +++++++++++++++++--------------------
 4 files changed, 214 insertions(+), 234 deletions(-)

diff --git a/sys/mips/include/cpuregs.h b/sys/mips/include/cpuregs.h
index ee6a47a83c9..6c8f0a327fb 100644
--- a/sys/mips/include/cpuregs.h
+++ b/sys/mips/include/cpuregs.h
@@ -76,8 +76,10 @@
  * Caching of mapped addresses is controlled by bits in the TLB entry.
  */
 
-#define	MIPS_KSEG0_LARGEST_PHYS         (0x20000000)
-#define	MIPS_PHYS_MASK			(0x1fffffff)
+#define	MIPS_KSEG0_LARGEST_PHYS		(0x20000000)
+#define	MIPS_KSEG0_PHYS_MASK		(0x1fffffff)
+#define	MIPS_XKPHYS_LARGEST_PHYS	(0x10000000000)  /* 40 bit PA */
+#define	MIPS_XKPHYS_PHYS_MASK		(0x0ffffffffff)
 
 #ifndef LOCORE
 #define	MIPS_KUSEG_START		0x00000000
@@ -95,8 +97,8 @@
 
 #define	MIPS_PHYS_TO_KSEG0(x)		((uintptr_t)(x) | MIPS_KSEG0_START)
 #define	MIPS_PHYS_TO_KSEG1(x)		((uintptr_t)(x) | MIPS_KSEG1_START)
-#define	MIPS_KSEG0_TO_PHYS(x)		((uintptr_t)(x) & MIPS_PHYS_MASK)
-#define	MIPS_KSEG1_TO_PHYS(x)		((uintptr_t)(x) & MIPS_PHYS_MASK)
+#define	MIPS_KSEG0_TO_PHYS(x)		((uintptr_t)(x) & MIPS_KSEG0_PHYS_MASK)
+#define	MIPS_KSEG1_TO_PHYS(x)		((uintptr_t)(x) & MIPS_KSEG0_PHYS_MASK)
 
 #define	MIPS_IS_KSEG0_ADDR(x)					\
 	(((vm_offset_t)(x) >= MIPS_KSEG0_START) &&		\
@@ -107,9 +109,6 @@
 #define	MIPS_IS_VALID_PTR(x)		(MIPS_IS_KSEG0_ADDR(x) || \
 					    MIPS_IS_KSEG1_ADDR(x))
 
-#define	MIPS_XKPHYS_START		0x8000000000000000
-#define	MIPS_XKPHYS_END			0xbfffffffffffffff
-
 /*
  * Cache Coherency Attributes:
  *	UC:	Uncached.
@@ -180,19 +179,34 @@
 #define	MIPS_PHYS_TO_XKPHYS_UNCACHED(x) \
 	((0x2ULL << 62) | ((unsigned long long)(MIPS_CCA_UNCACHED) << 59) | (x))
 
-#define	MIPS_XKPHYS_TO_PHYS(x)		((x) & 0x07ffffffffffffffULL)
+#define	MIPS_XKPHYS_TO_PHYS(x)		((uintptr_t)(x) & MIPS_XKPHYS_PHYS_MASK)
 
+#define	MIPS_XKPHYS_START		0x8000000000000000
+#define	MIPS_XKPHYS_END			0xbfffffffffffffff
 #define	MIPS_XUSEG_START		0x0000000000000000
 #define	MIPS_XUSEG_END			0x0000010000000000
-
 #define	MIPS_XKSEG_START		0xc000000000000000
 #define	MIPS_XKSEG_END			0xc00000ff80000000
 
+#ifdef __mips_n64
+#define	MIPS_DIRECT_MAPPABLE(pa)	1
+#define	MIPS_PHYS_TO_DIRECT(pa)		MIPS_PHYS_TO_XKPHYS_CACHED(pa)
+#define	MIPS_PHYS_TO_DIRECT_UNCACHED(pa)	MIPS_PHYS_TO_XKPHYS_UNCACHED(pa)
+#define	MIPS_DIRECT_TO_PHYS(va)		MIPS_XKPHYS_TO_PHYS(va)
+#else
+#define	MIPS_DIRECT_MAPPABLE(pa)	((pa) < MIPS_KSEG0_LARGEST_PHYS)
+#define	MIPS_PHYS_TO_DIRECT(pa)		MIPS_PHYS_TO_KSEG0(pa)
+#define	MIPS_PHYS_TO_DIRECT_UNCACHED(pa)	MIPS_PHYS_TO_KSEG1(pa)
+#define	MIPS_DIRECT_TO_PHYS(va)		MIPS_KSEG0_TO_PHYS(va)
+#endif
+
 /* CPU dependent mtc0 hazard hook */
 #ifdef CPU_CNMIPS
 #define	COP0_SYNC  nop; nop; nop; nop; nop;
 #elif defined(CPU_SB1)
 #define COP0_SYNC  ssnop; ssnop; ssnop; ssnop; ssnop; ssnop; ssnop; ssnop; ssnop
+#elif defined(CPU_RMI)
+#define COP0_SYNC
 #else
 /*
  * Pick a reasonable default based on the "typical" spacing described in the
diff --git a/sys/mips/include/vmparam.h b/sys/mips/include/vmparam.h
index a1e5e843fcc..3050a9151ee 100644
--- a/sys/mips/include/vmparam.h
+++ b/sys/mips/include/vmparam.h
@@ -96,7 +96,7 @@
 #define	VM_MINUSER_ADDRESS	((vm_offset_t)0x00000000)
 #define	VM_MAX_MMAP_ADDR	VM_MAXUSER_ADDRESS
 
-#if defined(__mips_n64)
+#ifdef __mips_n64
 #define	VM_MAXUSER_ADDRESS	(VM_MINUSER_ADDRESS + (NPDEPG * NBSEG))
 #define	VM_MIN_KERNEL_ADDRESS	((vm_offset_t)0xc000000000000000)
 #define	VM_MAX_KERNEL_ADDRESS	(VM_MIN_KERNEL_ADDRESS + (NPDEPG * NBSEG))
@@ -185,7 +185,7 @@
  *	  allocations use HIGHMEM if available, and then DEFAULT. 
  *	- HIGHMEM for other pages 
  */
-#if 0 /* Not yet, change n64 to use xkphys */
+#ifdef __mips_n64
 #define	VM_NFREELIST		1
 #define	VM_FREELIST_DEFAULT	0
 #define	VM_FREELIST_DIRECT	VM_FREELIST_DEFAULT
diff --git a/sys/mips/mips/exception.S b/sys/mips/mips/exception.S
index 1baf2b22e81..fdd0a02e02d 100644
--- a/sys/mips/mips/exception.S
+++ b/sys/mips/mips/exception.S
@@ -1167,7 +1167,7 @@ eintrcnt:
 	.text
 VECTOR(MipsCache, unknown)
 	PTR_LA	k0, _C_LABEL(MipsCacheException)
-	li	k1, MIPS_PHYS_MASK
+	li	k1, MIPS_KSEG0_PHYS_MASK
 	and	k0, k1
 	PTR_LI	k1, MIPS_KSEG1_START
 	or	k0, k1
diff --git a/sys/mips/mips/pmap.c b/sys/mips/mips/pmap.c
index 1b2d372e327..2ff6f1c3491 100644
--- a/sys/mips/mips/pmap.c
+++ b/sys/mips/mips/pmap.c
@@ -198,68 +198,135 @@ static void pmap_invalidate_all_action(void *arg);
 static void pmap_update_page_action(void *arg);
 #endif
 
-#if !defined(__mips_n64)
-struct local_sysmaps {
-	vm_offset_t base;
-	uint16_t valid1, valid2;
-};
-
-/* This structure is for large memory
- * above 512Meg. We can't (in 32 bit mode)
- * just use the direct mapped MIPS_KSEG0_TO_PHYS()
- * macros since we can't see the memory and must
- * map it in when we need to access it. In 64
- * bit mode this goes away.
+#ifndef __mips_n64
+/*
+ * This structure is for high memory (memory above 512Meg in 32 bit)
+ * This memory area does not have direct mapping, so we a mechanism to do
+ * temporary per-CPU mapping to access these addresses.
+ *
+ * At bootup we reserve 2 virtual pages per CPU for mapping highmem pages, to 
+ * access a highmem physical address on a CPU, we will disable interrupts and
+ * add the mapping from the reserved virtual address for the CPU to the physical
+ * address in the kernel pagetable.
  */
+struct local_sysmaps {
+	vm_offset_t	base;
+	uint32_t	saved_intr;
+	uint16_t	valid1, valid2;
+};
 static struct local_sysmaps sysmap_lmem[MAXCPU];
 
-#define	PMAP_LMEM_MAP1(va, phys)					\
-	int cpu;							\
-	struct local_sysmaps *sysm;					\
-	pt_entry_t *pte, npte;						\
-									\
-	intr = intr_disable();						\
-	cpu = PCPU_GET(cpuid);						\
-	sysm = &sysmap_lmem[cpu];					\
-	va = sysm->base;						\
-	npte = TLBLO_PA_TO_PFN(phys) |					\
-	    PTE_D | PTE_V | PTE_G | PTE_W | PTE_C_CACHE;		\
-	pte = pmap_pte(kernel_pmap, va);				\
-	*pte = npte;							\
-	sysm->valid1 = 1
+static __inline void
+pmap_alloc_lmem_map(void)
+{
+	int i;
 
-#define	PMAP_LMEM_MAP2(va1, phys1, va2, phys2)				\
-	int cpu;							\
-	struct local_sysmaps *sysm;					\
-	pt_entry_t *pte, npte;						\
-									\
-	intr = intr_disable();						\
-	cpu = PCPU_GET(cpuid);						\
-	sysm = &sysmap_lmem[cpu];					\
-	va1 = sysm->base;						\
-	va2 = sysm->base + PAGE_SIZE;					\
-	npte = TLBLO_PA_TO_PFN(phys1) |					\
-	    PTE_D | PTE_V | PTE_G | PTE_W | PTE_C_CACHE;		\
-	pte = pmap_pte(kernel_pmap, va1);				\
-	*pte = npte;							\
-	npte =  TLBLO_PA_TO_PFN(phys2) |				\
-	    PTE_D | PTE_V | PTE_G | PTE_W | PTE_C_CACHE;		\
-	pte = pmap_pte(kernel_pmap, va2);				\
-	*pte = npte;							\
-	sysm->valid1 = 1;						\
+	for (i = 0; i < MAXCPU; i++) {
+		sysmap_lmem[i].base = virtual_avail;
+		virtual_avail += PAGE_SIZE * 2;
+		sysmap_lmem[i].valid1 = sysmap_lmem[i].valid2 = 0;
+	}
+}
+
+static __inline vm_offset_t
+pmap_lmem_map1(vm_paddr_t phys)
+{
+	struct local_sysmaps *sysm;
+	pt_entry_t *pte, npte;
+	vm_offset_t va;
+	uint32_t intr;
+	int cpu;
+
+	intr = intr_disable();
+	cpu = PCPU_GET(cpuid);
+	sysm = &sysmap_lmem[cpu];
+	sysm->saved_intr = intr;
+	va = sysm->base;
+	npte = TLBLO_PA_TO_PFN(phys) |
+	    PTE_D | PTE_V | PTE_G | PTE_W | PTE_C_CACHE;
+	pte = pmap_pte(kernel_pmap, va);
+	*pte = npte;
+	sysm->valid1 = 1;
+	return (va);
+}
+
+static __inline vm_offset_t
+pmap_lmem_map2(vm_paddr_t phys1, vm_paddr_t phys2)
+{
+	struct local_sysmaps *sysm;
+	pt_entry_t *pte, npte;
+	vm_offset_t va1, va2;
+	uint32_t intr;
+	int cpu;
+
+	intr = intr_disable();
+	cpu = PCPU_GET(cpuid);
+	sysm = &sysmap_lmem[cpu];
+	sysm->saved_intr = intr;
+	va1 = sysm->base;
+	va2 = sysm->base + PAGE_SIZE;
+	npte = TLBLO_PA_TO_PFN(phys1) |
+	    PTE_D | PTE_V | PTE_G | PTE_W | PTE_C_CACHE;
+	pte = pmap_pte(kernel_pmap, va1);
+	*pte = npte;
+	npte =  TLBLO_PA_TO_PFN(phys2) |
+	    PTE_D | PTE_V | PTE_G | PTE_W | PTE_C_CACHE;
+	pte = pmap_pte(kernel_pmap, va2);
+	*pte = npte;
+	sysm->valid1 = 1;
 	sysm->valid2 = 1;
+	return (va1);
+}
 
-#define	PMAP_LMEM_UNMAP()						\
-	pte = pmap_pte(kernel_pmap, sysm->base);			\
-	*pte = PTE_G;							\
-	tlb_invalidate_address(kernel_pmap, sysm->base);		\
-	sysm->valid1 = 0;						\
-	pte = pmap_pte(kernel_pmap, sysm->base + PAGE_SIZE);		\
-	*pte = PTE_G;							\
-	tlb_invalidate_address(kernel_pmap, sysm->base + PAGE_SIZE);	\
-	sysm->valid2 = 0;						\
-	intr_restore(intr)
-#endif
+static __inline void
+pmap_lmem_unmap(void)
+{
+	struct local_sysmaps *sysm;
+	pt_entry_t *pte;
+	int cpu;
+
+	cpu = PCPU_GET(cpuid);
+	sysm = &sysmap_lmem[cpu];
+	pte = pmap_pte(kernel_pmap, sysm->base);
+	*pte = PTE_G;
+	tlb_invalidate_address(kernel_pmap, sysm->base);
+	sysm->valid1 = 0;
+	if (sysm->valid2) {
+		pte = pmap_pte(kernel_pmap, sysm->base + PAGE_SIZE);
+		*pte = PTE_G;
+		tlb_invalidate_address(kernel_pmap, sysm->base + PAGE_SIZE);
+		sysm->valid2 = 0;
+	}
+	intr_restore(sysm->saved_intr);
+}
+#else  /* __mips_n64 */
+
+static __inline void
+pmap_alloc_lmem_map(void)
+{
+}
+
+static __inline vm_offset_t
+pmap_lmem_map1(vm_paddr_t phys)
+{
+
+	return (0);
+}
+
+static __inline vm_offset_t
+pmap_lmem_map2(vm_paddr_t phys1, vm_paddr_t phys2)
+{
+
+	return (0);
+}
+
+static __inline vm_offset_t 
+pmap_lmem_unmap(void)
+{
+
+	return (0);
+}
+#endif /* !__mips_n64 */
 
 /*
  * Page table entry lookup routines.
@@ -354,10 +421,9 @@ pmap_steal_memory(vm_size_t size)
 
 	pa = phys_avail[0];
 	phys_avail[0] += size;
-	if (pa >= MIPS_KSEG0_LARGEST_PHYS) {
+	if (MIPS_DIRECT_MAPPABLE(pa) == 0)
 		panic("Out of memory below 512Meg?");
-	}
-	va = MIPS_PHYS_TO_KSEG0(pa);
+	va = MIPS_PHYS_TO_DIRECT(pa);
 	bzero((caddr_t)va, size);
 	return (va);
 }
@@ -429,9 +495,7 @@ void
 pmap_bootstrap(void)
 {
 	int i;
-#if !defined(__mips_n64)
-	int memory_larger_than_512meg = 0;
-#endif
+	int need_local_mappings = 0; 
 
 	/* Sort. */
 again:
@@ -459,10 +523,13 @@ again:
 		}
 	}
 
-#if !defined(__mips_n64)
-	if (phys_avail[i - 1] >= MIPS_KSEG0_LARGEST_PHYS)
-		memory_larger_than_512meg = 1;
-#endif
+       	/*
+	 * In 32 bit, we may have memory which cannot be mapped directly
+	 * this memory will need temporary mapping before it can be
+	 * accessed.
+	 */
+	if (!MIPS_DIRECT_MAPPABLE(phys_avail[i - 1]))
+		need_local_mappings = 1;
 
 	/*
 	 * Copy the phys_avail[] array before we start stealing memory from it.
@@ -521,22 +588,8 @@ again:
 		printf("pcpu is available at virtual address %p.\n", pcpup);
 #endif
 
-#if !defined(__mips_n64)
-	/*
-	 * Steal some virtual space that will not be in kernel_segmap. This
-	 * va memory space will be used to map in kernel pages that are
-	 * outside the 512Meg region. Note that we only do this steal when
-	 * we do have memory in this region, that way for systems with
-	 * smaller memory we don't "steal" any va ranges :-)
-	 */
-	if (memory_larger_than_512meg) {
-		for (i = 0; i < MAXCPU; i++) {
-			sysmap_lmem[i].base = virtual_avail;
-			virtual_avail += PAGE_SIZE * 2;
-			sysmap_lmem[i].valid1 = sysmap_lmem[i].valid2 = 0;
-		}
-	}
-#endif
+	if (need_local_mappings)
+		pmap_alloc_lmem_map();
 	pmap_create_kernel_pagetable();
 	pmap_max_asid = VMNUM_PIDS;
 	mips_wr_entryhi(0);
@@ -850,20 +903,13 @@ pmap_kremove(vm_offset_t va)
  *
  *	Use XKPHYS for 64 bit, and KSEG0 where possible for 32 bit.
  */
-#if defined(__mips_n64)
-vm_offset_t
-pmap_map(vm_offset_t *virt, vm_offset_t start, vm_offset_t end, int prot)
-{
-	return (MIPS_PHYS_TO_XKPHYS_CACHED(start));
-}
-#else
 vm_offset_t
 pmap_map(vm_offset_t *virt, vm_offset_t start, vm_offset_t end, int prot)
 {
 	vm_offset_t va, sva;
 
-	if (end <= MIPS_KSEG0_LARGEST_PHYS)
-		return (MIPS_PHYS_TO_KSEG0(start));
+	if (MIPS_DIRECT_MAPPABLE(end))
+		return (MIPS_PHYS_TO_DIRECT(start));
 
 	va = sva = *virt;
 	while (start < end) {
@@ -874,7 +920,6 @@ pmap_map(vm_offset_t *virt, vm_offset_t start, vm_offset_t end, int prot)
 	*virt = va;
 	return (sva);
 }
-#endif
 
 /*
  * Add a list of wired pages to the kva
@@ -971,7 +1016,7 @@ _pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m)
 		 * Recursively decrement next level pagetable refcount
 		 */
 		pdp = (pd_entry_t *)*pmap_segmap(pmap, va);
-		pdpg = PHYS_TO_VM_PAGE(MIPS_KSEG0_TO_PHYS(pdp));
+		pdpg = PHYS_TO_VM_PAGE(MIPS_DIRECT_TO_PHYS(pdp));
 		pmap_unwire_pte_hold(pmap, va, pdpg);
 	}
 #endif
@@ -1006,7 +1051,7 @@ pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
 			mpte = pmap->pm_ptphint;
 		} else {
 			pteva = *pmap_pde(pmap, va);
-			mpte = PHYS_TO_VM_PAGE(MIPS_KSEG0_TO_PHYS(pteva));
+			mpte = PHYS_TO_VM_PAGE(MIPS_DIRECT_TO_PHYS(pteva));
 			pmap->pm_ptphint = mpte;
 		}
 	}
@@ -1035,7 +1080,11 @@ static void
 pmap_grow_pte_page_cache()
 {
 
+#ifdef __mips_n64
+	vm_contig_grow_cache(3, 0, MIPS_XKPHYS_LARGEST_PHYS);
+#else
 	vm_contig_grow_cache(3, 0, MIPS_KSEG0_LARGEST_PHYS);
+#endif
 }
 
 static vm_page_t
@@ -1075,7 +1124,7 @@ pmap_pinit(pmap_t pmap)
 	while ((ptdpg = pmap_alloc_pte_page(NUSERPGTBLS, VM_ALLOC_NORMAL)) == NULL)
 	       pmap_grow_pte_page_cache();
 
-	ptdva = MIPS_PHYS_TO_KSEG0(VM_PAGE_TO_PHYS(ptdpg));
+	ptdva = MIPS_PHYS_TO_DIRECT(VM_PAGE_TO_PHYS(ptdpg));
 	pmap->pm_segtab = (pd_entry_t *)ptdva;
 	pmap->pm_active = 0;
 	pmap->pm_ptphint = NULL;
@@ -1126,7 +1175,7 @@ _pmap_allocpte(pmap_t pmap, unsigned ptepindex, int flags)
 	 * Map the pagetable page into the process address space, if it
 	 * isn't already there.
 	 */
-	pageva = MIPS_PHYS_TO_KSEG0(VM_PAGE_TO_PHYS(m));
+	pageva = MIPS_PHYS_TO_DIRECT(VM_PAGE_TO_PHYS(m));
 
 #ifdef __mips_n64
 	if (ptepindex >= NUPDE) {
@@ -1149,7 +1198,7 @@ _pmap_allocpte(pmap_t pmap, unsigned ptepindex, int flags)
 				return (NULL);
 			}
 		} else {
-			pg = PHYS_TO_VM_PAGE(MIPS_KSEG0_TO_PHYS(*pdep));
+			pg = PHYS_TO_VM_PAGE(MIPS_DIRECT_TO_PHYS(*pdep));
 			pg->wire_count++;
 		}
 		/* Next level entry */
@@ -1202,7 +1251,7 @@ retry:
 		    (pmap->pm_ptphint->pindex == ptepindex)) {
 			m = pmap->pm_ptphint;
 		} else {
-			m = PHYS_TO_VM_PAGE(MIPS_KSEG0_TO_PHYS(*pde));
+			m = PHYS_TO_VM_PAGE(MIPS_DIRECT_TO_PHYS(*pde));
 			pmap->pm_ptphint = m;
 		}
 		m->wire_count++;
@@ -1250,7 +1299,7 @@ pmap_release(pmap_t pmap)
 	    pmap->pm_stats.resident_count));
 
 	ptdva = (vm_offset_t)pmap->pm_segtab;
-	ptdpg = PHYS_TO_VM_PAGE(MIPS_KSEG0_TO_PHYS(ptdva));
+	ptdpg = PHYS_TO_VM_PAGE(MIPS_DIRECT_TO_PHYS(ptdva));
 
 	ptdpg->wire_count--;
 	atomic_subtract_int(&cnt.v_wire_count, 1);
@@ -1281,7 +1330,7 @@ pmap_growkernel(vm_offset_t addr)
 			nkpg = pmap_alloc_pte_page(nkpt, VM_ALLOC_INTERRUPT);
 			if (nkpg == NULL)
 				panic("pmap_growkernel: no memory to grow kernel");
-			*pdpe = (pd_entry_t)MIPS_PHYS_TO_KSEG0(VM_PAGE_TO_PHYS(nkpg));
+			*pdpe = (pd_entry_t)MIPS_PHYS_TO_DIRECT(VM_PAGE_TO_PHYS(nkpg));
 			continue; /* try again */
 		}
 #endif
@@ -1302,7 +1351,7 @@ pmap_growkernel(vm_offset_t addr)
 		if (!nkpg)
 			panic("pmap_growkernel: no memory to grow kernel");
 		nkpt++;
-		*pde = (pd_entry_t)MIPS_PHYS_TO_KSEG0(VM_PAGE_TO_PHYS(nkpg));
+		*pde = (pd_entry_t)MIPS_PHYS_TO_DIRECT(VM_PAGE_TO_PHYS(nkpg));
 
 		/*
 		 * The R[4-7]?00 stores only one copy of the Global bit in
@@ -2080,7 +2129,7 @@ pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
 					mpte = pmap->pm_ptphint;
 				} else {
 					mpte = PHYS_TO_VM_PAGE(
-						MIPS_KSEG0_TO_PHYS(*pde));
+						MIPS_DIRECT_TO_PHYS(*pde));
 					pmap->pm_ptphint = mpte;
 				}
 				mpte->wire_count++;
@@ -2156,30 +2205,21 @@ pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
  *
  * Use XKPHYS for 64 bit, and KSEG0 where possible for 32 bit.
  */
-#if defined(__mips_n64)
-void *
-pmap_kenter_temporary(vm_paddr_t pa, int i)
-{
-	return ((void *)MIPS_PHYS_TO_XKPHYS_CACHED(pa));
-}
-void
-pmap_kenter_temporary_free(vm_paddr_t pa)
-{
-}
-#else
 void *
 pmap_kenter_temporary(vm_paddr_t pa, int i)
 {
 	vm_offset_t va;
-	register_t intr;
+
 	if (i != 0)
 		printf("%s: ERROR!!! More than one page of virtual address mapping not supported\n",
 		    __func__);
 
-	if (pa < MIPS_KSEG0_LARGEST_PHYS) {
-		va = MIPS_PHYS_TO_KSEG0(pa);
+	if (MIPS_DIRECT_MAPPABLE(pa)) {
+		va = MIPS_PHYS_TO_DIRECT(pa);
 	} else {
+#ifndef __mips_n64    /* XXX : to be converted to new style */
 		int cpu;
+		register_t intr;
 		struct local_sysmaps *sysm;
 		pt_entry_t *pte, npte;
 
@@ -2199,6 +2239,7 @@ pmap_kenter_temporary(vm_paddr_t pa, int i)
 		pmap_update_page(kernel_pmap, sysm->base, npte);
 		va = sysm->base;
 		intr_restore(intr);
+#endif
 	}
 	return ((void *)va);
 }
@@ -2206,14 +2247,17 @@ pmap_kenter_temporary(vm_paddr_t pa, int i)
 void
 pmap_kenter_temporary_free(vm_paddr_t pa)
 {
+#ifndef __mips_n64    /* XXX : to be converted to new style */
 	int cpu;
 	register_t intr;
 	struct local_sysmaps *sysm;
+#endif
 
-	if (pa < MIPS_KSEG0_LARGEST_PHYS) {
+	if (MIPS_DIRECT_MAPPABLE(pa)) {
 		/* nothing to do for this case */
 		return;
 	}
+#ifndef __mips_n64    /* XXX : to be converted to new style */
 	cpu = PCPU_GET(cpuid);
 	sysm = &sysmap_lmem[cpu];
 	if (sysm->valid1) {
@@ -2226,8 +2270,8 @@ pmap_kenter_temporary_free(vm_paddr_t pa)
 		intr_restore(intr);
 		sysm->valid1 = 0;
 	}
-}
 #endif
+}
 
 /*
  * Moved the code to Machine Independent
@@ -2336,113 +2380,65 @@ pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
  *
  * 	Use XKPHYS for 64 bit, and KSEG0 where possible for 32 bit.
  */
-#if defined (__mips_n64)
 void
 pmap_zero_page(vm_page_t m)
 {
 	vm_offset_t va;
 	vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
 
-	va = MIPS_PHYS_TO_XKPHYS_CACHED(phys);
-	bzero((caddr_t)va, PAGE_SIZE);
-	mips_dcache_wbinv_range(va, PAGE_SIZE);
-}
-#else
-void
-pmap_zero_page(vm_page_t m)
-{
-	vm_offset_t va;
-	vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
-	register_t intr;
-
-	if (phys < MIPS_KSEG0_LARGEST_PHYS) {
-		va = MIPS_PHYS_TO_KSEG0(phys);
-
+	if (MIPS_DIRECT_MAPPABLE(phys)) {
+		va = MIPS_PHYS_TO_DIRECT(phys);
 		bzero((caddr_t)va, PAGE_SIZE);
 		mips_dcache_wbinv_range(va, PAGE_SIZE);
 	} else {
-		PMAP_LMEM_MAP1(va, phys);
-
+		va = pmap_lmem_map1(phys);
 		bzero((caddr_t)va, PAGE_SIZE);
 		mips_dcache_wbinv_range(va, PAGE_SIZE);
-
-		PMAP_LMEM_UNMAP();
+		pmap_lmem_unmap();
 	}
 }
-#endif
+
 /*
  *	pmap_zero_page_area zeros the specified hardware page by mapping
  *	the page into KVM and using bzero to clear its contents.
  *
  *	off and size may not cover an area beyond a single hardware page.
  */
-#if defined (__mips_n64)
 void
 pmap_zero_page_area(vm_page_t m, int off, int size)
 {
 	vm_offset_t va;
 	vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
 
-	va = MIPS_PHYS_TO_XKPHYS_CACHED(phys);
-	bzero((char *)(caddr_t)va + off, size);
-	mips_dcache_wbinv_range(va + off, size);
-}
-#else
-void
-pmap_zero_page_area(vm_page_t m, int off, int size)
-{
-	vm_offset_t va;
-	vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
-	register_t intr;
-
-	if (phys < MIPS_KSEG0_LARGEST_PHYS) {
-		va = MIPS_PHYS_TO_KSEG0(phys);
+	if (MIPS_DIRECT_MAPPABLE(phys)) {
+		va = MIPS_PHYS_TO_DIRECT(phys);
 		bzero((char *)(caddr_t)va + off, size);
 		mips_dcache_wbinv_range(va + off, size);
 	} else {
-		PMAP_LMEM_MAP1(va, phys);
-
+		va = pmap_lmem_map1(phys);
 		bzero((char *)va + off, size);
 		mips_dcache_wbinv_range(va + off, size);
-
-		PMAP_LMEM_UNMAP();
+		pmap_lmem_unmap();
 	}
 }
-#endif
 
-#if defined (__mips_n64)
 void
 pmap_zero_page_idle(vm_page_t m)
 {
 	vm_offset_t va;
 	vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
 
-	va = MIPS_PHYS_TO_XKPHYS_CACHED(phys);
-	bzero((caddr_t)va, PAGE_SIZE);
-	mips_dcache_wbinv_range(va, PAGE_SIZE);
-}
-#else
-void
-pmap_zero_page_idle(vm_page_t m)
-{
-	vm_offset_t va;
-	vm_paddr_t phys = VM_PAGE_TO_PHYS(m);
-	register_t intr;
-
-	if (phys < MIPS_KSEG0_LARGEST_PHYS) {
-		va = MIPS_PHYS_TO_KSEG0(phys);
+	if (MIPS_DIRECT_MAPPABLE(phys)) {
+		va = MIPS_PHYS_TO_DIRECT(phys);
 		bzero((caddr_t)va, PAGE_SIZE);
 		mips_dcache_wbinv_range(va, PAGE_SIZE);
 	} else {
-		PMAP_LMEM_MAP1(va, phys);
-
+		va = pmap_lmem_map1(phys);
 		bzero((caddr_t)va, PAGE_SIZE);
 		mips_dcache_wbinv_range(va, PAGE_SIZE);
-
-		PMAP_LMEM_UNMAP();
+		pmap_lmem_unmap();
 	}
 }
-#endif
 
 /*
  *	pmap_copy_page copies the specified (machine independent)
@@ -2452,31 +2448,14 @@ pmap_zero_page_idle(vm_page_t m)
  *
  * 	Use XKPHYS for 64 bit, and KSEG0 where possible for 32 bit.
  */
-#if defined (__mips_n64)
 void
 pmap_copy_page(vm_page_t src, vm_page_t dst)
 {
 	vm_offset_t va_src, va_dst;
-	vm_paddr_t phy_src = VM_PAGE_TO_PHYS(src);
-	vm_paddr_t phy_dst = VM_PAGE_TO_PHYS(dst);
+	vm_paddr_t phys_src = VM_PAGE_TO_PHYS(src);
+	vm_paddr_t phys_dst = VM_PAGE_TO_PHYS(dst);
 
-	pmap_flush_pvcache(src);
-	mips_dcache_wbinv_range_index(MIPS_PHYS_TO_XKPHYS_CACHED(phy_dst), PAGE_SIZE);
-	va_src = MIPS_PHYS_TO_XKPHYS_CACHED(phy_src);
-	va_dst = MIPS_PHYS_TO_XKPHYS_CACHED(phy_dst);
-	bcopy((caddr_t)va_src, (caddr_t)va_dst, PAGE_SIZE);
-	mips_dcache_wbinv_range(va_dst, PAGE_SIZE);
-}
-#else
-void
-pmap_copy_page(vm_page_t src, vm_page_t dst)
-{
-	vm_offset_t va_src, va_dst;
-	vm_paddr_t phy_src = VM_PAGE_TO_PHYS(src);
-	vm_paddr_t phy_dst = VM_PAGE_TO_PHYS(dst);
-	register_t intr;
-
-	if ((phy_src < MIPS_KSEG0_LARGEST_PHYS) && (phy_dst < MIPS_KSEG0_LARGEST_PHYS)) {
+	if (MIPS_DIRECT_MAPPABLE(phys_src) && MIPS_DIRECT_MAPPABLE(phys_dst)) {
 		/* easy case, all can be accessed via KSEG0 */
 		/*
 		 * Flush all caches for VA that are mapped to this page
@@ -2484,21 +2463,19 @@ pmap_copy_page(vm_page_t src, vm_page_t dst)
 		 */
 		pmap_flush_pvcache(src);
 		mips_dcache_wbinv_range_index(
-		    MIPS_PHYS_TO_KSEG0(phy_dst), PAGE_SIZE);
-		va_src = MIPS_PHYS_TO_KSEG0(phy_src);
-		va_dst = MIPS_PHYS_TO_KSEG0(phy_dst);
+		    MIPS_PHYS_TO_DIRECT(phys_dst), PAGE_SIZE);
+		va_src = MIPS_PHYS_TO_DIRECT(phys_src);
+		va_dst = MIPS_PHYS_TO_DIRECT(phys_dst);
 		bcopy((caddr_t)va_src, (caddr_t)va_dst, PAGE_SIZE);
 		mips_dcache_wbinv_range(va_dst, PAGE_SIZE);
 	} else {
-		PMAP_LMEM_MAP2(va_src, phy_src, va_dst, phy_dst);
-
+		va_src = pmap_lmem_map2(phys_src, phys_dst);
+		va_dst = va_src + PAGE_SIZE;
 		bcopy((void *)va_src, (void *)va_dst, PAGE_SIZE);
 		mips_dcache_wbinv_range(va_dst, PAGE_SIZE);
-
-		PMAP_LMEM_UNMAP();
+		pmap_lmem_unmap();
 	}
 }
-#endif
 
 /*
  * Returns true if the pmap's pv is one of the first
@@ -2914,18 +2891,6 @@ pmap_clear_reference(vm_page_t m)
  *
  * Use XKPHYS uncached for 64 bit, and KSEG1 where possible for 32 bit.
  */
-#if defined(__mips_n64)
-void *
-pmap_mapdev(vm_offset_t pa, vm_size_t size)
-{
-	return ((void *)MIPS_PHYS_TO_XKPHYS_UNCACHED(pa));
-}
-
-void
-pmap_unmapdev(vm_offset_t va, vm_size_t size)
-{
-}
-#else
 void *
 pmap_mapdev(vm_offset_t pa, vm_size_t size)
 {
@@ -2935,8 +2900,8 @@ pmap_mapdev(vm_offset_t pa, vm_size_t size)
 	 * KSEG1 maps only first 512M of phys address space. For 
 	 * pa > 0x20000000 we should make proper mapping * using pmap_kenter.
 	 */
-	if ((pa + size - 1) < MIPS_KSEG0_LARGEST_PHYS)
-		return ((void *)MIPS_PHYS_TO_KSEG1(pa));
+	if (MIPS_DIRECT_MAPPABLE(pa + size - 1))
+		return ((void *)MIPS_PHYS_TO_DIRECT_UNCACHED(pa));
 	else {
 		offset = pa & PAGE_MASK;
 		size = roundup(size + offset, PAGE_SIZE);
@@ -2959,6 +2924,7 @@ pmap_mapdev(vm_offset_t pa, vm_size_t size)
 void
 pmap_unmapdev(vm_offset_t va, vm_size_t size)
 {
+#ifndef __mips_n64
 	vm_offset_t base, offset, tmpva;
 
 	/* If the address is within KSEG1 then there is nothing to do */
@@ -2971,8 +2937,8 @@ pmap_unmapdev(vm_offset_t va, vm_size_t size)
 	for (tmpva = base; tmpva < base + size; tmpva += PAGE_SIZE)
 		pmap_kremove(tmpva);
 	kmem_free(kernel_map, base, size);
-}
 #endif
+}
 
 /*
  * perform the pmap work for mincore

From 3d7cfb15f5cc661b60605be899445679e4307373 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 18 Aug 2010 15:38:10 +0000
Subject: [PATCH 0059/1624] Remove bintime_cmp() function, unused since
 r200086.

MFC after:	1 week
---
 sys/geom/mirror/g_mirror.c | 15 ---------------
 1 file changed, 15 deletions(-)

diff --git a/sys/geom/mirror/g_mirror.c b/sys/geom/mirror/g_mirror.c
index 404ab986b35..41d35e45d34 100644
--- a/sys/geom/mirror/g_mirror.c
+++ b/sys/geom/mirror/g_mirror.c
@@ -844,21 +844,6 @@ g_mirror_unidle(struct g_mirror_softc *sc)
 	}
 }
 
-static __inline int
-bintime_cmp(struct bintime *bt1, struct bintime *bt2)
-{
-
-	if (bt1->sec < bt2->sec)
-		return (-1);
-	else if (bt1->sec > bt2->sec)
-		return (1);
-	if (bt1->frac < bt2->frac)
-		return (-1);
-	else if (bt1->frac > bt2->frac)
-		return (1);
-	return (0);
-}
-
 static void
 g_mirror_done(struct bio *bp)
 {

From b7d747ecec2a697e4edcd69c81f9f0b411e3aae1 Mon Sep 17 00:00:00 2001
From: Andre Oppermann 
Date: Wed, 18 Aug 2010 17:39:47 +0000
Subject: [PATCH 0060/1624] Untangle the net.inet.tcp.log_in_vain and
 net.inet.tcp.log_debug sysctl's and remove any side effects.

Both sysctl's share the same backend infrastructure and due to the
way it was implemented enabling net.inet.tcp.log_in_vain would also
cause log_debug output to be generated.  This was surprising and
eventually annoying to the user.

The log output backend is kept the same but a little shim is inserted
to properly separate log_in_vain and log_debug and to remove any side
effects.

PR:		kern/137317
MFC after:	1 week
---
 sys/netinet/tcp_input.c |  2 +-
 sys/netinet/tcp_subr.c  | 30 ++++++++++++++++++++++++++----
 sys/netinet/tcp_var.h   |  2 ++
 3 files changed, 29 insertions(+), 5 deletions(-)

diff --git a/sys/netinet/tcp_input.c b/sys/netinet/tcp_input.c
index cbba9cd4ed0..05671ce0052 100644
--- a/sys/netinet/tcp_input.c
+++ b/sys/netinet/tcp_input.c
@@ -571,7 +571,7 @@ findpcb:
 		 */
 		if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
 		    tcp_log_in_vain == 2) {
-			if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
+			if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
 				log(LOG_INFO, "%s; %s: Connection attempt "
 				    "to closed port\n", s, __func__);
 		}
diff --git a/sys/netinet/tcp_subr.c b/sys/netinet/tcp_subr.c
index f23a5404912..fe8f79a61ed 100644
--- a/sys/netinet/tcp_subr.c
+++ b/sys/netinet/tcp_subr.c
@@ -268,6 +268,8 @@ VNET_DEFINE(uma_zone_t, sack_hole_zone);
 
 static struct inpcb *tcp_notify(struct inpcb *, int);
 static void	tcp_isn_tick(void *);
+static char *	tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
+		    void *ip4hdr, const void *ip6hdr);
 
 /*
  * Target size of TCP PCB hash tables. Must be a power of two.
@@ -2233,10 +2235,34 @@ SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
  * Due to header inclusion and ordering limitations the struct ip
  * and ip6_hdr pointers have to be passed as void pointers.
  */
+char *
+tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
+    const void *ip6hdr)
+{
+
+	/* Is logging enabled? */
+	if (tcp_log_in_vain == 0)
+		return (NULL);
+
+	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
+}
+
 char *
 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
     const void *ip6hdr)
 {
+
+	/* Is logging enabled? */
+	if (tcp_log_debug == 0)
+		return (NULL);
+
+	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
+}
+
+static char *
+tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
+    const void *ip6hdr)
+{
 	char *s, *sp;
 	size_t size;
 	struct ip *ip;
@@ -2259,10 +2285,6 @@ tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
 	    2 * INET_ADDRSTRLEN;
 #endif /* INET6 */
 
-	/* Is logging enabled? */
-	if (tcp_log_debug == 0 && tcp_log_in_vain == 0)
-		return (NULL);
-
 	s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
 	if (s == NULL)
 		return (NULL);
diff --git a/sys/netinet/tcp_var.h b/sys/netinet/tcp_var.h
index 5811439dcd6..7482277be29 100644
--- a/sys/netinet/tcp_var.h
+++ b/sys/netinet/tcp_var.h
@@ -611,6 +611,8 @@ void	 tcp_destroy(void);
 void	 tcp_fini(void *);
 char 	*tcp_log_addrs(struct in_conninfo *, struct tcphdr *, void *,
 	    const void *);
+char	*tcp_log_vain(struct in_conninfo *, struct tcphdr *, void *,
+	    const void *);
 int	 tcp_reass(struct tcpcb *, struct tcphdr *, int *, struct mbuf *);
 void	 tcp_reass_init(void);
 #ifdef VIMAGE

From 3ed1008b891eb34df96a6ae4f87e5a3270be759c Mon Sep 17 00:00:00 2001
From: Gabor Kovesdan 
Date: Wed, 18 Aug 2010 17:40:10 +0000
Subject: [PATCH 0061/1624] - Refactor file reading code to use pure syscalls
 and an internal buffer   instead of stdio.  This gives BSD grep a very big
 performance boost,   its speed is now almost comparable to GNU grep.

Submitted by:	Dimitry Andric 
Approved by:	delphij (mentor)
---
 usr.bin/grep/fastgrep.c |   2 +-
 usr.bin/grep/file.c     | 348 +++++++++++++++++++---------------------
 usr.bin/grep/grep.h     |   9 +-
 usr.bin/grep/util.c     |   4 +-
 4 files changed, 171 insertions(+), 192 deletions(-)

diff --git a/usr.bin/grep/fastgrep.c b/usr.bin/grep/fastgrep.c
index c66f0a7ae2f..30a2dc50b0d 100644
--- a/usr.bin/grep/fastgrep.c
+++ b/usr.bin/grep/fastgrep.c
@@ -198,7 +198,7 @@ fastcomp(fastgrep_t *fg, const char *pat)
 }
 
 int
-grep_search(fastgrep_t *fg, unsigned char *data, size_t len, regmatch_t *pmatch)
+grep_search(fastgrep_t *fg, const unsigned char *data, size_t len, regmatch_t *pmatch)
 {
 	unsigned int j;
 	int ret = REG_NOMATCH;
diff --git a/usr.bin/grep/file.c b/usr.bin/grep/file.c
index 1872d0eff3d..51be53d8909 100644
--- a/usr.bin/grep/file.c
+++ b/usr.bin/grep/file.c
@@ -2,7 +2,8 @@
 
 /*-
  * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
- * Copyright (C) 2008-2009 Gabor Kovesdan 
+ * Copyright (C) 2008-2010 Gabor Kovesdan 
+ * Copyright (C) 2010 Dimitry Andric 
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -37,7 +38,8 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
+#include 
+#include 
 #include 
 #include 
 #include 
@@ -47,222 +49,204 @@ __FBSDID("$FreeBSD$");
 
 #include "grep.h"
 
-static char	 fname[MAXPATHLEN];	/* file name */
+#define	MAXBUFSIZ	(32 * 1024)
+#define	LNBUFBUMP	80
 
-#define		 MAXBUFSIZ	(16 * 1024)
-#define		 PREREAD_M	0.2
+static gzFile gzbufdesc;
+static BZFILE* bzbufdesc;
 
-/* Some global variables for the buffering and reading. */
-static char	*lnbuf;
-static size_t	 lnbuflen;
-static unsigned char *binbuf;
-static int	 binbufsiz;
-unsigned char	*binbufptr;
-static int	 bzerr;
+static unsigned char buffer[MAXBUFSIZ];
+static unsigned char *bufpos;
+static size_t bufrem;
 
-#define iswbinary(ch)	(!iswspace((ch)) && iswcntrl((ch)) && \
-			    (ch != L'\b') && (ch != L'\0'))
+static unsigned char *lnbuf;
+static size_t lnbuflen;
 
-/*
- * Returns a single character according to the file type.
- * Returns -1 on failure.
- */
 static inline int
-grep_fgetc(struct file *f)
+grep_refill(struct file *f)
 {
-	unsigned char c;
+	ssize_t nr;
+	int bzerr;
 
-	switch (filebehave) {
-	case FILE_STDIO:
-		return (getc_unlocked(f->f));
-	case FILE_GZIP:
-		return (gzgetc(f->gzf));
-	case FILE_BZIP:
-		BZ2_bzRead(&bzerr, f->bzf, &c, 1);
-		if (bzerr == BZ_STREAM_END)
-			return (-1);
-		else if (bzerr != BZ_SEQUENCE_ERROR && bzerr != BZ_OK)
-			errx(2, "%s", getstr(2));
-		return (c);
-	}
-	return (-1);
-}
+	bufpos = buffer;
+	bufrem = 0;
 
-/*
- * Returns true if the file position is a EOF, returns false
- * otherwise.
- */
-static inline int
-grep_feof(struct file *f)
-{
-
-	switch (filebehave) {
-	case FILE_STDIO:
-		return (feof_unlocked(f->f));
-	case FILE_GZIP:
-		return (gzeof(f->gzf));
-	case FILE_BZIP:
-		return (bzerr == BZ_STREAM_END);
-	}
-	return (1);
-}
-
-/*
- * At the first call, fills in an internal buffer and checks if the given
- * file is a binary file and sets the binary flag accordingly.  Then returns
- * a single line and sets len to the length of the returned line.
- * At any other call returns a single line either from the internal buffer
- * or from the file if the buffer is exhausted and sets len to the length
- * of the line.
- */
-char *
-grep_fgetln(struct file *f, size_t *len)
-{
-	struct stat st;
-	size_t bufsiz, i = 0;
-	int ch = 0;
-
-	/* Fill in the buffer if it is empty. */
-	if (binbufptr == NULL) {
-
-		/* Only pre-read to the buffer if we need the binary check. */
-		if (binbehave != BINFILE_TEXT) {
-			if (f->stdin)
-				st.st_size = MAXBUFSIZ;
-			else if (stat(fname, &st) != 0)
-				err(2, NULL);
-			/* no need to allocate buffer. */
-			if (st.st_size == 0)
-				return (NULL);
-
-			bufsiz = (MAXBUFSIZ > (st.st_size * PREREAD_M)) ?
-			    (st.st_size / 2) : MAXBUFSIZ;
-
-			binbuf = grep_malloc(sizeof(char) * bufsiz);
-
-			while (i < bufsiz) {
-				ch = grep_fgetc(f);
-				if (ch == EOF)
-					break;
-				binbuf[i++] = ch;
-				if ((ch == '\n') && lbflag)
-					break;
-			}
-
-			f->binary = memchr(binbuf, (filebehave != FILE_GZIP) ?
-			    '\0' : '\200', i - 1) != NULL;
-		}
-		binbufsiz = i;
-		binbufptr = binbuf;
-	}
-
-	/* Read a line whether from the buffer or from the file itself. */
-	for (i = 0; !(grep_feof(f) &&
-	    (binbufptr == &binbuf[binbufsiz])); i++) {
-		if (binbufptr == &binbuf[binbufsiz]) {
-			ch = grep_fgetc(f);
-		} else {
-			ch = binbufptr[0];
-			binbufptr++;
-		}
-		if (i >= lnbuflen) {
-			lnbuflen *= 2;
-			lnbuf = grep_realloc(lnbuf, ++lnbuflen);
-		}
-		if ((ch == '\n') || (ch == EOF)) {
-			lnbuf[i] = '\0';
+	if (filebehave == FILE_GZIP)
+		nr = gzread(gzbufdesc, buffer, MAXBUFSIZ);
+	else if (filebehave == FILE_BZIP && bzbufdesc != NULL) {
+		nr = BZ2_bzRead(&bzerr, bzbufdesc, buffer, MAXBUFSIZ);
+		switch (bzerr) {
+		case BZ_OK:
+		case BZ_STREAM_END:
+			/* No problem, nr will be okay */
 			break;
-		} else
-			lnbuf[i] = ch;
-	}
-	if (grep_feof(f) && (i == 0) && (ch != '\n'))
-		return (NULL);
-	*len = i;
-	return (lnbuf);
+		case BZ_DATA_ERROR_MAGIC:
+			/*
+			 * As opposed to gzread(), which simply returns the
+			 * plain file data, if it is not in the correct
+			 * compressed format, BZ2_bzRead() instead aborts.
+			 *
+			 * So, just restart at the beginning of the file again,
+			 * and use plain reads from now on.
+			 */
+			BZ2_bzReadClose(&bzerr, bzbufdesc);
+			bzbufdesc = NULL;
+			if (lseek(f->fd, 0, SEEK_SET) == -1)
+				return (-1);
+			nr = read(f->fd, buffer, MAXBUFSIZ);
+			break;
+		default:
+			/* Make sure we exit with an error */
+			nr = -1;
+		}
+	} else
+		nr = read(f->fd, buffer, MAXBUFSIZ);
+
+	if (nr < 0)
+		return (-1);
+
+	bufrem = nr;
+	return (0);
 }
 
-/*
- * Opens the standard input for processing.
- */
-struct file *
-grep_stdin_open(void)
+static inline int
+grep_lnbufgrow(size_t newlen)
 {
-	struct file *f;
 
-	/* Processing stdin implies --line-buffered for tail -f to work. */
-	lbflag = true;
-
-	snprintf(fname, sizeof fname, "%s", getstr(1));
-
-	f = grep_malloc(sizeof *f);
-
-	binbuf = NULL;
-	if ((f->f = fdopen(STDIN_FILENO, "r")) != NULL) {
-		flockfile(f->f);
-		f->stdin = true;
-		return (f);
+	if (lnbuflen < newlen) {
+		lnbuf = grep_realloc(lnbuf, newlen);
+		lnbuflen = newlen;
 	}
 
+	return (0);
+}
+
+char *
+grep_fgetln(struct file *f, size_t *lenp)
+{
+	unsigned char *p;
+	char *ret;
+	size_t len;
+	size_t off;
+	ptrdiff_t diff;
+
+	/* Fill the buffer, if necessary */
+	if (bufrem == 0 && grep_refill(f) != 0)
+		goto error;
+
+	if (bufrem == 0) {
+		/* Return zero length to indicate EOF */
+		*lenp = 0;
+		return (bufpos);
+	}
+
+	/* Look for a newline in the remaining part of the buffer */
+	if ((p = memchr(bufpos, '\n', bufrem)) != NULL) {
+		++p; /* advance over newline */
+		ret = bufpos;
+		len = p - bufpos;
+		bufrem -= len;
+		bufpos = p;
+		*lenp = len;
+		return (ret);
+	}
+
+	/* We have to copy the current buffered data to the line buffer */
+	for (len = bufrem, off = 0; ; len += bufrem) {
+		/* Make sure there is room for more data */
+		if (grep_lnbufgrow(len + LNBUFBUMP))
+			goto error;
+		memcpy(lnbuf + off, bufpos, len - off);
+		off = len;
+		if (grep_refill(f) != 0)
+			goto error;
+		if (bufrem == 0)
+			/* EOF: return partial line */
+			break;
+		if ((p = memchr(bufpos, '\n', bufrem)) == NULL)
+			continue;
+		/* got it: finish up the line (like code above) */
+		++p;
+		diff = p - bufpos;
+		len += diff;
+		if (grep_lnbufgrow(len))
+		    goto error;
+		memcpy(lnbuf + off, bufpos, diff);
+		bufrem -= diff;
+		bufpos = p;
+		break;
+	}
+	*lenp = len;
+	return (lnbuf);
+
+error:
+	*lenp = 0;
+	return (NULL);
+}
+
+static inline struct file *
+grep_file_init(struct file *f)
+{
+
+	if (filebehave == FILE_GZIP &&
+	    (gzbufdesc = gzdopen(f->fd, "r")) == NULL)
+		goto error;
+
+	if (filebehave == FILE_BZIP &&
+	    (bzbufdesc = BZ2_bzdopen(f->fd, "r")) == NULL)
+		goto error;
+
+	/* Fill read buffer, also catches errors early */
+	if (grep_refill(f) != 0)
+		goto error;
+
+	/* Check for binary stuff, if necessary */
+	if (binbehave != BINFILE_TEXT && memchr(bufpos, '\0', bufrem) != NULL)
+		f->binary = true;
+
+	return (f);
+error:
+	close(f->fd);
 	free(f);
 	return (NULL);
 }
 
 /*
- * Opens a normal, a gzipped or a bzip2 compressed file for processing.
+ * Opens a file for processing.
  */
 struct file *
 grep_open(const char *path)
 {
 	struct file *f;
 
-	snprintf(fname, sizeof fname, "%s", path);
-
 	f = grep_malloc(sizeof *f);
-
-	binbuf = NULL;
-	f->stdin = false;
-	switch (filebehave) {
-	case FILE_STDIO:
-		if ((f->f = fopen(path, "r")) != NULL) {
-			flockfile(f->f);
-			return (f);
-		}
-		break;
-	case FILE_GZIP:
-		if ((f->gzf = gzopen(fname, "r")) != NULL)
-			return (f);
-		break;
-	case FILE_BZIP:
-		if ((f->bzf = BZ2_bzopen(fname, "r")) != NULL)
-			return (f);
-		break;
+	memset(f, 0, sizeof *f);
+	if (path == NULL) {
+		/* Processing stdin implies --line-buffered. */
+		lbflag = true;
+		f->fd = STDIN_FILENO;
+	} else if ((f->fd = open(path, O_RDONLY)) == -1) {
+		free(f);
+		return (NULL);
 	}
 
-	free(f);
-	return (NULL);
+	return (grep_file_init(f));
 }
 
 /*
- * Closes a normal, a gzipped or a bzip2 compressed file.
+ * Closes a file.
  */
 void
 grep_close(struct file *f)
 {
 
-	switch (filebehave) {
-	case FILE_STDIO:
-		funlockfile(f->f);
-		fclose(f->f);
-		break;
-	case FILE_GZIP:
-		gzclose(f->gzf);
-		break;
-	case FILE_BZIP:
-		BZ2_bzclose(f->bzf);
-		break;
-	}
+	close(f->fd);
 
-	/* Reset read buffer for the file we are closing */
-	binbufptr = NULL;
-	free(binbuf);
+	/* Reset read buffer and line buffer */
+	bufpos = buffer;
+	bufrem = 0;
+
+	free(lnbuf);
+	lnbuf = NULL;
+	lnbuflen = 0;
 }
diff --git a/usr.bin/grep/grep.h b/usr.bin/grep/grep.h
index 2f743e48142..cf4443dfce5 100644
--- a/usr.bin/grep/grep.h
+++ b/usr.bin/grep/grep.h
@@ -77,12 +77,8 @@ extern const char		*errstr[];
 #define MAX_LINE_MATCHES	32
 
 struct file {
-	struct mmfile	*mmf;
-	BZFILE		*bzf;
-	FILE		*f;
-	gzFile		*gzf;
+	int		 fd;
 	bool		 binary;
-	bool		 stdin;
 };
 
 struct str {
@@ -150,11 +146,10 @@ void	 clearqueue(void);
 
 /* file.c */
 void		 grep_close(struct file *f);
-struct file	*grep_stdin_open(void);
 struct file	*grep_open(const char *path);
 char		*grep_fgetln(struct file *f, size_t *len);
 
 /* fastgrep.c */
 int		 fastcomp(fastgrep_t *, const char *);
 void		 fgrepcomp(fastgrep_t *, const char *);
-int		 grep_search(fastgrep_t *, unsigned char *, size_t, regmatch_t *);
+int		 grep_search(fastgrep_t *, const unsigned char *, size_t, regmatch_t *);
diff --git a/usr.bin/grep/util.c b/usr.bin/grep/util.c
index f084c3da09e..7ebbb5513ce 100644
--- a/usr.bin/grep/util.c
+++ b/usr.bin/grep/util.c
@@ -184,7 +184,7 @@ procfile(const char *fn)
 
 	if (strcmp(fn, "-") == 0) {
 		fn = label != NULL ? label : getstr(1);
-		f = grep_stdin_open();
+		f = grep_open(NULL);
 	} else {
 		if (!stat(fn, &sb)) {
 			/* Check if we need to process the file */
@@ -215,7 +215,7 @@ procfile(const char *fn)
 
 	for (c = 0;  c == 0 || !(lflag || qflag); ) {
 		ln.off += ln.len + 1;
-		if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL) {
+		if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
 			if (ln.line_no == 0 && matchall)
 				exit(0);
 			else

From c3f0bdc66bef575e021207038b18f2ee3ac173db Mon Sep 17 00:00:00 2001
From: Andre Oppermann 
Date: Wed, 18 Aug 2010 18:05:54 +0000
Subject: [PATCH 0062/1624] If a TCP connection has been idle for one
 retransmit timeout or more it must reset its congestion window back to the
 initial window.

RFC3390 has increased the initial window from 1 segment to up to
4 segments.

The initial window increase of RFC3390 wasn't reflected into the
restart window which remained at its original defaults of 4 segments
for local and 1 segment for all other connections.  Both values are
controllable through sysctl net.inet.tcp.local_slowstart_flightsize
and net.inet.tcp.slowstart_flightsize.

The increase helps TCP's slow start algorithm to open up the congestion
window much faster.

Reviewed by:	lstewart
MFC after:	1 week
---
 sys/netinet/tcp_output.c | 41 +++++++++++++++++++++++++---------------
 sys/netinet/tcp_var.h    |  2 ++
 2 files changed, 28 insertions(+), 15 deletions(-)

diff --git a/sys/netinet/tcp_output.c b/sys/netinet/tcp_output.c
index be8ea534ee0..50d0ee6a4cd 100644
--- a/sys/netinet/tcp_output.c
+++ b/sys/netinet/tcp_output.c
@@ -140,7 +140,7 @@ tcp_output(struct tcpcb *tp)
 {
 	struct socket *so = tp->t_inpcb->inp_socket;
 	long len, recwin, sendwin;
-	int off, flags, error;
+	int off, flags, error, rw;
 	struct mbuf *m;
 	struct ip *ip = NULL;
 	struct ipovly *ipov = NULL;
@@ -176,23 +176,34 @@ tcp_output(struct tcpcb *tp)
 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
 	if (idle && ticks - tp->t_rcvtime >= tp->t_rxtcur) {
 		/*
-		 * We have been idle for "a while" and no acks are
-		 * expected to clock out any data we send --
-		 * slow start to get ack "clock" running again.
+		 * If we've been idle for more than one retransmit
+		 * timeout the old congestion window is no longer
+		 * current and we have to reduce it to the restart
+		 * window before we can transmit again.
 		 *
-		 * Set the slow-start flight size depending on whether
-		 * this is a local network or not.
+		 * The restart window is the initial window or the last
+		 * CWND, whichever is smaller.
+		 * 
+		 * This is done to prevent us from flooding the path with
+		 * a full CWND at wirespeed, overloading router and switch
+		 * buffers along the way.
+		 *
+		 * See RFC5681 Section 4.1. "Restarting Idle Connections".
 		 */
-		int ss = V_ss_fltsz;
+		if (V_tcp_do_rfc3390)
+			rw = min(4 * tp->t_maxseg,
+				 max(2 * tp->t_maxseg, 4380));
 #ifdef INET6
-		if (isipv6) {
-			if (in6_localaddr(&tp->t_inpcb->in6p_faddr))
-				ss = V_ss_fltsz_local;
-		} else
-#endif /* INET6 */
-		if (in_localaddr(tp->t_inpcb->inp_faddr))
-			ss = V_ss_fltsz_local;
-		tp->snd_cwnd = tp->t_maxseg * ss;
+		else if ((isipv6 ? in6_localaddr(&tp->t_inpcb->in6p_faddr) :
+			  in_localaddr(tp->t_inpcb->inp_faddr)))
+#else
+		else if (in_localaddr(tp->t_inpcb->inp_faddr))
+#endif
+			rw = V_ss_fltsz_local * tp->t_maxseg;
+		else
+			rw = V_ss_fltsz * tp->t_maxseg;
+
+		tp->snd_cwnd = min(rw, tp->snd_cwnd);
 	}
 	tp->t_flags &= ~TF_LASTIDLE;
 	if (idle) {
diff --git a/sys/netinet/tcp_var.h b/sys/netinet/tcp_var.h
index 7482277be29..b753e105ee5 100644
--- a/sys/netinet/tcp_var.h
+++ b/sys/netinet/tcp_var.h
@@ -565,6 +565,7 @@ extern	int tcp_log_in_vain;
 VNET_DECLARE(int, tcp_mssdflt);	/* XXX */
 VNET_DECLARE(int, tcp_minmss);
 VNET_DECLARE(int, tcp_delack_enabled);
+VNET_DECLARE(int, tcp_do_rfc3390);
 VNET_DECLARE(int, tcp_do_newreno);
 VNET_DECLARE(int, path_mtu_discovery);
 VNET_DECLARE(int, ss_fltsz);
@@ -575,6 +576,7 @@ VNET_DECLARE(int, ss_fltsz_local);
 #define	V_tcp_mssdflt		VNET(tcp_mssdflt)
 #define	V_tcp_minmss		VNET(tcp_minmss)
 #define	V_tcp_delack_enabled	VNET(tcp_delack_enabled)
+#define	V_tcp_do_rfc3390	VNET(tcp_do_rfc3390)
 #define	V_tcp_do_newreno	VNET(tcp_do_newreno)
 #define	V_path_mtu_discovery	VNET(path_mtu_discovery)
 #define	V_ss_fltsz		VNET(ss_fltsz)

From 44510b41ff91fb130f995e87365011e3278c69b0 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Wed, 18 Aug 2010 20:26:50 +0000
Subject: [PATCH 0063/1624] sh: Add a test for break from a trap action.

---
 tools/regression/bin/sh/builtins/break2.0        | 12 ++++++++++++
 tools/regression/bin/sh/builtins/break2.0.stdout |  1 +
 2 files changed, 13 insertions(+)
 create mode 100644 tools/regression/bin/sh/builtins/break2.0
 create mode 100644 tools/regression/bin/sh/builtins/break2.0.stdout

diff --git a/tools/regression/bin/sh/builtins/break2.0 b/tools/regression/bin/sh/builtins/break2.0
new file mode 100644
index 00000000000..ff52dd32146
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/break2.0
@@ -0,0 +1,12 @@
+# $FreeBSD$
+
+# It is not immediately obvious that this should work, and someone probably
+# relies on it.
+
+while :; do
+	trap 'break' USR1
+	kill -USR1 $$
+	echo bad
+	exit 1
+done
+echo good
diff --git a/tools/regression/bin/sh/builtins/break2.0.stdout b/tools/regression/bin/sh/builtins/break2.0.stdout
new file mode 100644
index 00000000000..12799ccbe7c
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/break2.0.stdout
@@ -0,0 +1 @@
+good

From af8ec89da4861848686fd42ec962672defc71d50 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 18 Aug 2010 22:06:43 +0000
Subject: [PATCH 0064/1624] More tests.

---
 tools/regression/pjdfstest/tests/chflags/01.t | 10 +++---
 tools/regression/pjdfstest/tests/chmod/01.t   | 10 +++---
 tools/regression/pjdfstest/tests/chmod/06.t   |  6 ++--
 tools/regression/pjdfstest/tests/chown/01.t   | 12 ++++---
 tools/regression/pjdfstest/tests/link/01.t    | 16 +++++----
 tools/regression/pjdfstest/tests/link/10.t    | 26 ++++++--------
 tools/regression/pjdfstest/tests/mkdir/01.t   | 10 +++---
 tools/regression/pjdfstest/tests/mkfifo/01.t  | 10 +++---
 tools/regression/pjdfstest/tests/mkfifo/09.t  | 26 ++++++--------
 tools/regression/pjdfstest/tests/mknod/01.t   | 12 ++++---
 tools/regression/pjdfstest/tests/mknod/08.t   | 36 +++++++------------
 tools/regression/pjdfstest/tests/open/01.t    | 11 +++---
 tools/regression/pjdfstest/tests/rename/12.t  | 16 +++++----
 tools/regression/pjdfstest/tests/rmdir/06.t   | 32 ++++++-----------
 tools/regression/pjdfstest/tests/symlink/08.t | 22 ++++++------
 15 files changed, 120 insertions(+), 135 deletions(-)

diff --git a/tools/regression/pjdfstest/tests/chflags/01.t b/tools/regression/pjdfstest/tests/chflags/01.t
index 029ee4688ec..b71951bb71f 100644
--- a/tools/regression/pjdfstest/tests/chflags/01.t
+++ b/tools/regression/pjdfstest/tests/chflags/01.t
@@ -8,13 +8,15 @@ dir=`dirname $0`
 
 require chflags
 
-echo "1..5"
+echo "1..17"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR chflags ${n0}/${n1}/test SF_IMMUTABLE
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR chflags ${n0}/${n1}/test SF_IMMUTABLE
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/chmod/01.t b/tools/regression/pjdfstest/tests/chmod/01.t
index 469daa47bd9..49164e71585 100644
--- a/tools/regression/pjdfstest/tests/chmod/01.t
+++ b/tools/regression/pjdfstest/tests/chmod/01.t
@@ -6,13 +6,15 @@ desc="chmod returns ENOTDIR if a component of the path prefix is not a directory
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..5"
+echo "1..17"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR chmod ${n0}/${n1}/test 0644
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR chmod ${n0}/${n1}/test 0644
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/chmod/06.t b/tools/regression/pjdfstest/tests/chmod/06.t
index 8abdb0a82ad..c06fe2bb59f 100644
--- a/tools/regression/pjdfstest/tests/chmod/06.t
+++ b/tools/regression/pjdfstest/tests/chmod/06.t
@@ -7,9 +7,9 @@ dir=`dirname $0`
 . ${dir}/../misc.sh
 
 if supported lchmod; then
-	echo "1..8"
+	echo "1..10"
 else
-	echo "1..6"
+	echo "1..8"
 fi
 
 n0=`namegen`
@@ -17,6 +17,8 @@ n1=`namegen`
 
 expect 0 symlink ${n0} ${n1}
 expect 0 symlink ${n1} ${n0}
+expect ELOOP chmod ${n0} 0644
+expect ELOOP chmod ${n1} 0644
 expect ELOOP chmod ${n0}/test 0644
 expect ELOOP chmod ${n1}/test 0644
 if supported lchmod; then
diff --git a/tools/regression/pjdfstest/tests/chown/01.t b/tools/regression/pjdfstest/tests/chown/01.t
index d410f5dff70..249ce4de4c9 100644
--- a/tools/regression/pjdfstest/tests/chown/01.t
+++ b/tools/regression/pjdfstest/tests/chown/01.t
@@ -6,14 +6,16 @@ desc="chown returns ENOTDIR if a component of the path prefix is not a directory
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..6"
+echo "1..22"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR chown ${n0}/${n1}/test 65534 65534
-expect ENOTDIR lchown ${n0}/${n1}/test 65534 65534
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR chown ${n0}/${n1}/test 65534 65534
+	expect ENOTDIR lchown ${n0}/${n1}/test 65534 65534
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/link/01.t b/tools/regression/pjdfstest/tests/link/01.t
index 9a740ed9451..94009010d4d 100644
--- a/tools/regression/pjdfstest/tests/link/01.t
+++ b/tools/regression/pjdfstest/tests/link/01.t
@@ -6,17 +6,19 @@ desc="link returns ENOTDIR if a component of either path prefix is not a directo
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..8"
+echo "1..32"
 
 n0=`namegen`
 n1=`namegen`
 n2=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR link ${n0}/${n1}/test ${n0}/${n2}
-expect 0 create ${n0}/${n2} 0644
-expect ENOTDIR link ${n0}/${n2} ${n0}/${n1}/test
-expect 0 unlink ${n0}/${n1}
-expect 0 unlink ${n0}/${n2}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR link ${n0}/${n1}/test ${n0}/${n2}
+	create_file ${type} ${n0}/${n2}
+	expect ENOTDIR link ${n0}/${n2} ${n0}/${n1}/test
+	expect 0 unlink ${n0}/${n1}
+	expect 0 unlink ${n0}/${n2}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/link/10.t b/tools/regression/pjdfstest/tests/link/10.t
index beb141c81d8..725a020d7a2 100644
--- a/tools/regression/pjdfstest/tests/link/10.t
+++ b/tools/regression/pjdfstest/tests/link/10.t
@@ -6,27 +6,21 @@ desc="link returns EEXIST if the destination file does exist"
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..14"
+echo "1..23"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 create ${n0} 0644
 
-expect 0 create ${n1} 0644
-expect EEXIST link ${n0} ${n1}
-expect 0 unlink ${n1}
-
-expect 0 mkdir ${n1} 0755
-expect EEXIST link ${n0} ${n1}
-expect 0 rmdir ${n1}
-
-expect 0 symlink test ${n1}
-expect EEXIST link ${n0} ${n1}
-expect 0 unlink ${n1}
-
-expect 0 mkfifo ${n1} 0644
-expect EEXIST link ${n0} ${n1}
-expect 0 unlink ${n1}
+for type in regular dir fifo block char socket symlink; do
+	create_file ${type} ${n1}
+	expect EEXIST link ${n0} ${n1}
+	if [ "${type}" = "dir" ]; then
+		expect 0 rmdir ${n1}
+	else
+		expect 0 unlink ${n1}
+	fi
+done
 
 expect 0 unlink ${n0}
diff --git a/tools/regression/pjdfstest/tests/mkdir/01.t b/tools/regression/pjdfstest/tests/mkdir/01.t
index 43717e64847..c1de087079c 100644
--- a/tools/regression/pjdfstest/tests/mkdir/01.t
+++ b/tools/regression/pjdfstest/tests/mkdir/01.t
@@ -6,13 +6,15 @@ desc="mkdir returns ENOTDIR if a component of the path prefix is not a directory
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..5"
+echo "1..17"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR mkdir ${n0}/${n1}/test 0755
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR mkdir ${n0}/${n1}/test 0755
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/mkfifo/01.t b/tools/regression/pjdfstest/tests/mkfifo/01.t
index 69bfff58265..1c6193b1867 100644
--- a/tools/regression/pjdfstest/tests/mkfifo/01.t
+++ b/tools/regression/pjdfstest/tests/mkfifo/01.t
@@ -6,13 +6,15 @@ desc="mkfifo returns ENOTDIR if a component of the path prefix is not a director
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..5"
+echo "1..17"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR mkfifo ${n0}/${n1}/test 0644
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR mkfifo ${n0}/${n1}/test 0644
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/mkfifo/09.t b/tools/regression/pjdfstest/tests/mkfifo/09.t
index 102e12bae65..6b2015e28f3 100644
--- a/tools/regression/pjdfstest/tests/mkfifo/09.t
+++ b/tools/regression/pjdfstest/tests/mkfifo/09.t
@@ -6,22 +6,16 @@ desc="mkfifo returns EEXIST if the named file exists"
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..12"
+echo "1..21"
 
 n0=`namegen`
 
-expect 0 mkdir ${n0} 0755
-expect EEXIST mkfifo ${n0} 0644
-expect 0 rmdir ${n0}
-
-expect 0 create ${n0} 0644
-expect EEXIST mkfifo ${n0} 0644
-expect 0 unlink ${n0}
-
-expect 0 symlink test ${n0}
-expect EEXIST mkfifo ${n0} 0644
-expect 0 unlink ${n0}
-
-expect 0 mkfifo ${n0} 0644
-expect EEXIST mkfifo ${n0} 0644
-expect 0 unlink ${n0}
+for type in regular dir fifo block char socket symlink; do
+	create_file ${type} ${n0}
+	expect EEXIST mkfifo ${n0} 0644
+	if [ "${type}" = "dir" ]; then
+		expect 0 rmdir ${n0}
+	else
+		expect 0 unlink ${n0}
+	fi
+done
diff --git a/tools/regression/pjdfstest/tests/mknod/01.t b/tools/regression/pjdfstest/tests/mknod/01.t
index dc3609375b6..bc2b658417b 100644
--- a/tools/regression/pjdfstest/tests/mknod/01.t
+++ b/tools/regression/pjdfstest/tests/mknod/01.t
@@ -6,13 +6,17 @@ desc="mknod returns ENOTDIR if a component of the path prefix is not a directory
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..5"
+echo "1..27"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR mknod ${n0}/${n1}/test f 0644 0 0
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR mknod ${n0}/${n1}/test b 0644 1 2
+	expect ENOTDIR mknod ${n0}/${n1}/test c 0644 1 2
+	expect ENOTDIR mknod ${n0}/${n1}/test f 0644 0 0
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/mknod/08.t b/tools/regression/pjdfstest/tests/mknod/08.t
index 6eb0fda2ae2..47d001073c9 100644
--- a/tools/regression/pjdfstest/tests/mknod/08.t
+++ b/tools/regression/pjdfstest/tests/mknod/08.t
@@ -6,30 +6,18 @@ desc="mknod returns EEXIST if the named file exists"
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..18"
+echo "1..35"
 
 n0=`namegen`
 
-expect 0 mkdir ${n0} 0755
-expect EEXIST mknod ${n0} f 0644 0 0
-expect 0 rmdir ${n0}
-
-expect 0 create ${n0} 0644
-expect EEXIST mknod ${n0} f 0644 0 0
-expect 0 unlink ${n0}
-
-expect 0 symlink test ${n0}
-expect EEXIST mknod ${n0} f 0644 0 0
-expect 0 unlink ${n0}
-
-expect 0 mkfifo ${n0} 0644
-expect EEXIST mknod ${n0} f 0644 0 0
-expect 0 unlink ${n0}
-
-expect 0 bind ${n0}
-expect EEXIST mknod ${n0} f 0644 0 0
-expect 0 unlink ${n0}
-
-expect 0 mknod ${n0} f 0644 0 0
-expect EEXIST mknod ${n0} f 0644 0 0
-expect 0 unlink ${n0}
+for type in regular dir fifo block char socket symlink; do
+	create_file ${type} ${n0}
+	expect EEXIST mknod ${n0} b 0644 0 0
+	expect EEXIST mknod ${n0} c 0644 0 0
+	expect EEXIST mknod ${n0} f 0644 0 0
+	if [ "${type}" = "dir" ]; then
+		expect 0 rmdir ${n0}
+	else
+		expect 0 unlink ${n0}
+	fi
+done
diff --git a/tools/regression/pjdfstest/tests/open/01.t b/tools/regression/pjdfstest/tests/open/01.t
index 39446baf758..6dfc6f54b2a 100644
--- a/tools/regression/pjdfstest/tests/open/01.t
+++ b/tools/regression/pjdfstest/tests/open/01.t
@@ -6,13 +6,16 @@ desc="open returns ENOTDIR if a component of the path prefix is not a directory"
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..5"
+echo "1..22"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR open ${n0}/${n1}/test O_CREAT 0644
-expect 0 unlink ${n0}/${n1}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR open ${n0}/${n1}/test O_RDONLY
+	expect ENOTDIR open ${n0}/${n1}/test O_CREAT 0644
+	expect 0 unlink ${n0}/${n1}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/rename/12.t b/tools/regression/pjdfstest/tests/rename/12.t
index 504980ca512..4383d843b62 100644
--- a/tools/regression/pjdfstest/tests/rename/12.t
+++ b/tools/regression/pjdfstest/tests/rename/12.t
@@ -6,17 +6,19 @@ desc="rename returns ENOTDIR if a component of either path prefix is not a direc
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..8"
+echo "1..32"
 
 n0=`namegen`
 n1=`namegen`
 n2=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect ENOTDIR rename ${n0}/${n1}/test ${n0}/${n2}
-expect 0 create ${n0}/${n2} 0644
-expect ENOTDIR link ${n0}/${n2} ${n0}/${n1}/test
-expect 0 unlink ${n0}/${n1}
-expect 0 unlink ${n0}/${n2}
+for type in regular fifo block char socket; do
+	create_file ${type} ${n0}/${n1}
+	expect ENOTDIR rename ${n0}/${n1}/test ${n0}/${n2}
+	create_file ${type} ${n0}/${n2}
+	expect ENOTDIR link ${n0}/${n2} ${n0}/${n1}/test
+	expect 0 unlink ${n0}/${n1}
+	expect 0 unlink ${n0}/${n2}
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/rmdir/06.t b/tools/regression/pjdfstest/tests/rmdir/06.t
index dbb378b02c1..9de34b0e1d6 100644
--- a/tools/regression/pjdfstest/tests/rmdir/06.t
+++ b/tools/regression/pjdfstest/tests/rmdir/06.t
@@ -6,31 +6,19 @@ desc="rmdir returns EEXIST or ENOTEMPTY the named directory contains files other
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..20"
+echo "1..23"
 
 n0=`namegen`
 n1=`namegen`
 
 expect 0 mkdir ${n0} 0755
-expect 0 mkdir ${n0}/${n1} 0755
-expect "EEXIST|ENOTEMPTY" rmdir ${n0}
-expect 0 rmdir ${n0}/${n1}
-expect 0 rmdir ${n0}
-
-expect 0 mkdir ${n0} 0755
-expect 0 create ${n0}/${n1} 0644
-expect "EEXIST|ENOTEMPTY" rmdir ${n0}
-expect 0 unlink ${n0}/${n1}
-expect 0 rmdir ${n0}
-
-expect 0 mkdir ${n0} 0755
-expect 0 symlink test ${n0}/${n1}
-expect "EEXIST|ENOTEMPTY" rmdir ${n0}
-expect 0 unlink ${n0}/${n1}
-expect 0 rmdir ${n0}
-
-expect 0 mkdir ${n0} 0755
-expect 0 mkfifo ${n0}/${n1} 0644
-expect "EEXIST|ENOTEMPTY" rmdir ${n0}
-expect 0 unlink ${n0}/${n1}
+for type in regular dir fifo block char socket symlink; do
+	create_file ${type} ${n0}/${n1}
+	expect "EEXIST|ENOTEMPTY" rmdir ${n0}
+	if [ "${type}" = "dir" ]; then
+		expect 0 rmdir ${n0}/${n1}
+	else
+		expect 0 unlink ${n0}/${n1}
+	fi
+done
 expect 0 rmdir ${n0}
diff --git a/tools/regression/pjdfstest/tests/symlink/08.t b/tools/regression/pjdfstest/tests/symlink/08.t
index c4843e5aaed..9d539f16648 100644
--- a/tools/regression/pjdfstest/tests/symlink/08.t
+++ b/tools/regression/pjdfstest/tests/symlink/08.t
@@ -6,18 +6,16 @@ desc="symlink returns EEXIST if the name2 argument already exists"
 dir=`dirname $0`
 . ${dir}/../misc.sh
 
-echo "1..9"
+echo "1..21"
 
 n0=`namegen`
 
-expect 0 create ${n0} 0644
-expect EEXIST symlink test ${n0}
-expect 0 unlink ${n0}
-
-expect 0 mkdir ${n0} 0755
-expect EEXIST symlink test ${n0}
-expect 0 rmdir ${n0}
-
-expect 0 symlink test ${n0}
-expect EEXIST symlink test ${n0}
-expect 0 unlink ${n0}
+for type in regular dir fifo block char socket symlink; do
+	create_file ${type} ${n0}
+	expect EEXIST symlink test ${n0}
+	if [ "${type}" = "dir" ]; then
+		expect 0 rmdir ${n0}
+	else
+		expect 0 unlink ${n0}
+	fi
+done

From c38fa7e016711fbb846c355ea567a2d6ab52ee3c Mon Sep 17 00:00:00 2001
From: Xin LI 
Date: Thu, 19 Aug 2010 01:34:00 +0000
Subject: [PATCH 0065/1624] Check return value of dup(), it could be -1 when
 the system is running out of file descriptors for instance.

Found with:	Coverity Prevent(tm)
CID:		6084
MFC after:	1 month
---
 usr.bin/gzip/unpack.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/usr.bin/gzip/unpack.c b/usr.bin/gzip/unpack.c
index aa1480016d2..cc717a6a95e 100644
--- a/usr.bin/gzip/unpack.c
+++ b/usr.bin/gzip/unpack.c
@@ -312,7 +312,14 @@ unpack(int in, int out, char *pre, size_t prelen, off_t *bytes_in)
 {
 	unpack_descriptor_t	unpackd;
 
-	unpack_parse_header(dup(in), dup(out), pre, prelen, bytes_in, &unpackd);
+	in = dup(in);
+	if (in == -1)
+		maybe_err("dup");
+	out = dup(out);
+	if (out == -1)
+		maybe_err("dup");
+
+	unpack_parse_header(in, out, pre, prelen, bytes_in, &unpackd);
 	unpack_decode(&unpackd, bytes_in);
 	unpack_descriptor_fini(&unpackd);
 

From 70bd9230d19e185a23830eee17922f0839017900 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:03:12 +0000
Subject: [PATCH 0066/1624] Preparation work for supporting the AR91xx and
 AR724x.

* Implement a SoC probe function, from Linux, which determines the
  SoC family, type and revision. This only probes the AR71xx series
  SoC and (currently) panics on others.

* Migrate some of the AR71XX specific hardware init (USB device, determining
  system frequencies) into using the cpuops introduced in an earlier commit.
  Other SoC specific hardware stuff (per-device flush/WB, GPIO pin wiring,
  Ethernet PLL setup, other things I've likely missed) will be introduced in
  subsequent commits.

Reviewed by:	imp@
Obtained from:	(partially) Linux
---
 sys/mips/atheros/ar71xx_chip.c     | 180 +++++++++++++++++++++++++++++
 sys/mips/atheros/ar71xx_chip.h     |  34 ++++++
 sys/mips/atheros/ar71xx_machdep.c  |  13 +++
 sys/mips/atheros/ar71xx_setup.c    | 119 +++++++++++++++++++
 sys/mips/atheros/ar71xx_setup.h    |  48 ++++++++
 sys/mips/atheros/ar71xx_wdog.c     |   1 +
 sys/mips/atheros/ar71xxreg.h       |  50 +++-----
 sys/mips/atheros/files.ar71xx      |   2 +
 sys/mips/atheros/uart_bus_ar71xx.c |   1 +
 sys/mips/atheros/uart_cpu_ar71xx.c |   1 +
 10 files changed, 417 insertions(+), 32 deletions(-)
 create mode 100644 sys/mips/atheros/ar71xx_chip.c
 create mode 100644 sys/mips/atheros/ar71xx_chip.h
 create mode 100644 sys/mips/atheros/ar71xx_setup.c
 create mode 100644 sys/mips/atheros/ar71xx_setup.h

diff --git a/sys/mips/atheros/ar71xx_chip.c b/sys/mips/atheros/ar71xx_chip.c
new file mode 100644
index 00000000000..ae6340df6ec
--- /dev/null
+++ b/sys/mips/atheros/ar71xx_chip.c
@@ -0,0 +1,180 @@
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+
+#include 
+
+#include "opt_ddb.h"
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+ 
+#include 
+ 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+
+#include 
+
+#include 
+
+/* XXX these should replace the current definitions in ar71xxreg.h */
+/* XXX perhaps an ar71xx_chip.h header file? */
+#define AR71XX_PLL_REG_CPU_CONFIG       AR71XX_PLL_CPU_BASE + 0x00
+#define AR71XX_PLL_REG_SEC_CONFIG       AR71XX_PLL_CPU_BASE + 0x04
+#define AR71XX_PLL_REG_ETH0_INT_CLOCK   AR71XX_PLL_CPU_BASE + 0x10
+#define AR71XX_PLL_REG_ETH1_INT_CLOCK   AR71XX_PLL_CPU_BASE + 0x14
+
+#define AR71XX_PLL_DIV_SHIFT            3
+#define AR71XX_PLL_DIV_MASK             0x1f
+#define AR71XX_CPU_DIV_SHIFT            16
+#define AR71XX_CPU_DIV_MASK             0x3
+#define AR71XX_DDR_DIV_SHIFT            18
+#define AR71XX_DDR_DIV_MASK             0x3
+#define AR71XX_AHB_DIV_SHIFT            20
+#define AR71XX_AHB_DIV_MASK             0x7
+
+#define AR71XX_ETH0_PLL_SHIFT           17
+#define AR71XX_ETH1_PLL_SHIFT           19
+
+/* XXX these shouldn't be in here - this file is a per-chip file */
+/* XXX these should be in the top-level ar71xx type, not ar71xx -chip */
+uint32_t u_ar71xx_cpu_freq;
+uint32_t u_ar71xx_ahb_freq;
+uint32_t u_ar71xx_ddr_freq;
+
+static void
+ar71xx_chip_detect_mem_size(void)
+{
+}
+
+static void
+ar71xx_chip_detect_sys_frequency(void)
+{
+	uint32_t pll;
+	uint32_t freq;
+	uint32_t div;
+
+	pll = ATH_READ_REG(AR71XX_PLL_REG_CPU_CONFIG);
+
+	div = ((pll >> AR71XX_PLL_DIV_SHIFT) & AR71XX_PLL_DIV_MASK) + 1;
+	freq = div * AR71XX_BASE_FREQ;
+
+	div = ((pll >> AR71XX_CPU_DIV_SHIFT) & AR71XX_CPU_DIV_MASK) + 1;
+	u_ar71xx_cpu_freq = freq / div;
+
+	div = ((pll >> AR71XX_DDR_DIV_SHIFT) & AR71XX_DDR_DIV_MASK) + 1;
+	u_ar71xx_ddr_freq = freq / div;
+
+	div = (((pll >> AR71XX_AHB_DIV_SHIFT) & AR71XX_AHB_DIV_MASK) + 1) * 2;
+	u_ar71xx_ahb_freq = u_ar71xx_cpu_freq / div;
+}
+
+/*
+ * This does not lock the CPU whilst doing the work!
+ */
+static void
+ar71xx_chip_device_stop(uint32_t mask)
+{
+	uint32_t reg;
+
+	reg = ATH_READ_REG(AR71XX_RST_RESET);
+	ATH_WRITE_REG(AR71XX_RST_RESET, reg | mask);
+}
+
+static void
+ar71xx_chip_device_start(uint32_t mask)
+{
+	uint32_t reg;
+
+	reg = ATH_READ_REG(AR71XX_RST_RESET);
+	ATH_WRITE_REG(AR71XX_RST_RESET, reg & ~mask);
+}
+
+static int
+ar71xx_chip_device_stopped(uint32_t mask)
+{
+	uint32_t reg;
+
+	reg = ATH_READ_REG(AR71XX_RST_RESET);
+        return ((reg & mask) == mask);
+}
+
+static void
+ar71xx_chip_set_pll_ge0(int speed)
+{
+}
+
+static void
+ar71xx_chip_set_pll_ge1(int speed)
+{
+}
+
+static void
+ar71xx_chip_ddr_flush_ge0(void)
+{
+	ar71xx_ddr_flush(AR71XX_WB_FLUSH_GE0);
+}
+
+static void
+ar71xx_chip_ddr_flush_ge1(void)
+{
+	ar71xx_ddr_flush(AR71XX_WB_FLUSH_GE1);
+}
+
+static uint32_t
+ar71xx_chip_get_eth_pll(unsigned int mac, int speed)
+{
+	return 0;
+}
+
+static void
+ar71xx_chip_init_usb_peripheral(void)
+{
+	ar71xx_device_stop(RST_RESET_USB_OHCI_DLL | RST_RESET_USB_HOST | RST_RESET_USB_PHY);
+	DELAY(1000);
+
+	ar71xx_device_start(RST_RESET_USB_OHCI_DLL | RST_RESET_USB_HOST | RST_RESET_USB_PHY);
+	DELAY(1000);
+
+	ATH_WRITE_REG(AR71XX_USB_CTRL_CONFIG,
+	    USB_CTRL_CONFIG_OHCI_DES_SWAP | USB_CTRL_CONFIG_OHCI_BUF_SWAP |
+	    USB_CTRL_CONFIG_EHCI_DES_SWAP | USB_CTRL_CONFIG_EHCI_BUF_SWAP);
+
+	ATH_WRITE_REG(AR71XX_USB_CTRL_FLADJ,
+	    (32 << USB_CTRL_FLADJ_HOST_SHIFT) | (3 << USB_CTRL_FLADJ_A5_SHIFT));
+
+	DELAY(1000);
+}
+
+struct ar71xx_cpu_def ar71xx_chip_def = {
+	&ar71xx_chip_detect_mem_size,
+	&ar71xx_chip_detect_sys_frequency,
+	&ar71xx_chip_device_stop,
+	&ar71xx_chip_device_start,
+	&ar71xx_chip_device_stopped,
+	&ar71xx_chip_set_pll_ge0,
+	&ar71xx_chip_set_pll_ge1,
+	&ar71xx_chip_ddr_flush_ge0,
+	&ar71xx_chip_ddr_flush_ge1,
+	&ar71xx_chip_get_eth_pll,
+	NULL,
+	&ar71xx_chip_init_usb_peripheral,
+};
diff --git a/sys/mips/atheros/ar71xx_chip.h b/sys/mips/atheros/ar71xx_chip.h
new file mode 100644
index 00000000000..ccecc23294e
--- /dev/null
+++ b/sys/mips/atheros/ar71xx_chip.h
@@ -0,0 +1,34 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR71XX_CHIP_H__
+#define	__AR71XX_CHIP_H__
+
+extern struct ar71xx_cpu_def ar71xx_chip_def;
+
+#endif
diff --git a/sys/mips/atheros/ar71xx_machdep.c b/sys/mips/atheros/ar71xx_machdep.c
index 6cb68cefcca..a390167f0ad 100644
--- a/sys/mips/atheros/ar71xx_machdep.c
+++ b/sys/mips/atheros/ar71xx_machdep.c
@@ -57,6 +57,9 @@ __FBSDID("$FreeBSD$");
 
 #include 
 
+#include 
+#include 
+
 extern char edata[], end[];
 
 uint32_t ar711_base_mac[ETHER_ADDR_LEN];
@@ -202,11 +205,21 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused,
 	 * should be called first.
 	 */
 	init_param1();
+
+	/* Detect the system type - this is needed for subsequent chipset-specific calls */
+	ar71xx_detect_sys_type();
+	ar71xx_detect_sys_frequency();
+
 	platform_counter_freq = ar71xx_cpu_freq();
 	mips_timer_init_params(platform_counter_freq, 1);
 	cninit();
 	init_static_kenv(boot1_env, sizeof(boot1_env));
 
+	printf("CPU platform: %s\n", ar71xx_get_system_type());
+	printf("CPU Frequency=%d MHz\n", u_ar71xx_cpu_freq / 1000000);
+	printf("CPU DDR Frequency=%d MHz\n", u_ar71xx_ddr_freq / 1000000);
+	printf("CPU AHB Frequency=%d MHz\n", u_ar71xx_ahb_freq / 1000000); 
+
 	printf("platform frequency: %lld\n", platform_counter_freq);
 	printf("arguments: \n");
 	printf("  a0 = %08x\n", a0);
diff --git a/sys/mips/atheros/ar71xx_setup.c b/sys/mips/atheros/ar71xx_setup.c
new file mode 100644
index 00000000000..bce383efe1b
--- /dev/null
+++ b/sys/mips/atheros/ar71xx_setup.c
@@ -0,0 +1,119 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+
+#include 
+
+#include "opt_ddb.h"
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+ 
+#include 
+ 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+
+#include 
+
+#include 
+
+#define	AR71XX_SYS_TYPE_LEN		128
+
+static char ar71xx_sys_type[AR71XX_SYS_TYPE_LEN];
+enum ar71xx_soc_type ar71xx_soc;
+struct ar71xx_cpu_def * ar71xx_cpu_ops = NULL;
+
+void
+ar71xx_detect_sys_type(void)
+{
+	char *chip = "????";
+	uint32_t id;
+	uint32_t major;
+	uint32_t minor;
+	uint32_t rev = 0;
+
+	id = ATH_READ_REG(AR71XX_RST_RESET_REG_REV_ID);
+	major = id & REV_ID_MAJOR_MASK;
+
+	switch (major) {
+	case REV_ID_MAJOR_AR71XX:
+		minor = id & AR71XX_REV_ID_MINOR_MASK;
+		rev = id >> AR71XX_REV_ID_REVISION_SHIFT;
+		rev &= AR71XX_REV_ID_REVISION_MASK;
+		ar71xx_cpu_ops	= &ar71xx_chip_def;
+		switch (minor) {
+		case AR71XX_REV_ID_MINOR_AR7130:
+			ar71xx_soc = AR71XX_SOC_AR7130;
+			chip = "7130";
+			break;
+
+		case AR71XX_REV_ID_MINOR_AR7141:
+			ar71xx_soc = AR71XX_SOC_AR7141;
+			chip = "7141";
+			break;
+
+		case AR71XX_REV_ID_MINOR_AR7161:
+			ar71xx_soc = AR71XX_SOC_AR7161;
+			chip = "7161";
+			break;
+		}
+		break;
+
+	default:
+		panic("ar71xx: unknown chip id:0x%08x\n", id);
+	}
+
+	sprintf(ar71xx_sys_type, "Atheros AR%s rev %u", chip, rev);
+}
+
+const char *
+ar71xx_get_system_type(void)
+{
+	return ar71xx_sys_type;
+}
+
diff --git a/sys/mips/atheros/ar71xx_setup.h b/sys/mips/atheros/ar71xx_setup.h
new file mode 100644
index 00000000000..89f2490349f
--- /dev/null
+++ b/sys/mips/atheros/ar71xx_setup.h
@@ -0,0 +1,48 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR71XX_SETUP_H__
+#define	__AR71XX_SETUP_H__
+
+enum ar71xx_soc_type {
+	AR71XX_SOC_UNKNOWN,
+	AR71XX_SOC_AR7130,
+	AR71XX_SOC_AR7141,
+	AR71XX_SOC_AR7161,
+	AR71XX_SOC_AR7240,
+	AR71XX_SOC_AR7241,
+	AR71XX_SOC_AR7242,
+	AR71XX_SOC_AR9130,
+	AR71XX_SOC_AR9132
+};
+extern enum ar71xx_soc_type ar71xx_soc;   
+
+extern void ar71xx_detect_sys_type(void);
+extern const char *ar71xx_get_system_type(void);
+
+#endif
diff --git a/sys/mips/atheros/ar71xx_wdog.c b/sys/mips/atheros/ar71xx_wdog.c
index 450b9ebfacb..d582f18fdc3 100644
--- a/sys/mips/atheros/ar71xx_wdog.c
+++ b/sys/mips/atheros/ar71xx_wdog.c
@@ -41,6 +41,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include 
+#include 
 
 struct ar71xx_wdog_softc {
 	device_t dev;
diff --git a/sys/mips/atheros/ar71xxreg.h b/sys/mips/atheros/ar71xxreg.h
index e6b7b8e8ac5..0f6fddc6607 100644
--- a/sys/mips/atheros/ar71xxreg.h
+++ b/sys/mips/atheros/ar71xxreg.h
@@ -161,6 +161,7 @@
 #define			GPIO_FUNC_USB_CLK_EN    (0)
 
 #define	AR71XX_BASE_FREQ		40000000
+#define	AR71XX_PLL_CPU_BASE		0x18050000
 #define	AR71XX_PLL_CPU_CONFIG		0x18050000
 #define		PLL_SW_UPDATE			(1 << 31)
 #define		PLL_LOCKED			(1 << 30)
@@ -235,6 +236,23 @@
 #define		RST_RESET_PCI_BUS	(1 <<  1)
 #define		RST_RESET_PCI_CORE	(1 <<  0)
 
+/* Chipset revision details */
+#define	AR71XX_RST_RESET_REG_REV_ID	0x18060090
+#define		REV_ID_MAJOR_MASK	0xfff0
+#define		REV_ID_MAJOR_AR71XX	0x00a0
+#define		REV_ID_MAJOR_AR913X	0x00b0
+#define		REV_ID_MAJOR_AR7240	0x00c0
+#define		REV_ID_MAJOR_AR7241	0x0100
+#define		REV_ID_MAJOR_AR7242	0x1100
+
+/* AR71XX chipset revision details */
+#define		AR71XX_REV_ID_MINOR_MASK	0x3
+#define		AR71XX_REV_ID_MINOR_AR7130	0x0
+#define		AR71XX_REV_ID_MINOR_AR7141	0x1
+#define		AR71XX_REV_ID_MINOR_AR7161	0x2
+#define		AR71XX_REV_ID_REVISION_MASK	0x3
+#define		AR71XX_REV_ID_REVISION_SHIFT	2
+
 /*
  * GigE adapters region
  */
@@ -459,38 +477,6 @@
 #define ATH_WRITE_REG(reg, val) \
     *((volatile uint32_t *)MIPS_PHYS_TO_KSEG1((reg))) = (val)
 
-static inline uint64_t
-ar71xx_cpu_freq(void)
-{
-        uint32_t pll_config, div;
-        uint64_t freq;
-
-        /* PLL freq */
-        pll_config = ATH_READ_REG(AR71XX_PLL_CPU_CONFIG);
-        div = ((pll_config >> PLL_FB_SHIFT) & PLL_FB_MASK) + 1;
-        freq = div * AR71XX_BASE_FREQ;
-        /* CPU freq */
-        div = ((pll_config >> PLL_CPU_DIV_SEL_SHIFT) & PLL_CPU_DIV_SEL_MASK)
-            + 1;
-        freq = freq / div;
-
-	return (freq);
-}
-
-static inline uint64_t
-ar71xx_ahb_freq(void)
-{
-        uint32_t pll_config, div;
-        uint64_t freq;
-
-        /* PLL freq */
-        pll_config = ATH_READ_REG(AR71XX_PLL_CPU_CONFIG);
-        /* AHB freq */
-        div = (((pll_config >> PLL_AHB_DIV_SHIFT) & PLL_AHB_DIV_MASK) + 1) * 2;
-        freq = ar71xx_cpu_freq() / div;
-	return (freq);
-}
-
 static inline void
 ar71xx_ddr_flush(uint32_t reg)
 { 
diff --git a/sys/mips/atheros/files.ar71xx b/sys/mips/atheros/files.ar71xx
index fed21afc83b..e7daa1cb870 100644
--- a/sys/mips/atheros/files.ar71xx
+++ b/sys/mips/atheros/files.ar71xx
@@ -15,3 +15,5 @@ mips/atheros/uart_cpu_ar71xx.c	optional uart
 mips/atheros/ar71xx_bus_space_reversed.c	standard
 mips/mips/intr_machdep.c        standard
 mips/mips/tick.c		standard
+mips/atheros/ar71xx_setup.c	standard
+mips/atheros/ar71xx_chip.c	standard
diff --git a/sys/mips/atheros/uart_bus_ar71xx.c b/sys/mips/atheros/uart_bus_ar71xx.c
index 8d83291c271..4c04aba360f 100644
--- a/sys/mips/atheros/uart_bus_ar71xx.c
+++ b/sys/mips/atheros/uart_bus_ar71xx.c
@@ -41,6 +41,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include 
+#include 
 
 #include "uart_if.h"
 
diff --git a/sys/mips/atheros/uart_cpu_ar71xx.c b/sys/mips/atheros/uart_cpu_ar71xx.c
index 4528ac68142..8465c26d650 100644
--- a/sys/mips/atheros/uart_cpu_ar71xx.c
+++ b/sys/mips/atheros/uart_cpu_ar71xx.c
@@ -39,6 +39,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include 
+#include 
 #include 
 
 bus_space_tag_t uart_bus_space_io;

From fd11fd075a95e5411353fa90689505b294d9909d Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:04:35 +0000
Subject: [PATCH 0067/1624] Make if_arge use the new cpuops rather than hard
 coding the DDR flush registers.

---
 sys/mips/atheros/if_arge.c | 30 ++++++++----------------------
 1 file changed, 8 insertions(+), 22 deletions(-)

diff --git a/sys/mips/atheros/if_arge.c b/sys/mips/atheros/if_arge.c
index 807173d92b1..3930b180cb3 100644
--- a/sys/mips/atheros/if_arge.c
+++ b/sys/mips/atheros/if_arge.c
@@ -79,6 +79,7 @@ MODULE_DEPEND(arge, miibus, 1, 1, 1);
 
 #include 
 #include 
+#include 
 
 #undef ARGE_DEBUG
 #ifdef ARGE_DEBUG
@@ -181,14 +182,11 @@ MTX_SYSINIT(miibus_mtx, &miibus_mtx, "arge mii lock", MTX_DEF);
 static void
 arge_flush_ddr(struct arge_softc *sc)
 {
-
-	ATH_WRITE_REG(sc->arge_ddr_flush_reg, 1);
-	while (ATH_READ_REG(sc->arge_ddr_flush_reg) & 1)
-		;
-
-	ATH_WRITE_REG(sc->arge_ddr_flush_reg, 1);
-	while (ATH_READ_REG(sc->arge_ddr_flush_reg) & 1)
-		;
+	if (sc->arge_mac_unit == 0) {
+		ar71xx_device_flush_ddr_ge0();
+	} else {
+		ar71xx_device_flush_ddr_ge1();
+	}
 }
 
 static int 
@@ -237,11 +235,9 @@ arge_attach(device_t dev)
 	KASSERT(((sc->arge_mac_unit == 0) || (sc->arge_mac_unit == 1)), 
 	    ("if_arge: Only MAC0 and MAC1 supported"));
 	if (sc->arge_mac_unit == 0) {
-		sc->arge_ddr_flush_reg = AR71XX_WB_FLUSH_GE0;
 		sc->arge_pll_reg = AR71XX_PLL_ETH_INT0_CLK;
 		sc->arge_pll_reg_shift = 17;
 	} else {
-		sc->arge_ddr_flush_reg = AR71XX_WB_FLUSH_GE1;
 		sc->arge_pll_reg = AR71XX_PLL_ETH_INT1_CLK;
 		sc->arge_pll_reg_shift = 19;
 	}
@@ -381,19 +377,9 @@ arge_attach(device_t dev)
 	DELAY(20);
 
 	/* Step 2. Punt the MAC core from the central reset register */
-	reg = ATH_READ_REG(AR71XX_RST_RESET);
-	if (sc->arge_mac_unit == 0) 
-		reg |= RST_RESET_GE0_MAC;
-	else if (sc->arge_mac_unit == 1) 
-		reg |= RST_RESET_GE1_MAC;
-	ATH_WRITE_REG(AR71XX_RST_RESET, reg);
+	ar71xx_device_stop(sc->arge_mac_unit == 0 ? RST_RESET_GE0_MAC : RST_RESET_GE1_MAC);
 	DELAY(100);
-	reg = ATH_READ_REG(AR71XX_RST_RESET);
-	if (sc->arge_mac_unit == 0) 
-		reg &= ~RST_RESET_GE0_MAC;
-	else if (sc->arge_mac_unit == 1) 
-		reg &= ~RST_RESET_GE1_MAC;
-	ATH_WRITE_REG(AR71XX_RST_RESET, reg);
+	ar71xx_device_start(sc->arge_mac_unit == 0 ? RST_RESET_GE0_MAC : RST_RESET_GE1_MAC);
 
 	/* Step 3. Reconfigure MAC block */
 	ARGE_WRITE(sc, AR71XX_MAC_CFG1, 

From 23f10186b5d0861d4e7cb225fbf371c3e5424788 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:05:16 +0000
Subject: [PATCH 0068/1624] Make the PCI initialisation path use the new cpuops
 rather than directly programming the reset register.

---
 sys/mips/atheros/ar71xx_pci.c | 12 ++++--------
 1 file changed, 4 insertions(+), 8 deletions(-)

diff --git a/sys/mips/atheros/ar71xx_pci.c b/sys/mips/atheros/ar71xx_pci.c
index 2e6a5fa8091..632270cb8e6 100644
--- a/sys/mips/atheros/ar71xx_pci.c
+++ b/sys/mips/atheros/ar71xx_pci.c
@@ -56,6 +56,8 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 
+#include 
+
 #undef AR71XX_PCI_DEBUG
 #ifdef AR71XX_PCI_DEBUG
 #define dprintf printf
@@ -258,7 +260,6 @@ ar71xx_pci_attach(device_t dev)
 {
 	int busno = 0;
 	int rid = 0;
-	uint32_t reset;
 	struct ar71xx_pci_softc *sc = device_get_softc(dev);
 
 	sc->sc_mem_rman.rm_type = RMAN_ARRAY;
@@ -295,15 +296,10 @@ ar71xx_pci_attach(device_t dev)
 	}
 
 	/* reset PCI core and PCI bus */
-	reset = ATH_READ_REG(AR71XX_RST_RESET);
-	reset |= (RST_RESET_PCI_CORE | RST_RESET_PCI_BUS);
-	ATH_WRITE_REG(AR71XX_RST_RESET, reset);
-	ATH_READ_REG(AR71XX_RST_RESET);
+	ar71xx_device_stop(RST_RESET_PCI_CORE | RST_RESET_PCI_BUS);
 	DELAY(100000);
 
-	reset &= ~(RST_RESET_PCI_CORE | RST_RESET_PCI_BUS);
-	ATH_WRITE_REG(AR71XX_RST_RESET, reset);
-	ATH_READ_REG(AR71XX_RST_RESET);
+	ar71xx_device_start(RST_RESET_PCI_CORE | RST_RESET_PCI_BUS);
 	DELAY(100000);
 
 	/* Init PCI windows */

From 5b877d30b59209f0e7f80b2cb3f9bf1a721c88ff Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:10:05 +0000
Subject: [PATCH 0069/1624] Remove the now-unused DDR flush register value.

---
 sys/mips/atheros/if_argevar.h | 1 -
 1 file changed, 1 deletion(-)

diff --git a/sys/mips/atheros/if_argevar.h b/sys/mips/atheros/if_argevar.h
index df1c34dd018..3db039d7c27 100644
--- a/sys/mips/atheros/if_argevar.h
+++ b/sys/mips/atheros/if_argevar.h
@@ -150,7 +150,6 @@ struct arge_softc {
 	uint32_t		arge_intr_status;
 	int			arge_mac_unit;
 	int			arge_phymask;
-	uint32_t		arge_ddr_flush_reg;
 	uint32_t		arge_pll_reg;
 	uint32_t		arge_pll_reg_shift;
 	int			arge_if_flags;

From 1d110056721b58058a1cf0d3e257c729dbef5286 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:12:04 +0000
Subject: [PATCH 0070/1624] Migrate the CPU reset path to use the new cpuops.

---
 sys/mips/atheros/ar71xx_machdep.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/sys/mips/atheros/ar71xx_machdep.c b/sys/mips/atheros/ar71xx_machdep.c
index a390167f0ad..9943db0fe50 100644
--- a/sys/mips/atheros/ar71xx_machdep.c
+++ b/sys/mips/atheros/ar71xx_machdep.c
@@ -121,9 +121,7 @@ platform_identify(void)
 void
 platform_reset(void)
 {
-	uint32_t reg = ATH_READ_REG(AR71XX_RST_RESET);
-
-	ATH_WRITE_REG(AR71XX_RST_RESET, reg | RST_RESET_FULL_CHIP);
+	ar71xx_device_stop(RST_RESET_FULL_CHIP);
 	/* Wait for reset */
 	while(1)
 		;

From 6f96ebf3091116ebfb6d925e0fd0b61ac42d199a Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:14:53 +0000
Subject: [PATCH 0071/1624] Initialise the USB system using cpuops rather than
 the AR71XX specific method.

---
 sys/mips/atheros/ar71xx_machdep.c | 17 +----------------
 1 file changed, 1 insertion(+), 16 deletions(-)

diff --git a/sys/mips/atheros/ar71xx_machdep.c b/sys/mips/atheros/ar71xx_machdep.c
index 9943db0fe50..d84f7da185a 100644
--- a/sys/mips/atheros/ar71xx_machdep.c
+++ b/sys/mips/atheros/ar71xx_machdep.c
@@ -255,22 +255,7 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused,
 	/*
 	 * Reset USB devices 
 	 */
-	reg = ATH_READ_REG(AR71XX_RST_RESET);
-	reg |= 
-	    RST_RESET_USB_OHCI_DLL | RST_RESET_USB_HOST | RST_RESET_USB_PHY;
-	ATH_WRITE_REG(AR71XX_RST_RESET, reg);
-	DELAY(1000);
-	reg &= 
-	    ~(RST_RESET_USB_OHCI_DLL | RST_RESET_USB_HOST | RST_RESET_USB_PHY);
-	ATH_WRITE_REG(AR71XX_RST_RESET, reg);
-	
-	ATH_WRITE_REG(AR71XX_USB_CTRL_CONFIG,
-	    USB_CTRL_CONFIG_OHCI_DES_SWAP | USB_CTRL_CONFIG_OHCI_BUF_SWAP |
-	    USB_CTRL_CONFIG_EHCI_DES_SWAP | USB_CTRL_CONFIG_EHCI_BUF_SWAP);
-
-	ATH_WRITE_REG(AR71XX_USB_CTRL_FLADJ, 
-	    (32 << USB_CTRL_FLADJ_HOST_SHIFT) | (3 << USB_CTRL_FLADJ_A5_SHIFT));
-	DELAY(1000);
+	ar71xx_init_usb_peripheral();
 
 	kdb_init();
 #ifdef KDB

From 292899c376cef6ddd537d62fc86f1bdf5289e2f6 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 02:15:39 +0000
Subject: [PATCH 0072/1624] Remove now unused 'reg'.

---
 sys/mips/atheros/ar71xx_machdep.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/sys/mips/atheros/ar71xx_machdep.c b/sys/mips/atheros/ar71xx_machdep.c
index d84f7da185a..3c1bd5f2ca1 100644
--- a/sys/mips/atheros/ar71xx_machdep.c
+++ b/sys/mips/atheros/ar71xx_machdep.c
@@ -144,7 +144,6 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused,
     __register_t a2 __unused, __register_t a3 __unused)
 {
 	uint64_t platform_counter_freq;
-	uint32_t reg;
 	int argc, i, count = 0;
 	char **argv, **envp;
 	vm_offset_t kernend;

From 509a0eba890121bc8864f13602eb6b7d89bcdb3e Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 19 Aug 2010 03:19:26 +0000
Subject: [PATCH 0073/1624] Unbreak the LINT kernel on powerpc64. Note that the
 LINT kernel configuration is TARGET_ARCH specific and must be generated with
 TARGET_ARCH set.

Reviewed by:	imp
---
 sys/conf/makeLINT.mk      | 3 +++
 sys/powerpc/conf/Makefile | 3 +++
 sys/powerpc/conf/NOTES    | 4 +++-
 3 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/sys/conf/makeLINT.mk b/sys/conf/makeLINT.mk
index e7ca9092193..049d63be399 100644
--- a/sys/conf/makeLINT.mk
+++ b/sys/conf/makeLINT.mk
@@ -17,3 +17,6 @@ LINT: ${NOTES} ../../conf/makeLINT.sed
 	echo "ident ${.TARGET}-VIMAGE"	>> ${.TARGET}-VIMAGE
 	echo "options VIMAGE"		>> ${.TARGET}-VIMAGE
 .endif
+.if ${TARGET} == "powerpc"
+	echo "machine	${TARGET} ${TARGET_ARCH}" >> ${.TARGET}
+.endif
diff --git a/sys/powerpc/conf/Makefile b/sys/powerpc/conf/Makefile
index 562bc4693cd..f6652381004 100644
--- a/sys/powerpc/conf/Makefile
+++ b/sys/powerpc/conf/Makefile
@@ -1,5 +1,8 @@
 # $FreeBSD$
 
 TARGET=powerpc
+.if ${MACHINE_ARCH} == powerpc || ${MACHINE_ARCH} == powerpc64
+TARGET_ARCH?=${MACHINE_ARCH}
+.endif
 
 .include "${.CURDIR}/../../conf/makeLINT.mk"
diff --git a/sys/powerpc/conf/NOTES b/sys/powerpc/conf/NOTES
index f3b19eae6c6..d9437611ac2 100644
--- a/sys/powerpc/conf/NOTES
+++ b/sys/powerpc/conf/NOTES
@@ -8,7 +8,8 @@
 #####################################################################
 # CPU OPTIONS
 
-machine		powerpc powerpc
+# You must specify a machine directive to choose powerpc or powerpc64
+#machine		powerpc powerpc[64]
 
 #
 # You must specify at least one CPU (the one you intend to run on).
@@ -44,6 +45,7 @@ device		snd_davbus	# Apple Davbus Audio
 #####################################################################
 # Devices we don't want to deal with
 
+nodevice	bktr
 nodevice	fdc
 nodevice	ppc
 nodevice	splash

From 5c0e643e733743dc10b6608ac98a7bc5e2d4fca6 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 03:31:26 +0000
Subject: [PATCH 0074/1624] First cut at mips n64 ABI support

---
 .../opensolaris/uts/common/sys/isa_defs.h     | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/isa_defs.h b/sys/cddl/contrib/opensolaris/uts/common/sys/isa_defs.h
index 137cd971dbb..19faf42f731 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/isa_defs.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/isa_defs.h
@@ -403,6 +403,25 @@ extern "C" {
 #define	_INT_ALIGNMENT			4
 #define	_FLOAT_ALIGNMENT		4
 #define	_FLOAT_COMPLEX_ALIGNMENT	4
+#if defined(__mips_n64)
+#define	_LONG_ALIGNMENT			8
+#define	_LONG_LONG_ALIGNMENT		8
+#define	_DOUBLE_ALIGNMENT		8
+#define	_DOUBLE_COMPLEX_ALIGNMENT	8
+#define	_LONG_DOUBLE_ALIGNMENT		8
+#define	_LONG_DOUBLE_COMPLEX_ALIGNMENT	8
+#define	_POINTER_ALIGNMENT		8
+#define	_MAX_ALIGNMENT			8
+#define	_ALIGNMENT_REQUIRED		0
+
+#define	_LONG_LONG_ALIGNMENT_32		_INT_ALIGNMENT
+/*
+ * Define the appropriate "implementation choices".
+ */
+#if !defined(_LP64)
+#define	_LP64
+#endif
+#else
 #define	_LONG_ALIGNMENT			4
 #define	_LONG_LONG_ALIGNMENT		4
 #define	_DOUBLE_ALIGNMENT		4
@@ -422,6 +441,7 @@ extern "C" {
 #if !defined(_I32LPx) && defined(_KERNEL)
 #define	_I32LPx
 #endif
+#endif
 #define	_SUNOS_VTOC_16
 #define	_DMA_USES_PHYSADDR
 #define	_FIRMWARE_NEEDS_FDISK

From a5a3ab24a44c958bed37969e612d7fedf4aed25a Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 05:59:27 +0000
Subject: [PATCH 0075/1624] Various updates to support new pc-sysinstall
 directive "installPackages" that will install packages and all package
 dependencies.

PR:		148606
Submitted by:	John Hixon
---
 usr.sbin/pc-sysinstall/backend-query/Makefile |   4 +-
 .../backend-query/get-packages.sh             |  10 +-
 .../pc-sysinstall/backend-query/set-mirror.sh |  40 +++++
 usr.sbin/pc-sysinstall/backend/Makefile       |   2 +-
 .../pc-sysinstall/backend/functions-ftp.sh    |  24 ++-
 .../backend/functions-installpackages.sh      | 118 +++++++++++++
 .../backend/functions-packages.sh             | 158 ++++++++++++++++--
 .../backend/functions-runcommands.sh          |   8 +
 usr.sbin/pc-sysinstall/backend/parseconfig.sh |   9 +
 .../pc-sysinstall/conf/pc-sysinstall.conf     |   4 +
 usr.sbin/pc-sysinstall/doc/help-index         |   7 +-
 .../pc-sysinstall/pc-sysinstall.sh            |   9 +-
 12 files changed, 358 insertions(+), 35 deletions(-)
 create mode 100755 usr.sbin/pc-sysinstall/backend-query/set-mirror.sh
 create mode 100755 usr.sbin/pc-sysinstall/backend/functions-installpackages.sh

diff --git a/usr.sbin/pc-sysinstall/backend-query/Makefile b/usr.sbin/pc-sysinstall/backend-query/Makefile
index c042ac32f0f..c43b1412252 100644
--- a/usr.sbin/pc-sysinstall/backend-query/Makefile
+++ b/usr.sbin/pc-sysinstall/backend-query/Makefile
@@ -3,8 +3,8 @@
 FILES=	detect-laptop.sh detect-nics.sh detect-emulation.sh disk-info.sh \
 	disk-list.sh disk-part.sh enable-net.sh get-packages.sh list-config.sh \
 	list-components.sh list-mirrors.sh list-packages.sh list-rsync-backups.sh \
-	list-tzones.sh query-langs.sh send-logs.sh setup-ssh-keys.sh sys-mem.sh \
-	test-live.sh test-netup.sh update-part-list.sh xkeyboard-layouts.sh \
+	list-tzones.sh query-langs.sh send-logs.sh set-mirror.sh setup-ssh-keys.sh \
+	sys-mem.sh test-live.sh test-netup.sh update-part-list.sh xkeyboard-layouts.sh \
 	xkeyboard-models.sh xkeyboard-variants.sh
 FILESMODE=	${BINMODE}
 FILESDIR=${SHAREDIR}/pc-sysinstall/backend-query
diff --git a/usr.sbin/pc-sysinstall/backend-query/get-packages.sh b/usr.sbin/pc-sysinstall/backend-query/get-packages.sh
index 2c8eab2ef05..ee6fb7ba105 100755
--- a/usr.sbin/pc-sysinstall/backend-query/get-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/get-packages.sh
@@ -31,24 +31,16 @@
 . ${PROGDIR}/backend/functions.sh
 . ${PROGDIR}/backend/functions-packages.sh
 
-DEFAULT_FTP_SERVER="ftp.freebsd.org"
-FTP_SERVER="${1}"
 ID=`id -u`
-
 if [ "${ID}" -ne "0" ]
 then
 	echo "Error: must be root!" 
 	exit 1
 fi
 
-if [ -z "${FTP_SERVER}" ]
-then
-	FTP_SERVER="${DEFAULT_FTP_SERVER}"
-fi
-
 if [ ! -f "${PKGDIR}/INDEX" ]
 then
-	get_package_index "${FTP_SERVER}"
+	get_package_index
 fi
 
 if [ -f "${PKGDIR}/INDEX" ]
diff --git a/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh b/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh
new file mode 100755
index 00000000000..31c121d8443
--- /dev/null
+++ b/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh
@@ -0,0 +1,40 @@
+#!/bin/sh
+#-
+# Copyright (c) 2010 iXSystems, Inc.  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.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+#
+# $FreeBSD$
+
+. ${PROGDIR}/backend/functions.sh
+. ${PROGDIR}/backend/functions-ftp.sh
+
+MIRROR="${1}"
+
+if [ -z "${MIRROR}" ]
+then
+	echo "Error: No mirror specified!"
+	exit 1
+fi
+
+set_ftp_mirror "${MIRROR}"
+exit 0
diff --git a/usr.sbin/pc-sysinstall/backend/Makefile b/usr.sbin/pc-sysinstall/backend/Makefile
index 920772609a9..fa51d50be5c 100644
--- a/usr.sbin/pc-sysinstall/backend/Makefile
+++ b/usr.sbin/pc-sysinstall/backend/Makefile
@@ -2,7 +2,7 @@
 
 FILES=	functions-bsdlabel.sh functions-cleanup.sh functions-disk.sh \
 	functions-extractimage.sh functions-ftp.sh functions-installcomponents.sh \
-	functions-localize.sh functions-mountdisk.sh \
+	functions-installpackages.sh functions-localize.sh functions-mountdisk.sh \
 	functions-mountoptical.sh functions-networking.sh \
 	functions-newfs.sh functions-packages.sh functions-parse.sh \
 	functions-runcommands.sh functions-unmount.sh \
diff --git a/usr.sbin/pc-sysinstall/backend/functions-ftp.sh b/usr.sbin/pc-sysinstall/backend/functions-ftp.sh
index cd4853893b1..3bf95a8cde4 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-ftp.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-ftp.sh
@@ -30,6 +30,8 @@
 . ${BACKEND}/functions.sh
 . ${BACKEND}/functions-parse.sh
 
+DEFAULT_FTP_SERVER="ftp.freebsd.org"
+
 MAIN_FTP_SERVERS="\
 Main Site: ftp.freebsd.org"
 
@@ -274,7 +276,25 @@ show_mirrors()
     done
     IFS="${SAVE_IFS}"
   fi
-}
+};
+
+set_ftp_mirror()
+{
+	MIRROR="${1}"
+	echo "${MIRROR}" > "${CONFDIR}/mirrors.conf"
+};
+
+get_ftp_mirror()
+{
+	MIRROR="${DEFAULT_FTP_SERVER}"
+	if [ -f "${CONFDIR}/mirrors.conf" ]
+	then
+		MIRROR=`cat "${CONFDIR}/mirrors.conf"`
+	fi
+
+	VAL="${MIRROR}"
+	export VAL
+};
 
 get_ftp_mirrors()
 {
@@ -371,4 +391,4 @@ get_ftp_mirrors()
   fi
 
   export VAL
-}
+};
diff --git a/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh b/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
new file mode 100755
index 00000000000..8d5f408a43d
--- /dev/null
+++ b/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
@@ -0,0 +1,118 @@
+#!/bin/sh
+#-
+# Copyright (c) 2010 iXsystems, Inc.  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.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+#
+# $FreeBSD$
+
+# Functions which check and load any optional packages specified in the config
+
+. ${BACKEND}/functions.sh
+. ${BACKEND}/functions-parse.sh
+
+# Recursively determine all dependencies for this package
+determine_package_dependencies()
+{
+	local PKGNAME="${1}"
+	local DEPFILE="${2}"
+
+	grep "${PKGNAME}" "${DEPFILE}" >/dev/null
+	if [ "$?" -ne "0" ]
+	then
+		echo "${PKGNAME}" >> "${DEPFILE}"
+		get_package_dependencies "${PKGNAME}" "1"
+		local DEPS="${VAL}"
+
+		for d in ${DEPS}
+		do
+			get_all_package_dependencies "${d}" "${DEPFILE}"
+		done
+	fi
+};
+
+# Fetch packages dependencies from a file
+fetch_package_dependencies()
+{
+	local DEPFILE
+	local DEPS
+
+	DEPFILE="${1}"
+	DEPS=`cat "${DEPFILE}"`
+
+	for d in ${DEPS}
+	do
+		get_package_short_name "${d}"
+		SNAME="${VAL}"
+
+		get_package_category "${SNAME}"
+		CATEGORY="${VAL}"
+
+		fetch_package "${CATEGORY}" "${d}"
+	done
+};
+
+# Check for any packages specified, and begin loading them
+install_packages()
+{
+   # First, lets check and see if we even have any packages to install
+	get_value_from_cfg installPackages
+	if [ ! -z "${VAL}" ]
+	then
+	  mkdir -p "${PKGTMPDIR}"
+
+	  HERE=`pwd`
+	  cd "${PKGTMPDIR}"
+
+      # Lets start by cleaning up the string and getting it ready to parse
+      strip_white_space ${VAL}
+      PACKAGES=`echo ${VAL} | sed -e "s|,| |g"`
+      for i in $PACKAGES
+	  do
+		if get_package_name "${i}"
+		then
+			PKGNAME="${VAL}"
+			DEPFILE="${PKGTMPDIR}/.${PKGNAME}.deps"
+
+			touch "${DEPFILE}"
+			determine_package_dependencies "${PKGNAME}" "${DEPFILE}"
+			fetch_package_dependencies "${DEPFILE}"
+
+			# If the package is not already installed, install it!
+			if ! run_chroot_cmd "pkg_info -e ${PKGNAME}"
+			then
+				echo_log "Adding package ${PKGNAME}"
+				pkg_add -C "${FSMNT}" "${PKGNAME}.tbz" >/dev/null 2>&1
+				if [ "$?" -eq "0" ]
+				then
+					echo_log "${PKGNAME} successfully installed!"
+				fi
+			fi
+
+			rm "${DEPFILE}"
+		fi
+	  done
+
+	  #rm -rf "${PKGTMPDIR}"
+	  cd "${HERE}"
+	fi
+};
diff --git a/usr.sbin/pc-sysinstall/backend/functions-packages.sh b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
index 345b64953c6..a522718e632 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
@@ -34,29 +34,30 @@
 
 get_package_index()
 {
-	FTP_SERVER="${1}"
-	FTP_DIR="ftp://${FTP_SERVER}/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}/packages"
 	INDEX_FILE="INDEX"
 	USE_BZIP2=0
 
+	get_ftp_mirror
+	FTP_SERVER="${VAL}"
+
+	FTP_DIR="ftp://${FTP_SERVER}/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}/packages"
+
 	if [ -f "/usr/bin/bzip2" ]
 	then
 		INDEX_FILE="${INDEX_FILE}.bz2"
 		USE_BZIP2=1
 	fi
 
-	ftp "${FTP_DIR}/${INDEX_FILE}"
-	if [ -f "${INDEX_FILE}" ]
-	then
-		if [ "${USE_BZIP2}" -eq  "1" ]
-		then
-			bzip2 -d "${INDEX_FILE}"
-			INDEX_FILE="${INDEX_FILE%.bz2}"
-		fi
+	fetch_file "${FTP_DIR}/${INDEX_FILE}" "${PKGDIR}/${INDEX_FILE}" "1"
 
-		mv "${INDEX_FILE}" "${PKGDIR}"
+	HERE=`pwd`
+	cd "${PKGDIR}"
+	if [ -f "${INDEX_FILE}" ] && [ "${USE_BZIP2}" -eq "1" ]
+	then
+		bzip2 -d "${INDEX_FILE}"
 	fi
-}
+	cd "${HERE}"
+};
 
 parse_package_index()
 {
@@ -67,9 +68,11 @@ parse_package_index()
 
 	while read -r line
 	do
+		PKGNAME=""
 		CATEGORY=""
 		PACKAGE=""
 		DESC=""
+		DEPS=""
 		i=0
 
 		SAVE_IFS="${IFS}"
@@ -77,7 +80,11 @@ parse_package_index()
 
 		for part in ${line}
 		do
-			if [ "${i}" -eq "1" ]
+			if [ "${i}" -eq "0" ]
+			then
+				PKGNAME="${part}"
+
+			elif [ "${i}" -eq "1" ]
 			then
 				PACKAGE=`basename "${part}"`
 
@@ -88,17 +95,23 @@ parse_package_index()
 			elif [ "${i}" -eq "6" ]
 			then
 				CATEGORY=`echo "${part}" | cut -f1 -d' '`
+
+			elif [ "${i}" -eq "8" ]
+			then
+				DEPS="${part}"
 			fi
 
 			i=$((i+1))
 		done
 
 		echo "${CATEGORY}|${PACKAGE}|${DESC}" >> "${INDEX_FILE}.parsed"
+		echo "${PACKAGE}|${PKGNAME}|${DEPS}" >> "${INDEX_FILE}.deps"
+
 		IFS="${SAVE_IFS}"
 	done
 
 	exec 0<&3
-}
+};
 
 show_package_file()
 {
@@ -117,7 +130,7 @@ show_package_file()
 	done
 
 	exec 0<&3
-}
+};
 
 show_packages_by_category()
 {
@@ -128,7 +141,7 @@ show_packages_by_category()
 	grep "^${CATEGORY}|" "${INDEX_FILE}" > "${TMPFILE}"
 	show_package_file "${TMPFILE}"
 	rm "${TMPFILE}"
-}
+};
 
 show_package_by_name()
 {
@@ -140,9 +153,118 @@ show_package_by_name()
 	grep "^${CATEGORY}|${PACKAGE}" "${INDEX_FILE}" > "${TMPFILE}"
 	show_package_file "${TMPFILE}"
 	rm "${TMPFILE}"
-}
+};
 
 show_packages()
 {
 	show_package_file "${PKGDIR}/INDEX.parsed"
-}
+};
+
+get_package_dependencies()
+{
+	PACKAGE="${1}"
+	LONG="${2:-0}"
+	RES=0
+
+	INDEX_FILE="${PKGDIR}/INDEX.deps"
+	REGEX="^${PACKAGE}|"
+
+	if [ "${LONG}" -ne "0" ]
+	then
+		REGEX="^.*|${PACKAGE}|"
+	fi
+
+	LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
+	DEPS=`echo "${LINE}"|cut -f3 -d'|'`
+
+	VAL="${DEPS}"
+	export VAL
+
+	if [ -z "${VAL}" ]
+	then
+		RES=1
+	fi
+
+	return ${RES}
+};
+
+get_package_name()
+{
+	PACKAGE="${1}"
+	RES=0
+
+	INDEX_FILE="${PKGDIR}/INDEX.deps"
+	REGEX="^${PACKAGE}|"
+	
+	LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
+	NAME=`echo "${LINE}"|cut -f2 -d'|'`
+
+	VAL="${NAME}"
+	export VAL
+
+	if [ -z "${VAL}" ]
+	then
+		RES=1
+	fi
+
+	return ${RES}
+};
+
+get_package_short_name()
+{
+	PACKAGE="${1}"
+	RES=0
+
+	INDEX_FILE="${PKGDIR}/INDEX.deps"
+	REGEX="^.*|${PACKAGE}|"
+	
+	LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
+	NAME=`echo "${LINE}"|cut -f1 -d'|'`
+
+	VAL="${NAME}"
+	export VAL
+
+	if [ -z "${VAL}" ]
+	then
+		RES=1
+	fi
+
+	return ${RES}
+};
+
+get_package_category()
+{
+	PACKAGE="${1}"
+	INDEX_FILE="${PKGDIR}/INDEX.parsed"
+	RES=0
+
+	LINE=`grep "|${PACKAGE}|" "${INDEX_FILE}" 2>/dev/null`
+	NAME=`echo "${LINE}"|cut -f1 -d'|'`
+
+	VAL="${NAME}"
+	export VAL
+
+	if [ -z "${VAL}" ]
+	then
+		RES=1
+	fi
+
+	return ${RES}
+};
+
+fetch_package()
+{
+	CATEGORY="${1}"
+	PACKAGE="${2}"
+
+	get_ftp_mirror
+	FTP_SERVER="${VAL}"
+
+	PACKAGE="${PACKAGE}.tbz"
+	if [ ! -f "${PKGTMPDIR}/${PACKAGE}" ]
+	then
+		PKGPATH="${CATEGORY}/${PACKAGE}"
+		FTP_PATH="ftp://${FTP_SERVER}/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}/packages/${PKGPATH}"
+		fetch_file "${FTP_PATH}" "${PKGTMPDIR}/" "0"
+	fi
+};
diff --git a/usr.sbin/pc-sysinstall/backend/functions-runcommands.sh b/usr.sbin/pc-sysinstall/backend/functions-runcommands.sh
index beb1d98171d..fccc00a6f68 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-runcommands.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-runcommands.sh
@@ -37,7 +37,10 @@ run_chroot_cmd()
   echo "$CMD" >${FSMNT}/.runcmd.sh
   chmod 755 ${FSMNT}/.runcmd.sh
   chroot ${FSMNT} sh /.runcmd.sh
+  RES=$?
+
   rm ${FSMNT}/.runcmd.sh
+  return ${RES}
 };
 
 run_chroot_script()
@@ -50,8 +53,10 @@ run_chroot_script()
 
   echo_log "Running chroot script: ${SCRIPT}"
   chroot ${FSMNT} /.${SBASE}
+  RES=$?
 
   rm ${FSMNT}/.${SBASE}
+  return ${RES}
 };
 
 
@@ -64,7 +69,10 @@ run_ext_cmd()
   echo "${CMD}"> ${TMPDIR}/.runcmd.sh
   chmod 755 ${TMPDIR}/.runcmd.sh
   sh ${TMPDIR}/.runcmd.sh
+  RES=$?
+
   rm ${TMPDIR}/.runcmd.sh
+  return ${RES}
 };
 
 
diff --git a/usr.sbin/pc-sysinstall/backend/parseconfig.sh b/usr.sbin/pc-sysinstall/backend/parseconfig.sh
index 3c4ed4f9946..89b25eae83c 100755
--- a/usr.sbin/pc-sysinstall/backend/parseconfig.sh
+++ b/usr.sbin/pc-sysinstall/backend/parseconfig.sh
@@ -35,12 +35,15 @@
 . ${BACKEND}/functions-disk.sh
 . ${BACKEND}/functions-extractimage.sh
 . ${BACKEND}/functions-installcomponents.sh
+. ${BACKEND}/functions-installpackages.sh
 . ${BACKEND}/functions-localize.sh
 . ${BACKEND}/functions-mountdisk.sh
 . ${BACKEND}/functions-networking.sh
 . ${BACKEND}/functions-newfs.sh
+. ${BACKEND}/functions-packages.sh
 . ${BACKEND}/functions-parse.sh
 . ${BACKEND}/functions-runcommands.sh
+. ${BACKEND}/functions-ftp.sh
 . ${BACKEND}/functions-unmount.sh
 . ${BACKEND}/functions-upgrade.sh
 . ${BACKEND}/functions-users.sh
@@ -117,6 +120,9 @@ then
   # Check if we have any optional modules to load 
   install_components
 
+  # Check if we have any packages to install
+  install_packages
+
   # Do any localization in configuration
   run_localize
   
@@ -158,6 +164,9 @@ else
   # Check if we have any optional modules to load 
   install_components
 
+  # Check if we have any packages to install
+  install_packages
+
   # All finished, unmount the file-systems
   unmount_upgrade
 
diff --git a/usr.sbin/pc-sysinstall/conf/pc-sysinstall.conf b/usr.sbin/pc-sysinstall/conf/pc-sysinstall.conf
index 7d0aa4f105e..33f375382a7 100644
--- a/usr.sbin/pc-sysinstall/conf/pc-sysinstall.conf
+++ b/usr.sbin/pc-sysinstall/conf/pc-sysinstall.conf
@@ -51,6 +51,10 @@ export COMPFILEDIR
 COMPTMPDIR="/usr/.componenttmp"
 export COMPTMPDIR
 
+# set the package temp directory, which is relative to FSMNT
+PKGTMPDIR="/usr/.pkgtmp"
+export PKGTMPDIR
+
 # Variables to set the location of installation data
 UZIP_FILE="PCBSD.ufs.uzip"
 TAR_FILE="PCBSD.tbz"
diff --git a/usr.sbin/pc-sysinstall/doc/help-index b/usr.sbin/pc-sysinstall/doc/help-index
index d9e52b503b3..6a0f1bce51b 100644
--- a/usr.sbin/pc-sysinstall/doc/help-index
+++ b/usr.sbin/pc-sysinstall/doc/help-index
@@ -34,10 +34,10 @@ System Query Commands
     list-components
         Returns a listing of the available components which can be installed
 
-    list-mirrors
+    list-mirrors [country]
         Returns a listing of the available FTP mirrors
 
-    list-packages
+    list-packages [category] [package]
         Returns a listing of the available packages
 
     list-rsync-backups   
@@ -55,6 +55,9 @@ System Query Commands
     sys-mem
         Return the size of installed system RAM in MegaBytes
 
+    set-mirror 
+        Set FTP mirror
+
     test-netup
         Test if an internet connection is available
     
diff --git a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
index a26e3046211..85bb6af45a6 100755
--- a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
+++ b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
@@ -43,8 +43,11 @@ export PROGDIR
 COMPDIR="${PROGDIR}/components"
 export COMPDIR
 
+CONFDIR="${PROGDIR}/conf"
+export CONFDIR
+
 # Set this to the packages location
-PKGDIR="${PROGDIR}/conf"
+PKGDIR="${CONFDIR}"
 export PKGDIR
 
 # End of user-editable configuration
@@ -184,6 +187,10 @@ case $1 in
   get-packages) ${QUERYDIR}/get-packages.sh "${2}"
   ;;
 
+  # Function to set FTP mirror
+  set-mirror) ${QUERYDIR}/set-mirror.sh "${2}"
+  ;;
+
   # Function which allows setting up of SSH keys
   setup-ssh-keys) ${QUERYDIR}/setup-ssh-keys.sh "${2}" "${3}" "${4}"
   ;;

From 742736b9233ff4d1eda0e13a36c529c67718fc6e Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 06:01:25 +0000
Subject: [PATCH 0076/1624] Updates to pc-sysinstall that allow FTP
 installation of FreeBSD.

PR:		148661
Submitted by:	John Hixson
---
 .../backend-query/list-packages.sh            |  16 +-
 .../backend/functions-extractimage.sh         |  76 +++++++++-
 .../backend/functions-installpackages.sh      |  41 ++---
 .../backend/functions-packages.sh             | 140 +++++++++++++++---
 4 files changed, 229 insertions(+), 44 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend-query/list-packages.sh b/usr.sbin/pc-sysinstall/backend-query/list-packages.sh
index 02d3e9a0b3c..b5d93f52ccb 100755
--- a/usr.sbin/pc-sysinstall/backend-query/list-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/list-packages.sh
@@ -56,14 +56,26 @@ then
 	NARGS=$((NARGS+1))
 fi
 
-echo "Available Packages:"
 if [ "${NARGS}" -eq "0" ]
 then
 	show_packages
 
 elif [ "${NARGS}" -eq "1" ]
 then
-	show_packages_by_category "${PACKAGE_CATEGORY}"
+	
+	if [ "${PACKAGE_CATEGORY}" = "@INDEX@" ]
+	then
+		if [ -f "${PKGDIR}/INDEX" ]
+		then
+			echo "${PKGDIR}/INDEX"
+			exit 0
+		else
+			exit 1
+		fi
+		
+	else
+		show_packages_by_category "${PACKAGE_CATEGORY}"
+	fi
 
 elif [ "${NARGS}" -eq "2" ]
 then
diff --git a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
index e4fccce7c1f..de86711009e 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
@@ -203,6 +203,69 @@ fetch_install_file()
 
 };
 
+# Function which will download freebsd install files
+fetch_split_files()
+{
+  get_value_from_cfg ftpHost
+  if [ -z "$VAL" ]
+  then
+    exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
+  fi
+  FTPHOST="${VAL}"
+
+  get_value_from_cfg ftpDir
+  if [ -z "$VAL" ]
+  then
+    exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
+  fi
+  FTPDIR="${VAL}"
+
+  # Check if we have a /usr partition to save the download
+  if [ -d "${FSMNT}/usr" ]
+  then
+    OUTFILE="${FSMNT}/usr/.fetch-${INSFILE}"
+  else
+    OUTFILE="${FSMNT}/.fetch-${INSFILE}"
+  fi
+
+  NETRC="${OUTFILE}/.netrc"
+  cat<"${NETRC}"
+machine ${FTPHOST}
+login anonymous
+password anonymous
+macdef INSTALL
+bin
+prompt
+EOF
+
+  DIRS="base catpages dict doc games info manpages proflibs kernels src"
+  if [ "${FBSD_ARCH}" = "amd64" ]
+  then
+	DIRS="${DIRS} lib32"
+  fi
+
+  for d in ${DIRS}
+  do
+	cat<>"${NETRC}"
+cd ${FTPDIR}/${d}
+lcd ${OUTFILE}/${d}
+mreget *
+EOF
+  done
+
+	cat<>"${NETRC}"
+bye
+
+
+EOF
+
+   # Fetch the files via ftp
+   echo "$ INSTALL" | ftp -N "${NETRC}" "${FTPHOST}"
+
+  # Done fetching, now reset the INSFILE to our downloaded archived
+  INSFILE="${OUTFILE}" ; export INSFILE
+}
+
 # Function which does the rsync download from the server specifed in cfg
 start_rsync_copy()
 {
@@ -304,8 +367,17 @@ init_extraction()
           	start_extract_uzip_tar
 		  fi
           ;;
-     ftp) fetch_install_file
-          start_extract_uzip_tar 
+     ftp)
+		  if [ "$PACKAGETYPE" = "split" ]
+		  then
+			fetch_split_files
+
+			INSDIR="${INSFILE}" ; export INSDIR
+			start_extract_split
+		  else
+          	fetch_install_file
+          	start_extract_uzip_tar 
+		  fi
           ;;
      rsync) start_rsync_copy
             ;;
diff --git a/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh b/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
index 8d5f408a43d..e967011d64f 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
@@ -45,7 +45,7 @@ determine_package_dependencies()
 
 		for d in ${DEPS}
 		do
-			get_all_package_dependencies "${d}" "${DEPFILE}"
+			determine_package_dependencies "${d}" "${DEPFILE}"
 		done
 	fi
 };
@@ -55,9 +55,11 @@ fetch_package_dependencies()
 {
 	local DEPFILE
 	local DEPS
+	local SAVEDIR
 
 	DEPFILE="${1}"
 	DEPS=`cat "${DEPFILE}"`
+	SAVEDIR="${2}"
 
 	for d in ${DEPS}
 	do
@@ -67,7 +69,7 @@ fetch_package_dependencies()
 		get_package_category "${SNAME}"
 		CATEGORY="${VAL}"
 
-		fetch_package "${CATEGORY}" "${d}"
+		fetch_package "${CATEGORY}" "${d}" "${SAVEDIR}"
 	done
 };
 
@@ -78,10 +80,19 @@ install_packages()
 	get_value_from_cfg installPackages
 	if [ ! -z "${VAL}" ]
 	then
-	  mkdir -p "${PKGTMPDIR}"
-
 	  HERE=`pwd`
-	  cd "${PKGTMPDIR}"
+	  rc_nohalt "mkdir -p ${FSMNT}/${PKGTMPDIR}"
+	  rc_nohalt "cd ${FSMNT}/${PKGTMPDIR}"
+
+	  if [ ! -f "${CONFDIR}/INDEX" ]
+	  then
+		get_package_index
+	  fi
+
+	  if [ ! -f "${CONFDIR}/INDEX.parsed" ]
+	  then
+		parse_package_index
+	  fi
 
       # Lets start by cleaning up the string and getting it ready to parse
       strip_white_space ${VAL}
@@ -91,28 +102,24 @@ install_packages()
 		if get_package_name "${i}"
 		then
 			PKGNAME="${VAL}"
-			DEPFILE="${PKGTMPDIR}/.${PKGNAME}.deps"
+			DEPFILE="${FSMNT}/${PKGTMPDIR}/.${PKGNAME}.deps"
 
-			touch "${DEPFILE}"
+			rc_nohalt "touch ${DEPFILE}"
 			determine_package_dependencies "${PKGNAME}" "${DEPFILE}"
-			fetch_package_dependencies "${DEPFILE}"
+			fetch_package_dependencies "${DEPFILE}" "${FSMNT}/${PKGTMPDIR}"
 
 			# If the package is not already installed, install it!
 			if ! run_chroot_cmd "pkg_info -e ${PKGNAME}"
 			then
-				echo_log "Adding package ${PKGNAME}"
-				pkg_add -C "${FSMNT}" "${PKGNAME}.tbz" >/dev/null 2>&1
-				if [ "$?" -eq "0" ]
-				then
-					echo_log "${PKGNAME} successfully installed!"
-				fi
+				rc_nohalt "pkg_add -C ${FSMNT} ${PKGTMPDIR}/${PKGNAME}.tbz"
 			fi
 
-			rm "${DEPFILE}"
+			rc_nohalt "rm ${DEPFILE}"
 		fi
+
+		rc_nohalt "cd ${HERE}"
 	  done
 
-	  #rm -rf "${PKGTMPDIR}"
-	  cd "${HERE}"
+	  #rm -rf "${FSMNT}/${PKGTMPDIR}"
 	fi
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-packages.sh b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
index a522718e632..1ec24be696e 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
@@ -32,31 +32,80 @@
 . ${BACKEND}/functions-ftp.sh
 
 
-get_package_index()
+get_package_index_by_ftp()
 {
+	local INDEX_FILE
+	local FTP_SERVER
+
+	FTP_SERVER="${1}"
 	INDEX_FILE="INDEX"
 	USE_BZIP2=0
 
-	get_ftp_mirror
-	FTP_SERVER="${VAL}"
-
-	FTP_DIR="ftp://${FTP_SERVER}/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}/packages"
-
 	if [ -f "/usr/bin/bzip2" ]
 	then
 		INDEX_FILE="${INDEX_FILE}.bz2"
 		USE_BZIP2=1
 	fi
 
-	fetch_file "${FTP_DIR}/${INDEX_FILE}" "${PKGDIR}/${INDEX_FILE}" "1"
-
-	HERE=`pwd`
-	cd "${PKGDIR}"
-	if [ -f "${INDEX_FILE}" ] && [ "${USE_BZIP2}" -eq "1" ]
+	INDEX_PATH="${CONFDIR}/${INDEX_FILE}"
+	fetch_file "${FTP_SERVER}/${INDEX_FILE}" "${INDEX_PATH}" "1"
+	if [ -f "${INDEX_PATH}" ] && [ "${USE_BZIP2}" -eq "1" ]
 	then
-		bzip2 -d "${INDEX_FILE}"
+		bzip2 -d "${INDEX_PATH}"
 	fi
-	cd "${HERE}"
+};
+
+get_package_index_by_fs()
+{
+	local INDEX_FILE
+
+	INDEX_FILE="${CDMNT}/packages/INDEX"
+	fetch_file "${INDEX_FILE}" "${CONFDIR}/" "0"
+};
+
+get_package_index()
+{
+	RES=0
+
+	if [ -z "${INSTALLMODE}" ]
+	then
+		get_ftp_mirror
+		FTPHOST="${VAL}"
+
+		FTPDIR="/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}"
+		FTPPATH="ftp://${FTPHOST}${FTPDIR}/packages"
+
+		get_package_index_by_ftp "${FTPPATH}"
+
+	else
+		get_value_from_cfg ftpHost
+		if [ -z "$VAL" ]
+		then
+			exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
+		fi
+		FTPHOST="${VAL}"
+
+		get_value_from_cfg ftpDir
+		if [ -z "$VAL" ]
+		then
+			exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
+		fi
+		FTPDIR="${VAL}"
+
+		FTPPATH="ftp://${FTPHOST}${FTPDIR}"
+
+		case "${INSTALLMEDIUM}" in
+		usb|dvd) get_package_index_by_fs
+			;;
+		ftp) get_package_index_by_ftp "${FTPPATH}"
+			;;
+		*) RES=1
+			;;
+		esac
+
+	fi
+
+	return ${RES}
 };
 
 parse_package_index()
@@ -117,6 +166,8 @@ show_package_file()
 {
 	PKGFILE="${1}"
 
+	echo "Available Packages:"
+
 	exec 3<&0
 	exec 0<"${PKGFILE}"
 
@@ -252,19 +303,62 @@ get_package_category()
 	return ${RES}
 };
 
+fetch_package_by_ftp()
+{
+	CATEGORY="${1}"
+	PACKAGE="${2}"
+	SAVEDIR="${3}"
+
+	get_value_from_cfg ftpHost
+	if [ -z "$VAL" ]
+	then
+		exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
+	fi
+	FTPHOST="${VAL}"
+
+	get_value_from_cfg ftpDir
+	if [ -z "$VAL" ]
+	then
+		exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
+	fi
+	FTPDIR="${VAL}"
+
+	PACKAGE="${PACKAGE}.tbz"
+	FTP_SERVER="ftp://${FTPHOST}${FTPDIR}"
+
+	if [ ! -f "${SAVEDIR}/${PACKAGE}" ]
+	then
+		PKGPATH="${CATEGORY}/${PACKAGE}"
+		FTP_PATH="${FTP_HOST}/packages/${PKGPATH}"
+		fetch_file "${FTP_PATH}" "${SAVEDIR}/" "0"
+	fi
+};
+
+fetch_package_by_fs()
+{
+	CATEGORY="${1}"
+	PACKAGE="${2}"
+	SAVEDIR="${3}"
+
+	PACKAGE="${PACKAGE}.tbz"
+	if [ ! -f "${SAVEDIR}/${PACKAGE}" ]
+	then
+		fetch_file "${CDMNT}/packages/${CATEGORY}/${PACKAGE}" "${SAVEDIR}/" "0"
+	fi
+};
+
 fetch_package()
 {
 	CATEGORY="${1}"
 	PACKAGE="${2}"
+	SAVEDIR="${3}"
 
-	get_ftp_mirror
-	FTP_SERVER="${VAL}"
-
-	PACKAGE="${PACKAGE}.tbz"
-	if [ ! -f "${PKGTMPDIR}/${PACKAGE}" ]
-	then
-		PKGPATH="${CATEGORY}/${PACKAGE}"
-		FTP_PATH="ftp://${FTP_SERVER}/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}/packages/${PKGPATH}"
-		fetch_file "${FTP_PATH}" "${PKGTMPDIR}/" "0"
-	fi
+	case "${INSTALLMEDIUM}" in
+	usb|dvd)
+		fetch_package_by_fs "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}"
+		;;
+	ftp)
+		fetch_package_by_ftp "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}"
+		;;
+	esac
 };

From 6784d5cdbd0ceb5f90d65c45a473407d0d501d39 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 06:02:31 +0000
Subject: [PATCH 0077/1624] Some cleanup, changed some echo's to echo_log,
 check for PROGDIR so that different PROGDIR's can be set.

PR:		148806
Submitted by:	John Hixson
---
 .../backend/functions-extractimage.sh            | 10 +++++-----
 .../pc-sysinstall/backend/functions-packages.sh  | 16 ++++++++++++++++
 .../pc-sysinstall/pc-sysinstall/pc-sysinstall.sh |  7 +++++--
 3 files changed, 26 insertions(+), 7 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
index de86711009e..54a742bcf6f 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
@@ -123,7 +123,7 @@ start_extract_split()
 	cd "${dir}"
 	if [ -f "install.sh" ]
 	then
-	  echo "Extracting" `basename ${dir}`
+	  echo_log "Extracting" `basename ${dir}`
       echo "y" | sh install.sh >/dev/null
       if [ "$?" != "0" ]
       then
@@ -139,7 +139,7 @@ start_extract_split()
   cd "${KERNELS}"
   if [ -f "install.sh" ]
   then
-	echo "Extracting" `basename ${KERNELS}`
+	echo_log "Extracting" `basename ${KERNELS}`
     echo "y" | sh install.sh generic >/dev/null
     if [ "$?" != "0" ]
     then
@@ -155,7 +155,7 @@ start_extract_split()
   cd "${SOURCE}"
   if [ -f "install.sh" ]
   then
-	echo "Extracting" `basename ${SOURCE}`
+	echo_log "Extracting" `basename ${SOURCE}`
     echo "y" | sh install.sh all >/dev/null
     if [ "$?" != "0" ]
     then
@@ -259,8 +259,8 @@ bye
 
 EOF
 
-   # Fetch the files via ftp
-   echo "$ INSTALL" | ftp -N "${NETRC}" "${FTPHOST}"
+  # Fetch the files via ftp
+  echo "$ INSTALL" | ftp -N "${NETRC}" "${FTPHOST}"
 
   # Done fetching, now reset the INSFILE to our downloaded archived
   INSFILE="${OUTFILE}" ; export INSFILE
diff --git a/usr.sbin/pc-sysinstall/backend/functions-packages.sh b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
index 1ec24be696e..161a511cf5d 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
@@ -63,6 +63,22 @@ get_package_index_by_fs()
 	fetch_file "${INDEX_FILE}" "${CONFDIR}/" "0"
 };
 
+get_package_index_size()
+{
+	if [ -f "${CONFDIR}/INDEX" ]
+	then
+		SIZE=`ls -l ${CONFDIR}/INDEX | awk '{ print $5 }'`
+	else
+		get_ftp_mirror
+		FTPHOST="${VAL}"
+
+		FTPDIR="/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}"
+		FTPPATH="ftp://${FTPHOST}${FTPDIR}/packages"
+
+		fetch -s "${FTPPATH}/INDEX.bz2"
+	fi
+};
+
 get_package_index()
 {
 	RES=0
diff --git a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
index 85bb6af45a6..3c48c48e829 100755
--- a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
+++ b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
@@ -36,8 +36,11 @@
 # User-editable configuration variables
 
 # Set this to the program location
-PROGDIR="/usr/share/pc-sysinstall"
-export PROGDIR
+if [ -z "${PROGDIR}" ]
+then
+	PROGDIR="/usr/share/pc-sysinstall"
+	export PROGDIR
+fi
 
 # Set this to the components location
 COMPDIR="${PROGDIR}/components"

From a13642d62d093b5a16f467d65d54fb9897d0f439 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 06:05:05 +0000
Subject: [PATCH 0078/1624] Simple patch to add support zpool virtual devices
 that are not currently supported.

PR:		149599
Submitted by:	John Hixson
---
 .../backend/functions-bsdlabel.sh             | 19 ++++++-------------
 1 file changed, 6 insertions(+), 13 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh b/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
index c974ac81354..e645263db0c 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
@@ -58,20 +58,13 @@ get_fs_line_xvars()
     echo $LINE | grep '^ZFS' >/dev/null 2>/dev/null
     if [ "$?" = "0" ] ; then
       ZTYPE="NONE"
-      ZFSVARS="`echo $LINE | cut -d '(' -f 2- | cut -d ')' -f 1`"
+      ZFSVARS="`echo $LINE | cut -d '(' -f 2- | cut -d ')' -f 1 | xargs`"
 
-      # Check if we are doing raidz setup
-      echo $ZFSVARS | grep "^raidz:" >/dev/null 2>/dev/null
-      if [ "$?" = "0" ] ; then
-       ZTYPE="raidz" 
-       ZFSVARS="`echo $ZFSVARS | sed 's|raidz: ||g' | sed 's|raidz:||g'`"
-      fi
-
-      echo $ZFSVARS | grep "^mirror:" >/dev/null 2>/dev/null
-      if [ "$?" = "0" ] ; then
-        ZTYPE="mirror" 
-        ZFSVARS="`echo $ZFSVARS | sed 's|mirror: ||g' | sed 's|mirror:||g'`"
-      fi
+      echo $ZFSVARS | grep -E "^(disk|file|mirror|raidz(1|2)?|spare|log|cache):" >/dev/null 2>/dev/null
+	  if [ "$?" = "0" ] ; then
+       ZTYPE=`echo $ZFSVARS | cut -f1 -d:`
+       ZFSVARS=`echo $ZFSVARS | sed "s|$ZTYPE: ||g" | sed "s|$ZTYPE:||g"`
+	  fi
 
       # Return the ZFS options
       if [ "${ZTYPE}" = "NONE" ] ; then

From 924a3731d342e122bdea95669501cdedb584bd5d Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 06:07:49 +0000
Subject: [PATCH 0079/1624] Added "-m" option to "disk-list" to list memory
 disks along with standard disks.

PR:		149749
Submitted by:	John Hixson
---
 usr.sbin/pc-sysinstall/backend-query/disk-info.sh  | 11 +++++++----
 usr.sbin/pc-sysinstall/backend-query/disk-list.sh  | 14 ++++++++++++++
 .../pc-sysinstall/pc-sysinstall/pc-sysinstall.sh   |  2 +-
 3 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend-query/disk-info.sh b/usr.sbin/pc-sysinstall/backend-query/disk-info.sh
index 643ae71772a..75b0cd4df9b 100755
--- a/usr.sbin/pc-sysinstall/backend-query/disk-info.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/disk-info.sh
@@ -54,15 +54,18 @@ HEADS="${VAL}"
 get_disk_sectors "${DISK}"
 SECS="${VAL}"
 
-echo "cylinders=${CYLS}"
-echo "heads=${HEADS}"
-echo "sectors=${SECS}"
 
 # Now get the disks size in MB
 KB="`diskinfo -v ${1} | grep 'bytes' | cut -d '#' -f 1 | tr -s '\t' ' ' | tr -d ' '`"
 MB=$(convert_byte_to_megabyte ${KB})
-echo "size=$MB"
 
 # Now get the Controller Type
 CTYPE="`dmesg | grep "^${1}:" | grep "B <" | cut -d '>' -f 2 | cut -d ' ' -f 3-10`"
+
+
+echo "cylinders=${CYLS}"
+echo "heads=${HEADS}"
+echo "sectors=${SECS}"
+echo "size=$MB"
 echo "type=$CTYPE"
+
diff --git a/usr.sbin/pc-sysinstall/backend-query/disk-list.sh b/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
index 1b59bafb7df..4694b1a94d0 100755
--- a/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
@@ -25,8 +25,18 @@
 #
 # $FreeBSD$
 
+ARGS=$1
+
 # Create our device listing
 SYSDISK=$(sysctl -n kern.disks)
+if [ "${ARGS}" = "-m" ]
+then
+	MDS=`mdconfig -l`
+	if [ -n "${MDS}" ]
+	then
+		SYSDISK="${SYSDISK} ${MDS}"
+	fi
+fi
 
 # Now loop through these devices, and list the disk drives
 for i in ${SYSDISK}
@@ -45,6 +55,10 @@ do
   if [ -z "$NEWLINE" ]; then
     NEWLINE=" "
   fi
+  if echo "${DEV}" | grep -E '^md[0-9]+' >/dev/null 2>/dev/null
+  then
+	NEWLINE=" "
+  fi
 
   # Save the disk list
   if [ ! -z "$DLIST" ]
diff --git a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
index 3c48c48e829..bae78c1f986 100755
--- a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
+++ b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
@@ -143,7 +143,7 @@ case $1 in
   ;;
 
   # The user is wanting to query which disks are available
-  disk-list) ${QUERYDIR}/disk-list.sh
+  disk-list) ${QUERYDIR}/disk-list.sh "${2}"
   ;;
   
   # The user is wanting to query a disk's partitions

From 683b1913347332d4fc61b2b2186c5de9da7a14a8 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 19 Aug 2010 06:11:06 +0000
Subject: [PATCH 0080/1624] This patch to pc-sysinstall allows the setting of a
 new config variable for installation, which lets the user/front-end select
 between MBR or GPT partitioning schemes when doing a dedicated disk
 installation.

PR:		149772
Submitted by:	Kris Moore
---
 .../pc-sysinstall/backend/functions-disk.sh   | 99 +++++++++++++++++--
 usr.sbin/pc-sysinstall/examples/README        |  5 +
 2 files changed, 97 insertions(+), 7 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend/functions-disk.sh b/usr.sbin/pc-sysinstall/backend/functions-disk.sh
index 48a77b306f2..bcce58ed20f 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-disk.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-disk.sh
@@ -406,6 +406,18 @@ setup_disk_slice()
        fi
      fi
 
+     # Check if we have a partscheme specified
+     echo $line | grep "^partscheme=" >/dev/null 2>/dev/null
+     if [ "$?" = "0" ] ; then
+       # Found a partscheme= entry, lets read / set it 
+       get_value_from_string "${line}"
+       strip_white_space "$VAL"
+       PSCHEME="$VAL"
+       if [ "$PSCHEME" != "GPT" -a "$PSCHEME" != "MBR" ] ; then
+	 exit_err "Unknown partition scheme: $PSCHEME" 
+       fi
+     fi
+
      echo $line | grep "^bootManager=" >/dev/null 2>/dev/null
      if [ "$?" = "0" ]
      then
@@ -422,8 +434,13 @@ setup_disk_slice()
        if [ ! -z "${DISK}" -a ! -z "${PTYPE}" ]
        then
          case ${PTYPE} in
-                   all|ALL) tmpSLICE="${DISK}p1"  
-                        run_gpart_full "${DISK}" "${BMANAGER}" ;;
+               all|ALL) if [ "$PSCHEME" = "MBR" -o -z "$PSCHEME" ] ; then
+			  PSCHEME="MBR"
+			  tmpSLICE="${DISK}s1"  
+			else
+			  tmpSLICE="${DISK}p1"  
+			fi
+                        run_gpart_full "${DISK}" "${BMANAGER}" "${PSCHEME}" ;;
            s1|s2|s3|s4) tmpSLICE="${DISK}${PTYPE}" 
                         # Get the number of the slice we are working on
                         s="`echo ${PTYPE} | awk '{print substr($0,length,1)}'`" 
@@ -449,7 +466,7 @@ setup_disk_slice()
 
 
          # Increment our disk counter to look for next disk and unset
-         unset BMANAGER PTYPE DISK MIRRORDISK MIRRORBAL
+         unset BMANAGER PTYPE DISK MIRRORDISK MIRRORBAL PSCHEME
          disknum="`expr $disknum + 1`"
        else
          exit_err "ERROR: commitDiskPart was called without procceding disk= and partition= entries!!!" 
@@ -477,7 +494,7 @@ stop_gjournal() {
   fi
 } ;
 
-# Function which runs gpart and creates a single large slice
+# Function which runs gpart and creates a single large GPT partition scheme
 init_gpt_full_disk()
 {
   _intDISK=$1
@@ -506,14 +523,82 @@ init_gpt_full_disk()
 
 }
 
+# Function which runs gpart and creates a single large MBR partition scheme
+init_mbr_full_disk()
+{
+  _intDISK=$1
+  _intBOOT=$2
+ 
+  startblock="63"
+
+  # Set our sysctl so we can overwrite any geom using drives
+  sysctl kern.geom.debugflags=16 >>${LOGOUT} 2>>${LOGOUT}
+
+  # Stop any journaling
+  stop_gjournal "${_intDISK}"
+
+  # Remove any existing partitions
+  delete_all_gpart "${_intDISK}"
+
+  #Erase any existing bootloader
+  echo_log "Cleaning up ${_intDISK}"
+  rc_halt "dd if=/dev/zero of=/dev/${_intDISK} count=2048"
+
+  sleep 2
+
+  echo_log "Running gpart on ${_intDISK}"
+  rc_halt "gpart create -s mbr ${_intDISK}"
+
+  # Lets figure out disk size in blocks
+  # Get the cyl of this disk
+  get_disk_cyl "${_intDISK}"
+  cyl="${VAL}"
+
+  # Get the heads of this disk
+  get_disk_heads "${_intDISK}"
+  head="${VAL}"
+
+  # Get the tracks/sectors of this disk
+  get_disk_sectors "${_intDISK}"
+  sec="${VAL}"
+
+  # Multiply them all together to get our total blocks
+  totalblocks="`expr ${cyl} \* ${head}`"
+  totalblocks="`expr ${totalblocks} \* ${sec}`"
+
+
+  # Now set the ending block to the total disk block size
+  sizeblock="`expr ${totalblocks} - ${startblock}`"
+
+  # Install new partition setup
+  echo_log "Running gpart add on ${_intDISK}"
+  rc_halt "gpart add -b ${startblock} -s ${sizeblock} -t freebsd -i 1 ${_intDISK}"
+  sleep 2
+  
+  echo_log "Cleaning up ${_intDISK}s1"
+  rc_halt "dd if=/dev/zero of=/dev/${_intDISK}s1 count=1024"
+  
+  if [ "$_intBOOT" = "bsd" ] ; then
+    echo_log "Stamping boot sector on ${_intDISK}"
+    rc_halt "gpart bootcode -b /boot/boot0 ${_intDISK}"
+  fi
+
+}
+
 # Function which runs gpart and creates a single large slice
 run_gpart_full()
 {
   DISK=$1
+  BOOT=$2
+  SCHEME=$3
 
-  init_gpt_full_disk "$DISK"
-
-  slice="${DISK}-1-gpt"
+  if [ "$SCHEME" = "MBR" ] ; then
+    init_mbr_full_disk "$DISK" "$BOOT"
+    slice="${DISK}-1-mbr"
+  else
+    init_gpt_full_disk "$DISK"
+    slice="${DISK}-1-gpt"
+  fi
 
   # Lets save our slice, so we know what to look for in the config file later on
   if [ -z "$WORKINGSLICES" ]
diff --git a/usr.sbin/pc-sysinstall/examples/README b/usr.sbin/pc-sysinstall/examples/README
index 55d78e43d3f..eeb96d0ea2f 100644
--- a/usr.sbin/pc-sysinstall/examples/README
+++ b/usr.sbin/pc-sysinstall/examples/README
@@ -128,6 +128,11 @@ Setting this to "s1, s2, s3 or s4" will use the specified MBR slice
 
 (This tag is unused for upgrades)
 
+# partscheme=(MBR/GPT)
+
+When performing a "full" disk (partition=all), the partscheme= variable is used
+to determine the partition scheme type gpart will be using on the disk. Valid
+choices are MBR or GPT. 
 
 # mirror=(disk device such as ad1)
 

From a0ef9ad699a02f3a706d16a525f0c4d243c71c34 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Thu, 19 Aug 2010 09:28:59 +0000
Subject: [PATCH 0081/1624] UTFize my name.

---
 usr.bin/grep/fastgrep.c | 2 +-
 usr.bin/grep/file.c     | 2 +-
 usr.bin/grep/grep.c     | 2 +-
 usr.bin/grep/grep.h     | 2 +-
 usr.bin/grep/queue.c    | 2 +-
 usr.bin/grep/util.c     | 2 +-
 6 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/usr.bin/grep/fastgrep.c b/usr.bin/grep/fastgrep.c
index 30a2dc50b0d..d232ac61052 100644
--- a/usr.bin/grep/fastgrep.c
+++ b/usr.bin/grep/fastgrep.c
@@ -1,7 +1,7 @@
 /*	$OpenBSD: util.c,v 1.36 2007/10/02 17:59:18 otto Exp $	*/
 
 /*-
- * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
  * Copyright (C) 2008 Gabor Kovesdan 
  * All rights reserved.
  *
diff --git a/usr.bin/grep/file.c b/usr.bin/grep/file.c
index 51be53d8909..d19d57c7a1a 100644
--- a/usr.bin/grep/file.c
+++ b/usr.bin/grep/file.c
@@ -1,7 +1,7 @@
 /*	$OpenBSD: file.c,v 1.11 2010/07/02 20:48:48 nicm Exp $	*/
 
 /*-
- * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
  * Copyright (C) 2008-2010 Gabor Kovesdan 
  * Copyright (C) 2010 Dimitry Andric 
  * All rights reserved.
diff --git a/usr.bin/grep/grep.c b/usr.bin/grep/grep.c
index 12217850865..3cb277cb97a 100644
--- a/usr.bin/grep/grep.c
+++ b/usr.bin/grep/grep.c
@@ -1,7 +1,7 @@
 /*	$OpenBSD: grep.c,v 1.42 2010/07/02 22:18:03 tedu Exp $	*/
 
 /*-
- * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
  * Copyright (C) 2008-2009 Gabor Kovesdan 
  * All rights reserved.
  *
diff --git a/usr.bin/grep/grep.h b/usr.bin/grep/grep.h
index cf4443dfce5..5235e0218c9 100644
--- a/usr.bin/grep/grep.h
+++ b/usr.bin/grep/grep.h
@@ -2,7 +2,7 @@
 /*	$FreeBSD$	*/
 
 /*-
- * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
  * Copyright (c) 2008-2009 Gabor Kovesdan 
  * All rights reserved.
  *
diff --git a/usr.bin/grep/queue.c b/usr.bin/grep/queue.c
index dcef7f8fd43..b44c0e122a3 100644
--- a/usr.bin/grep/queue.c
+++ b/usr.bin/grep/queue.c
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
diff --git a/usr.bin/grep/util.c b/usr.bin/grep/util.c
index 7ebbb5513ce..c65d8f23f95 100644
--- a/usr.bin/grep/util.c
+++ b/usr.bin/grep/util.c
@@ -1,7 +1,7 @@
 /*	$OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $	*/
 
 /*-
- * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
  * Copyright (C) 2008-2010 Gabor Kovesdan 
  * All rights reserved.
  *

From 8d19ed7cbc0d2b10b163f53f8bc23c7d1f0aa81c Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 11:16:52 +0000
Subject: [PATCH 0082/1624] style(9) pick from imp@ .

---
 sys/mips/atheros/if_arge.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/sys/mips/atheros/if_arge.c b/sys/mips/atheros/if_arge.c
index 3930b180cb3..6cc627dec74 100644
--- a/sys/mips/atheros/if_arge.c
+++ b/sys/mips/atheros/if_arge.c
@@ -182,11 +182,10 @@ MTX_SYSINIT(miibus_mtx, &miibus_mtx, "arge mii lock", MTX_DEF);
 static void
 arge_flush_ddr(struct arge_softc *sc)
 {
-	if (sc->arge_mac_unit == 0) {
+	if (sc->arge_mac_unit == 0)
 		ar71xx_device_flush_ddr_ge0();
-	} else {
+	else
 		ar71xx_device_flush_ddr_ge1();
-	}
 }
 
 static int 

From c2ddd1eef707b31a79ccc786e9f925c3d9ea9424 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 11:18:50 +0000
Subject: [PATCH 0083/1624] Add missing licence.

---
 sys/mips/atheros/ar71xx_chip.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/sys/mips/atheros/ar71xx_chip.c b/sys/mips/atheros/ar71xx_chip.c
index ae6340df6ec..937803d2cf2 100644
--- a/sys/mips/atheros/ar71xx_chip.c
+++ b/sys/mips/atheros/ar71xx_chip.c
@@ -1,3 +1,29 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
 #include 
 __FBSDID("$FreeBSD$");
 

From 1727cdb62a65c114533b77595aee3960a14a2cef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Thu, 19 Aug 2010 11:19:21 +0000
Subject: [PATCH 0084/1624] expand_number(3) takes a uint64_t * now.

MFC after:	3 weeks
---
 sbin/ipfw/dummynet.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sbin/ipfw/dummynet.c b/sbin/ipfw/dummynet.c
index ea653b77027..f9341971234 100644
--- a/sbin/ipfw/dummynet.c
+++ b/sbin/ipfw/dummynet.c
@@ -1130,7 +1130,7 @@ end_mask:
 			NEED(p, "burst");
 			NEED1("burst needs argument\n");
 			errno = 0;
-			if (expand_number(av[0], (int64_t *)&p->burst) < 0)
+			if (expand_number(av[0], &p->burst) < 0)
 				if (errno != ERANGE)
 					errx(EX_DATAERR,
 					    "burst: invalid argument");

From 35efcc8b69e2e7665a9f8bfcd2564ea94bfef9f8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Thu, 19 Aug 2010 11:20:24 +0000
Subject: [PATCH 0085/1624] expand_number(3) takes a uint64_t * now; intmax_t
 was never correct except by accident.

MFC after:	3 weeks
---
 sbin/geom/core/geom.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index 49ebdc5364a..f673aad5413 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -237,7 +237,7 @@ static void
 set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 {
 	char *s;
-	intmax_t number;
+	uint64_t number;
 
 	if (G_OPT_TYPE(opt) == G_TYPE_NUMBER ||
 	    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {

From 1db8d1f8433157f6579fa297b1959d67540782b4 Mon Sep 17 00:00:00 2001
From: Ana Kukec 
Date: Thu, 19 Aug 2010 11:31:03 +0000
Subject: [PATCH 0086/1624] MFp4: anchie_soc2009 branch:

Add kernel side support for Secure Neighbor Discovery (SeND), RFC 3971.

The implementation consists of a kernel module that gets packets from
the nd6 code, sends them to user space on a dedicated socket and reinjects
them back for further processing.

Hooks are used from nd6 code paths to divert relevant packets to the
send implementation for processing in user space.  The hooks are only
triggered if the send module is loaded. In case no user space
application is connected to the send socket, processing continues
normaly as if the module would not be loaded. Unloading the module
is not possible at this time due to missing nd6 locking.

The native SeND socket is similar to a raw IPv6 socket but with its own,
internal pseudo-protocol.

Approved by:	bz (mentor)
---
 sys/modules/Makefile      |   1 +
 sys/modules/send/Makefile |   7 +
 sys/netinet/in.h          |   1 +
 sys/netinet6/icmp6.c      | 125 +++++++++++--
 sys/netinet6/nd6.c        |  28 +++
 sys/netinet6/nd6_nbr.c    |  31 ++++
 sys/netinet6/raw_ip6.c    |  20 +++
 sys/netinet6/send.c       | 367 ++++++++++++++++++++++++++++++++++++++
 sys/netinet6/send.h       |  45 +++++
 sys/sys/mbuf.h            |   1 +
 10 files changed, 612 insertions(+), 14 deletions(-)
 create mode 100644 sys/modules/send/Makefile
 create mode 100644 sys/netinet6/send.c
 create mode 100644 sys/netinet6/send.h

diff --git a/sys/modules/Makefile b/sys/modules/Makefile
index 8d8b394fcba..200d81476c5 100644
--- a/sys/modules/Makefile
+++ b/sys/modules/Makefile
@@ -257,6 +257,7 @@ SUBDIR=	${_3dfx} \
 	${_scsi_low} \
 	sdhci \
 	sem \
+	send \
 	sf \
 	sge \
 	siba_bwn \
diff --git a/sys/modules/send/Makefile b/sys/modules/send/Makefile
new file mode 100644
index 00000000000..1cb976b9b8d
--- /dev/null
+++ b/sys/modules/send/Makefile
@@ -0,0 +1,7 @@
+# $FreeBSD$
+.PATH: ${.CURDIR}/../../netinet6
+
+KMOD=	send
+SRCS=	send.c
+
+.include 
diff --git a/sys/netinet/in.h b/sys/netinet/in.h
index 9eb3b177c16..e453b692e75 100644
--- a/sys/netinet/in.h
+++ b/sys/netinet/in.h
@@ -252,6 +252,7 @@ __END_DECLS
 
 /* Only used internally, so can be outside the range of valid IP protocols. */
 #define	IPPROTO_DIVERT		258		/* divert pseudo-protocol */
+#define	IPPROTO_SEND		259		/* SeND pseudo-protocol */
 
 /*
  * Defined to avoid confusion.  The master value is defined by
diff --git a/sys/netinet6/icmp6.c b/sys/netinet6/icmp6.c
index 87df9c369c8..47657b2c0c1 100644
--- a/sys/netinet6/icmp6.c
+++ b/sys/netinet6/icmp6.c
@@ -105,6 +105,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #ifdef IPSEC
 #include 
@@ -414,6 +415,7 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 	int icmp6len = m->m_pkthdr.len - *offp;
 	int code, sum, noff;
 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
+	int ip6len, error;
 
 	ifp = m->m_pkthdr.rcvif;
 
@@ -428,6 +430,7 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 	 */
 
 	ip6 = mtod(m, struct ip6_hdr *);
+	ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
 	if (icmp6len < sizeof(struct icmp6_hdr)) {
 		ICMP6STAT_INC(icp6s_tooshort);
 		goto freeit;
@@ -766,11 +769,35 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			goto badlen;
 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
 			/* give up local */
-			nd6_rs_input(m, off, icmp6len);
+
+			/* Send incoming SeND packet to user space. */
+			if (send_sendso_input_hook != NULL) {
+				IP6_EXTHDR_CHECK(m, off,
+				    icmp6len, IPPROTO_DONE);
+				error = send_sendso_input_hook(m, ifp,
+				    SND_IN, ip6len);
+				/* -1 == no app on SEND socket */
+				if (error == 0)
+					return (IPPROTO_DONE);
+				nd6_rs_input(m, off, icmp6len);
+			} else
+				nd6_rs_input(m, off, icmp6len);
 			m = NULL;
 			goto freeit;
 		}
-		nd6_rs_input(n, off, icmp6len);
+		if (send_sendso_input_hook != NULL) {
+			IP6_EXTHDR_CHECK(m, off,
+			    icmp6len, IPPROTO_DONE);
+                        error = send_sendso_input_hook(n, ifp,
+			    SND_IN, ip6len);
+			if (error == 0) {
+				m_freem(n);
+				return (IPPROTO_DONE);
+			}
+			/* -1 == no app on SEND socket */
+			nd6_rs_input(n, off, icmp6len);
+		} else
+			nd6_rs_input(n, off, icmp6len);
 		/* m stays. */
 		break;
 
@@ -781,12 +808,28 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 		if (icmp6len < sizeof(struct nd_router_advert))
 			goto badlen;
 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
-			/* give up local */
-			nd6_ra_input(m, off, icmp6len);
+
+			/* Send incoming SeND-protected/ND packet to user space. */
+			if (send_sendso_input_hook != NULL) {
+				error = send_sendso_input_hook(m, ifp,
+				    SND_IN, ip6len);
+				if (error == 0)
+					return (IPPROTO_DONE);
+				nd6_ra_input(m, off, icmp6len);
+			} else
+				nd6_ra_input(m, off, icmp6len);
 			m = NULL;
+			m_freem(n);
 			goto freeit;
 		}
-		nd6_ra_input(n, off, icmp6len);
+		if (send_sendso_input_hook != NULL) {
+			error = send_sendso_input_hook(n, ifp,
+			    SND_IN, ip6len);
+			if (error == 0)
+				return (IPPROTO_DONE);
+			nd6_ra_input(n, off, icmp6len);
+		} else
+			nd6_ra_input(n, off, icmp6len);
 		/* m stays. */
 		break;
 
@@ -797,12 +840,26 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 		if (icmp6len < sizeof(struct nd_neighbor_solicit))
 			goto badlen;
 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
-			/* give up local */
-			nd6_ns_input(m, off, icmp6len);
+			if (send_sendso_input_hook != NULL) {
+				error = send_sendso_input_hook(m, ifp,
+				    SND_IN, ip6len);
+				if (error == 0)
+					return (IPPROTO_DONE);
+				nd6_ns_input(m, off, icmp6len);
+			} else
+				nd6_ns_input(m, off, icmp6len);
+			m_freem(n);
 			m = NULL;
 			goto freeit;
 		}
-		nd6_ns_input(n, off, icmp6len);
+		if (send_sendso_input_hook != NULL) {
+			error = send_sendso_input_hook(n, ifp,
+			    SND_IN, ip6len);
+			if (error == 0)
+				return (IPPROTO_DONE);
+			nd6_ns_input(n, off, icmp6len);
+		} else
+			nd6_ns_input(n, off, icmp6len);
 		/* m stays. */
 		break;
 
@@ -813,12 +870,28 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 		if (icmp6len < sizeof(struct nd_neighbor_advert))
 			goto badlen;
 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
-			/* give up local */
-			nd6_na_input(m, off, icmp6len);
+
+			/* Send incoming SeND-protected/ND packet to user space. */
+			if (send_sendso_input_hook != NULL) {
+				error = send_sendso_input_hook(m, ifp,
+				    SND_IN, ip6len);
+				if (error == 0)
+					return (IPPROTO_DONE);
+				nd6_na_input(m, off, icmp6len);
+			} else
+				nd6_na_input(m, off, icmp6len);
+			m_freem(n);
 			m = NULL;
 			goto freeit;
 		}
-		nd6_na_input(n, off, icmp6len);
+		if (send_sendso_input_hook != NULL) {
+			error = send_sendso_input_hook(n, ifp,
+			    SND_IN, ip6len);
+			if (error == 0)
+				return (IPPROTO_DONE);
+			nd6_na_input(n, off, icmp6len);
+		} else
+			nd6_na_input(n, off, icmp6len);
 		/* m stays. */
 		break;
 
@@ -829,12 +902,26 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 		if (icmp6len < sizeof(struct nd_redirect))
 			goto badlen;
 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
-			/* give up local */
-			icmp6_redirect_input(m, off);
+			if (send_sendso_input_hook != NULL) {
+				error = send_sendso_input_hook(m, ifp,
+				    SND_IN, ip6len);
+		 		if (error == 0)
+					return (IPPROTO_DONE);
+			    icmp6_redirect_input(m, off);
+			} else
+				icmp6_redirect_input(m, off);
+			m_freem(n);
 			m = NULL;
 			goto freeit;
 		}
-		icmp6_redirect_input(n, off);
+		if (send_sendso_input_hook != NULL) {
+			error = send_sendso_input_hook(n, ifp,
+			    SND_IN, ip6len);
+			if (error == 0)
+				return (IPPROTO_DONE);
+			icmp6_redirect_input(n, off);
+		} else
+			icmp6_redirect_input(n, off);
 		/* m stays. */
 		break;
 
@@ -2476,6 +2563,7 @@ icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
 	struct in6_addr *router_ll6;
 	struct ip6_hdr *sip6;	/* m0 as struct ip6_hdr */
 	struct mbuf *m = NULL;	/* newly allocated one */
+	struct m_tag *mtag;
 	struct ip6_hdr *ip6;	/* m as struct ip6_hdr */
 	struct nd_redirect *nd_rd;
 	struct llentry *ln = NULL;
@@ -2735,6 +2823,15 @@ noredhdropt:;
 	nd_rd->nd_rd_cksum = in6_cksum(m, IPPROTO_ICMPV6,
 	    sizeof(*ip6), ntohs(ip6->ip6_plen));
 
+        if (send_sendso_input_hook != NULL) {
+		mtag = m_tag_get(PACKET_TAG_ND_OUTGOING, sizeof(unsigned short),
+			M_NOWAIT);
+		if (mtag == NULL)
+			goto fail;
+		*(unsigned short *)(mtag + 1) = nd_rd->nd_rd_type;
+		m_tag_prepend(m, mtag);
+	}
+
 	/* send the packet to outside... */
 	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
 	if (outif) {
diff --git a/sys/netinet6/nd6.c b/sys/netinet6/nd6.c
index e9081c404c3..c9d9be05869 100644
--- a/sys/netinet6/nd6.c
+++ b/sys/netinet6/nd6.c
@@ -72,6 +72,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -121,6 +122,8 @@ VNET_DEFINE(int, nd6_recalc_reachtm_interval) = ND6_RECALC_REACHTM_INTERVAL;
 
 static struct sockaddr_in6 all1_sa;
 
+int	(*send_sendso_input_hook)(struct mbuf *, struct ifnet *, int, int);
+
 static int nd6_is_new_addr_neighbor __P((struct sockaddr_in6 *,
 	struct ifnet *));
 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
@@ -1758,9 +1761,12 @@ nd6_output_lle(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
 	struct mbuf **chain)
 {
 	struct mbuf *m = m0;
+	struct m_tag *mtag;
 	struct llentry *ln = lle;
+	struct ip6_hdr *ip6;
 	int error = 0;
 	int flags = 0;
+	int ip6len;
 
 #ifdef INVARIANTS
 	if (lle != NULL) {
@@ -1935,6 +1941,28 @@ nd6_output_lle(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
 #ifdef MAC
 	mac_netinet6_nd6_send(ifp, m);
 #endif
+
+	/*
+	 * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
+	 * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
+	 * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
+	 * to be diverted to user space.  When re-injected into the kernel,
+	 * send_output() will directly dispatch them to the outgoing interface.
+	 */
+	if (send_sendso_input_hook != NULL) {
+		mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
+		if (mtag != NULL) {
+			ip6 = mtod(m, struct ip6_hdr *);
+			ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
+			/* Use the SEND socket */
+			error = send_sendso_input_hook(m, ifp, SND_OUT,
+			    ip6len);
+			/* -1 == no app on SEND socket */
+			if (error == 0 || error != -1)
+			    return (error);
+		}
+	}
+
 	/*
 	 * We were passed in a pointer to an lle with the lock held 
 	 * this means that we can't call if_output as we will
diff --git a/sys/netinet6/nd6_nbr.c b/sys/netinet6/nd6_nbr.c
index 130189d079b..957e9652843 100644
--- a/sys/netinet6/nd6_nbr.c
+++ b/sys/netinet6/nd6_nbr.c
@@ -73,6 +73,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #define SDL(s) ((struct sockaddr_dl *)s)
 
@@ -379,6 +380,7 @@ nd6_ns_output(struct ifnet *ifp, const struct in6_addr *daddr6,
     const struct in6_addr *taddr6, struct llentry *ln, int dad)
 {
 	struct mbuf *m;
+	struct m_tag *mtag;
 	struct ip6_hdr *ip6;
 	struct nd_neighbor_solicit *nd_ns;
 	struct in6_addr *src, src_in;
@@ -557,6 +559,15 @@ nd6_ns_output(struct ifnet *ifp, const struct in6_addr *daddr6,
 	nd_ns->nd_ns_cksum =
 	    in6_cksum(m, IPPROTO_ICMPV6, sizeof(*ip6), icmp6len);
 
+	if (send_sendso_input_hook != NULL) {
+		mtag = m_tag_get(PACKET_TAG_ND_OUTGOING,
+			sizeof(unsigned short), M_NOWAIT);
+		if (mtag == NULL)
+			goto bad;
+		*(unsigned short *)(mtag + 1) = nd_ns->nd_ns_type;
+		m_tag_prepend(m, mtag);
+	}
+
 	ip6_output(m, NULL, &ro, dad ? IPV6_UNSPECSRC : 0, &im6o, NULL, NULL);
 	icmp6_ifstat_inc(ifp, ifs6_out_msg);
 	icmp6_ifstat_inc(ifp, ifs6_out_neighborsolicit);
@@ -604,6 +615,7 @@ nd6_na_input(struct mbuf *m, int off, int icmp6len)
 	struct llentry *ln = NULL;
 	union nd_opts ndopts;
 	struct mbuf *chain = NULL;
+	struct m_tag *mtag;
 	struct sockaddr_in6 sin6;
 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
 
@@ -873,6 +885,15 @@ nd6_na_input(struct mbuf *m, int off, int icmp6len)
 			 * we assume ifp is not a loopback here, so just set
 			 * the 2nd argument as the 1st one.
 			 */
+
+			if (send_sendso_input_hook != NULL) {
+				mtag = m_tag_get(PACKET_TAG_ND_OUTGOING,
+				    sizeof(unsigned short), M_NOWAIT);
+				if (mtag == NULL)
+					goto bad;
+				m_tag_prepend(m, mtag);
+			}
+
 			nd6_output_lle(ifp, ifp, m_hold, L3_ADDR_SIN6(ln), NULL, ln, &chain);
 		}
 	}
@@ -917,6 +938,7 @@ nd6_na_output(struct ifnet *ifp, const struct in6_addr *daddr6_0,
     struct sockaddr *sdl0)
 {
 	struct mbuf *m;
+	struct m_tag *mtag;
 	struct ip6_hdr *ip6;
 	struct nd_neighbor_advert *nd_na;
 	struct ip6_moptions im6o;
@@ -1055,6 +1077,15 @@ nd6_na_output(struct ifnet *ifp, const struct in6_addr *daddr6_0,
 	nd_na->nd_na_cksum =
 	    in6_cksum(m, IPPROTO_ICMPV6, sizeof(struct ip6_hdr), icmp6len);
 
+	if (send_sendso_input_hook != NULL) {
+		mtag = m_tag_get(PACKET_TAG_ND_OUTGOING,
+		    sizeof(unsigned short), M_NOWAIT);
+		if (mtag == NULL)
+			goto bad;
+		*(unsigned short *)(mtag + 1) = nd_na->nd_na_type;
+		m_tag_prepend(m, mtag);
+	}
+
 	ip6_output(m, NULL, &ro, 0, &im6o, NULL, NULL);
 	icmp6_ifstat_inc(ifp, ifs6_out_msg);
 	icmp6_ifstat_inc(ifp, ifs6_out_neighboradvert);
diff --git a/sys/netinet6/raw_ip6.c b/sys/netinet6/raw_ip6.c
index 936536087f6..0e5e8e07e17 100644
--- a/sys/netinet6/raw_ip6.c
+++ b/sys/netinet6/raw_ip6.c
@@ -92,6 +92,7 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -99,6 +100,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #ifdef IPSEC
 #include 
@@ -390,6 +392,7 @@ rip6_output(m, va_alist)
 #endif
 {
 	struct mbuf *control;
+	struct m_tag *mtag;
 	struct socket *so;
 	struct sockaddr_in6 *dstsock;
 	struct in6_addr *dst;
@@ -532,6 +535,23 @@ rip6_output(m, va_alist)
 		*p = in6_cksum(m, ip6->ip6_nxt, sizeof(*ip6), plen);
 	}
 
+	/*
+	 * Send RA/RS messages to user land for protection, before sending
+	 * them to rtadvd/rtsol.
+	 */
+	if ((send_sendso_input_hook != NULL) &&
+	    so->so_proto->pr_protocol == IPPROTO_ICMPV6) {
+		switch (type) {
+		case ND_ROUTER_ADVERT:
+		case ND_ROUTER_SOLICIT:
+			mtag = m_tag_get(PACKET_TAG_ND_OUTGOING,
+				sizeof(unsigned short), M_NOWAIT);
+			if (mtag == NULL)
+				goto bad;
+			m_tag_prepend(m, mtag);
+		}
+	}
+
 	error = ip6_output(m, optp, NULL, 0, in6p->in6p_moptions, &oifp, in6p);
 	if (so->so_proto->pr_protocol == IPPROTO_ICMPV6) {
 		if (oifp)
diff --git a/sys/netinet6/send.c b/sys/netinet6/send.c
new file mode 100644
index 00000000000..71d88d07a8a
--- /dev/null
+++ b/sys/netinet6/send.c
@@ -0,0 +1,367 @@
+/*-
+ * Copyright (c) 2009-2010 Ana Kukec 
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+MALLOC_DEFINE(M_SEND, "send", "Secure Neighbour Discovery");
+
+/*
+ * The socket used to communicate with the SeND daemon.
+ */
+static VNET_DEFINE(struct socket *, send_so);
+#define	V_send_so	VNET(send_so)
+
+u_long	send_sendspace	= 8 * (1024 + sizeof(struct sockaddr_send));
+u_long	send_recvspace	= 9216;
+
+struct mtx	send_mtx;
+#define SEND_LOCK_INIT()	mtx_init(&send_mtx, "send_mtx", NULL, MTX_DEF)
+#define SEND_LOCK()		mtx_lock(&send_mtx)
+#define SEND_UNLOCK()		mtx_unlock(&send_mtx)
+#define SEND_LOCK_DESTROY()     mtx_destroy(&send_mtx)
+
+static int
+send_attach(struct socket *so, int proto, struct thread *td)
+{
+	int error;
+
+	SEND_LOCK();
+	if (V_send_so != NULL) {
+		SEND_UNLOCK();
+		return (EEXIST);
+	}
+
+	error = priv_check(td, PRIV_NETINET_RAW);
+	if (error) {
+		SEND_UNLOCK();
+		return(error);
+	}
+
+	if (proto != IPPROTO_SEND) {
+		SEND_UNLOCK();
+		return (EPROTONOSUPPORT);
+	}
+	error = soreserve(so, send_sendspace, send_recvspace);
+	if (error) {
+		SEND_UNLOCK();
+		return(error);
+	}
+
+	V_send_so = so;
+	SEND_UNLOCK();
+
+	return (0);
+}
+
+static int
+send_output(struct mbuf *m, struct ifnet *ifp, int direction)
+{
+	struct ip6_hdr *ip6;
+	struct sockaddr_in6 dst;
+	struct icmp6_hdr *icmp6;
+	int icmp6len;
+
+	/*
+	 * Receive incoming (SeND-protected) or outgoing traffic
+	 * (SeND-validated) from the SeND user space application.
+	 */
+
+	switch (direction) {
+	case SND_IN:
+		if (m->m_len < (sizeof(struct ip6_hdr) +
+		    sizeof(struct icmp6_hdr))) {
+			m = m_pullup(m, sizeof(struct ip6_hdr) +
+			    sizeof(struct icmp6_hdr));
+			if (!m)
+				return (ENOBUFS);
+		}
+
+		/* Before passing off the mbuf record the proper interface. */
+		m->m_pkthdr.rcvif = ifp;
+
+		if (m->m_flags & M_PKTHDR)
+			icmp6len = m->m_pkthdr.len - sizeof(struct ip6_hdr);
+		else
+			panic("Doh! not the first mbuf.");
+
+		ip6 = mtod(m, struct ip6_hdr *);
+		icmp6 = (struct icmp6_hdr *)(ip6 + 1);
+
+		/*
+		 * Output the packet as icmp6.c:icpm6_input() would do.
+		 * The mbuf is always consumed, so we do not have to
+		 * care about that.
+		 */
+		switch (icmp6->icmp6_type) {
+		case ND_NEIGHBOR_SOLICIT:
+			nd6_ns_input(m, sizeof(struct ip6_hdr), icmp6len);
+			break;
+		case ND_NEIGHBOR_ADVERT:
+			nd6_na_input(m, sizeof(struct ip6_hdr), icmp6len);
+			break;
+		case ND_REDIRECT:
+			icmp6_redirect_input(m, sizeof(struct ip6_hdr));
+			break;
+		case ND_ROUTER_SOLICIT:
+			nd6_rs_input(m, sizeof(struct ip6_hdr), icmp6len);
+			break;
+		case ND_ROUTER_ADVERT:
+			nd6_ra_input(m, sizeof(struct ip6_hdr), icmp6len);
+			break;
+		default:
+			return (ENOSYS);
+		}
+		return (0);
+
+	case SND_OUT:
+		if (m->m_len < sizeof(struct ip6_hdr)) {
+			m = m_pullup(m, sizeof(struct ip6_hdr));
+			if (!m)
+				return (ENOBUFS);
+		}
+		ip6 = mtod(m, struct ip6_hdr *);
+		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
+			m->m_flags |= M_MCAST;
+
+		bzero(&dst, sizeof(dst));
+		dst.sin6_family = AF_INET6;
+		dst.sin6_len = sizeof(dst);
+		dst.sin6_addr = ip6->ip6_dst;
+
+		/*
+		 * Output the packet as nd6.c:nd6_output_lle() would do.
+		 * The mbuf is always consumed, so we do not have to care
+		 * about that.
+		 * XXX-BZ as we added data, what about fragmenting,
+		 * if now needed?
+		 */
+		int error;
+		error = ((*ifp->if_output)(ifp, m, (struct sockaddr *)&dst,
+		    NULL));
+		if (error)
+			error = ENOENT;
+		return (error);
+
+	default:
+		panic("%s: direction %d neither SND_IN nor SND_OUT.",
+		     __func__, direction);
+	}
+}
+
+/*
+ * Receive a SeND message from user space to be either send out by the kernel
+ * or, with SeND ICMPv6 options removed, to be further processed by the icmp6
+ * input path.
+ */
+static int
+send_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
+    struct mbuf *control, struct thread *td)
+{
+	struct sockaddr_send *sendsrc;
+	struct ifnet *ifp;
+	int error;
+
+	KASSERT(V_send_so == so, ("%s: socket %p not send socket %p",
+		__func__, so, V_send_so));
+
+	sendsrc = (struct sockaddr_send *)nam;
+	ifp = ifnet_byindex_ref(sendsrc->send_ifidx);
+	if (ifp == NULL) {
+		error = ENETUNREACH;
+		goto err;
+	}
+
+	error = send_output(m, ifp, sendsrc->send_direction);
+	if_rele(ifp);
+	m = NULL;
+
+err:
+	if (m != NULL)
+		m_freem(m);
+	return (error);
+}
+
+static void
+send_close(struct socket *so)
+{
+
+	SEND_LOCK();
+	if (V_send_so)
+		V_send_so = NULL;
+	SEND_UNLOCK();
+}
+
+/*
+ * Send a SeND message to user space, that was either received and has to be
+ * validated or was about to be send out and has to be handled by the SEND
+ * daemon adding SeND ICMPv6 options.
+ */
+static int
+send_input(struct mbuf *m, struct ifnet *ifp, int direction, int msglen __unused)
+{
+	struct ip6_hdr *ip6;
+	struct sockaddr_send sendsrc;
+
+	SEND_LOCK();
+	if (V_send_so == NULL) {
+		SEND_UNLOCK();
+		return (-1);
+	}
+
+	/*
+	 * Make sure to clear any possible internally embedded scope before
+	 * passing the packet to user space for SeND cryptographic signature
+	 * validation to succeed.
+	 */
+	ip6 = mtod(m, struct ip6_hdr *);
+	in6_clearscope(&ip6->ip6_src);
+	in6_clearscope(&ip6->ip6_dst);
+
+	bzero(&sendsrc, sizeof(sendsrc));
+	sendsrc.send_len = sizeof(sendsrc);
+	sendsrc.send_family = AF_INET6;
+	sendsrc.send_direction = direction;
+	sendsrc.send_ifidx = ifp->if_index;
+
+	/*
+	 * Send incoming or outgoing traffic to user space either to be
+	 * protected (outgoing) or validated (incoming) according to rfc3971.
+	 */
+	SOCKBUF_LOCK(&V_send_so->so_rcv);
+	if (sbappendaddr_locked(&V_send_so->so_rcv,
+	    (struct sockaddr *)&sendsrc, m, NULL) == 0) {
+		SOCKBUF_UNLOCK(&V_send_so->so_rcv);
+		/* XXX stats. */
+		m_freem(m);
+	} else {
+		sorwakeup_locked(V_send_so);
+	}
+
+	SEND_UNLOCK();
+	return (0);
+}
+
+struct pr_usrreqs send_usrreqs = {
+	.pru_attach =		send_attach,
+	.pru_send =		send_send,
+	.pru_detach =		send_close
+};
+struct protosw send_protosw = {
+	.pr_type =		SOCK_RAW,
+	.pr_flags =		PR_ATOMIC|PR_ADDR,
+	.pr_protocol =		IPPROTO_SEND,
+	.pr_usrreqs =		&send_usrreqs
+};
+
+static int
+send_modevent(module_t mod, int type, void *unused)
+{
+#ifdef __notyet__
+	VNET_ITERATOR_DECL(vnet_iter);
+#endif
+	int error;
+
+	switch (type) {
+	case MOD_LOAD:
+		SEND_LOCK_INIT();
+
+		error = pf_proto_register(PF_INET6, &send_protosw);
+		if (error != 0) {
+			printf("%s:%d: MOD_LOAD pf_proto_register(): %d\n",
+			   __func__, __LINE__, error);
+			SEND_LOCK_DESTROY();
+			break;
+		}
+		send_sendso_input_hook = send_input;
+		break;
+	case MOD_UNLOAD:
+		/* Do not allow unloading w/o locking. */
+		return (EBUSY);
+#ifdef __notyet__
+		VNET_LIST_RLOCK_NOSLEEP();
+		SEND_LOCK();
+		VNET_FOREACH(vnet_iter) {
+			CURVNET_SET(vnet_iter);
+			if (V_send_so != NULL) {
+				CURVNET_RESTORE();
+				SEND_UNLOCK();
+				VNET_LIST_RUNLOCK_NOSLEEP();
+				return (EBUSY);
+			}
+			CURVNET_RESTORE();
+		}
+		SEND_UNLOCK();
+		VNET_LIST_RUNLOCK_NOSLEEP();
+		error = pf_proto_unregister(PF_INET6, IPPROTO_SEND, SOCK_RAW);
+		if (error == 0)
+			SEND_LOCK_DESTROY();
+		send_sendso_input_hook = NULL;
+		break;
+#endif
+	default:
+		error = 0;
+		break;
+	}
+
+	return (error);
+}
+
+static moduledata_t sendmod = {
+	"send",
+	send_modevent,
+	0
+};
+
+DECLARE_MODULE(send, sendmod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
diff --git a/sys/netinet6/send.h b/sys/netinet6/send.h
new file mode 100644
index 00000000000..36ba571a554
--- /dev/null
+++ b/sys/netinet6/send.h
@@ -0,0 +1,45 @@
+/*-
+ * Copyright (c) 2009-2010 Ana Kukec 
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ *
+ * $FreeBSD$
+ */
+
+#ifndef _NETINET6_SEND_H_
+#define _NETINET6_SEND_H_
+
+#define	SND_OUT		0	/* Outgoing traffic */
+#define	SND_IN		1	/* Incoming traffic. */
+
+struct sockaddr_send {
+	unsigned char		send_len;	/* total length */
+	sa_family_t		send_family;	/* address family */
+	int			send_direction;
+	int			send_ifidx;
+	char			send_zero[8];
+};
+
+extern int (*send_sendso_input_hook)(struct mbuf *, struct ifnet *, int, int);
+
+#endif /* _NETINET6_SEND_H_ */
diff --git a/sys/sys/mbuf.h b/sys/sys/mbuf.h
index 95a44a4aecf..654f1450b5e 100644
--- a/sys/sys/mbuf.h
+++ b/sys/sys/mbuf.h
@@ -903,6 +903,7 @@ struct mbuf	*m_unshare(struct mbuf *, int how);
 #define	PACKET_TAG_IPOPTIONS			27 /* Saved IP options */
 #define	PACKET_TAG_CARP				28 /* CARP info */
 #define	PACKET_TAG_IPSEC_NAT_T_PORTS		29 /* two uint16_t */
+#define	PACKET_TAG_ND_OUTGOING			30 /* ND outgoing */
 
 /* Specific cookies and tags. */
 

From f3135331c60759ca7fd35e064e6fc4aac022cd7b Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 11:40:10 +0000
Subject: [PATCH 0087/1624] Add initial Atheros AR91XX support.

This works well enough to bring a system up to single-user mode
using an MDROOT.

Known Issues:

* The EHCI USB doesn't currently work and will panic the kernel during
  attach.
* The onboard ethernet won't work until the PLL routines have been
  fleshed out and shoe-horned into if_arge.
* The WMAC device glue (and quite likely the if_ath support)
  hasn't yet been implemented.
---
 sys/mips/atheros/ar71xx_setup.c |  20 ++++
 sys/mips/atheros/ar71xxreg.h    |  10 ++
 sys/mips/atheros/ar91xx_chip.c  | 171 ++++++++++++++++++++++++++++++++
 sys/mips/atheros/ar91xx_chip.h  |  34 +++++++
 sys/mips/atheros/files.ar71xx   |   1 +
 5 files changed, 236 insertions(+)
 create mode 100644 sys/mips/atheros/ar91xx_chip.c
 create mode 100644 sys/mips/atheros/ar91xx_chip.h

diff --git a/sys/mips/atheros/ar71xx_setup.c b/sys/mips/atheros/ar71xx_setup.c
index bce383efe1b..000a426abd4 100644
--- a/sys/mips/atheros/ar71xx_setup.c
+++ b/sys/mips/atheros/ar71xx_setup.c
@@ -61,6 +61,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include 
+#include 
 
 #define	AR71XX_SYS_TYPE_LEN		128
 
@@ -104,6 +105,25 @@ ar71xx_detect_sys_type(void)
 		}
 		break;
 
+	case REV_ID_MAJOR_AR913X:
+		minor = id & AR91XX_REV_ID_MINOR_MASK;
+		rev = id >> AR91XX_REV_ID_REVISION_SHIFT;
+		rev &= AR91XX_REV_ID_REVISION_MASK;
+		ar71xx_cpu_ops	= &ar91xx_chip_def;
+		switch (minor) {
+		case AR91XX_REV_ID_MINOR_AR9130:
+			ar71xx_soc = AR71XX_SOC_AR9130;
+			chip = "9130";
+			break;
+
+		case AR91XX_REV_ID_MINOR_AR9132:
+			ar71xx_soc = AR71XX_SOC_AR9132;
+			chip = "9132";
+			break;
+		}
+		break;
+
+
 	default:
 		panic("ar71xx: unknown chip id:0x%08x\n", id);
 	}
diff --git a/sys/mips/atheros/ar71xxreg.h b/sys/mips/atheros/ar71xxreg.h
index 0f6fddc6607..f4772a8d20c 100644
--- a/sys/mips/atheros/ar71xxreg.h
+++ b/sys/mips/atheros/ar71xxreg.h
@@ -195,6 +195,9 @@
 #define	AR71XX_PLL_ETH_EXT_CLK		0x18050018
 #define	AR71XX_PLL_PCI_CLK		0x1805001C
 
+/* Reset block */
+#define	AR71XX_RST_BLOCK_BASE	0x18060000
+
 #define AR71XX_RST_WDOG_CONTROL	0x18060008
 #define		RST_WDOG_LAST			(1 << 31)
 #define		RST_WDOG_ACTION_MASK		3
@@ -253,6 +256,13 @@
 #define		AR71XX_REV_ID_REVISION_MASK	0x3
 #define		AR71XX_REV_ID_REVISION_SHIFT	2
 
+/* AR91XX chipset revision details */
+#define		AR91XX_REV_ID_MINOR_MASK	0x3
+#define		AR91XX_REV_ID_MINOR_AR9130	0x0
+#define		AR91XX_REV_ID_MINOR_AR9132	0x1
+#define		AR91XX_REV_ID_REVISION_MASK	0x3
+#define		AR91XX_REV_ID_REVISION_SHIFT	2
+
 /*
  * GigE adapters region
  */
diff --git a/sys/mips/atheros/ar91xx_chip.c b/sys/mips/atheros/ar91xx_chip.c
new file mode 100644
index 00000000000..5ba56be8284
--- /dev/null
+++ b/sys/mips/atheros/ar91xx_chip.c
@@ -0,0 +1,171 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+
+#include 
+
+#include "opt_ddb.h"
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+ 
+#include 
+ 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+
+#include 
+#include 
+
+static void
+ar91xx_chip_detect_mem_size(void)
+{
+}
+
+static void
+ar91xx_chip_detect_sys_frequency(void)
+{
+        uint32_t pll;
+        uint32_t freq;
+        uint32_t div;
+        
+        pll = ATH_READ_REG(AR91XX_PLL_REG_CPU_CONFIG);
+
+        div = ((pll >> AR91XX_PLL_DIV_SHIFT) & AR91XX_PLL_DIV_MASK);
+        freq = div * AR91XX_BASE_FREQ;
+        
+        u_ar71xx_cpu_freq = freq;
+
+        div = ((pll >> AR91XX_DDR_DIV_SHIFT) & AR91XX_DDR_DIV_MASK) + 1;
+        u_ar71xx_ddr_freq = freq / div;
+        
+        div = (((pll >> AR91XX_AHB_DIV_SHIFT) & AR91XX_AHB_DIV_MASK) + 1) * 2;
+        u_ar71xx_ahb_freq = u_ar71xx_cpu_freq / div;
+}
+
+static void
+ar91xx_chip_device_stop(uint32_t mask)
+{
+        uint32_t reg;
+        
+        reg = ATH_READ_REG(AR91XX_RESET_REG_RESET_MODULE);
+        ATH_WRITE_REG(AR91XX_RESET_REG_RESET_MODULE, reg | mask);
+}
+
+static void
+ar91xx_chip_device_start(uint32_t mask)
+{
+        uint32_t reg;
+        
+        reg = ATH_READ_REG(AR91XX_RESET_REG_RESET_MODULE);
+        ATH_WRITE_REG(AR91XX_RESET_REG_RESET_MODULE, reg & ~mask);
+}
+
+static int
+ar91xx_chip_device_stopped(uint32_t mask)
+{
+        uint32_t reg;
+        
+        reg = ATH_READ_REG(AR91XX_RESET_REG_RESET_MODULE);
+        return ((reg & mask) == mask);
+}
+
+static void
+ar91xx_chip_set_pll_ge0(int speed)
+{
+}
+
+static void
+ar91xx_chip_set_pll_ge1(int speed)
+{
+}
+
+static void
+ar91xx_chip_ddr_flush_ge0(void)
+{
+	ar71xx_ddr_flush(AR91XX_DDR_REG_FLUSH_GE0);
+}
+
+static void
+ar91xx_chip_ddr_flush_ge1(void)
+{
+	ar71xx_ddr_flush(AR91XX_DDR_REG_FLUSH_GE1);
+}
+
+static uint32_t
+ar91xx_chip_get_eth_pll(unsigned int mac, int speed)
+{
+        return 0;
+}
+
+static void
+ar91xx_chip_init_usb_peripheral(void)
+{
+	ar71xx_device_stop(AR91XX_RST_RESET_MODULE_USBSUS_OVERRIDE);
+	DELAY(100);
+
+	ar71xx_device_start(RST_RESET_USB_HOST);
+	DELAY(100);
+
+	ar71xx_device_start(RST_RESET_USB_PHY);
+	DELAY(100);
+}
+
+struct ar71xx_cpu_def ar91xx_chip_def = {
+        &ar91xx_chip_detect_mem_size,
+        &ar91xx_chip_detect_sys_frequency,
+        &ar91xx_chip_device_stop,
+        &ar91xx_chip_device_start,
+        &ar91xx_chip_device_stopped,
+        &ar91xx_chip_set_pll_ge0,
+        &ar91xx_chip_set_pll_ge1,
+        &ar91xx_chip_ddr_flush_ge0,
+        &ar91xx_chip_ddr_flush_ge1,
+        &ar91xx_chip_get_eth_pll,
+	NULL,
+	&ar91xx_chip_init_usb_peripheral,
+};
diff --git a/sys/mips/atheros/ar91xx_chip.h b/sys/mips/atheros/ar91xx_chip.h
new file mode 100644
index 00000000000..a98c2649fef
--- /dev/null
+++ b/sys/mips/atheros/ar91xx_chip.h
@@ -0,0 +1,34 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR91XX_CHIP_H__
+#define	__AR91XX_CHIP_H__
+
+extern struct ar71xx_cpu_def ar91xx_chip_def;
+
+#endif
diff --git a/sys/mips/atheros/files.ar71xx b/sys/mips/atheros/files.ar71xx
index e7daa1cb870..c8d00e55bd8 100644
--- a/sys/mips/atheros/files.ar71xx
+++ b/sys/mips/atheros/files.ar71xx
@@ -17,3 +17,4 @@ mips/mips/intr_machdep.c        standard
 mips/mips/tick.c		standard
 mips/atheros/ar71xx_setup.c	standard
 mips/atheros/ar71xx_chip.c	standard
+mips/atheros/ar91xx_chip.c	standard

From c4df93502dbcaf13efa66dc697650ec1399ef0e1 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 11:53:55 +0000
Subject: [PATCH 0088/1624] Add some initial AR724X chipset support.

This is untested but should at least allow an AR724X to boot.

The current code is lacking the detail needed to expose the PCIe bus.
It is also lacking any NIC, PLL or flush/WB code.
---
 sys/mips/atheros/ar71xx_setup.c |  22 +++++
 sys/mips/atheros/ar71xxreg.h    |   3 +
 sys/mips/atheros/ar724x_chip.c  | 165 ++++++++++++++++++++++++++++++++
 sys/mips/atheros/ar724x_chip.h  |  34 +++++++
 sys/mips/atheros/ar724xreg.h    |   3 +
 sys/mips/atheros/files.ar71xx   |   1 +
 6 files changed, 228 insertions(+)
 create mode 100644 sys/mips/atheros/ar724x_chip.c
 create mode 100644 sys/mips/atheros/ar724x_chip.h

diff --git a/sys/mips/atheros/ar71xx_setup.c b/sys/mips/atheros/ar71xx_setup.c
index 000a426abd4..9a405fe6642 100644
--- a/sys/mips/atheros/ar71xx_setup.c
+++ b/sys/mips/atheros/ar71xx_setup.c
@@ -61,6 +61,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include 
+#include 
 #include 
 
 #define	AR71XX_SYS_TYPE_LEN		128
@@ -105,6 +106,27 @@ ar71xx_detect_sys_type(void)
 		}
 		break;
 
+	case REV_ID_MAJOR_AR7240:
+		ar71xx_soc = AR71XX_SOC_AR7240;
+		chip = "7240";
+		ar71xx_cpu_ops	= &ar724x_chip_def;
+		rev = (id & AR724X_REV_ID_REVISION_MASK);
+		break;
+
+	case REV_ID_MAJOR_AR7241:
+		ar71xx_soc = AR71XX_SOC_AR7241;
+		chip = "7241";
+		ar71xx_cpu_ops	= &ar724x_chip_def;
+		rev = (id & AR724X_REV_ID_REVISION_MASK);
+		break;
+
+	case REV_ID_MAJOR_AR7242:
+		ar71xx_soc = AR71XX_SOC_AR7242;
+		chip = "7242";
+		ar71xx_cpu_ops	= &ar724x_chip_def;
+		rev = (id & AR724X_REV_ID_REVISION_MASK);
+		break;
+
 	case REV_ID_MAJOR_AR913X:
 		minor = id & AR91XX_REV_ID_MINOR_MASK;
 		rev = id >> AR91XX_REV_ID_REVISION_SHIFT;
diff --git a/sys/mips/atheros/ar71xxreg.h b/sys/mips/atheros/ar71xxreg.h
index f4772a8d20c..62a3737c920 100644
--- a/sys/mips/atheros/ar71xxreg.h
+++ b/sys/mips/atheros/ar71xxreg.h
@@ -256,6 +256,9 @@
 #define		AR71XX_REV_ID_REVISION_MASK	0x3
 #define		AR71XX_REV_ID_REVISION_SHIFT	2
 
+/* AR724X chipset revision details */
+#define		AR724X_REV_ID_REVISION_MASK	0x3
+
 /* AR91XX chipset revision details */
 #define		AR91XX_REV_ID_MINOR_MASK	0x3
 #define		AR91XX_REV_ID_MINOR_AR9130	0x0
diff --git a/sys/mips/atheros/ar724x_chip.c b/sys/mips/atheros/ar724x_chip.c
new file mode 100644
index 00000000000..450dd19e942
--- /dev/null
+++ b/sys/mips/atheros/ar724x_chip.c
@@ -0,0 +1,165 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+
+#include 
+
+#include "opt_ddb.h"
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+ 
+#include 
+ 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+ 
+#include 
+#include 
+
+#include 
+#include 
+
+static void
+ar724x_chip_detect_mem_size(void)
+{
+}
+
+static void
+ar724x_chip_detect_sys_frequency(void)
+{
+	uint32_t pll;
+	uint32_t freq;
+	uint32_t div;
+	 
+	pll = ATH_READ_REG(AR724X_PLL_REG_CPU_CONFIG);
+	
+	div = ((pll >> AR724X_PLL_DIV_SHIFT) & AR724X_PLL_DIV_MASK);
+	freq = div * AR724X_BASE_FREQ;
+
+	div = ((pll >> AR724X_PLL_REF_DIV_SHIFT) & AR724X_PLL_REF_DIV_MASK);
+	freq *= div;
+	
+	u_ar71xx_cpu_freq = freq;
+	
+	div = ((pll >> AR724X_DDR_DIV_SHIFT) & AR724X_DDR_DIV_MASK) + 1;
+	u_ar71xx_ddr_freq = freq / div;
+	
+	div = (((pll >> AR724X_AHB_DIV_SHIFT) & AR724X_AHB_DIV_MASK) + 1) * 2;
+	u_ar71xx_ahb_freq = u_ar71xx_cpu_freq / div;
+}
+
+static void
+ar724x_chip_device_stop(uint32_t mask)
+{
+	uint32_t mask_inv, reg;
+
+	mask_inv = mask & AR724X_RESET_MODULE_USB_OHCI_DLL;
+	reg = ATH_READ_REG(AR724X_RESET_REG_RESET_MODULE);
+	reg |= mask;
+	reg &= ~mask_inv;
+	ATH_WRITE_REG(AR724X_RESET_REG_RESET_MODULE, reg);
+}
+
+static void
+ar724x_chip_device_start(uint32_t mask)
+{
+	uint32_t mask_inv, reg;
+
+	mask_inv = mask & AR724X_RESET_MODULE_USB_OHCI_DLL;
+	reg = ATH_READ_REG(AR724X_RESET_REG_RESET_MODULE);
+	reg &= ~mask;
+	reg |= mask_inv;
+	ATH_WRITE_REG(AR724X_RESET_REG_RESET_MODULE, reg);
+}
+
+static int
+ar724x_chip_device_stopped(uint32_t mask)
+{
+	uint32_t reg;
+
+	reg = ATH_READ_REG(AR724X_RESET_REG_RESET_MODULE);
+	return ((reg & mask) == mask);
+}
+
+static void
+ar724x_chip_set_pll_ge0(int speed)
+{
+}
+
+static void
+ar724x_chip_set_pll_ge1(int speed)
+{
+}
+
+static void
+ar724x_chip_ddr_flush_ge0(void)
+{
+}
+
+static void
+ar724x_chip_ddr_flush_ge1(void)
+{
+}
+
+static uint32_t
+ar724x_chip_get_eth_pll(unsigned int mac, int speed)
+{
+        return 0;
+}
+
+struct ar71xx_cpu_def ar724x_chip_def = {
+        &ar724x_chip_detect_mem_size,
+        &ar724x_chip_detect_sys_frequency,
+        &ar724x_chip_device_stop,
+        &ar724x_chip_device_start,
+        &ar724x_chip_device_stopped,
+        &ar724x_chip_set_pll_ge0,
+        &ar724x_chip_set_pll_ge1,
+        &ar724x_chip_ddr_flush_ge0,
+        &ar724x_chip_ddr_flush_ge1,
+        &ar724x_chip_get_eth_pll,
+	NULL,		/* ar71xx_chip_irq_flush_ip2 */
+	NULL		/* ar71xx_chip_init_usb_peripheral */
+};
diff --git a/sys/mips/atheros/ar724x_chip.h b/sys/mips/atheros/ar724x_chip.h
new file mode 100644
index 00000000000..11b30b7a217
--- /dev/null
+++ b/sys/mips/atheros/ar724x_chip.h
@@ -0,0 +1,34 @@
+/*-
+ * Copyright (c) 2010 Adrian Chadd
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/* $FreeBSD$ */
+
+#ifndef	__AR724X_CHIP_H__
+#define	__AR724X_CHIP_H__
+
+extern struct ar71xx_cpu_def ar724x_chip_def;
+
+#endif
diff --git a/sys/mips/atheros/ar724xreg.h b/sys/mips/atheros/ar724xreg.h
index 53faa78294b..ec7ef1552c0 100644
--- a/sys/mips/atheros/ar724xreg.h
+++ b/sys/mips/atheros/ar724xreg.h
@@ -47,6 +47,9 @@
 
 #define	AR724X_BASE_FREQ		5000000
 
+#define	AR724X_RESET_REG_RESET_MODULE	AR71XX_RST_BLOCK_BASE + 0x1c
+#define	AR724X_RESET_MODULE_USB_OHCI_DLL	(1 << 3)
+
 /* XXX so USB requires different init code? -adrian */
 #define	AR7240_OHCI_BASE		0x1b000000
 #define	AR7240_OHCI_SIZE		0x01000000
diff --git a/sys/mips/atheros/files.ar71xx b/sys/mips/atheros/files.ar71xx
index c8d00e55bd8..6b0051574a4 100644
--- a/sys/mips/atheros/files.ar71xx
+++ b/sys/mips/atheros/files.ar71xx
@@ -17,4 +17,5 @@ mips/mips/intr_machdep.c        standard
 mips/mips/tick.c		standard
 mips/atheros/ar71xx_setup.c	standard
 mips/atheros/ar71xx_chip.c	standard
+mips/atheros/ar724x_chip.c	standard
 mips/atheros/ar91xx_chip.c	standard

From 88e08e7ce6d30c48f070a842a915c91db9e563a5 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 12:52:49 +0000
Subject: [PATCH 0089/1624] Fix mistaken indenting.

---
 sys/mips/atheros/ar71xx_setup.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/sys/mips/atheros/ar71xx_setup.c b/sys/mips/atheros/ar71xx_setup.c
index 9a405fe6642..0720d52ff9d 100644
--- a/sys/mips/atheros/ar71xx_setup.c
+++ b/sys/mips/atheros/ar71xx_setup.c
@@ -87,7 +87,7 @@ ar71xx_detect_sys_type(void)
 		minor = id & AR71XX_REV_ID_MINOR_MASK;
 		rev = id >> AR71XX_REV_ID_REVISION_SHIFT;
 		rev &= AR71XX_REV_ID_REVISION_MASK;
-		ar71xx_cpu_ops	= &ar71xx_chip_def;
+		ar71xx_cpu_ops = &ar71xx_chip_def;
 		switch (minor) {
 		case AR71XX_REV_ID_MINOR_AR7130:
 			ar71xx_soc = AR71XX_SOC_AR7130;
@@ -109,21 +109,21 @@ ar71xx_detect_sys_type(void)
 	case REV_ID_MAJOR_AR7240:
 		ar71xx_soc = AR71XX_SOC_AR7240;
 		chip = "7240";
-		ar71xx_cpu_ops	= &ar724x_chip_def;
+		ar71xx_cpu_ops = &ar724x_chip_def;
 		rev = (id & AR724X_REV_ID_REVISION_MASK);
 		break;
 
 	case REV_ID_MAJOR_AR7241:
 		ar71xx_soc = AR71XX_SOC_AR7241;
 		chip = "7241";
-		ar71xx_cpu_ops	= &ar724x_chip_def;
+		ar71xx_cpu_ops = &ar724x_chip_def;
 		rev = (id & AR724X_REV_ID_REVISION_MASK);
 		break;
 
 	case REV_ID_MAJOR_AR7242:
 		ar71xx_soc = AR71XX_SOC_AR7242;
 		chip = "7242";
-		ar71xx_cpu_ops	= &ar724x_chip_def;
+		ar71xx_cpu_ops = &ar724x_chip_def;
 		rev = (id & AR724X_REV_ID_REVISION_MASK);
 		break;
 
@@ -131,7 +131,7 @@ ar71xx_detect_sys_type(void)
 		minor = id & AR91XX_REV_ID_MINOR_MASK;
 		rev = id >> AR91XX_REV_ID_REVISION_SHIFT;
 		rev &= AR91XX_REV_ID_REVISION_MASK;
-		ar71xx_cpu_ops	= &ar91xx_chip_def;
+		ar71xx_cpu_ops = &ar91xx_chip_def;
 		switch (minor) {
 		case AR91XX_REV_ID_MINOR_AR9130:
 			ar71xx_soc = AR71XX_SOC_AR9130;

From aeba5ab26bd900f9454466f80c451b18ef5f542c Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 19 Aug 2010 12:59:57 +0000
Subject: [PATCH 0090/1624] Remove unneeded casts in inline assembly in
 contrib/gcc/longlong.h, which are apparently "heinous" GNU extensions, so
 clang can compile this without using the -fheinous-gnu-extensions option.

Results in *no* binary change, neither with clang, nor with gcc.

Submitted by:	Dimitry Andric 
---
 contrib/gcc/longlong.h | 44 +++++++++++++++++++++---------------------
 1 file changed, 22 insertions(+), 22 deletions(-)

diff --git a/contrib/gcc/longlong.h b/contrib/gcc/longlong.h
index c4131c67b21..8805d91b2c4 100644
--- a/contrib/gcc/longlong.h
+++ b/contrib/gcc/longlong.h
@@ -314,38 +314,38 @@ UDItype __umulsidi3 (USItype, USItype);
 #if (defined (__i386__) || defined (__i486__)) && W_TYPE_SIZE == 32
 #define add_ssaaaa(sh, sl, ah, al, bh, bl) \
   __asm__ ("addl %5,%1\n\tadcl %3,%0"					\
-	   : "=r" ((USItype) (sh)),					\
-	     "=&r" ((USItype) (sl))					\
-	   : "%0" ((USItype) (ah)),					\
-	     "g" ((USItype) (bh)),					\
-	     "%1" ((USItype) (al)),					\
-	     "g" ((USItype) (bl)))
+	   : "=r" (sh),							\
+	     "=&r" (sl)							\
+	   : "%0" (ah),							\
+	     "g" (bh),							\
+	     "%1" (al),							\
+	     "g" (bl))
 #define sub_ddmmss(sh, sl, ah, al, bh, bl) \
   __asm__ ("subl %5,%1\n\tsbbl %3,%0"					\
-	   : "=r" ((USItype) (sh)),					\
-	     "=&r" ((USItype) (sl))					\
-	   : "0" ((USItype) (ah)),					\
-	     "g" ((USItype) (bh)),					\
-	     "1" ((USItype) (al)),					\
-	     "g" ((USItype) (bl)))
+	   : "=r" (sh),							\
+	     "=&r" (sl)							\
+	   : "0" (ah),							\
+	     "g" (bh),							\
+	     "1" (al),							\
+	     "g" (bl))
 #define umul_ppmm(w1, w0, u, v) \
   __asm__ ("mull %3"							\
-	   : "=a" ((USItype) (w0)),					\
-	     "=d" ((USItype) (w1))					\
-	   : "%0" ((USItype) (u)),					\
-	     "rm" ((USItype) (v)))
+	   : "=a" (w0),							\
+	     "=d" (w1)							\
+	   : "%0" (u),							\
+	     "rm" (v))
 #define udiv_qrnnd(q, r, n1, n0, dv) \
   __asm__ ("divl %4"							\
-	   : "=a" ((USItype) (q)),					\
-	     "=d" ((USItype) (r))					\
-	   : "0" ((USItype) (n0)),					\
-	     "1" ((USItype) (n1)),					\
-	     "rm" ((USItype) (dv)))
+	   : "=a" (q),							\
+	     "=d" (r)							\
+	   : "0" (n0),							\
+	     "1" (n1),							\
+	     "rm" (dv))
 #define count_leading_zeros(count, x) \
   do {									\
     USItype __cbtmp;							\
     __asm__ ("bsrl %1,%0"						\
-	     : "=r" (__cbtmp) : "rm" ((USItype) (x)));			\
+	     : "=r" (__cbtmp) : "rm" (x));				\
     (count) = __cbtmp ^ 31;						\
   } while (0)
 #define count_trailing_zeros(count, x) \

From d34c11b4682031ad49ea05876a0c99db9d869aa7 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 19 Aug 2010 15:55:50 +0000
Subject: [PATCH 0091/1624] Remove an unused macro.  exit1() invokes
 ktrprocexit() directly.

---
 sys/sys/ktrace.h | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/sys/sys/ktrace.h b/sys/sys/ktrace.h
index b5aa473e737..a3e546957e4 100644
--- a/sys/sys/ktrace.h
+++ b/sys/sys/ktrace.h
@@ -73,10 +73,6 @@ struct ktr_header {
 	if (KTRCHECKDRAIN(td))						\
 		ktruserret(td);						\
 } while (0)
-#define	KTRPROCEXIT(td) do {						\
-	if (KTRCHECKDRAIN(td))						\
-		ktrprocexit(td);					\
-} while (0)
 
 /*
  * ktrace record types

From 44c5dea1d8b7dda6554be356f2192e0d8e0d2180 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 16:15:30 +0000
Subject: [PATCH 0092/1624] add the PLL set functions to cpuops

---
 sys/mips/atheros/ar71xx_cpudef.h | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/sys/mips/atheros/ar71xx_cpudef.h b/sys/mips/atheros/ar71xx_cpudef.h
index 4a29c8f6dd9..f26c55aaadc 100644
--- a/sys/mips/atheros/ar71xx_cpudef.h
+++ b/sys/mips/atheros/ar71xx_cpudef.h
@@ -81,6 +81,16 @@ static inline int ar71xx_device_stopped(uint32_t mask)
 	return ar71xx_cpu_ops->ar71xx_chip_device_stopped(mask);
 }
 
+static inline void ar71xx_device_set_pll_ge0(int speed)
+{
+	ar71xx_cpu_ops->ar71xx_chip_set_pll_ge0(speed);
+}
+
+static inline void ar71xx_device_set_pll_ge1(int speed)
+{
+	ar71xx_cpu_ops->ar71xx_chip_set_pll_ge1(speed);
+}
+
 static inline void ar71xx_device_flush_ddr_ge0(void)
 {
 	ar71xx_cpu_ops->ar71xx_chip_ddr_flush_ge0();

From 303fea5cdc90c43fcaf67df502e5d4bc7cb26dc8 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 16:25:15 +0000
Subject: [PATCH 0093/1624] Implement PLL generalisation in preparation for use
 in if_arge.

* Add a function to write to the relevant PLL register
* Break out the PLL configuration for the AR71XX into the CPU ops,
  lifted from if_arge.c.
* Add the AR91XX PLL configuration ops, using the AR91XX register
  definitions.
---
 sys/mips/atheros/ar71xx_chip.c | 40 +++++++++++++++++++++++++++++++---
 sys/mips/atheros/ar71xxreg.h   | 25 +++++++++++++++++++++
 sys/mips/atheros/ar91xx_chip.c | 34 +++++++++++++++++++++++++++++
 3 files changed, 96 insertions(+), 3 deletions(-)

diff --git a/sys/mips/atheros/ar71xx_chip.c b/sys/mips/atheros/ar71xx_chip.c
index 937803d2cf2..ec179a16859 100644
--- a/sys/mips/atheros/ar71xx_chip.c
+++ b/sys/mips/atheros/ar71xx_chip.c
@@ -77,9 +77,6 @@ __FBSDID("$FreeBSD$");
 #define AR71XX_AHB_DIV_SHIFT            20
 #define AR71XX_AHB_DIV_MASK             0x7
 
-#define AR71XX_ETH0_PLL_SHIFT           17
-#define AR71XX_ETH1_PLL_SHIFT           19
-
 /* XXX these shouldn't be in here - this file is a per-chip file */
 /* XXX these should be in the top-level ar71xx type, not ar71xx -chip */
 uint32_t u_ar71xx_cpu_freq;
@@ -143,14 +140,51 @@ ar71xx_chip_device_stopped(uint32_t mask)
         return ((reg & mask) == mask);
 }
 
+/* Speed is either 10, 100 or 1000 */
 static void
 ar71xx_chip_set_pll_ge0(int speed)
 {
+	uint32_t pll;
+
+	switch(speed) {
+		case 10:
+			pll = PLL_ETH_INT_CLK_10;
+			break;
+		case 100:
+			pll = PLL_ETH_INT_CLK_100;
+			break;
+		case 1000:
+			pll = PLL_ETH_INT_CLK_1000;
+			break;
+		default:
+			printf("ar71xx_chip_set_pll_ge0: invalid speed %d\n", speed);
+			return;
+	}
+
+	ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG, AR71XX_PLL_ETH_INT0_CLK, pll, AR71XX_PLL_ETH0_SHIFT);
 }
 
 static void
 ar71xx_chip_set_pll_ge1(int speed)
 {
+	uint32_t pll;
+
+	switch(speed) {
+		case 10:
+			pll = PLL_ETH_INT_CLK_10;
+			break;
+		case 100:
+			pll = PLL_ETH_INT_CLK_100;
+			break;
+		case 1000:
+			pll = PLL_ETH_INT_CLK_1000;
+			break;
+		default:
+			printf("ar71xx_chip_set_pll_ge1: invalid speed %d\n", speed);
+			return;
+	}
+
+	ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG, AR71XX_PLL_ETH_INT1_CLK, pll, AR71XX_PLL_ETH1_SHIFT);
 }
 
 static void
diff --git a/sys/mips/atheros/ar71xxreg.h b/sys/mips/atheros/ar71xxreg.h
index 62a3737c920..2ee8baa49a6 100644
--- a/sys/mips/atheros/ar71xxreg.h
+++ b/sys/mips/atheros/ar71xxreg.h
@@ -182,6 +182,8 @@
 #define		PLL_BYPASS			(1 << 1)
 #define		PLL_POWER_DOWN			(1 << 0)
 #define	AR71XX_PLL_SEC_CONFIG		0x18050004
+#define		AR71XX_PLL_ETH0_SHIFT		17
+#define		AR71XX_PLL_ETH1_SHIFT		19
 #define	AR71XX_PLL_CPU_CLK_CTRL		0x18050008
 #define	AR71XX_PLL_ETH_INT0_CLK		0x18050010
 #define	AR71XX_PLL_ETH_INT1_CLK		0x18050014
@@ -501,4 +503,27 @@ ar71xx_ddr_flush(uint32_t reg)
 		;
 } 
 
+static inline void
+ar71xx_write_pll(uint32_t cfg_reg, uint32_t pll_reg, uint32_t pll, uint32_t pll_reg_shift)
+{
+	uint32_t sec_cfg;
+
+	/* set PLL registers */
+	sec_cfg = ATH_READ_REG(cfg_reg);
+	sec_cfg &= ~(3 << pll_reg_shift);
+	sec_cfg |= (2 << pll_reg_shift);
+
+	ATH_WRITE_REG(cfg_reg, sec_cfg);
+	DELAY(100);
+
+	ATH_WRITE_REG(pll_reg, pll);
+	sec_cfg |= (3 << pll_reg_shift);
+	ATH_WRITE_REG(cfg_reg, sec_cfg);
+	DELAY(100);
+
+	sec_cfg &= ~(3 << pll_reg_shift);
+	ATH_WRITE_REG(cfg_reg, sec_cfg);
+	DELAY(100);
+}
+
 #endif /* _AR71XX_REG_H_ */
diff --git a/sys/mips/atheros/ar91xx_chip.c b/sys/mips/atheros/ar91xx_chip.c
index 5ba56be8284..ae221561f52 100644
--- a/sys/mips/atheros/ar91xx_chip.c
+++ b/sys/mips/atheros/ar91xx_chip.c
@@ -117,11 +117,45 @@ ar91xx_chip_device_stopped(uint32_t mask)
 static void
 ar91xx_chip_set_pll_ge0(int speed)
 {
+	uint32_t pll;
+
+	switch(speed) {
+		case 10:
+			pll = AR91XX_PLL_VAL_10;
+			break;
+		case 100:
+			pll = AR91XX_PLL_VAL_100;
+			break;
+		case 1000:
+			pll = AR91XX_PLL_VAL_1000;
+			break;
+		default:
+			printf("ar91xx_chip_set_pll_ge0: invalid speed %d\n", speed);
+			return;
+	}
+	ar71xx_write_pll(AR91XX_PLL_REG_ETH_CONFIG, AR91XX_PLL_REG_ETH0_INT_CLOCK, pll, AR91XX_ETH0_PLL_SHIFT);
 }
 
 static void
 ar91xx_chip_set_pll_ge1(int speed)
 {
+	uint32_t pll;
+
+	switch(speed) {
+		case 10:
+			pll = AR91XX_PLL_VAL_10;
+			break;
+		case 100:
+			pll = AR91XX_PLL_VAL_100;
+			break;
+		case 1000:
+			pll = AR91XX_PLL_VAL_1000;
+			break;
+		default:
+			printf("ar91xx_chip_set_pll_ge0: invalid speed %d\n", speed);
+			return;
+	}
+	ar71xx_write_pll(AR91XX_PLL_REG_ETH_CONFIG, AR91XX_PLL_REG_ETH1_INT_CLOCK, pll, AR91XX_ETH1_PLL_SHIFT);
 }
 
 static void

From 813b73a5a9dc065c3b78f862943dea5f39885f31 Mon Sep 17 00:00:00 2001
From: Adrian Chadd 
Date: Thu, 19 Aug 2010 16:29:08 +0000
Subject: [PATCH 0094/1624] Migrate if_arge to use the PLL cpuops.

This has been lightly tested on the AR7161 and AR9132.
---
 sys/mips/atheros/if_arge.c    | 38 +++++++++--------------------------
 sys/mips/atheros/if_argevar.h |  2 --
 2 files changed, 10 insertions(+), 30 deletions(-)

diff --git a/sys/mips/atheros/if_arge.c b/sys/mips/atheros/if_arge.c
index 6cc627dec74..39e377c0cb7 100644
--- a/sys/mips/atheros/if_arge.c
+++ b/sys/mips/atheros/if_arge.c
@@ -233,13 +233,6 @@ arge_attach(device_t dev)
 
 	KASSERT(((sc->arge_mac_unit == 0) || (sc->arge_mac_unit == 1)), 
 	    ("if_arge: Only MAC0 and MAC1 supported"));
-	if (sc->arge_mac_unit == 0) {
-		sc->arge_pll_reg = AR71XX_PLL_ETH_INT0_CLK;
-		sc->arge_pll_reg_shift = 17;
-	} else {
-		sc->arge_pll_reg = AR71XX_PLL_ETH_INT1_CLK;
-		sc->arge_pll_reg_shift = 19;
-	}
 
 	/*
 	 *  Get which PHY of 5 available we should use for this unit
@@ -668,7 +661,8 @@ arge_link_task(void *arg, int pending)
 static void
 arge_set_pll(struct arge_softc *sc, int media, int duplex)
 {
-	uint32_t		cfg, ifcontrol, rx_filtmask, pll, sec_cfg;
+	uint32_t		cfg, ifcontrol, rx_filtmask;
+	int if_speed;
 
 	cfg = ARGE_READ(sc, AR71XX_MAC_CFG2);
 	cfg &= ~(MAC_CFG2_IFACE_MODE_1000 
@@ -687,21 +681,21 @@ arge_set_pll(struct arge_softc *sc, int media, int duplex)
 	switch(media) {
 	case IFM_10_T:
 		cfg |= MAC_CFG2_IFACE_MODE_10_100;
-		pll = PLL_ETH_INT_CLK_10;
+		if_speed = 10;
 		break;
 	case IFM_100_TX:
 		cfg |= MAC_CFG2_IFACE_MODE_10_100;
 		ifcontrol |= MAC_IFCONTROL_SPEED;
-		pll = PLL_ETH_INT_CLK_100;
+		if_speed = 100;
 		break;
 	case IFM_1000_T:
 	case IFM_1000_SX:
 		cfg |= MAC_CFG2_IFACE_MODE_1000;
 		rx_filtmask |= FIFO_RX_MASK_BYTE_MODE;
-		pll = PLL_ETH_INT_CLK_1000;
+		if_speed = 1000;
 		break;
 	default:
-		pll = PLL_ETH_INT_CLK_100;
+		if_speed = 100;
 		device_printf(sc->arge_dev, 
 		    "Unknown media %d\n", media);
 	}
@@ -715,22 +709,10 @@ arge_set_pll(struct arge_softc *sc, int media, int duplex)
 	    rx_filtmask);
 
 	/* set PLL registers */
-	sec_cfg = ATH_READ_REG(AR71XX_PLL_SEC_CONFIG);
-	sec_cfg &= ~(3 << sc->arge_pll_reg_shift);
-	sec_cfg |= (2 << sc->arge_pll_reg_shift);
-
-	ATH_WRITE_REG(AR71XX_PLL_SEC_CONFIG, sec_cfg);
-	DELAY(100);
-
-	ATH_WRITE_REG(sc->arge_pll_reg, pll);
-
-	sec_cfg |= (3 << sc->arge_pll_reg_shift);
-	ATH_WRITE_REG(AR71XX_PLL_SEC_CONFIG, sec_cfg);
-	DELAY(100);
-
-	sec_cfg &= ~(3 << sc->arge_pll_reg_shift);
-	ATH_WRITE_REG(AR71XX_PLL_SEC_CONFIG, sec_cfg);
-	DELAY(100);
+	if (sc->arge_mac_unit == 0)
+		ar71xx_device_set_pll_ge0(if_speed);
+	else
+		ar71xx_device_set_pll_ge1(if_speed);
 }
 
 
diff --git a/sys/mips/atheros/if_argevar.h b/sys/mips/atheros/if_argevar.h
index 3db039d7c27..4c336afdbbe 100644
--- a/sys/mips/atheros/if_argevar.h
+++ b/sys/mips/atheros/if_argevar.h
@@ -150,8 +150,6 @@ struct arge_softc {
 	uint32_t		arge_intr_status;
 	int			arge_mac_unit;
 	int			arge_phymask;
-	uint32_t		arge_pll_reg;
-	uint32_t		arge_pll_reg_shift;
 	int			arge_if_flags;
 	uint32_t		arge_debug;
 	struct {

From 2b3fb6156944e141e28b68a1dcf63e0c64637418 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 19 Aug 2010 16:38:58 +0000
Subject: [PATCH 0095/1624] Fix a whitespace nit and remove a questioning
 comment.  STAILQ_CONCAT() does require the STAILQ the existing list is being
 added to to already be initialized (it is CONCAT() vs MOVE()).

---
 sys/kern/kern_ktrace.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/kern/kern_ktrace.c b/sys/kern/kern_ktrace.c
index 26584379f5e..bf530e1d9ec 100644
--- a/sys/kern/kern_ktrace.c
+++ b/sys/kern/kern_ktrace.c
@@ -107,7 +107,7 @@ static int data_lengths[] = {
 	0,					/* KTR_NAMEI */
 	sizeof(struct ktr_genio),		/* KTR_GENIO */
 	sizeof(struct ktr_psig),		/* KTR_PSIG */
-	sizeof(struct ktr_csw),			/* KTR_CSW */
+	sizeof(struct ktr_csw),		/* KTR_CSW */
 	0,					/* KTR_USER */
 	0,					/* KTR_STRUCT */
 	0,					/* KTR_SYSCTL */
@@ -336,7 +336,7 @@ ktr_drain(struct thread *td)
 	ktrace_assert(td);
 	sx_assert(&ktrace_sx, SX_XLOCKED);
 
-	STAILQ_INIT(&local_queue);	/* XXXRW: needed? */
+	STAILQ_INIT(&local_queue);
 
 	if (!STAILQ_EMPTY(&td->td_proc->p_ktr)) {
 		mtx_lock(&ktrace_mtx);

From 96835d61b68bafdcb7bd4cdc88801e4bdc3096ea Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Thu, 19 Aug 2010 16:39:00 +0000
Subject: [PATCH 0096/1624] Call dev_rel() in error paths.

Reported by:	kib
Reviewed by:	kib
MFC after:	2 weeks
---
 sys/fs/devfs/devfs_vnops.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/sys/fs/devfs/devfs_vnops.c b/sys/fs/devfs/devfs_vnops.c
index 542ecaed35e..0bcc0932c6a 100644
--- a/sys/fs/devfs/devfs_vnops.c
+++ b/sys/fs/devfs/devfs_vnops.c
@@ -848,6 +848,8 @@ devfs_lookupx(struct vop_lookup_args *ap, int *dm_unlock)
 			*dm_unlock = 0;
 			sx_xunlock(&dmp->dm_lock);
 			devfs_unmount_final(dmp);
+			if (cdev != NULL)
+				dev_rel(cdev);
 			return (ENOENT);
 		}
 		if (cdev == NULL)
@@ -859,6 +861,7 @@ devfs_lookupx(struct vop_lookup_args *ap, int *dm_unlock)
 			*dm_unlock = 0;
 			sx_xunlock(&dmp->dm_lock);
 			devfs_unmount_final(dmp);
+			dev_rel(cdev);
 			return (ENOENT);
 		}
 

From ba50d5975d250cb85c9dbe6497b434551c462c42 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 19 Aug 2010 16:40:30 +0000
Subject: [PATCH 0097/1624] There isn't really a need to hold the ktrace mutex
 just to read the value of p_traceflag that is stored in the kinfo_proc
 structure.  It is still racey even with the lock and the code will read a
 consistent snapshot of the flag without the lock.

---
 sys/kern/kern_proc.c | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/sys/kern/kern_proc.c b/sys/kern/kern_proc.c
index beab035fb88..223bf7d2542 100644
--- a/sys/kern/kern_proc.c
+++ b/sys/kern/kern_proc.c
@@ -64,10 +64,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#include 
-#endif
 
 #ifdef DDB
 #include 
@@ -717,9 +713,7 @@ fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
 	kp->ki_textvp = p->p_textvp;
 #ifdef KTRACE
 	kp->ki_tracep = p->p_tracevp;
-	mtx_lock(&ktrace_mtx);
 	kp->ki_traceflag = p->p_traceflag;
-	mtx_unlock(&ktrace_mtx);
 #endif
 	kp->ki_fd = p->p_fd;
 	kp->ki_vmspace = p->p_vmspace;

From 8c7a92bd4a8213fe6146905c22c0002345134906 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 19 Aug 2010 16:41:27 +0000
Subject: [PATCH 0098/1624] Remove unused KTRACE includes.

---
 sys/amd64/amd64/trap.c        | 4 ----
 sys/amd64/ia32/ia32_syscall.c | 4 ----
 sys/i386/i386/trap.c          | 4 ----
 sys/ia64/ia64/trap.c          | 6 ------
 sys/kern/sched_ule.c          | 4 ----
 sys/powerpc/aim/trap.c        | 5 -----
 sys/powerpc/booke/trap.c      | 4 ----
 sys/sparc64/sparc64/trap.c    | 5 -----
 sys/sun4v/sun4v/trap.c        | 5 -----
 9 files changed, 41 deletions(-)

diff --git a/sys/amd64/amd64/trap.c b/sys/amd64/amd64/trap.c
index 36425547ff7..f38dbf969e3 100644
--- a/sys/amd64/amd64/trap.c
+++ b/sys/amd64/amd64/trap.c
@@ -50,7 +50,6 @@ __FBSDID("$FreeBSD$");
 #include "opt_isa.h"
 #include "opt_kdb.h"
 #include "opt_kdtrace.h"
-#include "opt_ktrace.h"
 
 #include 
 #include 
@@ -70,9 +69,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#endif
 #ifdef HWPMC_HOOKS
 #include 
 #endif
diff --git a/sys/amd64/ia32/ia32_syscall.c b/sys/amd64/ia32/ia32_syscall.c
index 6a649aeeb19..9a3488e6ac2 100644
--- a/sys/amd64/ia32/ia32_syscall.c
+++ b/sys/amd64/ia32/ia32_syscall.c
@@ -45,7 +45,6 @@ __FBSDID("$FreeBSD$");
 #include "opt_clock.h"
 #include "opt_cpu.h"
 #include "opt_isa.h"
-#include "opt_ktrace.h"
 
 #include 
 #include 
@@ -65,9 +64,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#endif
 #include 
 
 #include 
diff --git a/sys/i386/i386/trap.c b/sys/i386/i386/trap.c
index 9c93319369f..561ce68fe0d 100644
--- a/sys/i386/i386/trap.c
+++ b/sys/i386/i386/trap.c
@@ -50,7 +50,6 @@ __FBSDID("$FreeBSD$");
 #include "opt_isa.h"
 #include "opt_kdb.h"
 #include "opt_kdtrace.h"
-#include "opt_ktrace.h"
 #include "opt_npx.h"
 #include "opt_trap.h"
 
@@ -72,9 +71,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#endif
 #ifdef HWPMC_HOOKS
 #include 
 #endif
diff --git a/sys/ia64/ia64/trap.c b/sys/ia64/ia64/trap.c
index f6db8c943ce..60b00c4988e 100644
--- a/sys/ia64/ia64/trap.c
+++ b/sys/ia64/ia64/trap.c
@@ -28,7 +28,6 @@
 __FBSDID("$FreeBSD$");
 
 #include "opt_ddb.h"
-#include "opt_ktrace.h"
 
 #include 
 #include 
@@ -67,11 +66,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #endif
 
-#ifdef KTRACE
-#include 
-#include 
-#endif
-
 #include 
 
 #include 
diff --git a/sys/kern/sched_ule.c b/sys/kern/sched_ule.c
index e210ebc09f6..0a1f7b9f80b 100644
--- a/sys/kern/sched_ule.c
+++ b/sys/kern/sched_ule.c
@@ -62,10 +62,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#include 
-#endif
 
 #ifdef HWPMC_HOOKS
 #include 
diff --git a/sys/powerpc/aim/trap.c b/sys/powerpc/aim/trap.c
index df5c97153e9..76df6dd9b6f 100644
--- a/sys/powerpc/aim/trap.c
+++ b/sys/powerpc/aim/trap.c
@@ -34,8 +34,6 @@
 #include 
 __FBSDID("$FreeBSD$");
 
-#include "opt_ktrace.h"
-
 #include 
 #include 
 #include 
@@ -50,9 +48,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#endif
 #include 
 
 #include 
diff --git a/sys/powerpc/booke/trap.c b/sys/powerpc/booke/trap.c
index 93dc597e3e1..a2d0d7037b1 100644
--- a/sys/powerpc/booke/trap.c
+++ b/sys/powerpc/booke/trap.c
@@ -35,7 +35,6 @@
 __FBSDID("$FreeBSD$");
 
 #include "opt_fpu_emu.h"
-#include "opt_ktrace.h"
 
 #include 
 #include 
@@ -51,9 +50,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#endif
 #include 
 
 #include 
diff --git a/sys/sparc64/sparc64/trap.c b/sys/sparc64/sparc64/trap.c
index 8ce6970d65d..b9e5d94a534 100644
--- a/sys/sparc64/sparc64/trap.c
+++ b/sys/sparc64/sparc64/trap.c
@@ -44,7 +44,6 @@ __FBSDID("$FreeBSD$");
 
 #include "opt_ddb.h"
 #include "opt_ktr.h"
-#include "opt_ktrace.h"
 
 #include 
 #include 
@@ -65,10 +64,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#include 
-#endif
 #include 
 
 #include 
diff --git a/sys/sun4v/sun4v/trap.c b/sys/sun4v/sun4v/trap.c
index d099351e3e6..cfc51350f02 100644
--- a/sys/sun4v/sun4v/trap.c
+++ b/sys/sun4v/sun4v/trap.c
@@ -42,7 +42,6 @@
 
 #include "opt_ddb.h"
 #include "opt_ktr.h"
-#include "opt_ktrace.h"
 
 #include 
 #include 
@@ -62,10 +61,6 @@
 #include 
 #include 
 #include 
-#ifdef KTRACE
-#include 
-#include 
-#endif
 
 #include 
 

From 1ed622958d68921cdb919e9fdf97baa6517769ed Mon Sep 17 00:00:00 2001
From: Jack F Vogel 
Date: Thu, 19 Aug 2010 17:00:33 +0000
Subject: [PATCH 0099/1624] Eliminate the ambiguous queue setting logic for the
 VF, it made it possible to have 2 queues which we don't want, the HOST is
 unable to handle it.

---
 sys/dev/e1000/if_igb.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/e1000/if_igb.c b/sys/dev/e1000/if_igb.c
index c908517e45c..412ea9e8e0d 100644
--- a/sys/dev/e1000/if_igb.c
+++ b/sys/dev/e1000/if_igb.c
@@ -2473,8 +2473,8 @@ igb_setup_msix(struct adapter *adapter)
 	if ((adapter->hw.mac.type == e1000_82575) && (queues > 4))
 		queues = 4;
 
-	/* Limit the VF adapter to one queues */
-	if ((adapter->hw.mac.type == e1000_vfadapt) && (queues > 2))
+	/* Limit the VF adapter to one queue */
+	if (adapter->hw.mac.type == e1000_vfadapt)
 		queues = 1;
 
 	/*

From 6edc7d2994cc761604564c06d476c206486e946a Mon Sep 17 00:00:00 2001
From: Edwin Groothuis 
Date: Thu, 19 Aug 2010 21:59:39 +0000
Subject: [PATCH 0100/1624] '\0' -> 0

Fix silly mistake by being overly zeaolous[sp] of applying the style rules.
---
 usr.bin/calendar/locale.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/usr.bin/calendar/locale.c b/usr.bin/calendar/locale.c
index 1f9227a9ff1..70184289d34 100644
--- a/usr.bin/calendar/locale.c
+++ b/usr.bin/calendar/locale.c
@@ -76,7 +76,7 @@ setnnames(void)
 	int i, l;
 	struct tm tm;
 
-	memset(&tm, '\0', sizeof(struct tm));
+	memset(&tm, 0, sizeof(struct tm));
 	for (i = 0; i < 7; i++) {
 		tm.tm_wday = i;
 		strftime(buf, sizeof(buf), "%a", &tm);
@@ -104,7 +104,7 @@ setnnames(void)
 		fndays[i].len = strlen(buf);
 	}
 
-	memset(&tm, '\0', sizeof(struct tm));
+	memset(&tm, 0, sizeof(struct tm));
 	for (i = 0; i < 12; i++) {
 		tm.tm_mon = i;
 		strftime(buf, sizeof(buf), "%b", &tm);

From 67a94de261d38c04532f3992ea71906f0cdde8f2 Mon Sep 17 00:00:00 2001
From: Attilio Rao 
Date: Thu, 19 Aug 2010 22:37:43 +0000
Subject: [PATCH 0101/1624] Revert part of the r211149 as I erroneously ported
 the logical_cpus from Yahoo! patchset as a mask (and according manipulating
 variables) while it is actually a CPU count.

Submitted by:	neel
MFC after:	1 month
X-MFC:		211149
---
 sys/amd64/amd64/mp_machdep.c | 6 +++---
 sys/i386/i386/mp_machdep.c   | 6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/sys/amd64/amd64/mp_machdep.c b/sys/amd64/amd64/mp_machdep.c
index 034ae77cc82..e2f82ec282e 100644
--- a/sys/amd64/amd64/mp_machdep.c
+++ b/sys/amd64/amd64/mp_machdep.c
@@ -127,7 +127,7 @@ extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
  * Local data and functions.
  */
 
-static cpumask_t logical_cpus;
+static u_int logical_cpus;
 static volatile cpumask_t ipi_nmi_pending;
 
 /* used to hold the AP's until we are ready to release them */
@@ -162,8 +162,8 @@ static int	start_all_aps(void);
 static int	start_ap(int apic_id);
 static void	release_aps(void *dummy);
 
-static cpumask_t	hlt_logical_cpus;
-static cpumask_t	hyperthreading_cpus;
+static int	hlt_logical_cpus;
+static u_int	hyperthreading_cpus;
 static cpumask_t	hyperthreading_cpus_mask;
 static int	hyperthreading_allowed = 1;
 static struct	sysctl_ctx_list logical_cpu_clist;
diff --git a/sys/i386/i386/mp_machdep.c b/sys/i386/i386/mp_machdep.c
index ddbb6318cb8..fa50ecfe624 100644
--- a/sys/i386/i386/mp_machdep.c
+++ b/sys/i386/i386/mp_machdep.c
@@ -174,7 +174,7 @@ static u_long *ipi_statclock_counts[MAXCPU];
  * Local data and functions.
  */
 
-static cpumask_t logical_cpus;
+static u_int logical_cpus;
 static volatile cpumask_t ipi_nmi_pending;
 
 /* used to hold the AP's until we are ready to release them */
@@ -210,8 +210,8 @@ static int	start_all_aps(void);
 static int	start_ap(int apic_id);
 static void	release_aps(void *dummy);
 
-static cpumask_t	hlt_logical_cpus;
-static cpumask_t	hyperthreading_cpus;
+static int	hlt_logical_cpus;
+static u_int	hyperthreading_cpus;
 static cpumask_t	hyperthreading_cpus_mask;
 static int	hyperthreading_allowed = 1;
 static struct	sysctl_ctx_list logical_cpu_clist;

From c38208ad5ecf7d8d7b6592e3c6aa86cf55220c34 Mon Sep 17 00:00:00 2001
From: Xin LI 
Date: Thu, 19 Aug 2010 22:55:17 +0000
Subject: [PATCH 0102/1624] Revert a minor part of revision 211364:

 - Imply -h if single file is grepped, this is the GNU behaviour

This is already done by code above the change and have caused a regression
since this instance of code does not check Hflag.

Reported by:	davidxu
Pointy hat to:	delphij
---
 usr.bin/grep/grep.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/usr.bin/grep/grep.c b/usr.bin/grep/grep.c
index 3cb277cb97a..f531c566572 100644
--- a/usr.bin/grep/grep.c
+++ b/usr.bin/grep/grep.c
@@ -681,15 +681,12 @@ main(int argc, char *argv[])
 
 	if (dirbehave == DIR_RECURSE)
 		c = grep_tree(aargv);
-	else {
-		if (aargc == 1)
-			hflag = true;
+	else
 		for (c = 0; aargc--; ++aargv) {
 			if ((finclude || fexclude) && !file_matching(*aargv))
 				continue;
 			c+= procfile(*aargv);
 		}
-	}
 
 #ifndef WITHOUT_NLS
 	catclose(catalog);

From e7a6db74671908a2eeb94026a56dbd38529ab6be Mon Sep 17 00:00:00 2001
From: Ana Kukec 
Date: Thu, 19 Aug 2010 23:16:44 +0000
Subject: [PATCH 0103/1624] Fix mbuf leakages and remove unneccessary duplicate
 mbuf frees. Use the right copy of an mbuf for the IP6_EXTHDR_CHECK.

Reported by:	zec, hrs
Approved by:	bz (mentor)
---
 sys/netinet6/icmp6.c | 20 +++++++-------------
 1 file changed, 7 insertions(+), 13 deletions(-)

diff --git a/sys/netinet6/icmp6.c b/sys/netinet6/icmp6.c
index 47657b2c0c1..952b38acf85 100644
--- a/sys/netinet6/icmp6.c
+++ b/sys/netinet6/icmp6.c
@@ -786,14 +786,12 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			goto freeit;
 		}
 		if (send_sendso_input_hook != NULL) {
-			IP6_EXTHDR_CHECK(m, off,
+			IP6_EXTHDR_CHECK(n, off,
 			    icmp6len, IPPROTO_DONE);
                         error = send_sendso_input_hook(n, ifp,
 			    SND_IN, ip6len);
-			if (error == 0) {
-				m_freem(n);
-				return (IPPROTO_DONE);
-			}
+			if (error == 0)
+				goto freeit;
 			/* -1 == no app on SEND socket */
 			nd6_rs_input(n, off, icmp6len);
 		} else
@@ -819,14 +817,13 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			} else
 				nd6_ra_input(m, off, icmp6len);
 			m = NULL;
-			m_freem(n);
 			goto freeit;
 		}
 		if (send_sendso_input_hook != NULL) {
 			error = send_sendso_input_hook(n, ifp,
 			    SND_IN, ip6len);
 			if (error == 0)
-				return (IPPROTO_DONE);
+				goto freeit;
 			nd6_ra_input(n, off, icmp6len);
 		} else
 			nd6_ra_input(n, off, icmp6len);
@@ -848,7 +845,6 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 				nd6_ns_input(m, off, icmp6len);
 			} else
 				nd6_ns_input(m, off, icmp6len);
-			m_freem(n);
 			m = NULL;
 			goto freeit;
 		}
@@ -856,7 +852,7 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			error = send_sendso_input_hook(n, ifp,
 			    SND_IN, ip6len);
 			if (error == 0)
-				return (IPPROTO_DONE);
+				goto freeit;
 			nd6_ns_input(n, off, icmp6len);
 		} else
 			nd6_ns_input(n, off, icmp6len);
@@ -880,7 +876,6 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 				nd6_na_input(m, off, icmp6len);
 			} else
 				nd6_na_input(m, off, icmp6len);
-			m_freem(n);
 			m = NULL;
 			goto freeit;
 		}
@@ -888,7 +883,7 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			error = send_sendso_input_hook(n, ifp,
 			    SND_IN, ip6len);
 			if (error == 0)
-				return (IPPROTO_DONE);
+				goto freeit;
 			nd6_na_input(n, off, icmp6len);
 		} else
 			nd6_na_input(n, off, icmp6len);
@@ -910,7 +905,6 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			    icmp6_redirect_input(m, off);
 			} else
 				icmp6_redirect_input(m, off);
-			m_freem(n);
 			m = NULL;
 			goto freeit;
 		}
@@ -918,7 +912,7 @@ icmp6_input(struct mbuf **mp, int *offp, int proto)
 			error = send_sendso_input_hook(n, ifp,
 			    SND_IN, ip6len);
 			if (error == 0)
-				return (IPPROTO_DONE);
+				goto freeit;
 			icmp6_redirect_input(n, off);
 		} else
 			icmp6_redirect_input(n, off);

From 895051e367d95d78331e6fbc1771f49686b65cd7 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Fri, 20 Aug 2010 01:23:17 +0000
Subject: [PATCH 0104/1624] FPU EMU is 32-bit only for now, so mark it as a
 powerpc-only feature. This fixes powerpc64 LINT.

---
 sys/conf/files.powerpc | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/sys/conf/files.powerpc b/sys/conf/files.powerpc
index 1788a97bf23..70ca1087132 100644
--- a/sys/conf/files.powerpc
+++ b/sys/conf/files.powerpc
@@ -102,15 +102,15 @@ powerpc/booke/trap.c		optional	e500
 powerpc/booke/vm_machdep.c	optional	e500
 powerpc/cpufreq/dfs.c		optional	cpufreq
 powerpc/cpufreq/pcr.c		optional	cpufreq aim
-powerpc/fpu/fpu_add.c		optional	fpu_emu
-powerpc/fpu/fpu_compare.c	optional	fpu_emu
-powerpc/fpu/fpu_div.c		optional	fpu_emu
-powerpc/fpu/fpu_emu.c		optional	fpu_emu
-powerpc/fpu/fpu_explode.c	optional	fpu_emu
-powerpc/fpu/fpu_implode.c	optional	fpu_emu
-powerpc/fpu/fpu_mul.c		optional	fpu_emu
-powerpc/fpu/fpu_sqrt.c		optional	fpu_emu
-powerpc/fpu/fpu_subr.c		optional	fpu_emu
+powerpc/fpu/fpu_add.c		optional	fpu_emu powerpc
+powerpc/fpu/fpu_compare.c	optional	fpu_emu powerpc
+powerpc/fpu/fpu_div.c		optional	fpu_emu powerpc
+powerpc/fpu/fpu_emu.c		optional	fpu_emu powerpc
+powerpc/fpu/fpu_explode.c	optional	fpu_emu powerpc
+powerpc/fpu/fpu_implode.c	optional	fpu_emu powerpc
+powerpc/fpu/fpu_mul.c		optional	fpu_emu powerpc
+powerpc/fpu/fpu_sqrt.c		optional	fpu_emu powerpc
+powerpc/fpu/fpu_subr.c		optional	fpu_emu powerpc
 powerpc/mambo/mambocall.S	optional	mambo
 powerpc/mambo/mambo.c		optional	mambo
 powerpc/mambo/mambo_console.c	optional	mambo

From 719863239e5f6b682ffd82941fc989f857bc9f68 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 20 Aug 2010 04:15:05 +0000
Subject: [PATCH 0105/1624] According to specification, function fcntl() is a
 cancellation point only when cmd argument is F_SETLKW.

---
 lib/libthr/thread/thr_syscalls.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/lib/libthr/thread/thr_syscalls.c b/lib/libthr/thread/thr_syscalls.c
index 92670a9a77a..ad3f091470a 100644
--- a/lib/libthr/thread/thr_syscalls.c
+++ b/lib/libthr/thread/thr_syscalls.c
@@ -242,8 +242,6 @@ __fcntl(int fd, int cmd,...)
 	int	ret;
 	va_list	ap;
 	
-	_thr_cancel_enter(curthread);
-
 	va_start(ap, cmd);
 	switch (cmd) {
 	case F_DUPFD:
@@ -257,6 +255,17 @@ __fcntl(int fd, int cmd,...)
 	case F_GETFL:
 		ret = __sys_fcntl(fd, cmd);
 		break;
+
+	case F_OSETLKW:
+	case F_SETLKW:
+		_thr_cancel_enter(curthread);
+#ifdef SYSCALL_COMPAT
+		ret = __fcntl_compat(fd, cmd, va_arg(ap, void *));
+#else
+		ret = __sys_fcntl(fd, cmd, va_arg(ap, void *));
+#endif
+		_thr_cancel_leave(curthread);
+		break;
 	default:
 #ifdef SYSCALL_COMPAT
 		ret = __fcntl_compat(fd, cmd, va_arg(ap, void *));
@@ -266,8 +275,6 @@ __fcntl(int fd, int cmd,...)
 	}
 	va_end(ap);
 
-	_thr_cancel_leave(curthread);
-
 	return (ret);
 }
 

From c6aa908d9cb06c4b67e070f02fb60cd921305791 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 20 Aug 2010 04:28:30 +0000
Subject: [PATCH 0106/1624] If thread set a TDP_WAKEUP for itself, clears the
 flag and returns EINTR immediately, this is used for implementing reliable
 pthread cancellation.

---
 sys/kern/subr_sleepqueue.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/sys/kern/subr_sleepqueue.c b/sys/kern/subr_sleepqueue.c
index c51def62091..0d2c65e57e5 100644
--- a/sys/kern/subr_sleepqueue.c
+++ b/sys/kern/subr_sleepqueue.c
@@ -408,6 +408,12 @@ sleepq_catch_signals(void *wchan, int pri)
 	sc = SC_LOOKUP(wchan);
 	mtx_assert(&sc->sc_lock, MA_OWNED);
 	MPASS(wchan != NULL);
+	if ((td->td_pflags & TDP_WAKEUP) != 0) {
+		td->td_pflags &= ~TDP_WAKEUP;
+		ret = EINTR;
+		goto out;
+	}
+
 	/*
 	 * See if there are any pending signals for this thread.  If not
 	 * we can switch immediately.  Otherwise do the signal processing
@@ -453,6 +459,7 @@ sleepq_catch_signals(void *wchan, int pri)
 		sleepq_switch(wchan, pri);
 		return (0);
 	}
+out:
 	/*
 	 * There were pending signals and this thread is still
 	 * on the sleep queue, remove it from the sleep queue.

From 635f917a9d024248ee484721dd1d1c899c44e8d0 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 20 Aug 2010 05:15:39 +0000
Subject: [PATCH 0107/1624]   In current implementation, thread cancellation is
 done in signal handler, which does not know what is the state of interrupted
 system call, for example, open() system call opened a file and the thread is
 still cancelled, result is descriptor leak, there are other problems which
 can cause resource leak or undeterminable side effect when a thread is
 cancelled. However, this is no longer true in new implementation.

  In defering mode, a thread is canceled if cancellation request is pending and
later the thread enters a cancellation point, otherwise, a later
pthread_cancel() just causes SIGCANCEL to be sent to the target thread, and
causes target thread to abort system call, userland code in libthr then checks
cancellation state, and cancels the thread if needed. For example, the
cancellation point open(), the thread may be canceled at start,
but later, if it opened a file descriptor, it is not canceled, this avoids
file handle leak. Another example is read(), a thread may be canceled at start
of the function, but later, if it read some bytes from a socket, the thread
is not canceled, the caller then can decide if it should still enable cancelling
or disable it and continue reading data until it thinks it has read all
bytes of a packet, and keeps a protocol stream in health state, if user ignores
partly reading of a packet without disabling cancellation, then second iteration
of read loop cause the thread to be cancelled.
An exception is that the close() cancellation point always closes a file handle
despite whether the thread is cancelled or not.

  The old mechanism is still kept, for a functions which is not so easily to
fix a cancellation problem, the rough mechanism is used.

Reviewed by: kib@
---
 lib/libthr/thread/thr_cancel.c   |  46 +++---
 lib/libthr/thread/thr_cond.c     |  14 +-
 lib/libthr/thread/thr_join.c     |   9 +-
 lib/libthr/thread/thr_private.h  |   3 +-
 lib/libthr/thread/thr_sig.c      |  78 +++++++++--
 lib/libthr/thread/thr_syscalls.c | 233 +++++++++++++++++++++++--------
 6 files changed, 284 insertions(+), 99 deletions(-)

diff --git a/lib/libthr/thread/thr_cancel.c b/lib/libthr/thread/thr_cancel.c
index bf93fdcae4d..943d53c39e9 100644
--- a/lib/libthr/thread/thr_cancel.c
+++ b/lib/libthr/thread/thr_cancel.c
@@ -42,7 +42,7 @@ static inline void
 testcancel(struct pthread *curthread)
 {
 	if (__predict_false(SHOULD_CANCEL(curthread) &&
-	    !THR_IN_CRITICAL(curthread) && curthread->cancel_defer == 0))
+	    !THR_IN_CRITICAL(curthread)))
 		_pthread_exit(PTHREAD_CANCELED);
 }
 
@@ -143,40 +143,44 @@ _pthread_testcancel(void)
 void
 _thr_cancel_enter(struct pthread *curthread)
 {
-	if (curthread->cancel_enable) {
-		curthread->cancel_point++;
+	curthread->cancel_point++;
+	if (curthread->cancel_enable)
 		testcancel(curthread);
+}
+
+void
+_thr_cancel_enter_defer(struct pthread *curthread, int maycancel)
+{
+	curthread->cancel_defer++;
+	curthread->cancel_point++;
+	if (__predict_false(SHOULD_CANCEL(curthread) &&
+	    !THR_IN_CRITICAL(curthread))) {
+		if (!maycancel)
+			thr_wake(curthread->tid);
+		else
+			_pthread_exit(PTHREAD_CANCELED);
 	}
 }
 
 void
 _thr_cancel_leave(struct pthread *curthread)
 {
-	if (curthread->cancel_enable)
-		curthread->cancel_point--;
+	curthread->cancel_point--;
 }
 
 void
-_thr_cancel_enter_defer(struct pthread *curthread)
+_thr_cancel_leave2(struct pthread *curthread, int maycancel)
 {
-	if (curthread->cancel_enable) {
-		curthread->cancel_point++;
+	if (curthread->cancel_enable && maycancel)
 		testcancel(curthread);
-		curthread->cancel_defer++;
-	}
+	curthread->cancel_point--;
 }
 
 void
-_thr_cancel_leave_defer(struct pthread *curthread, int check)
+_thr_cancel_leave_defer(struct pthread *curthread, int maycancel)
 {
-	if (curthread->cancel_enable) {
-		if (!check) {
-			curthread->cancel_point--;
-			curthread->cancel_defer--;
-		} else {
-			curthread->cancel_defer--;
-			testcancel(curthread);
-			curthread->cancel_point--;
-		}
-	}
+	if (curthread->cancel_enable && maycancel)
+		testcancel(curthread);
+	curthread->cancel_point--;
+	curthread->cancel_defer--;
 }
diff --git a/lib/libthr/thread/thr_cond.c b/lib/libthr/thread/thr_cond.c
index 85eecaaf1ee..95970d9d0fc 100644
--- a/lib/libthr/thread/thr_cond.c
+++ b/lib/libthr/thread/thr_cond.c
@@ -162,6 +162,14 @@ cond_cancel_handler(void *arg)
 	_mutex_cv_lock(info->mutex, info->count);
 }
 
+/*
+ * Cancellation behaivor:
+ *   Thread may be canceled at start, if thread is canceled, it means it
+ *   did not get a wakeup from pthread_cond_signal(), otherwise, it is
+ *   not canceled.
+ *   Thread cancellation never cause wakeup from pthread_cond_signal()
+ *   to be lost.
+ */
 static int
 cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
 	const struct timespec *abstime, int cancel)
@@ -180,6 +188,8 @@ cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
 	    (ret = init_static(curthread, cond)) != 0))
 		return (ret);
 
+	_thr_testcancel(curthread);
+
 	cv = *cond;
 	THR_UMUTEX_LOCK(curthread, &cv->c_lock);
 	ret = _mutex_cv_unlock(mutex, &info.count);
@@ -200,10 +210,10 @@ cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
 
 	if (cancel) {
 		THR_CLEANUP_PUSH(curthread, cond_cancel_handler, &info);
-		_thr_cancel_enter_defer(curthread);
+		_thr_cancel_enter_defer(curthread, 0);
 		ret = _thr_ucond_wait(&cv->c_kerncv, &cv->c_lock, tsp, 1);
 		info.cond = NULL;
-		_thr_cancel_leave_defer(curthread, ret);
+		_thr_cancel_leave_defer(curthread, (ret != 0));
 		THR_CLEANUP_POP(curthread, 0);
 	} else {
 		ret = _thr_ucond_wait(&cv->c_kerncv, &cv->c_lock, tsp, 0);
diff --git a/lib/libthr/thread/thr_join.c b/lib/libthr/thread/thr_join.c
index 139c74c7925..8201abafeae 100644
--- a/lib/libthr/thread/thr_join.c
+++ b/lib/libthr/thread/thr_join.c
@@ -68,6 +68,10 @@ _pthread_timedjoin_np(pthread_t pthread, void **thread_return,
 	return (join_common(pthread, thread_return, abstime));
 }
 
+/*
+ * Cancellation behavior:
+ *   if the thread is canceled, joinee is not recycled.
+ */
 static int
 join_common(pthread_t pthread, void **thread_return,
 	const struct timespec *abstime)
@@ -103,10 +107,11 @@ join_common(pthread_t pthread, void **thread_return,
 	THREAD_LIST_UNLOCK(curthread);
 
 	THR_CLEANUP_PUSH(curthread, backout_join, pthread);
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 
 	tid = pthread->tid;
 	while (pthread->tid != TID_TERMINATED) {
+		_thr_testcancel(curthread);
 		if (abstime != NULL) {
 			clock_gettime(CLOCK_REALTIME, &ts);
 			TIMESPEC_SUB(&ts2, abstime, &ts);
@@ -122,7 +127,7 @@ join_common(pthread_t pthread, void **thread_return,
 			break;
 	}
 
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, 0);
 	THR_CLEANUP_POP(curthread, 0);
 
 	if (ret == ETIMEDOUT) {
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index 415c1ecc4ec..465f725cd42 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -644,7 +644,8 @@ void	_thread_printf(int, const char *, ...) __hidden;
 void	_thr_spinlock_init(void) __hidden;
 void	_thr_cancel_enter(struct pthread *) __hidden;
 void	_thr_cancel_leave(struct pthread *) __hidden;
-void	_thr_cancel_enter_defer(struct pthread *) __hidden;
+void	_thr_cancel_leave2(struct pthread *, int) __hidden;
+void	_thr_cancel_enter_defer(struct pthread *, int) __hidden;
 void	_thr_cancel_leave_defer(struct pthread *, int) __hidden;
 void	_thr_testcancel(struct pthread *) __hidden;
 void	_thr_signal_block(struct pthread *) __hidden;
diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index efd8cb49284..eed6fdbba09 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -67,8 +67,6 @@ sigcancel_handler(int sig __unused,
 {
 	struct pthread *curthread = _get_curthread();
 
-	if (curthread->cancel_defer && curthread->cancel_pending)
-		thr_wake(curthread->tid);
 	curthread->in_sigcancel_handler++;
 	_thr_ast(curthread);
 	curthread->in_sigcancel_handler--;
@@ -77,13 +75,50 @@ sigcancel_handler(int sig __unused,
 void
 _thr_ast(struct pthread *curthread)
 {
-	if (!THR_IN_CRITICAL(curthread)) {
-		_thr_testcancel(curthread);
-		if (__predict_false((curthread->flags &
-		    (THR_FLAGS_NEED_SUSPEND | THR_FLAGS_SUSPENDED))
-			== THR_FLAGS_NEED_SUSPEND))
-			_thr_suspend_check(curthread);
+
+	if (THR_IN_CRITICAL(curthread))
+		return;
+
+	if (curthread->cancel_pending && curthread->cancel_enable
+		&& !curthread->cancelling) {
+		if (curthread->cancel_async) {
+			/*
+		 	 * asynchronous cancellation mode, act upon
+			 * immediately.
+		 	 */
+			_pthread_exit(PTHREAD_CANCELED);
+		} else {
+			/*
+		 	 * Otherwise, we are in defer mode, and we are at
+			 * cancel point, tell kernel to not block the current
+			 * thread on next cancelable system call.
+			 * 
+			 * There are two cases we should call thr_wake() to 
+			 * turn on TDP_WAKEUP in kernel:
+			 * 1) we are going to call a cancelable system call,
+			 *    non-zero cancel_point means we are already in
+			 *    cancelable state, next system call is cancelable.
+			 * 2) because _thr_ast() may be called by
+			 *    THR_CRITICAL_LEAVE() which is used by rtld rwlock
+			 *    and any libthr internal locks, when rtld rwlock
+			 *    is used, it is mostly caused my an unresolved PLT.
+			 *    those routines may clear the TDP_WAKEUP flag by
+			 *    invoking some system calls, in those cases, we
+			 *    also should reenable the flag.
+		 	 */
+			if (curthread->cancel_point) {
+				if (curthread->cancel_defer)
+					thr_wake(curthread->tid);
+				else
+					_pthread_exit(PTHREAD_CANCELED);
+			}
+		}
 	}
+
+	if (__predict_false((curthread->flags &
+	    (THR_FLAGS_NEED_SUSPEND | THR_FLAGS_SUSPENDED))
+		== THR_FLAGS_NEED_SUSPEND))
+		_thr_suspend_check(curthread);
 }
 
 void
@@ -296,6 +331,11 @@ _sigtimedwait(const sigset_t *set, siginfo_t *info,
 	return (ret);
 }
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, if thread got signal,
+ *   it is not canceled.
+ */
 int
 __sigtimedwait(const sigset_t *set, siginfo_t *info,
 	const struct timespec * timeout)
@@ -311,9 +351,9 @@ __sigtimedwait(const sigset_t *set, siginfo_t *info,
 		pset = &newset;
 	} else
 		pset = set;
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_sigtimedwait(pset, info, timeout);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, (ret == -1));
 	return (ret);
 }
 
@@ -335,6 +375,11 @@ _sigwaitinfo(const sigset_t *set, siginfo_t *info)
 	return (ret);
 }
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, if thread got signal,
+ *   it is not canceled.
+ */ 
 int
 __sigwaitinfo(const sigset_t *set, siginfo_t *info)
 {
@@ -350,9 +395,9 @@ __sigwaitinfo(const sigset_t *set, siginfo_t *info)
 	} else
 		pset = set;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_sigwaitinfo(pset, info);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	return (ret);
 }
 
@@ -374,6 +419,11 @@ _sigwait(const sigset_t *set, int *sig)
 	return (ret);
 }
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, if thread got signal,
+ *   it is not canceled.
+ */ 
 int
 __sigwait(const sigset_t *set, int *sig)
 {
@@ -389,8 +439,8 @@ __sigwait(const sigset_t *set, int *sig)
 	} else 
 		pset = set;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_sigwait(pset, sig);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, (ret != 0));
 	return (ret);
 }
diff --git a/lib/libthr/thread/thr_syscalls.c b/lib/libthr/thread/thr_syscalls.c
index ad3f091470a..73fa56fcc8f 100644
--- a/lib/libthr/thread/thr_syscalls.c
+++ b/lib/libthr/thread/thr_syscalls.c
@@ -158,6 +158,10 @@ ssize_t	__writev(int, const struct iovec *, int);
 
 __weak_reference(__accept, accept);
 
+/*
+ * Cancellation behavior:
+ *   If thread is canceled, no socket is created.
+ */
 int
 __accept(int s, struct sockaddr *addr, socklen_t *addrlen)
 {
@@ -165,9 +169,9 @@ __accept(int s, struct sockaddr *addr, socklen_t *addrlen)
 	int ret;
 
 	curthread = _get_curthread();
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_accept(s, addr, addrlen);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
  	return (ret);
 }
@@ -190,61 +194,84 @@ __aio_suspend(const struct aiocb * const iocbs[], int niocb, const struct
 
 __weak_reference(__close, close);
 
+/*
+ * Cancellation behavior:
+ *   According to manual of close(), the file descriptor is always deleted.
+ *   Here, thread is only canceled after the system call, so the file
+ *   descriptor is always deleted despite whether the thread is canceled
+ *   or not.
+ */
 int
 __close(int fd)
 {
 	struct pthread	*curthread = _get_curthread();
 	int	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 0);
 	ret = __sys_close(fd);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, 1);
 	
 	return (ret);
 }
 
 __weak_reference(__connect, connect);
 
+/*
+ * Cancellation behavior:
+ *   If the thread is canceled, connection is not made.
+ */
 int
 __connect(int fd, const struct sockaddr *name, socklen_t namelen)
 {
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 0);
 	ret = __sys_connect(fd, name, namelen);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
  	return (ret);
 }
 
 __weak_reference(___creat, creat);
 
+/*
+ * Cancellation behavior:
+ *   If thread is canceled, file is not created.
+ */
 int
 ___creat(const char *path, mode_t mode)
 {
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __creat(path, mode);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	
 	return ret;
 }
 
 __weak_reference(__fcntl, fcntl);
 
+/*
+ * Cancellation behavior:
+ *   According to specification, only F_SETLKW is a cancellation point.
+ *   Thread is only canceled at start, or canceled if the system call
+ *   is failure, this means the function does not generate side effect
+ *   if it is canceled.
+ */
 int
 __fcntl(int fd, int cmd,...)
 {
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 	va_list	ap;
-	
+
 	va_start(ap, cmd);
 	switch (cmd) {
 	case F_DUPFD:
+	case F_DUP2FD:
 		ret = __sys_fcntl(fd, cmd, va_arg(ap, int));
 		break;
 	case F_SETFD:
@@ -255,16 +282,15 @@ __fcntl(int fd, int cmd,...)
 	case F_GETFL:
 		ret = __sys_fcntl(fd, cmd);
 		break;
-
 	case F_OSETLKW:
 	case F_SETLKW:
-		_thr_cancel_enter(curthread);
+		_thr_cancel_enter_defer(curthread, 1);
 #ifdef SYSCALL_COMPAT
 		ret = __fcntl_compat(fd, cmd, va_arg(ap, void *));
 #else
 		ret = __sys_fcntl(fd, cmd, va_arg(ap, void *));
 #endif
-		_thr_cancel_leave(curthread);
+		_thr_cancel_leave_defer(curthread, ret == -1);
 		break;
 	default:
 #ifdef SYSCALL_COMPAT
@@ -280,30 +306,38 @@ __fcntl(int fd, int cmd,...)
 
 __weak_reference(__fsync, fsync);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled after system call.
+ */
 int
 __fsync(int fd)
 {
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 0);
 	ret = __sys_fsync(fd);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, 1);
 
 	return (ret);
 }
 
 __weak_reference(__msync, msync);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled after system call.
+ */
 int
 __msync(void *addr, size_t len, int flags)
 {
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 0);
 	ret = __sys_msync(addr, len, flags);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, 1);
 
 	return ret;
 }
@@ -326,6 +360,10 @@ __nanosleep(const struct timespec *time_to_sleep,
 
 __weak_reference(__open, open);
 
+/*
+ * Cancellation behavior:
+ *   If the thread is canceled, file is not opened.
+ */
 int
 __open(const char *path, int flags,...)
 {
@@ -334,8 +372,6 @@ __open(const char *path, int flags,...)
 	int	mode = 0;
 	va_list	ap;
 
-	_thr_cancel_enter(curthread);
-	
 	/* Check if the file is being created: */
 	if (flags & O_CREAT) {
 		/* Get the creation mode: */
@@ -344,15 +380,19 @@ __open(const char *path, int flags,...)
 		va_end(ap);
 	}
 	
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_open(path, flags, mode);
-
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
 	return ret;
 }
 
 __weak_reference(__openat, openat);
 
+/*
+ * Cancellation behavior:
+ *   If the thread is canceled, file is not opened.
+ */
 int
 __openat(int fd, const char *path, int flags, ...)
 {
@@ -361,7 +401,6 @@ __openat(int fd, const char *path, int flags, ...)
 	int	mode = 0;
 	va_list	ap;
 
-	_thr_cancel_enter(curthread);
 	
 	/* Check if the file is being created: */
 	if (flags & O_CREAT) {
@@ -371,30 +410,40 @@ __openat(int fd, const char *path, int flags, ...)
 		va_end(ap);
 	}
 	
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_openat(fd, path, flags, mode);
-
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
 	return ret;
 }
 
 __weak_reference(__poll, poll);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns something,
+ *   the thread is not canceled.
+ */
 int
 __poll(struct pollfd *fds, unsigned int nfds, int timeout)
 {
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_poll(fds, nfds, timeout);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
 	return ret;
 }
 
 __weak_reference(___pselect, pselect);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns something,
+ *   the thread is not canceled.
+ */
 int 
 ___pselect(int count, fd_set *rfds, fd_set *wfds, fd_set *efds, 
 	const struct timespec *timo, const sigset_t *mask)
@@ -402,45 +451,59 @@ ___pselect(int count, fd_set *rfds, fd_set *wfds, fd_set *efds,
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_pselect(count, rfds, wfds, efds, timo, mask);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
 	return (ret);
 }
 
 __weak_reference(__read, read);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call got some data, 
+ *   the thread is not canceled.
+ */
 ssize_t
 __read(int fd, void *buf, size_t nbytes)
 {
 	struct pthread *curthread = _get_curthread();
 	ssize_t	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_read(fd, buf, nbytes);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 
 	return ret;
 }
 
 __weak_reference(__readv, readv);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call got some data, 
+ *   the thread is not canceled.
+ */
 ssize_t
 __readv(int fd, const struct iovec *iov, int iovcnt)
 {
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_readv(fd, iov, iovcnt);
-	_thr_cancel_leave(curthread);
-
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	return ret;
 }
 
 __weak_reference(__recvfrom, recvfrom);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call got some data, 
+ *   the thread is not canceled.
+ */
 ssize_t
 __recvfrom(int s, void *b, size_t l, int f, struct sockaddr *from,
     socklen_t *fl)
@@ -448,28 +511,38 @@ __recvfrom(int s, void *b, size_t l, int f, struct sockaddr *from,
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_recvfrom(s, b, l, f, from, fl);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	return (ret);
 }
 
 __weak_reference(__recvmsg, recvmsg);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call got some data, 
+ *   the thread is not canceled.
+ */
 ssize_t
 __recvmsg(int s, struct msghdr *m, int f)
 {
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_recvmsg(s, m, f);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	return (ret);
 }
 
 __weak_reference(__select, select);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns something,
+ *   the thread is not canceled.
+ */
 int 
 __select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
 	struct timeval *timeout)
@@ -477,28 +550,38 @@ __select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_select(numfds, readfds, writefds, exceptfds, timeout);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	return ret;
 }
 
 __weak_reference(__sendmsg, sendmsg);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call sent
+ *   data, the thread is not canceled.
+ */
 ssize_t
 __sendmsg(int s, const struct msghdr *m, int f)
 {
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_sendmsg(s, m, f);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret <= 0);
 	return (ret);
 }
 
 __weak_reference(__sendto, sendto);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call sent some
+ *   data, the thread is not canceled.
+ */
 ssize_t
 __sendto(int s, const void *m, size_t l, int f, const struct sockaddr *t,
     socklen_t tl)
@@ -506,9 +589,9 @@ __sendto(int s, const void *m, size_t l, int f, const struct sockaddr *t,
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_sendto(s, m, l, f, t, tl);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret <= 0);
 	return (ret);
 }
 
@@ -544,16 +627,20 @@ ___system(const char *string)
 
 __weak_reference(___tcdrain, tcdrain);
 
+/*
+ * Cancellation behavior:
+ *   If thread is canceled, the system call is not completed,
+ *   this means not all bytes were drained.
+ */
 int
 ___tcdrain(int fd)
 {
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 	
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __tcdrain(fd);
-	_thr_cancel_leave(curthread);
-
+	_thr_cancel_leave_defer(curthread, ret == -1);
 	return (ret);
 }
 
@@ -574,90 +661,118 @@ ___usleep(useconds_t useconds)
 
 __weak_reference(___wait, wait);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns
+ *   a child pid, the thread is not canceled.
+ */
 pid_t
 ___wait(int *istat)
 {
 	struct pthread *curthread = _get_curthread();
 	pid_t	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __wait(istat);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret <= 0);
 
 	return ret;
 }
 
 __weak_reference(__wait3, wait3);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns
+ *   a child pid, the thread is not canceled.
+ */
 pid_t
 __wait3(int *status, int options, struct rusage *rusage)
 {
 	struct pthread *curthread = _get_curthread();
 	pid_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = _wait4(WAIT_ANY, status, options, rusage);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret <= 0);
 
 	return (ret);
 }
 
 __weak_reference(__wait4, wait4);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns
+ *   a child pid, the thread is not canceled.
+ */
 pid_t
 __wait4(pid_t pid, int *status, int options, struct rusage *rusage)
 {
 	struct pthread *curthread = _get_curthread();
 	pid_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_wait4(pid, status, options, rusage);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret <= 0);
 
 	return ret;
 }
 
 __weak_reference(___waitpid, waitpid);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the system call returns
+ *   a child pid, the thread is not canceled.
+ */
 pid_t
 ___waitpid(pid_t wpid, int *status, int options)
 {
 	struct pthread *curthread = _get_curthread();
 	pid_t	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __waitpid(wpid, status, options);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave_defer(curthread, ret <= 0);
 	
 	return ret;
 }
 
 __weak_reference(__write, write);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the thread wrote some data,
+ *   it is not canceled.
+ */
 ssize_t
 __write(int fd, const void *buf, size_t nbytes)
 {
 	struct pthread *curthread = _get_curthread();
 	ssize_t	ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_write(fd, buf, nbytes);
-	_thr_cancel_leave(curthread);
-
+	_thr_cancel_leave_defer(curthread, (ret <= 0));
 	return ret;
 }
 
 __weak_reference(__writev, writev);
 
+/*
+ * Cancellation behavior:
+ *   Thread may be canceled at start, but if the thread wrote some data,
+ *   it is not canceled.
+ */
 ssize_t
 __writev(int fd, const struct iovec *iov, int iovcnt)
 {
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter(curthread);
+	_thr_cancel_enter_defer(curthread, 1);
 	ret = __sys_writev(fd, iov, iovcnt);
-	_thr_cancel_leave(curthread);
-
+	_thr_cancel_leave_defer(curthread, (ret <= 0));
 	return ret;
 }

From 82746ea546f8eca632fb40d7c307cad36d70699b Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 20 Aug 2010 13:42:48 +0000
Subject: [PATCH 0108/1624] Reduce redundant code.

Submitted by: kib
---
 lib/libthr/thread/thr_sig.c | 103 +++++++++---------------------------
 1 file changed, 24 insertions(+), 79 deletions(-)

diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index eed6fdbba09..115aa65a1cc 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -268,23 +268,26 @@ _pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
 
 __weak_reference(__sigsuspend, sigsuspend);
 
+static const sigset_t *
+thr_remove_thr_signals(const sigset_t *set, sigset_t *newset)
+{
+	const sigset_t *pset;
+
+	if (SIGISMEMBER(*set, SIGCANCEL)) {
+		*newset = *set;
+		SIGDELSET(*newset, SIGCANCEL);
+		pset = newset;
+	} else
+		pset = set;
+	return (pset);
+}
+
 int
 _sigsuspend(const sigset_t * set)
 {
 	sigset_t newset;
-	const sigset_t *pset;
-	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else
-		pset = set;
-
-	ret = __sys_sigsuspend(pset);
-
-	return (ret);
+	return (__sys_sigsuspend(thr_remove_thr_signals(set, &newset)));
 }
 
 int
@@ -292,18 +295,10 @@ __sigsuspend(const sigset_t * set)
 {
 	struct pthread *curthread = _get_curthread();
 	sigset_t newset;
-	const sigset_t *pset;
 	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else
-		pset = set;
-
 	_thr_cancel_enter(curthread);
-	ret = __sys_sigsuspend(pset);
+	ret = __sys_sigsuspend(thr_remove_thr_signals(set, &newset));
 	_thr_cancel_leave(curthread);
 
 	return (ret);
@@ -318,17 +313,9 @@ _sigtimedwait(const sigset_t *set, siginfo_t *info,
 	const struct timespec * timeout)
 {
 	sigset_t newset;
-	const sigset_t *pset;
-	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else
-		pset = set;
-	ret = __sys_sigtimedwait(pset, info, timeout);
-	return (ret);
+	return (__sys_sigtimedwait(thr_remove_thr_signals(set, &newset), info,
+	    timeout));
 }
 
 /*
@@ -342,17 +329,11 @@ __sigtimedwait(const sigset_t *set, siginfo_t *info,
 {
 	struct pthread	*curthread = _get_curthread();
 	sigset_t newset;
-	const sigset_t *pset;
 	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else
-		pset = set;
 	_thr_cancel_enter_defer(curthread, 1);
-	ret = __sys_sigtimedwait(pset, info, timeout);
+	ret = __sys_sigtimedwait(thr_remove_thr_signals(set, &newset), info,
+	    timeout);
 	_thr_cancel_leave_defer(curthread, (ret == -1));
 	return (ret);
 }
@@ -361,18 +342,8 @@ int
 _sigwaitinfo(const sigset_t *set, siginfo_t *info)
 {
 	sigset_t newset;
-	const sigset_t *pset;
-	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else
-		pset = set;
-
-	ret = __sys_sigwaitinfo(pset, info);
-	return (ret);
+	return (__sys_sigwaitinfo(thr_remove_thr_signals(set, &newset), info));
 }
 
 /*
@@ -385,18 +356,10 @@ __sigwaitinfo(const sigset_t *set, siginfo_t *info)
 {
 	struct pthread	*curthread = _get_curthread();
 	sigset_t newset;
-	const sigset_t *pset;
 	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else
-		pset = set;
-
 	_thr_cancel_enter_defer(curthread, 1);
-	ret = __sys_sigwaitinfo(pset, info);
+	ret = __sys_sigwaitinfo(thr_remove_thr_signals(set, &newset), info);
 	_thr_cancel_leave_defer(curthread, ret == -1);
 	return (ret);
 }
@@ -405,18 +368,8 @@ int
 _sigwait(const sigset_t *set, int *sig)
 {
 	sigset_t newset;
-	const sigset_t *pset;
-	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else 
-		pset = set;
-
-	ret = __sys_sigwait(pset, sig);
-	return (ret);
+	return (__sys_sigwait(thr_remove_thr_signals(set, &newset), sig));
 }
 
 /*
@@ -429,18 +382,10 @@ __sigwait(const sigset_t *set, int *sig)
 {
 	struct pthread	*curthread = _get_curthread();
 	sigset_t newset;
-	const sigset_t *pset;
 	int ret;
 
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		newset = *set;
-		SIGDELSET(newset, SIGCANCEL);
-		pset = &newset;
-	} else 
-		pset = set;
-
 	_thr_cancel_enter_defer(curthread, 1);
-	ret = __sys_sigwait(pset, sig);
+	ret = __sys_sigwait(thr_remove_thr_signals(set, &newset), sig);
 	_thr_cancel_leave_defer(curthread, (ret != 0));
 	return (ret);
 }

From be55a6bd2ab72bbb159a223b80ec20b3e4926151 Mon Sep 17 00:00:00 2001
From: Matt Jacob 
Date: Fri, 20 Aug 2010 17:20:05 +0000
Subject: [PATCH 0109/1624] Revert r211434. Offline discussions have convinced
 me that this should be left alone for now.

---
 sys/cam/scsi/scsi_da.c | 20 ++------------------
 1 file changed, 2 insertions(+), 18 deletions(-)

diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c
index 0bf175adc82..8f643611c0c 100644
--- a/sys/cam/scsi/scsi_da.c
+++ b/sys/cam/scsi/scsi_da.c
@@ -958,8 +958,6 @@ dainit(void)
 static void
 daoninvalidate(struct cam_periph *periph)
 {
-	struct ccb_abort cab;
-	struct ccb_hdr *ccb_h, *ccb_h_t;
 	struct da_softc *softc;
 
 	softc = (struct da_softc *)periph->softc;
@@ -969,29 +967,15 @@ daoninvalidate(struct cam_periph *periph)
 	 */
 	xpt_register_async(0, daasync, periph, periph->path);
 
-	/*
-	 * Invalidate the pack label
-	 */
 	softc->flags |= DA_FLAG_PACK_INVALID;
 
 	/*
 	 * Return all queued I/O with ENXIO.
+	 * XXX Handle any transactions queued to the card
+	 *     with XPT_ABORT_CCB.
 	 */
 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
 
-	/*
-	 * Issue aborts for any pending commands.
-	 */
-	xpt_setup_ccb(&cab.ccb_h, periph->path, CAM_PRIORITY_NORMAL+1);
-	cab.ccb_h.func_code = XPT_ABORT;
-	LIST_FOREACH_SAFE(ccb_h, &softc->pending_ccbs, periph_links.le, ccb_h_t) {
-		cab.abort_ccb = (union ccb *)ccb_h;
-		xpt_action((union ccb *)&cab);
-	}
-
-	/*
-	 * This disk is *history*....
-	 */
 	disk_gone(softc->disk);
 	xpt_print(periph->path, "lost device\n");
 }

From 365ccde0fb7f2b0809adf0c6be9ad511baf1dc90 Mon Sep 17 00:00:00 2001
From: Hajimu UMEMOTO 
Date: Fri, 20 Aug 2010 17:52:49 +0000
Subject: [PATCH 0110/1624] optp may be NULL.

---
 sys/netinet6/raw_ip6.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/netinet6/raw_ip6.c b/sys/netinet6/raw_ip6.c
index 0e5e8e07e17..6c10fc5479b 100644
--- a/sys/netinet6/raw_ip6.c
+++ b/sys/netinet6/raw_ip6.c
@@ -434,7 +434,8 @@ rip6_output(m, va_alist)
 	 * XXX: we may still need to determine the zone later.
 	 */
 	if (!(so->so_state & SS_ISCONNECTED)) {
-		if (!optp->ip6po_pktinfo || !optp->ip6po_pktinfo->ipi6_ifindex)
+		if (!optp || !optp->ip6po_pktinfo ||
+		    !optp->ip6po_pktinfo->ipi6_ifindex)
 			use_defzone = V_ip6_use_defzone;
 		if (dstsock->sin6_scope_id == 0 && !use_defzone)
 			scope_ambiguous = 1;

From 3634d5b2413604cb139184e0c60647b3d4490b33 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Fri, 20 Aug 2010 19:46:50 +0000
Subject: [PATCH 0111/1624] Add dedicated routines to toggle lockmgr flags such
 as LK_NOSHARE and LK_CANRECURSE after a lock is created.  Use them to
 implement macros that otherwise manipulated the flags directly.  Assert that
 the associated lockmgr lock is exclusively locked by the current thread when
 manipulating these flags to ensure the flag updates are safe.  This last
 change required some minor shuffling in a few filesystems to exclusively lock
 a brand new vnode slightly earlier.

Reviewed by:	kib
MFC after:	3 days
---
 sys/fs/devfs/devfs_vnops.c                |  2 +-
 sys/fs/nfsclient/nfs_clnode.c             |  2 +-
 sys/fs/nfsclient/nfs_clport.c             |  2 +-
 sys/fs/nwfs/nwfs_node.c                   |  2 +-
 sys/fs/pseudofs/pseudofs_vncache.c        |  2 +-
 sys/fs/smbfs/smbfs_node.c                 |  2 +-
 sys/gnu/fs/xfs/FreeBSD/xfs_freebsd_iget.c |  2 +-
 sys/kern/kern_lock.c                      | 28 +++++++++++++++++++++++
 sys/kern/vfs_lookup.c                     |  7 +++---
 sys/nfsclient/nfs_node.c                  |  2 +-
 sys/sys/lockmgr.h                         |  3 +++
 sys/sys/vnode.h                           |  6 ++---
 sys/ufs/ffs/ffs_softdep.c                 |  4 ++--
 sys/ufs/ffs/ffs_vfsops.c                  |  2 +-
 14 files changed, 47 insertions(+), 19 deletions(-)

diff --git a/sys/fs/devfs/devfs_vnops.c b/sys/fs/devfs/devfs_vnops.c
index 0bcc0932c6a..abf1dfadd38 100644
--- a/sys/fs/devfs/devfs_vnops.c
+++ b/sys/fs/devfs/devfs_vnops.c
@@ -412,8 +412,8 @@ devfs_allocv(struct devfs_dirent *de, struct mount *mp, int lockmode,
 	} else {
 		vp->v_type = VBAD;
 	}
-	VN_LOCK_ASHARE(vp);
 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY | LK_NOWITNESS);
+	VN_LOCK_ASHARE(vp);
 	mtx_lock(&devfs_de_interlock);
 	vp->v_data = de;
 	de->de_vnode = vp;
diff --git a/sys/fs/nfsclient/nfs_clnode.c b/sys/fs/nfsclient/nfs_clnode.c
index e36431fa0ec..7d76be0daca 100644
--- a/sys/fs/nfsclient/nfs_clnode.c
+++ b/sys/fs/nfsclient/nfs_clnode.c
@@ -140,6 +140,7 @@ ncl_nget(struct mount *mntp, u_int8_t *fhp, int fhsize, struct nfsnode **npp)
 	/*
 	 * NFS supports recursive and shared locking.
 	 */
+	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
 	VN_LOCK_AREC(vp);
 	VN_LOCK_ASHARE(vp);
 	/* 
@@ -157,7 +158,6 @@ ncl_nget(struct mount *mntp, u_int8_t *fhp, int fhsize, struct nfsnode **npp)
 	    M_NFSFH, M_WAITOK);
 	bcopy(fhp, np->n_fhp->nfh_fh, fhsize);
 	np->n_fhp->nfh_len = fhsize;
-	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
 	error = insmntque(vp, mntp);
 	if (error != 0) {
 		*npp = NULL;
diff --git a/sys/fs/nfsclient/nfs_clport.c b/sys/fs/nfsclient/nfs_clport.c
index 4d610b42c38..595c90876cd 100644
--- a/sys/fs/nfsclient/nfs_clport.c
+++ b/sys/fs/nfsclient/nfs_clport.c
@@ -230,9 +230,9 @@ nfscl_nget(struct mount *mntp, struct vnode *dvp, struct nfsfh *nfhp,
 	/*
 	 * NFS supports recursive and shared locking.
 	 */
+	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
 	VN_LOCK_AREC(vp);
 	VN_LOCK_ASHARE(vp);
-	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
 	error = insmntque(vp, mntp);
 	if (error != 0) {
 		*npp = NULL;
diff --git a/sys/fs/nwfs/nwfs_node.c b/sys/fs/nwfs/nwfs_node.c
index fc9b41bd890..cf6f6d951b9 100644
--- a/sys/fs/nwfs/nwfs_node.c
+++ b/sys/fs/nwfs/nwfs_node.c
@@ -185,7 +185,6 @@ rescan:
 	if (dvp) {
 		np->n_parent = VTONW(dvp)->n_fid;
 	}
-	VN_LOCK_AREC(vp);
 	sx_xlock(&nwhashlock);
 	/*
 	 * Another process can create vnode while we blocked in malloc() or
@@ -202,6 +201,7 @@ rescan:
 	nhpp = NWNOHASH(fid);
 	LIST_INSERT_HEAD(nhpp, np, n_hash);
 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
+	VN_LOCK_AREC(vp);
 	sx_xunlock(&nwhashlock);
 	
 	ASSERT_VOP_LOCKED(dvp, "nwfs_allocvp");
diff --git a/sys/fs/pseudofs/pseudofs_vncache.c b/sys/fs/pseudofs/pseudofs_vncache.c
index 035f2c79dd7..19cc70d9a5a 100644
--- a/sys/fs/pseudofs/pseudofs_vncache.c
+++ b/sys/fs/pseudofs/pseudofs_vncache.c
@@ -189,8 +189,8 @@ retry:
 	if ((pn->pn_flags & PFS_PROCDEP) != 0)
 		(*vpp)->v_vflag |= VV_PROCDEP;
 	pvd->pvd_vnode = *vpp;
-	VN_LOCK_AREC(*vpp);
 	vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY);
+	VN_LOCK_AREC(*vpp);
 	error = insmntque(*vpp, mp);
 	if (error != 0) {
 		free(pvd, M_PFSVNCACHE);
diff --git a/sys/fs/smbfs/smbfs_node.c b/sys/fs/smbfs/smbfs_node.c
index a0543e28ffa..661579cf220 100644
--- a/sys/fs/smbfs/smbfs_node.c
+++ b/sys/fs/smbfs/smbfs_node.c
@@ -253,8 +253,8 @@ loop:
 	} else if (vp->v_type == VREG)
 		SMBERROR("new vnode '%s' born without parent ?\n", np->n_name);
 
-	VN_LOCK_AREC(vp);
 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
+	VN_LOCK_AREC(vp);
 
 	smbfs_hash_lock(smp);
 	LIST_FOREACH(np2, nhpp, n_hash) {
diff --git a/sys/gnu/fs/xfs/FreeBSD/xfs_freebsd_iget.c b/sys/gnu/fs/xfs/FreeBSD/xfs_freebsd_iget.c
index 49cfb5d51c1..e4e1e8d57a3 100644
--- a/sys/gnu/fs/xfs/FreeBSD/xfs_freebsd_iget.c
+++ b/sys/gnu/fs/xfs/FreeBSD/xfs_freebsd_iget.c
@@ -389,8 +389,8 @@ xfs_vn_allocate(xfs_mount_t *mp, xfs_inode_t *ip, struct xfs_vnode **vpp)
 		return (error);
 	}
 
-	VN_LOCK_AREC(vp);
 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
+	VN_LOCK_AREC(vp);
 	error = insmntque(vp, XVFSTOMNT(XFS_MTOVFS(mp)));
 	if (error != 0) {
 		kmem_free(vdata, sizeof(*vdata));
diff --git a/sys/kern/kern_lock.c b/sys/kern/kern_lock.c
index 18bbf9a46cf..c9829cdf5ca 100644
--- a/sys/kern/kern_lock.c
+++ b/sys/kern/kern_lock.c
@@ -396,6 +396,34 @@ lockinit(struct lock *lk, int pri, const char *wmesg, int timo, int flags)
 	STACK_ZERO(lk);
 }
 
+/*
+ * XXX: Gross hacks to manipulate external lock flags after
+ * initialization.  Used for certain vnode and buf locks.
+ */
+void
+lockallowshare(struct lock *lk)
+{
+
+	lockmgr_assert(lk, KA_XLOCKED);
+	lk->lock_object.lo_flags &= ~LK_NOSHARE;
+}
+
+void
+lockallowrecurse(struct lock *lk)
+{
+
+	lockmgr_assert(lk, KA_XLOCKED);
+	lk->lock_object.lo_flags |= LO_RECURSABLE;
+}
+
+void
+lockdisablerecurse(struct lock *lk)
+{
+
+	lockmgr_assert(lk, KA_XLOCKED);
+	lk->lock_object.lo_flags &= ~LO_RECURSABLE;
+}
+
 void
 lockdestroy(struct lock *lk)
 {
diff --git a/sys/kern/vfs_lookup.c b/sys/kern/vfs_lookup.c
index 5b6ccf6ff46..e0684b16bde 100644
--- a/sys/kern/vfs_lookup.c
+++ b/sys/kern/vfs_lookup.c
@@ -84,14 +84,13 @@ static struct vnode *vp_crossmp;
 static void
 nameiinit(void *dummy __unused)
 {
-	int error;
 
 	namei_zone = uma_zcreate("NAMEI", MAXPATHLEN, NULL, NULL, NULL, NULL,
 	    UMA_ALIGN_PTR, 0);
-	error = getnewvnode("crossmp", NULL, &dead_vnodeops, &vp_crossmp);
-	if (error != 0)
-		panic("nameiinit: getnewvnode");
+	getnewvnode("crossmp", NULL, &dead_vnodeops, &vp_crossmp);
+	vn_lock(vp_crossmp, LK_EXCLUSIVE);
 	VN_LOCK_ASHARE(vp_crossmp);
+	VOP_UNLOCK(vp_crossmp, 0);
 }
 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nameiinit, NULL);
 
diff --git a/sys/nfsclient/nfs_node.c b/sys/nfsclient/nfs_node.c
index 947beed8267..9e558f4aa7e 100644
--- a/sys/nfsclient/nfs_node.c
+++ b/sys/nfsclient/nfs_node.c
@@ -150,6 +150,7 @@ nfs_nget(struct mount *mntp, nfsfh_t *fhp, int fhsize, struct nfsnode **npp, int
 	/*
 	 * NFS supports recursive and shared locking.
 	 */
+	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
 	VN_LOCK_AREC(vp);
 	VN_LOCK_ASHARE(vp);
 	if (fhsize > NFS_SMALLFH) {
@@ -158,7 +159,6 @@ nfs_nget(struct mount *mntp, nfsfh_t *fhp, int fhsize, struct nfsnode **npp, int
 		np->n_fhp = &np->n_fh;
 	bcopy((caddr_t)fhp, (caddr_t)np->n_fhp, fhsize);
 	np->n_fhsize = fhsize;
-	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
 	error = insmntque(vp, mntp);
 	if (error != 0) {
 		*npp = NULL;
diff --git a/sys/sys/lockmgr.h b/sys/sys/lockmgr.h
index 545dfa26abd..4c3a272abde 100644
--- a/sys/sys/lockmgr.h
+++ b/sys/sys/lockmgr.h
@@ -73,7 +73,10 @@ void	 _lockmgr_assert(struct lock *lk, int what, const char *file, int line);
 #endif
 void	 _lockmgr_disown(struct lock *lk, const char *file, int line);
 
+void	 lockallowrecurse(struct lock *lk);
+void	 lockallowshare(struct lock *lk);
 void	 lockdestroy(struct lock *lk);
+void	 lockdisablerecurse(struct lock *lk);
 void	 lockinit(struct lock *lk, int prio, const char *wmesg, int timo,
 	    int flags);
 #ifdef DDB
diff --git a/sys/sys/vnode.h b/sys/sys/vnode.h
index c38d645462e..e82f8ea54d6 100644
--- a/sys/sys/vnode.h
+++ b/sys/sys/vnode.h
@@ -419,10 +419,8 @@ extern	struct vattr va_null;		/* predefined null vattr structure */
 #define	VI_UNLOCK(vp)	mtx_unlock(&(vp)->v_interlock)
 #define	VI_MTX(vp)	(&(vp)->v_interlock)
 
-#define	VN_LOCK_AREC(vp)						\
-	((vp)->v_vnlock->lock_object.lo_flags |= LO_RECURSABLE)
-#define	VN_LOCK_ASHARE(vp)						\
-	((vp)->v_vnlock->lock_object.lo_flags &= ~LK_NOSHARE)
+#define	VN_LOCK_AREC(vp)	lockallowrecurse((vp)->v_vnlock)
+#define	VN_LOCK_ASHARE(vp)	lockallowshare((vp)->v_vnlock)
 
 #endif /* _KERNEL */
 
diff --git a/sys/ufs/ffs/ffs_softdep.c b/sys/ufs/ffs/ffs_softdep.c
index 039e436463c..b666c0fcf78 100644
--- a/sys/ufs/ffs/ffs_softdep.c
+++ b/sys/ufs/ffs/ffs_softdep.c
@@ -904,8 +904,8 @@ MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
 #define ACQUIRE_LOCK(lk)		mtx_lock(lk)
 #define FREE_LOCK(lk)			mtx_unlock(lk)
 
-#define	BUF_AREC(bp)	((bp)->b_lock.lock_object.lo_flags |= LO_RECURSABLE)
-#define	BUF_NOREC(bp)	((bp)->b_lock.lock_object.lo_flags &= ~LO_RECURSABLE)
+#define	BUF_AREC(bp)			lockallowrecurse(&(bp)->b_lock)
+#define	BUF_NOREC(bp)			lockdisablerecurse(&(bp)->b_lock)
 
 /*
  * Worklist queue management.
diff --git a/sys/ufs/ffs/ffs_vfsops.c b/sys/ufs/ffs/ffs_vfsops.c
index c099732398f..ccf346debd2 100644
--- a/sys/ufs/ffs/ffs_vfsops.c
+++ b/sys/ufs/ffs/ffs_vfsops.c
@@ -1501,6 +1501,7 @@ ffs_vgetf(mp, ino, flags, vpp, ffs_flags)
 	/*
 	 * FFS supports recursive locking.
 	 */
+	lockmgr(vp->v_vnlock, LK_EXCLUSIVE, NULL);
 	VN_LOCK_AREC(vp);
 	vp->v_data = ip;
 	vp->v_bufobj.bo_bsize = fs->fs_bsize;
@@ -1518,7 +1519,6 @@ ffs_vgetf(mp, ino, flags, vpp, ffs_flags)
 	}
 #endif
 
-	lockmgr(vp->v_vnlock, LK_EXCLUSIVE, NULL);
 	if (ffs_flags & FFSV_FORCEINSMQ)
 		vp->v_vflag |= VV_FORCEINSMQ;
 	error = insmntque(vp, mp);

From b27487040530059a4c955fdad0562e8db585eafd Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 20 Aug 2010 23:51:34 +0000
Subject: [PATCH 0112/1624] make sure thread lock is locked.

---
 sys/kern/subr_sleepqueue.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/kern/subr_sleepqueue.c b/sys/kern/subr_sleepqueue.c
index 0d2c65e57e5..cc207998d52 100644
--- a/sys/kern/subr_sleepqueue.c
+++ b/sys/kern/subr_sleepqueue.c
@@ -411,6 +411,7 @@ sleepq_catch_signals(void *wchan, int pri)
 	if ((td->td_pflags & TDP_WAKEUP) != 0) {
 		td->td_pflags &= ~TDP_WAKEUP;
 		ret = EINTR;
+		thread_lock(td);
 		goto out;
 	}
 

From 28be8b2ba9617bf9d1f2b85ea0f497f737ed7726 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 10:31:26 +0000
Subject: [PATCH 0113/1624] Revert part of r211505. Some of the removed casts
 are actually safe so put them back in again. Also, clang only complained
 about the lvalue cast.

Submitted by:	Dimitry Andric 
Pointed out:	bde
---
 contrib/gcc/longlong.h | 32 ++++++++++++++++----------------
 1 file changed, 16 insertions(+), 16 deletions(-)

diff --git a/contrib/gcc/longlong.h b/contrib/gcc/longlong.h
index 8805d91b2c4..a789d1673f7 100644
--- a/contrib/gcc/longlong.h
+++ b/contrib/gcc/longlong.h
@@ -314,38 +314,38 @@ UDItype __umulsidi3 (USItype, USItype);
 #if (defined (__i386__) || defined (__i486__)) && W_TYPE_SIZE == 32
 #define add_ssaaaa(sh, sl, ah, al, bh, bl) \
   __asm__ ("addl %5,%1\n\tadcl %3,%0"					\
-	   : "=r" (sh),							\
-	     "=&r" (sl)							\
-	   : "%0" (ah),							\
-	     "g" (bh),							\
-	     "%1" (al),							\
-	     "g" (bl))
+	   : "=r" ((USItype) (sh)),					\
+	     "=&r" ((USItype) (sl))					\
+	   : "%0" ((USItype) (ah)),					\
+	     "g" ((USItype) (bh)),					\
+	     "%1" ((USItype) (al)),					\
+	     "g" ((USItype) (bl)))
 #define sub_ddmmss(sh, sl, ah, al, bh, bl) \
   __asm__ ("subl %5,%1\n\tsbbl %3,%0"					\
 	   : "=r" (sh),							\
 	     "=&r" (sl)							\
-	   : "0" (ah),							\
-	     "g" (bh),							\
-	     "1" (al),							\
-	     "g" (bl))
+	   : "0" ((USItype) (ah)),					\
+	     "g" ((USItype) (bh)),					\
+	     "1" ((USItype) (al)),					\
+	     "g" ((USItype) (bl)))
 #define umul_ppmm(w1, w0, u, v) \
   __asm__ ("mull %3"							\
 	   : "=a" (w0),							\
 	     "=d" (w1)							\
-	   : "%0" (u),							\
-	     "rm" (v))
+	   : "%0" ((USItype) (u)),					\
+	     "rm" ((USItype) (v)))
 #define udiv_qrnnd(q, r, n1, n0, dv) \
   __asm__ ("divl %4"							\
 	   : "=a" (q),							\
 	     "=d" (r)							\
-	   : "0" (n0),							\
-	     "1" (n1),							\
-	     "rm" (dv))
+	   : "0" ((USItype) (n0)),					\
+	     "1" ((USItype) (n1)),					\
+	     "rm" ((USItype) (dv)))
 #define count_leading_zeros(count, x) \
   do {									\
     USItype __cbtmp;							\
     __asm__ ("bsrl %1,%0"						\
-	     : "=r" (__cbtmp) : "rm" (x));				\
+	     : "=r" (__cbtmp) : "rm" ((USItype) (x)));			\
     (count) = __cbtmp ^ 31;						\
   } while (0)
 #define count_trailing_zeros(count, x) \

From 9329096b802dbf6ea79757e60813c588ac6503d4 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 10:40:12 +0000
Subject: [PATCH 0114/1624] Install a PIC libelf. This will be needed by the
 DTrace runtime instrumentation object (dtri.o).

Sponsored by:	The FreeBSD Foundation
---
 lib/libelf/Makefile | 1 +
 1 file changed, 1 insertion(+)

diff --git a/lib/libelf/Makefile b/lib/libelf/Makefile
index fc70d9d865c..4e51de0cc61 100644
--- a/lib/libelf/Makefile
+++ b/lib/libelf/Makefile
@@ -55,6 +55,7 @@ SRCS=	elf_begin.c						\
 	${GENSRCS}
 INCS=	libelf.h gelf.h
 
+INSTALL_PIC_ARCHIVE=yes
 GENSRCS=	libelf_fsize.c libelf_msize.c libelf_convert.c
 CLEANFILES=	${GENSRCS}
 CFLAGS+=	-I. -I${.CURDIR}

From b2db760808f74bb53c232900091c9da801ebbfcc Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 11:04:38 +0000
Subject: [PATCH 0115/1624] Port most of the DTrace tests to FreeBSD.

Sponsored by:	The FreeBSD Foundation
---
 .../cmd/dtrace/test/cmd/scripts/dtest.pl      |  2 +-
 .../dtrace/test/tst/common/aggs/tst.subr.d    |  1 -
 .../tst/common/assocs/tst.orthogonality.d     |  4 +-
 .../common/dtraceUtil/tst.AddSearchPath.d.ksh |  2 +-
 .../dtraceUtil/tst.DestructWithModule.d.ksh   |  2 +-
 .../dtraceUtil/tst.ELFGenerationOut.d.ksh     |  2 +-
 .../dtraceUtil/tst.ELFGenerationWithO.d.ksh   |  2 +-
 .../tst.PreprocessorStatement.d.ksh           |  1 -
 .../common/funcs/err.D_PROTO_LEN.motoofew.d   |  2 +-
 .../common/funcs/err.D_PROTO_LEN.motoomany.d  |  2 +-
 .../common/funcs/err.D_PROTO_LEN.mtatoofew.d  |  2 +-
 .../common/funcs/err.D_PROTO_LEN.mtatoomany.d |  2 +-
 .../dtrace/test/tst/common/funcs/tst.index.d  |  2 +-
 .../test/tst/common/ip/get.ipv4remote.pl      |  4 +-
 .../test/tst/common/ip/get.ipv6remote.pl      |  4 +-
 .../test/tst/common/ip/tst.ipv4localicmp.ksh  |  2 +-
 .../test/tst/common/ip/tst.ipv4localtcp.ksh   |  2 +-
 .../test/tst/common/ip/tst.ipv4localudp.ksh   |  2 +-
 .../test/tst/common/ip/tst.ipv4remoteicmp.ksh |  2 +-
 .../test/tst/common/ip/tst.ipv4remotetcp.ksh  |  2 +-
 .../test/tst/common/ip/tst.ipv4remoteudp.ksh  |  2 +-
 .../test/tst/common/ip/tst.ipv6localicmp.ksh  |  2 +-
 .../test/tst/common/ip/tst.ipv6remoteicmp.ksh |  4 +-
 .../test/tst/common/ip/tst.localtcpstate.ksh  |  2 +-
 .../test/tst/common/ip/tst.remotetcpstate.ksh |  2 +-
 .../test/tst/common/misc/tst.include.ksh      |  2 +-
 .../test/tst/common/misc/tst.schrock.ksh      |  2 +-
 .../cmd/dtrace/test/tst/common/pid/tst.fork.c |  2 +-
 .../cmd/dtrace/test/tst/common/pid/tst.gcc.c  |  3 +-
 .../test/tst/common/pid/tst.provregex1.ksh    |  2 +-
 .../test/tst/common/pid/tst.provregex2.ksh    |  2 +-
 .../test/tst/common/pid/tst.provregex3.ksh    |  2 +-
 .../test/tst/common/pid/tst.provregex4.ksh    |  2 +-
 .../tst/common/printa/tst.largeusersym.ksh    |  2 +-
 .../tst/common/printa/tst.walltimestamp.ksh   |  2 +-
 .../test/tst/common/printf/tst.printT.ksh     |  2 +-
 .../test/tst/common/printf/tst.printY.ksh     |  2 +-
 .../dtrace/test/tst/common/printf/tst.sym.d   |  2 +-
 .../test/tst/common/printf/tst.sym.d.out      |  2 +-
 .../dtrace/test/tst/common/proc/tst.exec.ksh  |  2 +-
 .../tst/common/proc/tst.execfail.ENOENT.ksh   |  2 +-
 .../test/tst/common/proc/tst.execfail.ksh     |  2 +-
 .../dtrace/test/tst/common/proc/tst.sigwait.d |  4 +-
 .../scripting/tst.D_MACRO_UNUSED.overflow.ksh |  6 +--
 .../tst/common/scripting/tst.arguments.ksh    |  4 +-
 .../test/tst/common/scripting/tst.egid.ksh    |  8 ++--
 .../test/tst/common/scripting/tst.euid.ksh    |  2 +-
 .../test/tst/common/scripting/tst.gid.ksh     |  2 +-
 .../test/tst/common/scripting/tst.ppid.ksh    |  2 +-
 .../test/tst/common/scripting/tst.projid.ksh  |  2 +-
 .../test/tst/common/scripting/tst.sid.ksh     |  2 +-
 .../tst/common/scripting/tst.stringmacro.ksh  |  2 +-
 .../test/tst/common/scripting/tst.taskid.ksh  |  2 +-
 .../test/tst/common/scripting/tst.uid.ksh     |  2 +-
 .../dtrace/test/tst/common/sdt/tst.sdtargs.c  |  6 +++
 .../cmd/dtrace/test/tst/common/usdt/Makefile  | 13 ++++++
 .../cmd/dtrace/test/tst/common/usdt/main.c    | 11 +++++
 .../cmd/dtrace/test/tst/common/usdt/prov.d    |  3 ++
 .../cmd/dtrace/test/tst/common/usdt/prov.h    | 46 +++++++++++++++++++
 .../test/tst/common/usdt/tst.badguess.ksh     |  2 +-
 .../test/tst/common/usdt/tst.dlclose1.ksh     |  4 +-
 .../test/tst/common/usdt/tst.dlclose2.ksh     |  4 +-
 .../test/tst/common/usdt/tst.dlclose3.ksh     |  4 +-
 .../test/tst/common/usdt/tst.eliminate.ksh    |  2 +-
 .../test/tst/common/usdt/tst.enabled.ksh      |  2 +-
 .../test/tst/common/usdt/tst.enabled2.ksh     |  2 +-
 .../test/tst/common/usdt/tst.entryreturn.ksh  |  2 +-
 .../dtrace/test/tst/common/usdt/tst.fork.ksh  |  2 +-
 .../test/tst/common/usdt/tst.guess32.ksh      |  2 +-
 .../test/tst/common/usdt/tst.guess64.ksh      |  2 +-
 .../test/tst/common/usdt/tst.header.ksh       |  2 +-
 .../test/tst/common/usdt/tst.include.ksh      |  2 +-
 .../test/tst/common/usdt/tst.linkpriv.ksh     |  2 +-
 .../test/tst/common/usdt/tst.linkunpriv.ksh   |  2 +-
 .../test/tst/common/usdt/tst.multiple.ksh     |  2 +-
 .../test/tst/common/usdt/tst.nodtrace.ksh     |  2 +-
 .../test/tst/common/usdt/tst.onlyenabled.ksh  |  2 +-
 .../test/tst/common/usdt/tst.reeval.ksh       |  2 +-
 .../test/tst/common/usdt/tst.static.ksh       |  2 +-
 .../test/tst/common/usdt/tst.static2.ksh      |  2 +-
 .../dtrace/test/tst/common/usdt/tst.user.ksh  |  2 +-
 .../test/tst/common/vars/tst.ucaller.ksh      |  2 +-
 .../test/tst/sparc/usdt/tst.tailcall.ksh      |  4 +-
 83 files changed, 171 insertions(+), 93 deletions(-)
 create mode 100644 cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/Makefile
 create mode 100644 cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/main.c
 create mode 100644 cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.d
 create mode 100644 cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.h

diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/cmd/scripts/dtest.pl b/cddl/contrib/opensolaris/cmd/dtrace/test/cmd/scripts/dtest.pl
index 3ccea744264..7b47580ddf6 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/cmd/scripts/dtest.pl
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/cmd/scripts/dtest.pl
@@ -43,7 +43,7 @@ $USAGE = "Usage: $PNAME [-abfghjlnqs] [-d dir] [-i isa] "
 
 @dtrace_argv = ();
 
-$ksh_path = '/bin/sh';
+$ksh_path = '/usr/local/bin/ksh';
 
 @files = ();
 %exceptions = ();
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/aggs/tst.subr.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/aggs/tst.subr.d
index 5ca1f1ef938..d508596a97f 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/aggs/tst.subr.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/aggs/tst.subr.d
@@ -26,7 +26,6 @@
 
 #pragma ident	"%Z%%M%	%I%	%E% SMI"
 
-#include 
 
 #define INTFUNC(x)			\
 	BEGIN				\
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/assocs/tst.orthogonality.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/assocs/tst.orthogonality.d
index f474a572098..3a7d6a2c641 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/assocs/tst.orthogonality.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/assocs/tst.orthogonality.d
@@ -39,13 +39,13 @@ BEGIN
 }
 
 BEGIN
-/b[curthread->t_did] == 0/
+/b[curthread->td_flags] == 0/
 {
 	exit(0);
 }
 
 BEGIN
 {
-	printf("value should be 0; value is %x!", b[curthread->t_did]);
+	printf("value should be 0; value is %x!", b[curthread->td_flags]);
 	exit(1);
 }
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.AddSearchPath.d.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.AddSearchPath.d.ksh
index 2f49f733e3e..b36f1e4c181 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.AddSearchPath.d.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.AddSearchPath.d.ksh
@@ -78,5 +78,5 @@ if [ "$status" -ne 0 ]; then
 	exit $status
 fi
 
-/usr/bin/rm -f $tempfile
+/bin/rm -f $tempfile
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.DestructWithModule.d.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.DestructWithModule.d.ksh
index 923be51c699..8ab32fdb40e 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.DestructWithModule.d.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.DestructWithModule.d.ksh
@@ -44,7 +44,7 @@ fi
 
 dtrace=$1
 
-$dtrace -qwm unix'{chill(15); printf("Done chilling"); exit(0);}'
+$dtrace -qwm kernel'{chill(15); printf("Done chilling"); exit(0);}'
 status=$?
 
 if [ "$status" -ne 0 ]; then
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationOut.d.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationOut.d.ksh
index b68fc138749..a4f4670c02c 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationOut.d.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationOut.d.ksh
@@ -69,5 +69,5 @@ if [ ! -a "d.out" ]; then
 	exit 1
 fi
 
-/usr/bin/rm -f "d.out"
+/bin/rm -f "d.out"
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationWithO.d.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationWithO.d.ksh
index ec38b50285f..503dd50e089 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationWithO.d.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.ELFGenerationWithO.d.ksh
@@ -70,5 +70,5 @@ if [ ! -a "outputFile" ]; then
 	exit 1
 fi
 
-/usr/bin/rm -f "outputFile"
+/bin/rm -f "outputFile"
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.PreprocessorStatement.d.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.PreprocessorStatement.d.ksh
index 182466f4f8b..e4d093e4fc2 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.PreprocessorStatement.d.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/dtraceUtil/tst.PreprocessorStatement.d.ksh
@@ -43,7 +43,6 @@ script()
 {
 	$dtrace -CH -s /dev/stdin <
 
 	BEGIN
 	{
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoofew.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoofew.d
index e878713abb2..cf4dd5e0e55 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoofew.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoofew.d
@@ -34,7 +34,7 @@
  *
  */
 
-lockstat:genunix:mutex_enter:adaptive-acquire
+lockstat:kernel:mtx_lock:adaptive-acquire
 {
 	mutex_owned();
 	exit(1);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoomany.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoomany.d
index d3b9ed486eb..6cc4be03fa3 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoomany.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.motoomany.d
@@ -34,7 +34,7 @@
  *
  */
 
-lockstat:genunix:mutex_enter:adaptive-acquire
+lockstat:kernel:mtx_lock:adaptive-acquire
 {
 	mutex_owned((kmutex_t *)arg0, 99);
 	exit(1);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoofew.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoofew.d
index 98bc5c9313d..61d967a5b47 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoofew.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoofew.d
@@ -36,7 +36,7 @@
  */
 
 
-lockstat:genunix:mutex_enter:adaptive-acquire
+lockstat:kernel:mtx_lock:adaptive-acquire
 {
 	mutex_type_adaptive();
 	exit(1);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoomany.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoomany.d
index e4f259a7e78..f2c3178e31c 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoomany.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/err.D_PROTO_LEN.mtatoomany.d
@@ -35,7 +35,7 @@
  */
 
 
-lockstat:genunix:mutex_enter:adaptive-acquire
+lockstat:kernel:mtx_lock:adaptive-acquire
 {
 	mutex_type_adaptive((kmutex_t *)arg0, 99);
 	exit(1);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/tst.index.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/tst.index.d
index 547730a14ea..1ec96978ab1 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/tst.index.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/funcs/tst.index.d
@@ -80,7 +80,7 @@ BEGIN
 	i++;
 
 	end = j = k = 0;
-	printf("#!/usr/perl5/bin/perl\n\nBEGIN {\n");
+	printf("#!/usr/bin/perl\n\nBEGIN {\n");
 }
 
 tick-1ms
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv4remote.pl b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv4remote.pl
index fb41255473e..128263eaec2 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv4remote.pl
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv4remote.pl
@@ -50,7 +50,7 @@ my $local = "";
 my $remote = "";
 my %Broadcast;
 my $up;
-open IFCONFIG, '/usr/sbin/ifconfig -a |' or die "Couldn't run ifconfig: $!\n";
+open IFCONFIG, '/sbin/ifconfig -a |' or die "Couldn't run ifconfig: $!\n";
 while () {
 	next if /^lo/;
 
@@ -73,7 +73,7 @@ die "Could not determine local IP address" if $local eq "";
 # Find the first remote host that responds to an icmp echo,
 # which isn't a local address.
 #
-open PING, "/usr/sbin/ping -ns $Broadcast{$local} 56 $MAXHOSTS |" or
+open PING, "/sbin/ping -ns $Broadcast{$local} 56 $MAXHOSTS |" or
     die "Couldn't run ping: $!\n";
 while () {
 	if (/bytes from (.*): / and not defined $Broadcast{$1}) {
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv6remote.pl b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv6remote.pl
index 051ab8c3c32..837ca3c799d 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv6remote.pl
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv6remote.pl
@@ -50,7 +50,7 @@ my $local = "";
 my $remote = "";
 my %Local;
 my $up;
-open IFCONFIG, '/usr/sbin/ifconfig -a inet6 |'
+open IFCONFIG, '/sbin/ifconfig -a inet6 |'
     or die "Couldn't run ifconfig: $!\n";
 while () {
 	next if /^lo/;
@@ -74,7 +74,7 @@ exit 1 if $local eq "";
 # Find the first remote host that responds to an icmp echo,
 # which isn't a local address.
 #
-open PING, "/usr/sbin/ping -ns -A inet6 $MULTICAST 56 $MAXHOSTS |" or
+open PING, "/sbin/ping -ns -A inet6 $MULTICAST 56 $MAXHOSTS |" or
     die "Couldn't run ping: $!\n";
 while () {
 	if (/bytes from (.*): / and not defined $Local{$1}) {
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localicmp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localicmp.ksh
index 0965040e62e..0f2b64a2d90 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localicmp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localicmp.ksh
@@ -45,7 +45,7 @@ fi
 dtrace=$1
 local=127.0.0.1
 
-$dtrace -c "/usr/sbin/ping $local 3" -qs /dev/stdin <ip_saddr == "$local" && args[2]->ip_daddr == "$local" &&
     args[4]->ipv4_protocol == IPPROTO_ICMP/
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localtcp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localtcp.ksh
index 6fa8c35bf3b..c18dc7625d8 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localtcp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localtcp.ksh
@@ -120,6 +120,6 @@ EODTRACE
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localudp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localudp.ksh
index fa8f7acfc7a..6d08e24a9fb 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localudp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4localudp.ksh
@@ -57,7 +57,7 @@ fi
 dtrace=$1
 local=127.0.0.1
 
-$dtrace -c "/usr/sbin/ping -U $local" -qs /dev/stdin <ip_saddr == "$source" && args[2]->ip_daddr == "$dest" &&
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remotetcp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remotetcp.ksh
index 89a0cdb95ee..e513ace0be6 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remotetcp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remotetcp.ksh
@@ -123,6 +123,6 @@ EODTRACE
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $?
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remoteudp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remoteudp.ksh
index b0893c81614..cc7a32c556b 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remoteudp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv4remoteudp.ksh
@@ -60,7 +60,7 @@ if (( $? != 0 )); then
 	exit 4
 fi
 
-$dtrace -c "/usr/sbin/ping -U $dest" -qs /dev/stdin <ip_saddr == "$local" && args[2]->ip_daddr == "$local" &&
     args[5]->ipv6_nexthdr == IPPROTO_ICMPV6/
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv6remoteicmp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv6remoteicmp.ksh
index b94b7843975..c859e6bfe44 100755
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv6remoteicmp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.ipv6remoteicmp.ksh
@@ -62,9 +62,9 @@ fi
 #
 # Shake loose any ICMPv6 Neighbor advertisement messages before tracing.
 #
-/usr/sbin/ping $dest 3 > /dev/null 2>&1
+/sbin/ping $dest 3 > /dev/null 2>&1
 
-$dtrace -c "/usr/sbin/ping $dest 3" -qs /dev/stdin <ip_saddr == "$source" && args[2]->ip_daddr == "$dest" &&
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.localtcpstate.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.localtcpstate.ksh
index 8a65ce6f8d6..5e0c7474065 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.localtcpstate.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.localtcpstate.ksh
@@ -177,6 +177,6 @@ EODTRACE
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.remotetcpstate.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.remotetcpstate.ksh
index b6b9545d4e2..4bf4362b61d 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.remotetcpstate.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/tst.remotetcpstate.ksh
@@ -167,6 +167,6 @@ EODTRACE
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.include.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.include.ksh
index ec328021b3a..30a2ce4175b 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.include.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.include.ksh
@@ -31,7 +31,7 @@ if [ $# != 1 ]; then
 fi
 
 dtrace=$1
-CC=/usr/sfw/bin/gcc
+CC=/usr/bin/gcc
 CFLAGS=
 
 doit()
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.schrock.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.schrock.ksh
index 494f6f8e660..197bd8dd5f3 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.schrock.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/misc/tst.schrock.ksh
@@ -39,7 +39,7 @@ dtrace=$1
 # LD_NOEXEC_64 variable prevents nm from re-execing itself.
 #
 LD_NOEXEC_64=tomeeisrad $dtrace -F -s /dev/stdin -c \
-    '/usr/ccs/bin/nm /bin/ls' stat <
 #include 
+#include 
 
 void
 go(void)
 {
 	pid_t pid;
 
-	(void) posix_spawn(&pid, "/usr/bin/ls", NULL, NULL, NULL, NULL);
+	(void) posix_spawn(&pid, "/bin/ls", NULL, NULL, NULL, NULL);
 
 	(void) waitpid(pid, NULL, 0);
 }
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex1.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex1.ksh
index 892ff3e24df..7b0824eedd7 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex1.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex1.ksh
@@ -88,6 +88,6 @@ script
 status=$?
 
 cd /tmp
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex2.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex2.ksh
index 8d83bddd231..8951cb381f8 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex2.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex2.ksh
@@ -126,6 +126,6 @@ script
 status=$?
 
 cd /tmp
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex3.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex3.ksh
index c9ac6b1dd6a..49e362b33b2 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex3.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex3.ksh
@@ -97,6 +97,6 @@ script
 status=$?
 
 cd /tmp
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex4.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex4.ksh
index 278ec128131..865b9bbee5f 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex4.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/pid/tst.provregex4.ksh
@@ -149,6 +149,6 @@ script
 status=$?
 
 cd /tmp
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.largeusersym.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.largeusersym.ksh
index ed375fdbf9b..7d8bd39af74 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.largeusersym.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.largeusersym.ksh
@@ -78,6 +78,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.walltimestamp.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.walltimestamp.ksh
index bb0d5a0f6a6..69bf46b5383 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.walltimestamp.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/printa/tst.walltimestamp.ksh
@@ -33,7 +33,7 @@ fi
 dtrace=$1
 
 # The output files assumes the timezone is US/Pacific
-TZ=US/Pacific
+export TZ=America/Los_Angeles
 
 $dtrace -s /dev/stdin <exec = 1;
 	}
 
-	proc:::exec_success
+	proc:::exec-success
 	/self->exec/
 	{
 		exit(0);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ENOENT.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ENOENT.ksh
index 5dbce13e0c5..995eb056255 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ENOENT.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ENOENT.ksh
@@ -42,7 +42,7 @@ script()
 		self->exec = 1;
 	}
 
-	proc:::exec_failure
+	proc:::exec-failure
 	/self->exec && args[0] == ENOENT/
 	{
 		exit(0);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ksh
index 3b2dbb39a73..7fb3faaedc1 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.execfail.ksh
@@ -45,7 +45,7 @@ script()
 		self->exec = 1;
 	}
 
-	proc:::exec_failure
+	proc:::exec-failure
 	/self->exec/
 	{
 		exit(0);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.sigwait.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.sigwait.d
index fd6baffdc27..bb8281902e2 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.sigwait.d
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/proc/tst.sigwait.d
@@ -28,13 +28,13 @@
 
 #pragma D option destructive
 
-proc:::signal_send
+proc:::signal-send
 /args[1]->p_pid == $1 && args[2] == SIGUSR1/
 {
 	sent = 1;
 }
 
-proc:::signal_clear
+proc:::signal-clear
 /pid == $1 && args[0] == SIGUSR1 && sent/
 {
 	exit(0);
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.D_MACRO_UNUSED.overflow.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.D_MACRO_UNUSED.overflow.ksh
index 0f4e1455223..cc1e6dd9f74 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.D_MACRO_UNUSED.overflow.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.D_MACRO_UNUSED.overflow.ksh
@@ -70,11 +70,11 @@ fi
 grep "D_MACRO_UNUSED" /var/tmp/err.$$.txt >/dev/null 2>&1
 if [ $? -ne 0 ]; then
 	print -u2 "Expected error D_MACRO_UNUSED not returned"
-	/usr/bin/rm -f /var/tmp/err.$$.txt
+	/bin/rm -f /var/tmp/err.$$.txt
 	exit 1
 fi
 
-/usr/bin/rm -f $dfilename
-/usr/bin/rm -f /var/tmp/err.$$.txt
+/bin/rm -f $dfilename
+/bin/rm -f /var/tmp/err.$$.txt
 
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.arguments.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.arguments.ksh
index deb644a5013..6ec078abf29 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.arguments.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.arguments.ksh
@@ -42,7 +42,7 @@ fi
 
 dtrace=$1
 
-bname=`/bin/basename $0`
+bname=`/usr/bin/basename $0`
 
 dfilename=/var/tmp/$bname.$$
 
@@ -85,6 +85,6 @@ if [[ ${outarray[0]} != 1 || ${outarray[1]} != 2 || ${outarray[2]} != 3 || \
 	exit 1
 fi
 
-/usr/bin/rm -f $dfilename
+/bin/rm -f $dfilename
 exit 0
 
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.egid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.egid.ksh
index 9e1955f2980..afee24f83b7 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.egid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.egid.ksh
@@ -43,7 +43,7 @@ if [ $# != 1 ]; then
 fi
 
 dtrace=$1
-bname=`/bin/basename $0`
+bname=`/usr/bin/basename $0`
 dfilename=/var/tmp/$bname.$$.d
 
 ## Create .d file
@@ -70,14 +70,14 @@ EOF
 #chmod 555 the .d file
 
 chmod 555 $dfilename >/dev/null 2>&1
-if [ &? -ne 0 ]; then
+if [ $? -ne 0 ]; then
 	print -u2 "chmod $dfilename failed"
 	exit 1
 fi
 
 #Get the groupid of the calling process using ps
 
-groupid=`ps -o pid,gid | grep "$$ " | awk '{print $2}' 2>/dev/null`
+groupid=`ps -o pid,pgid | grep "$$ " | awk '{print $2}' 2>/dev/null`
 if [ $? -ne 0 ]; then
 	print -u2 "unable to get uid of the current process with pid = $$"
 	exit 1
@@ -93,5 +93,5 @@ fi
 
 #Cleanup leftovers
 
-/usr/bin/rm -f $dfilename
+/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.euid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.euid.ksh
index 7112b257817..1b6b9b3e0d3 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.euid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.euid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.gid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.gid.ksh
index 83955db1479..332b8e70d27 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.gid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.gid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.ppid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.ppid.ksh
index 4a74ee42819..bbd9a536479 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.ppid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.ppid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.projid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.projid.ksh
index da60ea1d61d..62bc817af5f 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.projid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.projid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.sid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.sid.ksh
index d1e122c1333..477ebc0290a 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.sid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.sid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.stringmacro.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.stringmacro.ksh
index 6903cb1cd99..724bd5fda7f 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.stringmacro.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.stringmacro.ksh
@@ -74,5 +74,5 @@ if [ "$output" != "this is test" ]; then
 	exit 1
 fi
 
-/usr/bin/rm -f $dfilename
+/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.taskid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.taskid.ksh
index 54392d23d73..88b450d381f 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.taskid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.taskid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.uid.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.uid.ksh
index 2630f2f945f..fabf0eda743 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.uid.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/scripting/tst.uid.ksh
@@ -82,5 +82,5 @@ if [ $? -ne 0 ]; then
 	exit 1
 fi
 
-#/usr/bin/rm -f $dfilename
+#/bin/rm -f $dfilename
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/sdt/tst.sdtargs.c b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/sdt/tst.sdtargs.c
index 07635502a9d..e2e9505fb59 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/sdt/tst.sdtargs.c
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/sdt/tst.sdtargs.c
@@ -27,11 +27,16 @@
 #pragma ident	"%Z%%M%	%I%	%E% SMI"
 
 #include 
+#ifndef __FreeBSD__
 #include 
+#endif
 
 int
 main(int argc, char **argv)
 {
+#ifdef __FreeBSD__
+	return (1);
+#else
 	while (1) {
 		if (uadmin(A_SDTTEST, 0, 0) < 0) {
 			perror("uadmin");
@@ -42,4 +47,5 @@ main(int argc, char **argv)
 	}
 
 	return (0);
+#endif
 }
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/Makefile b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/Makefile
new file mode 100644
index 00000000000..77fe870aa91
--- /dev/null
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/Makefile
@@ -0,0 +1,13 @@
+all: main
+
+main: main.o prov.o
+	$(CC) -o main main.o prov.o
+
+main.o: main.c prov.h
+	$(CC) -c main.c
+
+prov.h: prov.d
+	/usr/sbin/dtrace -h -s prov.d
+
+prov.o: prov.d main.o
+	/usr/sbin/dtrace -G -32 -s prov.d main.o
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/main.c b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/main.c
new file mode 100644
index 00000000000..9dc0a0e63be
--- /dev/null
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/main.c
@@ -0,0 +1,11 @@
+#include 
+#include 
+#include "prov.h"
+
+int
+main(int argc, char **argv, char **envp)
+{
+	envp[0] = (char*)0xff;
+	TESTER_ENTRY();
+	return 0;
+}
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.d b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.d
new file mode 100644
index 00000000000..53e5ef3988d
--- /dev/null
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.d
@@ -0,0 +1,3 @@
+provider tester {
+	probe entry();
+};
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.h b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.h
new file mode 100644
index 00000000000..e29654edb67
--- /dev/null
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/prov.h
@@ -0,0 +1,46 @@
+/*
+ * Generated by dtrace(1M).
+ */
+
+#ifndef	_PROV_H
+#define	_PROV_H
+
+#include 
+
+#ifdef	__cplusplus
+extern "C" {
+#endif
+
+#if _DTRACE_VERSION
+
+#define	TESTER_ENTRY() \
+	__dtrace_tester___entry()
+#ifndef	__sparc
+#define	TESTER_ENTRY_ENABLED() \
+	__dtraceenabled_tester___entry()
+#else
+#define	TESTER_ENTRY_ENABLED() \
+	__dtraceenabled_tester___entry(0)
+#endif
+
+
+extern void __dtrace_tester___entry(void);
+#ifndef	__sparc
+extern int __dtraceenabled_tester___entry(void);
+#else
+extern int __dtraceenabled_tester___entry(long);
+#endif
+
+#else
+
+#define	TESTER_ENTRY()
+#define	TESTER_ENTRY_ENABLED() (0)
+
+#endif
+
+
+#ifdef	__cplusplus
+}
+#endif
+
+#endif	/* _PROV_H */
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.badguess.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.badguess.ksh
index 291fe83fac2..91b6cf06f10 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.badguess.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.badguess.ksh
@@ -79,6 +79,6 @@ if [ $? -eq 0 ]; then
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose1.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose1.ksh
index 0a6666628fd..1c155febb5a 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose1.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose1.ksh
@@ -125,7 +125,7 @@ main(int argc, char **argv)
 }
 EOF
 
-/usr/ccs/bin/make > /dev/null
+/usr/bin/make > /dev/null
 if [ $? -ne 0 ]; then
 	print -u2 "failed to build"
 	exit 1
@@ -154,6 +154,6 @@ script 2>&1
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose2.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose2.ksh
index c83d8bfa861..107707ede32 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose2.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose2.ksh
@@ -136,7 +136,7 @@ main(int argc, char **argv)
 }
 EOF
 
-/usr/ccs/bin/make > /dev/null
+/usr/bin/make > /dev/null
 if [ $? -ne 0 ]; then
 	print -u2 "failed to build"
 	exit 1
@@ -155,6 +155,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose3.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose3.ksh
index 72f24ce5e30..a750b59e14e 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose3.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.dlclose3.ksh
@@ -131,7 +131,7 @@ main(int argc, char **argv)
 }
 EOF
 
-/usr/ccs/bin/make > /dev/null
+/usr/bin/make > /dev/null
 if [ $? -ne 0 ]; then
 	print -u2 "failed to build"
 	exit 1
@@ -165,6 +165,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.eliminate.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.eliminate.ksh
index 687e435e3fc..96b05d5cde2 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.eliminate.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.eliminate.ksh
@@ -101,6 +101,6 @@ if [ $? -eq 0 ]; then
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit 0
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled.ksh
index ba62be75a4c..d0ac1864877 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled.ksh
@@ -91,6 +91,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled2.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled2.ksh
index 340164847bf..d40036d8c57 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled2.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.enabled2.ksh
@@ -108,6 +108,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.entryreturn.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.entryreturn.ksh
index 9d2646cdf1f..51afe961a84 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.entryreturn.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.entryreturn.ksh
@@ -113,6 +113,6 @@ script | cut -c5-
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.fork.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.fork.ksh
index 9c12e6dea29..3ee9e9f228d 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.fork.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.fork.ksh
@@ -100,6 +100,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess32.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess32.ksh
index 68a8d016073..8affb3583f8 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess32.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess32.ksh
@@ -91,6 +91,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess64.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess64.ksh
index 39de8e0d81b..0c2801872e3 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess64.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.guess64.ksh
@@ -95,6 +95,6 @@ else
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.header.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.header.ksh
index 08a1912bae8..37ad97c3b0f 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.header.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.header.ksh
@@ -82,4 +82,4 @@ if [ $? -ne 0 ]; then
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.include.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.include.ksh
index 5683f47d427..6f809fdc7c8 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.include.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.include.ksh
@@ -56,6 +56,6 @@ fi
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkpriv.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkpriv.ksh
index ec07e057af8..a1ef9d89c30 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkpriv.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkpriv.ksh
@@ -79,4 +79,4 @@ if [ $? -ne 0 ]; then
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkunpriv.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkunpriv.ksh
index 01b2126c944..ffc5107b1bf 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkunpriv.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.linkunpriv.ksh
@@ -81,4 +81,4 @@ if [ $? -ne 0 ]; then
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.multiple.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.multiple.ksh
index 0c8b072cb0d..3f545a7bd48 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.multiple.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.multiple.ksh
@@ -94,6 +94,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.nodtrace.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.nodtrace.ksh
index a911bcdfdfb..f766f6d1d1a 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.nodtrace.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.nodtrace.ksh
@@ -85,6 +85,6 @@ fi
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.onlyenabled.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.onlyenabled.ksh
index 989d6d32aff..9def3c002b9 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.onlyenabled.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.onlyenabled.ksh
@@ -79,4 +79,4 @@ if [ $? -ne 0 ]; then
 fi
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.reeval.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.reeval.ksh
index 7fad40156a0..4ea33f76d83 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.reeval.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.reeval.ksh
@@ -93,6 +93,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static.ksh
index 1ebcdb95fdf..0cddf0db810 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static.ksh
@@ -93,6 +93,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static2.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static2.ksh
index 7cf9004c612..8385b27cdfe 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static2.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.static2.ksh
@@ -103,6 +103,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.user.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.user.ksh
index d5d9fdc4d3f..89ceb4a9485 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.user.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/usdt/tst.user.ksh
@@ -91,6 +91,6 @@ script
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/vars/tst.ucaller.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/vars/tst.ucaller.ksh
index 8427ea0cb4e..c09825ec21b 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/vars/tst.ucaller.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/vars/tst.ucaller.ksh
@@ -38,7 +38,7 @@ fi
 
 dtrace=$1
 
-$dtrace -qs /dev/stdin -c "/usr/bin/echo" <calloc = 1;
diff --git a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/sparc/usdt/tst.tailcall.ksh b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/sparc/usdt/tst.tailcall.ksh
index cfd7a631211..c3651ecf7eb 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/test/tst/sparc/usdt/tst.tailcall.ksh
+++ b/cddl/contrib/opensolaris/cmd/dtrace/test/tst/sparc/usdt/tst.tailcall.ksh
@@ -76,7 +76,7 @@ provider test {
 };
 EOF
 
-/usr/ccs/bin/as -xregsym=no -P -D_ASM -o test.o test.s
+/usr/bin/as -xregsym=no -P -D_ASM -o test.o test.s
 if [ $? -ne 0 ]; then
 	print -u2 "failed to compile test.s"
 	exit 1
@@ -127,6 +127,6 @@ EOF
 status=$?
 
 cd /
-/usr/bin/rm -rf $DIR
+/bin/rm -rf $DIR
 
 exit $status

From 87d87e1d2092de3b94481a39d03aa0872b34751f Mon Sep 17 00:00:00 2001
From: Bernhard Schmidt 
Date: Sat, 21 Aug 2010 11:06:21 +0000
Subject: [PATCH 0116/1624] Wrap remaining ieee80211_ratectl_node_init() calls
 missed in r211314.

MFC after:	1 week
---
 sys/net80211/ieee80211_node.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/sys/net80211/ieee80211_node.c b/sys/net80211/ieee80211_node.c
index e3c2769259f..2dc48712f03 100644
--- a/sys/net80211/ieee80211_node.c
+++ b/sys/net80211/ieee80211_node.c
@@ -1404,7 +1404,8 @@ ieee80211_fakeup_adhoc_node(struct ieee80211vap *vap,
 #endif
 		}
 		ieee80211_node_setuptxparms(ni);
-		ieee80211_ratectl_node_init(ni);
+		if (vap->iv_caps & IEEE80211_C_RATECTL)
+			ieee80211_ratectl_node_init(ni);
 		if (ic->ic_newassoc != NULL)
 			ic->ic_newassoc(ni, 1);
 		/* XXX not right for 802.1x/WPA */
@@ -1474,7 +1475,8 @@ ieee80211_add_neighbor(struct ieee80211vap *vap,
 		if (ieee80211_iserp_rateset(&ni->ni_rates))
 			ni->ni_flags |= IEEE80211_NODE_ERP;
 		ieee80211_node_setuptxparms(ni);
-		ieee80211_ratectl_node_init(ni);
+		if (vap->iv_caps & IEEE80211_C_RATECTL)
+			ieee80211_ratectl_node_init(ni);
 		if (ic->ic_newassoc != NULL)
 			ic->ic_newassoc(ni, 1);
 		/* XXX not right for 802.1x/WPA */
@@ -2343,7 +2345,8 @@ ieee80211_node_join(struct ieee80211_node *ni, int resp)
 	);
 
 	ieee80211_node_setuptxparms(ni);
-	ieee80211_ratectl_node_init(ni);
+	if (vap->iv_caps & IEEE80211_C_RATECTL)
+		ieee80211_ratectl_node_init(ni);
 	/* give driver a chance to setup state like ni_txrate */
 	if (ic->ic_newassoc != NULL)
 		ic->ic_newassoc(ni, newassoc);

From 0c0b3feeed2034b0ceeb4d6acdc453d7ca2aa594 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 11:09:03 +0000
Subject: [PATCH 0117/1624] The DTrace instrumentation object is going to be
 i386/amd64 only.

Sponsored by:	The FreeBSD Foundation
---
 cddl/lib/Makefile | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/cddl/lib/Makefile b/cddl/lib/Makefile
index 33cda45cbaf..17ef4744926 100644
--- a/cddl/lib/Makefile
+++ b/cddl/lib/Makefile
@@ -2,7 +2,7 @@
 
 .include 
 
-SUBDIR=	drti \
+SUBDIR=	${_drti} \
 	libavl \
 	libctf \
 	${_libdtrace} \
@@ -20,6 +20,7 @@ _libzpool=	libzpool
 .endif
 
 .if ${MACHINE_ARCH} == amd64 || ${MACHINE_ARCH} == i386
+_drti=		drti
 _libdtrace=	libdtrace
 .endif
 

From d6f390f2f1da9a460abe6cf8dc0747cd956e5016 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 11:14:50 +0000
Subject: [PATCH 0118/1624] Use double quotes when checking the value of
 MACHINE_ARCH.

Sponsored by:	The FreeBSD Foundation
---
 cddl/lib/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cddl/lib/Makefile b/cddl/lib/Makefile
index 17ef4744926..52e97d74be9 100644
--- a/cddl/lib/Makefile
+++ b/cddl/lib/Makefile
@@ -19,7 +19,7 @@ _libzpool=	libzpool
 .endif
 .endif
 
-.if ${MACHINE_ARCH} == amd64 || ${MACHINE_ARCH} == i386
+.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
 _drti=		drti
 _libdtrace=	libdtrace
 .endif

From e0be1c75f0ca6dcde4b8ada4867e5ac1b1bdde3b Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 11:41:32 +0000
Subject: [PATCH 0119/1624] Add sysname to struct opensolaris_utsname. This is
 needed by one DTrace test.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/compat/opensolaris/kern/opensolaris_misc.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/cddl/compat/opensolaris/kern/opensolaris_misc.c b/sys/cddl/compat/opensolaris/kern/opensolaris_misc.c
index 4f46933d017..4ac666dfbe6 100644
--- a/sys/cddl/compat/opensolaris/kern/opensolaris_misc.c
+++ b/sys/cddl/compat/opensolaris/kern/opensolaris_misc.c
@@ -38,7 +38,8 @@ __FBSDID("$FreeBSD$");
 char hw_serial[11] = "0";
 
 struct opensolaris_utsname utsname = {
-	.nodename = "unset"
+	.nodename = "unset",
+	.sysname  = "SunOS"
 };
 
 int

From 0f2bd1e89db1a2f09268edea21e0ead329e092df Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 11:50:53 +0000
Subject: [PATCH 0120/1624] Add libdtrace support for tracing userland
 programs.

Summary of changes:
* Implement a compatibility shim between Solaris libproc and our
libproc and remove several ifdefs because of this.
* Port the drti to FreeBSD.
* Implement the missing DOODAD sections
* Link with libproc and librtld_db
* Support for ustack, jstack and uregs (by sson@)
* Misc bugfixing

When writing the SUWN_dof section, we had to resort to building the ELF
file layout by "hand". This is the job of libelf, but our libelf doesn't
support this yet. When libelf is fixed, we can remove the code under
#ifdef BROKEN_LIBELF.

Sponsored by:	The FreeBSD Foundation
---
 cddl/contrib/opensolaris/cmd/dtrace/dtrace.c  |  24 ++-
 .../opensolaris/lib/libdtrace/common/drti.c   | 168 ++++++++++++++-
 .../lib/libdtrace/common/dt_aggregate.c       |   9 +-
 .../lib/libdtrace/common/dt_consume.c         |  27 +--
 .../lib/libdtrace/common/dt_link.c            | 193 +++++++++++++++++-
 .../lib/libdtrace/common/dt_open.c            |  14 +-
 .../opensolaris/lib/libdtrace/common/dt_pid.c |  83 ++------
 .../lib/libdtrace/common/dt_proc.c            | 154 +++++++-------
 .../lib/libdtrace/common/dt_proc.h            |   2 -
 .../lib/libdtrace/common/dt_subr.c            |  10 +-
 .../opensolaris/lib/libdtrace/common/dtrace.h |   3 +
 .../lib/libdtrace/i386/dt_isadep.c            |  44 ++++
 cddl/lib/libdtrace/Makefile                   |  16 +-
 cddl/lib/libdtrace/libproc_compat.h           |  62 ++++++
 cddl/lib/libdtrace/regs_x86.d                 | 121 +++++++++++
 15 files changed, 712 insertions(+), 218 deletions(-)
 create mode 100644 cddl/lib/libdtrace/libproc_compat.h
 create mode 100644 cddl/lib/libdtrace/regs_x86.d

diff --git a/cddl/contrib/opensolaris/cmd/dtrace/dtrace.c b/cddl/contrib/opensolaris/cmd/dtrace/dtrace.c
index 2580e6323a8..63721abc713 100644
--- a/cddl/contrib/opensolaris/cmd/dtrace/dtrace.c
+++ b/cddl/contrib/opensolaris/cmd/dtrace/dtrace.c
@@ -773,19 +773,27 @@ compile_str(dtrace_cmd_t *dcp)
 static void
 prochandler(struct ps_prochandle *P, const char *msg, void *arg)
 {
-fatal("DOODAD in function %s, file %s, line %d\n",__FUNCTION__,__FILE__,__LINE__);
-#ifdef DOODAD
+#if defined(sun)
 	const psinfo_t *prp = Ppsinfo(P);
 	int pid = Pstatus(P)->pr_pid;
 	char name[SIG2STR_MAX];
+#else
+	int wstatus = proc_getwstat(P);
+	int pid = proc_getpid(P);
+#endif
 
 	if (msg != NULL) {
 		notice("pid %d: %s\n", pid, msg);
 		return;
 	}
 
+#if defined(sun)
 	switch (Pstate(P)) {
+#else
+	switch (proc_state(P)) {
+#endif
 	case PS_UNDEAD:
+#if defined(sun)
 		/*
 		 * Ideally we would like to always report pr_wstat here, but it
 		 * isn't possible given current /proc semantics.  If we grabbed
@@ -798,9 +806,20 @@ fatal("DOODAD in function %s, file %s, line %d\n",__FUNCTION__,__FILE__,__LINE__
 			notice("pid %d terminated by %s\n", pid,
 			    proc_signame(WTERMSIG(prp->pr_wstat),
 			    name, sizeof (name)));
+#else
+		if (WIFSIGNALED(wstatus)) {
+			notice("pid %d terminated by %d\n", pid,
+			    WTERMSIG(wstatus));
+#endif
+#if defined(sun)
 		} else if (prp != NULL && WEXITSTATUS(prp->pr_wstat) != 0) {
 			notice("pid %d exited with status %d\n",
 			    pid, WEXITSTATUS(prp->pr_wstat));
+#else
+		} else if (WEXITSTATUS(wstatus) != 0) {
+			notice("pid %d exited with status %d\n",
+			    pid, WEXITSTATUS(wstatus));
+#endif
 		} else {
 			notice("pid %d has exited\n", pid);
 		}
@@ -812,7 +831,6 @@ fatal("DOODAD in function %s, file %s, line %d\n",__FUNCTION__,__FILE__,__LINE__
 		g_pslive--;
 		break;
 	}
-#endif
 }
 
 /*ARGSUSED*/
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c b/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c
index 1ae82838929..bce80383849 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c
@@ -34,6 +34,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 
 /*
  * In Solaris 10 GA, the only mechanism for communicating helper information
@@ -53,12 +55,16 @@
  */
 
 static const char *devnamep = "/dev/dtrace/helper";
+#if defined(sun)
 static const char *olddevname = "/devices/pseudo/dtrace@0:helper";
+#endif
 
 static const char *modname;	/* Name of this load object */
 static int gen;			/* DOF helper generation */
+#if defined(sun)
 extern dof_hdr_t __SUNW_dof;	/* DOF defined in the .SUNW_dof section */
-static boolean_t dof_init_debug = B_FALSE;	/* From DTRACE_DOF_INIT_DEBUG */
+#endif
+static boolean_t dof_init_debug = B_TRUE;	/* From DTRACE_DOF_INIT_DEBUG */
 
 static void
 dprintf(int debug, const char *fmt, ...)
@@ -83,6 +89,36 @@ dprintf(int debug, const char *fmt, ...)
 	va_end(ap);
 }
 
+#if !defined(sun)
+static void
+fixsymbol(Elf *e, Elf_Data *data, size_t idx, int nprobes, char *buf,
+    dof_sec_t *sec, int *fixedprobes, char *dofstrtab)
+{
+	GElf_Sym sym;
+	char *s;
+	unsigned char *funcname;
+	dof_probe_t *prb;
+	int j = 0;
+	int ndx;
+
+	while (gelf_getsym(data, j++, &sym) != NULL) {
+		prb = (dof_probe_t *)(buf + sec->dofs_offset);
+
+		for (ndx = nprobes; ndx; ndx--, prb += 1) {
+			funcname = dofstrtab + prb->dofpr_func;
+			s = elf_strptr(e, idx, sym.st_name);
+			if (strcmp(s, funcname) == 0) {
+				dprintf(1, "fixing %s() symbol\n", s);
+				prb->dofpr_addr = sym.st_value;
+				(*fixedprobes)++;
+			}
+		}
+		if (*fixedprobes == nprobes)
+			break;
+	}
+}
+#endif
+
 #if defined(sun)
 #pragma init(dtrace_dof_init)
 #else
@@ -92,22 +128,39 @@ static void dtrace_dof_init(void) __attribute__ ((constructor));
 static void
 dtrace_dof_init(void)
 {
+#if defined(sun)
 	dof_hdr_t *dof = &__SUNW_dof;
+#else
+	dof_hdr_t *dof = NULL;
+#endif
 #ifdef _LP64
 	Elf64_Ehdr *elf;
 #else
 	Elf32_Ehdr *elf;
 #endif
 	dof_helper_t dh;
-#if defined(sun)
 	Link_map *lmp;
+#if defined(sun)
 	Lmid_t lmid;
 #else
-	struct link_map *lmp;
 	u_long lmid = 0;
+	dof_sec_t *sec;
+	size_t i;
 #endif
 	int fd;
 	const char *p;
+#if !defined(sun)
+	Elf *e;
+	Elf_Scn *scn = NULL;
+	Elf_Data *symtabdata = NULL, *dynsymdata = NULL;
+	GElf_Shdr shdr;
+	int efd, nprobes;
+	char *s;
+	size_t shstridx, symtabidx = 0, dynsymidx = 0;
+	unsigned char *dofstrtab = NULL;
+	unsigned char *buf;
+	int fixedprobes = 0;
+#endif
 
 	if (getenv("DTRACE_DOF_INIT_DISABLE") != NULL)
 		return;
@@ -127,10 +180,46 @@ dtrace_dof_init(void)
 	}
 #endif
 
+
 	if ((modname = strrchr(lmp->l_name, '/')) == NULL)
 		modname = lmp->l_name;
 	else
 		modname++;
+#if !defined(sun)
+	elf_version(EV_CURRENT);
+	if ((efd = open(lmp->l_name, O_RDONLY, 0)) < 0) {
+		dprintf(1, "couldn't open file for reading\n");
+		return;
+	}
+	if ((e = elf_begin(efd, ELF_C_READ, NULL)) == NULL) {
+		dprintf(1, "elf_begin failed\n");
+		close(efd);
+		return;
+	}
+	elf_getshdrstrndx(e, &shstridx);
+	dof = NULL;
+	while ((scn = elf_nextscn(e, scn)) != NULL) {
+		gelf_getshdr(scn, &shdr);
+		if (shdr.sh_type == SHT_SYMTAB) {
+			symtabidx = shdr.sh_link;
+			symtabdata = elf_getdata(scn, NULL);
+		} else if (shdr.sh_type == SHT_DYNSYM) {
+			dynsymidx = shdr.sh_link;
+			dynsymdata = elf_getdata(scn, NULL);
+		} else if (shdr.sh_type == SHT_PROGBITS) {
+			s = elf_strptr(e, shstridx, shdr.sh_name);
+			if  (s && strcmp(s, ".SUNW_dof") == 0) {
+				dof = elf_getdata(scn, NULL)->d_buf;
+			}
+		}
+	}
+	if (dof == NULL) {
+		dprintf(1, "SUNW_dof section not found\n");
+		elf_end(e);
+		close(efd);
+		return;
+	}
+#endif
 
 	if (dof->dofh_ident[DOF_ID_MAG0] != DOF_MAG_MAG0 ||
 	    dof->dofh_ident[DOF_ID_MAG1] != DOF_MAG_MAG1 ||
@@ -158,7 +247,7 @@ dtrace_dof_init(void)
 
 	if ((fd = open64(devnamep, O_RDWR)) < 0) {
 		dprintf(1, "failed to open helper device %s", devnamep);
-
+#if defined(sun)
 		/*
 		 * If the device path wasn't explicitly set, try again with
 		 * the old device path.
@@ -172,14 +261,79 @@ dtrace_dof_init(void)
 			dprintf(1, "failed to open helper device %s", devnamep);
 			return;
 		}
+#else
+		return;
+#endif
 	}
-
+#if !defined(sun)
+	/*
+	 * We need to fix the base address of each probe since this wasn't
+	 * done by ld(1). (ld(1) needs to grow support for parsing the
+	 * SUNW_dof section).
+	 *
+	 * The complexity of this is not that great. The first for loop
+	 * iterates over the sections inside the DOF file. There are usually
+	 * 10 sections here. We asume the STRTAB section comes first and the
+	 * PROBES section comes after. Since we are only interested in fixing
+	 * data inside the PROBES section we quit the for loop after processing
+	 * the PROBES section. It's usually the case that the first section
+	 * is the STRTAB section and the second section is the PROBES section,
+	 * so this for loop is not meaningful when doing complexity analysis.
+	 *
+	 * After finding the probes section, we iterate over the symbols
+	 * in the symtab section. When we find a symbol name that matches
+	 * the probe function name, we fix it. If we have fixed all the
+	 * probes, we exit all the loops and we are done.
+	 * The number of probes is given by the variable 'nprobes' and this
+	 * depends entirely on the user, but some optimizations were done.
+	 *
+	 * We are assuming the number of probes is less than the number of
+	 * symbols (libc can have 4k symbols, for example).
+	 */
+	sec = (dof_sec_t *)(dof + 1);
+	buf = (char *)dof;
+	for (i = 0; i < dof->dofh_secnum; i++, sec++) {
+		if (sec->dofs_type == DOF_SECT_STRTAB)
+			dofstrtab = (unsigned char *)(buf + sec->dofs_offset);
+		else if (sec->dofs_type == DOF_SECT_PROBES && dofstrtab)
+			break;
+	
+	}
+	nprobes = sec->dofs_size / sec->dofs_entsize;
+	fixsymbol(e, symtabdata, symtabidx, nprobes, buf, sec, &fixedprobes,
+	    dofstrtab);
+	if (fixedprobes != nprobes) {
+		/*
+		 * If we haven't fixed all the probes using the
+		 * symtab section, look inside the dynsym
+		 * section.
+		 */
+		fixsymbol(e, dynsymdata, dynsymidx, nprobes, buf, sec,
+		    &fixedprobes, dofstrtab);
+	}
+	if (fixedprobes != nprobes) {
+		fprintf(stderr, "WARNING: number of probes "
+		    "fixed does not match the number of "
+		    "defined probes (%d != %d, "
+		    "respectively)\n", fixedprobes, nprobes);
+		fprintf(stderr, "WARNING: some probes might "
+		    "not fire or your program might crash\n");
+	}
+#endif
 	if ((gen = ioctl(fd, DTRACEHIOC_ADDDOF, &dh)) == -1)
 		dprintf(1, "DTrace ioctl failed for DOF at %p", dof);
-	else
+	else {
 		dprintf(1, "DTrace ioctl succeeded for DOF at %p\n", dof);
+#if !defined(sun)
+		gen = dh.gen;
+#endif
+	}
 
 	(void) close(fd);
+#if !defined(sun)
+	elf_end(e);
+	(void) close(efd);
+#endif
 }
 
 #if defined(sun)
@@ -198,7 +352,7 @@ dtrace_dof_fini(void)
 		return;
 	}
 
-	if ((gen = ioctl(fd, DTRACEHIOC_REMOVE, gen)) == -1)
+	if ((gen = ioctl(fd, DTRACEHIOC_REMOVE, &gen)) == -1)
 		dprintf(1, "DTrace ioctl failed to remove DOF (%d)\n", gen);
 	else
 		dprintf(1, "DTrace ioctl removed DOF (%d)\n", gen);
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_aggregate.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_aggregate.c
index ac32f769a93..f6c9622c6c8 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_aggregate.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_aggregate.c
@@ -36,6 +36,7 @@
 #include 
 #else
 #include 
+#include 
 #endif
 #include 
 
@@ -264,11 +265,7 @@ dt_aggregate_usym(dtrace_hdl_t *dtp, uint64_t *data)
 
 	dt_proc_lock(dtp, P);
 
-#if defined(sun)
 	if (Plookup_by_addr(P, *pc, NULL, 0, &sym) == 0)
-#else
-	if (proc_addr2sym(P, *pc, NULL, 0, &sym) == 0)
-#endif
 		*pc = sym.st_value;
 
 	dt_proc_unlock(dtp, P);
@@ -291,11 +288,7 @@ dt_aggregate_umod(dtrace_hdl_t *dtp, uint64_t *data)
 
 	dt_proc_lock(dtp, P);
 
-#if defined(sun)
 	if ((map = Paddr_to_map(P, *pc)) != NULL)
-#else
-	if ((map = proc_addr2map(P, *pc)) != NULL)
-#endif
 		*pc = map->pr_vaddr;
 
 	dt_proc_unlock(dtp, P);
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_consume.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_consume.c
index c8ac6b0d11c..911478ee075 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_consume.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_consume.c
@@ -34,6 +34,9 @@
 #include 
 #endif
 #include 
+#if !defined(sun)
+#include 
+#endif
 
 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
 
@@ -952,17 +955,9 @@ dt_print_ustack(dtrace_hdl_t *dtp, FILE *fp, const char *format,
 		if ((err = dt_printf(dtp, fp, "%*s", indent, "")) < 0)
 			break;
 
-#if defined(sun)
 		if (P != NULL && Plookup_by_addr(P, pc[i],
-#else
-		if (P != NULL && proc_addr2sym(P, pc[i],
-#endif
 		    name, sizeof (name), &sym) == 0) {
-#if defined(sun)
 			(void) Pobjname(P, pc[i], objname, sizeof (objname));
-#else
-			(void) proc_objname(P, pc[i], objname, sizeof (objname));
-#endif
 
 			if (pc[i] > sym.st_value) {
 				(void) snprintf(c, sizeof (c),
@@ -973,12 +968,8 @@ dt_print_ustack(dtrace_hdl_t *dtp, FILE *fp, const char *format,
 				    "%s`%s", dt_basename(objname), name);
 			}
 		} else if (str != NULL && str[0] != '\0' && str[0] != '@' &&
-#if defined(sun)
 		    (P != NULL && ((map = Paddr_to_map(P, pc[i])) == NULL ||
 		    (map->pr_mflags & MA_WRITE)))) {
-#else
-		    (P != NULL && ((map = proc_addr2map(P, pc[i])) == NULL))) {
-#endif
 			/*
 			 * If the current string pointer in the string table
 			 * does not point to an empty string _and_ the program
@@ -994,11 +985,7 @@ dt_print_ustack(dtrace_hdl_t *dtp, FILE *fp, const char *format,
 			 */
 			(void) snprintf(c, sizeof (c), "%s", str);
 		} else {
-#if defined(sun)
 			if (P != NULL && Pobjname(P, pc[i], objname,
-#else
-			if (P != NULL && proc_objname(P, pc[i], objname,
-#endif
 			    sizeof (objname)) != 0) {
 				(void) snprintf(c, sizeof (c), "%s`0x%llx",
 				    dt_basename(objname), (u_longlong_t)pc[i]);
@@ -1068,11 +1055,7 @@ dt_print_usym(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr, dtrace_actkind_t act)
 
 			dt_proc_lock(dtp, P);
 
-#if defined(sun)
 			if (Plookup_by_addr(P, pc, NULL, 0, &sym) == 0)
-#else
-			if (proc_addr2sym(P, pc, NULL, 0, &sym) == 0)
-#endif
 				pc = sym.st_value;
 
 			dt_proc_unlock(dtp, P);
@@ -1115,11 +1098,7 @@ dt_print_umod(dtrace_hdl_t *dtp, FILE *fp, const char *format, caddr_t addr)
 	if (P != NULL)
 		dt_proc_lock(dtp, P); /* lock handle while we perform lookups */
 
-#if defined(sun)
 	if (P != NULL && Pobjname(P, pc, objname, sizeof (objname)) != 0) {
-#else
-	if (P != NULL && proc_objname(P, pc, objname, sizeof (objname)) != 0) {
-#endif
 		(void) snprintf(c, sizeof (c), "%s", dt_basename(objname));
 	} else {
 		(void) snprintf(c, sizeof (c), "0x%llx", (u_longlong_t)pc);
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c
index aa78658b5fc..0b8899ab8b5 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c
@@ -51,6 +51,9 @@
 #include 
 #else
 #include 
+#include 
+#include 
+#include 
 #endif
 #include 
 #include 
@@ -412,7 +415,6 @@ prepare_elf64(dtrace_hdl_t *dtp, const dof_hdr_t *dof, dof_elf64_t *dep)
 		s = &dofs[dofrh->dofr_tgtsec];
 
 		for (j = 0; j < nrel; j++) {
-printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
 #ifdef DOODAD
 #if defined(__arm__)
 /* XXX */
@@ -1519,14 +1521,29 @@ process_obj(dtrace_hdl_t *dtp, const char *obj, int *eprobesp)
 
 			off = rela.r_offset - fsym.st_value;
 			if (dt_modtext(dtp, data_tgt->d_buf, eprobe,
-			    &rela, &off) != 0) {
+			    &rela, &off) != 0)
 				goto err;
-			}
 
 			if (dt_probe_define(pvp, prp, s, r, off, eprobe) != 0) {
 				return (dt_link_error(dtp, elf, fd, bufs,
 				    "failed to allocate space for probe"));
 			}
+#if !defined(sun)
+			/*
+			 * Our linker doesn't understand the SUNW_IGNORE ndx and
+			 * will try to use this relocation when we build the
+			 * final executable. Since we are done processing this
+			 * relocation, mark it as inexistant and let libelf
+			 * remove it from the file.
+			 * If this wasn't done, we would have garbage added to
+			 * the executable file as the symbol is going to be
+			 * change from UND to ABS.
+			 */
+			rela.r_offset = 0;
+			rela.r_info  = 0;
+			rela.r_addend = 0;
+			(void) gelf_update_rela(data_rel, i, &rela);
+#endif
 
 			mod = 1;
 			(void) elf_flagdata(data_tgt, ELF_C_SET, ELF_F_DIRTY);
@@ -1538,13 +1555,13 @@ process_obj(dtrace_hdl_t *dtp, const char *obj, int *eprobesp)
 			 * already been processed by an earlier link
 			 * invocation.
 			 */
-printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
-#ifdef DOODAD
+#if !defined(sun)
+#define SHN_SUNW_IGNORE	SHN_ABS
+#endif
 			if (rsym.st_shndx != SHN_SUNW_IGNORE) {
 				rsym.st_shndx = SHN_SUNW_IGNORE;
 				(void) gelf_update_sym(data_sym, ndx, &rsym);
 			}
-#endif
 		}
 	}
 
@@ -1554,6 +1571,9 @@ printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
 	(void) elf_end(elf);
 	(void) close(fd);
 
+#if !defined(sun)
+	if (nsym > 0)
+#endif
 	while ((pair = bufs) != NULL) {
 		bufs = pair->dlp_next;
 		dt_free(dtp, pair->dlp_str);
@@ -1574,6 +1594,19 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 {
 #if !defined(sun)
 	char tfile[PATH_MAX];
+	Elf *e;
+	Elf_Scn *scn;
+	Elf_Data *data;
+	GElf_Shdr shdr;
+	int efd;
+	size_t stridx;
+	unsigned char *buf;
+	char *s;
+	int loc;
+	GElf_Ehdr ehdr;
+	Elf_Scn *scn0;
+	GElf_Shdr shdr0;
+	uint64_t off, rc;
 #endif
 	char drti[PATH_MAX];
 	dof_hdr_t *dof;
@@ -1697,12 +1730,17 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 		(void) unlink(file);
 #endif
 
+#if defined(sun)
 	if (dtp->dt_oflags & DTRACE_O_LP64)
 		status = dump_elf64(dtp, dof, fd);
 	else
 		status = dump_elf32(dtp, dof, fd);
 
 	if (status != 0 || lseek(fd, 0, SEEK_SET) != 0) {
+#else
+	/* We don't write the ELF header, just the DOF section */
+	if (dt_write(dtp, fd, dof, dof->dofh_filesz) < dof->dofh_filesz) {
+#endif
 		return (dt_link_error(dtp, NULL, -1, NULL,
 		    "failed to write %s: %s", file, strerror(errno)));
 	}
@@ -1726,7 +1764,7 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 
 		(void) snprintf(cmd, len, fmt, dtp->dt_ld_path, file, fd, drti);
 #else
-		const char *fmt = "%s -o %s -r %s %s";
+		const char *fmt = "%s -o %s -r %s";
 
 #if defined(__amd64__)
 		/*
@@ -1748,11 +1786,14 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 		len = snprintf(&tmp, 1, fmt, dtp->dt_ld_path, file, tfile,
 		    drti) + 1;
 
+#if !defined(sun)
+		len *= 2;
+#endif
 		cmd = alloca(len);
 
-		(void) snprintf(cmd, len, fmt, dtp->dt_ld_path, file, tfile, drti);
+		(void) snprintf(cmd, len, fmt, dtp->dt_ld_path, file,
+		    drti);
 #endif
-
 		if ((status = system(cmd)) == -1) {
 			ret = dt_link_error(dtp, NULL, -1, NULL,
 			    "failed to run %s: %s", dtp->dt_ld_path,
@@ -1760,8 +1801,6 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 			goto done;
 		}
 
-		(void) close(fd); /* release temporary file */
-
 		if (WIFSIGNALED(status)) {
 			ret = dt_link_error(dtp, NULL, -1, NULL,
 			    "failed to link %s: %s failed due to signal %d",
@@ -1775,6 +1814,138 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 			    file, dtp->dt_ld_path, WEXITSTATUS(status));
 			goto done;
 		}
+#if !defined(sun)
+#define BROKEN_LIBELF
+		/*
+		 * FreeBSD's ld(1) is not instructed to interpret and add
+		 * correctly the SUNW_dof section present in tfile.
+		 * We use libelf to add this section manually and hope the next
+		 * ld invocation won't remove it.
+		 */
+		elf_version(EV_CURRENT);
+		if ((efd = open(file, O_RDWR, 0)) < 0) {
+			ret = dt_link_error(dtp, NULL, -1, NULL,
+			    "failed to open file %s: %s",
+			    file, strerror(errno));
+			goto done;
+		}
+		if ((e = elf_begin(efd, ELF_C_RDWR, NULL)) == NULL) {
+			close(efd);
+			ret = dt_link_error(dtp, NULL, -1, NULL,
+			    "failed to open elf file: %s",
+			    elf_errmsg(elf_errno()));
+			goto done;
+		}
+		/*
+		 * Add the string '.SUWN_dof' to the shstrtab section.
+		 */
+#ifdef BROKEN_LIBELF
+		elf_flagelf(e, ELF_C_SET, ELF_F_LAYOUT);
+#endif
+		elf_getshdrstrndx(e, &stridx);
+		scn = elf_getscn(e, stridx);
+		gelf_getshdr(scn, &shdr);
+		data = elf_newdata(scn);
+		data->d_off = shdr.sh_size;
+		data->d_buf = ".SUNW_dof";
+		data->d_size = 10;
+		data->d_type = ELF_T_BYTE;
+		loc = shdr.sh_size;
+		shdr.sh_size += data->d_size;
+		gelf_update_shdr(scn, &shdr);
+#ifdef BROKEN_LIBELF
+		off = shdr.sh_offset;
+		rc = shdr.sh_offset + shdr.sh_size;
+		gelf_getehdr(e, &ehdr);
+		if (ehdr.e_shoff > off) {
+			off = ehdr.e_shoff + ehdr.e_shnum * ehdr.e_shentsize;
+			rc = roundup(rc, 8);
+			ehdr.e_shoff = rc;
+			gelf_update_ehdr(e, &ehdr);
+			rc += ehdr.e_shnum * ehdr.e_shentsize;
+		}
+		for (;;) {
+			scn0 = NULL;
+			scn = NULL;
+			while ((scn = elf_nextscn(e, scn)) != NULL) {
+				gelf_getshdr(scn, &shdr);
+				if (shdr.sh_type == SHT_NOBITS ||
+				    shdr.sh_offset < off)
+					continue;
+				/* Find the immediately adjcent section. */
+				if (scn0 == NULL ||
+				    shdr.sh_offset < shdr0.sh_offset) {
+					scn0 = scn;
+					gelf_getshdr(scn0, &shdr0);
+				}
+			}
+			if (scn0 == NULL)
+				break;
+			/* Load section data to work around another bug */
+			elf_getdata(scn0, NULL);
+			/* Update section header, assure section alignment */
+			off = shdr0.sh_offset + shdr0.sh_size;
+			rc = roundup(rc, shdr0.sh_addralign);
+			shdr0.sh_offset = rc;
+			gelf_update_shdr(scn0, &shdr0);
+			rc += shdr0.sh_size;
+		}
+		if (elf_update(e, ELF_C_WRITE) < 0) {
+			ret = dt_link_error(dtp, NULL, -1, NULL,
+			    "failed to add append the shstrtab section: %s",
+			    elf_errmsg(elf_errno()));
+			elf_end(e);
+			close(efd);
+			goto done;
+		}
+		elf_end(e);
+		e = elf_begin(efd, ELF_C_RDWR, NULL);
+#endif
+		/*
+		 * Construct the .SUNW_dof section.
+		 */
+		scn = elf_newscn(e);
+		data = elf_newdata(scn);
+		buf = mmap(NULL, dof->dofh_filesz, PROT_READ, MAP_SHARED,
+		    fd, 0);
+		if (buf == MAP_FAILED) {
+			ret = dt_link_error(dtp, NULL, -1, NULL,
+			    "failed to mmap buffer %s", strerror(errno));
+			elf_end(e);
+			close(efd);
+			goto done;
+		}
+		data->d_buf = buf;
+		data->d_align = 4;
+		data->d_size = dof->dofh_filesz;
+		data->d_version = EV_CURRENT;
+		gelf_getshdr(scn, &shdr);
+		shdr.sh_name = loc;
+		shdr.sh_flags = SHF_ALLOC;
+		/*
+		 * Actually this should be SHT_SUNW_dof, but FreeBSD's ld(1)
+		 * will remove this 'unknown' section when we try to create an
+		 * executable using the object we are modifying, so we stop
+		 * playing by the rules and use SHT_PROGBITS.
+		 * Also, note that our drti has modifications to handle this.
+		 */
+		shdr.sh_type = SHT_PROGBITS;
+		shdr.sh_addralign = 4;
+		gelf_update_shdr(scn, &shdr);
+		if (elf_update(e, ELF_C_WRITE) < 0) {
+			ret = dt_link_error(dtp, NULL, -1, NULL,
+			    "failed to add the SUNW_dof section: %s",
+			    elf_errmsg(elf_errno()));
+			munmap(buf, dof->dofh_filesz);
+			elf_end(e);
+			close(efd);
+			goto done;
+		}
+		munmap(buf, dof->dofh_filesz);
+		elf_end(e);
+		close(efd);
+#endif
+		(void) close(fd); /* release temporary file */
 	} else {
 		(void) close(fd);
 	}
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c
index ec8bce83bb4..a8070e602ef 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c
@@ -283,10 +283,8 @@ static const dt_ident_t _dtrace_globals[] = {
 	DT_VERS_1_5, &dt_idops_func, "string(int, void *)" },
 { "ipl", DT_IDENT_SCALAR, 0, DIF_VAR_IPL, DT_ATTR_STABCMN, DT_VERS_1_0,
 	&dt_idops_type, "uint_t" },
-#if defined(sun)
 { "jstack", DT_IDENT_ACTFUNC, 0, DT_ACT_JSTACK, DT_ATTR_STABCMN, DT_VERS_1_0,
 	&dt_idops_func, "stack(...)" },
-#endif
 { "lltostr", DT_IDENT_FUNC, 0, DIF_SUBR_LLTOSTR, DT_ATTR_STABCMN, DT_VERS_1_0,
 	&dt_idops_func, "string(int64_t)" },
 { "lquantize", DT_IDENT_AGGFUNC, 0, DTRACEAGG_LQUANTIZE,
@@ -465,8 +463,10 @@ static const dt_ident_t _dtrace_globals[] = {
 #if defined(sun)
 { "uaddr", DT_IDENT_ACTFUNC, 0, DT_ACT_UADDR, DT_ATTR_STABCMN,
 	DT_VERS_1_2, &dt_idops_func, "_usymaddr(uintptr_t)" },
+#endif
 { "ucaller", DT_IDENT_SCALAR, 0, DIF_VAR_UCALLER, DT_ATTR_STABCMN,
 	DT_VERS_1_2, &dt_idops_type, "uint64_t" },
+#if defined(sun)
 { "ufunc", DT_IDENT_ACTFUNC, 0, DT_ACT_USYM, DT_ATTR_STABCMN,
 	DT_VERS_1_2, &dt_idops_func, "_usymaddr(uintptr_t)" },
 #endif
@@ -475,6 +475,7 @@ static const dt_ident_t _dtrace_globals[] = {
 #if defined(sun)
 { "umod", DT_IDENT_ACTFUNC, 0, DT_ACT_UMOD, DT_ATTR_STABCMN,
 	DT_VERS_1_2, &dt_idops_func, "_usymaddr(uintptr_t)" },
+#endif
 { "uregs", DT_IDENT_ARRAY, 0, DIF_VAR_UREGS, DT_ATTR_STABCMN, DT_VERS_1_0,
 	&dt_idops_regs, NULL },
 { "ustack", DT_IDENT_ACTFUNC, 0, DT_ACT_USTACK, DT_ATTR_STABCMN, DT_VERS_1_0,
@@ -482,6 +483,7 @@ static const dt_ident_t _dtrace_globals[] = {
 { "ustackdepth", DT_IDENT_SCALAR, 0, DIF_VAR_USTACKDEPTH,
 	DT_ATTR_STABCMN, DT_VERS_1_2,
 	&dt_idops_type, "uint32_t" },
+#if defined(sun)
 { "usym", DT_IDENT_ACTFUNC, 0, DT_ACT_USYM, DT_ATTR_STABCMN,
 	DT_VERS_1_2, &dt_idops_func, "_usymaddr(uintptr_t)" },
 #endif
@@ -760,9 +762,7 @@ int _dtrace_argmax = 32;	/* default maximum number of probe arguments */
 
 int _dtrace_debug = 0;		/* debug messages enabled (off) */
 const char *const _dtrace_version = DT_VERS_STRING; /* API version string */
-#if defined(sun)
 int _dtrace_rdvers = RD_VERSION; /* rtld_db feature version */
-#endif
 
 typedef struct dt_fdlist {
 	int *df_fds;		/* array of provider driver file descriptors */
@@ -780,12 +780,10 @@ _dtrace_init(void)
 {
 	_dtrace_debug = getenv("DTRACE_DEBUG") != NULL;
 
-#if defined(sun)
 	for (; _dtrace_rdvers > 0; _dtrace_rdvers--) {
 		if (rd_init(_dtrace_rdvers) == RD_OK)
 			break;
 	}
-#endif
 #if defined(__i386__)
 	/* make long doubles 64 bits -sson */
 	(void) fpsetprec(FP_PE);
@@ -1102,7 +1100,11 @@ alloc:
 
 	bzero(dtp, sizeof (dtrace_hdl_t));
 	dtp->dt_oflags = flags;
+#if defined(sun)
 	dtp->dt_prcmode = DT_PROC_STOP_PREINIT;
+#else
+	dtp->dt_prcmode = DT_PROC_STOP_POSTINIT;
+#endif
 	dtp->dt_linkmode = DT_LINK_KERNEL;
 	dtp->dt_linktype = DT_LTYP_ELF;
 	dtp->dt_xlatemode = DT_XL_STATIC;
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c
index a754d9cf3db..52b0eb94417 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c
@@ -40,6 +40,9 @@
 #include 
 #include 
 #include 
+#if !defined(sun)
+#include 
+#endif
 
 typedef struct dt_pid_probe {
 	dtrace_hdl_t *dpp_dtp;
@@ -142,7 +145,6 @@ dt_pid_per_sym(dt_pid_probe_t *pp, const GElf_Sym *symp, const char *func)
 	    pp->dpp_obj);
 
 	if (!isdash && gmatch("return", pp->dpp_name)) {
-#ifdef DOODAD
 		if (dt_pid_create_return_probe(pp->dpp_pr, dtp, ftp, symp,
 		    pp->dpp_stret) < 0) {
 			return (dt_pid_error(dtp, pcb, dpr, ftp,
@@ -150,20 +152,17 @@ dt_pid_per_sym(dt_pid_probe_t *pp, const GElf_Sym *symp, const char *func)
 			    "for '%s': %s", func,
 			    dtrace_errmsg(dtp, dtrace_errno(dtp))));
 		}
-#endif
 
 		nmatches++;
 	}
 
 	if (!isdash && gmatch("entry", pp->dpp_name)) {
-#ifdef DOODAD
 		if (dt_pid_create_entry_probe(pp->dpp_pr, dtp, ftp, symp) < 0) {
 			return (dt_pid_error(dtp, pcb, dpr, ftp,
 			    D_PROC_CREATEFAIL, "failed to create entry probe "
 			    "for '%s': %s", func,
 			    dtrace_errmsg(dtp, dtrace_errno(dtp))));
 		}
-#endif
 
 		nmatches++;
 	}
@@ -182,10 +181,8 @@ dt_pid_per_sym(dt_pid_probe_t *pp, const GElf_Sym *symp, const char *func)
 			    (u_longlong_t)off, func));
 		}
 
-#ifdef DOODAD
 		err = dt_pid_create_offset_probe(pp->dpp_pr, pp->dpp_dtp, ftp,
 		    symp, off);
-#endif
 
 		if (err == DT_PROC_ERR) {
 			return (dt_pid_error(dtp, pcb, dpr, ftp,
@@ -203,7 +200,6 @@ dt_pid_per_sym(dt_pid_probe_t *pp, const GElf_Sym *symp, const char *func)
 		nmatches++;
 
 	} else if (glob && !isdash) {
-#ifdef DOODAD
 		if (dt_pid_create_glob_offset_probes(pp->dpp_pr,
 		    pp->dpp_dtp, ftp, symp, pp->dpp_name) < 0) {
 			return (dt_pid_error(dtp, pcb, dpr, ftp,
@@ -211,7 +207,6 @@ dt_pid_per_sym(dt_pid_probe_t *pp, const GElf_Sym *symp, const char *func)
 			    "failed to create offset probes in '%s': %s", func,
 			    dtrace_errmsg(dtp, dtrace_errno(dtp))));
 		}
-#endif
 
 		nmatches++;
 	}
@@ -279,7 +274,6 @@ dt_pid_per_mod(void *arg, const prmap_t *pmp, const char *obj)
 		pp->dpp_obj = obj;
 	else
 		pp->dpp_obj++;
-
 #if defined(sun)
 	if (Pxlookup_by_name(pp->dpp_pr, pp->dpp_lmid, obj, ".stret1", &sym,
 	    NULL) == 0)
@@ -305,25 +299,10 @@ dt_pid_per_mod(void *arg, const prmap_t *pmp, const char *obj)
 	else
 		pp->dpp_stret[3] = 0;
 #else
-	if (proc_name2sym(pp->dpp_pr, obj, ".stret1", &sym) == 0)
-		pp->dpp_stret[0] = sym.st_value;
-	else
-		pp->dpp_stret[0] = 0;
-
-	if (proc_name2sym(pp->dpp_pr, obj, ".stret2", &sym) == 0)
-		pp->dpp_stret[1] = sym.st_value;
-	else
-		pp->dpp_stret[1] = 0;
-
-	if (proc_name2sym(pp->dpp_pr, obj, ".stret4", &sym) == 0)
-		pp->dpp_stret[2] = sym.st_value;
-	else
-		pp->dpp_stret[2] = 0;
-
-	if (proc_name2sym(pp->dpp_pr, obj, ".stret8", &sym) == 0)
-		pp->dpp_stret[3] = sym.st_value;
-	else
-		pp->dpp_stret[3] = 0;
+	pp->dpp_stret[0] = 0;
+	pp->dpp_stret[1] = 0;
+	pp->dpp_stret[2] = 0;
+	pp->dpp_stret[3] = 0;
 #endif
 
 	dt_dprintf("%s stret %llx %llx %llx %llx\n", obj,
@@ -345,12 +324,8 @@ dt_pid_per_mod(void *arg, const prmap_t *pmp, const char *obj)
 		 * just fail silently in the hopes that some other object will
 		 * contain the desired symbol.
 		 */
-#if defined(sun)
 		if (Pxlookup_by_name(pp->dpp_pr, pp->dpp_lmid, obj,
 		    pp->dpp_func, &sym, NULL) != 0) {
-#else
-		if (proc_name2sym(pp->dpp_pr, obj, pp->dpp_func, &sym) != 0) {
-#endif
 			if (strcmp("-", pp->dpp_func) == 0) {
 				sym.st_name = 0;
 				sym.st_info =
@@ -390,16 +365,11 @@ dt_pid_per_mod(void *arg, const prmap_t *pmp, const char *obj)
 			return (0);
 #endif
 
-#if defined(sun)
 		(void) Plookup_by_addr(pp->dpp_pr, sym.st_value, pp->dpp_func,
-#else
-		(void) proc_addr2sym(pp->dpp_pr, sym.st_value, pp->dpp_func,
-#endif
 		    DTRACE_FUNCNAMELEN, &sym);
 
 		return (dt_pid_per_sym(pp, &sym, pp->dpp_func));
 	} else {
-#ifdef DOODAD
 		uint_t nmatches = pp->dpp_nmatches;
 
 		if (Psymbol_iter_by_addr(pp->dpp_pr, obj, PR_SYMTAB,
@@ -415,7 +385,6 @@ dt_pid_per_mod(void *arg, const prmap_t *pmp, const char *obj)
 			    BIND_ANY | TYPE_FUNC, dt_pid_sym_filt, pp) == 1)
 				return (1);
 		}
-#endif
 	}
 
 	return (0);
@@ -459,14 +428,16 @@ dt_pid_mod_filt(void *arg, const prmap_t *pmp, const char *obj)
 static const prmap_t *
 dt_pid_fix_mod(dtrace_probedesc_t *pdp, struct ps_prochandle *P)
 {
-#ifdef DOODAD
 	char m[MAXPATHLEN];
+#if defined(sun)
 	Lmid_t lmid = PR_LMID_EVERY;
-	const char *obj;
+#else
+	Lmid_t lmid = 0;
 #endif
+	const char *obj;
 	const prmap_t *pmp;
 
-#ifdef DOODAD
+#if defined(sun)
 	/*
 	 * Pick apart the link map from the library name.
 	 */
@@ -487,10 +458,14 @@ dt_pid_fix_mod(dtrace_probedesc_t *pdp, struct ps_prochandle *P)
 	} else {
 		obj = pdp->dtpd_mod;
 	}
+#else
+	obj = pdp->dtpd_mod;
+#endif
 
 	if ((pmp = Plmid_to_map(P, lmid, obj)) == NULL)
 		return (NULL);
 
+#if defined(sun)
 	(void) Pobjname(P, pmp->pr_vaddr, m, sizeof (m));
 	if ((obj = strrchr(m, '/')) == NULL)
 		obj = &m[0];
@@ -498,11 +473,9 @@ dt_pid_fix_mod(dtrace_probedesc_t *pdp, struct ps_prochandle *P)
 		obj++;
 
 	(void) Plmid(P, pmp->pr_vaddr, &lmid);
+#endif
 
 	dt_pid_objname(pdp->dtpd_mod, sizeof (pdp->dtpd_mod), lmid, obj);
-#else
-pmp = NULL;
-#endif
 
 	return (pmp);
 }
@@ -544,13 +517,8 @@ dt_pid_create_pid_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 			pp.dpp_mod = pdp->dtpd_mod;
 			(void) strcpy(pdp->dtpd_mod, "a.out");
 		} else if (strisglob(pp.dpp_mod) ||
-#if defined(sun)
 		    (aout = Pname_to_map(pp.dpp_pr, "a.out")) == NULL ||
 		    (pmp = Pname_to_map(pp.dpp_pr, pp.dpp_mod)) == NULL ||
-#else
-		    (aout = proc_name2map(pp.dpp_pr, "a.out")) == NULL ||
-		    (pmp = proc_name2map(pp.dpp_pr, pp.dpp_mod)) == NULL ||
-#endif
 		    aout->pr_vaddr != pmp->pr_vaddr) {
 			return (dt_pid_error(dtp, pcb, dpr, NULL, D_PROC_LIB,
 			    "only the a.out module is valid with the "
@@ -569,7 +537,6 @@ dt_pid_create_pid_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 	 * to iterate over each module and compare its name against the
 	 * pattern. An empty module name is treated as '*'.
 	 */
-#ifdef DOODAD
 	if (strisglob(pp.dpp_mod)) {
 		ret = Pobject_iter(pp.dpp_pr, dt_pid_mod_filt, &pp);
 	} else {
@@ -590,7 +557,6 @@ dt_pid_create_pid_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 			ret = dt_pid_per_mod(&pp, pmp, obj);
 		}
 	}
-#endif
 
 	return (ret);
 }
@@ -616,12 +582,8 @@ dt_pid_usdt_mapping(void *data, const prmap_t *pmp, const char *oname)
 	 * run the code to instantiate these providers.
 	 */
 	for (i = 0; i < 2; i++) {
-#if defined(sun)
 		if (Pxlookup_by_name(P, PR_LMID_EVERY, oname, syms[i], &sym,
 		    &sip) != 0) {
-#else
-		if (proc_name2sym(P, oname, syms[i], &sym) != 0) {
-#endif
 			continue;
 		}
 
@@ -632,13 +594,11 @@ dt_pid_usdt_mapping(void *data, const prmap_t *pmp, const char *oname)
 
 		dt_dprintf("lookup of %s succeeded for %s\n", syms[i], mname);
 
-#ifdef DOODAD
 		if (Pread(P, &e_type, sizeof (e_type), pmp->pr_vaddr +
 		    offsetof(Elf64_Ehdr, e_type)) != sizeof (e_type)) {
 			dt_dprintf("read of ELF header failed");
 			continue;
 		}
-#endif
 
 		dh.dofhp_dof = sym.st_value;
 		dh.dofhp_addr = (e_type == ET_EXEC) ? 0 : pmp->pr_vaddr;
@@ -650,7 +610,7 @@ dt_pid_usdt_mapping(void *data, const prmap_t *pmp, const char *oname)
 		    0, mname);
 #endif
 
-#ifdef DOODAD
+#if defined(sun)
 		if (fd == -1 &&
 		    (fd = pr_open(P, "/dev/dtrace/helper", O_RDWR, 0)) < 0) {
 			dt_dprintf("pr_open of helper device failed: %s\n",
@@ -663,7 +623,7 @@ dt_pid_usdt_mapping(void *data, const prmap_t *pmp, const char *oname)
 #endif
 	}
 
-#ifdef DOODAD
+#if defined(sun)
 	if (fd != -1)
 		(void) pr_close(P, fd);
 #endif
@@ -679,9 +639,9 @@ dt_pid_create_usdt_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 	int ret = 0;
 
 	assert(DT_MUTEX_HELD(&dpr->dpr_lock));
-
-#ifdef DOODAD
+#if defined(sun)
 	(void) Pupdate_maps(P);
+#endif
 	if (Pobject_iter(P, dt_pid_usdt_mapping, P) != 0) {
 		ret = -1;
 		(void) dt_pid_error(dtp, pcb, dpr, NULL, D_PROC_USDT,
@@ -692,7 +652,6 @@ dt_pid_create_usdt_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 		    (int)proc_getpid(P), strerror(errno));
 #endif
 	}
-#endif
 
 	/*
 	 * Put the module name in its canonical form.
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c
index 13f5a1a5c6d..664a1225b31 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c
@@ -89,10 +89,15 @@
 #include 
 #include 
 
+#if !defined(sun)
+#include 
+#include 
+#define	SYS_forksys SYS_fork
+#endif
+
 #define	IS_SYS_EXEC(w)	(w == SYS_execve)
 #define	IS_SYS_FORK(w)	(w == SYS_vfork || w == SYS_forksys)
 
-#ifdef DOODAD
 static dt_bkpt_t *
 dt_proc_bpcreate(dt_proc_t *dpr, uintptr_t addr, dt_bkpt_f *func, void *data)
 {
@@ -114,53 +119,62 @@ dt_proc_bpcreate(dt_proc_t *dpr, uintptr_t addr, dt_bkpt_f *func, void *data)
 
 	return (dbp);
 }
-#endif
 
 static void
 dt_proc_bpdestroy(dt_proc_t *dpr, int delbkpts)
 {
-#if defined(sun)
 	int state = Pstate(dpr->dpr_proc);
-#else
-	int state = proc_state(dpr->dpr_proc);
-#endif
 	dt_bkpt_t *dbp, *nbp;
 
 	assert(DT_MUTEX_HELD(&dpr->dpr_lock));
 
 	for (dbp = dt_list_next(&dpr->dpr_bps); dbp != NULL; dbp = nbp) {
-printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
-#ifdef DOODAD
 		if (delbkpts && dbp->dbp_active &&
 		    state != PS_LOST && state != PS_UNDEAD) {
 			(void) Pdelbkpt(dpr->dpr_proc,
 			    dbp->dbp_addr, dbp->dbp_instr);
 		}
-#endif
 		nbp = dt_list_next(dbp);
 		dt_list_delete(&dpr->dpr_bps, dbp);
 		dt_free(dpr->dpr_hdl, dbp);
 	}
 }
 
-#ifdef DOODAD
 static void
 dt_proc_bpmatch(dtrace_hdl_t *dtp, dt_proc_t *dpr)
 {
+#if defined(sun)
 	const lwpstatus_t *psp = &Pstatus(dpr->dpr_proc)->pr_lwp;
+#else
+	unsigned long pc;
+#endif
 	dt_bkpt_t *dbp;
 
 	assert(DT_MUTEX_HELD(&dpr->dpr_lock));
 
+#if !defined(sun)
+	proc_regget(dpr->dpr_proc, REG_PC, &pc);
+	proc_bkptregadj(&pc);
+#endif
+
 	for (dbp = dt_list_next(&dpr->dpr_bps);
 	    dbp != NULL; dbp = dt_list_next(dbp)) {
+#if defined(sun)
 		if (psp->pr_reg[R_PC] == dbp->dbp_addr)
 			break;
+#else
+		if (pc == dbp->dbp_addr)
+			break;
+#endif
 	}
 
 	if (dbp == NULL) {
 		dt_dprintf("pid %d: spurious breakpoint wakeup for %lx\n",
+#if defined(sun)
 		    (int)dpr->dpr_pid, (ulong_t)psp->pr_reg[R_PC]);
+#else
+		    (int)dpr->dpr_pid, pc);
+#endif
 		return;
 	}
 
@@ -170,7 +184,6 @@ dt_proc_bpmatch(dtrace_hdl_t *dtp, dt_proc_t *dpr)
 	dbp->dbp_func(dtp, dpr, dbp->dbp_data);
 	(void) Pxecbkpt(dpr->dpr_proc, dbp->dbp_instr);
 }
-#endif
 
 static void
 dt_proc_bpenable(dt_proc_t *dpr)
@@ -181,12 +194,9 @@ dt_proc_bpenable(dt_proc_t *dpr)
 
 	for (dbp = dt_list_next(&dpr->dpr_bps);
 	    dbp != NULL; dbp = dt_list_next(dbp)) {
-printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
-#ifdef DOODAD
 		if (!dbp->dbp_active && Psetbkpt(dpr->dpr_proc,
 		    dbp->dbp_addr, &dbp->dbp_instr) == 0)
 			dbp->dbp_active = B_TRUE;
-#endif
 	}
 
 	dt_dprintf("breakpoints enabled\n");
@@ -201,12 +211,9 @@ dt_proc_bpdisable(dt_proc_t *dpr)
 
 	for (dbp = dt_list_next(&dpr->dpr_bps);
 	    dbp != NULL; dbp = dt_list_next(dbp)) {
-printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
-#ifdef DOODAD
 		if (dbp->dbp_active && Pdelbkpt(dpr->dpr_proc,
 		    dbp->dbp_addr, dbp->dbp_instr) == 0)
 			dbp->dbp_active = B_FALSE;
-#endif
 	}
 
 	dt_dprintf("breakpoints disabled\n");
@@ -279,7 +286,6 @@ dt_proc_bpmain(dtrace_hdl_t *dtp, dt_proc_t *dpr, const char *fname)
 	dt_proc_stop(dpr, DT_PROC_STOP_MAIN);
 }
 
-#if defined(sun)
 static void
 dt_proc_rdevent(dtrace_hdl_t *dtp, dt_proc_t *dpr, const char *evname)
 {
@@ -336,7 +342,12 @@ dt_proc_rdwatch(dt_proc_t *dpr, rd_event_e event, const char *evname)
 	}
 
 	(void) dt_proc_bpcreate(dpr, rdn.u.bptaddr,
+#if defined(sun)
 	    (dt_bkpt_f *)dt_proc_rdevent, (void *)evname);
+#else
+	    /* XXX ugly */
+	    (dt_bkpt_f *)dt_proc_rdevent, __DECONST(void *, evname));
+#endif
 }
 
 /*
@@ -346,25 +357,34 @@ dt_proc_rdwatch(dt_proc_t *dpr, rd_event_e event, const char *evname)
 static void
 dt_proc_attach(dt_proc_t *dpr, int exec)
 {
+#if defined(sun)
 	const pstatus_t *psp = Pstatus(dpr->dpr_proc);
+#endif
 	rd_err_e err;
 	GElf_Sym sym;
 
 	assert(DT_MUTEX_HELD(&dpr->dpr_lock));
 
 	if (exec) {
+#if defined(sun)
 		if (psp->pr_lwp.pr_errno != 0)
 			return; /* exec failed: nothing needs to be done */
+#endif
 
 		dt_proc_bpdestroy(dpr, B_FALSE);
+#if defined(sun)
 		Preset_maps(dpr->dpr_proc);
+#endif
 	}
-
 	if ((dpr->dpr_rtld = Prd_agent(dpr->dpr_proc)) != NULL &&
 	    (err = rd_event_enable(dpr->dpr_rtld, B_TRUE)) == RD_OK) {
+#if defined(sun)
 		dt_proc_rdwatch(dpr, RD_PREINIT, "RD_PREINIT");
+#endif
 		dt_proc_rdwatch(dpr, RD_POSTINIT, "RD_POSTINIT");
+#if defined(sun)
 		dt_proc_rdwatch(dpr, RD_DLACTIVITY, "RD_DLACTIVITY");
+#endif
 	} else {
 		dt_dprintf("pid %d: failed to enable rtld events: %s\n",
 		    (int)dpr->dpr_pid, dpr->dpr_rtld ? rd_errstr(err) :
@@ -406,6 +426,8 @@ dt_proc_attach(dt_proc_t *dpr, int exec)
 static void
 dt_proc_waitrun(dt_proc_t *dpr)
 {
+printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
+#ifdef DOODAD
 	struct ps_prochandle *P = dpr->dpr_proc;
 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
 
@@ -455,8 +477,8 @@ dt_proc_waitrun(dt_proc_t *dpr)
 	}
 
 	(void) pthread_mutex_lock(&dpr->dpr_lock);
-}
 #endif
+}
 
 typedef struct dt_proc_control_data {
 	dtrace_hdl_t *dpcd_hdl;			/* DTrace handle */
@@ -533,13 +555,18 @@ dt_proc_control(void *arg)
 	(void) Psysexit(P, SYS_forksys, B_TRUE);
 
 	Psync(P);				/* enable all /proc changes */
+#endif
 	dt_proc_attach(dpr, B_FALSE);		/* enable rtld breakpoints */
 
 	/*
 	 * If PR_KLC is set, we created the process; otherwise we grabbed it.
 	 * Check for an appropriate stop request and wait for dt_proc_continue.
 	 */
+#if defined(sun)
 	if (Pstatus(P)->pr_flags & PR_KLC)
+#else
+	if (proc_getflags(P) & PR_KLC)
+#endif
 		dt_proc_stop(dpr, DT_PROC_STOP_CREATE);
 	else
 		dt_proc_stop(dpr, DT_PROC_STOP_GRAB);
@@ -548,20 +575,6 @@ dt_proc_control(void *arg)
 		dt_dprintf("pid %d: failed to set running: %s\n",
 		    (int)dpr->dpr_pid, strerror(errno));
 	}
-#else
-	/*
-	 * If PR_KLC is set, we created the process; otherwise we grabbed it.
-	 * Check for an appropriate stop request and wait for dt_proc_continue.
-	 */
-	if (proc_getflags(P) & PR_KLC)
-		dt_proc_stop(dpr, DT_PROC_STOP_CREATE);
-	else
-		dt_proc_stop(dpr, DT_PROC_STOP_GRAB);
-
-	if (proc_continue(P) != 0)
-		dt_dprintf("pid %d: failed to set running: %s\n",
-		    (int)dpr->dpr_pid, strerror(errno));
-#endif
 
 	(void) pthread_mutex_unlock(&dpr->dpr_lock);
 
@@ -575,14 +588,16 @@ dt_proc_control(void *arg)
 	 * Pwait() (which will return immediately) and do our processing.
 	 */
 	while (!dpr->dpr_quit) {
-#if defined(sun)
 		const lwpstatus_t *psp;
 
+#if defined(sun)
 		if (write(pfd, &wstop, sizeof (wstop)) == -1 && errno == EINTR)
 			continue; /* check dpr_quit and continue waiting */
 #else
 		/* Wait for the process to report status. */
 		proc_wstatus(P);
+		if (errno == EINTR)
+			continue; /* check dpr_quit and continue waiting */
 #endif
 
 		(void) pthread_mutex_lock(&dpr->dpr_lock);
@@ -595,14 +610,13 @@ pwait_locked:
 		}
 #endif
 
-#if defined(sun)
 		switch (Pstate(P)) {
-#else
-		switch (proc_state(P)) {
-#endif
 		case PS_STOP:
-#ifdef DOODAD
+#if defined(sun)
 			psp = &Pstatus(P)->pr_lwp;
+#else
+			psp = proc_getlwpstatus(P);
+#endif
 
 			dt_dprintf("pid %d: proc stopped showing %d/%d\n",
 			    pid, psp->pr_why, psp->pr_what);
@@ -644,7 +658,6 @@ pwait_locked:
 			else if (psp->pr_why == PR_SYSEXIT &&
 			    IS_SYS_EXEC(psp->pr_what))
 				dt_proc_attach(dpr, B_TRUE);
-#endif
 			break;
 
 		case PS_LOST:
@@ -667,12 +680,10 @@ pwait_locked:
 			break;
 		}
 
-#if defined(sun)
 		if (Pstate(P) != PS_UNDEAD && Psetrun(P, 0, 0) == -1) {
 			dt_dprintf("pid %d: failed to set running: %s\n",
 			    (int)dpr->dpr_pid, strerror(errno));
 		}
-#endif
 
 		(void) pthread_mutex_unlock(&dpr->dpr_lock);
 	}
@@ -712,11 +723,7 @@ dt_proc_error(dtrace_hdl_t *dtp, dt_proc_t *dpr, const char *format, ...)
 	va_end(ap);
 
 	if (dpr->dpr_proc != NULL)
-#if defined(sun)
 		Prelease(dpr->dpr_proc, 0);
-#else
-		proc_detach(dpr->dpr_proc, 0);
-#endif
 
 	dt_free(dtp, dpr);
 	(void) dt_set_errno(dtp, EDT_COMPILER);
@@ -804,7 +811,7 @@ dt_proc_destroy(dtrace_hdl_t *dtp, struct ps_prochandle *P)
 #if defined(sun)
 		(void) _lwp_kill(dpr->dpr_tid, SIGCANCEL);
 #else
-		(void) pthread_kill(dpr->dpr_tid, SIGUSR1);
+		pthread_kill(dpr->dpr_tid, SIGUSR1);
 #endif
 
 		/*
@@ -853,11 +860,7 @@ dt_proc_destroy(dtrace_hdl_t *dtp, struct ps_prochandle *P)
 	}
 
 	dt_list_delete(&dph->dph_lrulist, dpr);
-#if defined(sun)
 	Prelease(dpr->dpr_proc, rflag);
-#else
-	proc_detach(dpr->dpr_proc, rflag);
-#endif
 	dt_free(dtp, dpr);
 }
 
@@ -912,18 +915,15 @@ dt_proc_create_thread(dtrace_hdl_t *dtp, dt_proc_t *dpr, uint_t stop)
 #if defined(sun)
 			const psinfo_t *prp = Ppsinfo(dpr->dpr_proc);
 			int stat = prp ? prp->pr_wstat : 0;
-#endif
 			int pid = dpr->dpr_pid;
-
-#if defined(sun)
-			if (Pstate(dpr->dpr_proc) == PS_LOST) {
 #else
-			if (proc_state(dpr->dpr_proc) == PS_LOST) {
+			int stat = proc_getwstat(dpr->dpr_proc);
+			int pid = proc_getpid(dpr->dpr_proc);
 #endif
+			if (proc_state(dpr->dpr_proc) == PS_LOST) {
 				(void) dt_proc_error(dpr->dpr_hdl, dpr,
 				    "failed to control pid %d: process exec'd "
 				    "set-id or unobservable program\n", pid);
-#if defined(sun)
 			} else if (WIFSIGNALED(stat)) {
 				(void) dt_proc_error(dpr->dpr_hdl, dpr,
 				    "failed to control pid %d: process died "
@@ -932,7 +932,6 @@ dt_proc_create_thread(dtrace_hdl_t *dtp, dt_proc_t *dpr, uint_t stop)
 				(void) dt_proc_error(dpr->dpr_hdl, dpr,
 				    "failed to control pid %d: process exited "
 				    "with status %d\n", pid, WEXITSTATUS(stat));
-#endif
 			}
 
 			err = ESRCH; /* cause grab() or create() to fail */
@@ -965,30 +964,25 @@ dt_proc_create(dtrace_hdl_t *dtp, const char *file, char *const *argv,
 
 #if defined(sun)
 	if ((dpr->dpr_proc = Pcreate(file, argv, &err, NULL, 0)) == NULL) {
+#else
+	if ((err = proc_create(file, argv, pcf, child_arg,
+	    &dpr->dpr_proc)) != 0) {
+#endif
 		return (dt_proc_error(dtp, dpr,
 		    "failed to execute %s: %s\n", file, Pcreate_error(err)));
 	}
 
 	dpr->dpr_hdl = dtp;
+#if defined(sun)
 	dpr->dpr_pid = Pstatus(dpr->dpr_proc)->pr_pid;
-
-	(void) Punsetflags(dpr->dpr_proc, PR_RLC);
-	(void) Psetflags(dpr->dpr_proc, PR_KLC);
 #else
-	(void) proc_clearflags(dpr->dpr_proc, PR_RLC);
-	(void) proc_setflags(dpr->dpr_proc, PR_KLC);
-	if ((err = proc_create(file, argv, pcf, child_arg, &dpr->dpr_proc)) != 0)
-		return (dt_proc_error(dtp, dpr,
-		    "failed to execute %s: %s\n", file, strerror(err)));
-	dpr->dpr_hdl = dtp;
 	dpr->dpr_pid = proc_getpid(dpr->dpr_proc);
 #endif
 
-#if defined(sun)
+	(void) Punsetflags(dpr->dpr_proc, PR_RLC);
+	(void) Psetflags(dpr->dpr_proc, PR_KLC);
+
 	if (dt_proc_create_thread(dtp, dpr, dtp->dt_prcmode) != 0)
-#else
-	if (dt_proc_create_thread(dtp, dpr, DT_PROC_STOP_IDLE) != 0)
-#endif
 		return (NULL); /* dt_proc_error() has been called for us */
 
 	dpr->dpr_hash = dph->dph_hash[dpr->dpr_pid & (dph->dph_hashlen - 1)];
@@ -1046,25 +1040,18 @@ dt_proc_grab(dtrace_hdl_t *dtp, pid_t pid, int flags, int nomonitor)
 
 #if defined(sun)
 	if ((dpr->dpr_proc = Pgrab(pid, flags, &err)) == NULL) {
+#else
+	if ((err = proc_attach(pid, flags, &dpr->dpr_proc)) != 0) {
+#endif
 		return (dt_proc_error(dtp, dpr,
 		    "failed to grab pid %d: %s\n", (int)pid, Pgrab_error(err)));
 	}
-#else
-	if ((err = proc_attach(pid, flags, &dpr->dpr_proc)) != 0)
-		return (dt_proc_error(dtp, dpr,
-		    "failed to grab pid %d: %s\n", (int) pid, strerror(err)));
-#endif
 
 	dpr->dpr_hdl = dtp;
 	dpr->dpr_pid = pid;
 
-#if defined(sun)
 	(void) Punsetflags(dpr->dpr_proc, PR_KLC);
 	(void) Psetflags(dpr->dpr_proc, PR_RLC);
-#else
-	(void) proc_clearflags(dpr->dpr_proc, PR_KLC);
-	(void) proc_setflags(dpr->dpr_proc, PR_RLC);
-#endif
 
 	/*
 	 * If we are attempting to grab the process without a monitor
@@ -1185,12 +1172,13 @@ dtrace_proc_create(dtrace_hdl_t *dtp, const char *file, char *const *argv,
 	dt_ident_t *idp = dt_idhash_lookup(dtp->dt_macros, "target");
 	struct ps_prochandle *P = dt_proc_create(dtp, file, argv, pcf, child_arg);
 
-	if (P != NULL && idp != NULL && idp->di_id == 0)
+	if (P != NULL && idp != NULL && idp->di_id == 0) {
 #if defined(sun)
 		idp->di_id = Pstatus(P)->pr_pid; /* $target = created pid */
 #else
 		idp->di_id = proc_getpid(P); /* $target = created pid */
 #endif
+	}
 
 	return (P);
 }
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.h b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.h
index b469f55b847..d1fc7652385 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.h
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.h
@@ -44,9 +44,7 @@ typedef struct dt_proc {
 	dtrace_hdl_t *dpr_hdl;		/* back pointer to libdtrace handle */
 	struct ps_prochandle *dpr_proc;	/* proc handle for libproc calls */
 	char dpr_errmsg[BUFSIZ];	/* error message */
-#if defined(sun)
 	rd_agent_t *dpr_rtld;		/* rtld handle for librtld_db calls */
-#endif
 	pthread_mutex_t dpr_lock;	/* lock for manipulating dpr_hdl */
 	pthread_cond_t dpr_cv;		/* cond for dpr_stop/quit/done */
 	pid_t dpr_pid;			/* pid of process */
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_subr.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_subr.c
index ca35e77a2c6..f4eadbc4f13 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_subr.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_subr.c
@@ -40,6 +40,7 @@
 #include 
 #else
 #include 
+#include 
 #endif
 #include 
 #include 
@@ -963,13 +964,8 @@ dtrace_uaddr2str(dtrace_hdl_t *dtp, pid_t pid,
 
 	dt_proc_lock(dtp, P);
 
-#if defined(sun)
 	if (Plookup_by_addr(P, addr, name, sizeof (name), &sym) == 0) {
 		(void) Pobjname(P, addr, objname, sizeof (objname));
-#else
-	if (proc_addr2sym(P, addr, name, sizeof (name), &sym) == 0) {
-		(void) proc_objname(P, addr, objname, sizeof (objname));
-#endif
 
 		obj = dt_basename(objname);
 
@@ -979,11 +975,7 @@ dtrace_uaddr2str(dtrace_hdl_t *dtp, pid_t pid,
 		} else {
 			(void) snprintf(c, sizeof (c), "%s`%s", obj, name);
 		}
-#if defined(sun)
 	} else if (Pobjname(P, addr, objname, sizeof (objname)) != 0) {
-#else
-	} else if (proc_objname(P, addr, objname, sizeof (objname)) != 0) {
-#endif
 		(void) snprintf(c, sizeof (c), "%s`0x%llx",
 		    dt_basename(objname), addr);
 	} else {
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dtrace.h b/cddl/contrib/opensolaris/lib/libdtrace/common/dtrace.h
index 00b32eebf07..13c27765bd4 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dtrace.h
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dtrace.h
@@ -34,6 +34,9 @@
 #include 
 #include 
 #include 
+#if !defined(sun)
+#include 
+#endif
 
 #ifdef	__cplusplus
 extern "C" {
diff --git a/cddl/contrib/opensolaris/lib/libdtrace/i386/dt_isadep.c b/cddl/contrib/opensolaris/lib/libdtrace/i386/dt_isadep.c
index c1484a40742..ad1c0324de6 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/i386/dt_isadep.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/i386/dt_isadep.c
@@ -35,6 +35,12 @@
 
 #include 
 
+#if !defined(sun)
+#define PR_MODEL_ILP32	1
+#define PR_MODEL_LP64	2
+#include 
+#endif
+
 #define	DT_POPL_EBP	0x5d
 #define	DT_RET		0xc3
 #define	DT_RET16	0xc2
@@ -78,8 +84,17 @@ dt_pid_has_jump_table(struct ps_prochandle *P, dtrace_hdl_t *dtp,
 {
 	ulong_t i;
 	int size;
+#if defined(sun)
 	pid_t pid = Pstatus(P)->pr_pid;
 	char dmodel = Pstatus(P)->pr_dmodel;
+#else
+	pid_t pid = proc_getpid(P);
+#if __i386__
+	char dmodel = PR_MODEL_ILP32;
+#elif __amd64__
+	char dmodel = PR_MODEL_LP64;
+#endif
+#endif
 
 	/*
 	 * Take a pass through the function looking for a register-dependant
@@ -98,6 +113,7 @@ dt_pid_has_jump_table(struct ps_prochandle *P, dtrace_hdl_t *dtp,
 			return (1);
 		}
 
+#ifdef notyet
 		/*
 		 * Register-dependant jmp instructions start with a 0xff byte
 		 * and have the modrm.reg field set to 4. They can have an
@@ -110,6 +126,7 @@ dt_pid_has_jump_table(struct ps_prochandle *P, dtrace_hdl_t *dtp,
 			    ftp->ftps_func, i);
 			return (1);
 		}
+#endif
 	}
 
 	return (0);
@@ -123,8 +140,17 @@ dt_pid_create_return_probe(struct ps_prochandle *P, dtrace_hdl_t *dtp,
 	uint8_t *text;
 	ulong_t i, end;
 	int size;
+#if defined(sun)
 	pid_t pid = Pstatus(P)->pr_pid;
 	char dmodel = Pstatus(P)->pr_dmodel;
+#else
+	pid_t pid = proc_getpid(P);
+#if __i386__
+	char dmodel = PR_MODEL_ILP32;
+#elif __amd64__
+	char dmodel = PR_MODEL_LP64;
+#endif
+#endif
 
 	/*
 	 * We allocate a few extra bytes at the end so we don't have to check
@@ -275,8 +301,17 @@ dt_pid_create_offset_probe(struct ps_prochandle *P, dtrace_hdl_t *dtp,
 		uint8_t *text;
 		ulong_t i;
 		int size;
+#if defined(sun)
 		pid_t pid = Pstatus(P)->pr_pid;
 		char dmodel = Pstatus(P)->pr_dmodel;
+#else
+		pid_t pid = proc_getpid(P);
+#if __i386__
+		char dmodel = PR_MODEL_ILP32;
+#elif __amd64__
+		char dmodel = PR_MODEL_LP64;
+#endif
+#endif
 
 		if ((text = malloc(symp->st_size)) == NULL) {
 			dt_dprintf("mr sparkle: malloc() failed\n");
@@ -349,8 +384,17 @@ dt_pid_create_glob_offset_probes(struct ps_prochandle *P, dtrace_hdl_t *dtp,
 	uint8_t *text;
 	int size;
 	ulong_t i, end = symp->st_size;
+#if defined(sun)
 	pid_t pid = Pstatus(P)->pr_pid;
 	char dmodel = Pstatus(P)->pr_dmodel;
+#else
+	pid_t pid = proc_getpid(P);
+#if __i386__
+	char dmodel = PR_MODEL_ILP32;
+#elif __amd64__
+	char dmodel = PR_MODEL_LP64;
+#endif
+#endif
 
 	ftp->ftps_type = DTFTP_OFFSETS;
 	ftp->ftps_pc = (uintptr_t)symp->st_value;
diff --git a/cddl/lib/libdtrace/Makefile b/cddl/lib/libdtrace/Makefile
index 7e500c71e73..2cc9564f6b3 100644
--- a/cddl/lib/libdtrace/Makefile
+++ b/cddl/lib/libdtrace/Makefile
@@ -18,6 +18,7 @@ SRCS=		dt_aggregate.c \
 		dt_grammar.y \
 		dt_handle.c \
 		dt_ident.c \
+		dt_isadep.c \
 		dt_inttab.c \
 		dt_lex.l \
 		dt_link.c \
@@ -41,7 +42,8 @@ SRCS=		dt_aggregate.c \
 		dt_subr.c \
 		dt_work.c \
 		dt_xlator.c \
-		gmatch.c
+		gmatch.c \
+		dis_tables.c
 
 DSRCS=		errno.d			\
 		psinfo.d		\
@@ -50,7 +52,8 @@ DSRCS=		errno.d			\
 
 WARNS?=		1
 
-CFLAGS+=	-I${.OBJDIR} \
+CFLAGS+=	-I${.OBJDIR} -I${.CURDIR} \
+		-I${.CURDIR}/../../../sys/cddl/dev/dtrace/${MACHINE_ARCH} \
 		-I${.CURDIR}/../../../sys/cddl/compat/opensolaris \
 		-I${.CURDIR}/../../../cddl/compat/opensolaris/include \
 		-I${OPENSOLARIS_USR_DISTDIR}/head \
@@ -61,14 +64,21 @@ CFLAGS+=	-I${.OBJDIR} \
 #CFLAGS+=	-DYYDEBUG
 
 .if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
-CFLAGS+=	-I${OPENSOLARIS_SYS_DISTDIR}/uts/intel
+CFLAGS+=	-I${OPENSOLARIS_SYS_DISTDIR}/uts/intel -DDIS_MEM
+.PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/i386
+.PATH:		${.CURDIR}/../../../sys/cddl/dev/dtrace/${MACHINE_ARCH}
 .elif ${MACHINE_ARCH} == "sparc64"
 CFLAGS+=	-I${OPENSOLARIS_SYS_DISTDIR}/uts/sparc
+.PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/sparc
 .else
 # temporary hack
 CFLAGS+=	-I${OPENSOLARIS_SYS_DISTDIR}/uts/intel
 .endif
 
+.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+DSRCS+=		regs_x86.d
+.endif
+
 LFLAGS+=-l
 
 YFLAGS+=-d
diff --git a/cddl/lib/libdtrace/libproc_compat.h b/cddl/lib/libdtrace/libproc_compat.h
new file mode 100644
index 00000000000..a561157c0ba
--- /dev/null
+++ b/cddl/lib/libdtrace/libproc_compat.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2010 The FreeBSD Foundation 
+ * All rights reserved. 
+ * 
+ * This software was developed by Rui Paulo under sponsorship from the
+ * FreeBSD Foundation. 
+ *  
+ * 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. 
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. 
+ *
+ * $FreeBSD$
+ */
+
+/*
+ * Compatibility functions between Solaris libproc and FreeBSD libproc.
+ * Functions sorted alphabetically.
+ */
+#define	PR_LMID_EVERY 0
+#define	Psetrun(p, a1, a2) proc_continue((p))
+#define	Pxlookup_by_addr(p, a, n, s, sym, i) \
+    proc_addr2sym(p, a, n, s, sym)
+#define	Pxlookup_by_name(p, l, s1, s2, sym, a) \
+    proc_name2sym((p), (s1), (s2), (sym))
+#define	Paddr_to_map proc_addr2map
+#define	Pcreate_error strerror
+#define	Pdelbkpt proc_bkptdel
+#define	Pgrab_error strerror
+#define	Plmid_to_map(p, l, o) proc_obj2map((p), (o))
+#define	Plookup_by_addr proc_addr2sym
+#define	Pname_to_map proc_name2map
+#define	Pobject_iter proc_iter_objs
+#define	Pobjname proc_objname
+#define	Pread proc_read
+#define	Prd_agent proc_rdagent
+#define	Prelease proc_detach
+#define	Psetbkpt proc_bkptset
+#define	Psetflags proc_setflags
+#define	Pstate proc_state
+#define	Pstate proc_state
+#define	Psymbol_iter_by_addr proc_iter_symbyaddr
+#define	Punsetflags proc_clearflags
+#define	Pupdate_maps(p) do { } while (0)
+#define	Pupdate_syms proc_updatesyms
+#define	Pxecbkpt proc_bkptexec
diff --git a/cddl/lib/libdtrace/regs_x86.d b/cddl/lib/libdtrace/regs_x86.d
new file mode 100644
index 00000000000..7dce1971764
--- /dev/null
+++ b/cddl/lib/libdtrace/regs_x86.d
@@ -0,0 +1,121 @@
+/*                                                                              
+ * 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
+ *
+ * Portions Copyright 2009 Stacey Son sson@FreeBSD.org
+ *
+ * $FreeBSD$
+ */
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#pragma ident	"@(#)regs.d.in	1.1	04/09/28 SMI"
+
+inline int R_GS = 0;
+#pragma D binding "1.0" R_GS
+inline int R_FS = 1;
+#pragma D binding "1.0" R_FS
+inline int R_ES = 2;
+#pragma D binding "1.0" R_ES
+inline int R_DS = 3;
+#pragma D binding "1.0" R_DS
+
+inline int R_EDI = 4;
+#pragma D binding "1.0" R_EDI
+inline int R_ESI = 5;
+#pragma D binding "1.0" R_ESI
+inline int R_EBP = 6;
+#pragma D binding "1.0" R_EBP
+inline int R_ESP = 7;
+#pragma D binding "1.0" R_ESP
+inline int R_EBX = 8;
+#pragma D binding "1.0" R_EBX
+inline int R_EDX = 9;
+#pragma D binding "1.0" R_EDX
+inline int R_ECX = 10;
+#pragma D binding "1.0" R_ECX
+inline int R_EAX = 11;
+#pragma D binding "1.0" R_EAX
+
+inline int R_TRAPNO = 12;
+#pragma D binding "1.0" R_TRAPNO
+inline int R_ERR = 13;
+#pragma D binding "1.0" R_ERR
+inline int R_EIP = 14;
+#pragma D binding "1.0" R_EIP
+inline int R_CS = 15;
+#pragma D binding "1.0" R_CS
+inline int R_EFL = 16;
+#pragma D binding "1.0" R_EFL
+inline int R_UESP = 17;
+#pragma D binding "1.0" R_UESP
+inline int R_SS = 18;
+#pragma D binding "1.0" R_SS
+
+inline int R_PC = R_EIP;
+#pragma D binding "1.0" R_PC
+inline int R_SP = R_UESP;
+#pragma D binding "1.0" R_SP
+inline int R_PS = R_EFL;
+#pragma D binding "1.0" R_PS
+inline int R_R0 = R_EAX;
+#pragma D binding "1.0" R_R0
+inline int R_R1 = R_EBX;
+#pragma D binding "1.0" R_R1
+
+inline int R_RSP = 18 + 1 + 20;
+#pragma D binding "1.0" R_RSP
+inline int R_RFL = 18 + 1 + 19;
+#pragma D binding "1.0" R_RFL
+inline int R_RIP = 18 + 1 + 17;
+#pragma D binding "1.0" R_RIP
+inline int R_RAX = 18 + 1 + 14;
+#pragma D binding "1.0" R_RAX
+inline int R_RCX = 18 + 1 + 13;
+#pragma D binding "1.0" R_RCX
+inline int R_RDX = 18 + 1 + 12;
+#pragma D binding "1.0" R_RDX
+inline int R_RBX = 18 + 1 + 11;
+#pragma D binding "1.0" R_RBX
+inline int R_RBP = 18 + 1 + 10;
+#pragma D binding "1.0" R_RBP
+inline int R_RSI = 18 + 1 + 9;
+#pragma D binding "1.0" R_RSI
+inline int R_RDI = 18 + 1 + 8;
+#pragma D binding "1.0" R_RDI
+inline int R_R8 = 18 + 1 + 7;
+#pragma D binding "1.0" R_R8
+inline int R_R9 = 18 + 1 + 6;
+#pragma D binding "1.0" R_R9
+inline int R_R10 = 18 + 1 + 5;
+#pragma D binding "1.0" R_R10
+inline int R_R11 = 18 + 1 + 4;
+#pragma D binding "1.0" R_R11
+inline int R_R12 = 18 + 1 + 3;
+#pragma D binding "1.0" R_R12
+inline int R_R13 = 18 + 1 + 2;
+#pragma D binding "1.0" R_R13
+inline int R_R14 = 18 + 1 + 1;
+#pragma D binding "1.0" R_R14
+inline int R_R15 = 18 + 1 + 0;
+#pragma D binding "1.0" R_R15
+

From e60cf26f21f89482b6c68d14e52b63b197d9d6bf Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 11:58:08 +0000
Subject: [PATCH 0121/1624] Port the DTrace helper ioctls to FreeBSD and add a
 helper member to dof_helper_t (needed by drti.o).

Sponsored by:	The FreeBSD Foundation
---
 .../contrib/opensolaris/uts/common/sys/dtrace.h    | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h b/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h
index 82b97a37368..1e20f566540 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h
@@ -1322,15 +1322,24 @@ typedef struct {
  * helpers and should no longer be used.  No other ioctls are valid on the
  * helper minor node.
  */
+#if defined(sun)
 #define	DTRACEHIOC		(('d' << 24) | ('t' << 16) | ('h' << 8))
 #define	DTRACEHIOC_ADD		(DTRACEHIOC | 1)	/* add helper */
 #define	DTRACEHIOC_REMOVE	(DTRACEHIOC | 2)	/* remove helper */
 #define	DTRACEHIOC_ADDDOF	(DTRACEHIOC | 3)	/* add helper DOF */
+#else
+#define	DTRACEHIOC_ADD		_IOWR('z', 1, dof_hdr_t)/* add helper */
+#define	DTRACEHIOC_REMOVE	_IOW('z', 2, int)	/* remove helper */
+#define	DTRACEHIOC_ADDDOF	_IOWR('z', 3, dof_helper_t)/* add helper DOF */
+#endif
 
 typedef struct dof_helper {
 	char dofhp_mod[DTRACE_MODNAMELEN];	/* executable or library name */
 	uint64_t dofhp_addr;			/* base address of object */
 	uint64_t dofhp_dof;			/* address of helper DOF */
+#if !defined(sun)
+	int gen;
+#endif
 } dof_helper_t;
 
 #define	DTRACEMNR_DTRACE	"dtrace"	/* node for DTrace ops */
@@ -2219,10 +2228,11 @@ extern void dtrace_vtime_enable(void);
 extern void dtrace_vtime_disable(void);
 
 struct regs;
+struct reg;
 
 #if defined(sun)
-extern int (*dtrace_pid_probe_ptr)(struct regs *);
-extern int (*dtrace_return_probe_ptr)(struct regs *);
+extern int (*dtrace_pid_probe_ptr)(struct reg *);
+extern int (*dtrace_return_probe_ptr)(struct reg *);
 extern void (*dtrace_fasttrap_fork_ptr)(proc_t *, proc_t *);
 extern void (*dtrace_fasttrap_exec_ptr)(proc_t *);
 extern void (*dtrace_fasttrap_exit_ptr)(proc_t *);

From 87c8f7aa3a46118212b99f0d58b18aa93c06b02a Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 13:15:56 +0000
Subject: [PATCH 0122/1624] Import dtruss from Brendan Gregg's DTraceToolkit.

Sponsored by:	The FreeBSD Foundation
---
 dtruss | 467 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 467 insertions(+)
 create mode 100755 dtruss

diff --git a/dtruss b/dtruss
new file mode 100755
index 00000000000..f4b5e45a30d
--- /dev/null
+++ b/dtruss
@@ -0,0 +1,467 @@
+#!/usr/bin/sh
+#
+# dtruss - print process system call time details.
+#          Written using DTrace (Solaris 10 3/05).
+#
+# $Id: dtruss 9 2007-08-07 10:21:07Z brendan $
+#
+# USAGE: dtruss [-acdeflhoLs] [-t syscall] { -p PID | -n name | command }
+#
+#		-p PID		# examine this PID
+#		-n name		# examine this process name
+#		-t syscall	# examine this syscall only
+#		-a		# print all details
+#		-c		# print system call counts
+#		-d		# print relative timestamps (us)
+#		-e		# print elapsed times (us)
+#		-f		# follow children as they are forked
+#		-l		# force printing of pid/lwpid per line
+#		-o		# print on cpu times (us)
+#		-s		# print stack backtraces
+#		-L		# don't print pid/lwpid per line
+#		-b bufsize	# dynamic variable buf size (default is "4m")
+#  eg,
+#		dtruss df -h	# run and examine the "df -h" command
+#		dtruss -p 1871	# examine PID 1871
+#		dtruss -n tar	# examine all processes called "tar"
+#		dtruss -f test.sh	# run test.sh and follow children
+#
+# See the man page dtruss(1M) for further details.
+#
+# SEE ALSO: procsystime    # DTraceToolkit
+#           dapptrace      # DTraceToolkit
+#           truss
+#
+# COPYRIGHT: Copyright (c) 2005, 2006, 2007 Brendan Gregg.
+#
+# 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 Docs/cddl1.txt
+#  or http://www.opensolaris.org/os/licensing.
+#  See the License for the specific language governing permissions
+#  and limitations under the License.
+#
+# CDDL HEADER END
+#
+# TODO: Track signals, more output formatting.
+#
+# 29-Apr-2005   Brendan Gregg   Created this.
+# 09-May-2005      "      " 	Fixed evaltime (thanks Adam L.)
+# 16-May-2005	   "      "	Added -t syscall tracing.
+# 17-Jun-2005	   "      "	Added -s stack backtraces.
+# 17-Jun-2005	   "      "	Last update.
+# 29-Jun-2007	   "      "	Used progenyof() (thanks Aaron Gutman).
+# 06-Aug-2007	   "      "	Various updates.
+#
+
+
+##############################
+# --- Process Arguments ---
+#
+
+### Default variables
+opt_pid=0; opt_name=0; pid=0; pname="."; opt_elapsed=0; opt_cpu=0
+opt_counts=0; opt_relative=0; opt_printid=0; opt_follow=0; opt_command=0
+command=""; opt_buf=0; buf="4m"; opt_trace=0; trace="."; opt_stack=0
+
+### Process options
+while getopts ab:cdefhln:op:st:L name
+do
+        case $name in
+	b)	opt_buf=1; buf=$OPTARG ;;
+        p)      opt_pid=1; pid=$OPTARG ;;
+        n)      opt_name=1; pname=$OPTARG ;;
+        t)      opt_trace=1; trace=$OPTARG ;;
+	a)	opt_counts=1; opt_relative=1; opt_elapsed=1; opt_follow=1
+		opt_printid=1; opt_cpu=1 ;;
+	c)	opt_counts=1 ;;
+	d)	opt_relative=1 ;;
+	e)	opt_elapsed=1 ;;
+	f)	opt_follow=1 ;;
+	l)	opt_printid=1 ;;
+	o)	opt_cpu=1 ;;
+	L)	opt_printid=-1 ;;
+	s)	opt_stack=-1 ;;
+        h|?)    cat <<-END >&2
+		USAGE: dtruss [-acdefholLs] [-t syscall] { -p PID | -n name | command }
+
+		          -p PID          # examine this PID
+		          -n name         # examine this process name
+		          -t syscall      # examine this syscall only
+		          -a              # print all details
+		          -c              # print syscall counts
+		          -d              # print relative times (us)
+		          -e              # print elapsed times (us)
+		          -f              # follow children (-p or cmd only)
+		          -l              # force printing pid/lwpid
+		          -o              # print on cpu times
+		          -s              # print stack backtraces
+		          -L              # don't print pid/lwpid
+		          -b bufsize      # dynamic variable buf size
+		   eg,
+		       dtruss df -h       # run and examine "df -h"
+		       dtruss -p 1871     # examine PID 1871
+		       dtruss -n tar      # examine all processes called "tar"
+		       dtruss -f test.sh  # run test.sh and follow children
+		END
+		exit 1
+        esac
+done
+shift `expr $OPTIND - 1`
+
+### Option logic
+if [ $opt_pid -eq 0 -a $opt_name -eq 0 ]; then
+	opt_command=1
+	if [ "$*" = "" ]; then
+		$0 -h
+		exit
+	fi
+	command="$*"	# yes, I meant $*!
+fi
+if [ $opt_follow -eq 1 -o $opt_name -eq 1 ]; then
+	if [ $opt_printid -ne -1 ]; then
+		opt_printid=1
+	else
+		opt_printid=0
+	fi
+fi
+if [ $opt_follow -eq 1 -a $opt_name -eq 1 ]; then
+	echo "ERROR: -f option cannot be used with -n (use -p or cmd instead)."
+	exit 1
+fi
+
+### Option translation
+if [ "$trace" = "exec" ]; then trace="exece"; fi
+if [ "$trace" = "time" ]; then trace="gtime"; fi
+if [ "$trace" = "exit" ]; then trace="rexit"; fi
+
+
+#################################
+# --- Main Program, DTrace ---
+#
+
+### Define D Script
+dtrace='
+#pragma D option quiet
+#pragma D option switchrate=10
+ 
+/*
+ * Command line arguments
+ */
+inline int OPT_command   = '$opt_command';
+inline int OPT_follow    = '$opt_follow';
+inline int OPT_printid   = '$opt_printid';
+inline int OPT_relative  = '$opt_relative';
+inline int OPT_elapsed   = '$opt_elapsed';
+inline int OPT_cpu       = '$opt_cpu';
+inline int OPT_counts    = '$opt_counts';
+inline int OPT_pid       = '$opt_pid';
+inline int OPT_name      = '$opt_name';
+inline int OPT_trace     = '$opt_trace';
+inline int OPT_stack     = '$opt_stack';
+inline string NAME       = "'$pname'";
+inline string TRACE      = "'$trace'";
+
+dtrace:::BEGIN 
+{
+	/* print header */
+	OPT_printid  ? printf("%-9s  ", "PID/LWP") : 1;
+	OPT_relative ? printf("%8s ", "RELATIVE") : 1;
+	OPT_elapsed  ? printf("%7s ", "ELAPSD") : 1;
+	OPT_cpu      ? printf("%6s ", "CPU") : 1;
+	printf("SYSCALL(args) \t\t = return\n");
+}
+
+/*
+ * Save syscall entry info
+ */
+syscall:::entry
+/((OPT_command || OPT_pid) && pid == $target) || 
+ (OPT_name && execname == NAME) ||
+ (OPT_follow && progenyof($target))/
+{
+	/* set start details */
+	self->start = timestamp;
+	self->vstart = vtimestamp;
+	self->arg0 = arg0;
+	self->arg1 = arg1;
+	self->arg2 = arg2;
+
+	/* count occurances */
+	OPT_counts == 1 ? @Counts[probefunc] = count() : 1;
+}
+
+/*
+ * Follow children
+ */
+syscall::fork*:return
+/(OPT_follow && progenyof($target)) && (!OPT_trace || (TRACE == probefunc))/
+{
+	/* print output */
+	self->code = errno == 0 ? "" : "Err#";
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d:  ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d:  ", 0) : 1;
+	OPT_cpu      ? printf("%6d ", 0) : 1;
+	printf("%s(0x%X, 0x%X, 0x%X)\t\t = %d %s%d\n", probefunc,
+	    self->arg0, self->arg1, self->arg2, (int)arg0, self->code,
+	    (int)errno);
+}
+
+/*
+ * Check for syscall tracing
+ */
+syscall:::entry
+/OPT_trace && probefunc != TRACE/
+{
+	/* drop info */
+	self->start = 0;
+	self->vstart = 0;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/*
+ * Print return data
+ */
+
+/*
+ * The following code is written in an intentionally repetative way.
+ * The first versions had no code redundancies, but performed badly during
+ * benchmarking. The priority here is speed, not cleverness. I know there
+ * are many obvious shortcuts to this code, I have tried them. This style has
+ * shown in benchmarks to be the fastest (fewest probes fired, fewest actions).
+ */
+
+/* print 3 args, return as hex */
+syscall::lwp_sigmask:return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s(0x%X, 0x%X, 0x%X)\t\t = 0x%X %s%d\n", probefunc,
+	    (int)self->arg0, self->arg1, self->arg2, (int)arg0,
+	    self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* print 3 args, arg0 as a string */
+syscall::stat*:return, 
+syscall::lstat*:return, 
+syscall::open*:return,
+syscall::resolvepath:return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu      ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s(\"%S\", 0x%X, 0x%X)\t\t = %d %s%d\n", probefunc,
+	    copyinstr(self->arg0), self->arg1, self->arg2, (int)arg0,
+	    self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* print 3 args, arg1 as a string */
+syscall::write:return,
+syscall::pwrite:return,
+syscall::*read*:return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu      ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s(0x%X, \"%S\", 0x%X)\t\t = %d %s%d\n", probefunc, self->arg0,
+	    stringof(copyin(self->arg1, self->arg2)), self->arg2, (int)arg0,
+	    self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* print 0 arg output */
+syscall::gtime:return,
+syscall::*fork*:return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu      ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s()\t\t = %d %s%d\n", probefunc,
+	    (int)arg0, self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* print 1 arg output */
+syscall::brk:return,
+syscall::times:return,
+syscall::stime:return,
+syscall::close:return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu      ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s(0x%X)\t\t = %d %s%d\n", probefunc, self->arg0,
+	    (int)arg0, self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* print 2 arg output */
+syscall::utime:return,
+syscall::munmap:return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu      ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s(0x%X, 0x%X)\t\t = %d %s%d\n", probefunc, self->arg0,
+	    self->arg1, (int)arg0, self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* print 3 arg output - default */
+syscall:::return
+/self->start/
+{
+	/* calculate elapsed time */
+	this->elapsed = timestamp - self->start;
+	self->start = 0;
+	this->cpu = vtimestamp - self->vstart;
+	self->vstart = 0;
+	self->code = errno == 0 ? "" : "Err#";
+ 
+	/* print optional fields */
+	OPT_printid  ? printf("%6d/%d:  ", pid, tid) : 1;
+	OPT_relative ? printf("%8d ", vtimestamp/1000) : 1;
+	OPT_elapsed  ? printf("%7d ", this->elapsed/1000) : 1;
+	OPT_cpu      ? printf("%6d ", this->cpu/1000) : 1;
+ 
+	/* print main data */
+	printf("%s(0x%X, 0x%X, 0x%X)\t\t = %d %s%d\n", probefunc, self->arg0,
+	    self->arg1, self->arg2, (int)arg0, self->code, (int)errno);
+	OPT_stack ? ustack()    : 1;
+	OPT_stack ? trace("\n") : 1;
+	self->arg0 = 0;
+	self->arg1 = 0;
+	self->arg2 = 0;
+}
+
+/* program exited */
+proc:::exit
+/(OPT_command || OPT_pid) && pid == $target/
+{
+	exit(0);
+}
+
+/* print counts */
+dtrace:::END
+{
+	OPT_counts == 1 ? printf("\n%-32s %16s\n", "CALL", "COUNT") : 1;
+	OPT_counts == 1 ? printa("%-32s %@16d\n", @Counts) : 1;
+}
+'
+
+### Run DTrace
+if [ $opt_command -eq 1 ]; then
+	/usr/sbin/dtrace -x dynvarsize=$buf -x evaltime=exec -n "$dtrace" \
+	    -c "$command" >&2
+elif [ $opt_pid -eq 1 ]; then
+	/usr/sbin/dtrace -x dynvarsize=$buf -n "$dtrace" -p "$pid" >&2
+else
+	/usr/sbin/dtrace -x dynvarsize=$buf -n "$dtrace" >&2
+fi

From 9510083e01984af6328f9e167c2fcf72525bc8a8 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 13:42:12 +0000
Subject: [PATCH 0123/1624] Add libelf to the prebuild libs.

This is needed for the DTrace instrumentation object.

Sponsored by:	The FreeBSD Foundation
---
 Makefile.inc1 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index d2581c573ec..1e2bec68ad6 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -1142,7 +1142,7 @@ gnu/lib/libgcc__L: lib/libc__L
 _prebuild_libs=	${_kerberos5_lib_libasn1} ${_kerberos5_lib_libheimntlm} \
 		${_kerberos5_lib_libhx509} ${_kerberos5_lib_libkrb5} \
 		${_kerberos5_lib_libroken} \
-		lib/libbz2 lib/libcom_err lib/libcrypt \
+		lib/libbz2 lib/libcom_err lib/libcrypt lib/libelf \
 		lib/libexpat lib/libfetch \
 		${_lib_libgssapi} ${_lib_libipx} \
 		lib/libkiconv lib/libkvm lib/liblzma lib/libmd \

From 513bdf9ac019c983b2bb0352b867d811f5d28a6e Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 13:48:04 +0000
Subject: [PATCH 0124/1624] Link drti.o with a PIC version of libelf. This is
 needed because drti.o depends on libelf and this avoids linking every other
 drti.o program (namely programs with USDT probes) with libelf.

Sponsored by:	The FreeBSD Foundation
---
 cddl/lib/drti/Makefile | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/cddl/lib/drti/Makefile b/cddl/lib/drti/Makefile
index ffd161c89d2..57b161f74e1 100644
--- a/cddl/lib/drti/Makefile
+++ b/cddl/lib/drti/Makefile
@@ -8,13 +8,20 @@ FILESOWN=	${LIBOWN}
 FILESGRP=	${LIBGRP}
 FILESMODE=	${LIBMODE}
 FILESDIR=	${LIBDIR}/dtrace
-CLEANFILES=	${FILES}
+CLEANFILES=	${FILES} ${FILES}.tmp
 
 CFLAGS+=	-I${.CURDIR}/../../../sys/cddl/compat/opensolaris \
 		-I${.CURDIR}/../../../cddl/compat/opensolaris/include \
 		-I${OPENSOLARIS_USR_DISTDIR}/head \
 		-I${OPENSOLARIS_USR_DISTDIR}/lib/libctf/common \
 		-I${OPENSOLARIS_USR_DISTDIR}/lib/libdtrace/common \
-		-I${OPENSOLARIS_SYS_DISTDIR}/uts/common
+		-I${OPENSOLARIS_SYS_DISTDIR}/uts/common \
+		-DPIC -fpic
+
+.c.o:
+	${CC} ${CFLAGS} -c ${.IMPSRC}
+	mv ${FILES} ${FILES}.tmp
+	${LD} -o ${FILES} -r ${FILES}.tmp ${LIBELF_PIC}
+	rm -f ${FILES}.tmp
 
 .include 

From 6544c9194119a741f3ea75ad3d9d4c4609f01974 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 13:54:33 +0000
Subject: [PATCH 0125/1624] Port plockstat to FreeBSD. This will be connected
 to the build later.

Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/cmd/plockstat/plockstat.c     | 47 ++++++++++++++-----
 cddl/usr.sbin/plockstat/Makefile              | 27 +++++++++++
 2 files changed, 63 insertions(+), 11 deletions(-)
 create mode 100644 cddl/usr.sbin/plockstat/Makefile

diff --git a/cddl/contrib/opensolaris/cmd/plockstat/plockstat.c b/cddl/contrib/opensolaris/cmd/plockstat/plockstat.c
index 0dfd7004fed..aa2c1f9d2db 100644
--- a/cddl/contrib/opensolaris/cmd/plockstat/plockstat.c
+++ b/cddl/contrib/opensolaris/cmd/plockstat/plockstat.c
@@ -24,7 +24,9 @@
  * Use is subject to license terms.
  */
 
+#if defined(sun)
 #pragma ident	"%Z%%M%	%I%	%E% SMI"
+#endif
 
 #include 
 #include 
@@ -41,6 +43,7 @@
 #include 
 #include 
 #include 
+#include 
 
 static char *g_pname;
 static dtrace_hdl_t *g_dtp;
@@ -502,7 +505,12 @@ getsym(struct ps_prochandle *P, uintptr_t addr, char *buf, size_t size,
 {
 	char name[256];
 	GElf_Sym sym;
+#if defined(sun)
 	prsyminfo_t info;
+#else
+	prmap_t *map;
+	int info; /* XXX unused */
+#endif
 	size_t len;
 
 	if (P == NULL || Pxlookup_by_addr(P, addr, name, sizeof (name),
@@ -510,6 +518,7 @@ getsym(struct ps_prochandle *P, uintptr_t addr, char *buf, size_t size,
 		(void) snprintf(buf, size, "%#lx", addr);
 		return (0);
 	}
+#if defined(sun)
 	if (info.prs_object == NULL)
 		info.prs_object = "";
 
@@ -520,15 +529,19 @@ getsym(struct ps_prochandle *P, uintptr_t addr, char *buf, size_t size,
 	}
 
 	len = snprintf(buf, size, "%s`%s", info.prs_object, info.prs_name);
+#else
+	map = proc_addr2map(P, addr);
+	len = snprintf(buf, size, "%s`%s", map->pr_mapname, name);
+#endif
 	buf += len;
 	size -= len;
 
 	if (sym.st_value != addr)
 		len = snprintf(buf, size, "+%#lx", addr - sym.st_value);
 
-	if (nolocks && strcmp("libc.so.1", info.prs_object) == 0 &&
-	    (strstr("mutex", info.prs_name) == 0 ||
-	    strstr("rw", info.prs_name) == 0))
+	if (nolocks && strcmp("libc.so.1", map->pr_mapname) == 0 &&
+	    (strstr("mutex", name) == 0 ||
+	    strstr("rw", name) == 0))
 		return (-1);
 
 	return (0);
@@ -655,8 +668,13 @@ process_aggregate(const dtrace_aggdata_t **aggsdata, int naggvars, void *arg)
 static void
 prochandler(struct ps_prochandle *P, const char *msg, void *arg)
 {
+#if defined(sun)
 	const psinfo_t *prp = Ppsinfo(P);
 	int pid = Pstatus(P)->pr_pid;
+#else
+	int pid = proc_getpid(P);
+	int wstat = proc_getwstat(P);
+#endif
 	char name[SIG2STR_MAX];
 
 	if (msg != NULL) {
@@ -674,13 +692,13 @@ prochandler(struct ps_prochandle *P, const char *msg, void *arg)
 		 * When /proc provides a stable pr_wstat in the status file,
 		 * this code can be improved by examining this new pr_wstat.
 		 */
-		if (prp != NULL && WIFSIGNALED(prp->pr_wstat)) {
+		if (WIFSIGNALED(wstat)) {
 			notice("pid %d terminated by %s\n", pid,
-			    proc_signame(WTERMSIG(prp->pr_wstat),
+			    proc_signame(WTERMSIG(wstat),
 			    name, sizeof (name)));
-		} else if (prp != NULL && WEXITSTATUS(prp->pr_wstat) != 0) {
+		} else if (WEXITSTATUS(wstat) != 0) {
 			notice("pid %d exited with status %d\n",
-			    pid, WEXITSTATUS(prp->pr_wstat));
+			    pid, WEXITSTATUS(wstat));
 		} else {
 			notice("pid %d has exited\n", pid);
 		}
@@ -755,7 +773,9 @@ intr(int signo)
 int
 main(int argc, char **argv)
 {
+#if defined(sun)
 	ucred_t *ucp;
+#endif
 	int err;
 	int opt_C = 0, opt_H = 0, opt_p = 0, opt_v = 0;
 	char c, *p, *end;
@@ -764,7 +784,7 @@ main(int argc, char **argv)
 
 	g_pname = basename(argv[0]);
 	argv[0] = g_pname; /* rewrite argv[0] for getopt errors */
-
+#if defined(sun)
 	/*
 	 * Make sure we have the required dtrace_proc privilege.
 	 */
@@ -777,6 +797,7 @@ main(int argc, char **argv)
 
 		ucred_free(ucp);
 	}
+#endif
 
 	while ((c = getopt(argc, argv, PLOCKSTAT_OPTSTR)) != EOF) {
 		switch (c) {
@@ -907,7 +928,7 @@ main(int argc, char **argv)
 
 	if (opt_H) {
 		dprog_add(g_hold_init);
-		if (g_opt_s == NULL)
+		if (!g_opt_s)
 			dprog_add(g_hold_times);
 		else
 			dprog_add(g_hold_histogram);
@@ -915,7 +936,7 @@ main(int argc, char **argv)
 
 	if (opt_C) {
 		dprog_add(g_ctnd_init);
-		if (g_opt_s == NULL)
+		if (!g_opt_s)
 			dprog_add(g_ctnd_times);
 		else
 			dprog_add(g_ctnd_histogram);
@@ -941,7 +962,7 @@ main(int argc, char **argv)
 		if ((g_pr = dtrace_proc_grab(g_dtp, (pid_t)pid, 0)) == NULL)
 			dfatal(NULL);
 	} else {
-		if ((g_pr = dtrace_proc_create(g_dtp, argv[0], argv)) == NULL)
+		if ((g_pr = dtrace_proc_create(g_dtp, argv[0], argv, NULL, NULL)) == NULL)
 			dfatal(NULL);
 	}
 
@@ -966,7 +987,11 @@ main(int argc, char **argv)
 
 	if (opt_v)
 		(void) printf("%s: tracing enabled for pid %d\n", g_pname,
+#if defined(sun)
 		    (int)Pstatus(g_pr)->pr_pid);
+#else
+		    (int)proc_getpid(g_pr));
+#endif
 
 	do {
 		if (!g_intr && !done)
diff --git a/cddl/usr.sbin/plockstat/Makefile b/cddl/usr.sbin/plockstat/Makefile
new file mode 100644
index 00000000000..20683115a43
--- /dev/null
+++ b/cddl/usr.sbin/plockstat/Makefile
@@ -0,0 +1,27 @@
+# $FreeBSD$
+
+.PATH: ${.CURDIR}/../../../cddl/contrib/opensolaris/cmd/plockstat
+
+PROG=		plockstat
+NO_MAN=
+SRCS=		plockstat.c 
+BINDIR?=	/usr/sbin
+
+WARNS?=		1
+
+CFLAGS+=	-I${.CURDIR}/../../../sys/cddl/compat/opensolaris \
+		-I${.CURDIR}/../../../cddl/compat/opensolaris/include \
+		-I${OPENSOLARIS_USR_DISTDIR}/head \
+		-I${OPENSOLARIS_USR_DISTDIR}/lib/libdtrace/common \
+		-I${OPENSOLARIS_USR_DISTDIR}/lib/libproc/common \
+		-I${OPENSOLARIS_SYS_DISTDIR}/uts/common \
+		-I${OPENSOLARIS_SYS_DISTDIR}/compat \
+		-I${.CURDIR}/../../../cddl/lib/libdtrace \
+		-I${.CURDIR}/../../../sys
+
+DPADD=		${LIBPTHREAD} ${LIBDTRACE} ${LIBY} ${LIBL} ${LIBPROC} ${LIBCTF}\
+		${LIBELF} ${LIBZ} ${LIBRT} ${LIBRTLD_DB} ${LIBUTIL}
+LDADD=		-lpthread -ldtrace -ly -ll -lproc -lctf -lelf -lz -lrt \
+		-lrtld_db -lutil
+
+.include 

From 7672c57a48632040e55b0ca276a7bd6f6b0fec82 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 13:56:29 +0000
Subject: [PATCH 0126/1624] Add a Makefile for dtruss.

Sponsored by:	The FreeBSD Foundation
---
 cddl/usr.sbin/dtruss/Makefile | 8 ++++++++
 1 file changed, 8 insertions(+)
 create mode 100644 cddl/usr.sbin/dtruss/Makefile

diff --git a/cddl/usr.sbin/dtruss/Makefile b/cddl/usr.sbin/dtruss/Makefile
new file mode 100644
index 00000000000..e09ed2e830d
--- /dev/null
+++ b/cddl/usr.sbin/dtruss/Makefile
@@ -0,0 +1,8 @@
+# $FreeBSD$
+
+.PATH: ${.CURDIR}/../../../cddl/contrib/dtracetoolkit
+
+SCRIPTS=dtruss
+NO_MAN=
+
+.include 

From 013abb00562fe393c22060fa18ff6b5da1ae3eed Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 14:02:04 +0000
Subject: [PATCH 0127/1624] Use double quotes when checking the value of
 MACHINE_ARCH.

Sponsored by:	The FreeBSD Foundation
---
 cddl/usr.sbin/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cddl/usr.sbin/Makefile b/cddl/usr.sbin/Makefile
index 92f00be9a56..fe72665a36f 100644
--- a/cddl/usr.sbin/Makefile
+++ b/cddl/usr.sbin/Makefile
@@ -12,7 +12,7 @@ _zdb=	zdb
 .endif
 .endif
 
-.if ${MACHINE_ARCH} == amd64 || ${MACHINE_ARCH} == i386
+.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
 _dtrace=	dtrace
 _lockstat=	lockstat
 .endif

From 60b77a1e4b2ffc38fdd65f7eb2649fb42fb484d0 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 14:08:04 +0000
Subject: [PATCH 0128/1624] Add the definition of LIBELF_PIC.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/bsd.libnames.mk | 1 +
 1 file changed, 1 insertion(+)

diff --git a/share/mk/bsd.libnames.mk b/share/mk/bsd.libnames.mk
index 0ba6f1d118c..986d76419c5 100644
--- a/share/mk/bsd.libnames.mk
+++ b/share/mk/bsd.libnames.mk
@@ -45,6 +45,7 @@ LIBDTRACE?=	${DESTDIR}${LIBDIR}/libdtrace.a
 LIBDWARF?=	${DESTDIR}${LIBDIR}/libdwarf.a
 LIBEDIT?=	${DESTDIR}${LIBDIR}/libedit.a
 LIBELF?=	${DESTDIR}${LIBDIR}/libelf.a
+LIBELF_PIC?=	${DESTDIR}${LIBDIR}/libelf_pic.a
 LIBFETCH?=	${DESTDIR}${LIBDIR}/libfetch.a
 LIBFL?=		"don't use LIBFL, use LIBL"
 LIBFORM?=	${DESTDIR}${LIBDIR}/libform.a

From cd306d6fa1a0ee5bd92d9a395f791b4cb7bbbc1d Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 14:09:24 +0000
Subject: [PATCH 0129/1624] Add a sysname char * to struct opensolaris_utsname.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/compat/opensolaris/sys/misc.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/cddl/compat/opensolaris/sys/misc.h b/sys/cddl/compat/opensolaris/sys/misc.h
index 0343f2f959b..20d335b0674 100644
--- a/sys/cddl/compat/opensolaris/sys/misc.h
+++ b/sys/cddl/compat/opensolaris/sys/misc.h
@@ -46,6 +46,7 @@
 #ifdef _KERNEL
 struct opensolaris_utsname {
 	char *nodename;
+	char *sysname;
 };
 
 extern char hw_serial[11];

From 7d924a46c24e23b4762b4932efdb4708689aefcd Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 14:14:24 +0000
Subject: [PATCH 0130/1624] Update for the new tests.

Sponsored by:	The FreeBSD Foundation
---
 tools/test/dtrace/Makefile | 462 ++++++++++++++++---------------------
 1 file changed, 199 insertions(+), 263 deletions(-)

diff --git a/tools/test/dtrace/Makefile b/tools/test/dtrace/Makefile
index 8ad8e62e76a..5cafb87a530 100644
--- a/tools/test/dtrace/Makefile
+++ b/tools/test/dtrace/Makefile
@@ -1,274 +1,206 @@
 # $FreeBSD$
 
 TESTSRCDIR=	${.CURDIR}/../../../cddl/contrib/opensolaris/cmd/dtrace/test
+CFLAGS+=	-w
 DTEST=		${TESTSRCDIR}/cmd/scripts/dtest.pl -n
 
 IGNORE=		\
-	${TESTSRCDIR}/tst/common/arrays/err.D_IDENT_UNDEF.badureg.d		\
-	${TESTSRCDIR}/tst/common/printa/err.D_PRINTF_ARG_TYPE.jstack.d		\
-	${TESTSRCDIR}/tst/common/printa/err.D_PRINTF_ARG_TYPE.ustack.d		\
-	${TESTSRCDIR}/tst/common/printa/tst.stack.d				\
-	${TESTSRCDIR}/tst/common/stack/err.D_USTACK_FRAMES.bad.d		\
-	${TESTSRCDIR}/tst/common/stack/err.D_USTACK_PROTO.bad.d			\
-	${TESTSRCDIR}/tst/common/stack/err.D_USTACK_STRSIZE.bad.d		\
-	${TESTSRCDIR}/tst/common/stop/tst.stop1.d				\
-	${TESTSRCDIR}/tst/common/aggs/tst.subr.d				\
-	${TESTSRCDIR}/tst/common/aggs/tst.signature.d				\
-	${TESTSRCDIR}/tst/common/arrays/tst.uregsarray.d			\
-	${TESTSRCDIR}/tst/common/assocs/err.D_OP_INCOMPAT.dupgtype.d		\
-	${TESTSRCDIR}/tst/common/assocs/err.D_OP_INCOMPAT.dupttype.d		\
-	${TESTSRCDIR}/tst/common/assocs/tst.orthogonality.d			\
-	${TESTSRCDIR}/tst/common/buffering/tst.cputime.ksh			\
-	${TESTSRCDIR}/tst/common/buffering/tst.ring3.d				\
-	${TESTSRCDIR}/tst/common/builtinvar/tst.psinfo.d			\
-	${TESTSRCDIR}/tst/common/builtinvar/tst.psinfo1.d			\
-	${TESTSRCDIR}/tst/common/drops/drp.DTRACEDROP_STKSTROVERFLOW.d		\
-	${TESTSRCDIR}/tst/common/dtraceUtil/err.D_PDESC_ZERO.InvalidDescription1.d	\
-	${TESTSRCDIR}/tst/common/dtraceUtil/tst.DataModel32.d.ksh		\
-	${TESTSRCDIR}/tst/common/dtraceUtil/tst.DestructWithFunction.d.ksh	\
-	${TESTSRCDIR}/tst/common/dtraceUtil/tst.DestructWithModule.d.ksh	\
-	${TESTSRCDIR}/tst/common/dtraceUtil/tst.PreprocessorStatement.d.ksh	\
-	${TESTSRCDIR}/tst/common/dtraceUtil/tst.ZeroFunctionProbes.d.ksh	\
-	${TESTSRCDIR}/tst/common/funcs/err.D_PROTO_ARG.mobadarg.d		\
-	${TESTSRCDIR}/tst/common/funcs/err.D_PROTO_LEN.motoofew.d		\
-	${TESTSRCDIR}/tst/common/funcs/err.D_PROTO_LEN.motoomany.d		\
-	${TESTSRCDIR}/tst/common/funcs/err.D_PROTO_LEN.mtabadarg.d		\
-	${TESTSRCDIR}/tst/common/funcs/err.D_PROTO_LEN.mtatoofew.d		\
-	${TESTSRCDIR}/tst/common/funcs/err.D_PROTO_LEN.mtatoomany.d		\
-	${TESTSRCDIR}/tst/common/funcs/tst.bcopy.d				\
-	${TESTSRCDIR}/tst/common/funcs/tst.copyin.d				\
-	${TESTSRCDIR}/tst/common/funcs/tst.copyinto.d				\
-	${TESTSRCDIR}/tst/common/funcs/tst.ddi_pathname.d			\
-	${TESTSRCDIR}/tst/common/inline/err.D_OP_INCOMPAT.badxlate.d		\
-	${TESTSRCDIR}/tst/common/inline/tst.InlineDataAssign.d			\
-	${TESTSRCDIR}/tst/common/inline/tst.InlineExpression.d			\
-	${TESTSRCDIR}/tst/common/inline/tst.InlineTypedef.d			\
-	${TESTSRCDIR}/tst/common/io/tst.fds.c					\
-	${TESTSRCDIR}/tst/common/java_api/tst.FunctionLookup.c			\
-	${TESTSRCDIR}/tst/common/java_api/tst.ProbeData.c			\
-	${TESTSRCDIR}/tst/common/misc/tst.dynopt.d				\
-	${TESTSRCDIR}/tst/common/misc/tst.include.ksh				\
-	${TESTSRCDIR}/tst/common/misc/tst.roch.d				\
-	${TESTSRCDIR}/tst/common/misc/tst.schrock.ksh				\
-	${TESTSRCDIR}/tst/common/nfs/tst.call.c					\
-	${TESTSRCDIR}/tst/common/nfs/tst.call.d					\
-	${TESTSRCDIR}/tst/common/nfs/tst.call3.c				\
-	${TESTSRCDIR}/tst/common/nfs/tst.call3.d				\
-	${TESTSRCDIR}/tst/common/offsetof/err.D_OFFSETOF_BITFIELD.bitfield.d	\
-	${TESTSRCDIR}/tst/common/pid/err.D_PDESC_ZERO.badlib.d			\
-	${TESTSRCDIR}/tst/common/pid/err.D_PDESC_ZERO.badproc1.d		\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_BADPID.badproc2.d		\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_CREATEFAIL.many.d		\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_FUNC.badfunc.d			\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_LIB.libdash.d			\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_NAME.alldash.d			\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_NAME.badname.d			\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_NAME.globdash.d			\
-	${TESTSRCDIR}/tst/common/pid/err.D_PROC_OFF.toobig.d			\
-	${TESTSRCDIR}/tst/common/pid/tst.addprobes.ksh 				\
-	${TESTSRCDIR}/tst/common/pid/tst.args1.c				\
-	${TESTSRCDIR}/tst/common/pid/tst.args1.d				\
-	${TESTSRCDIR}/tst/common/pid/tst.coverage.d				\
-	${TESTSRCDIR}/tst/common/pid/tst.emptystack.d				\
-	${TESTSRCDIR}/tst/common/pid/tst.float.c				\
-	${TESTSRCDIR}/tst/common/pid/tst.float.d				\
-	${TESTSRCDIR}/tst/common/pid/tst.fork.c					\
-	${TESTSRCDIR}/tst/common/pid/tst.fork.d					\
-	${TESTSRCDIR}/tst/common/pid/tst.gcc.c					\
-	${TESTSRCDIR}/tst/common/pid/tst.gcc.d					\
-	${TESTSRCDIR}/tst/common/pid/tst.main.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.manypids.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.probemod.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.provregex1.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.provregex2.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.provregex3.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.provregex4.ksh				\
-	${TESTSRCDIR}/tst/common/pid/tst.ret1.c					\
-	${TESTSRCDIR}/tst/common/pid/tst.ret1.d					\
-	${TESTSRCDIR}/tst/common/pid/tst.ret2.c					\
-	${TESTSRCDIR}/tst/common/pid/tst.ret2.d					\
-	${TESTSRCDIR}/tst/common/pid/tst.vfork.c				\
-	${TESTSRCDIR}/tst/common/pid/tst.vfork.d				\
-	${TESTSRCDIR}/tst/common/pid/tst.weak1.c				\
-	${TESTSRCDIR}/tst/common/pid/tst.weak1.d				\
-	${TESTSRCDIR}/tst/common/pid/tst.weak2.c				\
-	${TESTSRCDIR}/tst/common/pid/tst.weak2.d				\
-	${TESTSRCDIR}/tst/common/plockstat/tst.available.d			\
-	${TESTSRCDIR}/tst/common/plockstat/tst.libmap.d				\
-	${TESTSRCDIR}/tst/common/pointers/err.D_OP_LVAL.AddressChange.d		\
-	${TESTSRCDIR}/tst/common/pointers/tst.GlobalVar.d			\
-	${TESTSRCDIR}/tst/common/pointers/tst.basic1.d				\
-	${TESTSRCDIR}/tst/common/pointers/tst.basic2.d				\
-	${TESTSRCDIR}/tst/common/predicates/tst.argsnotcached.d			\
-	${TESTSRCDIR}/tst/common/printa/tst.walltimestamp.ksh			\
-	${TESTSRCDIR}/tst/common/printf/tst.basics.d				\
-	${TESTSRCDIR}/tst/common/printf/tst.printT.ksh				\
-	${TESTSRCDIR}/tst/common/printf/tst.printY.ksh				\
-	${TESTSRCDIR}/tst/common/printf/tst.str.d				\
-	${TESTSRCDIR}/tst/common/printf/tst.sym.d				\
-	${TESTSRCDIR}/tst/common/privs/tst.func_access.ksh			\
-	${TESTSRCDIR}/tst/common/privs/tst.op_access.ksh			\
-	${TESTSRCDIR}/tst/common/proc/tst.discard.ksh				\
-	${TESTSRCDIR}/tst/common/proc/tst.signal.ksh				\
-	${TESTSRCDIR}/tst/common/proc/tst.startexit.ksh				\
-	${TESTSRCDIR}/tst/common/profile-n/tst.ufuncsort.c			\
-	${TESTSRCDIR}/tst/common/scalars/tst.misc.d				\
-	${TESTSRCDIR}/tst/common/scalars/tst.selfarray2.d			\
-	${TESTSRCDIR}/tst/common/scripting/err.D_MACRO_UNDEF.invalidargs.d	\
-	${TESTSRCDIR}/tst/common/scripting/err.D_OP_LVAL.rdonly.d		\
-	${TESTSRCDIR}/tst/common/scripting/err.D_OP_WRITE.usepidmacro.d		\
-	${TESTSRCDIR}/tst/common/scripting/err.D_SYNTAX.concat.d		\
-	${TESTSRCDIR}/tst/common/scripting/err.D_SYNTAX.desc.d			\
-	${TESTSRCDIR}/tst/common/scripting/err.D_SYNTAX.inval.d			\
-	${TESTSRCDIR}/tst/common/scripting/err.D_SYNTAX.pid.d			\
-	${TESTSRCDIR}/tst/common/scripting/tst.arguments.ksh			\
-	${TESTSRCDIR}/tst/common/scripting/tst.egid.ksh				\
-	${TESTSRCDIR}/tst/common/scripting/tst.gid.ksh				\
-	${TESTSRCDIR}/tst/common/scripting/tst.projid.ksh			\
-	${TESTSRCDIR}/tst/common/scripting/tst.taskid.ksh			\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithBreakPoint.d	\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithChill.d	\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithCopyOut.d	\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithCopyOutStr.d	\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithPanic.d	\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithRaise.d	\
-	${TESTSRCDIR}/tst/common/speculation/err.D_ACT_SPEC.SpeculateWithStop.d	\
-	${TESTSRCDIR}/tst/common/syscall/tst.args.c				\
-	${TESTSRCDIR}/tst/common/syscall/tst.args.d				\
-	${TESTSRCDIR}/tst/common/syscall/tst.openret.ksh			\
-	${TESTSRCDIR}/tst/common/sysevent/tst.post.c				\
-	${TESTSRCDIR}/tst/common/sysevent/tst.post.d				\
-	${TESTSRCDIR}/tst/common/sysevent/tst.post_chan.c			\
-	${TESTSRCDIR}/tst/common/sysevent/tst.post_chan.d			\
-	${TESTSRCDIR}/tst/common/trace/tst.misc.d				\
-	${TESTSRCDIR}/tst/common/tracemem/err.D_TRACEMEM_ADDR.badaddr.d		\
-	${TESTSRCDIR}/tst/common/tracemem/tst.rootvp.d				\
-	${TESTSRCDIR}/tst/common/translators/tst.ProcModelTrans.d		\
-	${TESTSRCDIR}/tst/common/types/err.D_XLATE_REDECL.ResultDynType.d	\
-	${TESTSRCDIR}/tst/common/types/tst.ptrops.d				\
-	${TESTSRCDIR}/tst/common/types/tst.struct.d				\
-	${TESTSRCDIR}/tst/common/types/tst.typedef.d				\
-	${TESTSRCDIR}/tst/common/usdt/tst.argmap.c				\
-	${TESTSRCDIR}/tst/common/usdt/tst.args.c				\
-	${TESTSRCDIR}/tst/common/usdt/tst.forker.c				\
-	${TESTSRCDIR}/tst/common/ustack/tst.bigstack.c				\
-	${TESTSRCDIR}/tst/common/ustack/tst.spin.c				\
-	${TESTSRCDIR}/tst/common/vars/tst.ppid.d				\
-	${TESTSRCDIR}/tst/common/vars/tst.ucaller.ksh				\
-	${TESTSRCDIR}/tst/common/vars/tst.walltimestamp.d			\
+	${TESTSRCDIR}/tst/common/aggs/tst.subr.d			\
+	${TESTSRCDIR}/tst/common/buffering/tst.cputime.ksh		\
+	${TESTSRCDIR}/tst/common/buffering/tst.ring3.d			\
+	${TESTSRCDIR}/tst/common/cpc/err.D_PDESC_ZERO.lowfrequency.d	\
+	${TESTSRCDIR}/tst/common/cpc/err.D_PDESC_ZERO.malformedoverflow.d\
+	${TESTSRCDIR}/tst/common/cpc/err.D_PDESC_ZERO.nonexistentevent.d\
+	${TESTSRCDIR}/tst/common/cpc/err.cpcvscpustatpart1.ksh		\
+	${TESTSRCDIR}/tst/common/cpc/err.cpcvscpustatpart2.ksh		\
+	${TESTSRCDIR}/tst/common/cpc/err.cputrackfailtostart.ksh	\
+	${TESTSRCDIR}/tst/common/cpc/err.cputrackterminates.ksh		\
+	${TESTSRCDIR}/tst/common/cpc/err.toomanyenablings.d		\
+	${TESTSRCDIR}/tst/common/cpc/tst.allcpus.ksh			\
+	${TESTSRCDIR}/tst/common/cpc/tst.genericevent.d			\
+	${TESTSRCDIR}/tst/common/cpc/tst.platformevent.ksh		\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.ListProbesWithFunctions	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.ListProbesWithModules	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.ListProbesWithNames	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.ListProbesWithProviders	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.TraceFunctions		\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.TraceModule		\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.TraceNames		\
+	${TESTSRCDIR}/tst/common/dtraceUtil/man.TraceProvider		\
+	${TESTSRCDIR}/tst/common/dtraceUtil/tst.InvalidModule3.d.ksh	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/tst.InvalidProvider3.d.ksh	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/tst.InvalidTraceFunc7.d.ksh	\
+	${TESTSRCDIR}/tst/common/dtraceUtil/tst.InvalidTraceModule6.d.ksh\
+	${TESTSRCDIR}/tst/common/dtraceUtil/tst.InvalidTraceProvider4.d.ksh\
+	${TESTSRCDIR}/tst/common/funcs/tst.bcopy.d			\
+	${TESTSRCDIR}/tst/common/funcs/tst.copyin.d			\
+	${TESTSRCDIR}/tst/common/funcs/tst.copyinto.d			\
+	${TESTSRCDIR}/tst/common/funcs/tst.ddi_pathname.d		\
+	${TESTSRCDIR}/tst/common/funcs/tst.index.d			\
+	${TESTSRCDIR}/tst/common/inline/err.D_OP_INCOMPAT.badxlate.d	\
+	${TESTSRCDIR}/tst/common/inline/tst.InlineTypedef.d		\
+	${TESTSRCDIR}/tst/common/io/tst.fds.c				\
+	${TESTSRCDIR}/tst/common/java_api/tst.FunctionLookup.c		\
+	${TESTSRCDIR}/tst/common/java_api/tst.ProbeData.c		\
+	${TESTSRCDIR}/common/misc/tst.include.ksh			\
+	${TESTSRCDIR}/tst/common/misc/tst.roch.d			\
+	${TESTSRCDIR}/tst/common/nfs/tst.call.c				\
+	${TESTSRCDIR}/tst/common/nfs/tst.call.d				\
+	${TESTSRCDIR}/tst/common/nfs/tst.call3.c			\
+	${TESTSRCDIR}/tst/common/nfs/tst.call3.d			\
+	${TESTSRCDIR}/tst/common/offsetof/err.D_OFFSETOF_BITFIELD.bitfield.d\
+	${TESTSRCDIR}/tst/common/pointers/err.D_OP_LVAL.AddressChange.d	\
+	${TESTSRCDIR}/tst/common/pointers/tst.GlobalVar.d		\
+	${TESTSRCDIR}/tst/common/pointers/tst.basic1.d			\
+	${TESTSRCDIR}/tst/common/pointers/tst.basic2.d			\
+	${TESTSRCDIR}/tst/common/predicates/tst.argsnotcached.d		\
+	${TESTSRCDIR}/tst/common/privs/tst.func_access.ksh		\
+	${TESTSRCDIR}/tst/common/privs/tst.op_access.ksh		\
+	${TESTSRCDIR}/tst/common/proc/tst.discard.ksh			\
+	${TESTSRCDIR}/tst/common/proc/tst.signal.ksh			\
+	${TESTSRCDIR}/tst/common/proc/tst.startexit.ksh			\
+	${TESTSRCDIR}/tst/common/profile-n/tst.ufuncsort.c		\
+	${TESTSRCDIR}/tst/common/scalars/tst.misc.d			\
+	${TESTSRCDIR}/tst/common/scalars/tst.selfarray2.d		\
+	${TESTSRCDIR}/tst/common/sysevent/tst.post.c			\
+	${TESTSRCDIR}/tst/common/sysevent/tst.post.d			\
+	${TESTSRCDIR}/tst/common/sysevent/tst.post_chan.c		\
+	${TESTSRCDIR}/tst/common/sysevent/tst.post_chan.d		\
+	${TESTSRCDIR}/tst/common/trace/tst.misc.d			\
+	${TESTSRCDIR}/tst/common/tracemem/err.D_TRACEMEM_ADDR.badaddr.d	\
+	${TESTSRCDIR}/tst/common/tracemem/tst.rootvp.d			\
+	${TESTSRCDIR}/tst/common/translators/tst.ProcModelTrans.d	\
+	${TESTSRCDIR}/tst/common/types/err.D_XLATE_REDECL.ResultDynType.d\
+	${TESTSRCDIR}/tst/common/types/tst.ptrops.d			\
+	${TESTSRCDIR}/tst/common/types/tst.struct.d			\
+	${TESTSRCDIR}/tst/common/types/tst.typedef.d			\
+	${TESTSRCDIR}/tst/common/vars/tst.ucaller.ksh			\
+	${TESTSRCDIR}/tst/common/vars/tst.walltimestamp.d		\
+	${TESTSRCDIR}/tst/common/usdt/tst.argmap.c			\
+	${TESTSRCDIR}/tst/common/usdt/tst.args.c			\
+	${TESTSRCDIR}/tst/common/usdt/tst.forker.c			\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv4localtcp.ksh		\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv4localudp.ksh		\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv4remotetcp.ksh		\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv4remoteudp.ksh		\
+	${TESTSRCDIR}/tst/common/ip/tst.localtcpstate.ksh		\
+	${TESTSRCDIR}/tst/common/ip/tst.remotetcpstate.ksh		\
+	${TESTSRCDIR}/tst/common/scripting/tst.projid.ksh		\
+	${TESTSRCDIR}/tst/common/scripting/tst.taskid.ksh
+
+
 
 NOTWORK+= \
-	${TESTSRCDIR}/tst/common/io/tst.fds.d					\
-	${TESTSRCDIR}/tst/common/java_api/tst.Abort.ksh				\
-	${TESTSRCDIR}/tst/common/java_api/tst.Bean.ksh				\
-	${TESTSRCDIR}/tst/common/java_api/tst.Close.ksh				\
-	${TESTSRCDIR}/tst/common/java_api/tst.Drop.ksh				\
-	${TESTSRCDIR}/tst/common/java_api/tst.Enable.ksh			\
-	${TESTSRCDIR}/tst/common/java_api/tst.FunctionLookup.ksh		\
-	${TESTSRCDIR}/tst/common/java_api/tst.MaxConsumers.ksh			\
-	${TESTSRCDIR}/tst/common/java_api/tst.MultiAggPrinta.ksh		\
-	${TESTSRCDIR}/tst/common/java_api/tst.ProbeData.ksh			\
-	${TESTSRCDIR}/tst/common/java_api/tst.ProbeDescription.ksh		\
-	${TESTSRCDIR}/tst/common/java_api/tst.StateMachine.ksh			\
-	${TESTSRCDIR}/tst/common/java_api/tst.StopLock.ksh 			\
-	${TESTSRCDIR}/tst/common/java_api/tst.printa.d				\
-	${TESTSRCDIR}/tst/common/lexer/err.D_CHR_NL.char.d			\
-	${TESTSRCDIR}/tst/common/lexer/err.D_STR_NL.string.d			\
-	${TESTSRCDIR}/tst/common/mdb/tst.dtracedcmd.ksh				\
-	${TESTSRCDIR}/tst/common/mib/tst.icmp.ksh				\
-	${TESTSRCDIR}/tst/common/mib/tst.tcp.ksh				\
-	${TESTSRCDIR}/tst/common/mib/tst.udp.ksh				\
-	${TESTSRCDIR}/tst/common/profile-n/tst.func.ksh				\
-	${TESTSRCDIR}/tst/common/profile-n/tst.mod.ksh				\
-	${TESTSRCDIR}/tst/common/profile-n/tst.sym.ksh				\
-	${TESTSRCDIR}/tst/common/profile-n/tst.ufunc.ksh			\
-	${TESTSRCDIR}/tst/common/profile-n/tst.ufuncsort.ksh			\
-	${TESTSRCDIR}/tst/common/profile-n/tst.umod.ksh				\
-	${TESTSRCDIR}/tst/common/profile-n/tst.usym.ksh				\
-	${TESTSRCDIR}/tst/common/safety/tst.basename.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.caller.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.cleanpath.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.copyin.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.copyin2.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.ddi_pathname.d			\
-	${TESTSRCDIR}/tst/common/safety/tst.dirname.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.errno.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.execname.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.gid.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.hton.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.index.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.msgdsize.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.msgsize.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.null.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.pid.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.ppid.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.progenyof.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.random.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.rw.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.shortstr.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.stack.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.stackdepth.d			\
-	${TESTSRCDIR}/tst/common/safety/tst.stddev.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.strchr.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.strjoin.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.strstr.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.strtok.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.substr.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.ucaller.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.uid.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.unalign.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.uregs.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.ustack.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.ustackdepth.d			\
-	${TESTSRCDIR}/tst/common/safety/tst.vahole.d				\
-	${TESTSRCDIR}/tst/common/safety/tst.violentdeath.ksh			\
-	${TESTSRCDIR}/tst/common/safety/tst.zonename.d				\
-	${TESTSRCDIR}/tst/common/sched/tst.enqueue.d				\
-	${TESTSRCDIR}/tst/common/sched/tst.oncpu.d				\
-	${TESTSRCDIR}/tst/common/sched/tst.stackdepth.d				\
-	${TESTSRCDIR}/tst/common/usdt/argmap.d					\
-	${TESTSRCDIR}/tst/common/usdt/args.d					\
-	${TESTSRCDIR}/tst/common/usdt/forker.d					\
-	${TESTSRCDIR}/tst/common/usdt/tst.andpid.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.argmap.d				\
-	${TESTSRCDIR}/tst/common/usdt/tst.args.d				\
-	${TESTSRCDIR}/tst/common/usdt/tst.badguess.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.dlclose1.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.dlclose2.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.dlclose3.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.eliminate.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.enabled.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.entryreturn.ksh			\
-	${TESTSRCDIR}/tst/common/usdt/tst.fork.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.forker.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.guess32.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.guess64.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.header.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.include.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.linkpriv.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.linkunpriv.ksh			\
-	${TESTSRCDIR}/tst/common/usdt/tst.multiple.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.nodtrace.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.onlyenabled.ksh			\
-	${TESTSRCDIR}/tst/common/usdt/tst.reeval.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.static.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.static2.ksh				\
-	${TESTSRCDIR}/tst/common/usdt/tst.user.ksh				\
-	${TESTSRCDIR}/tst/common/ustack/tst.bigstack.d				\
-	${TESTSRCDIR}/tst/common/ustack/tst.depth.ksh				\
-	${TESTSRCDIR}/tst/common/ustack/tst.spin.ksh				\
+	${TESTSRCDIR}/tst/common/io/tst.fds.d				\
+	${TESTSRCDIR}/tst/common/java_api/tst.Abort.ksh			\
+	${TESTSRCDIR}/tst/common/java_api/tst.Bean.ksh			\
+	${TESTSRCDIR}/tst/common/java_api/tst.Close.ksh			\
+	${TESTSRCDIR}/tst/common/java_api/tst.Drop.ksh			\
+	${TESTSRCDIR}/tst/common/java_api/tst.Enable.ksh		\
+	${TESTSRCDIR}/tst/common/java_api/tst.FunctionLookup.ksh	\
+	${TESTSRCDIR}/tst/common/java_api/tst.GetAggregate.ksh		\
+	${TESTSRCDIR}/tst/common/java_api/tst.MaxConsumers.ksh		\
+	${TESTSRCDIR}/tst/common/java_api/tst.MultiAggPrinta.ksh	\
+	${TESTSRCDIR}/tst/common/java_api/tst.ProbeData.ksh		\
+	${TESTSRCDIR}/tst/common/java_api/tst.ProbeDescription.ksh	\
+	${TESTSRCDIR}/tst/common/java_api/tst.StateMachine.ksh		\
+	${TESTSRCDIR}/tst/common/java_api/tst.StopLock.ksh 		\
+	${TESTSRCDIR}/tst/common/java_api/tst.printa.d			\
+	${TESTSRCDIR}/tst/common/lexer/err.D_CHR_NL.char.d		\
+	${TESTSRCDIR}/tst/common/lexer/err.D_STR_NL.string.d		\
+	${TESTSRCDIR}/tst/common/mdb/tst.dtracedcmd.ksh			\
+	${TESTSRCDIR}/tst/common/mib/tst.icmp.ksh			\
+	${TESTSRCDIR}/tst/common/mib/tst.tcp.ksh			\
+	${TESTSRCDIR}/tst/common/mib/tst.udp.ksh			\
+	${TESTSRCDIR}/tst/common/profile-n/tst.func.ksh			\
+	${TESTSRCDIR}/tst/common/profile-n/tst.mod.ksh			\
+	${TESTSRCDIR}/tst/common/profile-n/tst.sym.ksh			\
+	${TESTSRCDIR}/tst/common/profile-n/tst.ufunc.ksh		\
+	${TESTSRCDIR}/tst/common/profile-n/tst.ufuncsort.ksh		\
+	${TESTSRCDIR}/tst/common/profile-n/tst.umod.ksh			\
+	${TESTSRCDIR}/tst/common/profile-n/tst.usym.ksh			\
+	${TESTSRCDIR}/tst/common/safety/tst.basename.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.caller.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.cleanpath.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.copyin.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.copyin2.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.ddi_pathname.d		\
+	${TESTSRCDIR}/tst/common/safety/tst.dirname.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.errno.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.execname.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.gid.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.hton.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.index.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.msgdsize.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.msgsize.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.null.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.pid.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.ppid.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.progenyof.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.random.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.rw.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.shortstr.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.stack.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.stackdepth.d		\
+	${TESTSRCDIR}/tst/common/safety/tst.stddev.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.strchr.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.strjoin.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.strstr.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.strtok.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.substr.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.ucaller.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.uid.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.unalign.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.ustack.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.ustackdepth.d		\
+	${TESTSRCDIR}/tst/common/safety/tst.vahole.d			\
+	${TESTSRCDIR}/tst/common/safety/tst.violentdeath.ksh		\
+	${TESTSRCDIR}/tst/common/safety/tst.zonename.d			\
+	${TESTSRCDIR}/tst/common/sched/tst.enqueue.d			\
+	${TESTSRCDIR}/tst/common/sched/tst.oncpu.d			\
+	${TESTSRCDIR}/tst/common/sched/tst.stackdepth.d			\
+	${TESTSRCDIR}/tst/common/sdt/tst.sdtargs.d			\
+	${TESTSRCDIR}/tst/common/usdt/argmap.d				\
+	${TESTSRCDIR}/tst/common/usdt/args.d				\
+	${TESTSRCDIR}/tst/common/usdt/forker.d				\
+	${TESTSRCDIR}/tst/common/usdt/tst.andpid.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.argmap.d			\
+	${TESTSRCDIR}/tst/common/usdt/tst.args.d			\
+	${TESTSRCDIR}/tst/common/usdt/tst.badguess.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.dlclose1.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.dlclose2.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.dlclose3.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.eliminate.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.enabled.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.entryreturn.ksh		\
+	${TESTSRCDIR}/tst/common/usdt/tst.fork.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.forker.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.guess32.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.guess64.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.header.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.include.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.linkpriv.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.linkunpriv.ksh		\
+	${TESTSRCDIR}/tst/common/usdt/tst.multiple.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.nodtrace.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.onlyenabled.ksh		\
+	${TESTSRCDIR}/tst/common/usdt/tst.reeval.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.static.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.static2.ksh			\
+	${TESTSRCDIR}/tst/common/usdt/tst.user.ksh			\
+	${TESTSRCDIR}/tst/common/misc/tst.schrock.ksh 
 
 # --------------------------------------------------------------------------------
 # Tests that just don't complete (even to fail) at the moment...
 
 NOTWORK+= \
-	${TESTSRCDIR}/tst/common/dtraceUtil/tst.ZeroModuleProbes.d.ksh		\
-	${TESTSRCDIR}/tst/common/printa/tst.many.d				\
-	${TESTSRCDIR}/tst/common/scalars/err.D_OP_INCOMPAT.dupgtype.d		\
-	${TESTSRCDIR}/tst/common/scalars/err.D_OP_INCOMPAT.dupltype.d		\
-	${TESTSRCDIR}/tst/common/scalars/err.D_OP_INCOMPAT.dupttype.d		\
-	${TESTSRCDIR}/tst/common/vars/tst.gid.d					\
-	${TESTSRCDIR}/tst/common/vars/tst.uid.d					\
+	${TESTSRCDIR}/tst/common/dtraceUtil/tst.ZeroModuleProbes.d.ksh	\
+	${TESTSRCDIR}/tst/common/printa/tst.many.d			\
+	${TESTSRCDIR}/tst/common/scalars/err.D_OP_INCOMPAT.dupgtype.d	\
+	${TESTSRCDIR}/tst/common/scalars/err.D_OP_INCOMPAT.dupltype.d	\
+	${TESTSRCDIR}/tst/common/scalars/err.D_OP_INCOMPAT.dupttype.d	\
+	${TESTSRCDIR}/tst/common/vars/tst.gid.d				\
+	${TESTSRCDIR}/tst/common/vars/tst.uid.d				\
 
 # --------------------------------------------------------------------------------
 # Tests that currently hang the system:
@@ -276,10 +208,10 @@ NOTWORK+= \
 NOTWORK+= \
 	${TESTSRCDIR}/tst/common/fbtprovider/tst.basic.d	\
 	${TESTSRCDIR}/tst/common/fbtprovider/tst.return.d	\
-	${TESTSRCDIR}/tst/common/grammar/tst.stmts.d	\
+	${TESTSRCDIR}/tst/common/grammar/tst.stmts.d		\
 	${TESTSRCDIR}/tst/common/misc/tst.enablerace.ksh	\
-	${TESTSRCDIR}/tst/common/predicates/tst.predcache.ksh			\
-	${TESTSRCDIR}/tst/common/proc/tst.exitkilled.ksh			\
+	${TESTSRCDIR}/tst/common/predicates/tst.predcache.ksh	\
+	${TESTSRCDIR}/tst/common/proc/tst.exitkilled.ksh	\
 
 .if ${MACHINE_ARCH} == "i386"
 
@@ -320,10 +252,14 @@ NOTWORK+= ${TESTSRCDIR}/tst/common/builtinvar/tst.ipl.d \
 	${TESTSRCDIR}/tst/common/builtinvar/tst.ipl1.d
 
 # --------------------------------------------------------------------------------
-# This test relies on the Solaris ping behaviour of exiting after a number of
+# These tests relies on the Solaris ping behaviour of exiting after a number of
 # pings. On FreeBSD ping doesn't do that.
 
-NOTWORK+= ${TESTSRCDIR}/tst/common/funcs/tst.system.d
+NOTWORK+= ${TESTSRCDIR}/tst/common/funcs/tst.system.d 		\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv6remoteicmp.ksh 	\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv6localicmp.ksh 	\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv4localicmp.ksh 	\
+	${TESTSRCDIR}/tst/common/ip/tst.ipv4remoteicmp.ksh 
 
 # --------------------------------------------------------------------------------
 # This test checks for a leading tab on a line before #define. That is illegal

From 760d65b894cfc03b36095aab7227f151c99fb3f7 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Sat, 21 Aug 2010 14:28:48 +0000
Subject: [PATCH 0131/1624] Skip a KASSERT which isn't appropriate when not
 employing page coloring. Reported by: Michael Moll

---
 sys/sparc64/sparc64/pmap.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/sys/sparc64/sparc64/pmap.c b/sys/sparc64/sparc64/pmap.c
index e158bf481af..b34a07f4821 100644
--- a/sys/sparc64/sparc64/pmap.c
+++ b/sys/sparc64/sparc64/pmap.c
@@ -833,14 +833,15 @@ pmap_cache_remove(vm_page_t m, vm_offset_t va)
 	    m->md.colors[DCACHE_COLOR(va)]);
 	KASSERT((m->flags & PG_FICTITIOUS) == 0,
 	    ("pmap_cache_remove: fake page"));
-	KASSERT(m->md.colors[DCACHE_COLOR(va)] > 0,
-	    ("pmap_cache_remove: no mappings %d <= 0",
-	    m->md.colors[DCACHE_COLOR(va)]));
 	PMAP_STATS_INC(pmap_ncache_remove);
 
 	if (dcache_color_ignore != 0)
 		return;
 
+	KASSERT(m->md.colors[DCACHE_COLOR(va)] > 0,
+	    ("pmap_cache_remove: no mappings %d <= 0",
+	    m->md.colors[DCACHE_COLOR(va)]));
+
 	/*
 	 * Find the color for this virtual address and note the removal of
 	 * the mapping.

From 3a060e4a1ae1bffe25468dbf666e5494363faa90 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 14:59:37 +0000
Subject: [PATCH 0132/1624] We need to pull bsd.own.mk before modifying the CC
 variable. Otherwise it will be overwritten when we include bsd.lib.mk.

Pointed out by:	Dimitry Andric 
---
 gnu/lib/libobjc/Makefile | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/gnu/lib/libobjc/Makefile b/gnu/lib/libobjc/Makefile
index ddf9e5d2663..3dc49d842a6 100644
--- a/gnu/lib/libobjc/Makefile
+++ b/gnu/lib/libobjc/Makefile
@@ -1,5 +1,7 @@
 # $FreeBSD$
 
+.include 
+
 OBJCDIR=${.CURDIR}/../../../contrib/libobjc
 GCCDIR=	${.CURDIR}/../../../contrib/gcc
 GCCLIB=	${.CURDIR}/../../../contrib/gcclibs

From 934f2f338c60d98c03226895e34297d7e0b3f89f Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 15:01:59 +0000
Subject: [PATCH 0133/1624] Make sure the boot2 stage is compiled with gcc, as
 clang has no problems compiling it, but it just gets too big at the moment,
 even with -Os.  This is not applicable to gptboot, though.

Submitted by:	Dimitry Andric 
---
 sys/boot/i386/boot2/Makefile | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/sys/boot/i386/boot2/Makefile b/sys/boot/i386/boot2/Makefile
index ab5a69a8ba4..84a63c1ad4b 100644
--- a/sys/boot/i386/boot2/Makefile
+++ b/sys/boot/i386/boot2/Makefile
@@ -1,5 +1,10 @@
 # $FreeBSD$
 
+.include 
+
+# XXX: clang can compile the boot code just fine, but boot2 gets too big
+CC:=${CC:C/^cc|^clang/gcc/}
+
 FILES=		boot boot1 boot2
 
 NM?=		nm

From ad8a0e422ce574dae5276cdbe9baef6e30f0f12c Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 15:39:06 +0000
Subject: [PATCH 0134/1624] Add clang to the cross-tools build stage.

Submitted by:	Dimitry Andric 
---
 Makefile.inc1 | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/Makefile.inc1 b/Makefile.inc1
index 1e2bec68ad6..790a1cd2049 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -1078,8 +1078,15 @@ _kgzip=		usr.sbin/kgzip
 .endif
 .endif
 
+.if ${CC:T:Mclang} == "clang"
+_clang=		usr.bin/clang
+_clang_libs=	lib/clang
+.endif
+
 cross-tools:
 .for _tool in \
+    ${_clang_libs} \
+    ${_clang} \
     gnu/usr.bin/binutils \
     gnu/usr.bin/cc \
     usr.bin/xlint/lint1 usr.bin/xlint/lint2 usr.bin/xlint/xlint \

From 2aedda247be1141625c91bb67bc39b759cfe6c6f Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 15:46:33 +0000
Subject: [PATCH 0135/1624] Modify clang so that when TOOLS_PREFIX is defined
 we register the CLANG_PREFIX macro. This changes the default header search
 path when we are building clang as part of cross-tools.

Submitted by:	Dimitry Andric 
Reviewed by:	freebsd-current
---
 .../tools/clang/lib/Driver/ToolChains.cpp     | 10 ++++----
 .../clang/lib/Frontend/InitHeaderSearch.cpp   | 23 ++++++++++++-------
 lib/clang/clang.build.mk                      |  4 ++++
 3 files changed, 25 insertions(+), 12 deletions(-)

diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
index a78d1536fa1..35065901620 100644
--- a/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
+++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
@@ -26,6 +26,10 @@
 
 #include  // ::getenv
 
+#ifndef CLANG_PREFIX
+#define CLANG_PREFIX
+#endif
+
 using namespace clang::driver;
 using namespace clang::driver::toolchains;
 
@@ -869,11 +873,9 @@ FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple, bool Lib32)
   getProgramPaths().push_back(getDriver().Dir + "/../libexec");
   getProgramPaths().push_back("/usr/libexec");
   if (Lib32) {
-    getFilePaths().push_back(getDriver().Dir + "/../lib32");
-    getFilePaths().push_back("/usr/lib32");
+    getFilePaths().push_back(CLANG_PREFIX "/usr/lib32");
   } else {
-    getFilePaths().push_back(getDriver().Dir + "/../lib");
-    getFilePaths().push_back("/usr/lib");
+    getFilePaths().push_back(CLANG_PREFIX "/usr/lib");
   }
 }
 
diff --git a/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp b/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp
index fcfee71266b..91871484fde 100644
--- a/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp
+++ b/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp
@@ -30,6 +30,9 @@
   #define WIN32_LEAN_AND_MEAN 1
   #include 
 #endif
+#ifndef CLANG_PREFIX
+#define CLANG_PREFIX
+#endif
 using namespace clang;
 using namespace clang::frontend;
 
@@ -408,9 +411,10 @@ static bool getWindowsSDKDir(std::string &path) {
 
 void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
                                             const HeaderSearchOptions &HSOpts) {
-#if 0 /* Remove unneeded include paths. */
   // FIXME: temporary hack: hard-coded paths.
-  AddPath("/usr/local/include", System, true, false, false);
+#ifndef __FreeBSD__
+  AddPath(CLANG_PREFIX "/usr/local/include", System, true, false, false);
+#endif
 
   // Builtin includes use #include_next directives and should be positioned
   // just prior C include dirs.
@@ -421,7 +425,6 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
     P.appendComponent("include");
     AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
   }
-#endif
 
   // Add dirs specified via 'configure --with-c-include-dirs'.
   llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
@@ -518,13 +521,15 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
   case llvm::Triple::MinGW32:
     AddPath("c:/mingw/include", System, true, false, false);
     break;
+  case llvm::Triple::FreeBSD:
+    AddPath(CLANG_PREFIX "/usr/include/clang/" CLANG_VERSION_STRING,
+      System, false, false, false);
+    break;
   default:
     break;
   }
 
-  AddPath("/usr/include/clang/" CLANG_VERSION_STRING,
-    System, false, false, false);
-  AddPath("/usr/include", System, false, false, false);
+  AddPath(CLANG_PREFIX "/usr/include", System, false, false, false);
 }
 
 void InitHeaderSearch::
@@ -726,8 +731,10 @@ AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
   case llvm::Triple::FreeBSD:
     // FreeBSD 8.0
     // FreeBSD 7.3
-    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
-    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2/backward", "", "", "", triple);
+    AddGnuCPlusPlusIncludePaths(CLANG_PREFIX "/usr/include/c++/4.2",
+                                "", "", "", triple);
+    AddGnuCPlusPlusIncludePaths(CLANG_PREFIX "/usr/include/c++/4.2/backward",
+                                "", "", "", triple);
     break;
   case llvm::Triple::Minix:
     AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
diff --git a/lib/clang/clang.build.mk b/lib/clang/clang.build.mk
index 6351edae213..86384dbf6ad 100644
--- a/lib/clang/clang.build.mk
+++ b/lib/clang/clang.build.mk
@@ -28,6 +28,10 @@ LLVM_REQUIRES_RTTI=
 CFLAGS+=-fno-rtti
 .endif
 
+.ifdef TOOLS_PREFIX
+CFLAGS+=-DCLANG_PREFIX=\"${TOOLS_PREFIX}\"
+.endif
+
 .PATH:	${LLVM_SRCS}/${SRCDIR}
 
 TBLGEN=tblgen ${CFLAGS:M-I*}

From 029a737371cea014cef5aa0eaacd3baba3dbedbe Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 17:29:59 +0000
Subject: [PATCH 0136/1624] Don't link drti.o with libelf_pic.a. This means
 that all software with userland SDT probes must be linked with libelf
 explicitly.

Requested by:	kib
Sponsored by:	The FreeBSD Foundation
---
 Makefile.inc1          | 2 +-
 cddl/lib/drti/Makefile | 8 +-------
 lib/libelf/Makefile    | 1 -
 3 files changed, 2 insertions(+), 9 deletions(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index 790a1cd2049..6e58396fc53 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -1149,7 +1149,7 @@ gnu/lib/libgcc__L: lib/libc__L
 _prebuild_libs=	${_kerberos5_lib_libasn1} ${_kerberos5_lib_libheimntlm} \
 		${_kerberos5_lib_libhx509} ${_kerberos5_lib_libkrb5} \
 		${_kerberos5_lib_libroken} \
-		lib/libbz2 lib/libcom_err lib/libcrypt lib/libelf \
+		lib/libbz2 lib/libcom_err lib/libcrypt \
 		lib/libexpat lib/libfetch \
 		${_lib_libgssapi} ${_lib_libipx} \
 		lib/libkiconv lib/libkvm lib/liblzma lib/libmd \
diff --git a/cddl/lib/drti/Makefile b/cddl/lib/drti/Makefile
index 57b161f74e1..605bde75272 100644
--- a/cddl/lib/drti/Makefile
+++ b/cddl/lib/drti/Makefile
@@ -8,7 +8,7 @@ FILESOWN=	${LIBOWN}
 FILESGRP=	${LIBGRP}
 FILESMODE=	${LIBMODE}
 FILESDIR=	${LIBDIR}/dtrace
-CLEANFILES=	${FILES} ${FILES}.tmp
+CLEANFILES=	${FILES}
 
 CFLAGS+=	-I${.CURDIR}/../../../sys/cddl/compat/opensolaris \
 		-I${.CURDIR}/../../../cddl/compat/opensolaris/include \
@@ -18,10 +18,4 @@ CFLAGS+=	-I${.CURDIR}/../../../sys/cddl/compat/opensolaris \
 		-I${OPENSOLARIS_SYS_DISTDIR}/uts/common \
 		-DPIC -fpic
 
-.c.o:
-	${CC} ${CFLAGS} -c ${.IMPSRC}
-	mv ${FILES} ${FILES}.tmp
-	${LD} -o ${FILES} -r ${FILES}.tmp ${LIBELF_PIC}
-	rm -f ${FILES}.tmp
-
 .include 
diff --git a/lib/libelf/Makefile b/lib/libelf/Makefile
index 4e51de0cc61..fc70d9d865c 100644
--- a/lib/libelf/Makefile
+++ b/lib/libelf/Makefile
@@ -55,7 +55,6 @@ SRCS=	elf_begin.c						\
 	${GENSRCS}
 INCS=	libelf.h gelf.h
 
-INSTALL_PIC_ARCHIVE=yes
 GENSRCS=	libelf_fsize.c libelf_msize.c libelf_convert.c
 CLEANFILES=	${GENSRCS}
 CFLAGS+=	-I. -I${.CURDIR}

From 21022fe7e9733bdbc188db5dc9cbad1cdfb2d495 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 21 Aug 2010 17:53:16 +0000
Subject: [PATCH 0137/1624] Remove LIBELF_PIC.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/bsd.libnames.mk | 1 -
 1 file changed, 1 deletion(-)

diff --git a/share/mk/bsd.libnames.mk b/share/mk/bsd.libnames.mk
index 986d76419c5..0ba6f1d118c 100644
--- a/share/mk/bsd.libnames.mk
+++ b/share/mk/bsd.libnames.mk
@@ -45,7 +45,6 @@ LIBDTRACE?=	${DESTDIR}${LIBDIR}/libdtrace.a
 LIBDWARF?=	${DESTDIR}${LIBDIR}/libdwarf.a
 LIBEDIT?=	${DESTDIR}${LIBDIR}/libedit.a
 LIBELF?=	${DESTDIR}${LIBDIR}/libelf.a
-LIBELF_PIC?=	${DESTDIR}${LIBDIR}/libelf_pic.a
 LIBFETCH?=	${DESTDIR}${LIBDIR}/libfetch.a
 LIBFL?=		"don't use LIBFL, use LIBL"
 LIBFORM?=	${DESTDIR}${LIBDIR}/libform.a

From 7e32f79a4499e8b0f5c01bc31bdefd701b1422d7 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sat, 21 Aug 2010 23:13:16 +0000
Subject: [PATCH 0138/1624] Load tunable from loader.conf(5) instead of
 device.hints(5).

---
 sys/dev/bge/if_bge.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index a473919189c..8599b8893c9 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -4898,6 +4898,8 @@ bge_add_sysctls(struct bge_softc *sc)
 	struct sysctl_ctx_list *ctx;
 	struct sysctl_oid_list *children, *schildren;
 	struct sysctl_oid *tree;
+	char tn[32];
+	int unit;
 
 	ctx = device_get_sysctl_ctx(sc->bge_dev);
 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->bge_dev));
@@ -4917,6 +4919,7 @@ bge_add_sysctls(struct bge_softc *sc)
 
 #endif
 
+	unit = device_get_unit(sc->bge_dev);
 	/*
 	 * A common design characteristic for many Broadcom client controllers
 	 * is that they only support a single outstanding DMA read operation
@@ -4929,13 +4932,13 @@ bge_add_sysctls(struct bge_softc *sc)
 	 * performance is about 850Mbps. However forcing coalescing mbufs
 	 * consumes a lot of CPU cycles, so leave it off by default.
 	 */
+	sc->bge_forced_collapse = 0;
+	snprintf(tn, sizeof(tn), "dev.bge.%d.forced_collapse", unit);
+	TUNABLE_INT_FETCH(tn, &sc->bge_forced_collapse);
 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "forced_collapse",
 	    CTLFLAG_RW, &sc->bge_forced_collapse, 0,
 	    "Number of fragmented TX buffers of a frame allowed before "
 	    "forced collapsing");
-	resource_int_value(device_get_name(sc->bge_dev),
-	    device_get_unit(sc->bge_dev), "forced_collapse",
-	    &sc->bge_forced_collapse);
 
 	if (BGE_IS_5705_PLUS(sc))
 		return;

From 35f945cd6212e8add6ec14f1b134ae9516a45e61 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sun, 22 Aug 2010 01:39:09 +0000
Subject: [PATCH 0139/1624] It seems all Broadcom controllers have a bug that
 can generate UDP datagrams with checksum value 0 when TX UDP checksum
 offloading is enabled.  Generating UDP checksum value 0 is RFC 768 violation.
 Even though the probability of generating such UDP datagrams is low, I don't
 want to see FreeBSD boxes to inject such datagrams into network so disable
 UDP checksum offloading by default.  Users still override this behavior by
 setting a sysctl variable or loader tunable, dev.bge.%d.forced_udpcsum.

I have no idea why this issue was not reported so far given that
bge(4) is one of the most commonly used controller on high-end
server class systems. Thanks to andre@ who passed the PR to me.

PR:	kern/104826
---
 sys/dev/bge/if_bge.c    | 48 +++++++++++++++++++++++++++++++++++------
 sys/dev/bge/if_bgereg.h |  2 ++
 2 files changed, 43 insertions(+), 7 deletions(-)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index 8599b8893c9..c90319406ae 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -120,7 +120,7 @@ __FBSDID("$FreeBSD$");
 
 #include 
 
-#define	BGE_CSUM_FEATURES	(CSUM_IP | CSUM_TCP | CSUM_UDP)
+#define	BGE_CSUM_FEATURES	(CSUM_IP | CSUM_TCP)
 #define	ETHER_MIN_NOPAD		(ETHER_MIN_LEN - ETHER_CRC_LEN) /* i.e., 60 */
 
 MODULE_DEPEND(bge, pci, 1, 1, 1);
@@ -2795,6 +2795,8 @@ bge_attach(device_t dev)
 		goto fail;
 	}
 
+	bge_add_sysctls(sc);
+
 	/* Set default tuneable values. */
 	sc->bge_stat_ticks = BGE_TICKS_PER_SEC;
 	sc->bge_rx_coal_ticks = 150;
@@ -2802,6 +2804,11 @@ bge_attach(device_t dev)
 	sc->bge_rx_max_coal_bds = 10;
 	sc->bge_tx_max_coal_bds = 10;
 
+	/* Initialize checksum features to use. */
+	sc->bge_csum_features = BGE_CSUM_FEATURES;
+	if (sc->bge_forced_udpcsum != 0)
+		sc->bge_csum_features |= CSUM_UDP;
+
 	/* Set up ifnet structure */
 	ifp = sc->bge_ifp = if_alloc(IFT_ETHER);
 	if (ifp == NULL) {
@@ -2818,7 +2825,7 @@ bge_attach(device_t dev)
 	ifp->if_snd.ifq_drv_maxlen = BGE_TX_RING_CNT - 1;
 	IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
 	IFQ_SET_READY(&ifp->if_snd);
-	ifp->if_hwassist = BGE_CSUM_FEATURES;
+	ifp->if_hwassist = sc->bge_csum_features;
 	ifp->if_capabilities = IFCAP_HWCSUM | IFCAP_VLAN_HWTAGGING |
 	    IFCAP_VLAN_MTU;
 	if ((sc->bge_flags & BGE_FLAG_TSO) != 0) {
@@ -2975,8 +2982,6 @@ again:
 		device_printf(sc->bge_dev, "couldn't set up irq\n");
 	}
 
-	bge_add_sysctls(sc);
-
 	return (0);
 
 fail:
@@ -3960,7 +3965,7 @@ bge_encap(struct bge_softc *sc, struct mbuf **m_head, uint32_t *txidx)
 			return (ENOBUFS);
 		csum_flags |= BGE_TXBDFLAG_CPU_PRE_DMA |
 		    BGE_TXBDFLAG_CPU_POST_DMA;
-	} else if ((m->m_pkthdr.csum_flags & BGE_CSUM_FEATURES) != 0) {
+	} else if ((m->m_pkthdr.csum_flags & sc->bge_csum_features) != 0) {
 		if (m->m_pkthdr.csum_flags & CSUM_IP)
 			csum_flags |= BGE_TXBDFLAG_IP_CSUM;
 		if (m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP)) {
@@ -4237,6 +4242,17 @@ bge_init_locked(struct bge_softc *sc)
 	/* Program VLAN tag stripping. */
 	bge_setvlan(sc);
 
+	/* Override UDP checksum offloading. */
+	if (sc->bge_forced_udpcsum == 0)
+		sc->bge_csum_features &= ~CSUM_UDP;
+	else
+		sc->bge_csum_features |= CSUM_UDP;
+	if (ifp->if_capabilities & IFCAP_TXCSUM &&
+	    ifp->if_capenable & IFCAP_TXCSUM) {
+		ifp->if_hwassist &= ~(BGE_CSUM_FEATURES | CSUM_UDP);
+		ifp->if_hwassist |= sc->bge_csum_features;
+	}
+
 	/* Init RX ring. */
 	if (bge_init_rx_ring_std(sc) != 0) {
 		device_printf(sc->bge_dev, "no memory for std Rx buffers.\n");
@@ -4562,9 +4578,9 @@ bge_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 			ifp->if_capenable ^= IFCAP_HWCSUM;
 			if (IFCAP_HWCSUM & ifp->if_capenable &&
 			    IFCAP_HWCSUM & ifp->if_capabilities)
-				ifp->if_hwassist |= BGE_CSUM_FEATURES;
+				ifp->if_hwassist |= sc->bge_csum_features;
 			else
-				ifp->if_hwassist &= ~BGE_CSUM_FEATURES;
+				ifp->if_hwassist &= ~sc->bge_csum_features;
 		}
 
 		if ((mask & IFCAP_TSO4) != 0 &&
@@ -4940,6 +4956,24 @@ bge_add_sysctls(struct bge_softc *sc)
 	    "Number of fragmented TX buffers of a frame allowed before "
 	    "forced collapsing");
 
+	/*
+	 * It seems all Broadcom controllers have a bug that can generate UDP
+	 * datagrams with checksum value 0 when TX UDP checksum offloading is
+	 * enabled.  Generating UDP checksum value 0 is RFC 768 violation.
+	 * Even though the probability of generating such UDP datagrams is
+	 * low, I don't want to see FreeBSD boxes to inject such datagrams
+	 * into network so disable UDP checksum offloading by default.  Users
+	 * still override this behavior by setting a sysctl variable,
+	 * dev.bge.0.forced_udpcsum.
+	 */
+	sc->bge_forced_udpcsum = 0;
+	snprintf(tn, sizeof(tn), "dev.bge.%d.bge_forced_udpcsum", unit);
+	TUNABLE_INT_FETCH(tn, &sc->bge_forced_udpcsum);
+	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "forced_udpcsum",
+	    CTLFLAG_RW, &sc->bge_forced_udpcsum, 0,
+	    "Enable UDP checksum offloading even if controller can "
+	    "generate UDP checksum value 0");
+
 	if (BGE_IS_5705_PLUS(sc))
 		return;
 
diff --git a/sys/dev/bge/if_bgereg.h b/sys/dev/bge/if_bgereg.h
index 6664d5b7e56..6970a3d60da 100644
--- a/sys/dev/bge/if_bgereg.h
+++ b/sys/dev/bge/if_bgereg.h
@@ -2644,6 +2644,8 @@ struct bge_softc {
 	int			bge_link_evt;	/* pending link event */
 	int			bge_timer;
 	int			bge_forced_collapse;
+	int			bge_forced_udpcsum;
+	int			bge_csum_features;
 	struct callout		bge_stat_ch;
 	uint32_t		bge_rx_discards;
 	uint32_t		bge_tx_discards;

From 8024e98228427e22045bdf4b4012a659503f4aea Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sun, 22 Aug 2010 01:40:59 +0000
Subject: [PATCH 0140/1624] Document newly introduced tunable
 dev.bge.%d.forced_udpcsum. While I'm here also mention tunable
 dev.bge.%d.forced_collapse.

---
 share/man/man4/bge.4 | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/bge.4 b/share/man/man4/bge.4
index 45c7156cbc6..e3509c7da3f 100644
--- a/share/man/man4/bge.4
+++ b/share/man/man4/bge.4
@@ -31,7 +31,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd October 7, 2009
+.Dd August 21, 2010
 .Dt BGE 4
 .Os
 .Sh NAME
@@ -219,6 +219,26 @@ Allow the ASF feature for cooperating with IPMI.
 Can cause system lockup problems on a small number of systems.
 Enabled by default.
 .El
+.Sh SYSCTL VARIABLES
+The following variables are available as both
+.Xr sysctl 8
+variables and
+.Xr loader 8
+tunables:
+.Bl -tag -width indent
+.It Va dev.bge.%d.forced_collapse
+Allow collapsing multiple transmit buffers into a single buffer
+to increase transmit performance with the cost of CPU cycles.
+The default value is 0 to disable transmit buffer collapsing.
+.It Va dev.bge.%d.forced_udpcsum
+Enable UDP transmit checksum offloading even if controller can generate
+UDP datagrams with checksum value 0.
+UDP datagrams with checksum value 0 can confuse receiver host as it means
+sender did not compute UDP checksum.
+The default value is 0 which disables UDP transmit checksum offloading.
+The interface need to be brought down and up again before a change takes
+effect.
+.El
 .Sh DIAGNOSTICS
 .Bl -diag
 .It "bge%d: couldn't map memory"

From 99d57a6bd894d9afea3876da93fc217186aa3368 Mon Sep 17 00:00:00 2001
From: Ed Schouten 
Date: Sun, 22 Aug 2010 05:36:06 +0000
Subject: [PATCH 0141/1624] Add support for whiteouts on tmpfs.

Right now unionfs only allows filesystems to be mounted on top of
another if it supports whiteouts. Even though I have sent a patch to
daichi@ to let unionfs work without it, we'd better also add support for
whiteouts to tmpfs.

This patch implements .vop_whiteout and makes necessary changes to
lookup() and readdir() to take them into account. We must also make sure
that when adding or removing a file, we honour the componentname's
DOWHITEOUT and ISWHITEOUT, to prevent duplicate filenames.

MFC after:	1 month
---
 sys/fs/tmpfs/tmpfs.h       |  5 +-
 sys/fs/tmpfs/tmpfs_subr.c  | 94 ++++++++++++++++++++++++++------------
 sys/fs/tmpfs/tmpfs_vnops.c | 43 ++++++++++++++++-
 3 files changed, 109 insertions(+), 33 deletions(-)

diff --git a/sys/fs/tmpfs/tmpfs.h b/sys/fs/tmpfs/tmpfs.h
index 04b1a06cd24..b1c42496e66 100644
--- a/sys/fs/tmpfs/tmpfs.h
+++ b/sys/fs/tmpfs/tmpfs.h
@@ -72,7 +72,8 @@ struct tmpfs_dirent {
 	* td_namelen field must always be used when accessing its value. */
 	char *				td_name;
 
-	/* Pointer to the node this entry refers to. */
+	/* Pointer to the node this entry refers to.  In case this field
+	 * is NULL, the node is a whiteout. */
 	struct tmpfs_node *		td_node;
 };
 
@@ -434,6 +435,8 @@ int	tmpfs_dir_getdotdent(struct tmpfs_node *, struct uio *);
 int	tmpfs_dir_getdotdotdent(struct tmpfs_node *, struct uio *);
 struct tmpfs_dirent *	tmpfs_dir_lookupbycookie(struct tmpfs_node *, off_t);
 int	tmpfs_dir_getdents(struct tmpfs_node *, struct uio *, off_t *);
+int	tmpfs_dir_whiteout_add(struct vnode *, struct componentname *);
+void	tmpfs_dir_whiteout_remove(struct vnode *, struct componentname *);
 int	tmpfs_reg_resize(struct vnode *, off_t);
 int	tmpfs_chflags(struct vnode *, int, struct ucred *, struct thread *);
 int	tmpfs_chmod(struct vnode *, mode_t, struct ucred *, struct thread *);
diff --git a/sys/fs/tmpfs/tmpfs_subr.c b/sys/fs/tmpfs/tmpfs_subr.c
index b6c5cfe68b2..84a2038112f 100644
--- a/sys/fs/tmpfs/tmpfs_subr.c
+++ b/sys/fs/tmpfs/tmpfs_subr.c
@@ -261,7 +261,8 @@ tmpfs_alloc_dirent(struct tmpfs_mount *tmp, struct tmpfs_node *node,
 	memcpy(nde->td_name, name, len);
 
 	nde->td_node = node;
-	node->tn_links++;
+	if (node != NULL)
+		node->tn_links++;
 
 	*de = nde;
 
@@ -287,9 +288,10 @@ tmpfs_free_dirent(struct tmpfs_mount *tmp, struct tmpfs_dirent *de,
 		struct tmpfs_node *node;
 
 		node = de->td_node;
-
-		MPASS(node->tn_links > 0);
-		node->tn_links--;
+		if (node != NULL) {
+			MPASS(node->tn_links > 0);
+			node->tn_links--;
+		}
 	}
 
 	free(de->td_name, M_TMPFSNAME);
@@ -518,6 +520,8 @@ tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
 	/* Now that all required items are allocated, we can proceed to
 	 * insert the new node into the directory, an operation that
 	 * cannot fail. */
+	if (cnp->cn_flags & ISWHITEOUT)
+		tmpfs_dir_whiteout_remove(dvp, cnp);
 	tmpfs_dir_attach(dvp, de);
 
 out:
@@ -768,39 +772,44 @@ tmpfs_dir_getdents(struct tmpfs_node *node, struct uio *uio, off_t *cntp)
 
 		/* Create a dirent structure representing the current
 		 * tmpfs_node and fill it. */
-		d.d_fileno = de->td_node->tn_id;
-		switch (de->td_node->tn_type) {
-		case VBLK:
-			d.d_type = DT_BLK;
-			break;
+		if (de->td_node == NULL) {
+			d.d_fileno = 1;
+			d.d_type = DT_WHT;
+		} else {
+			d.d_fileno = de->td_node->tn_id;
+			switch (de->td_node->tn_type) {
+			case VBLK:
+				d.d_type = DT_BLK;
+				break;
 
-		case VCHR:
-			d.d_type = DT_CHR;
-			break;
+			case VCHR:
+				d.d_type = DT_CHR;
+				break;
 
-		case VDIR:
-			d.d_type = DT_DIR;
-			break;
+			case VDIR:
+				d.d_type = DT_DIR;
+				break;
 
-		case VFIFO:
-			d.d_type = DT_FIFO;
-			break;
+			case VFIFO:
+				d.d_type = DT_FIFO;
+				break;
 
-		case VLNK:
-			d.d_type = DT_LNK;
-			break;
+			case VLNK:
+				d.d_type = DT_LNK;
+				break;
 
-		case VREG:
-			d.d_type = DT_REG;
-			break;
+			case VREG:
+				d.d_type = DT_REG;
+				break;
 
-		case VSOCK:
-			d.d_type = DT_SOCK;
-			break;
+			case VSOCK:
+				d.d_type = DT_SOCK;
+				break;
 
-		default:
-			panic("tmpfs_dir_getdents: type %p %d",
-			    de->td_node, (int)de->td_node->tn_type);
+			default:
+				panic("tmpfs_dir_getdents: type %p %d",
+				    de->td_node, (int)de->td_node->tn_type);
+			}
 		}
 		d.d_namlen = de->td_namelen;
 		MPASS(de->td_namelen < sizeof(d.d_name));
@@ -837,6 +846,31 @@ tmpfs_dir_getdents(struct tmpfs_node *node, struct uio *uio, off_t *cntp)
 	return error;
 }
 
+int
+tmpfs_dir_whiteout_add(struct vnode *dvp, struct componentname *cnp)
+{
+	struct tmpfs_dirent *de;
+	int error;
+
+	error = tmpfs_alloc_dirent(VFS_TO_TMPFS(dvp->v_mount), NULL,
+	    cnp->cn_nameptr, cnp->cn_namelen, &de);
+	if (error != 0)
+		return (error);
+	tmpfs_dir_attach(dvp, de);
+	return (0);
+}
+
+void
+tmpfs_dir_whiteout_remove(struct vnode *dvp, struct componentname *cnp)
+{
+	struct tmpfs_dirent *de;
+
+	de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
+	MPASS(de != NULL && de->td_node == NULL);
+	tmpfs_dir_detach(dvp, de);
+	tmpfs_free_dirent(VFS_TO_TMPFS(dvp->v_mount), de, TRUE);
+}
+
 /* --------------------------------------------------------------------- */
 
 /*
diff --git a/sys/fs/tmpfs/tmpfs_vnops.c b/sys/fs/tmpfs/tmpfs_vnops.c
index 88e09399648..295d2ca3ee7 100644
--- a/sys/fs/tmpfs/tmpfs_vnops.c
+++ b/sys/fs/tmpfs/tmpfs_vnops.c
@@ -109,14 +109,19 @@ tmpfs_lookup(struct vop_cachedlookup_args *v)
 		error = 0;
 	} else {
 		de = tmpfs_dir_lookup(dnode, NULL, cnp);
-		if (de == NULL) {
+		if (de != NULL && de->td_node == NULL)
+			cnp->cn_flags |= ISWHITEOUT;
+		if (de == NULL || de->td_node == NULL) {
 			/* The entry was not found in the directory.
 			 * This is OK if we are creating or renaming an
 			 * entry and are working on the last component of
 			 * the path name. */
 			if ((cnp->cn_flags & ISLASTCN) &&
 			    (cnp->cn_nameiop == CREATE || \
-			    cnp->cn_nameiop == RENAME)) {
+			    cnp->cn_nameiop == RENAME ||
+			    (cnp->cn_nameiop == DELETE &&
+			    cnp->cn_flags & DOWHITEOUT &&
+			    cnp->cn_flags & ISWHITEOUT))) {
 				error = VOP_ACCESS(dvp, VWRITE, cnp->cn_cred,
 				    cnp->cn_thread);
 				if (error != 0)
@@ -834,6 +839,8 @@ tmpfs_remove(struct vop_remove_args *v)
 	/* Remove the entry from the directory; as it is a file, we do not
 	 * have to change the number of hard links of the directory. */
 	tmpfs_dir_detach(dvp, de);
+	if (v->a_cnp->cn_flags & DOWHITEOUT)
+		tmpfs_dir_whiteout_add(dvp, v->a_cnp);
 
 	/* Free the directory entry we just deleted.  Note that the node
 	 * referred by it will not be removed until the vnode is really
@@ -904,6 +911,8 @@ tmpfs_link(struct vop_link_args *v)
 		goto out;
 
 	/* Insert the new directory entry into the appropriate directory. */
+	if (cnp->cn_flags & ISWHITEOUT)
+		tmpfs_dir_whiteout_remove(dvp, cnp);
 	tmpfs_dir_attach(dvp, de);
 
 	/* vp link count has changed, so update node times. */
@@ -1099,6 +1108,10 @@ tmpfs_rename(struct vop_rename_args *v)
 		/* Do the move: just remove the entry from the source directory
 		 * and insert it into the target one. */
 		tmpfs_dir_detach(fdvp, de);
+		if (fcnp->cn_flags & DOWHITEOUT)
+			tmpfs_dir_whiteout_add(fdvp, fcnp);
+		if (tcnp->cn_flags & ISWHITEOUT)
+			tmpfs_dir_whiteout_remove(tdvp, tcnp);
 		tmpfs_dir_attach(tdvp, de);
 	}
 
@@ -1223,6 +1236,8 @@ tmpfs_rmdir(struct vop_rmdir_args *v)
 
 	/* Detach the directory entry from the directory (dnode). */
 	tmpfs_dir_detach(dvp, de);
+	if (v->a_cnp->cn_flags & DOWHITEOUT)
+		tmpfs_dir_whiteout_add(dvp, v->a_cnp);
 
 	/* No vnode should be allocated for this entry from this point */
 	TMPFS_NODE_LOCK(node);
@@ -1541,6 +1556,29 @@ tmpfs_vptofh(struct vop_vptofh_args *ap)
 	return (0);
 }
 
+static int
+tmpfs_whiteout(struct vop_whiteout_args *ap)
+{
+	struct vnode *dvp = ap->a_dvp;
+	struct componentname *cnp = ap->a_cnp;
+	struct tmpfs_dirent *de;
+
+	switch (ap->a_flags) {
+	case LOOKUP:
+		return (0);
+	case CREATE:
+		de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
+		if (de != NULL)
+			return (de->td_node == NULL ? 0 : EEXIST);
+		return (tmpfs_dir_whiteout_add(dvp, cnp));
+	case DELETE:
+		tmpfs_dir_whiteout_remove(dvp, cnp);
+		return (0);
+	default:
+		panic("tmpfs_whiteout: unknown op");
+	}
+}
+
 /* --------------------------------------------------------------------- */
 
 /*
@@ -1573,6 +1611,7 @@ struct vop_vector tmpfs_vnodeop_entries = {
 	.vop_print =			tmpfs_print,
 	.vop_pathconf =			tmpfs_pathconf,
 	.vop_vptofh =			tmpfs_vptofh,
+	.vop_whiteout =			tmpfs_whiteout,
 	.vop_bmap =			VOP_EOPNOTSUPP,
 };
 

From 5e3caca7f6916de0db240efa49cde5bbbe0e934b Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 10:13:56 +0000
Subject: [PATCH 0142/1624] Add the FreeBSD definition for the fasttrap ioctls.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap.h | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap.h b/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap.h
index 7f803144bcf..58967fd6c12 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap.h
@@ -37,9 +37,14 @@
 extern "C" {
 #endif
 
+#if defined(sun)
 #define	FASTTRAPIOC		(('m' << 24) | ('r' << 16) | ('f' << 8))
 #define	FASTTRAPIOC_MAKEPROBE	(FASTTRAPIOC | 1)
 #define	FASTTRAPIOC_GETINSTR	(FASTTRAPIOC | 2)
+#else
+#define	FASTTRAPIOC_MAKEPROBE	_IOW('f', 1, fasttrap_probe_spec_t)
+#define	FASTTRAPIOC_GETINSTR	_IOWR('f', 2, uint8_t)
+#endif
 
 typedef enum fasttrap_probe_type {
 	DTFTP_NONE = 0,

From 58f668bba5db03b9b94c495678ba64a75d10b06e Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 10:40:15 +0000
Subject: [PATCH 0143/1624] Add a function compatibility function
 dtrace_instr_size_isa() that on FreeBSD does the same as dtrace_dis_isize().

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/dev/dtrace/amd64/instr_size.c | 7 +++++++
 sys/cddl/dev/dtrace/i386/instr_size.c  | 7 +++++++
 2 files changed, 14 insertions(+)

diff --git a/sys/cddl/dev/dtrace/amd64/instr_size.c b/sys/cddl/dev/dtrace/amd64/instr_size.c
index 418d9f1fb53..1acf2c5813e 100644
--- a/sys/cddl/dev/dtrace/amd64/instr_size.c
+++ b/sys/cddl/dev/dtrace/amd64/instr_size.c
@@ -47,6 +47,7 @@
 typedef	u_int			model_t;
 #define	DATAMODEL_NATIVE	0
 int dtrace_instr_size(uchar_t *);
+int dtrace_instr_size_isa(uchar_t *, model_t, int *);
 #endif
 
 #include 
@@ -124,6 +125,12 @@ dtrace_dis_isize(uchar_t *instr, dis_isize_t which, model_t model, int *rmindex)
 	return (sz);
 }
 
+int
+dtrace_instr_size_isa(uchar_t *instr, model_t model, int *rmindex)
+{
+	return (dtrace_dis_isize(instr, DIS_ISIZE_INSTR, model, rmindex));
+}
+
 int
 dtrace_instr_size(uchar_t *instr)
 {
diff --git a/sys/cddl/dev/dtrace/i386/instr_size.c b/sys/cddl/dev/dtrace/i386/instr_size.c
index fb6af2d0abd..7f667f7e5ca 100644
--- a/sys/cddl/dev/dtrace/i386/instr_size.c
+++ b/sys/cddl/dev/dtrace/i386/instr_size.c
@@ -47,6 +47,7 @@
 typedef	u_int			model_t;
 #define	DATAMODEL_NATIVE	0
 int dtrace_instr_size(uchar_t *);
+int dtrace_instr_size_isa(uchar_t *, model_t, int *);
 #endif
 
 #include 
@@ -124,6 +125,12 @@ dtrace_dis_isize(uchar_t *instr, dis_isize_t which, model_t model, int *rmindex)
 	return (sz);
 }
 
+int
+dtrace_instr_size_isa(uchar_t *instr, model_t model, int *rmindex)
+{
+	return (dtrace_dis_isize(instr, DIS_ISIZE_INSTR, model, rmindex));
+}
+
 int
 dtrace_instr_size(uchar_t *instr)
 {

From c6f5742f90cd2f1cb8a5d0c2fb5c16b43bd3d977 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 10:53:32 +0000
Subject: [PATCH 0144/1624] Kernel DTrace support for: o uregs  (sson@) o
 ustack (sson@) o /dev/dtrace/helper device (needed for USDT probes)

The work done by me was:
Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/uts/common/dtrace/dtrace.c    |  50 +--
 .../opensolaris/uts/common/sys/dtrace_impl.h  |   2 +-
 sys/cddl/dev/dtrace/amd64/dtrace_isa.c        | 198 +++++------
 sys/cddl/dev/dtrace/amd64/regset.h            | 127 ++++++++
 sys/cddl/dev/dtrace/dtrace_ioctl.c            |  49 +++
 sys/cddl/dev/dtrace/dtrace_load.c             |   5 +-
 sys/cddl/dev/dtrace/i386/dtrace_isa.c         | 307 ++++++++++--------
 sys/cddl/dev/dtrace/i386/regset.h             | 127 ++++++++
 sys/cddl/dev/systrace/systrace.c              |  15 +-
 sys/sys/sysent.h                              |   3 +-
 10 files changed, 625 insertions(+), 258 deletions(-)
 create mode 100644 sys/cddl/dev/dtrace/amd64/regset.h
 create mode 100644 sys/cddl/dev/dtrace/i386/regset.h

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
index 70282e9a3a2..a4684bd2653 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
@@ -551,20 +551,16 @@ static void dtrace_enabling_provide(dtrace_provider_t *);
 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
 static void dtrace_enabling_matchall(void);
 static dtrace_state_t *dtrace_anon_grab(void);
-#if defined(sun)
 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
     dtrace_state_t *, uint64_t, uint64_t);
 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
-#endif
 static void dtrace_buffer_drop(dtrace_buffer_t *);
 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
     dtrace_state_t *, dtrace_mstate_t *);
 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
     dtrace_optval_t);
 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
-#if defined(sun)
 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
-#endif
 uint16_t dtrace_load16(uintptr_t);
 uint32_t dtrace_load32(uintptr_t);
 uint64_t dtrace_load64(uintptr_t);
@@ -2784,6 +2780,21 @@ dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
 		return (dtrace_getreg(lwp->lwp_regs, ndx));
 		return (0);
 	}
+#else
+	case DIF_VAR_UREGS: {
+		struct trapframe *tframe;
+
+		if (!dtrace_priv_proc(state))
+			return (0);
+
+		if ((tframe = curthread->td_frame) == NULL) {
+			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
+			cpu_core[curcpu].cpuc_dtrace_illval = 0;
+			return (0);
+		}
+
+		return (dtrace_getreg(tframe, ndx));
+	}
 #endif
 
 	case DIF_VAR_CURTHREAD:
@@ -2839,7 +2850,6 @@ dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
 		}
 		return (mstate->dtms_stackdepth);
 
-#if defined(sun)
 	case DIF_VAR_USTACKDEPTH:
 		if (!dtrace_priv_proc(state))
 			return (0);
@@ -2859,7 +2869,6 @@ dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
 		}
 		return (mstate->dtms_ustackdepth);
-#endif
 
 	case DIF_VAR_CALLER:
 		if (!dtrace_priv_kernel(state))
@@ -2896,7 +2905,6 @@ dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
 		}
 		return (mstate->dtms_caller);
 
-#if defined(sun)
 	case DIF_VAR_UCALLER:
 		if (!dtrace_priv_proc(state))
 			return (0);
@@ -2920,7 +2928,6 @@ dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
 		}
 
 		return (mstate->dtms_ucaller);
-#endif
 
 	case DIF_VAR_PROBEPROV:
 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
@@ -5736,7 +5743,6 @@ dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
 	cpu->cpu_dtrace_chilled += val;
 }
 
-#if defined(sun)
 static void
 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
     uint64_t *buf, uint64_t arg)
@@ -5849,7 +5855,6 @@ dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
 out:
 	mstate->dtms_scratch_ptr = old;
 }
-#endif
 
 /*
  * If you're looking for the epicenter of DTrace, you just found it.  This
@@ -6172,7 +6177,6 @@ dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
 				    (uint32_t *)arg0);
 				continue;
 
-#if defined(sun)
 			case DTRACEACT_JSTACK:
 			case DTRACEACT_USTACK:
 				if (!dtrace_priv_proc(state))
@@ -6214,7 +6218,6 @@ dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
 				continue;
-#endif
 
 			default:
 				break;
@@ -8141,7 +8144,6 @@ dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
 	dtrace_enabling_matchall();
 }
 
-#if defined(sun)
 static void
 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
 {
@@ -8189,7 +8191,6 @@ dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
 		dtrace_helper_provider_remove_one(dhp, sec, pid);
 	}
 }
-#endif
 
 /*
  * DTrace Meta Provider-to-Framework API Functions
@@ -8729,7 +8730,6 @@ dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
 	return (err);
 }
 
-#if defined(sun)
 /*
  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
  * are much more constrained than normal DIFOs.  Specifically, they may
@@ -8887,7 +8887,6 @@ dtrace_difo_validate_helper(dtrace_difo_t *dp)
 
 	return (err);
 }
-#endif
 
 /*
  * Returns 1 if the expression in the DIF object can be cached on a per-thread
@@ -13791,7 +13790,6 @@ dtrace_anon_property(void)
 	}
 }
 
-#if defined(sun)
 /*
  * DTrace Helper Functions
  */
@@ -13855,9 +13853,7 @@ dtrace_helper_trace(dtrace_helper_action_t *helper,
 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
 	}
 }
-#endif
 
-#if defined(sun)
 static uint64_t
 dtrace_helper(int which, dtrace_mstate_t *mstate,
     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
@@ -13865,7 +13861,7 @@ dtrace_helper(int which, dtrace_mstate_t *mstate,
 	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
 	uint64_t sarg0 = mstate->dtms_arg[0];
 	uint64_t sarg1 = mstate->dtms_arg[1];
-	uint64_t rval;
+	uint64_t rval = 0;
 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
 	dtrace_helper_action_t *helper;
 	dtrace_vstate_t *vstate;
@@ -14056,9 +14052,7 @@ dtrace_helper_destroygen(int gen)
 
 	return (0);
 }
-#endif
 
-#if defined(sun)
 static int
 dtrace_helper_validate(dtrace_helper_action_t *helper)
 {
@@ -14073,9 +14067,7 @@ dtrace_helper_validate(dtrace_helper_action_t *helper)
 
 	return (err == 0);
 }
-#endif
 
-#if defined(sun)
 static int
 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
 {
@@ -14622,6 +14614,7 @@ dtrace_helpers_create(proc_t *p)
 	return (help);
 }
 
+#if defined(sun)
 static void
 dtrace_helpers_destroy(void)
 {
@@ -16466,6 +16459,7 @@ _fini(void)
 #else
 
 static d_ioctl_t	dtrace_ioctl;
+static d_ioctl_t	dtrace_ioctl_helper;
 static void		dtrace_load(void *);
 static int		dtrace_unload(void);
 #if __FreeBSD_version < 800039
@@ -16474,6 +16468,7 @@ static struct clonedevs	*dtrace_clones;		/* Ptr to the array of cloned devices.
 static eventhandler_tag	eh_tag;			/* Event handler tag. */
 #else
 static struct cdev	*dtrace_dev;
+static struct cdev	*helper_dev;
 #endif
 
 void dtrace_invop_init(void);
@@ -16488,6 +16483,13 @@ static struct cdevsw dtrace_cdevsw = {
 	.d_name		= "dtrace",
 };
 
+static struct cdevsw helper_cdevsw = {
+	.d_version	= D_VERSION,
+	.d_flags	= D_TRACKCLOSE | D_NEEDMINOR,
+	.d_ioctl	= dtrace_ioctl_helper,
+	.d_name		= "helper",
+};
+
 #include 
 #if __FreeBSD_version < 800039
 #include 
diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace_impl.h b/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace_impl.h
index 369d41a35ed..6870a0b2b2e 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace_impl.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace_impl.h
@@ -1268,7 +1268,7 @@ extern void dtrace_copyout(uintptr_t, uintptr_t, size_t, volatile uint16_t *);
 extern void dtrace_copyoutstr(uintptr_t, uintptr_t, size_t,
     volatile uint16_t *);
 extern void dtrace_getpcstack(pc_t *, int, int, uint32_t *);
-extern ulong_t dtrace_getreg(struct regs *, uint_t);
+extern ulong_t dtrace_getreg(struct trapframe *, uint_t);
 extern int dtrace_getstackdepth(int);
 extern void dtrace_getupcstack(uint64_t *, int);
 extern void dtrace_getufpstack(uint64_t *, uint64_t *, int);
diff --git a/sys/cddl/dev/dtrace/amd64/dtrace_isa.c b/sys/cddl/dev/dtrace/amd64/dtrace_isa.c
index c58e88ec71a..d9ed0800654 100644
--- a/sys/cddl/dev/dtrace/amd64/dtrace_isa.c
+++ b/sys/cddl/dev/dtrace/amd64/dtrace_isa.c
@@ -42,6 +42,7 @@
 #include 
 #include 
 
+#include "regset.h"
 
 uint8_t dtrace_fuword8_nocheck(void *);
 uint16_t dtrace_fuword16_nocheck(void *);
@@ -103,12 +104,11 @@ dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
 {
 	volatile uint16_t *flags =
 	    (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
-	struct amd64_frame *frame;
 	int ret = 0;
 
 	ASSERT(pcstack == NULL || pcstack_limit > 0);
 
-	while (pc != 0 && sp != 0) {
+	while (pc != 0) {
 		ret++;
 		if (pcstack != NULL) {
 			*pcstack++ = (uint64_t)pc;
@@ -117,10 +117,12 @@ dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
 				break;
 		}
 
-		frame = (struct amd64_frame *) sp;
+		if (sp == 0)
+			break;
 
-		pc = dtrace_fulword(&frame->f_retaddr);
-		sp = dtrace_fulword(&frame->f_frame);
+		pc = dtrace_fuword64((void *)(sp +
+			offsetof(struct amd64_frame, f_retaddr)));
+		sp = dtrace_fuword64((void *)sp);
 
 		/*
 		 * This is totally bogus:  if we faulted, we're going to clear
@@ -141,7 +143,7 @@ dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
 {
 	proc_t *p = curproc;
 	struct trapframe *tf;
-	uintptr_t pc, sp;
+	uintptr_t pc, sp, fp;
 	volatile uint16_t *flags =
 	    (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
 	int n;
@@ -165,18 +167,28 @@ dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
 		return;
 
 	pc = tf->tf_rip;
+	fp = tf->tf_rbp;
 	sp = tf->tf_rsp;
 
 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
+		/* 
+		 * In an entry probe.  The frame pointer has not yet been
+		 * pushed (that happens in the function prologue).  The
+		 * best approach is to add the current pc as a missing top
+		 * of stack and back the pc up to the caller, which is stored
+		 * at the current stack pointer address since the call 
+		 * instruction puts it there right before the branch.
+		 */
+
 		*pcstack++ = (uint64_t)pc;
 		pcstack_limit--;
 		if (pcstack_limit <= 0)
 			return;
 
-		pc = dtrace_fulword((void *) sp);
+		pc = dtrace_fuword64((void *) sp);
 	}
 
-	n = dtrace_getustack_common(pcstack, pcstack_limit, pc, sp);
+	n = dtrace_getustack_common(pcstack, pcstack_limit, pc, fp);
 	ASSERT(n >= 0);
 	ASSERT(n <= pcstack_limit);
 
@@ -193,7 +205,7 @@ dtrace_getustackdepth(void)
 {
 	proc_t *p = curproc;
 	struct trapframe *tf;
-	uintptr_t pc, sp;
+	uintptr_t pc, fp, sp;
 	int n = 0;
 
 	if (p == NULL || (tf = curthread->td_frame) == NULL)
@@ -203,30 +215,40 @@ dtrace_getustackdepth(void)
 		return (-1);
 
 	pc = tf->tf_rip;
+	fp = tf->tf_rbp;
 	sp = tf->tf_rsp;
 
 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
-		n++;
+		/* 
+		 * In an entry probe.  The frame pointer has not yet been
+		 * pushed (that happens in the function prologue).  The
+		 * best approach is to add the current pc as a missing top
+		 * of stack and back the pc up to the caller, which is stored
+		 * at the current stack pointer address since the call 
+		 * instruction puts it there right before the branch.
+		 */
 
-		pc = dtrace_fulword((void *) sp);
+		pc = dtrace_fuword64((void *) sp);
+		n++;
 	}
 
-	n += dtrace_getustack_common(NULL, 0, pc, sp);
+	n += dtrace_getustack_common(NULL, 0, pc, fp);
 
 	return (n);
 }
 
-#ifdef notyet
 void
 dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 {
-	klwp_t *lwp = ttolwp(curthread);
 	proc_t *p = curproc;
-	struct regs *rp;
-	uintptr_t pc, sp, oldcontext;
+	struct trapframe *tf;
+	uintptr_t pc, sp, fp;
 	volatile uint16_t *flags =
 	    (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
+#ifdef notyet	/* XXX signal stack */
+	uintptr_t oldcontext;
 	size_t s1, s2;
+#endif
 
 	if (*flags & CPU_DTRACE_FAULT)
 		return;
@@ -237,7 +259,7 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 	/*
 	 * If there's no user context we still need to zero the stack.
 	 */
-	if (lwp == NULL || p == NULL || (rp = lwp->lwp_regs) == NULL)
+	if (p == NULL || (tf = curthread->td_frame) == NULL)
 		goto zero;
 
 	*pcstack++ = (uint64_t)p->p_pid;
@@ -246,12 +268,15 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 	if (pcstack_limit <= 0)
 		return;
 
-	pc = rp->r_pc;
-	sp = rp->r_fp;
-	oldcontext = lwp->lwp_oldcontext;
+	pc = tf->tf_rip;
+	sp = tf->tf_rsp;
+	fp = tf->tf_rbp;
 
+#ifdef notyet /* XXX signal stack */
+	oldcontext = lwp->lwp_oldcontext;
 	s1 = sizeof (struct xframe) + 2 * sizeof (long);
 	s2 = s1 + sizeof (siginfo_t);
+#endif
 
 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
 		*pcstack++ = (uint64_t)pc;
@@ -260,19 +285,20 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 		if (pcstack_limit <= 0)
 			return;
 
-		if (p->p_model == DATAMODEL_NATIVE)
-			pc = dtrace_fulword((void *)rp->r_sp);
-		else
-			pc = dtrace_fuword32((void *)rp->r_sp);
+		pc = dtrace_fuword64((void *)sp);
 	}
 
-	while (pc != 0 && sp != 0) {
+	while (pc != 0) {
 		*pcstack++ = (uint64_t)pc;
-		*fpstack++ = sp;
+		*fpstack++ = fp;
 		pcstack_limit--;
 		if (pcstack_limit <= 0)
 			break;
 
+		if (fp == 0)
+			break;
+
+#ifdef notyet /* XXX signal stack */
 		if (oldcontext == sp + s1 || oldcontext == sp + s2) {
 			ucontext_t *ucp = (ucontext_t *)oldcontext;
 			greg_t *gregs = ucp->uc_mcontext.gregs;
@@ -281,11 +307,12 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 			pc = dtrace_fulword(&gregs[REG_PC]);
 
 			oldcontext = dtrace_fulword(&ucp->uc_link);
-		} else {
-			struct xframe *fr = (struct xframe *)sp;
-
-			pc = dtrace_fulword(&fr->fr_savpc);
-			sp = dtrace_fulword(&fr->fr_savfp);
+		} else
+#endif /* XXX */
+		{
+			pc = dtrace_fuword64((void *)(fp +
+				offsetof(struct amd64_frame, f_retaddr)));
+			fp = dtrace_fuword64((void *)fp);
 		}
 
 		/*
@@ -301,9 +328,8 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 
 zero:
 	while (pcstack_limit-- > 0)
-		*pcstack++ = NULL;
+		*pcstack++ = 0;
 }
-#endif
 
 /*ARGSUSED*/
 uint64_t
@@ -412,31 +438,30 @@ dtrace_getstackdepth(int aframes)
 		return depth - aframes;
 }
 
-#ifdef notyet
 ulong_t
-dtrace_getreg(struct regs *rp, uint_t reg)
+dtrace_getreg(struct trapframe *rp, uint_t reg)
 {
-#if defined(__amd64)
+	/* This table is dependent on reg.d. */
 	int regmap[] = {
-		REG_GS,		/* GS */
-		REG_FS,		/* FS */
-		REG_ES,		/* ES */
-		REG_DS,		/* DS */
-		REG_RDI,	/* EDI */
-		REG_RSI,	/* ESI */
-		REG_RBP,	/* EBP */
-		REG_RSP,	/* ESP */
-		REG_RBX,	/* EBX */
-		REG_RDX,	/* EDX */
-		REG_RCX,	/* ECX */
-		REG_RAX,	/* EAX */
-		REG_TRAPNO,	/* TRAPNO */
-		REG_ERR,	/* ERR */
-		REG_RIP,	/* EIP */
-		REG_CS,		/* CS */
-		REG_RFL,	/* EFL */
-		REG_RSP,	/* UESP */
-		REG_SS		/* SS */
+		REG_GS,		/* 0  GS */
+		REG_FS,		/* 1  FS */
+		REG_ES,		/* 2  ES */
+		REG_DS,		/* 3  DS */
+		REG_RDI,	/* 4  EDI */
+		REG_RSI,	/* 5  ESI */
+		REG_RBP,	/* 6  EBP, REG_FP */
+		REG_RSP,	/* 7  ESP */
+		REG_RBX,	/* 8  EBX, REG_R1 */
+		REG_RDX,	/* 9  EDX */
+		REG_RCX,	/* 10 ECX */
+		REG_RAX,	/* 11 EAX, REG_R0 */
+		REG_TRAPNO,	/* 12 TRAPNO */
+		REG_ERR,	/* 13 ERR */
+		REG_RIP,	/* 14 EIP, REG_PC */
+		REG_CS,		/* 15 CS */
+		REG_RFL,	/* 16 EFL, REG_PS */
+		REG_RSP,	/* 17 UESP, REG_SP */
+		REG_SS		/* 18 SS */
 	};
 
 	if (reg <= SS) {
@@ -447,77 +472,68 @@ dtrace_getreg(struct regs *rp, uint_t reg)
 
 		reg = regmap[reg];
 	} else {
+		/* This is dependent on reg.d. */
 		reg -= SS + 1;
 	}
 
 	switch (reg) {
 	case REG_RDI:
-		return (rp->r_rdi);
+		return (rp->tf_rdi);
 	case REG_RSI:
-		return (rp->r_rsi);
+		return (rp->tf_rsi);
 	case REG_RDX:
-		return (rp->r_rdx);
+		return (rp->tf_rdx);
 	case REG_RCX:
-		return (rp->r_rcx);
+		return (rp->tf_rcx);
 	case REG_R8:
-		return (rp->r_r8);
+		return (rp->tf_r8);
 	case REG_R9:
-		return (rp->r_r9);
+		return (rp->tf_r9);
 	case REG_RAX:
-		return (rp->r_rax);
+		return (rp->tf_rax);
 	case REG_RBX:
-		return (rp->r_rbx);
+		return (rp->tf_rbx);
 	case REG_RBP:
-		return (rp->r_rbp);
+		return (rp->tf_rbp);
 	case REG_R10:
-		return (rp->r_r10);
+		return (rp->tf_r10);
 	case REG_R11:
-		return (rp->r_r11);
+		return (rp->tf_r11);
 	case REG_R12:
-		return (rp->r_r12);
+		return (rp->tf_r12);
 	case REG_R13:
-		return (rp->r_r13);
+		return (rp->tf_r13);
 	case REG_R14:
-		return (rp->r_r14);
+		return (rp->tf_r14);
 	case REG_R15:
-		return (rp->r_r15);
+		return (rp->tf_r15);
 	case REG_DS:
-		return (rp->r_ds);
+		return (rp->tf_ds);
 	case REG_ES:
-		return (rp->r_es);
+		return (rp->tf_es);
 	case REG_FS:
-		return (rp->r_fs);
+		return (rp->tf_fs);
 	case REG_GS:
-		return (rp->r_gs);
+		return (rp->tf_gs);
 	case REG_TRAPNO:
-		return (rp->r_trapno);
+		return (rp->tf_trapno);
 	case REG_ERR:
-		return (rp->r_err);
+		return (rp->tf_err);
 	case REG_RIP:
-		return (rp->r_rip);
+		return (rp->tf_rip);
 	case REG_CS:
-		return (rp->r_cs);
+		return (rp->tf_cs);
 	case REG_SS:
-		return (rp->r_ss);
+		return (rp->tf_ss);
 	case REG_RFL:
-		return (rp->r_rfl);
+		return (rp->tf_rflags);
 	case REG_RSP:
-		return (rp->r_rsp);
+		return (rp->tf_rsp);
 	default:
 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
 		return (0);
 	}
-
-#else
-	if (reg > SS) {
-		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
-		return (0);
-	}
-
-	return ((&rp->r_gs)[reg]);
-#endif
 }
-#endif
 
 static int
 dtrace_copycheck(uintptr_t uaddr, uintptr_t kaddr, size_t size)
diff --git a/sys/cddl/dev/dtrace/amd64/regset.h b/sys/cddl/dev/dtrace/amd64/regset.h
new file mode 100644
index 00000000000..d6732ff5e99
--- /dev/null
+++ b/sys/cddl/dev/dtrace/amd64/regset.h
@@ -0,0 +1,127 @@
+/*
+ * 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
+ *
+ * $FreeBSD$ 
+ */
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+/*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc. */
+
+/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T		*/
+/*	All Rights Reserved	*/
+
+#ifndef	_REGSET_H
+#define	_REGSET_H
+
+/*
+ * #pragma ident	"@(#)regset.h	1.11	05/06/08 SMI"
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The names and offsets defined here should be specified by the
+ * AMD64 ABI suppl.
+ *
+ * We make fsbase and gsbase part of the lwp context (since they're
+ * the only way to access the full 64-bit address range via the segment
+ * registers) and thus belong here too.  However we treat them as
+ * read-only; if %fs or %gs are updated, the results of the descriptor
+ * table lookup that those updates implicitly cause will be reflected
+ * in the corresponding fsbase and/or gsbase values the next time the
+ * context can be inspected.  However it is NOT possible to override
+ * the fsbase/gsbase settings via this interface.
+ *
+ * Direct modification of the base registers (thus overriding the
+ * descriptor table base address) can be achieved with _lwp_setprivate.
+ */
+
+#define	REG_GSBASE	27
+#define	REG_FSBASE	26
+#define	REG_DS		25
+#define	REG_ES		24
+
+#define	REG_GS		23
+#define	REG_FS		22
+#define	REG_SS		21
+#define	REG_RSP		20
+#define	REG_RFL		19
+#define	REG_CS		18
+#define	REG_RIP		17
+#define	REG_ERR		16
+#define	REG_TRAPNO	15
+#define	REG_RAX		14
+#define	REG_RCX		13
+#define	REG_RDX		12
+#define	REG_RBX		11
+#define	REG_RBP		10
+#define	REG_RSI		9
+#define	REG_RDI		8
+#define	REG_R8		7
+#define	REG_R9		6
+#define	REG_R10		5
+#define	REG_R11		4
+#define	REG_R12		3
+#define	REG_R13		2
+#define	REG_R14		1
+#define	REG_R15		0
+
+/*
+ * The names and offsets defined here are specified by i386 ABI suppl.
+ */
+
+#define	SS		18	/* only stored on a privilege transition */
+#define	UESP		17	/* only stored on a privilege transition */
+#define	EFL		16
+#define	CS		15
+#define	EIP		14
+#define	ERR		13
+#define	TRAPNO		12
+#define	EAX		11
+#define	ECX		10
+#define	EDX		9
+#define	EBX		8
+#define	ESP		7
+#define	EBP		6
+#define	ESI		5
+#define	EDI		4
+#define	DS		3
+#define	ES		2
+#define	FS		1
+#define	GS		0
+
+#define REG_PC  EIP
+#define REG_FP  EBP
+#define REG_SP  UESP
+#define REG_PS  EFL
+#define REG_R0  EAX
+#define REG_R1  EDX
+
+#ifdef	__cplusplus
+}
+#endif
+
+#endif	/* _REGSET_H */
diff --git a/sys/cddl/dev/dtrace/dtrace_ioctl.c b/sys/cddl/dev/dtrace/dtrace_ioctl.c
index bc408c43e55..79fea7bb79d 100644
--- a/sys/cddl/dev/dtrace/dtrace_ioctl.c
+++ b/sys/cddl/dev/dtrace/dtrace_ioctl.c
@@ -27,6 +27,55 @@ SYSCTL_INT(_debug_dtrace, OID_AUTO, verbose_ioctl, CTLFLAG_RW, &dtrace_verbose_i
 
 #define DTRACE_IOCTL_PRINTF(fmt, ...)	if (dtrace_verbose_ioctl) printf(fmt, ## __VA_ARGS__ )
 
+static int
+dtrace_ioctl_helper(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
+    struct thread *td)
+{
+	int rval;
+	dof_helper_t *dhp = NULL;
+	dof_hdr_t *dof = NULL;
+
+	switch (cmd) {
+	case DTRACEHIOC_ADDDOF:
+		dhp = (dof_helper_t *)addr;
+		/* XXX all because dofhp_dof is 64 bit */
+#ifdef __i386
+		addr = (caddr_t)(uint32_t)dhp->dofhp_dof;
+#else
+		addr = (caddr_t)dhp->dofhp_dof;
+#endif
+		/* FALLTHROUGH */
+	case DTRACEHIOC_ADD:
+		dof = dtrace_dof_copyin((intptr_t)addr, &rval);
+
+		if (dof == NULL)
+			return (rval);
+
+		mutex_enter(&dtrace_lock);
+		if ((rval = dtrace_helper_slurp((dof_hdr_t *)dof, dhp)) != -1) {
+			if (dhp) {
+				dhp->gen = rval;
+				copyout(dhp, addr, sizeof(*dhp));
+			}
+			rval = 0;
+		} else {
+			rval = EINVAL;
+		}
+		mutex_exit(&dtrace_lock);
+		return (rval);
+	case DTRACEHIOC_REMOVE:
+		mutex_enter(&dtrace_lock);
+		rval = dtrace_helper_destroygen((int)*addr);
+		mutex_exit(&dtrace_lock);
+
+		return (rval);
+	default:
+		break;
+	}
+
+	return (ENOTTY);
+}
+
 /* ARGSUSED */
 static int
 dtrace_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
diff --git a/sys/cddl/dev/dtrace/dtrace_load.c b/sys/cddl/dev/dtrace/dtrace_load.c
index accee4706ac..912fe976b68 100644
--- a/sys/cddl/dev/dtrace/dtrace_load.c
+++ b/sys/cddl/dev/dtrace/dtrace_load.c
@@ -161,7 +161,10 @@ dtrace_load(void *dummy)
 	/* Setup device cloning events. */
 	eh_tag = EVENTHANDLER_REGISTER(dev_clone, dtrace_clone, 0, 1000);
 #else
-	dtrace_dev = make_dev(&dtrace_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "dtrace/dtrace");
+	dtrace_dev = make_dev(&dtrace_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
+	    "dtrace/dtrace");
+	helper_dev = make_dev(&helper_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
+	    "dtrace/helper");
 #endif
 
 	return;
diff --git a/sys/cddl/dev/dtrace/i386/dtrace_isa.c b/sys/cddl/dev/dtrace/i386/dtrace_isa.c
index bf891aa39e1..3f73a50ef2e 100644
--- a/sys/cddl/dev/dtrace/i386/dtrace_isa.c
+++ b/sys/cddl/dev/dtrace/i386/dtrace_isa.c
@@ -33,13 +33,17 @@
 #include 
 #include 
 
+#include 
 #include 
+#include 
 #include 
 
 #include 
 #include 
 #include 
 
+#include "regset.h"
+
 extern uintptr_t kernbase;
 uintptr_t kernelbase = (uintptr_t) &kernbase;
 
@@ -100,21 +104,22 @@ dtrace_getpcstack(pc_t *pcstack, int pcstack_limit, int aframes,
 	}
 }
 
-#ifdef notyet
 static int
 dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
     uintptr_t sp)
 {
-	klwp_t *lwp = ttolwp(curthread);
+#ifdef notyet
 	proc_t *p = curproc;
-	uintptr_t oldcontext = lwp->lwp_oldcontext;
+	uintptr_t oldcontext = lwp->lwp_oldcontext; /* XXX signal stack. */
+	size_t s1, s2;
+#endif
 	volatile uint16_t *flags =
 	    (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
-	size_t s1, s2;
 	int ret = 0;
 
 	ASSERT(pcstack == NULL || pcstack_limit > 0);
 
+#ifdef notyet /* XXX signal stack. */
 	if (p->p_model == DATAMODEL_NATIVE) {
 		s1 = sizeof (struct frame) + 2 * sizeof (long);
 		s2 = s1 + sizeof (siginfo_t);
@@ -122,8 +127,9 @@ dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
 		s1 = sizeof (struct frame32) + 3 * sizeof (int);
 		s2 = s1 + sizeof (siginfo32_t);
 	}
+#endif
 
-	while (pc != 0 && sp != 0) {
+	while (pc != 0) {
 		ret++;
 		if (pcstack != NULL) {
 			*pcstack++ = (uint64_t)pc;
@@ -132,6 +138,10 @@ dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
 				break;
 		}
 
+		if (sp == 0)
+			break;
+
+#ifdef notyet /* XXX signal stack. */ 
 		if (oldcontext == sp + s1 || oldcontext == sp + s2) {
 			if (p->p_model == DATAMODEL_NATIVE) {
 				ucontext_t *ucp = (ucontext_t *)oldcontext;
@@ -163,6 +173,11 @@ dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
 				sp = dtrace_fuword32(&fr->fr_savfp);
 			}
 		}
+#else
+		pc = dtrace_fuword32((void *)(sp +
+			offsetof(struct i386_frame, f_retaddr)));
+		sp = dtrace_fuword32((void *)sp);
+#endif /* ! notyet */
 
 		/*
 		 * This is totally bogus:  if we faulted, we're going to clear
@@ -181,10 +196,9 @@ dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, uintptr_t pc,
 void
 dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
 {
-	klwp_t *lwp = ttolwp(curthread);
 	proc_t *p = curproc;
-	struct regs *rp;
-	uintptr_t pc, sp;
+	struct trapframe *tf;
+	uintptr_t pc, sp, fp;
 	volatile uint16_t *flags =
 	    (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
 	int n;
@@ -198,7 +212,7 @@ dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
 	/*
 	 * If there's no user context we still need to zero the stack.
 	 */
-	if (lwp == NULL || p == NULL || (rp = lwp->lwp_regs) == NULL)
+	if (p == NULL || (tf = curthread->td_frame) == NULL)
 		goto zero;
 
 	*pcstack++ = (uint64_t)p->p_pid;
@@ -207,19 +221,26 @@ dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
 	if (pcstack_limit <= 0)
 		return;
 
-	pc = rp->r_pc;
-	sp = rp->r_fp;
+	pc = tf->tf_eip;
+	fp = tf->tf_ebp;
+	sp = tf->tf_esp;
 
 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
+		/*
+		 * In an entry probe.  The frame pointer has not yet been
+		 * pushed (that happens in the function prologue).  The
+		 * best approach is to add the current pc as a missing top
+		 * of stack and back the pc up to the caller, which is stored
+		 * at the current stack pointer address since the call 
+		 * instruction puts it there right before the branch.
+		 */
+
 		*pcstack++ = (uint64_t)pc;
 		pcstack_limit--;
 		if (pcstack_limit <= 0)
 			return;
 
-		if (p->p_model == DATAMODEL_NATIVE)
-			pc = dtrace_fulword((void *)rp->r_sp);
-		else
-			pc = dtrace_fuword32((void *)rp->r_sp);
+		pc = dtrace_fuword32((void *) sp);
 	}
 
 	n = dtrace_getustack_common(pcstack, pcstack_limit, pc, sp);
@@ -231,24 +252,58 @@ dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
 
 zero:
 	while (pcstack_limit-- > 0)
-		*pcstack++ = NULL;
+		*pcstack++ = 0;
 }
 
 int
 dtrace_getustackdepth(void)
 {
+	proc_t *p = curproc;
+	struct trapframe *tf;
+	uintptr_t pc, fp, sp;
+	int n = 0;
+
+	if (p == NULL || (tf = curthread->td_frame) == NULL)
+		return (0);
+
+	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
+		return (-1);
+
+	pc = tf->tf_eip;
+	fp = tf->tf_ebp;
+	sp = tf->tf_esp;
+
+	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
+		/*
+		 * In an entry probe.  The frame pointer has not yet been
+		 * pushed (that happens in the function prologue).  The
+		 * best approach is to add the current pc as a missing top
+		 * of stack and back the pc up to the caller, which is stored
+		 * at the current stack pointer address since the call 
+		 * instruction puts it there right before the branch.
+		 */
+
+		pc = dtrace_fuword32((void *) sp);
+		n++;
+	}
+
+	n += dtrace_getustack_common(NULL, 0, pc, fp);
+
+	return (n);
 }
 
 void
 dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 {
-	klwp_t *lwp = ttolwp(curthread);
 	proc_t *p = curproc;
-	struct regs *rp;
-	uintptr_t pc, sp, oldcontext;
+	struct trapframe *tf;
+	uintptr_t pc, sp, fp;
 	volatile uint16_t *flags =
 	    (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
+#ifdef notyet /* XXX signal stack */
+	uintptr_t oldcontext;
 	size_t s1, s2;
+#endif
 
 	if (*flags & CPU_DTRACE_FAULT)
 		return;
@@ -259,7 +314,7 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 	/*
 	 * If there's no user context we still need to zero the stack.
 	 */
-	if (lwp == NULL || p == NULL || (rp = lwp->lwp_regs) == NULL)
+	if (p == NULL || (tf = curthread->td_frame) == NULL)
 		goto zero;
 
 	*pcstack++ = (uint64_t)p->p_pid;
@@ -268,8 +323,11 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 	if (pcstack_limit <= 0)
 		return;
 
-	pc = rp->r_pc;
-	sp = rp->r_fp;
+	pc = tf->tf_eip;
+	fp = tf->tf_ebp;
+	sp = tf->tf_esp;
+
+#ifdef notyet /* XXX signal stack */
 	oldcontext = lwp->lwp_oldcontext;
 
 	if (p->p_model == DATAMODEL_NATIVE) {
@@ -279,6 +337,7 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 		s1 = sizeof (struct frame32) + 3 * sizeof (int);
 		s2 = s1 + sizeof (siginfo32_t);
 	}
+#endif
 
 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
 		*pcstack++ = (uint64_t)pc;
@@ -287,19 +346,20 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 		if (pcstack_limit <= 0)
 			return;
 
-		if (p->p_model == DATAMODEL_NATIVE)
-			pc = dtrace_fulword((void *)rp->r_sp);
-		else
-			pc = dtrace_fuword32((void *)rp->r_sp);
+		pc = dtrace_fuword32((void *)sp);
 	}
 
-	while (pc != 0 && sp != 0) {
+	while (pc != 0) {
 		*pcstack++ = (uint64_t)pc;
-		*fpstack++ = sp;
+		*fpstack++ = fp;
 		pcstack_limit--;
 		if (pcstack_limit <= 0)
 			break;
 
+		if (fp == 0)
+			break;
+
+#ifdef notyet /* XXX signal stack */
 		if (oldcontext == sp + s1 || oldcontext == sp + s2) {
 			if (p->p_model == DATAMODEL_NATIVE) {
 				ucontext_t *ucp = (ucontext_t *)oldcontext;
@@ -318,18 +378,12 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 
 				oldcontext = dtrace_fuword32(&ucp->uc_link);
 			}
-		} else {
-			if (p->p_model == DATAMODEL_NATIVE) {
-				struct frame *fr = (struct frame *)sp;
-
-				pc = dtrace_fulword(&fr->fr_savpc);
-				sp = dtrace_fulword(&fr->fr_savfp);
-			} else {
-				struct frame32 *fr = (struct frame32 *)sp;
-
-				pc = dtrace_fuword32(&fr->fr_savpc);
-				sp = dtrace_fuword32(&fr->fr_savfp);
-			}
+		} else
+#endif /* XXX */
+		{
+			pc = dtrace_fuword32((void *)(fp +
+				offsetof(struct i386_frame, f_retaddr)));
+			fp = dtrace_fuword32((void *)fp);
 		}
 
 		/*
@@ -345,9 +399,8 @@ dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
 
 zero:
 	while (pcstack_limit-- > 0)
-		*pcstack++ = NULL;
+		*pcstack++ = 0;
 }
-#endif
 
 uint64_t
 dtrace_getarg(int arg, int aframes)
@@ -424,112 +477,92 @@ dtrace_getstackdepth(int aframes)
 		return depth - aframes;
 }
 
-#ifdef notyet
 ulong_t
-dtrace_getreg(struct regs *rp, uint_t reg)
+dtrace_getreg(struct trapframe *rp, uint_t reg)
 {
-#if defined(__amd64)
-	int regmap[] = {
-		REG_GS,		/* GS */
-		REG_FS,		/* FS */
-		REG_ES,		/* ES */
-		REG_DS,		/* DS */
-		REG_RDI,	/* EDI */
-		REG_RSI,	/* ESI */
-		REG_RBP,	/* EBP */
-		REG_RSP,	/* ESP */
-		REG_RBX,	/* EBX */
-		REG_RDX,	/* EDX */
-		REG_RCX,	/* ECX */
-		REG_RAX,	/* EAX */
-		REG_TRAPNO,	/* TRAPNO */
-		REG_ERR,	/* ERR */
-		REG_RIP,	/* EIP */
-		REG_CS,		/* CS */
-		REG_RFL,	/* EFL */
-		REG_RSP,	/* UESP */
-		REG_SS		/* SS */
+	struct pcb *pcb;
+	int regmap[] = {  /* Order is dependent on reg.d */
+		REG_GS,		/* 0  GS */
+		REG_FS,		/* 1  FS */
+		REG_ES,		/* 2  ES */
+		REG_DS,		/* 3  DS */
+		REG_RDI,	/* 4  EDI */
+		REG_RSI,	/* 5  ESI */
+		REG_RBP,	/* 6  EBP, REG_FP */
+		REG_RSP,	/* 7  ESP */
+		REG_RBX,	/* 8  EBX */
+		REG_RDX,	/* 9  EDX, REG_R1 */
+		REG_RCX,	/* 10 ECX */
+		REG_RAX,	/* 11 EAX, REG_R0 */
+		REG_TRAPNO,	/* 12 TRAPNO */
+		REG_ERR,	/* 13 ERR */
+		REG_RIP,	/* 14 EIP, REG_PC */
+		REG_CS,		/* 15 CS */
+		REG_RFL,	/* 16 EFL, REG_PS */
+		REG_RSP,	/* 17 UESP, REG_SP */
+		REG_SS		/* 18 SS */
 	};
 
-	if (reg <= SS) {
-		if (reg >= sizeof (regmap) / sizeof (int)) {
-			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
-			return (0);
-		}
-
-		reg = regmap[reg];
-	} else {
-		reg -= SS + 1;
-	}
-
-	switch (reg) {
-	case REG_RDI:
-		return (rp->r_rdi);
-	case REG_RSI:
-		return (rp->r_rsi);
-	case REG_RDX:
-		return (rp->r_rdx);
-	case REG_RCX:
-		return (rp->r_rcx);
-	case REG_R8:
-		return (rp->r_r8);
-	case REG_R9:
-		return (rp->r_r9);
-	case REG_RAX:
-		return (rp->r_rax);
-	case REG_RBX:
-		return (rp->r_rbx);
-	case REG_RBP:
-		return (rp->r_rbp);
-	case REG_R10:
-		return (rp->r_r10);
-	case REG_R11:
-		return (rp->r_r11);
-	case REG_R12:
-		return (rp->r_r12);
-	case REG_R13:
-		return (rp->r_r13);
-	case REG_R14:
-		return (rp->r_r14);
-	case REG_R15:
-		return (rp->r_r15);
-	case REG_DS:
-		return (rp->r_ds);
-	case REG_ES:
-		return (rp->r_es);
-	case REG_FS:
-		return (rp->r_fs);
-	case REG_GS:
-		return (rp->r_gs);
-	case REG_TRAPNO:
-		return (rp->r_trapno);
-	case REG_ERR:
-		return (rp->r_err);
-	case REG_RIP:
-		return (rp->r_rip);
-	case REG_CS:
-		return (rp->r_cs);
-	case REG_SS:
-		return (rp->r_ss);
-	case REG_RFL:
-		return (rp->r_rfl);
-	case REG_RSP:
-		return (rp->r_rsp);
-	default:
-		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
-		return (0);
-	}
-
-#else
 	if (reg > SS) {
 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
 		return (0);
 	}
 
-	return ((&rp->r_gs)[reg]);
+	if (reg >= sizeof (regmap) / sizeof (int)) {
+		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
+		return (0);
+	}
+
+	reg = regmap[reg];
+
+	switch(reg) {
+	case REG_GS:
+		if ((pcb = curthread->td_pcb) == NULL) {
+			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
+			return (0);
+		}
+		return (pcb->pcb_gs);
+	case REG_FS:
+		return (rp->tf_fs);
+	case REG_ES:
+		return (rp->tf_es);
+	case REG_DS:
+		return (rp->tf_ds);
+	case REG_RDI:
+		return (rp->tf_edi);
+	case REG_RSI:
+		return (rp->tf_esi);
+	case REG_RBP:
+		return (rp->tf_ebp);
+	case REG_RSP:
+		return (rp->tf_isp);
+	case REG_RBX:
+		return (rp->tf_ebx);
+	case REG_RCX:
+		return (rp->tf_ecx);
+	case REG_RAX:
+		return (rp->tf_eax);
+	case REG_TRAPNO:
+		return (rp->tf_trapno);
+	case REG_ERR:
+		return (rp->tf_err);
+	case REG_RIP:
+		return (rp->tf_eip);
+	case REG_CS:
+		return (rp->tf_cs);
+	case REG_RFL:
+		return (rp->tf_eflags);
+#if 0
+	case REG_RSP:
+		return (rp->tf_esp);
 #endif
+	case REG_SS:
+		return (rp->tf_ss);
+	default:
+		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
+		return (0);
+	}
 }
-#endif
 
 static int
 dtrace_copycheck(uintptr_t uaddr, uintptr_t kaddr, size_t size)
diff --git a/sys/cddl/dev/dtrace/i386/regset.h b/sys/cddl/dev/dtrace/i386/regset.h
new file mode 100644
index 00000000000..d6732ff5e99
--- /dev/null
+++ b/sys/cddl/dev/dtrace/i386/regset.h
@@ -0,0 +1,127 @@
+/*
+ * 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
+ *
+ * $FreeBSD$ 
+ */
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+/*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc. */
+
+/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T		*/
+/*	All Rights Reserved	*/
+
+#ifndef	_REGSET_H
+#define	_REGSET_H
+
+/*
+ * #pragma ident	"@(#)regset.h	1.11	05/06/08 SMI"
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The names and offsets defined here should be specified by the
+ * AMD64 ABI suppl.
+ *
+ * We make fsbase and gsbase part of the lwp context (since they're
+ * the only way to access the full 64-bit address range via the segment
+ * registers) and thus belong here too.  However we treat them as
+ * read-only; if %fs or %gs are updated, the results of the descriptor
+ * table lookup that those updates implicitly cause will be reflected
+ * in the corresponding fsbase and/or gsbase values the next time the
+ * context can be inspected.  However it is NOT possible to override
+ * the fsbase/gsbase settings via this interface.
+ *
+ * Direct modification of the base registers (thus overriding the
+ * descriptor table base address) can be achieved with _lwp_setprivate.
+ */
+
+#define	REG_GSBASE	27
+#define	REG_FSBASE	26
+#define	REG_DS		25
+#define	REG_ES		24
+
+#define	REG_GS		23
+#define	REG_FS		22
+#define	REG_SS		21
+#define	REG_RSP		20
+#define	REG_RFL		19
+#define	REG_CS		18
+#define	REG_RIP		17
+#define	REG_ERR		16
+#define	REG_TRAPNO	15
+#define	REG_RAX		14
+#define	REG_RCX		13
+#define	REG_RDX		12
+#define	REG_RBX		11
+#define	REG_RBP		10
+#define	REG_RSI		9
+#define	REG_RDI		8
+#define	REG_R8		7
+#define	REG_R9		6
+#define	REG_R10		5
+#define	REG_R11		4
+#define	REG_R12		3
+#define	REG_R13		2
+#define	REG_R14		1
+#define	REG_R15		0
+
+/*
+ * The names and offsets defined here are specified by i386 ABI suppl.
+ */
+
+#define	SS		18	/* only stored on a privilege transition */
+#define	UESP		17	/* only stored on a privilege transition */
+#define	EFL		16
+#define	CS		15
+#define	EIP		14
+#define	ERR		13
+#define	TRAPNO		12
+#define	EAX		11
+#define	ECX		10
+#define	EDX		9
+#define	EBX		8
+#define	ESP		7
+#define	EBP		6
+#define	ESI		5
+#define	EDI		4
+#define	DS		3
+#define	ES		2
+#define	FS		1
+#define	GS		0
+
+#define REG_PC  EIP
+#define REG_FP  EBP
+#define REG_SP  UESP
+#define REG_PS  EFL
+#define REG_R0  EAX
+#define REG_R1  EDX
+
+#ifdef	__cplusplus
+}
+#endif
+
+#endif	/* _REGSET_H */
diff --git a/sys/cddl/dev/systrace/systrace.c b/sys/cddl/dev/systrace/systrace.c
index 72c25e4e291..3e992e3a553 100644
--- a/sys/cddl/dev/systrace/systrace.c
+++ b/sys/cddl/dev/systrace/systrace.c
@@ -153,22 +153,24 @@ static dtrace_provider_id_t	systrace_id;
  *       compat syscall from something like Linux.
  */
 static void
-systrace_probe(u_int32_t id, int sysnum, struct sysent *sysent, void *params)
+systrace_probe(u_int32_t id, int sysnum, struct sysent *sysent, void *params,
+    int ret)
 {
 	int		n_args	= 0;
 	u_int64_t	uargs[8];
 
+	memset(uargs, 0, sizeof(uargs));
 	/*
 	 * Check if this syscall has an argument conversion function
 	 * registered.
 	 */
-	if (sysent->sy_systrace_args_func != NULL)
+	if (params && sysent->sy_systrace_args_func != NULL) {
 		/*
 		 * Convert the syscall parameters using the registered
 		 * function.
 		 */
 		(*sysent->sy_systrace_args_func)(sysnum, params, uargs, &n_args);
-	else
+	} else if (params) {
 		/*
 		 * Use the built-in system call argument conversion
 		 * function to translate the syscall structure fields
@@ -176,6 +178,13 @@ systrace_probe(u_int32_t id, int sysnum, struct sysent *sysent, void *params)
 		 * expects.
 		 */
 		systrace_args(sysnum, params, uargs, &n_args);
+	} else {
+		/*
+		 * Since params is NULL, this is a 'return' probe.
+		 * Set arg0 and arg1 as the return value of this syscall.
+		 */
+		uargs[0] = uargs[1] = ret;
+	}
 
 	/* Process the probe using the converted argments. */
 	dtrace_probe(id, uargs[0], uargs[1], uargs[2], uargs[3], uargs[4]);
diff --git a/sys/sys/sysent.h b/sys/sys/sysent.h
index 4754f54a483..e726fcebde2 100644
--- a/sys/sys/sysent.h
+++ b/sys/sys/sysent.h
@@ -42,7 +42,8 @@ struct ksiginfo;
 typedef	int	sy_call_t(struct thread *, void *);
 
 /* Used by the machine dependent syscall() code. */
-typedef	void (*systrace_probe_func_t)(u_int32_t, int, struct sysent *, void *);
+typedef	void (*systrace_probe_func_t)(u_int32_t, int, struct sysent *, void *,
+    int);
 
 /*
  * Used by loaded syscalls to convert arguments to a DTrace array

From 193da04bd876291deb3230c4f15256eeca370ba4 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 22 Aug 2010 11:04:30 +0000
Subject: [PATCH 0145/1624] sh: Add a test for breaking from a loop outside the
 current function.

It is unwise to rely on this but I'd like to know if this would break.
---
 tools/regression/bin/sh/builtins/break3.0 | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
 create mode 100644 tools/regression/bin/sh/builtins/break3.0

diff --git a/tools/regression/bin/sh/builtins/break3.0 b/tools/regression/bin/sh/builtins/break3.0
new file mode 100644
index 00000000000..10a5ca88edf
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/break3.0
@@ -0,0 +1,15 @@
+# $FreeBSD$
+
+# We accept this and people might rely on it.
+# However, various other shells do not accept it.
+
+f() {
+	break
+	echo bad1
+}
+
+while :; do
+	f
+	echo bad2
+	exit 2
+done

From 6c4452088661419d5e588f7c573fc17d2a5f2ed1 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:04:43 +0000
Subject: [PATCH 0146/1624] Add more compatibility structure members needed by
 the upcoming fasttrap DTrace device.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/dev/dtrace/dtrace_cddl.h | 36 ++++++++++++++++++++++++++++---
 1 file changed, 33 insertions(+), 3 deletions(-)

diff --git a/sys/cddl/dev/dtrace/dtrace_cddl.h b/sys/cddl/dev/dtrace/dtrace_cddl.h
index 75fe8648cc1..d2adfbc07c3 100644
--- a/sys/cddl/dev/dtrace/dtrace_cddl.h
+++ b/sys/cddl/dev/dtrace/dtrace_cddl.h
@@ -36,6 +36,7 @@ typedef struct kdtrace_proc {
 	int		p_dtrace_probes;	/* Are there probes for this proc? */
 	u_int64_t	p_dtrace_count;		/* Number of DTrace tracepoints */
 	void		*p_dtrace_helpers;	/* DTrace helpers, if any */
+	int		p_dtrace_model;
 
 } kdtrace_proc_t;
 
@@ -59,6 +60,9 @@ typedef struct kdtrace_thread {
 					/* Handling a return probe. */
 			u_int8_t	_td_dtrace_ast;
 					/* Saved ast flag. */
+#ifdef __amd64__
+			u_int8_t	_td_dtrace_reg;
+#endif
 		} _tds;
 		u_long	_td_dtrace_ft;	/* Bitwise or of these flags. */
 	} _tdu;
@@ -67,6 +71,7 @@ typedef struct kdtrace_thread {
 #define	td_dtrace_step	_tdu._tds._td_dtrace_step
 #define	td_dtrace_ret	_tdu._tds._td_dtrace_ret
 #define	td_dtrace_ast	_tdu._tds._td_dtrace_ast
+#define	td_dtrace_reg	_tdu._tds._td_dtrace_reg
 
 	uintptr_t	td_dtrace_pc;	/* DTrace saved pc from fasttrap. */
 	uintptr_t	td_dtrace_npc;	/* DTrace next pc from fasttrap. */
@@ -74,6 +79,9 @@ typedef struct kdtrace_thread {
 					/* DTrace per-thread scratch location. */
 	uintptr_t	td_dtrace_astpc;
 					/* DTrace return sequence location. */
+#ifdef __amd64__
+	uintptr_t	td_dtrace_regv;
+#endif
 	u_int64_t	td_hrtime;	/* Last time on cpu. */
 	int		td_errno;	/* Syscall return value. */
 } kdtrace_thread_t;
@@ -89,16 +97,38 @@ typedef struct kdtrace_thread {
 #define	t_dtrace_stop	td_dtrace->td_dtrace_stop
 #define	t_dtrace_sig	td_dtrace->td_dtrace_sig
 #define	t_predcache	td_dtrace->td_predcache
-#define p_dtrace_helpers	p_dtrace->p_dtrace_helpers
+#define	t_dtrace_ft	td_dtrace->td_dtrace_ft
+#define	t_dtrace_on	td_dtrace->td_dtrace_on
+#define	t_dtrace_step	td_dtrace->td_dtrace_step
+#define	t_dtrace_ret	td_dtrace->td_dtrace_ret
+#define	t_dtrace_ast	td_dtrace->td_dtrace_ast
+#define	t_dtrace_reg	td_dtrace->td_dtrace_reg
+#define	t_dtrace_pc	td_dtrace->td_dtrace_pc
+#define	t_dtrace_npc	td_dtrace->td_dtrace_npc
+#define	t_dtrace_scrpc	td_dtrace->td_dtrace_scrpc
+#define	t_dtrace_astpc	td_dtrace->td_dtrace_astpc
+#define	t_dtrace_regv	td_dtrace->td_dtrace_regv
+#define	p_dtrace_helpers	p_dtrace->p_dtrace_helpers
+#define	p_dtrace_count	p_dtrace->p_dtrace_count
+#define	p_dtrace_probes	p_dtrace->p_dtrace_probes
+#define	p_model		p_dtrace->p_dtrace_model
+#define	DATAMODEL_NATIVE	0
+#ifdef __amd64__
+#define	DATAMODEL_LP64		0
+#define	DATAMODEL_ILP32		1
+#else
+#define	DATAMODEL_LP64		1
+#define	DATAMODEL_ILP32		0
+#endif
 
 /*
- * Definitions for fields in struct proc which are named differntly in FreeBSD.
+ * Definitions for fields in struct proc which are named differently in FreeBSD.
  */
 #define	p_cred		p_ucred
 #define	p_parent	p_pptr
 
 /*
- * Definitions for fields in struct thread which are named differntly in FreeBSD.
+ * Definitions for fields in struct thread which are named differently in FreeBSD.
  */
 #define	t_procp		td_proc
 #define	t_tid		td_tid

From de788cde7b5c4f48578c3478592199f8f8508aaf Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:05:37 +0000
Subject: [PATCH 0147/1624] Destroy the helper device when unloading.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/dev/dtrace/dtrace_unload.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/cddl/dev/dtrace/dtrace_unload.c b/sys/cddl/dev/dtrace/dtrace_unload.c
index 40b09dc463a..247cbb183dd 100644
--- a/sys/cddl/dev/dtrace/dtrace_unload.c
+++ b/sys/cddl/dev/dtrace/dtrace_unload.c
@@ -43,6 +43,7 @@ dtrace_unload()
 	}
 #else
 	destroy_dev(dtrace_dev);
+	destroy_dev(helper_dev);
 #endif
 
 	mutex_enter(&dtrace_provider_lock);

From 9f3a1843edb1c0a8377381e9a1484b352d1da8a3 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:08:18 +0000
Subject: [PATCH 0149/1624] Fix style issues.

Sponsored by:	The FreeBSD Foundation
---
 sys/kern/kern_dtrace.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)

diff --git a/sys/kern/kern_dtrace.c b/sys/kern/kern_dtrace.c
index 145535201e2..cfadee302dd 100644
--- a/sys/kern/kern_dtrace.c
+++ b/sys/kern/kern_dtrace.c
@@ -49,7 +49,8 @@ MALLOC_DEFINE(M_KDTRACE, "kdtrace", "DTrace hooks");
 size_t
 kdtrace_proc_size()
 {
-	return(KDTRACE_PROC_SIZE);
+
+	return (KDTRACE_PROC_SIZE);
 }
 
 static void
@@ -63,6 +64,7 @@ kdtrace_proc_ctor(void *arg __unused, struct proc *p)
 static void
 kdtrace_proc_dtor(void *arg __unused, struct proc *p)
 {
+
 	if (p->p_dtrace != NULL) {
 		free(p->p_dtrace, M_KDTRACE);
 		p->p_dtrace = NULL;
@@ -73,7 +75,7 @@ kdtrace_proc_dtor(void *arg __unused, struct proc *p)
 size_t
 kdtrace_thread_size()
 {
-	return(KDTRACE_THREAD_SIZE);
+	return (KDTRACE_THREAD_SIZE);
 }
 
 static void
@@ -87,6 +89,7 @@ kdtrace_thread_ctor(void *arg __unused, struct thread *td)
 static void
 kdtrace_thread_dtor(void *arg __unused, struct thread *td)
 {
+
 	if (td->td_dtrace != NULL) {
 		free(td->td_dtrace, M_KDTRACE);
 		td->td_dtrace = NULL;
@@ -99,10 +102,15 @@ kdtrace_thread_dtor(void *arg __unused, struct thread *td)
 static void
 init_dtrace(void *dummy __unused)
 {
-	EVENTHANDLER_REGISTER(process_ctor, kdtrace_proc_ctor, NULL, EVENTHANDLER_PRI_ANY);
-	EVENTHANDLER_REGISTER(process_dtor, kdtrace_proc_dtor, NULL, EVENTHANDLER_PRI_ANY);
-	EVENTHANDLER_REGISTER(thread_ctor, kdtrace_thread_ctor, NULL, EVENTHANDLER_PRI_ANY);
-	EVENTHANDLER_REGISTER(thread_dtor, kdtrace_thread_dtor, NULL, EVENTHANDLER_PRI_ANY);
+
+	EVENTHANDLER_REGISTER(process_ctor, kdtrace_proc_ctor, NULL,
+	    EVENTHANDLER_PRI_ANY);
+	EVENTHANDLER_REGISTER(process_dtor, kdtrace_proc_dtor, NULL,
+	    EVENTHANDLER_PRI_ANY);
+	EVENTHANDLER_REGISTER(thread_ctor, kdtrace_thread_ctor, NULL,
+	    EVENTHANDLER_PRI_ANY);
+	EVENTHANDLER_REGISTER(thread_dtor, kdtrace_thread_dtor, NULL,
+	    EVENTHANDLER_PRI_ANY);
 }
 
 SYSINIT(kdtrace, SI_SUB_KDTRACE, SI_ORDER_FIRST, init_dtrace, NULL);

From 258f5a255ee133b6b7d351f22c2c0d35799bcc47 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:09:53 +0000
Subject: [PATCH 0150/1624] Bump KDTRACE_THREAD_ZERO and use M_ZERO as a malloc
 flag instead of calling bzero.

Sponsored by:	The FreeBSD Foundation
---
 sys/kern/kern_dtrace.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/sys/kern/kern_dtrace.c b/sys/kern/kern_dtrace.c
index cfadee302dd..603b4cf8c4e 100644
--- a/sys/kern/kern_dtrace.c
+++ b/sys/kern/kern_dtrace.c
@@ -39,9 +39,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #define KDTRACE_PROC_SIZE	64
-#define KDTRACE_PROC_ZERO	8
 #define	KDTRACE_THREAD_SIZE	256
-#define	KDTRACE_THREAD_ZERO	64
 
 MALLOC_DEFINE(M_KDTRACE, "kdtrace", "DTrace hooks");
 
@@ -56,9 +54,8 @@ kdtrace_proc_size()
 static void
 kdtrace_proc_ctor(void *arg __unused, struct proc *p)
 {
-	p->p_dtrace = malloc(KDTRACE_PROC_SIZE, M_KDTRACE, M_WAITOK);
 
-	bzero(p->p_dtrace, KDTRACE_PROC_ZERO);
+	p->p_dtrace = malloc(KDTRACE_PROC_SIZE, M_KDTRACE, M_WAITOK|M_ZERO);
 }
 
 static void
@@ -75,15 +72,15 @@ kdtrace_proc_dtor(void *arg __unused, struct proc *p)
 size_t
 kdtrace_thread_size()
 {
+
 	return (KDTRACE_THREAD_SIZE);
 }
 
 static void
 kdtrace_thread_ctor(void *arg __unused, struct thread *td)
 {
-	td->td_dtrace = malloc(KDTRACE_THREAD_SIZE, M_KDTRACE, M_WAITOK);
 
-	bzero(td->td_dtrace, KDTRACE_THREAD_ZERO);
+	td->td_dtrace = malloc(KDTRACE_THREAD_SIZE, M_KDTRACE, M_WAITOK|M_ZERO);
 }
 
 static void

From 5b5779d0007bb7bd91b42d7853551b9433bc0a02 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:12:07 +0000
Subject: [PATCH 0151/1624] Remove an elif and add an or-clause.

Sponsored by:	The FreeBSD Foundation
---
 sys/modules/dtrace/Makefile | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/sys/modules/dtrace/Makefile b/sys/modules/dtrace/Makefile
index ba468788bbf..8fad00c2683 100644
--- a/sys/modules/dtrace/Makefile
+++ b/sys/modules/dtrace/Makefile
@@ -14,9 +14,7 @@ SUBDIR=		dtmalloc	\
 		sdt		\
 		systrace
 
-.if ${MACHINE_ARCH} == "amd64"
-SUBDIR+=	fbt
-.elif ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
 SUBDIR+=	fbt
 .endif
 

From 79856499bd6f3f11cd2bd6b140d36a1183cd49ad Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:18:57 +0000
Subject: [PATCH 0152/1624] Add an extra comment to the SDT probes definition.
 This allows us to get use '-' in probe names, matching the probe names in
 Solaris.[1]

Add userland SDT probes definitions to sys/sdt.h.

Sponsored by:	The FreeBSD Foundation
Discussed with:	rwaston [1]
---
 sys/kern/kern_exec.c             |  6 +--
 sys/kern/kern_exit.c             |  2 +-
 sys/kern/kern_fork.c             |  2 +-
 sys/kern/kern_priv.c             |  4 +-
 sys/kern/kern_proc.c             | 12 ++---
 sys/kern/kern_sig.c              |  6 +--
 sys/kern/kern_timeout.c          |  4 +-
 sys/kern/vfs_cache.c             | 32 ++++++------
 sys/kern/vfs_lookup.c            |  4 +-
 sys/kern/vfs_syscalls.c          |  4 +-
 sys/net/vnet.c                   | 14 +++--
 sys/opencrypto/deflate.c         |  8 +--
 sys/security/mac/mac_framework.c |  8 +--
 sys/security/mac/mac_internal.h  | 20 ++++----
 sys/sys/sdt.h                    | 87 ++++++++++++++++++++++----------
 sys/tools/vnode_if.awk           |  4 +-
 16 files changed, 128 insertions(+), 89 deletions(-)

diff --git a/sys/kern/kern_exec.c b/sys/kern/kern_exec.c
index c4bdb91c7e4..2e7e08a56f5 100644
--- a/sys/kern/kern_exec.c
+++ b/sys/kern/kern_exec.c
@@ -91,11 +91,11 @@ dtrace_execexit_func_t	dtrace_fasttrap_exec;
 #endif
 
 SDT_PROVIDER_DECLARE(proc);
-SDT_PROBE_DEFINE(proc, kernel, , exec);
+SDT_PROBE_DEFINE(proc, kernel, , exec, exec);
 SDT_PROBE_ARGTYPE(proc, kernel, , exec, 0, "char *");
-SDT_PROBE_DEFINE(proc, kernel, , exec_failure);
+SDT_PROBE_DEFINE(proc, kernel, , exec_failure, exec-failure);
 SDT_PROBE_ARGTYPE(proc, kernel, , exec_failure, 0, "int");
-SDT_PROBE_DEFINE(proc, kernel, , exec_success);
+SDT_PROBE_DEFINE(proc, kernel, , exec_success, exec-success);
 SDT_PROBE_ARGTYPE(proc, kernel, , exec_success, 0, "char *");
 
 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
diff --git a/sys/kern/kern_exit.c b/sys/kern/kern_exit.c
index a781f8bf87f..8358f7503a8 100644
--- a/sys/kern/kern_exit.c
+++ b/sys/kern/kern_exit.c
@@ -90,7 +90,7 @@ dtrace_execexit_func_t	dtrace_fasttrap_exit;
 #endif
 
 SDT_PROVIDER_DECLARE(proc);
-SDT_PROBE_DEFINE(proc, kernel, , exit);
+SDT_PROBE_DEFINE(proc, kernel, , exit, exit);
 SDT_PROBE_ARGTYPE(proc, kernel, , exit, 0, "int");
 
 /* Required to be non-static for SysVR4 emulator */
diff --git a/sys/kern/kern_fork.c b/sys/kern/kern_fork.c
index 03d8cbc6bc1..29aa1213cfc 100644
--- a/sys/kern/kern_fork.c
+++ b/sys/kern/kern_fork.c
@@ -84,7 +84,7 @@ dtrace_fork_func_t	dtrace_fasttrap_fork;
 #endif
 
 SDT_PROVIDER_DECLARE(proc);
-SDT_PROBE_DEFINE(proc, kernel, , create);
+SDT_PROBE_DEFINE(proc, kernel, , create, create);
 SDT_PROBE_ARGTYPE(proc, kernel, , create, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, , create, 1, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, , create, 2, "int");
diff --git a/sys/kern/kern_priv.c b/sys/kern/kern_priv.c
index 352e502338d..fd3a95c5759 100644
--- a/sys/kern/kern_priv.c
+++ b/sys/kern/kern_priv.c
@@ -60,8 +60,8 @@ SYSCTL_INT(_security_bsd, OID_AUTO, suser_enabled, CTLFLAG_RW,
 TUNABLE_INT("security.bsd.suser_enabled", &suser_enabled);
 
 SDT_PROVIDER_DEFINE(priv);
-SDT_PROBE_DEFINE1(priv, kernel, priv_check, priv_ok, "int");
-SDT_PROBE_DEFINE1(priv, kernel, priv_check, priv_err, "int");
+SDT_PROBE_DEFINE1(priv, kernel, priv_check, priv_ok, priv-ok, "int");
+SDT_PROBE_DEFINE1(priv, kernel, priv_check, priv_err, priv-err, "int");
 
 /*
  * Check a credential for privilege.  Lots of good reasons to deny privilege;
diff --git a/sys/kern/kern_proc.c b/sys/kern/kern_proc.c
index 223bf7d2542..4899946a568 100644
--- a/sys/kern/kern_proc.c
+++ b/sys/kern/kern_proc.c
@@ -82,30 +82,30 @@ __FBSDID("$FreeBSD$");
 #endif
 
 SDT_PROVIDER_DEFINE(proc);
-SDT_PROBE_DEFINE(proc, kernel, ctor, entry);
+SDT_PROBE_DEFINE(proc, kernel, ctor, entry, entry);
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, entry, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, entry, 1, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, entry, 2, "void *");
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, entry, 3, "int");
-SDT_PROBE_DEFINE(proc, kernel, ctor, return);
+SDT_PROBE_DEFINE(proc, kernel, ctor, return, return);
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, return, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, return, 1, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, return, 2, "void *");
 SDT_PROBE_ARGTYPE(proc, kernel, ctor, return, 3, "int");
-SDT_PROBE_DEFINE(proc, kernel, dtor, entry);
+SDT_PROBE_DEFINE(proc, kernel, dtor, entry, entry);
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, entry, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, entry, 1, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, entry, 2, "void *");
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, entry, 3, "struct thread *");
-SDT_PROBE_DEFINE(proc, kernel, dtor, return);
+SDT_PROBE_DEFINE(proc, kernel, dtor, return, return);
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, return, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, return, 1, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, dtor, return, 2, "void *");
-SDT_PROBE_DEFINE(proc, kernel, init, entry);
+SDT_PROBE_DEFINE(proc, kernel, init, entry, entry);
 SDT_PROBE_ARGTYPE(proc, kernel, init, entry, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, init, entry, 1, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, init, entry, 2, "int");
-SDT_PROBE_DEFINE(proc, kernel, init, return);
+SDT_PROBE_DEFINE(proc, kernel, init, return, return);
 SDT_PROBE_ARGTYPE(proc, kernel, init, return, 0, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, init, return, 1, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, init, return, 2, "int");
diff --git a/sys/kern/kern_sig.c b/sys/kern/kern_sig.c
index 8a322de1d62..c620bdc21bd 100644
--- a/sys/kern/kern_sig.c
+++ b/sys/kern/kern_sig.c
@@ -89,14 +89,14 @@ __FBSDID("$FreeBSD$");
 #define	ONSIG	32		/* NSIG for osig* syscalls.  XXX. */
 
 SDT_PROVIDER_DECLARE(proc);
-SDT_PROBE_DEFINE(proc, kernel, , signal_send);
+SDT_PROBE_DEFINE(proc, kernel, , signal_send, signal-send);
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_send, 0, "struct thread *");
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_send, 1, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_send, 2, "int");
-SDT_PROBE_DEFINE(proc, kernel, , signal_clear);
+SDT_PROBE_DEFINE(proc, kernel, , signal_clear, signal-clear);
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_clear, 0, "int");
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_clear, 1, "ksiginfo_t *");
-SDT_PROBE_DEFINE(proc, kernel, , signal_discard);
+SDT_PROBE_DEFINE(proc, kernel, , signal_discard, signal-discard);
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_discard, 0, "struct thread *");
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_discard, 1, "struct proc *");
 SDT_PROBE_ARGTYPE(proc, kernel, , signal_discard, 2, "int");
diff --git a/sys/kern/kern_timeout.c b/sys/kern/kern_timeout.c
index 78b094928b9..32d5691812d 100644
--- a/sys/kern/kern_timeout.c
+++ b/sys/kern/kern_timeout.c
@@ -57,10 +57,10 @@ __FBSDID("$FreeBSD$");
 #include 
 
 SDT_PROVIDER_DEFINE(callout_execute);
-SDT_PROBE_DEFINE(callout_execute, kernel, , callout_start);
+SDT_PROBE_DEFINE(callout_execute, kernel, , callout_start, callout-start);
 SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_start, 0,
     "struct callout *");
-SDT_PROBE_DEFINE(callout_execute, kernel, , callout_end); 
+SDT_PROBE_DEFINE(callout_execute, kernel, , callout_end, callout-end); 
 SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_end, 0,
     "struct callout *");
 
diff --git a/sys/kern/vfs_cache.c b/sys/kern/vfs_cache.c
index c0732ac63f7..026aec38ac6 100644
--- a/sys/kern/vfs_cache.c
+++ b/sys/kern/vfs_cache.c
@@ -61,28 +61,28 @@ __FBSDID("$FreeBSD$");
 #include 
 
 SDT_PROVIDER_DECLARE(vfs);
-SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
+SDT_PROBE_DEFINE3(vfs, namecache, enter, done, done, "struct vnode *", "char *",
     "struct vnode *");
-SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
+SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, done, "struct vnode *",
     "char *");
-SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
-SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
+SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, entry, "struct vnode *");
+SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, hit, "struct vnode *",
     "struct char *", "struct vnode *");
-SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
-SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int", "struct vnode *",
-    "struct char *");
-SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
+SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, miss, "struct vnode *");
+SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, return, "int",
+    "struct vnode *", "struct char *");
+SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, hit, "struct vnode *", "char *",
     "struct vnode *");
-SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit_negative, "struct vnode *",
+SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit_negative, hit-negative,
+    "struct vnode *", "char *");
+SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, miss, "struct vnode *",
     "char *");
-SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
-    "char *");
-SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
-SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
-SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
-SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
+SDT_PROBE_DEFINE1(vfs, namecache, purge, done, done, "struct vnode *");
+SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, done, "struct vnode *");
+SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, done, "struct mount *");
+SDT_PROBE_DEFINE3(vfs, namecache, zap, done, done, "struct vnode *", "char *",
     "struct vnode *");
-SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
+SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, done, "struct vnode *",
     "char *");
 
 /*
diff --git a/sys/kern/vfs_lookup.c b/sys/kern/vfs_lookup.c
index e0684b16bde..50a2570254f 100644
--- a/sys/kern/vfs_lookup.c
+++ b/sys/kern/vfs_lookup.c
@@ -68,9 +68,9 @@ __FBSDID("$FreeBSD$");
 #undef NAMEI_DIAGNOSTIC
 
 SDT_PROVIDER_DECLARE(vfs);
-SDT_PROBE_DEFINE3(vfs, namei, lookup, entry, "struct vnode *", "char *",
+SDT_PROBE_DEFINE3(vfs, namei, lookup, entry, entry, "struct vnode *", "char *",
     "unsigned long");
-SDT_PROBE_DEFINE2(vfs, namei, lookup, return, "int", "struct vnode *");
+SDT_PROBE_DEFINE2(vfs, namei, lookup, return, return, "int", "struct vnode *");
 
 /*
  * Allocation zone for namei
diff --git a/sys/kern/vfs_syscalls.c b/sys/kern/vfs_syscalls.c
index 4fd9dfa0e8f..9046d1cb17e 100644
--- a/sys/kern/vfs_syscalls.c
+++ b/sys/kern/vfs_syscalls.c
@@ -85,10 +85,10 @@ __FBSDID("$FreeBSD$");
 #include 
 
 SDT_PROVIDER_DEFINE(vfs);
-SDT_PROBE_DEFINE(vfs, , stat, mode);
+SDT_PROBE_DEFINE(vfs, , stat, mode, mode);
 SDT_PROBE_ARGTYPE(vfs, , stat, mode, 0, "char *");
 SDT_PROBE_ARGTYPE(vfs, , stat, mode, 1, "int");
-SDT_PROBE_DEFINE(vfs, , stat, reg);
+SDT_PROBE_DEFINE(vfs, , stat, reg, reg);
 SDT_PROBE_ARGTYPE(vfs, , stat, reg, 0, "char *");
 SDT_PROBE_ARGTYPE(vfs, , stat, reg, 1, "int");
 
diff --git a/sys/net/vnet.c b/sys/net/vnet.c
index fb0db347b32..8fc52b22798 100644
--- a/sys/net/vnet.c
+++ b/sys/net/vnet.c
@@ -208,11 +208,15 @@ static TAILQ_HEAD(, vnet_data_free) vnet_data_free_head =
 static struct sx vnet_data_free_lock;
 
 SDT_PROVIDER_DEFINE(vnet);
-SDT_PROBE_DEFINE1(vnet, functions, vnet_alloc, entry, "int");
-SDT_PROBE_DEFINE2(vnet, functions, vnet_alloc, alloc, "int", "struct vnet *");
-SDT_PROBE_DEFINE2(vnet, functions, vnet_alloc, return, "int", "struct vnet *");
-SDT_PROBE_DEFINE2(vnet, functions, vnet_destroy, entry, "int", "struct vnet *");
-SDT_PROBE_DEFINE1(vnet, functions, vnet_destroy, return, "int");
+SDT_PROBE_DEFINE1(vnet, functions, vnet_alloc, entry, entry, "int");
+SDT_PROBE_DEFINE2(vnet, functions, vnet_alloc, alloc, alloc, "int",
+    "struct vnet *");
+SDT_PROBE_DEFINE2(vnet, functions, vnet_alloc, return, return,
+    "int", "struct vnet *");
+SDT_PROBE_DEFINE2(vnet, functions, vnet_destroy, entry, entry,
+    "int", "struct vnet *");
+SDT_PROBE_DEFINE1(vnet, functions, vnet_destroy, return, entry,
+    "int");
 
 #ifdef DDB
 static void db_show_vnet_print_vs(struct vnet_sysinit *, int);
diff --git a/sys/opencrypto/deflate.c b/sys/opencrypto/deflate.c
index 2113611ae0d..deaf0527344 100644
--- a/sys/opencrypto/deflate.c
+++ b/sys/opencrypto/deflate.c
@@ -50,13 +50,13 @@ __FBSDID("$FreeBSD$");
 #include 
 
 SDT_PROVIDER_DECLARE(opencrypto);
-SDT_PROBE_DEFINE2(opencrypto, deflate, deflate_global, entry,
+SDT_PROBE_DEFINE2(opencrypto, deflate, deflate_global, entry, entry,
     "int", "u_int32_t");
-SDT_PROBE_DEFINE5(opencrypto, deflate, deflate_global, bad,
+SDT_PROBE_DEFINE5(opencrypto, deflate, deflate_global, bad, bad,
     "int", "int", "int", "int", "int");
-SDT_PROBE_DEFINE5(opencrypto, deflate, deflate_global, iter,
+SDT_PROBE_DEFINE5(opencrypto, deflate, deflate_global, iter, iter,
     "int", "int", "int", "int", "int");
-SDT_PROBE_DEFINE2(opencrypto, deflate, deflate_global, return,
+SDT_PROBE_DEFINE2(opencrypto, deflate, deflate_global, return, return,
     "int", "u_int32_t");
 
 int window_inflate = -1 * MAX_WBITS;
diff --git a/sys/security/mac/mac_framework.c b/sys/security/mac/mac_framework.c
index 1f43c0278f7..fa069280dcc 100644
--- a/sys/security/mac/mac_framework.c
+++ b/sys/security/mac/mac_framework.c
@@ -94,10 +94,12 @@ __FBSDID("$FreeBSD$");
 SDT_PROVIDER_DEFINE(mac);
 SDT_PROVIDER_DEFINE(mac_framework);
 
-SDT_PROBE_DEFINE2(mac, kernel, policy, modevent, "int",
+SDT_PROBE_DEFINE2(mac, kernel, policy, modevent, modevent, "int",
     "struct mac_policy_conf *mpc");
-SDT_PROBE_DEFINE1(mac, kernel, policy, register, "struct mac_policy_conf *");
-SDT_PROBE_DEFINE1(mac, kernel, policy, unregister, "struct mac_policy_conf *");
+SDT_PROBE_DEFINE1(mac, kernel, policy, register, register,
+    "struct mac_policy_conf *");
+SDT_PROBE_DEFINE1(mac, kernel, policy, unregister, unregister,
+    "struct mac_policy_conf *");
 
 /*
  * Root sysctl node for all MAC and MAC policy controls.
diff --git a/sys/security/mac/mac_internal.h b/sys/security/mac/mac_internal.h
index 39fc4042beb..72444772ab2 100644
--- a/sys/security/mac/mac_internal.h
+++ b/sys/security/mac/mac_internal.h
@@ -75,27 +75,27 @@ SDT_PROVIDER_DECLARE(mac_framework);	/* Entry points to MAC. */
 
 #define	MAC_CHECK_PROBE_DEFINE4(name, arg0, arg1, arg2, arg3)		\
 	SDT_PROBE_DEFINE5(mac_framework, kernel, name, mac_check_err,	\
-	    "int", arg0, arg1, arg2, arg3);				\
+	    mac-check-ok, "int", arg0, arg1, arg2, arg3);		\
 	SDT_PROBE_DEFINE5(mac_framework, kernel, name, mac_check_ok,	\
-	    "int", arg0, arg1, arg2, arg3);
+	    mac-check-ok, "int", arg0, arg1, arg2, arg3);
 
 #define	MAC_CHECK_PROBE_DEFINE3(name, arg0, arg1, arg2)			\
 	SDT_PROBE_DEFINE4(mac_framework, kernel, name, mac_check_err,	\
-	    "int", arg0, arg1, arg2);					\
+	    mac-check-err, "int", arg0, arg1, arg2);			\
 	SDT_PROBE_DEFINE4(mac_framework, kernel, name, mac_check_ok,	\
-	    "int", arg0, arg1, arg2);
+	    mac-check-ok, "int", arg0, arg1, arg2);
 
 #define	MAC_CHECK_PROBE_DEFINE2(name, arg0, arg1)			\
 	SDT_PROBE_DEFINE3(mac_framework, kernel, name, mac_check_err,	\
-	    "int", arg0, arg1);						\
+	    mac-check-err, "int", arg0, arg1);				\
 	SDT_PROBE_DEFINE3(mac_framework, kernel, name, mac_check_ok,	\
-	    "int", arg0, arg1);
+	    mac-check-ok, "int", arg0, arg1);
 
 #define	MAC_CHECK_PROBE_DEFINE1(name, arg0)				\
 	SDT_PROBE_DEFINE2(mac_framework, kernel, name, mac_check_err,	\
-	    "int", arg0);						\
+	    mac-check-err, "int", arg0);				\
 	SDT_PROBE_DEFINE2(mac_framework, kernel, name, mac_check_ok,	\
-	    "int", arg0);
+	    mac-check-ok, "int", arg0);
 
 #define	MAC_CHECK_PROBE4(name, error, arg0, arg1, arg2, arg3)	do {	\
 	if (error) {							\
@@ -117,9 +117,9 @@ SDT_PROVIDER_DECLARE(mac_framework);	/* Entry points to MAC. */
 
 #define	MAC_GRANT_PROBE_DEFINE2(name, arg0, arg1)			\
 	SDT_PROBE_DEFINE3(mac_framework, kernel, name, mac_grant_err,	\
-	    "int", arg0, arg1);						\
+	    mac-grant-err, "int", arg0, arg1);				\
 	SDT_PROBE_DEFINE3(mac_framework, kernel, name, mac_grant_ok,	\
-	    "INT", arg0, arg1);
+	    mac-grant-ok, "INT", arg0, arg1);
 
 #define	MAC_GRANT_PROBE2(name, error, arg0, arg1)	do {		\
 	if (error) {							\
diff --git a/sys/sys/sdt.h b/sys/sys/sdt.h
index eeae665c141..d9031023c4c 100644
--- a/sys/sys/sdt.h
+++ b/sys/sys/sdt.h
@@ -31,33 +31,66 @@
 #ifndef _SYS_SDT_H
 #define	_SYS_SDT_H
 
-/* Stub these for the time being. */
-#define	DTRACE_PROBE(name)
-#define	DTRACE_PROBE1(name, type1, arg1)
-#define	DTRACE_PROBE2(name, type1, arg1, type2, arg2)
-#define	DTRACE_PROBE3(name, type1, arg1, type2, arg2, type3, arg3)
-#define	DTRACE_PROBE4(name, type1, arg1, type2, arg2, type3, arg3, type4, arg4)
-
 #ifndef _KERNEL
 
-/* The promise of things to come. Worlds to explore. People to meet. Things to do. */
+#define	_DTRACE_VERSION	1
 
-#else
+#define	DTRACE_PROBE(prov, name) {				\
+	extern void __dtrace_##prov##___##name(void);		\
+	__dtrace_##prov##___##name();				\
+}
+
+#define	DTRACE_PROBE1(prov, name, arg1) {			\
+	extern void __dtrace_##prov##___##name(unsigned long);	\
+	__dtrace_##prov##___##name((unsigned long)arg1);	\
+}
+
+#define	DTRACE_PROBE2(prov, name, arg1, arg2) {			\
+	extern void __dtrace_##prov##___##name(unsigned long,	\
+	    unsigned long);					\
+	__dtrace_##prov##___##name((unsigned long)arg1,		\
+	    (unsigned long)arg2);				\
+}
+
+#define	DTRACE_PROBE3(prov, name, arg1, arg2, arg3) {		\
+	extern void __dtrace_##prov##___##name(unsigned long,	\
+	    unsigned long, unsigned long);			\
+	__dtrace_##prov##___##name((unsigned long)arg1,		\
+	    (unsigned long)arg2, (unsigned long)arg3);		\
+}
+
+#define	DTRACE_PROBE4(prov, name, arg1, arg2, arg3, arg4) {	\
+	extern void __dtrace_##prov##___##name(unsigned long,	\
+	    unsigned long, unsigned long, unsigned long);	\
+	__dtrace_##prov##___##name((unsigned long)arg1,		\
+	    (unsigned long)arg2, (unsigned long)arg3,		\
+	    (unsigned long)arg4);				\
+}
+
+#define	DTRACE_PROBE5(prov, name, arg1, arg2, arg3, arg4, arg5) {	\
+	extern void __dtrace_##prov##___##name(unsigned long,		\
+	    unsigned long, unsigned long, unsigned long, unsigned long);\
+	__dtrace_##prov##___##name((unsigned long)arg1,			\
+	    (unsigned long)arg2, (unsigned long)arg3,			\
+	    (unsigned long)arg4, (unsigned long)arg5);			\
+}
+
+#else /* _KERNEL */
 
 #ifndef KDTRACE_HOOKS
 
 #define SDT_PROVIDER_DEFINE(prov)
 #define SDT_PROVIDER_DECLARE(prov)
-#define SDT_PROBE_DEFINE(prov, mod, func, name)
+#define SDT_PROBE_DEFINE(prov, mod, func, name, sname)
 #define SDT_PROBE_DECLARE(prov, mod, func, name)
 #define SDT_PROBE(prov, mod, func, name, arg0, arg1, arg2, arg3, arg4)
 #define SDT_PROBE_ARGTYPE(prov, mod, func, name, num, type)
 
-#define	SDT_PROBE_DEFINE1(prov, mod, func, name, arg0)
-#define	SDT_PROBE_DEFINE2(prov, mod, func, name, arg0, arg1)
-#define	SDT_PROBE_DEFINE3(prov, mod, func, name, arg0, arg1, arg2)
-#define	SDT_PROBE_DEFINE4(prov, mod, func, name, arg0, arg1, arg2, arg3)
-#define	SDT_PROBE_DEFINE5(prov, mod, func, name, arg0, arg1, arg2, arg3, arg4)
+#define	SDT_PROBE_DEFINE1(prov, mod, func, name, sname, arg0)
+#define	SDT_PROBE_DEFINE2(prov, mod, func, name, sname, arg0, arg1)
+#define	SDT_PROBE_DEFINE3(prov, mod, func, name, sname, arg0, arg1, arg2)
+#define	SDT_PROBE_DEFINE4(prov, mod, func, name, sname, arg0, arg1, arg2, arg3)
+#define	SDT_PROBE_DEFINE5(prov, mod, func, name, sname, arg0, arg1, arg2, arg3, arg4)
 
 #define	SDT_PROBE1(prov, mod, func, name, arg0)
 #define	SDT_PROBE2(prov, mod, func, name, arg0, arg1)
@@ -135,10 +168,10 @@ struct sdt_provider {
 #define SDT_PROVIDER_DECLARE(prov)						\
 	extern struct sdt_provider sdt_provider_##prov[1]
 
-#define SDT_PROBE_DEFINE(prov, mod, func, name)					\
+#define SDT_PROBE_DEFINE(prov, mod, func, name, sname)				\
 	struct sdt_probe sdt_##prov##_##mod##_##func##_##name[1] = {		\
 		{ sizeof(struct sdt_probe), 0, sdt_provider_##prov,		\
-		    { NULL, NULL }, { NULL, NULL }, #mod, #func, #name, 0, 0 }	\
+		    { NULL, NULL }, { NULL, NULL }, #mod, #func, #sname, 0, 0 }	\
 	};									\
 	SYSINIT(sdt_##prov##_##mod##_##func##_##name##_init, SI_SUB_KDTRACE, 	\
 	    SI_ORDER_SECOND + 1, sdt_probe_register, 				\
@@ -168,30 +201,30 @@ struct sdt_provider {
 	    SI_SUB_KDTRACE, SI_ORDER_SECOND + 2, sdt_argtype_deregister,	\
 	    sdt_##prov##_##mod##_##func##_##name##num )
 
-#define	SDT_PROBE_DEFINE1(prov, mod, func, name, arg0)			\
-	SDT_PROBE_DEFINE(prov, mod, func, name);			\
+#define	SDT_PROBE_DEFINE1(prov, mod, func, name, sname, arg0)		\
+	SDT_PROBE_DEFINE(prov, mod, func, name, sname);			\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 0, arg0)
 
-#define	SDT_PROBE_DEFINE2(prov, mod, func, name, arg0, arg1)		\
-	SDT_PROBE_DEFINE(prov, mod, func, name);			\
+#define	SDT_PROBE_DEFINE2(prov, mod, func, name, sname, arg0, arg1)	\
+	SDT_PROBE_DEFINE(prov, mod, func, name, sname);			\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 0, arg0);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 1, arg1)
 
-#define	SDT_PROBE_DEFINE3(prov, mod, func, name, arg0, arg1, arg2)	\
-	SDT_PROBE_DEFINE(prov, mod, func, name);			\
+#define	SDT_PROBE_DEFINE3(prov, mod, func, name, sname, arg0, arg1, arg2)\
+	SDT_PROBE_DEFINE(prov, mod, func, name, sname);			\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 0, arg0);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 1, arg1);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 2, arg2)
 
-#define	SDT_PROBE_DEFINE4(prov, mod, func, name, arg0, arg1, arg2, arg3) \
-	SDT_PROBE_DEFINE(prov, mod, func, name);			\
+#define	SDT_PROBE_DEFINE4(prov, mod, func, name, sname, arg0, arg1, arg2, arg3) \
+	SDT_PROBE_DEFINE(prov, mod, func, name, sname);			\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 0, arg0);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 1, arg1);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 2, arg2);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 3, arg3)
 
-#define	SDT_PROBE_DEFINE5(prov, mod, func, name, arg0, arg1, arg2, arg3, arg4) \
-	SDT_PROBE_DEFINE(prov, mod, func, name);			\
+#define	SDT_PROBE_DEFINE5(prov, mod, func, name, sname, arg0, arg1, arg2, arg3, arg4) \
+	SDT_PROBE_DEFINE(prov, mod, func, name, sname);			\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 0, arg0);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 1, arg1);		\
 	SDT_PROBE_ARGTYPE(prov, mod, func, name, 2, arg2);		\
diff --git a/sys/tools/vnode_if.awk b/sys/tools/vnode_if.awk
index 86c6bdc522e..3fdea0a24c1 100644
--- a/sys/tools/vnode_if.awk
+++ b/sys/tools/vnode_if.awk
@@ -355,8 +355,8 @@ while ((getline < srcfile) > 0) {
 		printc("};");
 
 		printc("\n");
-		printc("SDT_PROBE_DEFINE2(vfs, vop, " name ", entry, \"struct vnode *\", \"struct " name "_args *\");\n");
-		printc("SDT_PROBE_DEFINE3(vfs, vop, " name ", return, \"struct vnode *\", \"struct " name "_args *\", \"int\");\n");
+		printc("SDT_PROBE_DEFINE2(vfs, vop, " name ", entry, entry, \"struct vnode *\", \"struct " name "_args *\");\n");
+		printc("SDT_PROBE_DEFINE3(vfs, vop, " name ", return, return, \"struct vnode *\", \"struct " name "_args *\", \"int\");\n");
 
 		# Print out function.
 		printc("\nint\n" uname "_AP(struct " name "_args *a)");

From b3d354c9ceccc7a9cc43b1abd1497170b451612c Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:30:49 +0000
Subject: [PATCH 0153/1624] Call the systrace_probe_func() when the error
 value.

Sponsored by:	The FreeBSD Foundation
---
 sys/kern/subr_trap.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/kern/subr_trap.c b/sys/kern/subr_trap.c
index 5c90d956e78..3884abf0465 100644
--- a/sys/kern/subr_trap.c
+++ b/sys/kern/subr_trap.c
@@ -312,7 +312,7 @@ syscallenter(struct thread *td, struct syscall_args *sa)
 		 */
 		if (systrace_probe_func != NULL && sa->callp->sy_entry != 0)
 			(*systrace_probe_func)(sa->callp->sy_entry, sa->code,
-			    sa->callp, sa->args);
+			    sa->callp, sa->args, 0);
 #endif
 
 		AUDIT_SYSCALL_ENTER(sa->code, td);
@@ -330,7 +330,7 @@ syscallenter(struct thread *td, struct syscall_args *sa)
 		 */
 		if (systrace_probe_func != NULL && sa->callp->sy_return != 0)
 			(*systrace_probe_func)(sa->callp->sy_return, sa->code,
-			    sa->callp, sa->args);
+			    sa->callp, NULL, (error) ? -1 : td->td_retval[0]);
 #endif
 		syscall_thread_exit(td, sa->callp);
 		CTR4(KTR_SYSC, "syscall: p=%p error=%d return %#lx %#lx",

From 4e41f3537a6aff9ca1df1e0c1dc694e24ac5db9e Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 22 Aug 2010 11:41:06 +0000
Subject: [PATCH 0154/1624] Port this to FreeBSD. We miss some suword
 functions, so we use copyout.

Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/uts/common/sys/fasttrap_impl.h  | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap_impl.h b/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap_impl.h
index 232b5f63330..a4e51fd04d6 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap_impl.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/fasttrap_impl.h
@@ -158,10 +158,16 @@ typedef struct fasttrap_hash {
  */
 #define	fasttrap_copyout	copyout
 #define	fasttrap_fuword32	fuword32
-#define	fasttrap_suword32	suword32
+#define	fasttrap_suword32(_k, _u)	copyout((_k), (_u), sizeof(uint32_t))
+#define	fasttrap_suword64(_k, _u)	copyout((_k), (_u), sizeof(uint64_t))
 
-#define	fasttrap_fulword	fulword
-#define	fasttrap_sulword	sulword
+#ifdef __amd64__
+#define	fasttrap_fulword	fuword64
+#define	fasttrap_sulword	fasttrap_suword64
+#else
+#define	fasttrap_fulword	fuword32
+#define	fasttrap_sulword	fasttrap_suword32
+#endif
 
 extern void fasttrap_sigtrap(proc_t *, kthread_t *, uintptr_t);
 
@@ -179,8 +185,9 @@ extern int fasttrap_tracepoint_init(proc_t *, fasttrap_tracepoint_t *,
 extern int fasttrap_tracepoint_install(proc_t *, fasttrap_tracepoint_t *);
 extern int fasttrap_tracepoint_remove(proc_t *, fasttrap_tracepoint_t *);
 
-extern int fasttrap_pid_probe(struct regs *);
-extern int fasttrap_return_probe(struct regs *);
+struct reg;
+extern int fasttrap_pid_probe(struct reg *);
+extern int fasttrap_return_probe(struct reg *);
 
 extern uint64_t fasttrap_pid_getarg(void *, dtrace_id_t, void *, int, int);
 extern uint64_t fasttrap_usdt_getarg(void *, dtrace_id_t, void *, int, int);

From b8370f59bd3d87905bb1e8a810f83d46d956cb7b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Sun, 22 Aug 2010 11:48:32 +0000
Subject: [PATCH 0155/1624] UTFize my name.

---
 lib/libutil/kld.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libutil/kld.c b/lib/libutil/kld.c
index bc806409f10..b4a6ab6d6fb 100644
--- a/lib/libutil/kld.c
+++ b/lib/libutil/kld.c
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2006 Dag-Erling Coïdan Smørgrav
+ * Copyright (c) 2006 Dag-Erling Coïdan Smørgrav
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without

From 36cf3efe4174756592699983628ea9850637d710 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 22 Aug 2010 13:04:00 +0000
Subject: [PATCH 0156/1624] sh(1): Add a brief summary of arithmetic
 expressions.

---
 bin/sh/sh.1 | 41 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 36 insertions(+), 5 deletions(-)

diff --git a/bin/sh/sh.1 b/bin/sh/sh.1
index 1498564e33a..ff89125c50e 100644
--- a/bin/sh/sh.1
+++ b/bin/sh/sh.1
@@ -32,7 +32,7 @@
 .\"	from: @(#)sh.1	8.6 (Berkeley) 5/4/95
 .\" $FreeBSD$
 .\"
-.Dd June 29, 2010
+.Dd August 22, 2010
 .Dt SH 1
 .Os
 .Sh NAME
@@ -1230,7 +1230,7 @@ Quote Removal.
 The
 .Ql $
 character is used to introduce parameter expansion, command
-substitution, or arithmetic evaluation.
+substitution, or arithmetic expansion.
 .Ss Tilde Expansion (substituting a user's home directory)
 A word beginning with an unquoted tilde character
 .Pq Ql ~
@@ -1463,10 +1463,41 @@ The
 shell expands all tokens in the
 .Ar expression
 for parameter expansion,
-command substitution, and quote removal.
+command substitution,
+arithmetic expansion
+and quote removal.
 .Pp
-Next, the shell treats this as an arithmetic expression and
-substitutes the value of the expression.
+The allowed expressions are a subset of C expressions,
+summarized below.
+.Bl -tag -width "Variables" -offset indent
+.It Values
+All values are of type
+.Ft intmax_t .
+.It Constants
+Decimal, octal (starting with
+.Li 0 )
+and hexadecimal (starting with 
+.Li 0x )
+integer constants.
+.It Variables
+Shell variables can be read and written
+and contain integer constants.
+.It Unary operators
+.Li "! ~ + -"
+.It Binary operators
+.Li "* / % + - << >> < <= > >= == != & ^ | && ||"
+.It Assignment operators
+.Li "= += -= *= /= %= <<= >>= &= ^= |="
+.It Short-circuit evaluation
+The
+.Li &&
+and
+.Li ||
+operators always evaluate both sides.
+This is a bug.
+.El
+.Pp
+The result of the expression is substituted in decimal.
 .Ss White Space Splitting (Field Splitting)
 After parameter expansion, command substitution, and
 arithmetic expansion the shell scans the results of

From 394357b2b6ca31315e7c47e062bc40c8c18bc091 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 22 Aug 2010 13:09:12 +0000
Subject: [PATCH 0157/1624] sh: Test that all bytes from 128 to 255 can be used
 in IFS.

To avoid multibyte issues, this test forces ISO8859-1 charset.

This also passes on stable/8.
---
 tools/regression/bin/sh/expansion/ifs3.0 | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
 create mode 100644 tools/regression/bin/sh/expansion/ifs3.0

diff --git a/tools/regression/bin/sh/expansion/ifs3.0 b/tools/regression/bin/sh/expansion/ifs3.0
new file mode 100644
index 00000000000..0569b5729ca
--- /dev/null
+++ b/tools/regression/bin/sh/expansion/ifs3.0
@@ -0,0 +1,21 @@
+# $FreeBSD$
+
+failures=0
+unset LC_ALL
+export LC_CTYPE=en_US.ISO8859-1
+i=128
+set -f
+while [ "$i" -le 255 ]; do
+	i2=$((i^2))
+	c=$(printf \\"$(printf %o "$i")")
+	c2=$(printf \\"$(printf %o "$i2")")
+	IFS=$c
+	set -- $c2$c$c2$c$c2
+	if [ "$#" -ne 3 ] || [ "$1" != "$c2" ] || [ "$2" != "$c2" ] ||
+	    [ "$3" != "$c2" ]; then
+		echo "Bad results for separator $i (word $i2)" >&2
+		: $((failures += 1))
+	fi
+	i=$((i+1))
+done
+exit $((failures > 0))

From 0f6bb099ae1f5b9b58f9aa38e6cd4e35a7d42f5d Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Sun, 22 Aug 2010 16:08:12 +0000
Subject: [PATCH 0158/1624] Introduce and use devfs_populate_vp() to unlock a
 vnode before calling devfs_populate(). This is a prerequisite for the
 automatic removal of empty directories which will be committed in the future.

Reviewed by:	kib (previous version)
---
 sys/fs/devfs/devfs_vnops.c | 82 ++++++++++++++++++++++++++------------
 1 file changed, 56 insertions(+), 26 deletions(-)

diff --git a/sys/fs/devfs/devfs_vnops.c b/sys/fs/devfs/devfs_vnops.c
index abf1dfadd38..2e106fe0af8 100644
--- a/sys/fs/devfs/devfs_vnops.c
+++ b/sys/fs/devfs/devfs_vnops.c
@@ -185,6 +185,43 @@ devfs_clear_cdevpriv(void)
 	devfs_fpdrop(fp);
 }
 
+/*
+ * On success devfs_populate_vp() returns with dmp->dm_lock held.
+ */
+static int
+devfs_populate_vp(struct vnode *vp)
+{
+	struct devfs_mount *dmp;
+	int locked;
+
+	ASSERT_VOP_LOCKED(vp, "devfs_populate_vp");
+
+	dmp = VFSTODEVFS(vp->v_mount);
+	locked = VOP_ISLOCKED(vp);
+
+	sx_xlock(&dmp->dm_lock);
+	DEVFS_DMP_HOLD(dmp);
+
+	/* Can't call devfs_populate() with the vnode lock held. */
+	VOP_UNLOCK(vp, 0);
+	devfs_populate(dmp);
+
+	sx_xunlock(&dmp->dm_lock);
+	vn_lock(vp, locked | LK_RETRY);
+	sx_xlock(&dmp->dm_lock);
+	if (DEVFS_DMP_DROP(dmp)) {
+		sx_xunlock(&dmp->dm_lock);
+		devfs_unmount_final(dmp);
+		return (EBADF);
+	}
+	if (vp->v_iflag & VI_DOOMED) {
+		sx_xunlock(&dmp->dm_lock);
+		return (EBADF);
+	}
+
+	return (0);
+}
+
 static int
 devfs_vptocnp(struct vop_vptocnp_args *ap)
 {
@@ -813,14 +850,6 @@ devfs_lookupx(struct vop_lookup_args *ap, int *dm_unlock)
 		return (error);
 	}
 
-	DEVFS_DMP_HOLD(dmp);
-	devfs_populate(dmp);
-	if (DEVFS_DMP_DROP(dmp)) {
-		*dm_unlock = 0;
-		sx_xunlock(&dmp->dm_lock);
-		devfs_unmount_final(dmp);
-		return (ENOENT);
-	}
 	dd = dvp->v_data;
 	de = devfs_find(dd, cnp->cn_nameptr, cnp->cn_namelen, 0);
 	while (de == NULL) {	/* While(...) so we can use break */
@@ -843,7 +872,20 @@ devfs_lookupx(struct vop_lookup_args *ap, int *dm_unlock)
 		EVENTHANDLER_INVOKE(dev_clone,
 		    td->td_ucred, pname, strlen(pname), &cdev);
 		sx_sunlock(&clone_drain_lock);
-		sx_xlock(&dmp->dm_lock);
+
+		if (cdev == NULL)
+			sx_xlock(&dmp->dm_lock);
+		else if (devfs_populate_vp(dvp) != 0) {
+			*dm_unlock = 0;
+			sx_xlock(&dmp->dm_lock);
+			if (DEVFS_DMP_DROP(dmp)) {
+				sx_xunlock(&dmp->dm_lock);
+				devfs_unmount_final(dmp);
+			} else
+				sx_xunlock(&dmp->dm_lock);
+			dev_rel(cdev);
+			return (ENOENT);
+		}
 		if (DEVFS_DMP_DROP(dmp)) {
 			*dm_unlock = 0;
 			sx_xunlock(&dmp->dm_lock);
@@ -852,19 +894,10 @@ devfs_lookupx(struct vop_lookup_args *ap, int *dm_unlock)
 				dev_rel(cdev);
 			return (ENOENT);
 		}
+
 		if (cdev == NULL)
 			break;
 
-		DEVFS_DMP_HOLD(dmp);
-		devfs_populate(dmp);
-		if (DEVFS_DMP_DROP(dmp)) {
-			*dm_unlock = 0;
-			sx_xunlock(&dmp->dm_lock);
-			devfs_unmount_final(dmp);
-			dev_rel(cdev);
-			return (ENOENT);
-		}
-
 		dev_lock();
 		dde = &cdev2priv(cdev)->cdp_dirents[dmp->dm_idx];
 		if (dde != NULL && *dde != NULL)
@@ -909,9 +942,11 @@ devfs_lookup(struct vop_lookup_args *ap)
 	struct devfs_mount *dmp;
 	int dm_unlock;
 
+	if (devfs_populate_vp(ap->a_dvp) != 0)
+		return (ENOTDIR);
+
 	dmp = VFSTODEVFS(ap->a_dvp->v_mount);
 	dm_unlock = 1;
-	sx_xlock(&dmp->dm_lock);
 	j = devfs_lookupx(ap, &dm_unlock);
 	if (dm_unlock == 1)
 		sx_xunlock(&dmp->dm_lock);
@@ -1139,12 +1174,7 @@ devfs_readdir(struct vop_readdir_args *ap)
 	}
 
 	dmp = VFSTODEVFS(ap->a_vp->v_mount);
-	sx_xlock(&dmp->dm_lock);
-	DEVFS_DMP_HOLD(dmp);
-	devfs_populate(dmp);
-	if (DEVFS_DMP_DROP(dmp)) {
-		sx_xunlock(&dmp->dm_lock);
-		devfs_unmount_final(dmp);
+	if (devfs_populate_vp(ap->a_vp) != 0) {
 		if (tmp_ncookies != NULL)
 			ap->a_ncookies = tmp_ncookies;
 		return (EIO);

From cd1c27af3664e4dafd2206d232544ed0fb735227 Mon Sep 17 00:00:00 2001
From: Ed Schouten 
Date: Sun, 22 Aug 2010 16:42:46 +0000
Subject: [PATCH 0159/1624] Add missing mlink for insmntque1().

MFC after:	1 week
---
 share/man/man9/Makefile | 1 +
 1 file changed, 1 insertion(+)

diff --git a/share/man/man9/Makefile b/share/man/man9/Makefile
index f8dec172838..b438b90b9b1 100644
--- a/share/man/man9/Makefile
+++ b/share/man/man9/Makefile
@@ -700,6 +700,7 @@ MLINKS+=ieee80211_vap.9 ieee80211_vap_attach.9 \
 MLINKS+=ifnet.9 ifaddr.9 \
 	ifnet.9 if_data.9 \
 	ifnet.9 ifqueue.9
+MLINKS+=insmntque.9 insmntque1.9
 MLINKS+=ithread.9 ithread_add_handler.9 \
 	ithread.9 ithread_create.9 \
 	ithread.9 ithread_destroy.9 \

From 8fdbdb5d500d43db6177e9ada7c25939d8ac3f28 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 22 Aug 2010 21:18:21 +0000
Subject: [PATCH 0160/1624] sh: Remove remnants of '!!' to negate pattern.

This Almquist extension was disabled long ago.

In pathname generation, components starting with '!!' were treated as
containing wildcards, causing unnecessary readdir (which could fail, causing
pathname generation to fail while it should not).
---
 bin/sh/expand.c                               | 19 ++-----------
 tools/regression/bin/sh/expansion/pathname4.0 | 28 +++++++++++++++++++
 2 files changed, 30 insertions(+), 17 deletions(-)
 create mode 100644 tools/regression/bin/sh/expansion/pathname4.0

diff --git a/bin/sh/expand.c b/bin/sh/expand.c
index fded6da22f2..73540109959 100644
--- a/bin/sh/expand.c
+++ b/bin/sh/expand.c
@@ -109,7 +109,6 @@ STATIC void expmeta(char *, char *);
 STATIC void addfname(char *);
 STATIC struct strlist *expsort(struct strlist *);
 STATIC struct strlist *msort(struct strlist *, int);
-STATIC int pmatch(const char *, const char *, int);
 STATIC char *cvtnum(int, char *);
 STATIC int collate_range_cmp(int, int);
 
@@ -1101,7 +1100,7 @@ expandmeta(struct strlist *str, int flag __unused)
 		for (;;) {			/* fast check for meta chars */
 			if ((c = *p++) == '\0')
 				goto nometa;
-			if (c == '*' || c == '?' || c == '[' || c == '!')
+			if (c == '*' || c == '?' || c == '[')
 				break;
 		}
 		savelastp = exparg.lastp;
@@ -1168,8 +1167,6 @@ expmeta(char *enddir, char *name)
 					break;
 				}
 			}
-		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
-			metaflag = 1;
 		} else if (*p == '\0')
 			break;
 		else if (*p == CTLQUOTEMARK)
@@ -1352,18 +1349,6 @@ msort(struct strlist *list, int len)
 
 int
 patmatch(const char *pattern, const char *string, int squoted)
-{
-#ifdef notdef
-	if (pattern[0] == '!' && pattern[1] == '!')
-		return 1 - pmatch(pattern + 2, string);
-	else
-#endif
-		return pmatch(pattern, string, squoted);
-}
-
-
-STATIC int
-pmatch(const char *pattern, const char *string, int squoted)
 {
 	const char *p, *q;
 	char c;
@@ -1406,7 +1391,7 @@ pmatch(const char *pattern, const char *string, int squoted)
 				}
 			}
 			do {
-				if (pmatch(p, q, squoted))
+				if (patmatch(p, q, squoted))
 					return 1;
 				if (squoted && *q == CTLESC)
 					q++;
diff --git a/tools/regression/bin/sh/expansion/pathname4.0 b/tools/regression/bin/sh/expansion/pathname4.0
new file mode 100644
index 00000000000..18269c4318e
--- /dev/null
+++ b/tools/regression/bin/sh/expansion/pathname4.0
@@ -0,0 +1,28 @@
+# $FreeBSD$
+
+failures=0
+
+check() {
+	testcase=$1
+	expect=$2
+	eval "set -- $testcase"
+	actual="$*"
+	if [ "$actual" != "$expect" ]; then
+		failures=$((failures+1))
+		printf '%s\n' "For $testcase, expected $expect actual $actual"
+	fi
+}
+
+set -e
+T=$(mktemp -d ${TMPDIR:-/tmp}/sh-test.XXXXXX)
+trap 'rm -rf $T' 0
+cd -P $T
+
+mkdir !!a
+touch !!a/fff
+
+chmod u-r .
+check '!!a/ff*' '!!a/fff'
+chmod u+r .
+
+exit $((failures != 0))

From c6a3d2bb77363f8032b981da36c9d9f9d2918ad6 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sun, 22 Aug 2010 21:26:35 +0000
Subject: [PATCH 0161/1624] It seems some newer RTL8139 controllers provides
 only memory space register mapping. I'm not sure whether it comes from the
 fact that controllers live behind certain PCI brdge(PLX PCI 6152 33BC) and
 the bridge has some issues in handling I/O space register mapping.
 Unfortunately it's not possible to narrow down to an exact controller that
 shows this issue because RealTek used the same PCI device/revision id again.
 In theory, it's possible to check parent PCI bridge device and change rl(4)
 to use memory space register mapping if the parent PCI bridge is PLX PCI
 6152. But I didn't try to do that and we wouldn't get much benefit with added
 complexity.

Blindly switching to use memory space register mapping for rl(4)
may make most old controllers not to work. At least, I don't want
to take potential risk from such change. So use I/O space register
mapping by default but give users chance to override it via a
tunable. The tunable to use memory space register mapping would be
given by adding the following line to /boot/loader.conf file.

dev.rl.%d.prefer_iomap="0"

This change makes P811B quad-port work with this tunable.

Tested by:	Nikola Kalpazanov ( n.kalpazanov <> gmail dot com )
MFC after:	1 week
---
 sys/pci/if_rl.c | 50 ++++++++++++++++++++++++++-----------------------
 1 file changed, 27 insertions(+), 23 deletions(-)

diff --git a/sys/pci/if_rl.c b/sys/pci/if_rl.c
index ad7bbdc6703..110e7058d17 100644
--- a/sys/pci/if_rl.c
+++ b/sys/pci/if_rl.c
@@ -125,16 +125,6 @@ MODULE_DEPEND(rl, miibus, 1, 1, 1);
 /* "device miibus" required.  See GENERIC if you get errors here. */
 #include "miibus_if.h"
 
-/*
- * Default to using PIO access for this driver. On SMP systems,
- * there appear to be problems with memory mapped mode: it looks like
- * doing too many memory mapped access back to back in rapid succession
- * can hang the bus. I'm inclined to blame this on crummy design/construction
- * on the part of RealTek. Memory mapped mode does appear to work on
- * uniprocessor systems though.
- */
-#define RL_USEIOSPACE
-
 #include 
 
 /*
@@ -225,14 +215,6 @@ static void rl_watchdog(struct rl_softc *);
 static void rl_setwol(struct rl_softc *);
 static void rl_clrwol(struct rl_softc *);
 
-#ifdef RL_USEIOSPACE
-#define RL_RES			SYS_RES_IOPORT
-#define RL_RID			RL_PCI_LOIO
-#else
-#define RL_RES			SYS_RES_MEMORY
-#define RL_RID			RL_PCI_LOMEM
-#endif
-
 static device_method_t rl_methods[] = {
 	/* Device interface */
 	DEVMETHOD(device_probe,		rl_probe),
@@ -806,7 +788,7 @@ rl_attach(device_t dev)
 	struct sysctl_ctx_list	*ctx;
 	struct sysctl_oid_list	*children;
 	int			error = 0, hwrev, i, pmc, rid;
-	int			unit;
+	int			prefer_iomap, unit;
 	uint16_t		rl_did = 0;
 	char			tn[32];
 
@@ -828,10 +810,31 @@ rl_attach(device_t dev)
 
 	pci_enable_busmaster(dev);
 
-	/* Map control/status registers. */
-	rid = RL_RID;
-	sc->rl_res = bus_alloc_resource_any(dev, RL_RES, &rid, RF_ACTIVE);
 
+	/*
+	 * Map control/status registers.
+	 * Default to using PIO access for this driver. On SMP systems,
+	 * there appear to be problems with memory mapped mode: it looks
+	 * like doing too many memory mapped access back to back in rapid
+	 * succession can hang the bus. I'm inclined to blame this on
+	 * crummy design/construction on the part of RealTek. Memory
+	 * mapped mode does appear to work on uniprocessor systems though.
+	 */
+	prefer_iomap = 1;
+	snprintf(tn, sizeof(tn), "dev.rl.%d.prefer_iomap", unit);
+	TUNABLE_INT_FETCH(tn, &prefer_iomap);
+	if (prefer_iomap) {
+		sc->rl_res_id = PCIR_BAR(0);
+		sc->rl_res_type = SYS_RES_IOPORT;
+		sc->rl_res = bus_alloc_resource_any(dev, sc->rl_res_type,
+		    &sc->rl_res_id, RF_ACTIVE);
+	}
+	if (prefer_iomap == 0 || sc->rl_res == NULL) {
+		sc->rl_res_id = PCIR_BAR(1);
+		sc->rl_res_type = SYS_RES_MEMORY;
+		sc->rl_res = bus_alloc_resource_any(dev, sc->rl_res_type,
+		    &sc->rl_res_id, RF_ACTIVE);
+	}
 	if (sc->rl_res == NULL) {
 		device_printf(dev, "couldn't map ports/memory\n");
 		error = ENXIO;
@@ -1029,7 +1032,8 @@ rl_detach(device_t dev)
 	if (sc->rl_irq[0])
 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->rl_irq[0]);
 	if (sc->rl_res)
-		bus_release_resource(dev, RL_RES, RL_RID, sc->rl_res);
+		bus_release_resource(dev, sc->rl_res_type, sc->rl_res_id,
+		    sc->rl_res);
 
 	if (ifp)
 		if_free(ifp);

From b817ddc741abc8a6c3dfb2209aea3be8439bde2f Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sun, 22 Aug 2010 21:32:48 +0000
Subject: [PATCH 0162/1624] Document tunable dev.rl.%unit.prefer_iomap

---
 share/man/man4/rl.4 | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/rl.4 b/share/man/man4/rl.4
index 1897b08b584..56c57be9376 100644
--- a/share/man/man4/rl.4
+++ b/share/man/man4/rl.4
@@ -30,7 +30,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd November 1, 2008
+.Dd August 22, 2010
 .Dt RL 4
 .Os
 .Sh NAME
@@ -203,6 +203,13 @@ SOHO (PRAGMATIC) UE-1211C
 .El
 .Sh LOADER TUNABLES
 .Bl -tag -width indent
+.It Va dev.rl.%unit.prefer_iomap
+This tunable controls which register mapping should be used on the
+specified device.
+Non-zero value enables I/O space register mapping.
+For controllers that have no I/O space register mapping this tunable
+should be set to 0 to use I/O space register mapping.
+The default value is 1 to use I/O space register mapping.
 .It Va dev.rl.%unit.twister_enable
 Non-zero value enables the long cable tuning on the specified device.
 Disabled by default.

From 72cfc9a6087f244bf3db00da95a940f79fcb40c1 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Mon, 23 Aug 2010 00:10:43 +0000
Subject: [PATCH 0163/1624] Better wording and fix wrong explanation.

Submitted by:	Ben Kaduk ( minimarmot <> gmail dot com )
---
 share/man/man4/rl.4 | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/share/man/man4/rl.4 b/share/man/man4/rl.4
index 56c57be9376..d88a25f4538 100644
--- a/share/man/man4/rl.4
+++ b/share/man/man4/rl.4
@@ -206,9 +206,9 @@ SOHO (PRAGMATIC) UE-1211C
 .It Va dev.rl.%unit.prefer_iomap
 This tunable controls which register mapping should be used on the
 specified device.
-Non-zero value enables I/O space register mapping.
+A non-zero value enables I/O space register mapping.
 For controllers that have no I/O space register mapping this tunable
-should be set to 0 to use I/O space register mapping.
+should be set to 0 to use memory space register mapping.
 The default value is 1 to use I/O space register mapping.
 .It Va dev.rl.%unit.twister_enable
 Non-zero value enables the long cable tuning on the specified device.

From a3835274a4129bcadb64a298cd79118a22bd477e Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Mon, 23 Aug 2010 00:24:12 +0000
Subject: [PATCH 0164/1624] Clean up SIOCSIFCAP handler and allow RX checksum
 offloading could be controlled by user.

---
 sys/dev/xl/if_xl.c | 69 +++++++++++++++++++++++++---------------------
 1 file changed, 38 insertions(+), 31 deletions(-)

diff --git a/sys/dev/xl/if_xl.c b/sys/dev/xl/if_xl.c
index 05150af2b7f..2145ec86509 100644
--- a/sys/dev/xl/if_xl.c
+++ b/sys/dev/xl/if_xl.c
@@ -3083,7 +3083,7 @@ xl_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 {
 	struct xl_softc		*sc = ifp->if_softc;
 	struct ifreq		*ifr = (struct ifreq *) data;
-	int			error = 0;
+	int			error = 0, mask;
 	struct mii_data		*mii = NULL;
 	u_int8_t		rxfilt;
 
@@ -3143,40 +3143,47 @@ xl_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 			    &mii->mii_media, command);
 		break;
 	case SIOCSIFCAP:
+		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
 #ifdef DEVICE_POLLING
-		if (ifr->ifr_reqcap & IFCAP_POLLING &&
-		    !(ifp->if_capenable & IFCAP_POLLING)) {
-			error = ether_poll_register(xl_poll, ifp);
-			if (error)
-				return(error);
-			XL_LOCK(sc);
-			/* Disable interrupts */
-			CSR_WRITE_2(sc, XL_COMMAND, XL_CMD_INTR_ENB|0);
-			ifp->if_capenable |= IFCAP_POLLING;
-			XL_UNLOCK(sc);
-			return (error);
-		}
-		if (!(ifr->ifr_reqcap & IFCAP_POLLING) &&
-		    ifp->if_capenable & IFCAP_POLLING) {
-			error = ether_poll_deregister(ifp);
-			/* Enable interrupts. */
-			XL_LOCK(sc);
-			CSR_WRITE_2(sc, XL_COMMAND, XL_CMD_INTR_ACK|0xFF);
-			CSR_WRITE_2(sc, XL_COMMAND, XL_CMD_INTR_ENB|XL_INTRS);
-			if (sc->xl_flags & XL_FLAG_FUNCREG)
-				bus_space_write_4(sc->xl_ftag, sc->xl_fhandle,
-				    4, 0x8000);
-			ifp->if_capenable &= ~IFCAP_POLLING;
-			XL_UNLOCK(sc);
-			return (error);
+		if ((mask & IFCAP_POLLING) != 0 &&
+		    (ifp->if_capabilities & IFCAP_POLLING) != 0) {
+			ifp->if_capenable ^= IFCAP_POLLING;
+			if ((ifp->if_capenable & IFCAP_POLLING) != 0) {
+				error = ether_poll_register(xl_poll, ifp);
+				if (error)
+					break;
+				XL_LOCK(sc);
+				/* Disable interrupts */
+				CSR_WRITE_2(sc, XL_COMMAND, XL_CMD_INTR_ENB|0);
+				ifp->if_capenable |= IFCAP_POLLING;
+				XL_UNLOCK(sc);
+			} else {
+				error = ether_poll_deregister(ifp);
+				/* Enable interrupts. */
+				XL_LOCK(sc);
+				CSR_WRITE_2(sc, XL_COMMAND,
+				    XL_CMD_INTR_ACK | 0xFF);
+				CSR_WRITE_2(sc, XL_COMMAND,
+				    XL_CMD_INTR_ENB | XL_INTRS);
+				if (sc->xl_flags & XL_FLAG_FUNCREG)
+					bus_space_write_4(sc->xl_ftag,
+					    sc->xl_fhandle, 4, 0x8000);
+				XL_UNLOCK(sc);
+			}
 		}
 #endif /* DEVICE_POLLING */
 		XL_LOCK(sc);
-		ifp->if_capenable = ifr->ifr_reqcap;
-		if (ifp->if_capenable & IFCAP_TXCSUM)
-			ifp->if_hwassist = XL905B_CSUM_FEATURES;
-		else
-			ifp->if_hwassist = 0;
+		if ((mask & IFCAP_TXCSUM) != 0 &&
+		    (ifp->if_capabilities & IFCAP_TXCSUM) != 0) {
+			ifp->if_capenable ^= IFCAP_TXCSUM;
+			if ((ifp->if_capenable & IFCAP_TXCSUM) != 0)
+				ifp->if_hwassist |= XL905B_CSUM_FEATURES;
+			else
+				ifp->if_hwassist &= ~XL905B_CSUM_FEATURES;
+		}
+		if ((mask & IFCAP_RXCSUM) != 0 &&
+		    (ifp->if_capabilities & IFCAP_RXCSUM) != 0)
+			ifp->if_capenable ^= IFCAP_RXCSUM;
 		XL_UNLOCK(sc);
 		break;
 	default:

From 27b031a9ad029b57bf363795e17fc9cc026fa686 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Mon, 23 Aug 2010 00:31:55 +0000
Subject: [PATCH 0165/1624] Remove unnecessary controller reinitialization by
 checking IFF_DRV_RUNNING flag.

---
 sys/dev/xl/if_xl.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/sys/dev/xl/if_xl.c b/sys/dev/xl/if_xl.c
index 2145ec86509..6623551dcaa 100644
--- a/sys/dev/xl/if_xl.c
+++ b/sys/dev/xl/if_xl.c
@@ -2247,6 +2247,7 @@ xl_intr(void *arg)
 
 		if (status & XL_STAT_ADFAIL) {
 			xl_reset(sc);
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			xl_init_locked(sc);
 		}
 
@@ -2318,6 +2319,7 @@ xl_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
 
 			if (status & XL_STAT_ADFAIL) {
 				xl_reset(sc);
+				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 				xl_init_locked(sc);
 			}
 
@@ -2745,6 +2747,8 @@ xl_init_locked(struct xl_softc *sc)
 
 	XL_LOCK_ASSERT(sc);
 
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+		return;
 	/*
 	 * Cancel pending I/O and free all RX/TX buffers.
 	 */
@@ -2993,6 +2997,7 @@ xl_ifmedia_upd(struct ifnet *ifp)
 	if (sc->xl_media & XL_MEDIAOPT_MII ||
 	    sc->xl_media & XL_MEDIAOPT_BTX ||
 	    sc->xl_media & XL_MEDIAOPT_BT4) {
+		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		xl_init_locked(sc);
 	} else {
 		xl_setmode(sc, ifm->ifm_media);
@@ -3108,10 +3113,8 @@ xl_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 				CSR_WRITE_2(sc, XL_COMMAND,
 				    XL_CMD_RX_SET_FILT|rxfilt);
 				XL_SEL_WIN(7);
-			} else {
-				if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
-					xl_init_locked(sc);
-			}
+			} else
+				xl_init_locked(sc);
 		} else {
 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
 				xl_stop(sc);
@@ -3234,6 +3237,7 @@ xl_watchdog(struct xl_softc *sc)
 		    "no carrier - transceiver cable problem?\n");
 
 	xl_reset(sc);
+	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	xl_init_locked(sc);
 
 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
@@ -3364,8 +3368,10 @@ xl_resume(device_t dev)
 	XL_LOCK(sc);
 
 	xl_reset(sc);
-	if (ifp->if_flags & IFF_UP)
+	if (ifp->if_flags & IFF_UP) {
+		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		xl_init_locked(sc);
+	}
 
 	XL_UNLOCK(sc);
 

From 767bb8496ae4a27cf1e183f47f5fa8a6522f4683 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:07:07 +0000
Subject: [PATCH 0166/1624] Minor tweak from tbemd

---
 Makefile.inc1 | 1 -
 1 file changed, 1 deletion(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index 6e58396fc53..28144a6d064 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -29,7 +29,6 @@
 #		obj depend all install clean cleandepend cleanobj
 
 .include 
-
 .include 
 
 # We must do share/info early so that installation of info `dir'

From ee0b65d9d025d835dc6a96424884e58be0a7eabc Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:33:27 +0000
Subject: [PATCH 0167/1624] MF tbemd: differentiate between arm and armeb

---
 sys/boot/arm/uboot/Makefile       |   2 +-
 sys/boot/arm/uboot/ldscript.armeb | 134 ++++++++++++++++++++++++++++++
 2 files changed, 135 insertions(+), 1 deletion(-)
 create mode 100644 sys/boot/arm/uboot/ldscript.armeb

diff --git a/sys/boot/arm/uboot/Makefile b/sys/boot/arm/uboot/Makefile
index 573f9489f35..e8ac403247a 100644
--- a/sys/boot/arm/uboot/Makefile
+++ b/sys/boot/arm/uboot/Makefile
@@ -77,7 +77,7 @@ CLEANFILES+=	vers.c loader.help
 
 CFLAGS+=	-ffreestanding
 
-LDFLAGS=	-nostdlib -static -T ${.CURDIR}/ldscript.arm
+LDFLAGS=	-nostdlib -static -T ${.CURDIR}/ldscript.${MACHINE_ARCH}
 
 # Pull in common loader code
 .PATH:		${.CURDIR}/../../uboot/common
diff --git a/sys/boot/arm/uboot/ldscript.armeb b/sys/boot/arm/uboot/ldscript.armeb
new file mode 100644
index 00000000000..17a02caa50c
--- /dev/null
+++ b/sys/boot/arm/uboot/ldscript.armeb
@@ -0,0 +1,134 @@
+/* $FreeBSD$ */
+
+OUTPUT_FORMAT("elf32-bigarm", "elf32-bigarm", "elf32-littlearm")
+OUTPUT_ARCH(arm)
+ENTRY(_start)
+SECTIONS
+{
+  /* Read-only sections, merged into text segment: */
+  . = 0x1000000 + SIZEOF_HEADERS;
+  .interp     : { *(.interp) 	}
+  .hash          : { *(.hash)		}
+  .dynsym        : { *(.dynsym)		}
+  .dynstr        : { *(.dynstr)		}
+  .gnu.version   : { *(.gnu.version)	}
+  .gnu.version_d   : { *(.gnu.version_d)	}
+  .gnu.version_r   : { *(.gnu.version_r)	}
+  .rela.text     :
+    { *(.rela.text) *(.rela.gnu.linkonce.t*) }
+  .rela.data     :
+    { *(.rela.data) *(.rela.gnu.linkonce.d*) }
+  .rela.rodata   :
+    { *(.rela.rodata) *(.rela.gnu.linkonce.r*) }
+  .rela.got      : { *(.rela.got)		}
+  .rela.got1     : { *(.rela.got1)		}
+  .rela.got2     : { *(.rela.got2)		}
+  .rela.ctors    : { *(.rela.ctors)	}
+  .rela.dtors    : { *(.rela.dtors)	}
+  .rela.init     : { *(.rela.init)	}
+  .rela.fini     : { *(.rela.fini)	}
+  .rela.bss      : { *(.rela.bss)		}
+  .rela.plt      : { *(.rela.plt)		}
+  .rela.sdata    : { *(.rela.sdata)		}
+  .rela.sbss     : { *(.rela.sbss)		}
+  .rela.sdata2   : { *(.rela.sdata2)		}
+  .rela.sbss2    : { *(.rela.sbss2)		}
+  .text      :
+  {
+    *(.text)
+    /* .gnu.warning sections are handled specially by elf32.em.  */
+    *(.gnu.warning)
+    *(.gnu.linkonce.t*)
+  } =0
+  _etext = .;
+  PROVIDE (etext = .);
+  .init      : { *(.init)    } =0
+  .fini      : { *(.fini)    } =0
+  .rodata    : { *(.rodata) *(.gnu.linkonce.r*) }
+  .rodata1   : { *(.rodata1) }
+  .sdata2    : { *(.sdata2)  }
+  .sbss2     : { *(.sbss2)   }
+  /* Adjust the address for the data segment to the next page up. */
+  . = ((. + 0x1000) & ~(0x1000 - 1));
+  .data    :
+  {
+    *(.data)
+    *(.gnu.linkonce.d*)
+    CONSTRUCTORS
+  }
+  .data1   : { *(.data1) }
+  .got1           : { *(.got1) }
+  .dynamic        : { *(.dynamic) }
+  /* Put .ctors and .dtors next to the .got2 section, so that the pointers
+     get relocated with -mrelocatable. Also put in the .fixup pointers.
+     The current compiler no longer needs this, but keep it around for 2.7.2  */
+                PROVIDE (_GOT2_START_ = .);
+  .got2           :  { *(.got2) }
+                PROVIDE (__CTOR_LIST__ = .);
+  .ctors          : { *(.ctors) }
+                PROVIDE (__CTOR_END__ = .);
+                PROVIDE (__DTOR_LIST__ = .);
+  .dtors          : { *(.dtors) }
+                PROVIDE (__DTOR_END__ = .);
+                PROVIDE (_FIXUP_START_ = .);
+  .fixup          : { *(.fixup) }
+                PROVIDE (_FIXUP_END_ = .);
+                PROVIDE (_GOT2_END_ = .);
+                PROVIDE (_GOT_START_ = .);
+  .got            : { *(.got) }
+  .got.plt        : { *(.got.plt) }
+                PROVIDE (_GOT_END_ = .);
+  /* We want the small data sections together, so single-instruction offsets
+     can access them all, and initialized data all before uninitialized, so
+     we can shorten the on-disk segment size.  */
+  .sdata     : { *(.sdata) }
+  _edata  =  .;
+  PROVIDE (edata = .);
+  .sbss      :
+  {
+    PROVIDE (__sbss_start = .);
+    *(.sbss)
+    *(.scommon)
+    *(.dynsbss)
+    PROVIDE (__sbss_end = .);
+  }
+  .plt   : { *(.plt) }
+  .bss       :
+  {
+   PROVIDE (__bss_start = .);
+   *(.dynbss)
+   *(.bss)
+   *(COMMON)
+  }
+  _end = . ;
+  PROVIDE (end = .);
+  /* Stabs debugging sections.  */
+  .stab 0 : { *(.stab) }
+  .stabstr 0 : { *(.stabstr) }
+  /* DWARF debug sections.
+     Symbols in the DWARF debugging sections are relative to the beginning
+     of the section so we begin them at 0.  */
+  /* DWARF 1 */
+  .debug          0 : { *(.debug) }
+  .line           0 : { *(.line) }
+  /* GNU DWARF 1 extensions */
+  .debug_srcinfo  0 : { *(.debug_srcinfo) }
+  .debug_sfnames  0 : { *(.debug_sfnames) }
+  /* DWARF 1.1 and DWARF 2 */
+  .debug_aranges  0 : { *(.debug_aranges) }
+  .debug_pubnames 0 : { *(.debug_pubnames) }
+  /* DWARF 2 */
+  .debug_info     0 : { *(.debug_info) }
+  .debug_abbrev   0 : { *(.debug_abbrev) }
+  .debug_line     0 : { *(.debug_line) }
+  .debug_frame    0 : { *(.debug_frame) }
+  .debug_str      0 : { *(.debug_str) }
+  .debug_loc      0 : { *(.debug_loc) }
+  .debug_macinfo  0 : { *(.debug_macinfo) }
+  /* SGI/MIPS DWARF 2 extensions */
+  .debug_weaknames 0 : { *(.debug_weaknames) }
+  .debug_funcnames 0 : { *(.debug_funcnames) }
+  .debug_typenames 0 : { *(.debug_typenames) }
+  .debug_varnames  0 : { *(.debug_varnames) }
+  /* These must appear regardless of  .  */
+}

From e8120f3d4ed9ca53904a11403a5fe92d38e824a6 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:37:55 +0000
Subject: [PATCH 0168/1624] It turns out that the OUTPUT_FORMAT should do the
 right thing for both endians...

---
 sys/boot/arm/uboot/Makefile       |   2 +-
 sys/boot/arm/uboot/ldscript.armeb | 134 ------------------------------
 2 files changed, 1 insertion(+), 135 deletions(-)
 delete mode 100644 sys/boot/arm/uboot/ldscript.armeb

diff --git a/sys/boot/arm/uboot/Makefile b/sys/boot/arm/uboot/Makefile
index e8ac403247a..906fc871a88 100644
--- a/sys/boot/arm/uboot/Makefile
+++ b/sys/boot/arm/uboot/Makefile
@@ -77,7 +77,7 @@ CLEANFILES+=	vers.c loader.help
 
 CFLAGS+=	-ffreestanding
 
-LDFLAGS=	-nostdlib -static -T ${.CURDIR}/ldscript.${MACHINE_ARCH}
+LDFLAGS=	-nostdlib -static -T ${.CURDIR}/ldscript.${MACHINE_CPUARCH}
 
 # Pull in common loader code
 .PATH:		${.CURDIR}/../../uboot/common
diff --git a/sys/boot/arm/uboot/ldscript.armeb b/sys/boot/arm/uboot/ldscript.armeb
deleted file mode 100644
index 17a02caa50c..00000000000
--- a/sys/boot/arm/uboot/ldscript.armeb
+++ /dev/null
@@ -1,134 +0,0 @@
-/* $FreeBSD$ */
-
-OUTPUT_FORMAT("elf32-bigarm", "elf32-bigarm", "elf32-littlearm")
-OUTPUT_ARCH(arm)
-ENTRY(_start)
-SECTIONS
-{
-  /* Read-only sections, merged into text segment: */
-  . = 0x1000000 + SIZEOF_HEADERS;
-  .interp     : { *(.interp) 	}
-  .hash          : { *(.hash)		}
-  .dynsym        : { *(.dynsym)		}
-  .dynstr        : { *(.dynstr)		}
-  .gnu.version   : { *(.gnu.version)	}
-  .gnu.version_d   : { *(.gnu.version_d)	}
-  .gnu.version_r   : { *(.gnu.version_r)	}
-  .rela.text     :
-    { *(.rela.text) *(.rela.gnu.linkonce.t*) }
-  .rela.data     :
-    { *(.rela.data) *(.rela.gnu.linkonce.d*) }
-  .rela.rodata   :
-    { *(.rela.rodata) *(.rela.gnu.linkonce.r*) }
-  .rela.got      : { *(.rela.got)		}
-  .rela.got1     : { *(.rela.got1)		}
-  .rela.got2     : { *(.rela.got2)		}
-  .rela.ctors    : { *(.rela.ctors)	}
-  .rela.dtors    : { *(.rela.dtors)	}
-  .rela.init     : { *(.rela.init)	}
-  .rela.fini     : { *(.rela.fini)	}
-  .rela.bss      : { *(.rela.bss)		}
-  .rela.plt      : { *(.rela.plt)		}
-  .rela.sdata    : { *(.rela.sdata)		}
-  .rela.sbss     : { *(.rela.sbss)		}
-  .rela.sdata2   : { *(.rela.sdata2)		}
-  .rela.sbss2    : { *(.rela.sbss2)		}
-  .text      :
-  {
-    *(.text)
-    /* .gnu.warning sections are handled specially by elf32.em.  */
-    *(.gnu.warning)
-    *(.gnu.linkonce.t*)
-  } =0
-  _etext = .;
-  PROVIDE (etext = .);
-  .init      : { *(.init)    } =0
-  .fini      : { *(.fini)    } =0
-  .rodata    : { *(.rodata) *(.gnu.linkonce.r*) }
-  .rodata1   : { *(.rodata1) }
-  .sdata2    : { *(.sdata2)  }
-  .sbss2     : { *(.sbss2)   }
-  /* Adjust the address for the data segment to the next page up. */
-  . = ((. + 0x1000) & ~(0x1000 - 1));
-  .data    :
-  {
-    *(.data)
-    *(.gnu.linkonce.d*)
-    CONSTRUCTORS
-  }
-  .data1   : { *(.data1) }
-  .got1           : { *(.got1) }
-  .dynamic        : { *(.dynamic) }
-  /* Put .ctors and .dtors next to the .got2 section, so that the pointers
-     get relocated with -mrelocatable. Also put in the .fixup pointers.
-     The current compiler no longer needs this, but keep it around for 2.7.2  */
-                PROVIDE (_GOT2_START_ = .);
-  .got2           :  { *(.got2) }
-                PROVIDE (__CTOR_LIST__ = .);
-  .ctors          : { *(.ctors) }
-                PROVIDE (__CTOR_END__ = .);
-                PROVIDE (__DTOR_LIST__ = .);
-  .dtors          : { *(.dtors) }
-                PROVIDE (__DTOR_END__ = .);
-                PROVIDE (_FIXUP_START_ = .);
-  .fixup          : { *(.fixup) }
-                PROVIDE (_FIXUP_END_ = .);
-                PROVIDE (_GOT2_END_ = .);
-                PROVIDE (_GOT_START_ = .);
-  .got            : { *(.got) }
-  .got.plt        : { *(.got.plt) }
-                PROVIDE (_GOT_END_ = .);
-  /* We want the small data sections together, so single-instruction offsets
-     can access them all, and initialized data all before uninitialized, so
-     we can shorten the on-disk segment size.  */
-  .sdata     : { *(.sdata) }
-  _edata  =  .;
-  PROVIDE (edata = .);
-  .sbss      :
-  {
-    PROVIDE (__sbss_start = .);
-    *(.sbss)
-    *(.scommon)
-    *(.dynsbss)
-    PROVIDE (__sbss_end = .);
-  }
-  .plt   : { *(.plt) }
-  .bss       :
-  {
-   PROVIDE (__bss_start = .);
-   *(.dynbss)
-   *(.bss)
-   *(COMMON)
-  }
-  _end = . ;
-  PROVIDE (end = .);
-  /* Stabs debugging sections.  */
-  .stab 0 : { *(.stab) }
-  .stabstr 0 : { *(.stabstr) }
-  /* DWARF debug sections.
-     Symbols in the DWARF debugging sections are relative to the beginning
-     of the section so we begin them at 0.  */
-  /* DWARF 1 */
-  .debug          0 : { *(.debug) }
-  .line           0 : { *(.line) }
-  /* GNU DWARF 1 extensions */
-  .debug_srcinfo  0 : { *(.debug_srcinfo) }
-  .debug_sfnames  0 : { *(.debug_sfnames) }
-  /* DWARF 1.1 and DWARF 2 */
-  .debug_aranges  0 : { *(.debug_aranges) }
-  .debug_pubnames 0 : { *(.debug_pubnames) }
-  /* DWARF 2 */
-  .debug_info     0 : { *(.debug_info) }
-  .debug_abbrev   0 : { *(.debug_abbrev) }
-  .debug_line     0 : { *(.debug_line) }
-  .debug_frame    0 : { *(.debug_frame) }
-  .debug_str      0 : { *(.debug_str) }
-  .debug_loc      0 : { *(.debug_loc) }
-  .debug_macinfo  0 : { *(.debug_macinfo) }
-  /* SGI/MIPS DWARF 2 extensions */
-  .debug_weaknames 0 : { *(.debug_weaknames) }
-  .debug_funcnames 0 : { *(.debug_funcnames) }
-  .debug_typenames 0 : { *(.debug_typenames) }
-  .debug_varnames  0 : { *(.debug_varnames) }
-  /* These must appear regardless of  .  */
-}

From 5aae6977bc729a2a3981f363c81995fcbd474bbf Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:42:09 +0000
Subject: [PATCH 0169/1624] MF tbemd: Minor tweaks, prefer MACHINE_CPUARCH
 generally to MACHINE_ARCH

---
 sys/boot/i386/Makefile.inc         | 2 +-
 sys/boot/i386/boot2/Makefile       | 2 +-
 sys/boot/i386/gptboot/Makefile     | 2 +-
 sys/boot/i386/gptzfsboot/Makefile  | 2 +-
 sys/boot/i386/libfirewire/Makefile | 4 ++--
 sys/boot/i386/libi386/Makefile     | 4 ++--
 sys/boot/i386/loader/Makefile      | 2 +-
 sys/boot/i386/zfsboot/Makefile     | 2 +-
 8 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/sys/boot/i386/Makefile.inc b/sys/boot/i386/Makefile.inc
index 72c6395acf0..a25684012c9 100644
--- a/sys/boot/i386/Makefile.inc
+++ b/sys/boot/i386/Makefile.inc
@@ -9,7 +9,7 @@ CFLAGS+=	-ffreestanding -mpreferred-stack-boundary=2 \
 		-mno-mmx -mno-3dnow -mno-sse -mno-sse2 -mno-sse3
 LDFLAGS+=	-nostdlib
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-m32 -march=i386
 LDFLAGS+=	-m elf_i386_fbsd
 AFLAGS+=	--32
diff --git a/sys/boot/i386/boot2/Makefile b/sys/boot/i386/boot2/Makefile
index 84a63c1ad4b..bff4647668a 100644
--- a/sys/boot/i386/boot2/Makefile
+++ b/sys/boot/i386/boot2/Makefile
@@ -99,7 +99,7 @@ boot2.h: boot1.out
 	    ORG1=`printf "%d" ${ORG1}` \
 	    REL1=`printf "%d" ${REL1}` > ${.TARGET}
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend boot2.s: machine
 CLEANFILES+=	machine
 machine:
diff --git a/sys/boot/i386/gptboot/Makefile b/sys/boot/i386/gptboot/Makefile
index cc71b3575e8..f76fb4e70af 100644
--- a/sys/boot/i386/gptboot/Makefile
+++ b/sys/boot/i386/gptboot/Makefile
@@ -67,7 +67,7 @@ gptboot.out: ${BTXCRT} gptboot.o sio.o
 
 gptboot.o: ${.CURDIR}/../../common/ufsread.c
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend gptboot.o: machine
 CLEANFILES+=	machine
 machine:
diff --git a/sys/boot/i386/gptzfsboot/Makefile b/sys/boot/i386/gptzfsboot/Makefile
index 467d3123aec..cf7ff35b642 100644
--- a/sys/boot/i386/gptzfsboot/Makefile
+++ b/sys/boot/i386/gptzfsboot/Makefile
@@ -64,7 +64,7 @@ gptzfsboot.out: ${BTXCRT} zfsboot.o sio.o
 
 zfsboot.o: ${.CURDIR}/../../zfs/zfsimpl.c
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend zfsboot.o: machine
 CLEANFILES+=	machine
 machine:
diff --git a/sys/boot/i386/libfirewire/Makefile b/sys/boot/i386/libfirewire/Makefile
index 28f76307d8a..191b95479e2 100644
--- a/sys/boot/i386/libfirewire/Makefile
+++ b/sys/boot/i386/libfirewire/Makefile
@@ -16,7 +16,7 @@ CFLAGS+=	-I${.CURDIR}/../libi386
 
 CFLAGS+=	-Wformat -Wall
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CLEANFILES+=    machine
 machine:
 	ln -sf ${.CURDIR}/../../../i386/include machine
@@ -24,7 +24,7 @@ machine:
 
 .include 
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend ${OBJS}: machine
 .endif
 
diff --git a/sys/boot/i386/libi386/Makefile b/sys/boot/i386/libi386/Makefile
index f1a461a88c4..3b897847ea8 100644
--- a/sys/boot/i386/libi386/Makefile
+++ b/sys/boot/i386/libi386/Makefile
@@ -53,7 +53,7 @@ CFLAGS+=	-I${.CURDIR}/../../common -I${.CURDIR}/../btx/lib \
 # the location of libstand
 CFLAGS+=	-I${.CURDIR}/../../../../lib/libstand/
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CLEANFILES+=	machine
 machine:
 	ln -sf ${.CURDIR}/../../../i386/include machine
@@ -61,6 +61,6 @@ machine:
 
 .include 
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend ${OBJS}: machine
 .endif
diff --git a/sys/boot/i386/loader/Makefile b/sys/boot/i386/loader/Makefile
index 71307c04606..a6f0d97919a 100644
--- a/sys/boot/i386/loader/Makefile
+++ b/sys/boot/i386/loader/Makefile
@@ -119,7 +119,7 @@ LDADD=	${LIBFICL} ${LIBFIREWIRE} ${LIBZFS} ${LIBI386} ${LIBSTAND}
 
 .include 
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend ${OBJS}: machine
 CLEANFILES+=	machine
 machine:
diff --git a/sys/boot/i386/zfsboot/Makefile b/sys/boot/i386/zfsboot/Makefile
index 1653534a325..7e5cb567e0e 100644
--- a/sys/boot/i386/zfsboot/Makefile
+++ b/sys/boot/i386/zfsboot/Makefile
@@ -98,7 +98,7 @@ zfsboot.h: zfsldr.out
 	    ORG1=`printf "%d" ${ORG1}` \
 	    REL1=`printf "%d" ${REL1}` > ${.TARGET}
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend zfsboot.s: machine
 CLEANFILES+=	machine
 machine:

From 343bc19749e3f1863a23468d307dad671ca3c278 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:43:47 +0000
Subject: [PATCH 0170/1624] MF tbemd: Minor tweaks, prefer MACHINE_CPUARCH
 generally to MACHINE_ARCH (which simplifies some powerpc/powerpc64 ifs)

---
 sys/boot/common/Makefile.inc |  8 ++++----
 sys/boot/ficl/Makefile       | 14 +++++++-------
 2 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/sys/boot/common/Makefile.inc b/sys/boot/common/Makefile.inc
index 6b4c769ce84..ff3ec3912b7 100644
--- a/sys/boot/common/Makefile.inc
+++ b/sys/boot/common/Makefile.inc
@@ -4,17 +4,17 @@ SRCS+=	boot.c commands.c console.c devopen.c interp.c
 SRCS+=	interp_backslash.c interp_parse.c ls.c misc.c 
 SRCS+=	module.c panic.c
 
-.if ${MACHINE} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	load_elf32.c load_elf32_obj.c reloc_elf32.c
 SRCS+=	load_elf64.c load_elf64_obj.c reloc_elf64.c
 .elif ${MACHINE} == "pc98"
 SRCS+=	load_elf32.c load_elf32_obj.c reloc_elf32.c
-.elif ${MACHINE_ARCH} == "arm"
+.elif ${MACHINE_ARCH} == "powerpc" || ${MACHINE_CPUARCH} == "arm"
 SRCS+=	load_elf32.c reloc_elf32.c
-.elif ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.elif ${MACHINE_CPUARCH} == "powerpc"
 SRCS+=	load_elf32.c reloc_elf32.c
 SRCS+=	load_elf64.c reloc_elf64.c
-.elif ${MACHINE_ARCH} == "sparc64" || ${MACHINE_ARCH} == "ia64"
+.elif ${MACHINE_CPUARCH} == "sparc64" || ${MACHINE_CPUARCH} == "ia64"
 SRCS+=	load_elf64.c reloc_elf64.c
 .endif
 
diff --git a/sys/boot/ficl/Makefile b/sys/boot/ficl/Makefile
index cdc8f7eddee..61760d00328 100644
--- a/sys/boot/ficl/Makefile
+++ b/sys/boot/ficl/Makefile
@@ -1,20 +1,20 @@
 # $FreeBSD$
 #
-.PATH: ${.CURDIR}/${MACHINE_ARCH:S/amd64/i386/:S/powerpc64/powerpc/}
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH:S/amd64/i386/}
 BASE_SRCS=	dict.c ficl.c fileaccess.c float.c loader.c math64.c \
 		prefix.c search.c stack.c tools.c vm.c words.c
 
 SRCS=		${BASE_SRCS} sysdep.c softcore.c
 CLEANFILES=	softcore.c testmain testmain.o
 CFLAGS+=	-ffreestanding
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-mpreferred-stack-boundary=2
 CFLAGS+=	-mno-mmx -mno-3dnow -mno-sse -mno-sse2
 .endif
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 CFLAGS+=	-mno-sse3
 .endif
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64" || ${MACHINE_ARCH} == "arm" 
+.if ${MACHINE_CPUARCH} == "powerpc" || ${MACHINE_CPUARCH} == "arm"
 CFLAGS+=	-msoft-float
 .endif
 .if ${MACHINE} == "pc98"
@@ -41,7 +41,7 @@ SOFTWORDS=	softcore.fr jhlocal.fr marker.fr freebsd.fr ficllocal.fr \
 # Optional OO extension softwords
 #SOFTWORDS+=	oo.fr classes.fr
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-m32 -march=i386 -I.
 .endif
 
@@ -49,14 +49,14 @@ CFLAGS+=	-m32 -march=i386 -I.
 CFLAGS+=	-m32 -mcpu=powerpc -I.
 .endif
 
-CFLAGS+=	-I${.CURDIR} -I${.CURDIR}/${MACHINE_ARCH:S/amd64/i386/:S/powerpc64/powerpc/} \
+CFLAGS+=	-I${.CURDIR} -I${.CURDIR}/${MACHINE_CPUARCH:S/amd64/i386/} \
 		-I${.CURDIR}/../common
 
 softcore.c: ${SOFTWORDS} softcore.awk
 	(cd ${.CURDIR}/softwords; cat ${SOFTWORDS} \
 	    | awk -f softcore.awk -v datestamp="`LC_ALL=C date`") > ${.TARGET}
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 ${SRCS:M*.c:R:S/$/.o/g}: machine
 
 beforedepend ${OBJS}: machine

From 99a4fb6cbc891bcee2267da411334d4b3a7720f7 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:48:07 +0000
Subject: [PATCH 0171/1624] MF tbemd: move to using specific architecture
 makefiles

---
 sys/boot/Makefile            | 20 +-------------------
 sys/boot/Makefile.amd64      |  4 ++++
 sys/boot/Makefile.arm        |  3 +++
 sys/boot/Makefile.i386       |  4 ++++
 sys/boot/Makefile.ia64       |  3 +++
 sys/boot/Makefile.pc98       |  4 ++++
 sys/boot/Makefile.powerpc    |  4 ++++
 sys/boot/Makefile.sparc64    |  3 +++
 sys/boot/efi/libefi/Makefile |  2 +-
 9 files changed, 27 insertions(+), 20 deletions(-)
 create mode 100644 sys/boot/Makefile.amd64
 create mode 100644 sys/boot/Makefile.arm
 create mode 100644 sys/boot/Makefile.i386
 create mode 100644 sys/boot/Makefile.ia64
 create mode 100644 sys/boot/Makefile.pc98
 create mode 100644 sys/boot/Makefile.powerpc
 create mode 100644 sys/boot/Makefile.sparc64

diff --git a/sys/boot/Makefile b/sys/boot/Makefile
index b2eeb955470..6c879972f92 100644
--- a/sys/boot/Makefile
+++ b/sys/boot/Makefile
@@ -1,31 +1,13 @@
 # $FreeBSD$
 
 .include 
+.include 
 
 .if ${MK_FORTH} != "no"
 # Build the add-in FORTH interpreter.
 SUBDIR+=		ficl
 .endif
 
-# Build EFI library.
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE} == "i386" || ${MACHINE_ARCH} == "ia64"
-SUBDIR+=		efi
-.endif
-
-# Build Open Firmware library.
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64" || ${MACHINE_ARCH} == "sparc64"
-SUBDIR+=		ofw
-.endif
-
-# Build U-Boot library.
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64" || ${MACHINE_ARCH} == "arm"
-SUBDIR+=		uboot
-.endif
-
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE} == "i386"
-SUBDIR+=		zfs
-.endif
-
 .if ${MK_FDT} != "no"
 SUBDIR+=		fdt
 .endif
diff --git a/sys/boot/Makefile.amd64 b/sys/boot/Makefile.amd64
new file mode 100644
index 00000000000..256201d4f94
--- /dev/null
+++ b/sys/boot/Makefile.amd64
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR+=		efi
+SUBDIR+=		zfs
diff --git a/sys/boot/Makefile.arm b/sys/boot/Makefile.arm
new file mode 100644
index 00000000000..f96104db47c
--- /dev/null
+++ b/sys/boot/Makefile.arm
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR+=		uboot
diff --git a/sys/boot/Makefile.i386 b/sys/boot/Makefile.i386
new file mode 100644
index 00000000000..256201d4f94
--- /dev/null
+++ b/sys/boot/Makefile.i386
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR+=		efi
+SUBDIR+=		zfs
diff --git a/sys/boot/Makefile.ia64 b/sys/boot/Makefile.ia64
new file mode 100644
index 00000000000..921f2930d30
--- /dev/null
+++ b/sys/boot/Makefile.ia64
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR+=		efi
diff --git a/sys/boot/Makefile.pc98 b/sys/boot/Makefile.pc98
new file mode 100644
index 00000000000..aa989e1784b
--- /dev/null
+++ b/sys/boot/Makefile.pc98
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+# Blank, to override Makefile.i386 since Makefile.$MACHINE is included before 
+# Makefile.$MACHINE_ARCH
diff --git a/sys/boot/Makefile.powerpc b/sys/boot/Makefile.powerpc
new file mode 100644
index 00000000000..ca8c33139b1
--- /dev/null
+++ b/sys/boot/Makefile.powerpc
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR+=		ofw
+SUBDIR+=		uboot
diff --git a/sys/boot/Makefile.sparc64 b/sys/boot/Makefile.sparc64
new file mode 100644
index 00000000000..5723629ba47
--- /dev/null
+++ b/sys/boot/Makefile.sparc64
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR+=		ofw
diff --git a/sys/boot/efi/libefi/Makefile b/sys/boot/efi/libefi/Makefile
index 55053e1042f..beb9269d0a2 100644
--- a/sys/boot/efi/libefi/Makefile
+++ b/sys/boot/efi/libefi/Makefile
@@ -7,7 +7,7 @@ SRCS=	delay.c efi_console.c efinet.c efipart.c errno.c handles.c \
 	libefi.c time.c
 
 CFLAGS+= -I${.CURDIR}/../include
-CFLAGS+= -I${.CURDIR}/../include/${MACHINE_ARCH:S/amd64/i386/}
+CFLAGS+= -I${.CURDIR}/../include/${MACHINE_CPUARCH:S/amd64/i386/}
 CFLAGS+= -I${.CURDIR}/../../../../lib/libstand
 
 # Pick up the bootstrap header for some interface items

From f0e82e0b0134580c9ae463da8946142ff4641fd8 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 01:50:34 +0000
Subject: [PATCH 0172/1624] MF tbemd: Minor tweaks, prefer MACHINE_CPUARCH
 generally to MACHINE_ARCH (which simplifies some powerpc/powerpc64 ifs)

---
 sys/boot/ia64/common/Makefile |  4 ++--
 sys/boot/ia64/efi/Makefile    | 10 +++++-----
 sys/boot/ia64/ski/Makefile    |  4 ++--
 sys/boot/ofw/libofw/Makefile  |  4 ++--
 sys/boot/uboot/lib/Makefile   |  2 +-
 sys/boot/zfs/Makefile         | 12 ++++++------
 6 files changed, 18 insertions(+), 18 deletions(-)

diff --git a/sys/boot/ia64/common/Makefile b/sys/boot/ia64/common/Makefile
index 8261c25539c..3204edcd6c4 100644
--- a/sys/boot/ia64/common/Makefile
+++ b/sys/boot/ia64/common/Makefile
@@ -9,7 +9,7 @@ INTERNALLIB=
 SRCS=		autoload.c bootinfo.c copy.c devicename.c exec.c
 
 CFLAGS+=	-I${.CURDIR}/../../efi/include
-CFLAGS+=	-I${.CURDIR}/../../efi/include/${MACHINE_ARCH}
+CFLAGS+=	-I${.CURDIR}/../../efi/include/${MACHINE_CPUARCH}
 CFLAGS+=	-I${.CURDIR}/../../..
 CFLAGS+=	-I${.CURDIR}/../../../../lib/libstand
 
@@ -17,7 +17,7 @@ CFLAGS+=	-I${.CURDIR}/../../../../lib/libstand
 BOOT_FORTH=	yes
 CFLAGS+=	-DBOOT_FORTH
 CFLAGS+=	-I${.CURDIR}/../../ficl
-CFLAGS+=	-I${.CURDIR}/../../ficl/${MACHINE_ARCH}
+CFLAGS+=	-I${.CURDIR}/../../ficl/${MACHINE_CPUARCH}
 .endif
 
 .PATH: ${.CURDIR}/../../common
diff --git a/sys/boot/ia64/efi/Makefile b/sys/boot/ia64/efi/Makefile
index 5682ac85ea6..27e81b996ab 100644
--- a/sys/boot/ia64/efi/Makefile
+++ b/sys/boot/ia64/efi/Makefile
@@ -9,21 +9,21 @@ PROG=		loader.sym
 INTERNALPROG=
 SRCS=		conf.c efimd.c main.c pal.S start.S vers.c
 
-.PATH: ${.CURDIR}/../../../${MACHINE_ARCH}/${MACHINE_ARCH}
+.PATH: ${.CURDIR}/../../../${MACHINE_CPUARCH}/${MACHINE_CPUARCH}
 
 CFLAGS+=	-I${.CURDIR}/../common
 CFLAGS+=	-I${.CURDIR}/../../common
 CFLAGS+=	-I${.CURDIR}/../../efi/include
-CFLAGS+=	-I${.CURDIR}/../../efi/include/${MACHINE_ARCH}
+CFLAGS+=	-I${.CURDIR}/../../efi/include/${MACHINE_CPUARCH}
 CFLAGS+=	-I${.CURDIR}/../../..
 CFLAGS+=	-I${.CURDIR}/../../../../lib/libstand
 
-LDSCRIPT=	${.CURDIR}/ldscript.${MACHINE_ARCH}
+LDSCRIPT=	${.CURDIR}/ldscript.${MACHINE_CPUARCH}
 LDFLAGS=	-Wl,-T${LDSCRIPT} -shared -symbolic
 
 ${PROG}: ${LDSCRIPT}
 
-NEWVERSWHAT=	"EFI boot" ${MACHINE_ARCH}
+NEWVERSWHAT=	"EFI boot" ${MACHINE_CPUARCH}
 
 vers.c: ${.CURDIR}/../../common/newvers.sh ${.CURDIR}/version
 	sh ${.CURDIR}/../../common/newvers.sh ${.CURDIR}/version ${NEWVERSWHAT}
@@ -42,7 +42,7 @@ loader.efi: loader.sym
 	fi
 	${OBJCOPY} -j .data -j .dynamic -j .dynstr -j .dynsym -j .hash \
 	    -j .rela.dyn -j .reloc -j .sdata -j .text \
-	    --target=efi-app-${MACHINE_ARCH} ${.ALLSRC} ${.TARGET}
+	    --target=efi-app-${MACHINE_CPUARCH} ${.ALLSRC} ${.TARGET}
 
 CLEANFILES=	vers.c loader.efi
 
diff --git a/sys/boot/ia64/ski/Makefile b/sys/boot/ia64/ski/Makefile
index 081fd72e8e7..5151435b94c 100644
--- a/sys/boot/ia64/ski/Makefile
+++ b/sys/boot/ia64/ski/Makefile
@@ -17,10 +17,10 @@ CFLAGS+=	-I${.CURDIR}/../../common
 CFLAGS+=	-I${.CURDIR}/../../..
 CFLAGS+=	-I${.CURDIR}/../../../../lib/libstand
 
-LDSCRIPT=	${.CURDIR}/ldscript.${MACHINE_ARCH}
+LDSCRIPT=	${.CURDIR}/ldscript.${MACHINE_CPUARCH}
 LDFLAGS=	-Wl,-T${LDSCRIPT}
 
-NEWVERSWHAT=	"SKI boot" ${MACHINE_ARCH}
+NEWVERSWHAT=	"SKI boot" ${MACHINE_CPUARCH}
 
 vers.c: ${.CURDIR}/../../common/newvers.sh ${.CURDIR}/version
 	sh ${.CURDIR}/../../common/newvers.sh ${.CURDIR}/version ${NEWVERSWHAT}
diff --git a/sys/boot/ofw/libofw/Makefile b/sys/boot/ofw/libofw/Makefile
index 5ea0de972af..945d6508988 100644
--- a/sys/boot/ofw/libofw/Makefile
+++ b/sys/boot/ofw/libofw/Makefile
@@ -13,7 +13,7 @@ CFLAGS+=	-I${.CURDIR}/../../../../lib/libstand/
 CFLAGS+=	-I${.CURDIR}/../../common -I${.CURDIR}/../../.. -I.
 
 CFLAGS+=	-ffreestanding
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_CPUARCH} == "powerpc"
 CFLAGS+=	-msoft-float
 SRCS+=		ppc64_elf_freebsd.c
 .endif
@@ -24,7 +24,7 @@ CFLAGS+= -DDISK_DEBUG
 .endif
 
 machine:
-	ln -sf ${.CURDIR}/../../../${MACHINE_ARCH}/include machine
+	ln -sf ${.CURDIR}/../../../${MACHINE_CPUARCH}/include machine
 
 CLEANFILES+=	machine
 
diff --git a/sys/boot/uboot/lib/Makefile b/sys/boot/uboot/lib/Makefile
index 11088f133f2..039a282553c 100644
--- a/sys/boot/uboot/lib/Makefile
+++ b/sys/boot/uboot/lib/Makefile
@@ -23,7 +23,7 @@ CFLAGS+= -DDISK_DEBUG
 .endif
 
 machine:
-	ln -sf ${.CURDIR}/../../../${MACHINE_ARCH}/include machine
+	ln -sf ${.CURDIR}/../../../${MACHINE_CPUARCH}/include machine
 
 CLEANFILES+=	machine
 
diff --git a/sys/boot/zfs/Makefile b/sys/boot/zfs/Makefile
index b48804bc37a..beba733581c 100644
--- a/sys/boot/zfs/Makefile
+++ b/sys/boot/zfs/Makefile
@@ -10,23 +10,23 @@ CFLAGS+=	-I${.CURDIR}/../../../lib/libstand
 CFLAGS+=	-I${.CURDIR}/../../cddl/boot/zfs
 
 CFLAGS+=	-ffreestanding
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-mpreferred-stack-boundary=2
 CFLAGS+=	-mno-mmx -mno-3dnow -mno-sse -mno-sse2
 .endif
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 CFLAGS+=	-mno-sse3
 .endif
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "powerpc" || ${MACHINE_CPUARCH} == "arm"
 CFLAGS+=	-msoft-float
 .endif
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-m32 -march=i386
 .endif
 
 CFLAGS+=	-Wformat -Wall
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CLEANFILES+=    machine
 machine:
 	ln -sf ${.CURDIR}/../../i386/include machine
@@ -34,6 +34,6 @@ machine:
 
 .include 
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend ${OBJS}: machine
 .endif

From 90db41b62bf17f2260ea09d543fedf2f68a33865 Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Mon, 23 Aug 2010 05:33:31 +0000
Subject: [PATCH 0173/1624] uio_resid isn't updated by VOP_READDIR for nfs
 filesystems.  Use the uio_offset adjustment instead to calculate a correct
 *len.

Without this change, we run off the end of the directory data
we're reading and panic horribly for nfs filesystems.

MFC after:	1 week
---
 sys/kern/vfs_default.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/sys/kern/vfs_default.c b/sys/kern/vfs_default.c
index 2d9a9082422..bf037feb744 100644
--- a/sys/kern/vfs_default.c
+++ b/sys/kern/vfs_default.c
@@ -281,10 +281,9 @@ get_next_dirent(struct vnode *vp, struct dirent **dpp, char *dirbuf,
 		if (error)
 			return (error);
 
-		*off = uio.uio_offset;
-
 		*cpos = dirbuf;
-		*len = (dirbuflen - uio.uio_resid);
+		*len = uio.uio_offset - *off;
+		*off = uio.uio_offset;
 	}
 
 	dp = (struct dirent *)(*cpos);

From c09808d0d611d103bece3d41886b87de160900c0 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 06:13:29 +0000
Subject: [PATCH 0174/1624] MFtbemd:

Use MACHINE_CPUARCH in preference to MACHINE_ARCH.  The former is the
source code location of the machine, the latter the binary output.  In
general, we want to use MACHINE_CPUARCH instead of MACHINE_ARCH unless
we're tesitng for a specific target.  The isn't even moot for
i386/amd64 where there's momemntum towards a MACHINE_CPUARCH == x86,
although a specific cleanup for that likely would be needed...
---
 sys/modules/Makefile                     | 12 ++++++------
 sys/modules/aac/Makefile                 |  2 +-
 sys/modules/acpi/acpi/Makefile           | 13 ++++++++-----
 sys/modules/agp/Makefile                 |  4 ++--
 sys/modules/amr/Makefile                 |  2 +-
 sys/modules/asr/Makefile                 |  2 +-
 sys/modules/bge/Makefile                 |  2 +-
 sys/modules/cpufreq/Makefile             |  2 +-
 sys/modules/cxgb/Makefile                |  4 ++--
 sys/modules/cyclic/Makefile              |  4 ++--
 sys/modules/dtrace/Makefile              |  2 +-
 sys/modules/dtrace/Makefile.inc          |  4 ++--
 sys/modules/dtrace/dtrace/Makefile       |  6 +++---
 sys/modules/dtrace/fasttrap/Makefile     |  2 +-
 sys/modules/hptmv/Makefile               |  4 ++--
 sys/modules/hptrr/Makefile               |  2 +-
 sys/modules/hwpmc/Makefile               | 10 +++++-----
 sys/modules/i2c/controllers/pcf/Makefile |  4 ++--
 sys/modules/io/Makefile                  |  2 +-
 sys/modules/le/Makefile                  |  2 +-
 sys/modules/linprocfs/Makefile           |  2 +-
 sys/modules/linsysfs/Makefile            |  2 +-
 sys/modules/linux/Makefile               |  8 ++++----
 sys/modules/mem/Makefile                 |  8 ++++----
 sys/modules/mfi/Makefile                 |  2 +-
 sys/modules/ndis/Makefile                |  4 ++--
 sys/modules/ppc/Makefile                 |  6 +++---
 sys/modules/procfs/Makefile              |  2 +-
 sys/modules/smbfs/Makefile               |  4 ++--
 sys/modules/sound/driver/Makefile        |  4 ++--
 sys/modules/svr4/Makefile                |  2 +-
 sys/modules/syscons/Makefile             |  5 +++--
 sys/modules/uart/Makefile                |  2 +-
 sys/modules/usb/Makefile                 |  6 +++---
 sys/modules/vx/Makefile                  |  2 +-
 35 files changed, 74 insertions(+), 70 deletions(-)

diff --git a/sys/modules/Makefile b/sys/modules/Makefile
index 200d81476c5..80850bd4ec2 100644
--- a/sys/modules/Makefile
+++ b/sys/modules/Makefile
@@ -323,8 +323,8 @@ SUBDIR=	${_3dfx} \
 	${_zfs} \
 	zlib \
 
-.if ${MACHINE_CPUARCH} != "powerpc" && ${MACHINE_ARCH} != "arm" && \
-	${MACHINE_ARCH} != "mips"
+.if ${MACHINE_CPUARCH} != "powerpc" && ${MACHINE_CPUARCH} != "arm" && \
+	${MACHINE_CPUARCH} != "mips"
 _syscons=	syscons
 _vpo=		vpo
 .endif
@@ -360,7 +360,7 @@ _pf=		pf
 _pflog=		pflog
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 # XXX some of these can move to the general case when de-i386'ed
 # XXX some of these can move now, but are untested on other architectures.
 _3dfx=		3dfx
@@ -500,7 +500,7 @@ _snc=		snc
 .endif
 .endif
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 _aac=		aac
 _acpi=		acpi
 .if ${MK_CRYPT} != "no" || defined(ALL_MODULES)
@@ -590,7 +590,7 @@ _zfs=		zfs
 .endif
 .endif
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 _aac=		aac
 _aic=		aic
 _an=		an
@@ -647,7 +647,7 @@ _zfs=		zfs
 .endif
 .endif
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 _auxio=		auxio
 _em=		em
 _epic=		epic
diff --git a/sys/modules/aac/Makefile b/sys/modules/aac/Makefile
index 6964defc820..5b6525f7dea 100644
--- a/sys/modules/aac/Makefile
+++ b/sys/modules/aac/Makefile
@@ -2,7 +2,7 @@
 
 .PATH: ${.CURDIR}/../../dev/aac
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SUBDIR= aac_linux
 .endif
 
diff --git a/sys/modules/acpi/acpi/Makefile b/sys/modules/acpi/acpi/Makefile
index e37b1d90a2c..98289b38ff6 100644
--- a/sys/modules/acpi/acpi/Makefile
+++ b/sys/modules/acpi/acpi/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 .error "ACPI can only be compiled into the kernel on the ia64 platform"
 .endif
 
@@ -22,7 +22,7 @@
 	${.CURDIR}/../../../pci \
 	${.CURDIR}/../../../dev/acpica \
 	${.CURDIR}/../../../dev/acpica/Osd \
-	${.CURDIR}/../../../${MACHINE_ARCH}/acpica
+	${.CURDIR}/../../../${MACHINE_CPUARCH}/acpica
 
 KMOD=	acpi
 
@@ -98,7 +98,10 @@ SRCS+=	acpi_machdep.c acpi_wakecode.h acpi_wakeup.c
 SRCS+=	assym.s madt.c
 CLEANFILES+=	acpi_wakecode.bin acpi_wakecode.h acpi_wakecode.o
 
-.if ${MACHINE_ARCH} == "amd64"
+SRCS+=	opt_global.h
+
+.if ${MACHINE_CPUARCH} == "amd64"
+SRCS+=	acpi_switch.S opt_global.h
 .if !defined(KERNBUILDDIR)
 CFLAGS+=-DSMP
 .endif
@@ -119,8 +122,8 @@ acpi_wakedata.h: acpi_wakecode.o
 	    echo "#define	$${what}	0x$${offset}"; done > ${.TARGET}
 .else
 acpi_wakecode.h: acpi_wakecode.S assym.s
-	${MAKE} -f ${.CURDIR}/../../../${MACHINE_ARCH}/acpica/Makefile \
-		MAKESRCPATH=${.CURDIR}/../../../${MACHINE_ARCH}/acpica
+	${MAKE} -f ${.CURDIR}/../../../${MACHINE_CPUARCH}/acpica/Makefile \
+		MAKESRCPATH=${.CURDIR}/../../../${MACHINE_CPUARCH}/acpica
 .endif
 
 .include 
diff --git a/sys/modules/agp/Makefile b/sys/modules/agp/Makefile
index 40263251beb..f77e38cfeff 100644
--- a/sys/modules/agp/Makefile
+++ b/sys/modules/agp/Makefile
@@ -4,14 +4,14 @@
 
 KMOD=	agp
 SRCS=	agp.c agp_if.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	agp_i810.c agp_intel.c agp_via.c agp_sis.c agp_ali.c agp_amd.c \
 	agp_nvidia.c agp_ati.c
 .endif
 .if ${MACHINE} == "i386"
 SRCS+=	agp_amd64.c
 .endif
-.if  ${MACHINE_ARCH} == "amd64"
+.if  ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	agp_amd64.c agp_i810.c agp_via.c
 .endif
 SRCS+=	device_if.h bus_if.h agp_if.h pci_if.h
diff --git a/sys/modules/amr/Makefile b/sys/modules/amr/Makefile
index 4c31997c844..02de047d2aa 100644
--- a/sys/modules/amr/Makefile
+++ b/sys/modules/amr/Makefile
@@ -3,7 +3,7 @@
 .PATH: ${.CURDIR}/../../dev/amr
 
 SUBDIR= amr_cam
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SUBDIR+= amr_linux
 .endif
 
diff --git a/sys/modules/asr/Makefile b/sys/modules/asr/Makefile
index 7addf52974f..5873415d028 100644
--- a/sys/modules/asr/Makefile
+++ b/sys/modules/asr/Makefile
@@ -7,7 +7,7 @@ SRCS=	asr.c
 SRCS+=	opt_scsi.h opt_cam.h
 SRCS+=	device_if.h bus_if.h pci_if.h
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	opt_asr.h
 .endif
 
diff --git a/sys/modules/bge/Makefile b/sys/modules/bge/Makefile
index f8ebf42fd8d..9742e6b8f37 100644
--- a/sys/modules/bge/Makefile
+++ b/sys/modules/bge/Makefile
@@ -5,7 +5,7 @@
 KMOD=	if_bge
 SRCS=	if_bge.c miibus_if.h miidevs.h device_if.h bus_if.h pci_if.h
 
-.if ${MACHINE_ARCH} == sparc64
+.if ${MACHINE_CPUARCH} == sparc64
 SRCS+=	ofw_bus_if.h
 .endif
 
diff --git a/sys/modules/cpufreq/Makefile b/sys/modules/cpufreq/Makefile
index 894096ff14a..26fea830b8c 100644
--- a/sys/modules/cpufreq/Makefile
+++ b/sys/modules/cpufreq/Makefile
@@ -1,7 +1,7 @@
 # $FreeBSD$
 
 .PATH:	${.CURDIR}/../../dev/cpufreq		\
-	${.CURDIR}/../../${MACHINE_ARCH}/cpufreq
+	${.CURDIR}/../../${MACHINE_CPUARCH}/cpufreq
 
 KMOD=	cpufreq
 SRCS=	ichss.c
diff --git a/sys/modules/cxgb/Makefile b/sys/modules/cxgb/Makefile
index 71cbb7add81..a6af8179daf 100644
--- a/sys/modules/cxgb/Makefile
+++ b/sys/modules/cxgb/Makefile
@@ -28,11 +28,11 @@ _toecore = toecore
 #_tom = tom
 .endif
 
-.if ${MACHINE_ARCH} == "i386" && exists(${_toe_header})
+.if ${MACHINE_CPUARCH} == "i386" && exists(${_toe_header})
 _iw_cxgb = iw_cxgb
 .endif
 
-.if ${MACHINE_ARCH} == "amd64" && exists(${_toe_header})
+.if ${MACHINE_CPUARCH} == "amd64" && exists(${_toe_header})
 _iw_cxgb = iw_cxgb
 .endif
 
diff --git a/sys/modules/cyclic/Makefile b/sys/modules/cyclic/Makefile
index 371dac68054..b29cac1bd6e 100644
--- a/sys/modules/cyclic/Makefile
+++ b/sys/modules/cyclic/Makefile
@@ -4,13 +4,13 @@
 
 KMOD=		cyclic
 SRCS=		cyclic.c
-		
+
 SRCS+=		vnode_if.h
 
 CFLAGS+=	-I${.CURDIR}/../../cddl/compat/opensolaris		\
 		-I${.CURDIR}/../../cddl/contrib/opensolaris/uts/common	\
 		-I${.CURDIR}/../..					\
-		-I${.CURDIR}/../../cddl/dev/cyclic/${MACHINE_ARCH:S/amd64/i386/}
+		-I${.CURDIR}/../../cddl/dev/cyclic/${MACHINE_CPUARCH:S/amd64/i386/}
 
 CFLAGS+=	-DDEBUG=1
 
diff --git a/sys/modules/dtrace/Makefile b/sys/modules/dtrace/Makefile
index 8fad00c2683..75d4a44dcab 100644
--- a/sys/modules/dtrace/Makefile
+++ b/sys/modules/dtrace/Makefile
@@ -14,7 +14,7 @@ SUBDIR=		dtmalloc	\
 		sdt		\
 		systrace
 
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 SUBDIR+=	fbt
 .endif
 
diff --git a/sys/modules/dtrace/Makefile.inc b/sys/modules/dtrace/Makefile.inc
index c35764b2998..db329604700 100644
--- a/sys/modules/dtrace/Makefile.inc
+++ b/sys/modules/dtrace/Makefile.inc
@@ -5,7 +5,7 @@ IGNORE_PRAGMA=	1
 load	:
 	-kldload cyclic
 	-kldload dtrace
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 	-kldload sdt
 	-kldload lockstat
 	-kldload fbt
@@ -18,7 +18,7 @@ load	:
 unload	:
 	-kldunload systrace
 	-kldunload profile
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 	-kldunload prototype
 	-kldunload fbt
 	-kldunload lockstat
diff --git a/sys/modules/dtrace/dtrace/Makefile b/sys/modules/dtrace/dtrace/Makefile
index 08e61a94c4f..5f10e925af3 100644
--- a/sys/modules/dtrace/dtrace/Makefile
+++ b/sys/modules/dtrace/dtrace/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-ARCHDIR=	${MACHINE_ARCH}
+ARCHDIR=	${MACHINE_CPUARCH}
 
 .PATH: ${.CURDIR}/../../../cddl/contrib/opensolaris/uts/common/dtrace
 .PATH: ${.CURDIR}/../../../cddl/kern
@@ -12,7 +12,7 @@ SRCS=		dtrace.c \
 		dtrace_asm.S \
 		dtrace_subr.c
 
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 SRCS+=		dis_tables.c \
 		instr_size.c
 .endif
@@ -25,7 +25,7 @@ SRCS+=		assym.s
 # These are needed for assym.s
 SRCS+=		opt_compat.h opt_kstack_pages.h opt_nfs.h opt_hwpmc_hooks.h
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=		opt_apic.h
 .endif
 
diff --git a/sys/modules/dtrace/fasttrap/Makefile b/sys/modules/dtrace/fasttrap/Makefile
index 104fd9af445..0af63c4eb03 100644
--- a/sys/modules/dtrace/fasttrap/Makefile
+++ b/sys/modules/dtrace/fasttrap/Makefile
@@ -10,7 +10,7 @@ CFLAGS+=	-I${.CURDIR}/../../../cddl/compat/opensolaris \
 		-I${.CURDIR}/../../../cddl/contrib/opensolaris/uts/common \
 		-I${.CURDIR}/../../..
 
-.if ${MACHINE_ARCH} == "amd64" ||  ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "amd64" ||  ${MACHINE_CPUARCH} == "i386"
 CFLAGS+=	-I${.CURDIR}/../../../cddl/contrib/opensolaris/uts/intel
 .endif
 
diff --git a/sys/modules/hptmv/Makefile b/sys/modules/hptmv/Makefile
index 05ceac7bb1f..134c207020d 100644
--- a/sys/modules/hptmv/Makefile
+++ b/sys/modules/hptmv/Makefile
@@ -13,7 +13,7 @@ SRCS+= bus_if.h device_if.h pci_if.h
 SRCS+= mv.c entry.c ioctl.c hptproc.c gui_lib.c
 OBJS+= hptmvraid.o
 
-.if $(MACHINE_ARCH) == "amd64"
+.if $(MACHINE_CPUARCH) == "amd64"
 HPTMV_RAID_O = amd64-elf.raid.o.uu
 .else
 HPTMV_RAID_O = i386-elf.raid.o.uu
@@ -48,5 +48,5 @@ DEBUGOPT += -DFOR_DEMO
 .endif
 
 CFLAGS = ${DEBUGOPT}
-	
+
 .include 
diff --git a/sys/modules/hptrr/Makefile b/sys/modules/hptrr/Makefile
index 038c5a45f46..7cbd7e85a24 100644
--- a/sys/modules/hptrr/Makefile
+++ b/sys/modules/hptrr/Makefile
@@ -9,6 +9,6 @@ SRCS+= hptrr_os_bsd.c hptrr_osm_bsd.c hptrr_config.c
 OBJS = hptrr_lib.o
 
 hptrr_lib.o:
-	uudecode -p < ${HPTRR}/$(MACHINE_ARCH)-elf.hptrr_lib.o.uu > hptrr_lib.o
+	uudecode -p < ${HPTRR}/$(MACHINE_CPUARCH)-elf.hptrr_lib.o.uu > hptrr_lib.o
 
 .include 
diff --git a/sys/modules/hwpmc/Makefile b/sys/modules/hwpmc/Makefile
index b295a67f5ae..b834f174dbf 100644
--- a/sys/modules/hwpmc/Makefile
+++ b/sys/modules/hwpmc/Makefile
@@ -8,23 +8,23 @@ KMOD=	hwpmc
 
 SRCS=	hwpmc_mod.c hwpmc_logging.c vnode_if.h
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	hwpmc_amd.c hwpmc_core.c hwpmc_intel.c hwpmc_piv.c hwpmc_tsc.c
 SRCS+=	hwpmc_x86.c hwpmc_uncore.c
 SRCS+=	device_if.h bus_if.h
 .endif
 
-.if ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "arm"
 SRCS+=	hwpmc_arm.c
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	hwpmc_amd.c hwpmc_core.c hwpmc_intel.c hwpmc_piv.c hwpmc_ppro.c
 SRCS+=	hwpmc_pentium.c hwpmc_tsc.c hwpmc_x86.c hwpmc_uncore.c
 SRCS+=	device_if.h bus_if.h
 .endif
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 SRCS+=	hwpmc_ia64.c
 .endif
 
@@ -32,7 +32,7 @@ SRCS+=	hwpmc_ia64.c
 SRCS+=	hwpmc_powerpc.c
 .endif
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 SRCS+=	hwpmc_sparc64.c
 .endif
 
diff --git a/sys/modules/i2c/controllers/pcf/Makefile b/sys/modules/i2c/controllers/pcf/Makefile
index 4714cfd9c1c..27d9339822f 100644
--- a/sys/modules/i2c/controllers/pcf/Makefile
+++ b/sys/modules/i2c/controllers/pcf/Makefile
@@ -6,12 +6,12 @@ KMOD=	pcf
 SRCS=	${envctrl} pcf.c ${pcf_ebus} ${pcf_isa}
 SRCS+=	bus_if.h device_if.h iicbus_if.h ${isa_if} ${ofw_bus_if}
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 isa_if=		isa_if.h
 pcf_isa=	pcf_isa.c
 .endif
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 envctrl=	envctrl.c
 ofw_bus_if=	ofw_bus_if.h
 pcf_ebus=	pcf_ebus.c
diff --git a/sys/modules/io/Makefile b/sys/modules/io/Makefile
index d90a8e473b1..1612fa0eff5 100644
--- a/sys/modules/io/Makefile
+++ b/sys/modules/io/Makefile
@@ -1,7 +1,7 @@
 # $FreeBSD$
 
 .PATH: ${.CURDIR}/../../dev/io
-.PATH: ${.CURDIR}/../../${MACHINE_ARCH}/${MACHINE_ARCH}
+.PATH: ${.CURDIR}/../../${MACHINE_CPUARCH}/${MACHINE_CPUARCH}
 
 KMOD=	io
 SRCS=	iodev.c io.c
diff --git a/sys/modules/le/Makefile b/sys/modules/le/Makefile
index dd202fb8955..d267cbec2c2 100644
--- a/sys/modules/le/Makefile
+++ b/sys/modules/le/Makefile
@@ -7,7 +7,7 @@ SRCS=	am7990.c am79900.c ${if_le_cbus} ${if_le_isa} ${if_le_lebuffer}
 SRCS+=	${if_le_ledma} if_le_pci.c lance.c ${lebuffer_sbus}
 SRCS+=	bus_if.h device_if.h ${isa_if} ${ofw_bus_if} pci_if.h
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 .if ${MACHINE} == "pc98"
 if_le_cbus=	if_le_cbus.c
 .else
diff --git a/sys/modules/linprocfs/Makefile b/sys/modules/linprocfs/Makefile
index f0f00cbea6f..4b1b3754303 100644
--- a/sys/modules/linprocfs/Makefile
+++ b/sys/modules/linprocfs/Makefile
@@ -8,7 +8,7 @@ SRCS=	vnode_if.h \
 	linprocfs.c \
 	opt_compat.h
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=-DCOMPAT_LINUX32
 .endif
 
diff --git a/sys/modules/linsysfs/Makefile b/sys/modules/linsysfs/Makefile
index 1320212004f..40179677920 100644
--- a/sys/modules/linsysfs/Makefile
+++ b/sys/modules/linsysfs/Makefile
@@ -8,7 +8,7 @@ SRCS=	vnode_if.h \
 	linsysfs.c \
 	opt_compat.h
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=-DCOMPAT_LINUX32
 .endif
 
diff --git a/sys/modules/linux/Makefile b/sys/modules/linux/Makefile
index 6474327df4f..78f6f8599ab 100644
--- a/sys/modules/linux/Makefile
+++ b/sys/modules/linux/Makefile
@@ -1,11 +1,11 @@
 # $FreeBSD$
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 SFX= 32
 CFLAGS+=-DCOMPAT_FREEBSD32 -DCOMPAT_LINUX32
 .endif
 
-.PATH: ${.CURDIR}/../../compat/linux ${.CURDIR}/../../${MACHINE_ARCH}/linux${SFX}
+.PATH: ${.CURDIR}/../../compat/linux ${.CURDIR}/../../${MACHINE_CPUARCH}/linux${SFX}
 
 KMOD=	linux
 SRCS=	linux${SFX}_dummy.c linux_emul.c linux_file.c \
@@ -18,13 +18,13 @@ SRCS=	linux${SFX}_dummy.c linux_emul.c linux_file.c \
 
 # XXX: for assym.s
 SRCS+=  opt_kstack_pages.h opt_nfs.h opt_compat.h opt_hwpmc_hooks.h
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	opt_apic.h
 .endif
 
 OBJS=	linux${SFX}_locore.o linux${SFX}_support.o
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	linux_ptrace.c imgact_linux.c opt_cpu.h
 .endif
 
diff --git a/sys/modules/mem/Makefile b/sys/modules/mem/Makefile
index 812da143936..b4fdb9c8443 100644
--- a/sys/modules/mem/Makefile
+++ b/sys/modules/mem/Makefile
@@ -2,17 +2,17 @@
 
 .PATH: ${.CURDIR}/../../dev/mem
 .PATH: ${.CURDIR}/../../${MACHINE}/${MACHINE}
-.PATH: ${.CURDIR}/../../${MACHINE_ARCH}/${MACHINE_ARCH}
+.PATH: ${.CURDIR}/../../${MACHINE_CPUARCH}/${MACHINE_CPUARCH}
 
 KMOD=	mem
 SRCS=	memdev.c mem.c
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 SRCS+=	memutil.c
 .endif
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	i686_mem.c k6_mem.c
 .endif
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	amd64_mem.c
 .endif
 SRCS+=	bus_if.h device_if.h
diff --git a/sys/modules/mfi/Makefile b/sys/modules/mfi/Makefile
index a58e968ffd4..00caa57e177 100644
--- a/sys/modules/mfi/Makefile
+++ b/sys/modules/mfi/Makefile
@@ -4,7 +4,7 @@
 
 SUBDIR= mfip
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SUBDIR+= mfi_linux
 .endif
 
diff --git a/sys/modules/ndis/Makefile b/sys/modules/ndis/Makefile
index 8ef7089ac3f..b4dc428bdb5 100644
--- a/sys/modules/ndis/Makefile
+++ b/sys/modules/ndis/Makefile
@@ -8,11 +8,11 @@ SRCS+=	kern_windrv.c subr_usbd.c
 SRCS+=	device_if.h bus_if.h pci_if.h vnode_if.h
 SRCS+=	opt_bus.h opt_usb.h usb_if.h usbdevs.h
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	winx64_wrap.S
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	winx32_wrap.S
 .endif
 
diff --git a/sys/modules/ppc/Makefile b/sys/modules/ppc/Makefile
index db36e733773..c097002a62c 100644
--- a/sys/modules/ppc/Makefile
+++ b/sys/modules/ppc/Makefile
@@ -6,18 +6,18 @@ SRCS=	bus_if.h device_if.h ppbus_if.h isa_if.h pci_if.h serdev_if.h \
 	opt_ppc.h opt_isa.h \
 	ppc.c ppc_pci.c ppc_puc.c
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	ppc_acpi.c ppc_isa.c
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 .if ${MACHINE} != "pc98"
 SRCS+=	ppc_acpi.c
 .endif
 SRCS+=	ppc_isa.c
 .endif
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 SRCS+=	ppc_acpi.c
 .endif
 
diff --git a/sys/modules/procfs/Makefile b/sys/modules/procfs/Makefile
index 9a94838c70a..2b3b0620bbe 100644
--- a/sys/modules/procfs/Makefile
+++ b/sys/modules/procfs/Makefile
@@ -34,7 +34,7 @@ opt_compat.h:
 	echo "#define COMPAT_FREEBSD4 1" >> ${.TARGET}
 	echo "#define COMPAT_FREEBSD5 1" >> ${.TARGET}
 	echo "#define COMPAT_FREEBSD6 1" >> ${.TARGET}
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 	echo "#define COMPAT_FREEBSD32 1" >> ${.TARGET}
 	echo "#define COMPAT_LINUX32 1" >> ${.TARGET}
 .endif
diff --git a/sys/modules/smbfs/Makefile b/sys/modules/smbfs/Makefile
index e8432e39297..476e598edb6 100644
--- a/sys/modules/smbfs/Makefile
+++ b/sys/modules/smbfs/Makefile
@@ -1,7 +1,7 @@
 # $FreeBSD$
 
 .PATH:	${.CURDIR}/../../crypto/des \
-	${.CURDIR}/../../crypto/des/arch/${MACHINE_ARCH} \
+	${.CURDIR}/../../crypto/des/arch/${MACHINE_CPUARCH} \
 	${.CURDIR}/../../kern \
 	${.CURDIR}/../../libkern \
 	${.CURDIR}/../../netsmb \
@@ -21,7 +21,7 @@ SRCS=	vnode_if.h \
 
 # NETSMBCRYPTO
 SRCS+=	des_ecb.c des_setkey.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	des_enc.S
 .else
 SRCS+=	des_enc.c
diff --git a/sys/modules/sound/driver/Makefile b/sys/modules/sound/driver/Makefile
index c07a1c55337..ef018b2f607 100644
--- a/sys/modules/sound/driver/Makefile
+++ b/sys/modules/sound/driver/Makefile
@@ -5,11 +5,11 @@ SUBDIR+=	envy24 envy24ht es137x ess fm801 hda ich maestro maestro3
 SUBDIR+=	neomagic sb16 sb8 sbc solo spicds t4dwave via8233
 SUBDIR+=	via82c686 vibes driver uaudio
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SUBDIR+=	cmi mss
 .endif
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 .if ${MACHINE} == "sparc64"
 SUBDIR+=	audiocs
 .endif
diff --git a/sys/modules/svr4/Makefile b/sys/modules/svr4/Makefile
index 50550989a6e..9fc0901ff46 100644
--- a/sys/modules/svr4/Makefile
+++ b/sys/modules/svr4/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.PATH:	${.CURDIR}/../../${MACHINE_ARCH}/svr4 ${.CURDIR}/../../compat/svr4
+.PATH:	${.CURDIR}/../../${MACHINE_CPUARCH}/svr4 ${.CURDIR}/../../compat/svr4
 KMOD=	svr4
 SRCS=	svr4_sysent.c svr4_sysvec.c opt_compat.h opt_svr4.h \
 	vnode_if.h imgact_svr4.c svr4_signal.c svr4_fcntl.c \
diff --git a/sys/modules/syscons/Makefile b/sys/modules/syscons/Makefile
index 13cbc57f000..b047845dece 100644
--- a/sys/modules/syscons/Makefile
+++ b/sys/modules/syscons/Makefile
@@ -14,11 +14,12 @@ SUBDIR=	${_apm} \
 	${_star} \
 	${_warp}
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 _apm=		apm
 .endif
 
-.if ${MACHINE_ARCH} != "sparc64"
+.if ${MACHINE_CPUARCH} != "sparc64"
+_beastie=	beastie
 _beastie=	beastie
 _daemon=	daemon
 _dragon=	dragon
diff --git a/sys/modules/uart/Makefile b/sys/modules/uart/Makefile
index 862930db80c..1a5ce4436da 100644
--- a/sys/modules/uart/Makefile
+++ b/sys/modules/uart/Makefile
@@ -2,7 +2,7 @@
 
 .PATH: ${.CURDIR}/../../dev/uart
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 uart_bus_ebus=	uart_bus_ebus.c
 ofw_bus_if=	ofw_bus_if.h
 .endif
diff --git a/sys/modules/usb/Makefile b/sys/modules/usb/Makefile
index 7f43e2bcc08..dc4c17849fc 100644
--- a/sys/modules/usb/Makefile
+++ b/sys/modules/usb/Makefile
@@ -35,16 +35,16 @@ SUBDIR += uether aue axe cdce cue kue rue udav uhso
 SUBDIR += usfs umass urio
 SUBDIR += quirk template
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 _urtw=		urtw
 .endif
 
-.if ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "arm"
 _at91dci=	at91dci
 _atmegadci=	atmegadci
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 _urtw=		urtw
 .endif
 
diff --git a/sys/modules/vx/Makefile b/sys/modules/vx/Makefile
index 6293b1a21fd..e1822ea3459 100644
--- a/sys/modules/vx/Makefile
+++ b/sys/modules/vx/Makefile
@@ -4,7 +4,7 @@
 
 KMOD=	if_vx
 SRCS=	if_vx.c if_vx_pci.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	if_vx_eisa.c
 .endif
 SRCS+=	device_if.h bus_if.h pci_if.h eisa_if.h

From b3cdb67393df57a094f55394600c52d964062fb1 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 06:22:35 +0000
Subject: [PATCH 0175/1624] This should really be MACHINE not MACHINE_ARCH, and
 is this Makefile even used?

---
 sys/kern/Makefile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/kern/Makefile b/sys/kern/Makefile
index 07c2d570fc0..5ab113ea803 100644
--- a/sys/kern/Makefile
+++ b/sys/kern/Makefile
@@ -28,7 +28,7 @@ init_sysent.c syscalls.c systrace_args.c ../sys/syscall.h \
 # are placed in each source directory.  We need to have links to tags files
 # from the generic directories that are relative to the machine type, even
 # via remote mounts; therefore we use symlinks to $SYSTAGS, which points at
-# ${SYSDIR}/${MACHINE_ARCH}/tags.
+# ${SYSDIR}/${MACHINE}/tags.
 
 SYSTAGS=/var/db/sys_tags
 SYSDIR=/sys
@@ -51,7 +51,7 @@ tags::
 
 links::
 	rm -f ${SYSTAGS}
-	ln -s ${SYSDIR}/${MACHINE_ARCH}/tags ${SYSTAGS}
+	ln -s ${SYSDIR}/${MACHINE}/tags ${SYSTAGS}
 	-for i in ${DGEN}; do \
 	    (cd ../$$i && { rm -f tags; ln -s ${SYSTAGS} tags; }) done
 	-for i in ${ARCH}; do \

From 6608cc579e210d6083f73e5c3477e8683a442ae0 Mon Sep 17 00:00:00 2001
From: Gabor Kovesdan 
Date: Mon, 23 Aug 2010 10:04:26 +0000
Subject: [PATCH 0176/1624] - Change default grep back to GNU version. BSD grep
 can be built with the   WITH_BSD_GREP knob. - Bump __FreeBSD_version

Requested by:   dougb
Approved by:    delphij (mentor)
---
 gnu/usr.bin/Makefile              | 8 ++++----
 share/mk/bsd.own.mk               | 2 +-
 sys/sys/param.h                   | 2 +-
 tools/build/options/WITH_BSD_GREP | 2 ++
 tools/build/options/WITH_GNU_GREP | 2 --
 usr.bin/Makefile                  | 8 ++++----
 6 files changed, 12 insertions(+), 12 deletions(-)
 create mode 100644 tools/build/options/WITH_BSD_GREP
 delete mode 100644 tools/build/options/WITH_GNU_GREP

diff --git a/gnu/usr.bin/Makefile b/gnu/usr.bin/Makefile
index 0a6d51fdcdf..2d9ad726639 100644
--- a/gnu/usr.bin/Makefile
+++ b/gnu/usr.bin/Makefile
@@ -28,6 +28,10 @@ _groff=		groff
 .endif
 .endif
 
+.if ${MK_BSD_GREP} != "yes"
+_grep=          grep
+.endif
+
 .if ${MK_CVS} != "no"
 _cvs=		cvs
 .endif
@@ -36,10 +40,6 @@ _cvs=		cvs
 _dtc=		dtc
 .endif
 
-.if ${MK_GNU_GREP} != "no"
-_grep=		grep
-.endif
-
 .if ${MK_INFO} != "no"
 _texinfo=	texinfo
 .endif
diff --git a/share/mk/bsd.own.mk b/share/mk/bsd.own.mk
index 24b2ca41538..477a83abf7d 100644
--- a/share/mk/bsd.own.mk
+++ b/share/mk/bsd.own.mk
@@ -419,9 +419,9 @@ MK_${var}:=	yes
     BIND_LIBS \
     BIND_SIGCHASE \
     BIND_XML \
+    BSD_GREP \
     ${_clang_no} \
     FDT \
-    GNU_GREP \
     HESIOD \
     IDEA
 .if defined(WITH_${var}) && defined(WITHOUT_${var})
diff --git a/sys/sys/param.h b/sys/sys/param.h
index 7e781d2f526..8d3e34e28b3 100644
--- a/sys/sys/param.h
+++ b/sys/sys/param.h
@@ -58,7 +58,7 @@
  *		in the range 5 to 9.
  */
 #undef __FreeBSD_version
-#define __FreeBSD_version 900016	/* Master, propagated to newvers */
+#define __FreeBSD_version 900017	/* Master, propagated to newvers */
 
 #ifndef LOCORE
 #include 
diff --git a/tools/build/options/WITH_BSD_GREP b/tools/build/options/WITH_BSD_GREP
new file mode 100644
index 00000000000..702ca25f612
--- /dev/null
+++ b/tools/build/options/WITH_BSD_GREP
@@ -0,0 +1,2 @@
+.\" $FreeBSD$
+Build BSD-licensed grep instead of GNU grep.
diff --git a/tools/build/options/WITH_GNU_GREP b/tools/build/options/WITH_GNU_GREP
deleted file mode 100644
index c4bd008bf73..00000000000
--- a/tools/build/options/WITH_GNU_GREP
+++ /dev/null
@@ -1,2 +0,0 @@
-.\" $FreeBSD$
-Set to build the base system with GNU grep instead of BSD grep
diff --git a/usr.bin/Makefile b/usr.bin/Makefile
index 08c10c39be9..3214761f60a 100644
--- a/usr.bin/Makefile
+++ b/usr.bin/Makefile
@@ -277,6 +277,10 @@ _bluetooth=	bluetooth
 _cpio=		cpio
 .endif
 
+.if ${MK_BSD_GREP} != "no"
+_grep=		grep
+.endif
+
 .if ${MK_CALENDAR} != "no"
 _calendar=	calendar
 .endif
@@ -285,10 +289,6 @@ _calendar=	calendar
 _clang=		clang
 .endif
 
-.if ${MK_GNU_GREP} != "yes"
-_grep=		grep
-.endif
-
 .if ${MK_HESIOD} != "no"
 _hesinfo=	hesinfo
 .endif

From aeaffd647e876e9fb494a1332355d0364fa2fe6c Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 23 Aug 2010 15:18:35 +0000
Subject: [PATCH 0177/1624] Style.

MFC after:	3 days
---
 lib/libc/Makefile        | 2 +-
 lib/libc/stdlib/atexit.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/lib/libc/Makefile b/lib/libc/Makefile
index 9f7033027c1..ad4e5bd1629 100644
--- a/lib/libc/Makefile
+++ b/lib/libc/Makefile
@@ -124,7 +124,7 @@ libkern.${MACHINE_ARCH}:: ${KMSRCS}
 .if defined(KMSRCS) && !empty(KMSRCS)
 	cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${MACHINE_ARCH}
 .endif
-        
+
 .include 
 
 # Disable warnings in contributed sources.
diff --git a/lib/libc/stdlib/atexit.c b/lib/libc/stdlib/atexit.c
index aba3eddeea7..a7a9a32e1dd 100644
--- a/lib/libc/stdlib/atexit.c
+++ b/lib/libc/stdlib/atexit.c
@@ -120,7 +120,7 @@ atexit(void (*func)(void))
 	int error;
 
 	fn.fn_type = ATEXIT_FN_STD;
-	fn.fn_ptr.std_func = func;;
+	fn.fn_ptr.std_func = func;
 	fn.fn_arg = NULL;
 	fn.fn_dso = NULL;
 
@@ -139,7 +139,7 @@ __cxa_atexit(void (*func)(void *), void *arg, void *dso)
 	int error;
 
 	fn.fn_type = ATEXIT_FN_CXA;
-	fn.fn_ptr.cxa_func = func;;
+	fn.fn_ptr.cxa_func = func;
 	fn.fn_arg = arg;
 	fn.fn_dso = dso;
 

From e048186a626fdd1dc11f7dc9336a49a556a13cb5 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 23 Aug 2010 15:27:03 +0000
Subject: [PATCH 0178/1624] Introduce implementation-private rtld interface
 _rtld_addr_phdr, which fills struct dl_phdr_info for the shared object that
 contains the specified address, if any.

Idea and reviewed by:	kan
MFC after:	3 weeks
---
 lib/libc/gen/Symbol.map     |  1 +
 lib/libc/gen/dlfcn.c        |  8 +++++++
 libexec/rtld-elf/Symbol.map |  1 +
 libexec/rtld-elf/rtld.c     | 47 +++++++++++++++++++++++++++++--------
 sys/sys/link_elf.h          |  1 +
 5 files changed, 48 insertions(+), 10 deletions(-)

diff --git a/lib/libc/gen/Symbol.map b/lib/libc/gen/Symbol.map
index 5ba18604db6..c4f21b559d7 100644
--- a/lib/libc/gen/Symbol.map
+++ b/lib/libc/gen/Symbol.map
@@ -446,6 +446,7 @@ FBSDprivate_1.0 {
 	_spinlock;
 	_spinlock_debug;
 	_spinunlock;
+	_rtld_addr_phdr;
 	_rtld_atfork_pre;
 	_rtld_atfork_post;
 	_rtld_error;		/* for private use */
diff --git a/lib/libc/gen/dlfcn.c b/lib/libc/gen/dlfcn.c
index a1ca29daceb..930ebc11ce7 100644
--- a/lib/libc/gen/dlfcn.c
+++ b/lib/libc/gen/dlfcn.c
@@ -157,3 +157,11 @@ void
 _rtld_atfork_post(int *locks)
 {
 }
+
+#pragma weak _rtld_addr_phdr
+int
+_rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
+{
+
+	return (0);
+}
diff --git a/libexec/rtld-elf/Symbol.map b/libexec/rtld-elf/Symbol.map
index 04fe9b84f77..7a8273f6301 100644
--- a/libexec/rtld-elf/Symbol.map
+++ b/libexec/rtld-elf/Symbol.map
@@ -27,4 +27,5 @@ FBSDprivate_1.0 {
     _rtld_free_tls;
     _rtld_atfork_pre;
     _rtld_atfork_post;
+    _rtld_addr_phdr;
 };
diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
index a13ecb7b94a..77eeafbef39 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -147,6 +147,8 @@ static int  rtld_verify_object_versions(Obj_Entry *);
 static void object_add_name(Obj_Entry *, const char *);
 static int  object_match_name(const Obj_Entry *, const char *);
 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
+static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
+    struct dl_phdr_info *phdr_info);
 
 void r_debug_state(struct r_debug *, struct link_map *);
 
@@ -220,6 +222,7 @@ static func_ptr_type exports[] = {
     (func_ptr_type) &dl_iterate_phdr,
     (func_ptr_type) &_rtld_atfork_pre,
     (func_ptr_type) &_rtld_atfork_post,
+    (func_ptr_type) &_rtld_addr_phdr,
     NULL
 };
 
@@ -2260,6 +2263,24 @@ dlvsym(void *handle, const char *name, const char *version)
 	    SYMLOOK_DLSYM);
 }
 
+int
+_rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
+{
+    const Obj_Entry *obj;
+    int lockstate;
+
+    lockstate = rlock_acquire(rtld_bind_lock);
+    obj = obj_from_addr(addr);
+    if (obj == NULL) {
+        _rtld_error("No shared object contains address");
+	rlock_release(rtld_bind_lock, lockstate);
+        return (0);
+    }
+    rtld_fill_dl_phdr_info(obj, phdr_info);
+    rlock_release(rtld_bind_lock, lockstate);
+    return (1);
+}
+
 int
 dladdr(const void *addr, Dl_info *info)
 {
@@ -2362,6 +2383,21 @@ dlinfo(void *handle, int request, void *p)
     return (error);
 }
 
+static void
+rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
+{
+
+	phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
+	phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
+	    STAILQ_FIRST(&obj->names)->name : obj->path;
+	phdr_info->dlpi_phdr = obj->phdr;
+	phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
+	phdr_info->dlpi_tls_modid = obj->tlsindex;
+	phdr_info->dlpi_tls_data = obj->tlsinit;
+	phdr_info->dlpi_adds = obj_loads;
+	phdr_info->dlpi_subs = obj_loads - obj_count;
+}
+
 int
 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
 {
@@ -2375,16 +2411,7 @@ dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
     error = 0;
 
     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
-	phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
-	phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
-	    STAILQ_FIRST(&obj->names)->name : obj->path;
-	phdr_info.dlpi_phdr = obj->phdr;
-	phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
-	phdr_info.dlpi_tls_modid = obj->tlsindex;
-	phdr_info.dlpi_tls_data = obj->tlsinit;
-	phdr_info.dlpi_adds = obj_loads;
-	phdr_info.dlpi_subs = obj_loads - obj_count;
-
+	rtld_fill_dl_phdr_info(obj, &phdr_info);
 	if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
 		break;
 
diff --git a/sys/sys/link_elf.h b/sys/sys/link_elf.h
index 98840a51988..93fe1de1964 100644
--- a/sys/sys/link_elf.h
+++ b/sys/sys/link_elf.h
@@ -92,6 +92,7 @@ __BEGIN_DECLS
 
 typedef int (*__dl_iterate_hdr_callback)(struct dl_phdr_info *, size_t, void *);
 extern int dl_iterate_phdr(__dl_iterate_hdr_callback, void *);
+int _rtld_addr_phdr(const void *, struct dl_phdr_info *);
 
 __END_DECLS
 

From ea246b6369b9c4311cbaeaf69610cee4c434a295 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 23 Aug 2010 15:38:02 +0000
Subject: [PATCH 0179/1624] On shared object unload, in __cxa_finalize, call
 and clear all installed atexit and __cxa_atexit handlers that are either
 installed by unloaded dso, or points to the functions provided by the dso.

Use _rtld_addr_phdr to locate segment information from the address of
private variable belonging to the dso, supplied by crtstuff.c. Provide
utility function __elf_phdr_match_addr to do the match of address against
dso executable segment.

Call back into libthr from __cxa_finalize using weak
__pthread_cxa_finalize symbol to remove any atfork handler which
function points into unloaded object.

The rtld needs private __pthread_cxa_finalize symbol to not require
resolution of the weak undefined symbol at initialization time. This
cannot work, since rtld is relocated before sym_zero is set up.

Idea by:	kan
Reviewed by:	kan (previous version)
MFC after:	3 weeks
---
 lib/libc/gen/Makefile.inc       |  2 +-
 lib/libc/gen/Symbol.map         |  1 +
 lib/libc/gen/elf_utils.c        | 47 +++++++++++++++++++++++++++++++++
 lib/libc/include/libc_private.h |  2 ++
 lib/libc/stdlib/atexit.c        | 23 +++++++++++++---
 lib/libthr/pthread.map          |  1 +
 lib/libthr/thread/thr_fork.c    | 22 +++++++++++++++
 lib/libthr/thread/thr_private.h |  3 +++
 libexec/rtld-elf/rtld.c         | 12 +++++++++
 9 files changed, 109 insertions(+), 4 deletions(-)
 create mode 100644 lib/libc/gen/elf_utils.c

diff --git a/lib/libc/gen/Makefile.inc b/lib/libc/gen/Makefile.inc
index 2c3d3920dfe..5056392ccd2 100644
--- a/lib/libc/gen/Makefile.inc
+++ b/lib/libc/gen/Makefile.inc
@@ -10,7 +10,7 @@ SRCS+=  __getosreldate.c __xuname.c \
 	alarm.c arc4random.c assert.c aux.c basename.c check_utility_compat.c \
 	clock.c closedir.c confstr.c \
 	crypt.c ctermid.c daemon.c devname.c dirname.c disklabel.c \
-	dlfcn.c drand48.c erand48.c err.c errlst.c errno.c \
+	dlfcn.c drand48.c elf_utils.c erand48.c err.c errlst.c errno.c \
 	exec.c fdevname.c feature_present.c fmtcheck.c fmtmsg.c fnmatch.c \
 	fpclassify.c frexp.c fstab.c ftok.c fts.c fts-compat.c ftw.c \
 	getbootfile.c getbsize.c \
diff --git a/lib/libc/gen/Symbol.map b/lib/libc/gen/Symbol.map
index c4f21b559d7..6bd3140be0a 100644
--- a/lib/libc/gen/Symbol.map
+++ b/lib/libc/gen/Symbol.map
@@ -451,6 +451,7 @@ FBSDprivate_1.0 {
 	_rtld_atfork_post;
 	_rtld_error;		/* for private use */
 	_rtld_thread_init;	/* for private use */
+	__elf_phdr_match_addr;
 	_err;
 	_warn;
 	__fmtcheck;
diff --git a/lib/libc/gen/elf_utils.c b/lib/libc/gen/elf_utils.c
new file mode 100644
index 00000000000..9ee5f419607
--- /dev/null
+++ b/lib/libc/gen/elf_utils.c
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2010 Konstantin Belousov 
+ * 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. Neither the name of the author nor the names of any co-contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ *
+ * $FreeBSD$
+ */
+
+#include 
+
+int
+__elf_phdr_match_addr(struct dl_phdr_info *phdr_info, void *addr)
+{
+	const Elf_Phdr *ph;
+	int i;
+
+	for (i = 0; i < phdr_info->dlpi_phnum; i++) {
+		ph = &phdr_info->dlpi_phdr[i];
+		if (ph->p_type != PT_LOAD || (ph->p_flags & PF_X) == 0)
+			continue;
+		if (phdr_info->dlpi_addr + ph->p_vaddr <= (uintptr_t)addr &&
+		    (uintptr_t)addr + sizeof(addr) < phdr_info->dlpi_addr +
+		    ph->p_vaddr + ph->p_memsz)
+			break;
+	}
+	return (i != phdr_info->dlpi_phnum);
+}
diff --git a/lib/libc/include/libc_private.h b/lib/libc/include/libc_private.h
index 570441b1f6f..c5f6eb3f469 100644
--- a/lib/libc/include/libc_private.h
+++ b/lib/libc/include/libc_private.h
@@ -214,5 +214,7 @@ extern int	__sys_fcntl(int, int, ...);
 int _execvpe(const char *, char * const *, char * const *);
 
 int _elf_aux_info(int aux, void *buf, int buflen);
+struct dl_phdr_info;
+int __elf_phdr_match_addr(struct dl_phdr_info *, void *);
 
 #endif /* _LIBC_PRIVATE_H_ */
diff --git a/lib/libc/stdlib/atexit.c b/lib/libc/stdlib/atexit.c
index a7a9a32e1dd..97cf2344659 100644
--- a/lib/libc/stdlib/atexit.c
+++ b/lib/libc/stdlib/atexit.c
@@ -37,6 +37,7 @@ static char sccsid[] = "@(#)atexit.c	8.2 (Berkeley) 7/3/94";
 __FBSDID("$FreeBSD$");
 
 #include "namespace.h"
+#include 
 #include 
 #include 
 #include 
@@ -147,6 +148,9 @@ __cxa_atexit(void (*func)(void *), void *arg, void *dso)
 	return (error);
 }
 
+#pragma weak __pthread_cxa_finalize
+void __pthread_cxa_finalize(const struct dl_phdr_info *);
+
 /*
  * Call all handlers registered with __cxa_atexit for the shared
  * object owning 'dso'.  Note: if 'dso' is NULL, then all remaining
@@ -155,18 +159,28 @@ __cxa_atexit(void (*func)(void *), void *arg, void *dso)
 void
 __cxa_finalize(void *dso)
 {
+	struct dl_phdr_info phdr_info;
 	struct atexit *p;
 	struct atexit_fn fn;
-	int n;
+	int n, has_phdr;
+
+	if (dso != NULL)
+		has_phdr = _rtld_addr_phdr(dso, &phdr_info);
+	else
+		has_phdr = 0;
 
 	_MUTEX_LOCK(&atexit_mutex);
 	for (p = __atexit; p; p = p->next) {
 		for (n = p->ind; --n >= 0;) {
 			if (p->fns[n].fn_type == ATEXIT_FN_EMPTY)
 				continue; /* already been called */
-			if (dso != NULL && dso != p->fns[n].fn_dso)
-				continue; /* wrong DSO */
 			fn = p->fns[n];
+			if (dso != NULL && dso != fn.fn_dso) {
+				/* wrong DSO ? */
+				if (!has_phdr || !__elf_phdr_match_addr(
+				    &phdr_info, fn.fn_ptr.cxa_func))
+					continue;
+			}
 			/*
 			  Mark entry to indicate that this particular handler
 			  has already been called.
@@ -185,4 +199,7 @@ __cxa_finalize(void *dso)
 	_MUTEX_UNLOCK(&atexit_mutex);
 	if (dso == NULL)
 		_MUTEX_DESTROY(&atexit_mutex);
+
+	if (&__pthread_cxa_finalize != NULL)
+		__pthread_cxa_finalize(&phdr_info);
 }
diff --git a/lib/libthr/pthread.map b/lib/libthr/pthread.map
index 6460bec514a..8457996825b 100644
--- a/lib/libthr/pthread.map
+++ b/lib/libthr/pthread.map
@@ -192,6 +192,7 @@ FBSDprivate_1.0 {
 	__poll;
 	__pthread_cond_timedwait;
 	__pthread_cond_wait;
+	__pthread_cxa_finalize;
 	__pthread_mutex_init;
 	__pthread_mutex_lock;
 	__pthread_mutex_timedlock;
diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index 529f38f7c35..b1c221eca83 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -59,6 +59,7 @@
 
 #include "namespace.h"
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -94,6 +95,27 @@ _pthread_atfork(void (*prepare)(void), void (*parent)(void),
 	return (0);
 }
 
+void
+__pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
+{
+	struct pthread *curthread;
+	struct pthread_atfork *af, *af1;
+
+	_thr_check_init();
+
+	curthread = _get_curthread();
+	THR_UMUTEX_LOCK(curthread, &_thr_atfork_lock);
+	TAILQ_FOREACH_SAFE(af, &_thr_atfork_list, qe, af1) {
+		if (__elf_phdr_match_addr(phdr_info, af->prepare) ||
+		    __elf_phdr_match_addr(phdr_info, af->parent) ||
+		    __elf_phdr_match_addr(phdr_info, af->child)) {
+			TAILQ_REMOVE(&_thr_atfork_list, af, qe);
+			free(af);
+		}
+	}
+	THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
+}
+
 __weak_reference(_fork, fork);
 
 pid_t _fork(void);
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index 465f725cd42..f0c3aa0ec9a 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -740,6 +740,9 @@ _thr_check_init(void)
 		_libpthread_init(NULL);
 }
 
+struct dl_phdr_info;
+void __pthread_cxa_finalize(struct dl_phdr_info *phdr_info);
+
 __END_DECLS
 
 #endif  /* !_THR_PRIVATE_H */
diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
index 77eeafbef39..dc5cdca2ee9 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -3692,6 +3692,10 @@ fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
     return NULL;
 }
 
+/*
+ * Overrides for libc_pic-provided functions.
+ */
+
 int
 __getosreldate(void)
 {
@@ -3711,3 +3715,11 @@ __getosreldate(void)
 		osreldate = osrel;
 	return (osreldate);
 }
+
+/*
+ * No unresolved symbols for rtld.
+ */
+void
+__pthread_cxa_finalize(struct dl_phdr_info *a)
+{
+}

From de563149f58a4cdad8a5493b7d9a6a0ac415d1b1 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Mon, 23 Aug 2010 16:47:29 +0000
Subject: [PATCH 0180/1624] Add powerpc64 to the list of architectures with
 real atomic operations.

Submitted by:	imp
---
 cddl/lib/libzpool/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cddl/lib/libzpool/Makefile b/cddl/lib/libzpool/Makefile
index 045e13d71db..6d8d59f8211 100644
--- a/cddl/lib/libzpool/Makefile
+++ b/cddl/lib/libzpool/Makefile
@@ -11,7 +11,7 @@
 # LIST_SRCS
 .PATH: ${.CURDIR}/../../../sys/cddl/contrib/opensolaris/uts/common/os
 # ATOMIC_SRCS
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "ia64" || ${MACHINE_ARCH} == "powerpc64"
 .PATH: ${.CURDIR}/../../../sys/cddl/contrib/opensolaris/common/atomic/${MACHINE_ARCH}
 ATOMIC_SRCS=	opensolaris_atomic.S
 .else

From ac681091791454cb975c64d553904a95cdff65da Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Mon, 23 Aug 2010 18:51:31 +0000
Subject: [PATCH 0181/1624] Move xl_reset() to xl_init_locked(). This will make
 driver initialize controller from a known good state. Previously driver used
 to issue controller reset while TX/RX DMA are in progress. I guess resetting
 controller in active TX/RX DMA cycle is to ensure stopping I/Os in
 xl_shutdown(). I remember some buggy controllers didn't respond with stop
 command if controller is under high network load at the time of shutdown so
 resetting controller was the only safe way to stop the I/Os. However, from my
 experiments, controller always responded with stop command under high network
 load so I think it's okay to remove the xl_reset() in device_shutdown
 handler. Resetting controller also will clear configured RX filter which in
 turn will make WOL support hard because driver have to reprogram RX filter in
 WOL handler as well as setting station address.

---
 sys/dev/xl/if_xl.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/sys/dev/xl/if_xl.c b/sys/dev/xl/if_xl.c
index 6623551dcaa..d8ea2c47e89 100644
--- a/sys/dev/xl/if_xl.c
+++ b/sys/dev/xl/if_xl.c
@@ -1635,7 +1635,6 @@ xl_detach(device_t dev)
 	/* These should only be active if attach succeeded */
 	if (device_is_attached(dev)) {
 		XL_LOCK(sc);
-		xl_reset(sc);
 		xl_stop(sc);
 		XL_UNLOCK(sc);
 		taskqueue_drain(taskqueue_swi, &sc->xl_task);
@@ -2246,7 +2245,6 @@ xl_intr(void *arg)
 		}
 
 		if (status & XL_STAT_ADFAIL) {
-			xl_reset(sc);
 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			xl_init_locked(sc);
 		}
@@ -2318,7 +2316,6 @@ xl_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
 			}
 
 			if (status & XL_STAT_ADFAIL) {
-				xl_reset(sc);
 				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 				xl_init_locked(sc);
 			}
@@ -2754,6 +2751,9 @@ xl_init_locked(struct xl_softc *sc)
 	 */
 	xl_stop(sc);
 
+	/* Reset the chip to a known state. */
+	xl_reset(sc);
+
 	if (sc->xl_miibus == NULL) {
 		CSR_WRITE_2(sc, XL_COMMAND, XL_CMD_RX_RESET);
 		xl_wait(sc);
@@ -3236,7 +3236,6 @@ xl_watchdog(struct xl_softc *sc)
 		device_printf(sc->xl_dev,
 		    "no carrier - transceiver cable problem?\n");
 
-	xl_reset(sc);
 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	xl_init_locked(sc);
 
@@ -3335,7 +3334,6 @@ xl_shutdown(device_t dev)
 	sc = device_get_softc(dev);
 
 	XL_LOCK(sc);
-	xl_reset(sc);
 	xl_stop(sc);
 	XL_UNLOCK(sc);
 
@@ -3367,7 +3365,6 @@ xl_resume(device_t dev)
 
 	XL_LOCK(sc);
 
-	xl_reset(sc);
 	if (ifp->if_flags & IFF_UP) {
 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		xl_init_locked(sc);

From 9ae11bbaa6e055710030e98f5bbccd48e4520175 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Mon, 23 Aug 2010 19:18:50 +0000
Subject: [PATCH 0182/1624] Implement basic WOL support. Note, not all xl(4)
 controllers support WOL. Some controllers require additional 3-wire auxiliary
 remote wakeup connector to draw power. More recent xl(4) controllers may not
 need the wakeup connector though.

---
 sys/dev/xl/if_xl.c    | 72 +++++++++++++++++++++++++++++++++++++------
 sys/dev/xl/if_xlreg.h | 18 +++++++++++
 2 files changed, 80 insertions(+), 10 deletions(-)

diff --git a/sys/dev/xl/if_xl.c b/sys/dev/xl/if_xl.c
index d8ea2c47e89..3f0e1d751ec 100644
--- a/sys/dev/xl/if_xl.c
+++ b/sys/dev/xl/if_xl.c
@@ -246,6 +246,7 @@ static int xl_watchdog(struct xl_softc *);
 static int xl_shutdown(device_t);
 static int xl_suspend(device_t);
 static int xl_resume(device_t);
+static void xl_setwol(struct xl_softc *);
 
 #ifdef DEVICE_POLLING
 static int xl_poll(struct ifnet *ifp, enum poll_cmd cmd, int count);
@@ -1145,10 +1146,10 @@ static int
 xl_attach(device_t dev)
 {
 	u_char			eaddr[ETHER_ADDR_LEN];
-	u_int16_t		xcvr[2];
+	u_int16_t		sinfo2, xcvr[2];
 	struct xl_softc		*sc;
 	struct ifnet		*ifp;
-	int			media;
+	int			media, pmcap;
 	int			unit, error = 0, rid, res;
 	uint16_t		did;
 
@@ -1405,6 +1406,18 @@ xl_attach(device_t dev)
 	else
 		sc->xl_type = XL_TYPE_90X;
 
+	/* Check availability of WOL. */
+	if ((sc->xl_caps & XL_CAPS_PWRMGMT) != 0 &&
+	    pci_find_extcap(dev, PCIY_PMG, &pmcap) == 0) {
+		sc->xl_pmcap = pmcap;
+		sc->xl_flags |= XL_FLAG_WOL;
+		sinfo2 = 0;
+		xl_read_eeprom(sc, (caddr_t)&sinfo2, XL_EE_SOFTINFO2, 1, 0);
+		if ((sinfo2 & XL_SINFO2_AUX_WOL_CON) == 0 && bootverbose)
+			device_printf(dev,
+			    "No auxiliary remote wakeup connector!\n");
+	}
+
 	/* Set the TX start threshold for best performance. */
 	sc->xl_tx_thresh = XL_MIN_FRAMELEN;
 
@@ -1419,6 +1432,8 @@ xl_attach(device_t dev)
 		ifp->if_capabilities |= IFCAP_HWCSUM;
 #endif
 	}
+	if ((sc->xl_flags & XL_FLAG_WOL) != 0)
+		ifp->if_capabilities |= IFCAP_WOL_MAGIC;
 	ifp->if_capenable = ifp->if_capabilities;
 #ifdef DEVICE_POLLING
 	ifp->if_capabilities |= IFCAP_POLLING;
@@ -2765,6 +2780,15 @@ xl_init_locked(struct xl_softc *sc)
 	if (sc->xl_miibus != NULL)
 		mii = device_get_softc(sc->xl_miibus);
 
+	/*
+	 * Clear WOL status and disable all WOL feature as WOL
+	 * would interfere Rx operation under normal environments.
+	 */
+	if ((sc->xl_flags & XL_FLAG_WOL) != 0) {
+		XL_SEL_WIN(7);
+		CSR_READ_2(sc, XL_W7_BM_PME);
+		CSR_WRITE_2(sc, XL_W7_BM_PME, 0);
+	}
 	/* Init our MAC address */
 	XL_SEL_WIN(2);
 	for (i = 0; i < ETHER_ADDR_LEN; i++) {
@@ -3187,6 +3211,9 @@ xl_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 		if ((mask & IFCAP_RXCSUM) != 0 &&
 		    (ifp->if_capabilities & IFCAP_RXCSUM) != 0)
 			ifp->if_capenable ^= IFCAP_RXCSUM;
+		if ((mask & IFCAP_WOL_MAGIC) != 0 &&
+		    (ifp->if_capabilities & IFCAP_WOL_MAGIC) != 0)
+			ifp->if_capenable ^= IFCAP_WOL_MAGIC;
 		XL_UNLOCK(sc);
 		break;
 	default:
@@ -3329,15 +3356,8 @@ xl_stop(struct xl_softc *sc)
 static int
 xl_shutdown(device_t dev)
 {
-	struct xl_softc		*sc;
 
-	sc = device_get_softc(dev);
-
-	XL_LOCK(sc);
-	xl_stop(sc);
-	XL_UNLOCK(sc);
-
-	return (0);
+	return (xl_suspend(dev));
 }
 
 static int
@@ -3349,6 +3369,7 @@ xl_suspend(device_t dev)
 
 	XL_LOCK(sc);
 	xl_stop(sc);
+	xl_setwol(sc);
 	XL_UNLOCK(sc);
 
 	return (0);
@@ -3374,3 +3395,34 @@ xl_resume(device_t dev)
 
 	return (0);
 }
+
+static void
+xl_setwol(struct xl_softc *sc)
+{
+	struct ifnet		*ifp;
+	u_int16_t		cfg, pmstat;
+
+	if ((sc->xl_flags & XL_FLAG_WOL) == 0)
+		return;
+
+	ifp = sc->xl_ifp;
+	XL_SEL_WIN(7);
+	/* Clear any pending PME events. */
+	CSR_READ_2(sc, XL_W7_BM_PME);
+	cfg = 0;
+	if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
+		cfg |= XL_BM_PME_MAGIC;
+	CSR_WRITE_2(sc, XL_W7_BM_PME, cfg);
+	/* Enable RX. */
+	if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
+		CSR_WRITE_2(sc, XL_COMMAND, XL_CMD_RX_ENABLE);
+	/* Request PME. */
+	pmstat = pci_read_config(sc->xl_dev,
+	    sc->xl_pmcap + PCIR_POWER_STATUS, 2);
+	if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
+		pmstat |= PCIM_PSTAT_PMEENABLE;
+	else
+		pmstat &= ~PCIM_PSTAT_PMEENABLE;
+	pci_write_config(sc->xl_dev,
+	    sc->xl_pmcap + PCIR_POWER_STATUS, pmstat, 2);
+}
diff --git a/sys/dev/xl/if_xlreg.h b/sys/dev/xl/if_xlreg.h
index 538661410d5..2685c44a592 100644
--- a/sys/dev/xl/if_xlreg.h
+++ b/sys/dev/xl/if_xlreg.h
@@ -81,6 +81,17 @@
 #define XL_CAPS_100MBPS		0x1000
 #define XL_CAPS_PWRMGMT		0x2000
 
+/*
+ * Bits in the software information 2 word
+ */
+#define	XL_SINFO2_FIXED_BCAST_RX_BUG	0x0002
+#define	XL_SINFO2_FIXED_ENDEC_LOOP_BUG	0x0004
+#define	XL_SINFO2_AUX_WOL_CON		0x0008
+#define	XL_SINFO2_PME_PULSED		0x0010
+#define	XL_SINFO2_FIXED_MWI_BUG		0x0020
+#define	XL_SINFO2_WOL_AFTER_PWR_LOSS	0x0040
+#define	XL_SINFO2_AUTO_RST_TO_D0	0x0080
+
 #define XL_PACKET_SIZE 1540
 #define XL_MAX_FRAMELEN	(ETHER_MAX_LEN + ETHER_VLAN_ENCAP_LEN)
 
@@ -408,7 +419,12 @@
 #define XL_W7_BM_LEN		0x06
 #define XL_W7_BM_STATUS		0x0B
 #define XL_W7_BM_TIMEr		0x0A
+#define XL_W7_BM_PME		0x0C
 
+#define	XL_BM_PME_WAKE		0x0001
+#define	XL_BM_PME_MAGIC		0x0002
+#define	XL_BM_PME_LINKCHG	0x0004
+#define	XL_BM_PME_WAKETIMER	0x0008
 /*
  * bus master control registers
  */
@@ -577,6 +593,7 @@ struct xl_mii_frame {
 #define XL_FLAG_NO_XCVR_PWR		0x0080
 #define XL_FLAG_USE_MMIO		0x0100
 #define	XL_FLAG_NO_MMIO			0x0200
+#define	XL_FLAG_WOL			0x0400
 
 #define XL_NO_XCVR_PWR_MAGICBITS	0x0900
 
@@ -599,6 +616,7 @@ struct xl_softc {
 	u_int16_t		xl_caps;
 	u_int8_t		xl_stats_no_timeout;
 	u_int16_t		xl_tx_thresh;
+	int			xl_pmcap;
 	int			xl_if_flags;
 	struct xl_list_data	xl_ldata;
 	struct xl_chain_data	xl_cdata;

From 820b53e152b542f5c6b4bd1f3c7f1b7ae1e9a7c7 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Mon, 23 Aug 2010 21:40:03 +0000
Subject: [PATCH 0183/1624] Fix a possible unaligned access to savebyte array.

PR:	kern/122195
---
 sys/dev/ed/if_ed.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/sys/dev/ed/if_ed.c b/sys/dev/ed/if_ed.c
index 839e2a52cc9..6213ce763d7 100644
--- a/sys/dev/ed/if_ed.c
+++ b/sys/dev/ed/if_ed.c
@@ -1476,9 +1476,12 @@ ed_pio_write_mbufs(struct ed_softc *sc, struct mbuf *m, bus_size_t dst)
 		}
 	} else {
 		/* NE2000s are a pain */
-		unsigned char *data;
+		uint8_t *data;
 		int len, wantbyte;
-		unsigned char savebyte[2];
+		union {
+			uint16_t w;
+			uint8_t b[2];
+		} saveword;
 
 		wantbyte = 0;
 
@@ -1488,9 +1491,9 @@ ed_pio_write_mbufs(struct ed_softc *sc, struct mbuf *m, bus_size_t dst)
 				data = mtod(m, caddr_t);
 				/* finish the last word */
 				if (wantbyte) {
-					savebyte[1] = *data;
+					saveword.b[1] = *data;
 					ed_asic_outw(sc, ED_NOVELL_DATA,
-						     *(u_short *)savebyte);
+					    saveword.w);
 					data++;
 					len--;
 					wantbyte = 0;
@@ -1504,7 +1507,7 @@ ed_pio_write_mbufs(struct ed_softc *sc, struct mbuf *m, bus_size_t dst)
 				}
 				/* save last byte, if necessary */
 				if (len == 1) {
-					savebyte[0] = *data;
+					saveword.b[0] = *data;
 					wantbyte = 1;
 				}
 			}
@@ -1512,7 +1515,7 @@ ed_pio_write_mbufs(struct ed_softc *sc, struct mbuf *m, bus_size_t dst)
 		}
 		/* spit last byte */
 		if (wantbyte)
-			ed_asic_outw(sc, ED_NOVELL_DATA, *(u_short *)savebyte);
+			ed_asic_outw(sc, ED_NOVELL_DATA, saveword.w);
 	}
 
 	/*

From 222447d5e0b0966ae6350312718c2c783c3ce88b Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Mon, 23 Aug 2010 22:04:30 +0000
Subject: [PATCH 0184/1624] Use real atomic operations for sparc64.

MFC after:	1 week
---
 cddl/lib/libzpool/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cddl/lib/libzpool/Makefile b/cddl/lib/libzpool/Makefile
index 6d8d59f8211..2199a014ae1 100644
--- a/cddl/lib/libzpool/Makefile
+++ b/cddl/lib/libzpool/Makefile
@@ -11,7 +11,7 @@
 # LIST_SRCS
 .PATH: ${.CURDIR}/../../../sys/cddl/contrib/opensolaris/uts/common/os
 # ATOMIC_SRCS
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "ia64" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "ia64" || ${MACHINE_ARCH} == "sparc64" || ${MACHINE_ARCH} == "powerpc64"
 .PATH: ${.CURDIR}/../../../sys/cddl/contrib/opensolaris/common/atomic/${MACHINE_ARCH}
 ATOMIC_SRCS=	opensolaris_atomic.S
 .else

From 25faff346c8453b8248f99c7cff71708262faa37 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 23 Aug 2010 22:24:11 +0000
Subject: [PATCH 0185/1624] MFtbemd:

Prefer MACHNE_CPUARCH to MACHINE_ARCH in most contexts where you want
to test of all the CPUs of a given family conform.
---
 Makefile.inc1                       |  4 ++--
 cddl/lib/libdtrace/Makefile         |  4 ++--
 cddl/lib/libzpool/Makefile          |  2 +-
 gnu/lib/csu/Makefile                |  6 +++---
 gnu/lib/libgomp/Makefile            |  7 ++++---
 gnu/lib/libstdc++/Makefile          | 12 ++++++------
 gnu/usr.bin/binutils/gdb/Makefile   | 19 +++++-------------
 gnu/usr.bin/gdb/Makefile            |  3 +--
 gnu/usr.bin/gdb/gdbserver/Makefile  |  5 ++---
 include/Makefile                    |  4 ++--
 lib/Makefile                        | 20 ++++++++++++-------
 lib/libc/Makefile                   | 20 +++++++++----------
 lib/libc/compat-43/Makefile.inc     |  2 +-
 lib/libc/gen/Makefile.inc           |  6 +++---
 lib/libc/locale/Makefile.inc        |  2 +-
 lib/libc/quad/Makefile.inc          |  4 ++--
 lib/libc/softfloat/Makefile.inc     |  4 ++--
 lib/libc/stdlib/Makefile.inc        |  4 ++--
 lib/libc/string/Makefile.inc        |  6 +++---
 lib/libc/sys/Makefile.inc           |  6 +++---
 lib/libc_r/sys/Makefile.inc         |  2 +-
 lib/libdisk/Makefile                |  2 +-
 lib/libkvm/Makefile                 |  7 ++++---
 lib/libpmc/Makefile                 |  4 ++--
 lib/libstand/Makefile               | 26 ++++++++++++-------------
 lib/libthread_db/Makefile           |  2 +-
 lib/msun/Makefile                   |  2 +-
 libexec/rtld-elf/Makefile           | 14 +++++++-------
 libexec/rtld-elf/amd64/Makefile.inc |  4 +++-
 libexec/rtld-elf/i386/Makefile.inc  |  4 +++-
 rescue/rescue/Makefile              |  8 ++++----
 sbin/atm/atmconfig/Makefile         |  3 ++-
 sbin/bsdlabel/Makefile              |  2 +-
 sbin/camcontrol/Makefile            |  3 ++-
 sbin/gbde/Makefile                  |  2 +-
 sbin/newfs_msdos/Makefile           |  3 ++-
 sbin/sunlabel/Makefile              |  2 +-
 secure/lib/libcrypto/Makefile       | 30 ++++++++++++++---------------
 share/man/man4/Makefile             |  4 ++--
 share/man/man5/Makefile             |  2 +-
 share/mk/bsd.lib.mk                 |  2 +-
 share/mk/bsd.sys.mk                 |  5 +++--
 sys/boot/arm/ixp425/boot2/Makefile  |  2 +-
 sys/conf/kern.post.mk               |  4 ++--
 sys/conf/kern.pre.mk                |  2 +-
 usr.bin/ldd/Makefile                |  2 +-
 usr.bin/truss/Makefile              |  6 +++---
 usr.sbin/ac/Makefile                |  2 +-
 usr.sbin/amd/Makefile.inc           |  2 +-
 usr.sbin/apm/Makefile               |  2 +-
 usr.sbin/kldxref/Makefile           |  4 ++--
 usr.sbin/sade/Makefile              |  2 +-
 usr.sbin/sysinstall/Makefile        |  2 +-
 usr.sbin/tcpdump/tcpdump/Makefile   |  2 +-
 54 files changed, 155 insertions(+), 150 deletions(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index 28144a6d064..36c1a34ba2d 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -1131,8 +1131,8 @@ _prereq_libs= gnu/lib/libssp/libssp_nonshared gnu/lib/libgcc
 # all shared libraries for ELF.
 #
 _startup_libs=	gnu/lib/csu
-.if exists(${.CURDIR}/lib/csu/${MACHINE_ARCH}-elf)
-_startup_libs+=	lib/csu/${MACHINE_ARCH}-elf
+.if exists(${.CURDIR}/lib/csu/${MACHINE_CPUARCH}-elf)
+_startup_libs+=	lib/csu/${MACHINE_CPUARCH}-elf
 .elif exists(${.CURDIR}/lib/csu/${MACHINE_CPUARCH}-elf)
 _startup_libs+=	lib/csu/${MACHINE_CPUARCH}-elf
 .elif exists(${.CURDIR}/lib/csu/${MACHINE_ARCH})
diff --git a/cddl/lib/libdtrace/Makefile b/cddl/lib/libdtrace/Makefile
index 2cc9564f6b3..9a107439c20 100644
--- a/cddl/lib/libdtrace/Makefile
+++ b/cddl/lib/libdtrace/Makefile
@@ -63,11 +63,11 @@ CFLAGS+=	-I${.OBJDIR} -I${.CURDIR} \
 
 #CFLAGS+=	-DYYDEBUG
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-I${OPENSOLARIS_SYS_DISTDIR}/uts/intel -DDIS_MEM
 .PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/i386
 .PATH:		${.CURDIR}/../../../sys/cddl/dev/dtrace/${MACHINE_ARCH}
-.elif ${MACHINE_ARCH} == "sparc64"
+.elif ${MACHINE_CPUARCH} == "sparc64"
 CFLAGS+=	-I${OPENSOLARIS_SYS_DISTDIR}/uts/sparc
 .PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/sparc
 .else
diff --git a/cddl/lib/libzpool/Makefile b/cddl/lib/libzpool/Makefile
index 2199a014ae1..7a0ce3cb98e 100644
--- a/cddl/lib/libzpool/Makefile
+++ b/cddl/lib/libzpool/Makefile
@@ -51,7 +51,7 @@ CFLAGS+=	-I${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libnvpair
 CFLAGS+=	-DWANTS_MUTEX_OWNED
 CFLAGS+=	-I${.CURDIR}/../../../lib/libpthread/thread
 CFLAGS+=	-I${.CURDIR}/../../../lib/libpthread/sys
-CFLAGS+=	-I${.CURDIR}/../../../lib/libthr/arch/${MACHINE_ARCH}/include
+CFLAGS+=	-I${.CURDIR}/../../../lib/libthr/arch/${MACHINE_CPUARCH}/include
 
 DPADD=		${LIBPTHREAD} ${LIBZ}
 LDADD=		-lpthread -lz
diff --git a/gnu/lib/csu/Makefile b/gnu/lib/csu/Makefile
index b7dcb600082..4999d06a578 100644
--- a/gnu/lib/csu/Makefile
+++ b/gnu/lib/csu/Makefile
@@ -24,18 +24,18 @@ CFLAGS+=	-I${GCCLIB}/include -I${GCCDIR}/config -I${GCCDIR} -I. \
 CRTS_CFLAGS=	-DCRTSTUFFS_O -DSHARED ${PICFLAG}
 MKDEP=		-DCRT_BEGIN
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 BEGINSRC=	crtbegin.asm
 ENDSRC=		crtend.asm
 CFLAGS+=	-x assembler-with-cpp	# Ugly hack
 CFLAGS+=	-include osreldate.h
 .undef SRCS				# hack for 'make depend'
 .endif
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_CPUARCH} == "powerpc"
 TGTOBJS=	crtsavres.o
 SRCS+=		crtsavres.asm
 .endif
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 TGTOBJS=	crtfastmath.o
 SRCS+=		crtfastmath.c
 .endif
diff --git a/gnu/lib/libgomp/Makefile b/gnu/lib/libgomp/Makefile
index 097451673b1..da28f8999fd 100644
--- a/gnu/lib/libgomp/Makefile
+++ b/gnu/lib/libgomp/Makefile
@@ -23,9 +23,10 @@ CFLAGS+= -I${.CURDIR} -I. -I${SRCDIR} -I${SRCDIR}/config/posix
 VERSION_MAP=	${SRCDIR}/libgomp.map
 
 # Target-specific OpenMP configuration
-.if ${MACHINE_ARCH} == arm || ${MACHINE_ARCH} == i386 || \
-    ${MACHINE_ARCH} == powerpc || \
-    (${MACHINE_ARCH} == mips && (!defined(TARGET_ABI) || ${TARGET_ABI} != "n64"))
+.if ${MACHINE_CPUARCH} == arm || ${MACHINE_CPUARCH} == i386 || \
+    ${MACHINE_CPUARCH} == powerpc || \
+    (${MACHINE_CPUARCH} == mips && \
+	(!defined(TARGET_ABI) || ${TARGET_ABI} != "n64"))
 OMP_LOCK_ALIGN	=	4
 OMP_LOCK_KIND=		4
 OMP_LOCK_SIZE=		4
diff --git a/gnu/lib/libstdc++/Makefile b/gnu/lib/libstdc++/Makefile
index 9fcc5e9edf6..e0a7bb214ed 100644
--- a/gnu/lib/libstdc++/Makefile
+++ b/gnu/lib/libstdc++/Makefile
@@ -14,7 +14,7 @@ LIB=		stdc++
 SHLIB_MAJOR=	6
 
 CFLAGS+=	-DIN_GLIBCPP_V3 -DHAVE_CONFIG_H
-.if ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "arm"
 CFLAGS+=	-D_GLIBCXX_SJLJ_EXCEPTIONS=1
 .endif
 CFLAGS+=	-I${.CURDIR} -I${SUPDIR} -I${GCCDIR} -I${SRCDIR}/include
@@ -67,14 +67,14 @@ SRCS+=	del_op.cc del_opnt.cc del_opv.cc del_opvnt.cc eh_alloc.cc eh_arm.cc \
 SRCS+=	cp-demangle.c
 
 # MD headers location
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 MARCHDIR=	sparc
-.elif ${MACHINE_ARCH} == "i386" && ${MACHINE_CPU} != 'i386'
+.elif ${MACHINE_CPUARCH} == "i386" && ${MACHINE_CPU} != 'i386'
 MARCHDIR=	i486
-.elif ${MACHINE_ARCH} == "amd64"
+.elif ${MACHINE_CPUARCH} == "amd64"
 MARCHDIR=	i486
 .else
-MARCHDIR=	${MACHINE_ARCH}
+MARCHDIR=	${MACHINE_CPUARCH}
 .endif
 
 .if exists(${SRCDIR}/config/cpu/${MARCHDIR}/atomicity.h)
@@ -83,7 +83,7 @@ ATOMICITY_H=	${SRCDIR}/config/cpu/${MARCHDIR}/atomicity.h
 ATOMICITY_H=	${SRCDIR}/config/cpu/generic/atomicity_mutex/atomicity.h
 .endif
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 .if exists(${SRCDIR}/config/cpu/generic/atomicity_builtins/atomicity.h)
 ATOMICITY_H=	${SRCDIR}/config/cpu/generic/atomicity_builtins/atomicity.h
 .endif
diff --git a/gnu/usr.bin/binutils/gdb/Makefile b/gnu/usr.bin/binutils/gdb/Makefile
index 6e52616ad30..f51d9e35704 100644
--- a/gnu/usr.bin/binutils/gdb/Makefile
+++ b/gnu/usr.bin/binutils/gdb/Makefile
@@ -8,16 +8,7 @@ GDBDIR= ${.CURDIR}/../../../../contrib/gdb
 .PATH: ${SRCDIR}/opcodes ${SRCDIR}/binutils
 
 #	For FSF GDB files, use their CPU (arch) name; for our files use ours.
-.if ${TARGET_ARCH} == "sparc64"
-GDB_CPU=	sparc
-.elif ${TARGET_ARCH} == "amd64"
-GDB_CPU=	i386
-.elif ${TARGET_ARCH} == "powerpc64"
-GDB_CPU=        powerpc
-.else
-GDB_CPU=	${TARGET_ARCH}
-.endif
-
+GDB_CPU=${TARGET_CPUARCH:C/amd64/i386/:C/powerpc.*/rs6000/:C/sparc64/sparc/}
 NO_SHARED?=yes
 PROG=	gdb
 XSRCS=	annotate.c arch-utils.c ax-general.c ax-gdb.c bcache.c		\
@@ -57,7 +48,7 @@ WARNS?=	0
 CFLAGS+=	-DCROSS_COMPILE=1
 .endif
 CFLAGS+=	-DDEFAULT_BFD_ARCH=bfd_${GDB_CPU}_arch
-CFLAGS+=	-I${.CURDIR}/${TARGET_ARCH}
+CFLAGS+=	-I${.CURDIR}/${TARGET_CPUARCH}
 CFLAGS+=	-I${SRCDIR}/binutils -I${SRCDIR}/bfd
 CFLAGS+=	-I${GDBDIR}/gdb -I${GDBDIR}/gdb/config
 CFLAGS+=        -I$(.CURDIR)
@@ -123,8 +114,8 @@ init.c: ${XSRCS}
 
 tm.h:
 	echo '#include "${GDB_CPU}/tm-fbsd.h"'		> ${.TARGET}
-.if exists(${.CURDIR}/fbsd-kgdb-${TARGET_ARCH}.h)
-	echo '#include "fbsd-kgdb-${TARGET_ARCH}.h"'	>> ${.TARGET}
+.if exists(${.CURDIR}/fbsd-kgdb-${TARGET_CPUARCH}.h)
+	echo '#include "fbsd-kgdb-${TARGET_CPUARCH}.h"'	>> ${.TARGET}
 .endif
 
 .for H in nm-fbsd xm-${GDB_CPU}
@@ -133,7 +124,7 @@ ${H:C/-.*$//}.h:
 .endfor
 
 kvm-fbsd-machine.h:
-	ln -sf ${.CURDIR}/kvm-fbsd-${TARGET_ARCH}.h ${.TARGET}
+	ln -sf ${.CURDIR}/kvm-fbsd-${TARGET_CPUARCH}.h ${.TARGET}
 
 GDB_VERSION=	"5.2.1 (FreeBSD)"
 gdbversion.c: Makefile
diff --git a/gnu/usr.bin/gdb/Makefile b/gnu/usr.bin/gdb/Makefile
index db21e5615e5..33f81cb187b 100644
--- a/gnu/usr.bin/gdb/Makefile
+++ b/gnu/usr.bin/gdb/Makefile
@@ -2,8 +2,7 @@
 
 SUBDIR=	doc libgdb gdb gdbtui kgdb
 
-TARGET_ARCH?= ${MACHINE_ARCH}
-.if exists(${.CURDIR}/gdbserver/reg-${TARGET_ARCH}.c)
+.if exists(${.CURDIR}/gdbserver/reg-${MACHINE_CPUARCH}.c)
 SUBDIR+=gdbserver
 .endif
 
diff --git a/gnu/usr.bin/gdb/gdbserver/Makefile b/gnu/usr.bin/gdb/gdbserver/Makefile
index 08f25ae61a5..f5cfd4c49f6 100644
--- a/gnu/usr.bin/gdb/gdbserver/Makefile
+++ b/gnu/usr.bin/gdb/gdbserver/Makefile
@@ -14,11 +14,10 @@ SRCS=	inferiors.c mem-break.c regcache.c remote-utils.c	\
 	server.c signals.c target.c utils.c
 SRCS+=	fbsd-low.c
 
-SRCS+= fbsd-${MACHINE_ARCH}-low.c reg-${MACHINE_ARCH}.c
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
+SRCS+=	fbsd-${MACHINE_CPUARCH}-low.c reg-${MACHINE_CPUARCH}.c
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SRCS+= i387-fp.c
 .endif
-
 #CFLAGS+=	-I${.CURDIR}/../arch/${MACHINE_ARCH}
 CFLAGS+=	-I${GDBDIR}/gdb/gdbserver
 CFLAGS+=	-I${GDBDIR}/gdb/regformats
diff --git a/include/Makefile b/include/Makefile
index 0ba8b17d54b..4e7fd935ae5 100644
--- a/include/Makefile
+++ b/include/Makefile
@@ -115,8 +115,8 @@ INCSLINKS+=	machine/$i ${INCLUDEDIR}/$i
 INCSLINKS+=	sys/$i ${INCLUDEDIR}/$i
 .endfor
 
-.if ${MACHINE} != ${MACHINE_ARCH}
-_MARCH=${MACHINE_ARCH}
+.if ${MACHINE} != ${MACHINE_CPUARCH}
+_MARCH=${MACHINE_CPUARCH}
 .endif
 
 .include 
diff --git a/lib/Makefile b/lib/Makefile
index 1f41df4b5ae..6f158a4596b 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -112,10 +112,10 @@ SUBDIR=	${SUBDIR_ORDERED} \
 	${_bind} \
 	${_clang}
 
-.if exists(${.CURDIR}/csu/${MACHINE_ARCH}-elf)
-_csu=csu/${MACHINE_ARCH}-elf
-.elif exists(${.CURDIR}/csu/${MACHINE_ARCH}/Makefile)
-_csu=csu/${MACHINE_ARCH}
+.if exists(${.CURDIR}/csu/${MACHINE_CPUARCH}-elf)
+_csu=csu/${MACHINE_CPUARCH}-elf
+.elif exists(${.CURDIR}/csu/${MACHINE_CPUARCH}/Makefile)
+_csu=csu/${MACHINE_CPUARCH}
 .else
 _csu=csu
 .endif
@@ -168,7 +168,7 @@ _libnetgraph=	libnetgraph
 _libypclnt=	libypclnt
 .endif
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 .if ${MK_NCP} != "no"
 _libncp=	libncp
 .endif
@@ -178,16 +178,22 @@ _libproc=	libproc
 _librtld_db=	librtld_db
 .endif
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 _libefi=	libefi
 _libsmb=	libsmb
 .endif
 
+.if ${MACHINE_CPUARCH} == "amd64"
+.if ${MK_NCP} != "no"
+_libncp=	libncp
+.endif
+.endif
+
 .if ${MACHINE_CPUARCH} == "powerpc"
 _libsmb=	libsmb
 .endif
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 _libsmb=	libsmb
 .endif
 
diff --git a/lib/libc/Makefile b/lib/libc/Makefile
index ad4e5bd1629..8aed00f8ad7 100644
--- a/lib/libc/Makefile
+++ b/lib/libc/Makefile
@@ -15,7 +15,7 @@ LIB=c
 SHLIB_MAJOR= 7
 WARNS?=	2
 CFLAGS+=-I${.CURDIR}/include -I${.CURDIR}/../../include
-CFLAGS+=-I${.CURDIR}/${MACHINE_ARCH}
+CFLAGS+=-I${.CURDIR}/${MACHINE_CPUARCH}
 CFLAGS+=-DNLS
 CLEANFILES+=tags
 INSTALL_PIC_ARCHIVE=
@@ -36,7 +36,7 @@ MDASM=
 MIASM=
 NOASM=
 
-.include "${.CURDIR}/${MACHINE_ARCH}/Makefile.inc"
+.include "${.CURDIR}/${MACHINE_CPUARCH}/Makefile.inc"
 .include "${.CURDIR}/db/Makefile.inc"
 .include "${.CURDIR}/compat-43/Makefile.inc"
 .include "${.CURDIR}/gdtoa/Makefile.inc"
@@ -49,11 +49,11 @@ NOASM=
 .include "${.CURDIR}/net/Makefile.inc"
 .include "${.CURDIR}/nls/Makefile.inc"
 .include "${.CURDIR}/posix1e/Makefile.inc"
-.if ${MACHINE_ARCH} != "amd64" && \
-    ${MACHINE_ARCH} != "ia64" && \
+.if ${MACHINE_CPUARCH} != "amd64" && \
+    ${MACHINE_CPUARCH} != "ia64" && \
     ${MACHINE_ARCH} != "powerpc64" && \
-    ${MACHINE_ARCH} != "sparc64" && \
-    ${MACHINE_ARCH} != "mips"
+    ${MACHINE_CPUARCH} != "sparc64" && \
+    ${MACHINE_CPUARCH} != "mips"
 .include "${.CURDIR}/quad/Makefile.inc"
 .endif
 .if ${MACHINE_ARCH} == "mips" && \
@@ -70,7 +70,7 @@ NOASM=
 .include "${.CURDIR}/rpc/Makefile.inc"
 .include "${.CURDIR}/uuid/Makefile.inc"
 .include "${.CURDIR}/xdr/Makefile.inc"
-.if ${MACHINE_ARCH} == "arm" || ${MACHINE_ARCH} == "mips"
+.if ${MACHINE_CPUARCH} == "arm" || ${MACHINE_CPUARCH} == "mips"
 .include "${.CURDIR}/softfloat/Makefile.inc"
 .endif
 .if ${MK_NIS} != "no"
@@ -115,14 +115,14 @@ KQSRCS=	adddi3.c anddi3.c ashldi3.c ashrdi3.c cmpdi2.c divdi3.c iordi3.c \
 KSRCS=	bcmp.c ffs.c ffsl.c fls.c flsl.c index.c mcount.c rindex.c \
 	strcat.c strcmp.c strcpy.c strlen.c strncpy.c
 
-libkern: libkern.gen libkern.${MACHINE_ARCH}
+libkern: libkern.gen libkern.${MACHINE_CPUARCH}
 
 libkern.gen: ${KQSRCS} ${KSRCS}
 	cp -p ${.CURDIR}/quad/quad.h ${.ALLSRC} ${DESTDIR}/sys/libkern
 
-libkern.${MACHINE_ARCH}:: ${KMSRCS}
+libkern.${MACHINE_CPUARCH}:: ${KMSRCS}
 .if defined(KMSRCS) && !empty(KMSRCS)
-	cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${MACHINE_ARCH}
+	cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${MACHINE_CPUARCH}
 .endif
 
 .include 
diff --git a/lib/libc/compat-43/Makefile.inc b/lib/libc/compat-43/Makefile.inc
index 8505ff22787..e8ec364a2cf 100644
--- a/lib/libc/compat-43/Makefile.inc
+++ b/lib/libc/compat-43/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # compat-43 sources
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/compat-43 ${.CURDIR}/compat-43
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/compat-43 ${.CURDIR}/compat-43
 
 SRCS+=	creat.c gethostid.c getwd.c killpg.c sethostid.c setpgrp.c \
 	setrgid.c setruid.c sigcompat.c
diff --git a/lib/libc/gen/Makefile.inc b/lib/libc/gen/Makefile.inc
index 5056392ccd2..204541e594f 100644
--- a/lib/libc/gen/Makefile.inc
+++ b/lib/libc/gen/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # machine-independent gen sources
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/gen ${.CURDIR}/gen
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/gen ${.CURDIR}/gen
 
 SRCS+=  __getosreldate.c __xuname.c \
 	_once_stub.c _pthread_stubs.c _rand48.c _spinlock_stub.c \
@@ -38,8 +38,8 @@ SRCS+=  __getosreldate.c __xuname.c \
 SYM_MAPS+=${.CURDIR}/gen/Symbol.map
 
 # machine-dependent gen sources
-.if exists(${.CURDIR}/${MACHINE_ARCH}/gen/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_ARCH}/gen/Makefile.inc"
+.if exists(${.CURDIR}/${MACHINE_CPUARCH}/gen/Makefile.inc)
+.include "${.CURDIR}/${MACHINE_CPUARCH}/gen/Makefile.inc"
 .endif
 
 MAN+=	alarm.3 arc4random.3 \
diff --git a/lib/libc/locale/Makefile.inc b/lib/libc/locale/Makefile.inc
index 074c4d9ded2..8cf5bebd5d7 100644
--- a/lib/libc/locale/Makefile.inc
+++ b/lib/libc/locale/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # locale sources
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/locale ${.CURDIR}/locale
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/locale ${.CURDIR}/locale
 
 SRCS+=	ascii.c big5.c btowc.c collate.c collcmp.c euc.c fix_grouping.c \
 	gb18030.c gb2312.c gbk.c isctype.c iswctype.c \
diff --git a/lib/libc/quad/Makefile.inc b/lib/libc/quad/Makefile.inc
index 14a5b1f50d1..84723a73658 100644
--- a/lib/libc/quad/Makefile.inc
+++ b/lib/libc/quad/Makefile.inc
@@ -2,9 +2,9 @@
 # $FreeBSD$
 
 # Quad support, if needed
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/quad ${.CURDIR}/quad
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/quad ${.CURDIR}/quad
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 
 SRCS+=	cmpdi2.c divdi3.c moddi3.c qdivrem.c ucmpdi2.c udivdi3.c umoddi3.c
 
diff --git a/lib/libc/softfloat/Makefile.inc b/lib/libc/softfloat/Makefile.inc
index c7867618265..c3df0ae69ec 100644
--- a/lib/libc/softfloat/Makefile.inc
+++ b/lib/libc/softfloat/Makefile.inc
@@ -2,10 +2,10 @@
 # $FreeBSD$
 
 SOFTFLOAT_BITS?=64
-.PATH:		${MACHINE_ARCH}/softfloat \
+.PATH:		${MACHINE_CPUARCH}/softfloat \
 		${.CURDIR}/softfloat/bits${SOFTFLOAT_BITS} ${.CURDIR}/softfloat
 
-CFLAGS+=	-I${.CURDIR}/${MACHINE_ARCH}/softfloat -I${.CURDIR}/softfloat
+CFLAGS+=	-I${.CURDIR}/${MACHINE_CPUARCH}/softfloat -I${.CURDIR}/softfloat
 CFLAGS+=	-DSOFTFLOAT_FOR_GCC
 
 SRCS+=		softfloat.c
diff --git a/lib/libc/stdlib/Makefile.inc b/lib/libc/stdlib/Makefile.inc
index 1d06dd390c5..d26f66a09ae 100644
--- a/lib/libc/stdlib/Makefile.inc
+++ b/lib/libc/stdlib/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # machine-independent stdlib sources
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/stdlib ${.CURDIR}/stdlib
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/stdlib ${.CURDIR}/stdlib
 
 MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \
 	bsearch.c div.c exit.c getenv.c getopt.c getopt_long.c \
@@ -16,7 +16,7 @@ MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \
 SYM_MAPS+= ${.CURDIR}/stdlib/Symbol.map
 
 # machine-dependent stdlib sources
-.sinclude "${.CURDIR}/${MACHINE_ARCH}/stdlib/Makefile.inc"
+.sinclude "${.CURDIR}/${MACHINE_CPUARCH}/stdlib/Makefile.inc"
 
 MAN+=	a64l.3 abort.3 abs.3 alloca.3 atexit.3 atof.3 atoi.3 atol.3 bsearch.3 \
 	div.3 exit.3 getenv.3 getopt.3 getopt_long.3 getsubopt.3 \
diff --git a/lib/libc/string/Makefile.inc b/lib/libc/string/Makefile.inc
index b0a1899009d..96759d5bd7d 100644
--- a/lib/libc/string/Makefile.inc
+++ b/lib/libc/string/Makefile.inc
@@ -1,7 +1,7 @@
 #	@(#)Makefile.inc	8.1 (Berkeley) 6/4/93
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/string ${.CURDIR}/string
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/string ${.CURDIR}/string
 
 CFLAGS+= -I${.CURDIR}/locale
 
@@ -26,8 +26,8 @@ SYM_MAPS+=	${.CURDIR}/string/Symbol.map
 
 
 # machine-dependent string sources
-.if exists(${.CURDIR}/${MACHINE_ARCH}/string/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_ARCH}/string/Makefile.inc"
+.if exists(${.CURDIR}/${MACHINE_CPUARCH}/string/Makefile.inc)
+.include "${.CURDIR}/${MACHINE_CPUARCH}/string/Makefile.inc"
 .endif
 
 MAN+=	bcmp.3 bcopy.3 bstring.3 bzero.3 ffs.3 index.3 memccpy.3 memchr.3 \
diff --git a/lib/libc/sys/Makefile.inc b/lib/libc/sys/Makefile.inc
index 1915c550eba..05c3e173d10 100644
--- a/lib/libc/sys/Makefile.inc
+++ b/lib/libc/sys/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # sys sources
-.PATH: ${.CURDIR}/${MACHINE_ARCH}/sys ${.CURDIR}/sys
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/sys ${.CURDIR}/sys
 
 # Include the generated makefile containing the *complete* list
 # of syscall names in MIASM.
@@ -13,8 +13,8 @@
 # MDASM names override the default syscall names in MIASM.
 # NOASM will prevent the default syscall code from being generated.
 #
-.if exists(${.CURDIR}/${MACHINE_ARCH}/sys/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_ARCH}/sys/Makefile.inc"
+.if exists(${.CURDIR}/${MACHINE_CPUARCH}/sys/Makefile.inc)
+.include "${.CURDIR}/${MACHINE_CPUARCH}/sys/Makefile.inc"
 .endif
 
 # Sources common to both syscall interfaces:
diff --git a/lib/libc_r/sys/Makefile.inc b/lib/libc_r/sys/Makefile.inc
index e608afa6990..ab6db1f4f15 100644
--- a/lib/libc_r/sys/Makefile.inc
+++ b/lib/libc_r/sys/Makefile.inc
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.PATH:	 ${.CURDIR}/sys ${.CURDIR}/arch/${MACHINE_ARCH}
+.PATH:	 ${.CURDIR}/sys ${.CURDIR}/arch/${MACHINE_CPUARCH}
 
 SRCS+=	uthread_error.c _atomic_lock.S
 
diff --git a/lib/libdisk/Makefile b/lib/libdisk/Makefile
index 763170d4852..47cf372e70e 100644
--- a/lib/libdisk/Makefile
+++ b/lib/libdisk/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 _open_disk=	open_ia64_disk.c
 .else
 _change	=	change.c
diff --git a/lib/libkvm/Makefile b/lib/libkvm/Makefile
index e62d7cae291..bf464eddc4f 100644
--- a/lib/libkvm/Makefile
+++ b/lib/libkvm/Makefile
@@ -11,10 +11,11 @@ CFLAGS+=-DSUN4V
 
 WARNS?=	0
 
-SRCS=	kvm.c kvm_${MACHINE_ARCH}.c kvm_cptime.c kvm_file.c kvm_getloadavg.c \
+SRCS=	kvm.c kvm_${MACHINE_CPUARCH}.c kvm_cptime.c kvm_file.c kvm_getloadavg.c \
 	kvm_getswapinfo.c kvm_pcpu.c kvm_proc.c kvm_vnet.c
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "arm"
-SRCS+=	kvm_minidump_${MACHINE_ARCH}.c
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386" || \
+    ${MACHINE_CPUARCH} == "arm"
+SRCS+=	kvm_minidump_${MACHINE_CPUARCH}.c
 .endif
 INCS=	kvm.h
 
diff --git a/lib/libpmc/Makefile b/lib/libpmc/Makefile
index fd35fd5acb2..85ddf0f45a1 100644
--- a/lib/libpmc/Makefile
+++ b/lib/libpmc/Makefile
@@ -22,7 +22,7 @@ MAN+=	pmc_start.3
 MAN+=	pmclog.3
 
 # PMC-dependent manual pages
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 MAN+=	pmc.atom.3
 MAN+=	pmc.core.3
 MAN+=	pmc.core2.3
@@ -38,7 +38,7 @@ MAN+=	pmc.corei7uc.3
 MAN+=	pmc.westmere.3
 MAN+=	pmc.westmereuc.3
 MAN+=	pmc.tsc.3
-.elif ${MACHINE_ARCH} == "arm" && ${CPUTYPE} == "xscale"
+.elif ${MACHINE_CPUARCH} == "arm" && ${CPUTYPE} == "xscale"
 MAN+=	pmc.xscale.3
 .endif
 
diff --git a/lib/libstand/Makefile b/lib/libstand/Makefile
index f44d60dd255..90b47e78021 100644
--- a/lib/libstand/Makefile
+++ b/lib/libstand/Makefile
@@ -20,23 +20,23 @@ WARNS?=		0
 CFLAGS+= -ffreestanding -Wformat
 CFLAGS+= -I${.CURDIR}
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-mpreferred-stack-boundary=2
 CFLAGS+=	-mno-mmx -mno-3dnow -mno-sse -mno-sse2
 .endif
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 CFLAGS+=	-mno-sse3
 .endif
 .if ${MACHINE} == "pc98"
 CFLAGS+=	-Os
 .endif
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_CPUARCH} == "powerpc"
 CFLAGS+=	-msoft-float -D_STANDALONE -DNETIF_DEBUG
 .endif
 .if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "powerpc64"
 CFLAGS+=	-m32 -I.
 .endif
-.if ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "arm"
 CFLAGS+=	-msoft-float -D_STANDALONE
 .endif
 
@@ -54,19 +54,19 @@ SRCS+= ntoh.c
 
 # string functions from libc
 .PATH: ${.CURDIR}/../libc/string
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "powerpc" || \
-	${MACHINE_ARCH} == "powerpc64" || ${MACHINE_ARCH} == "sparc64" || \
-	${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "powerpc" || \
+	${MACHINE_CPUARCH} == "sparc64" || ${MACHINE_CPUARCH} == "amd64" || \
+	${MACHINE_CPUARCH} == "arm"
 SRCS+=	bcmp.c bcopy.c bzero.c ffs.c index.c memccpy.c memchr.c memcmp.c \
         memcpy.c memmove.c memset.c qdivrem.c rindex.c strcat.c strchr.c \
         strcmp.c strcpy.c strcspn.c strlen.c strncat.c strncmp.c strncpy.c \
 	strpbrk.c strrchr.c strsep.c strspn.c strstr.c strtok.c swab.c
 .endif
-.if ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "arm"
 .PATH: ${.CURDIR}/../libc/arm/gen
 SRCS+= divsi3.S
 .endif
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 .PATH: ${.CURDIR}/../libc/ia64/string
 SRCS+=	bcmp.c bcopy.S bzero.S ffs.S index.c memccpy.c memchr.c memcmp.c \
 	memcpy.S memmove.S memset.c rindex.c strcat.c strchr.c \
@@ -78,7 +78,7 @@ SRCS+=	bcmp.c bcopy.S bzero.S ffs.S index.c memccpy.c memchr.c memcmp.c \
 SRCS+= __divdi3.S __divsi3.S __moddi3.S __modsi3.S
 SRCS+= __udivdi3.S __udivsi3.S __umoddi3.S __umodsi3.S
 .endif
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_CPUARCH} == "powerpc"
 .PATH: ${.CURDIR}/../libc/quad
 SRCS+=	ashldi3.c ashrdi3.c
 .PATH: ${.CURDIR}/../libc/powerpc/gen
@@ -90,12 +90,12 @@ SRCS+=	syncicache.c
 SRCS+= uuid_equal.c uuid_is_nil.c
 
 # _setjmp/_longjmp
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 .PATH: ${.CURDIR}/i386
 .elif ${MACHINE_ARCH} == "powerpc64"
 .PATH: ${.CURDIR}/powerpc
 .else
-.PATH: ${.CURDIR}/${MACHINE_ARCH}
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}
 .endif
 SRCS+=	_setjmp.S
 
@@ -157,7 +157,7 @@ SRCS+=	splitfs.c
 
 .include 
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 beforedepend ${OBJS}: machine
 cleandepend: cleanmachine
 cleanmachine:
diff --git a/lib/libthread_db/Makefile b/lib/libthread_db/Makefile
index 7aaefd7cfd4..047bbe66808 100644
--- a/lib/libthread_db/Makefile
+++ b/lib/libthread_db/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.PATH:	${.CURDIR}/arch/${MACHINE_ARCH}
+.PATH:	${.CURDIR}/arch/${MACHINE_CPUARCH}
 
 LIB=	thread_db
 SHLIB_MAJOR= 3
diff --git a/lib/msun/Makefile b/lib/msun/Makefile
index 35077a38dbb..38ce172cb3d 100644
--- a/lib/msun/Makefile
+++ b/lib/msun/Makefile
@@ -76,7 +76,7 @@ COMMON_SRCS= b_exp.c b_log.c b_tgamma.c \
 # Location of fpmath.h and _fpmath.h
 LIBCDIR=	${.CURDIR}/../libc
 CFLAGS+=	-I${.CURDIR}/src -I${LIBCDIR}/include \
-	-I${LIBCDIR}/${MACHINE_ARCH}
+	-I${LIBCDIR}/${MACHINE_CPUARCH}
 SYM_MAPS+=	${.CURDIR}/Symbol.map
 
 VERSION_DEF=	${LIBCDIR}/Versions.def
diff --git a/libexec/rtld-elf/Makefile b/libexec/rtld-elf/Makefile
index 2f5d574ada6..6cf09bed281 100644
--- a/libexec/rtld-elf/Makefile
+++ b/libexec/rtld-elf/Makefile
@@ -10,7 +10,7 @@ SRCS=		rtld_start.S \
 MAN=		rtld.1
 CSTD?=		gnu99
 CFLAGS+=	-Wall -DFREEBSD_ELF -DIN_RTLD
-CFLAGS+=	-I${.CURDIR}/${MACHINE_ARCH} -I${.CURDIR}
+CFLAGS+=	-I${.CURDIR}/${MACHINE_CPUARCH} -I${.CURDIR}
 .if ${MACHINE_ARCH} == "powerpc64"
 LDFLAGS+=	-nostdlib -e _rtld_start
 .else
@@ -29,7 +29,7 @@ LDFLAGS+=	-shared -Wl,-Bsymbolic
 DPADD=		${LIBC_PIC}
 LDADD=		-lc_pic -lssp_nonshared
 
-.if ${MACHINE_ARCH} != "ia64"
+.if ${MACHINE_CPUARCH} != "ia64"
 .if ${MK_SYMVER} == "yes"
 LIBCDIR=	${.CURDIR}/../../lib/libc
 VERSION_DEF=	${LIBCDIR}/Versions.def
@@ -39,14 +39,14 @@ LDFLAGS+=	-Wl,--version-script=${VERSION_MAP}
 
 ${PROG}:	${VERSION_MAP}
 
-.if exists(${.CURDIR}/${MACHINE_ARCH}/Symbol.map)
-SYMBOL_MAPS+=	${.CURDIR}/${MACHINE_ARCH}/Symbol.map
+.if exists(${.CURDIR}/${MACHINE_CPUARCH}/Symbol.map)
+SYMBOL_MAPS+=	${.CURDIR}/${MACHINE_CPUARCH}/Symbol.map
 .endif
 .endif
 .endif
 
-.if exists(${.CURDIR}/${MACHINE_ARCH}/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_ARCH}/Makefile.inc"
+.if exists(${.CURDIR}/${MACHINE_CPUARCH}/Makefile.inc)
+.include "${.CURDIR}/${MACHINE_CPUARCH}/Makefile.inc"
 .endif
 
 # Since moving rtld-elf to /libexec, we need to create a symlink.
@@ -56,7 +56,7 @@ beforeinstall:
 	-chflags noschg ${DESTDIR}/usr/libexec/${PROG}
 .endif
 
-.PATH: ${.CURDIR}/${MACHINE_ARCH}
+.PATH: ${.CURDIR}/${MACHINE_CPUARCH}
 
 .include 
 .include 
diff --git a/libexec/rtld-elf/amd64/Makefile.inc b/libexec/rtld-elf/amd64/Makefile.inc
index ba39193cf89..b265a9d7677 100644
--- a/libexec/rtld-elf/amd64/Makefile.inc
+++ b/libexec/rtld-elf/amd64/Makefile.inc
@@ -1,5 +1,7 @@
+# $FreeBSD$
+
 CFLAGS+=	-elf
 LDFLAGS+=	-elf
 # Uncomment this to build the dynamic linker as an executable instead
 # of a shared library:
-#LDSCRIPT=	${.CURDIR}/${MACHINE_ARCH}/elf_rtld.x
+#LDSCRIPT=	${.CURDIR}/${MACHINE_CPUARCH}/elf_rtld.x
diff --git a/libexec/rtld-elf/i386/Makefile.inc b/libexec/rtld-elf/i386/Makefile.inc
index ba39193cf89..b265a9d7677 100644
--- a/libexec/rtld-elf/i386/Makefile.inc
+++ b/libexec/rtld-elf/i386/Makefile.inc
@@ -1,5 +1,7 @@
+# $FreeBSD$
+
 CFLAGS+=	-elf
 LDFLAGS+=	-elf
 # Uncomment this to build the dynamic linker as an executable instead
 # of a shared library:
-#LDSCRIPT=	${.CURDIR}/${MACHINE_ARCH}/elf_rtld.x
+#LDSCRIPT=	${.CURDIR}/${MACHINE_CPUARCH}/elf_rtld.x
diff --git a/rescue/rescue/Makefile b/rescue/rescue/Makefile
index d62b6f45cec..54caad6ff1e 100644
--- a/rescue/rescue/Makefile
+++ b/rescue/rescue/Makefile
@@ -145,7 +145,7 @@ CRUNCH_LIBS+= -lzfs -lnvpair -luutil -lavl
 .endif
 CRUNCH_LIBS+= -lgeom -lbsdxml -ljail -lkiconv -lmd -lreadline -lsbuf -lufs -lz
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 CRUNCH_PROGS_sbin+= bsdlabel sconfig fdisk
 CRUNCH_ALIAS_bsdlabel= disklabel
 #.if ${MK_NCP} != "no"
@@ -161,15 +161,15 @@ CRUNCH_PROGS_sbin+= bsdlabel
 CRUNCH_SRCDIR_fdisk= $(.CURDIR)/../../sbin/fdisk_pc98
 .endif
 
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 CRUNCH_PROGS_sbin+= mca
 .endif
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 CRUNCH_PROGS_sbin+= bsdlabel sunlabel
 .endif
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CRUNCH_PROGS_sbin+= bsdlabel fdisk
 CRUNCH_ALIAS_bsdlabel= disklabel
 .endif
diff --git a/sbin/atm/atmconfig/Makefile b/sbin/atm/atmconfig/Makefile
index 8564d355efb..cbf5a9a87d4 100644
--- a/sbin/atm/atmconfig/Makefile
+++ b/sbin/atm/atmconfig/Makefile
@@ -27,7 +27,8 @@ LDADD=	-lbsnmp
 CLEANFILES+= oid.h
 .endif
 
-.if ${MACHINE_ARCH} == "arm"
+# XXX - this is verboten
+.if ${MACHINE_CPUARCH} == "arm"
 WARNS?= 3
 .endif
 
diff --git a/sbin/bsdlabel/Makefile b/sbin/bsdlabel/Makefile
index b60bbd03add..f91f1601fc7 100644
--- a/sbin/bsdlabel/Makefile
+++ b/sbin/bsdlabel/Makefile
@@ -8,7 +8,7 @@ SRCS=	bsdlabel.c geom_bsd_enc.c
 #MAN=	bsdlabel.5
 MAN+=	bsdlabel.8
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 LINKS=	${BINDIR}/bsdlabel ${BINDIR}/disklabel
 MLINKS=	bsdlabel.8 disklabel.8
 .endif
diff --git a/sbin/camcontrol/Makefile b/sbin/camcontrol/Makefile
index 31bbd46f4a5..877e332b835 100644
--- a/sbin/camcontrol/Makefile
+++ b/sbin/camcontrol/Makefile
@@ -7,7 +7,8 @@ SRCS+=	modeedit.c
 .else
 CFLAGS+= -DMINIMALISTIC
 .endif
-.if ${MACHINE_ARCH} == "arm"
+# This is verboten
+.if ${MACHINE_CPUARCH} == "arm"
 WARNS?= 3
 .endif
 DPADD=	${LIBCAM} ${LIBSBUF} ${LIBUTIL}
diff --git a/sbin/gbde/Makefile b/sbin/gbde/Makefile
index 0faa6ba6d39..2abfcb807c1 100644
--- a/sbin/gbde/Makefile
+++ b/sbin/gbde/Makefile
@@ -9,7 +9,7 @@ SRCS+=	g_bde_lock.c
 
 # rijndael-fst.c does evil casting things which results in warnings on
 # 64 bit machines, the test-vectors check out however, so it works right.
-.if ${MACHINE_ARCH} != "i386"
+.if ${MACHINE_CPUARCH} != "i386"
 WARNS?=	3
 .endif
 
diff --git a/sbin/newfs_msdos/Makefile b/sbin/newfs_msdos/Makefile
index 558f673edea..0a9ffb4340a 100644
--- a/sbin/newfs_msdos/Makefile
+++ b/sbin/newfs_msdos/Makefile
@@ -3,7 +3,8 @@
 PROG=	newfs_msdos
 MAN=	newfs_msdos.8
 
-.if ${MACHINE_ARCH} == "arm"
+# XXX - this is verboten
+.if ${MACHINE_CPUARCH} == "arm"
 WARNS?= 3
 .endif
 
diff --git a/sbin/sunlabel/Makefile b/sbin/sunlabel/Makefile
index 9eb1a325709..ed64bee5809 100644
--- a/sbin/sunlabel/Makefile
+++ b/sbin/sunlabel/Makefile
@@ -6,7 +6,7 @@ PROG=	sunlabel
 SRCS=	sunlabel.c geom_sunlabel_enc.c
 MAN=	sunlabel.8
 
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 LINKS=	${BINDIR}/sunlabel ${BINDIR}/disklabel
 MLINKS=	sunlabel.8 disklabel.8
 .endif
diff --git a/secure/lib/libcrypto/Makefile b/secure/lib/libcrypto/Makefile
index 212427fb9fe..af48d7061f4 100644
--- a/secure/lib/libcrypto/Makefile
+++ b/secure/lib/libcrypto/Makefile
@@ -49,7 +49,7 @@ INCS+=	asn1.h asn1_mac.h asn1t.h
 
 # bf
 SRCS+=	bf_cfb64.c bf_ecb.c bf_ofb64.c bf_skey.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 .if ${MACHINE_CPU:Mi686}
 SRCS+=	bf-686.s
 .else
@@ -73,9 +73,9 @@ SRCS+=	bn_add.c bn_blind.c bn_const.c bn_ctx.c bn_depr.c bn_div.c \
 	bn_lib.c bn_mod.c bn_mont.c bn_mpi.c bn_mul.c bn_nist.c bn_opt.c \
 	bn_prime.c bn_print.c bn_rand.c bn_recp.c bn_shift.c bn_sqr.c \
 	bn_sqrt.c bn_word.c bn_x931p.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	bn-586.s co-586.s
-.elif ${MACHINE_ARCH} == "amd64"
+.elif ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	x86_64-gcc.c
 .else
 SRCS+=	bn_asm.c
@@ -89,7 +89,7 @@ INCS+=	buffer.h
 
 # cast
 SRCS+=	c_cfb64.c c_ecb.c c_ofb64.c c_skey.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	cast-586.s
 .else
 SRCS+=	c_enc.c
@@ -97,7 +97,7 @@ SRCS+=	c_enc.c
 INCS+=	cast.h
 
 # camellia
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	camellia.c cmll_cbc.c cmll_cfb.c cmll_ctr.c cmll_ecb.c \
 	cmll_misc.c cmll_ofb.c
 INCS+=	camellia.h
@@ -117,7 +117,7 @@ SRCS+=	cbc3_enc.c cbc_cksm.c cbc_enc.c cfb64ede.c cfb64enc.c cfb_enc.c \
 	enc_read.c enc_writ.c fcrypt.c ofb64ede.c ofb64enc.c \
 	ofb_enc.c pcbc_enc.c qud_cksm.c rand_key.c read2pwd.c \
 	rpc_enc.c set_key.c str2key.c xcbc_enc.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	des-586.s crypt586.s
 .else
 SRCS+=	des_enc.c fcrypt_b.c
@@ -172,7 +172,7 @@ SRCS+=	bio_b64.c bio_enc.c bio_md.c bio_ok.c c_all.c c_allc.c c_alld.c \
 	m_mdc2.c m_null.c m_ripemd.c m_sha.c m_sha1.c names.c \
 	openbsd_hw.c p5_crpt.c p5_crpt2.c p_dec.c p_enc.c p_lib.c \
 	p_open.c p_seal.c p_sign.c p_verify.c
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "i386" || ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	e_camellia.c
 .endif
 INCS+=	evp.h
@@ -208,7 +208,7 @@ INCS+=	md4.h
 
 # md5
 SRCS+=	md5_dgst.c md5_one.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	md5-586.s
 .endif
 INCS+=	md5.h
@@ -255,7 +255,7 @@ INCS+=	rc2.h
 
 # rc4
 SRCS+=	rc4_skey.c rc4_fblk.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	rc4-586.s
 .else
 SRCS+=	rc4_enc.c
@@ -264,7 +264,7 @@ INCS+=	rc4.h
 
 # rc5
 SRCS+=	rc5_ecb.c rc5_skey.c rc5cfb64.c rc5ofb64.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	rc5-586.s
 .else
 SRCS+=	rc5_enc.c
@@ -284,7 +284,7 @@ INCS+=	rsa.h
 
 # sha
 SRCS+=	sha1_one.c sha1dgst.c sha_dgst.c sha_one.c sha256.c sha512.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	sha1-586.s
 .endif
 INCS+=	sha.h
@@ -351,10 +351,10 @@ buildinf.h: ${.CURDIR}/Makefile
 	( echo "#ifndef MK1MF_BUILD"; \
 	echo "  /* auto-generated by crypto/Makefile.ssl for crypto/cversion.c */"; \
 	echo "  #define CFLAGS \"$(CC)\""; \
-	echo "  #define PLATFORM \"FreeBSD-${MACHINE_ARCH}\""; \
+	echo "  #define PLATFORM \"FreeBSD-${MACHINE_CPUARCH}\""; \
 	echo "#endif" ) > ${.TARGET}
 
-opensslconf.h: opensslconf-${MACHINE_ARCH}.h
+opensslconf.h: opensslconf-${MACHINE_CPUARCH}.h
 	cp -f ${.ALLSRC} ${.TARGET}
 
 evp.h: ${LCRYPTO_SRC}/crypto/evp/evp.h
@@ -383,11 +383,11 @@ afterinstall:
 
 .include 
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 .PATH: ${.CURDIR}/i386
 .endif
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 _bn_asmpath=	${LCRYPTO_SRC}/crypto/bn/asm
 .endif
 
diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile
index 4863cda0248..2fa0e9d9631 100644
--- a/share/man/man4/Makefile
+++ b/share/man/man4/Makefile
@@ -628,7 +628,7 @@ MLINKS+=xe.4 if_xe.4
 MLINKS+=xl.4 if_xl.4
 MLINKS+=zyd.4 if_zyd.4
 
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 _acpi_asus.4=	acpi_asus.4
 _acpi_dock.4=	acpi_dock.4
 _acpi_fujitsu.4=acpi_fujitsu.4
@@ -678,7 +678,7 @@ _wpi.4=		wpi.4
 MLINKS+=lindev.4 full.4
 .endif
 
-.if ${MACHINE_ARCH} == "powerpc"
+.if ${MACHINE_CPUARCH} == "powerpc"
 _atp.4=		atp.4
 .endif
 
diff --git a/share/man/man5/Makefile b/share/man/man5/Makefile
index 1216fc4491c..7aad66b907e 100644
--- a/share/man/man5/Makefile
+++ b/share/man/man5/Makefile
@@ -83,7 +83,7 @@ MLINKS+=resolver.5 resolv.conf.5
 MAN+=	hesiod.conf.5 
 .endif
 
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 _boot.config.5=	boot.config.5
 .endif
 
diff --git a/share/mk/bsd.lib.mk b/share/mk/bsd.lib.mk
index 94d918b4879..ecb91bfd288 100644
--- a/share/mk/bsd.lib.mk
+++ b/share/mk/bsd.lib.mk
@@ -58,7 +58,7 @@ STRIP?=	-s
 .SUFFIXES: .out .o .po .So .S .asm .s .c .cc .cpp .cxx .m .C .f .y .l .ln
 
 .if !defined(PICFLAG)
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 PICFLAG=-fPIC
 .else
 PICFLAG=-fpic
diff --git a/share/mk/bsd.sys.mk b/share/mk/bsd.sys.mk
index 3559a267f2b..f6f8a005f50 100644
--- a/share/mk/bsd.sys.mk
+++ b/share/mk/bsd.sys.mk
@@ -79,8 +79,9 @@ CWARNFLAGS	+=	-Werror
 CWARNFLAGS	+=	-Wno-unknown-pragmas
 .endif
 
-.if ${MK_SSP} != "no" && ${CC:T:Micc} != "icc" && ${MACHINE_ARCH} != "ia64" && \
-	${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
+.if ${MK_SSP} != "no" && ${CC:T:Micc} != "icc" && \
+	${MACHINE_CPUARCH} != "ia64" && \
+	${MACHINE_CPUARCH} != "arm" && ${MACHINE_CPUARCH} != "mips"
 # Don't use -Wstack-protector as it breaks world with -Werror.
 SSP_CFLAGS	?=	-fstack-protector
 CFLAGS		+=	${SSP_CFLAGS}
diff --git a/sys/boot/arm/ixp425/boot2/Makefile b/sys/boot/arm/ixp425/boot2/Makefile
index 138446b6fa2..a329b65c0db 100644
--- a/sys/boot/arm/ixp425/boot2/Makefile
+++ b/sys/boot/arm/ixp425/boot2/Makefile
@@ -20,7 +20,7 @@ NO_MAN=
 KERNPHYSADDR=0x180000
 KERNVIRTADDR=${KERNPHYSADDR}
 BOOT_STACK=0x200000-4
-M=${MACHINE_ARCH}
+M=${MACHINE}
 LDFLAGS=-e ${KERNPHYSADDR} -EB -T ldscript.${M}
 OBJS+=  ${SRCS:N*.h:R:S/$/.o/g}
 S=${.CURDIR}/../../../..
diff --git a/sys/conf/kern.post.mk b/sys/conf/kern.post.mk
index f759f271fb8..c7e6281f69e 100644
--- a/sys/conf/kern.post.mk
+++ b/sys/conf/kern.post.mk
@@ -84,8 +84,8 @@ gdbinit:
 	grep -v '# XXX' ${S}/../tools/debugscripts/dot.gdbinit | \
 	    sed "s:MODPATH:${.OBJDIR}/modules:" > .gdbinit
 	cp ${S}/../tools/debugscripts/gdbinit.kernel ${.CURDIR}
-.if exists(${S}/../tools/debugscripts/gdbinit.${MACHINE_ARCH})
-	cp ${S}/../tools/debugscripts/gdbinit.${MACHINE_ARCH} \
+.if exists(${S}/../tools/debugscripts/gdbinit.${MACHINE_CPUARCH})
+	cp ${S}/../tools/debugscripts/gdbinit.${MACHINE_CPUARCH} \
 	    ${.CURDIR}/gdbinit.machine
 .endif
 .endif
diff --git a/sys/conf/kern.pre.mk b/sys/conf/kern.pre.mk
index b61113e7e50..d4bdc1f54b2 100644
--- a/sys/conf/kern.pre.mk
+++ b/sys/conf/kern.pre.mk
@@ -32,7 +32,7 @@ CTFFLAGS+=	-g
 . else
 _MINUS_O=	-O2
 . endif
-. if ${MACHINE_ARCH} == "amd64"
+. if ${MACHINE_CPUARCH} == "amd64"
 COPTFLAGS?=-O2 -frename-registers -pipe
 . else
 COPTFLAGS?=${_MINUS_O} -pipe
diff --git a/usr.bin/ldd/Makefile b/usr.bin/ldd/Makefile
index cd172280d78..fd2b7b4d9cc 100644
--- a/usr.bin/ldd/Makefile
+++ b/usr.bin/ldd/Makefile
@@ -2,7 +2,7 @@
 
 PROG?=		ldd
 SRCS=		ldd.c
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=		sods.c
 .endif
 
diff --git a/usr.bin/truss/Makefile b/usr.bin/truss/Makefile
index d907ad59c8e..ca0ce9234a2 100644
--- a/usr.bin/truss/Makefile
+++ b/usr.bin/truss/Makefile
@@ -2,7 +2,7 @@
 
 NO_WERROR=
 PROG=	truss
-SRCS=	main.c setup.c syscalls.c syscalls.h ioctl.c ${MACHINE_ARCH}-fbsd.c
+SRCS=	main.c setup.c syscalls.c syscalls.h ioctl.c ${MACHINE_CPUARCH}-fbsd.c
 
 CFLAGS+= -I${.CURDIR} -I.
 CLEANFILES= syscalls.master syscalls.h ioctl.c
@@ -19,7 +19,7 @@ syscalls.h:	syscalls.master
 ioctl.c: ${.CURDIR}/../kdump/mkioctls
 	sh ${.CURDIR}/../kdump/mkioctls ${DESTDIR}/usr/include > ${.TARGET}
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 SRCS+=	i386-linux.c linux_syscalls.h
 CLEANFILES+=i386l-syscalls.master linux_syscalls.h
 
@@ -31,7 +31,7 @@ linux_syscalls.h:	i386l-syscalls.master
 		${.CURDIR}/i386linux.conf
 .endif
 
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 SRCS+=	amd64-linux32.c linux32_syscalls.h
 CLEANFILES+=amd64l32-syscalls.master linux32_syscalls.h
 
diff --git a/usr.sbin/ac/Makefile b/usr.sbin/ac/Makefile
index 46064fcf300..576dbb3323c 100644
--- a/usr.sbin/ac/Makefile
+++ b/usr.sbin/ac/Makefile
@@ -4,7 +4,7 @@ PROG=	ac
 MAN=	ac.8
 
 # Temporary, while tracking down problem wrt 64-bit time_t's on sparc64
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 CFLAGS+=-DDEBUG
 .endif
 
diff --git a/usr.sbin/amd/Makefile.inc b/usr.sbin/amd/Makefile.inc
index 673edc1b915..1965ff933e4 100644
--- a/usr.sbin/amd/Makefile.inc
+++ b/usr.sbin/amd/Makefile.inc
@@ -27,7 +27,7 @@ CFLAGS+= -DHAVE_LOCALCONFIG_H
 CFLAGS+= -DYES_HESIOD
 .endif
 
-CFLAGS+= -DHOST_CPU=\"${MACHINE_ARCH}\" -DHOST_ARCH=\"${MACHINE_ARCH}\"
+CFLAGS+= -DHOST_CPU=\"${MACHINE_CPUARCH}\" -DHOST_ARCH=\"${MACHINE_ARCH}\"
 
 .if exists(${.OBJDIR}/../libamu)
 LIBAMUDIR=	${.OBJDIR}/../libamu
diff --git a/usr.sbin/apm/Makefile b/usr.sbin/apm/Makefile
index 08ed25fce66..3cc6f5042ea 100644
--- a/usr.sbin/apm/Makefile
+++ b/usr.sbin/apm/Makefile
@@ -3,6 +3,6 @@
 PROG=	apm
 MAN=	apm.8
 MLINKS=	apm.8 apmconf.8
-MANSUBDIR= /${MACHINE_ARCH}
+MANSUBDIR= /${MACHINE_CPUARCH}
 
 .include 
diff --git a/usr.sbin/kldxref/Makefile b/usr.sbin/kldxref/Makefile
index 2f1550583cf..c877a8a57ff 100644
--- a/usr.sbin/kldxref/Makefile
+++ b/usr.sbin/kldxref/Makefile
@@ -7,8 +7,8 @@ SRCS=	kldxref.c ef.c ef_obj.c
 WARNS?=	2
 CFLAGS+=-fno-strict-aliasing
 
-.if exists(ef_${MACHINE_ARCH}.c)
-SRCS+=	ef_${MACHINE_ARCH}.c
+.if exists(ef_${MACHINE_CPUARCH}.c)
+SRCS+=	ef_${MACHINE_CPUARCH}.c
 .else
 SRCS+=	ef_nop.c
 .endif
diff --git a/usr.sbin/sade/Makefile b/usr.sbin/sade/Makefile
index bd94155595a..ad284894df0 100644
--- a/usr.sbin/sade/Makefile
+++ b/usr.sbin/sade/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.if ${MACHINE_ARCH} != "ia64"
+.if ${MACHINE_CPUARCH} != "ia64"
 _wizard=	wizard.c
 .endif
 
diff --git a/usr.sbin/sysinstall/Makefile b/usr.sbin/sysinstall/Makefile
index c9a7c8980ec..d18033aacac 100644
--- a/usr.sbin/sysinstall/Makefile
+++ b/usr.sbin/sysinstall/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-.if ${MACHINE_ARCH} != "ia64"
+.if ${MACHINE_CPUARCH} != "ia64"
 _wizard=	wizard.c
 .endif
 
diff --git a/usr.sbin/tcpdump/tcpdump/Makefile b/usr.sbin/tcpdump/tcpdump/Makefile
index 6f072b72eff..c29694388c4 100644
--- a/usr.sbin/tcpdump/tcpdump/Makefile
+++ b/usr.sbin/tcpdump/tcpdump/Makefile
@@ -46,7 +46,7 @@ SRCS+=	print-ip6.c print-ip6opts.c print-mobility.c print-ripng.c \
 	print-icmp6.c print-frag6.c print-rt6.c print-ospf6.c print-dhcp6.c
 CFLAGS+=	-DINET6
 .endif
-.if ${MACHINE_ARCH} != "i386"
+.if ${MACHINE_CPUARCH} != "i386"
 CFLAGS+=	-DLBL_ALIGN
 .endif
 

From 0c898ccd3003dd0b5403eb0f6d116a41944430d2 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 00:23:40 +0000
Subject: [PATCH 0186/1624] Mark the following static variables as __used__
 instead of __unused__: o force_to_data o __CTOR_LIST__ o
 __do_global_dtors_aux_fini_array_entry o __frame_dummy_init_array_entry

This is necessary because Clang is smart enough to optimize out these
variables was they were marked as __unused__ (and they are also static).
The end result was programs segfaulting because these symbols weren't
present.

This follows the upstream revision 159228 and the author of that
revision (Jan Hubicka ) allowed us to backport this to our
GPLv2 GCC.

Discussed with:	core
---
 contrib/gcc/crtstuff.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/contrib/gcc/crtstuff.c b/contrib/gcc/crtstuff.c
index 8fdc021d019..706528060ca 100644
--- a/contrib/gcc/crtstuff.c
+++ b/contrib/gcc/crtstuff.c
@@ -175,14 +175,14 @@ CTOR_LIST_BEGIN;
 #elif defined(CTORS_SECTION_ASM_OP)
 /* Hack: force cc1 to switch to .data section early, so that assembling
    __CTOR_LIST__ does not undo our behind-the-back change to .ctors.  */
-static func_ptr force_to_data[1] __attribute__ ((__unused__)) = { };
+static func_ptr force_to_data[1] __attribute__ ((__used__)) = { };
 asm (CTORS_SECTION_ASM_OP);
 STATIC func_ptr __CTOR_LIST__[1]
-  __attribute__ ((__unused__, aligned(sizeof(func_ptr))))
+  __attribute__ ((__used__, aligned(sizeof(func_ptr))))
   = { (func_ptr) (-1) };
 #else
 STATIC func_ptr __CTOR_LIST__[1]
-  __attribute__ ((__unused__, section(".ctors"), aligned(sizeof(func_ptr))))
+  __attribute__ ((__used__, section(".ctors"), aligned(sizeof(func_ptr))))
   = { (func_ptr) (-1) };
 #endif /* __CTOR_LIST__ alternatives */
 
@@ -308,7 +308,7 @@ __do_global_dtors_aux (void)
 CRT_CALL_STATIC_FUNCTION (FINI_SECTION_ASM_OP, __do_global_dtors_aux)
 #else /* !defined(FINI_SECTION_ASM_OP) */
 static func_ptr __do_global_dtors_aux_fini_array_entry[]
-  __attribute__ ((__unused__, section(".fini_array")))
+  __attribute__ ((__used__, section(".fini_array")))
   = { __do_global_dtors_aux };
 #endif /* !defined(FINI_SECTION_ASM_OP) */
 
@@ -348,7 +348,7 @@ frame_dummy (void)
 CRT_CALL_STATIC_FUNCTION (INIT_SECTION_ASM_OP, frame_dummy)
 #else /* defined(INIT_SECTION_ASM_OP) */
 static func_ptr __frame_dummy_init_array_entry[]
-  __attribute__ ((__unused__, section(".init_array")))
+  __attribute__ ((__used__, section(".init_array")))
   = { frame_dummy };
 #endif /* !defined(INIT_SECTION_ASM_OP) */
 #endif /* USE_EH_FRAME_REGISTRY || JCR_SECTION_NAME */
@@ -456,7 +456,7 @@ CTOR_LIST_END;
 #elif defined(CTORS_SECTION_ASM_OP)
 /* Hack: force cc1 to switch to .data section early, so that assembling
    __CTOR_LIST__ does not undo our behind-the-back change to .ctors.  */
-static func_ptr force_to_data[1] __attribute__ ((__unused__)) = { };
+static func_ptr force_to_data[1] __attribute__ ((__used__)) = { };
 asm (CTORS_SECTION_ASM_OP);
 STATIC func_ptr __CTOR_END__[1]
   __attribute__((aligned(sizeof(func_ptr))))

From b3b8bde7048030a1331a9cab204a5e79984b5d18 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Tue, 24 Aug 2010 06:11:46 +0000
Subject: [PATCH 0187/1624] Indent things consistently

PR:		149926
Submitted by:	John Hixson
---
 .../pc-sysinstall/backend-query/disk-info.sh  |   6 +-
 .../pc-sysinstall/backend-query/disk-list.sh  |  38 +-
 .../pc-sysinstall/backend-query/disk-part.sh  |  16 +-
 .../pc-sysinstall/backend-query/enable-net.sh |   4 +-
 .../backend-query/get-packages.sh             |  10 +-
 .../backend-query/list-packages.sh            |  40 +-
 .../pc-sysinstall/backend-query/set-mirror.sh |   4 +-
 .../pc-sysinstall/backend-query/test-netup.sh |   8 +-
 .../backend-query/update-part-list.sh         |  61 +--
 .../backend-query/xkeyboard-layouts.sh        |   2 +-
 .../backend-query/xkeyboard-models.sh         |   2 +-
 .../backend-query/xkeyboard-variants.sh       |   2 +-
 .../backend/functions-bsdlabel.sh             |  83 ++--
 .../backend/functions-cleanup.sh              |  46 +-
 .../pc-sysinstall/backend/functions-disk.sh   |  79 ++--
 .../backend/functions-extractimage.sh         | 176 +++----
 .../pc-sysinstall/backend/functions-ftp.sh    |  41 +-
 .../backend/functions-installcomponents.sh    |  89 ++--
 .../backend/functions-installpackages.sh      | 130 +++---
 .../backend/functions-localize.sh             | 429 +++++++++--------
 .../backend/functions-mountdisk.sh            | 169 ++++---
 .../backend/functions-mountoptical.sh         | 176 +++----
 .../backend/functions-networking.sh           |  25 +-
 .../pc-sysinstall/backend/functions-newfs.sh  | 190 ++++----
 .../backend/functions-packages.sh             | 440 +++++++++---------
 .../pc-sysinstall/backend/functions-parse.sh  |  26 +-
 .../backend/functions-unmount.sh              | 229 ++++-----
 .../backend/functions-upgrade.sh              | 100 ++--
 .../pc-sysinstall/backend/functions-users.sh  | 156 +++----
 usr.sbin/pc-sysinstall/backend/functions.sh   | 101 ++--
 usr.sbin/pc-sysinstall/backend/parseconfig.sh |   2 +-
 .../pc-sysinstall/pc-sysinstall.sh            |  40 +-
 32 files changed, 1517 insertions(+), 1403 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend-query/disk-info.sh b/usr.sbin/pc-sysinstall/backend-query/disk-info.sh
index 75b0cd4df9b..222e8c5423c 100755
--- a/usr.sbin/pc-sysinstall/backend-query/disk-info.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/disk-info.sh
@@ -54,7 +54,6 @@ HEADS="${VAL}"
 get_disk_sectors "${DISK}"
 SECS="${VAL}"
 
-
 # Now get the disks size in MB
 KB="`diskinfo -v ${1} | grep 'bytes' | cut -d '#' -f 1 | tr -s '\t' ' ' | tr -d ' '`"
 MB=$(convert_byte_to_megabyte ${KB})
@@ -62,10 +61,9 @@ MB=$(convert_byte_to_megabyte ${KB})
 # Now get the Controller Type
 CTYPE="`dmesg | grep "^${1}:" | grep "B <" | cut -d '>' -f 2 | cut -d ' ' -f 3-10`"
 
-
 echo "cylinders=${CYLS}"
 echo "heads=${HEADS}"
 echo "sectors=${SECS}"
-echo "size=$MB"
-echo "type=$CTYPE"
+echo "size=${MB}"
+echo "type=${CTYPE}"
 
diff --git a/usr.sbin/pc-sysinstall/backend-query/disk-list.sh b/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
index 4694b1a94d0..eb6b43709ba 100755
--- a/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
@@ -26,16 +26,32 @@
 # $FreeBSD$
 
 ARGS=$1
+FLAGS_MD=""
+FLAGS_VERBOSE=""
+
+shift
+while [ -n "$1" ]
+do
+  case "$1" in
+    -m)
+      FLAGS_MD=1
+      ;;
+    -v)
+      FLAGS_VERBOSE=1
+      ;;
+  esac
+  shift
+done
 
 # Create our device listing
 SYSDISK=$(sysctl -n kern.disks)
-if [ "${ARGS}" = "-m" ]
+if [ -n "${FLAGS_MD}" ]
 then
-	MDS=`mdconfig -l`
-	if [ -n "${MDS}" ]
-	then
-		SYSDISK="${SYSDISK} ${MDS}"
-	fi
+  MDS=`mdconfig -l`
+  if [ -n "${MDS}" ]
+  then
+    SYSDISK="${SYSDISK} ${MDS}"
+  fi
 fi
 
 # Now loop through these devices, and list the disk drives
@@ -47,7 +63,7 @@ do
 
   # Make sure we don't find any cd devices
   case "${DEV}" in
-     acd[0-9]*|cd[0-9]*|scd[0-9]*) continue ;;
+    acd[0-9]*|cd[0-9]*|scd[0-9]*) continue ;;
   esac
 
   # Check the dmesg output for some more info about this device
@@ -55,11 +71,17 @@ do
   if [ -z "$NEWLINE" ]; then
     NEWLINE=" "
   fi
-  if echo "${DEV}" | grep -E '^md[0-9]+' >/dev/null 2>/dev/null
+
+  if [ -n "${FLAGS_MD}" ] && echo "${DEV}" | grep -E '^md[0-9]+' >/dev/null 2>/dev/null
   then
 	NEWLINE=" "
   fi
 
+  if [ -n "${FLAGS_VERBOSE}" ]
+  then
+	:
+  fi
+
   # Save the disk list
   if [ ! -z "$DLIST" ]
   then
diff --git a/usr.sbin/pc-sysinstall/backend-query/disk-part.sh b/usr.sbin/pc-sysinstall/backend-query/disk-part.sh
index bf43358330a..900cbca8c69 100755
--- a/usr.sbin/pc-sysinstall/backend-query/disk-part.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/disk-part.sh
@@ -51,8 +51,6 @@ MB=$(convert_byte_to_megabyte ${KB})
 TOTALSIZE="$MB"
 TOTALB="`diskinfo -v ${1} | grep 'in sectors' | tr -s '\t' ' ' | cut -d ' ' -f 2`"
 
-
-
 gpart show ${1} >/dev/null 2>/dev/null
 if [ "$?" != "0" ] ; then
   # No partitions on this disk, display entire disk size and exit
@@ -85,14 +83,14 @@ do
 
   # First get the sysid / label for this partition
   if [ "$TYPE" = "MBR" ] ; then
-     get_partition_sysid_mbr "${DISK}" "${curpart}"
-     echo "${curpart}-sysid: ${VAL}"
-     get_partition_label_mbr "${DISK}" "${curpart}"
-     echo "${curpart}-label: ${VAL}"
+    get_partition_sysid_mbr "${DISK}" "${curpart}"
+    echo "${curpart}-sysid: ${VAL}"
+    get_partition_label_mbr "${DISK}" "${curpart}"
+    echo "${curpart}-label: ${VAL}"
   else
-     get_partition_label_gpt "${DISK}" "${curpart}"
-     echo "${curpart}-sysid: ${VAL}"
-     echo "${curpart}-label: ${VAL}"
+    get_partition_label_gpt "${DISK}" "${curpart}"
+    echo "${curpart}-sysid: ${VAL}"
+    echo "${curpart}-label: ${VAL}"
   fi
 
   # Now get the startblock, blocksize and MB size of this partition
diff --git a/usr.sbin/pc-sysinstall/backend-query/enable-net.sh b/usr.sbin/pc-sysinstall/backend-query/enable-net.sh
index 099840e2c3f..3c73550fa59 100755
--- a/usr.sbin/pc-sysinstall/backend-query/enable-net.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/enable-net.sh
@@ -60,6 +60,6 @@ else
 fi
 
 case ${MIRRORFETCH} in
-   ON|on|yes|YES) fetch -o /tmp/mirrors-list.txt ${MIRRORLIST} >/dev/null 2>/dev/null;;
-   *) ;;
+  ON|on|yes|YES) fetch -o /tmp/mirrors-list.txt ${MIRRORLIST} >/dev/null 2>/dev/null;;
+  *) ;;
 esac
diff --git a/usr.sbin/pc-sysinstall/backend-query/get-packages.sh b/usr.sbin/pc-sysinstall/backend-query/get-packages.sh
index ee6fb7ba105..6bdcd3b522a 100755
--- a/usr.sbin/pc-sysinstall/backend-query/get-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/get-packages.sh
@@ -34,19 +34,19 @@
 ID=`id -u`
 if [ "${ID}" -ne "0" ]
 then
-	echo "Error: must be root!" 
-	exit 1
+  echo "Error: must be root!" 
+  exit 1
 fi
 
 if [ ! -f "${PKGDIR}/INDEX" ]
 then
-	get_package_index
+  get_package_index
 fi
 
 if [ -f "${PKGDIR}/INDEX" ]
 then
-	echo "${PKGDIR}/INDEX"
-	exit 0
+  echo "${PKGDIR}/INDEX"
+  exit 0
 fi
 
 exit 1
diff --git a/usr.sbin/pc-sysinstall/backend-query/list-packages.sh b/usr.sbin/pc-sysinstall/backend-query/list-packages.sh
index b5d93f52ccb..45941ffd370 100755
--- a/usr.sbin/pc-sysinstall/backend-query/list-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/list-packages.sh
@@ -37,50 +37,50 @@ NARGS=0
 
 if [ ! -f "${PKGDIR}/INDEX" ]
 then
-	echo "Error: please fetch package index with get-packages!"
-	exit 1
+  echo "Error: please fetch package index with get-packages!"
+  exit 1
 fi
 
 if [ ! -f "${PKGDIR}/INDEX.parsed" ]
 then
-	parse_package_index
+  parse_package_index
 fi
 
 if [ -n "${PACKAGE_CATEGORY}" ]
 then
-	NARGS=$((NARGS+1))
+  NARGS=$((NARGS+1))
 fi
 
 if [ -n "${PACKAGE_NAME}" ]
 then
-	NARGS=$((NARGS+1))
+  NARGS=$((NARGS+1))
 fi
 
 if [ "${NARGS}" -eq "0" ]
 then
-	show_packages
+  show_packages
 
 elif [ "${NARGS}" -eq "1" ]
 then
 	
-	if [ "${PACKAGE_CATEGORY}" = "@INDEX@" ]
-	then
-		if [ -f "${PKGDIR}/INDEX" ]
-		then
-			echo "${PKGDIR}/INDEX"
-			exit 0
-		else
-			exit 1
-		fi
+  if [ "${PACKAGE_CATEGORY}" = "@INDEX@" ]
+  then
+    if [ -f "${PKGDIR}/INDEX" ]
+    then
+      echo "${PKGDIR}/INDEX"
+      exit 0
+    else
+      exit 1
+    fi
 		
-	else
-		show_packages_by_category "${PACKAGE_CATEGORY}"
-	fi
+  else
+    show_packages_by_category "${PACKAGE_CATEGORY}"
+  fi
 
 elif [ "${NARGS}" -eq "2" ]
 then
-	show_package_by_name "${PACKAGE_CATEGORY}" "${PACKAGE_NAME}"
+  show_package_by_name "${PACKAGE_CATEGORY}" "${PACKAGE_NAME}"
 
 else
-	show_packages
+  show_packages
 fi
diff --git a/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh b/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh
index 31c121d8443..23306bb1ba0 100755
--- a/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/set-mirror.sh
@@ -32,8 +32,8 @@ MIRROR="${1}"
 
 if [ -z "${MIRROR}" ]
 then
-	echo "Error: No mirror specified!"
-	exit 1
+  echo "Error: No mirror specified!"
+  exit 1
 fi
 
 set_ftp_mirror "${MIRROR}"
diff --git a/usr.sbin/pc-sysinstall/backend-query/test-netup.sh b/usr.sbin/pc-sysinstall/backend-query/test-netup.sh
index 25eca2cff25..4c8304ef741 100755
--- a/usr.sbin/pc-sysinstall/backend-query/test-netup.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/test-netup.sh
@@ -35,15 +35,15 @@ rm ${TMPDIR}/.testftp >/dev/null 2>/dev/null
 ping -c 2 www.pcbsd.org >/dev/null 2>/dev/null
 if [ "$?" = "0" ]
 then
-   echo "ftp: Up"
-   exit 0
+  echo "ftp: Up"
+  exit 0
 fi
 
 ping -c 2 www.freebsd.org >/dev/null 2>/dev/null
 if [ "$?" = "0" ]
 then
-   echo "ftp: Up"
-   exit 0
+  echo "ftp: Up"
+  exit 0
 fi
    
 echo "ftp: Down"
diff --git a/usr.sbin/pc-sysinstall/backend-query/update-part-list.sh b/usr.sbin/pc-sysinstall/backend-query/update-part-list.sh
index 7cc74b2c84b..54f28c6b011 100755
--- a/usr.sbin/pc-sysinstall/backend-query/update-part-list.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/update-part-list.sh
@@ -35,16 +35,17 @@ rm ${TMPDIR}/AvailUpgrades >/dev/null 2>/dev/null
 FSMNT="/mnt"
 
 # Get the freebsd version on this partition
-get_fbsd_ver() {
+get_fbsd_ver()
+{
 
   VER="`file ${FSMNT}/bin/sh | grep 'for FreeBSD' | sed 's|for FreeBSD |;|g' | cut -d ';' -f 2 | cut -d ',' -f 1`"
   if [ "$?" = "0" ] ; then
-      file ${FSMNT}/bin/sh | grep '32-bit' >/dev/null 2>/dev/null
-      if [ "${?}" = "0" ] ; then
-        echo "${1}: FreeBSD ${VER} (32bit)"
-      else
-        echo "${1}: FreeBSD ${VER} (64bit)"
-      fi
+    file ${FSMNT}/bin/sh | grep '32-bit' >/dev/null 2>/dev/null
+    if [ "${?}" = "0" ] ; then
+      echo "${1}: FreeBSD ${VER} (32bit)"
+    else
+      echo "${1}: FreeBSD ${VER} (64bit)"
+    fi
   fi
 
 }
@@ -62,7 +63,7 @@ do
   # Make sure we don't find any cd devices
   echo "${DEV}" | grep -e "^acd[0-9]" -e "^cd[0-9]" -e "^scd[0-9]" >/dev/null 2>/dev/null
   if [ "$?" != "0" ] ; then
-   DEVS="${DEVS} `ls /dev/${i}*`" 
+    DEVS="${DEVS} `ls /dev/${i}*`" 
   fi
 
 done
@@ -70,25 +71,25 @@ done
 # Search for regular UFS / Geom Partitions to upgrade
 for i in $DEVS
 do
-    if [ ! -e "${i}a.journal" -a ! -e "${i}a" -a ! -e "${i}p2" -a ! -e "${i}p2.journal" ] ; then
-	continue
-    fi
+  if [ ! -e "${i}a.journal" -a ! -e "${i}a" -a ! -e "${i}p2" -a ! -e "${i}p2.journal" ] ; then
+    continue
+  fi
 
-    if [ -e "${i}a.journal" ] ; then
-	_dsk="${i}a.journal" 
-    elif [ -e "${i}a" ] ; then
-	_dsk="${i}a" 
-    elif [ -e "${i}p2" ] ; then
-	_dsk="${i}p2" 
-    elif [ -e "${i}p2.journal" ] ; then
-	_dsk="${i}p2.journal" 
-    fi
+  if [ -e "${i}a.journal" ] ; then
+    _dsk="${i}a.journal" 
+  elif [ -e "${i}a" ] ; then
+    _dsk="${i}a" 
+  elif [ -e "${i}p2" ] ; then
+    _dsk="${i}p2" 
+  elif [ -e "${i}p2.journal" ] ; then
+    _dsk="${i}p2.journal" 
+  fi
 
-   mount -o ro ${_dsk} ${FSMNT} >>${LOGOUT} 2>>${LOGOUT}
-   if [ "${?}" = "0" -a -e "${FSMNT}/bin/sh" ] ; then
-    	get_fbsd_ver "`echo ${_dsk} | sed 's|/dev/||g'`"
-        umount -f ${FSMNT} >/dev/null 2>/dev/null
-   fi
+  mount -o ro ${_dsk} ${FSMNT} >>${LOGOUT} 2>>${LOGOUT}
+  if [ "${?}" = "0" -a -e "${FSMNT}/bin/sh" ] ; then
+    get_fbsd_ver "`echo ${_dsk} | sed 's|/dev/||g'`"
+    umount -f ${FSMNT} >/dev/null 2>/dev/null
+  fi
 done
 
 # Now search for any ZFS root partitions
@@ -101,9 +102,9 @@ umount_all_dir "${FSMNT}"
 _zps="`zpool list | grep -v 'NAME' | cut -d ' ' -f 1`"
 for _zpools in ${_zps}
 do
-   mount -o ro -t zfs ${_zpools} ${FSMNT} >>${LOGOUT} 2>>${LOGOUT}
-   if [ "${?}" = "0" -a -e "${FSMNT}/bin/sh" ] ; then
-    	get_fbsd_ver "${_zpools}"
-        umount -f ${FSMNT} >/dev/null 2>/dev/null
-   fi
+  mount -o ro -t zfs ${_zpools} ${FSMNT} >>${LOGOUT} 2>>${LOGOUT}
+  if [ "${?}" = "0" -a -e "${FSMNT}/bin/sh" ] ; then
+    get_fbsd_ver "${_zpools}"
+    umount -f ${FSMNT} >/dev/null 2>/dev/null
+  fi
 done
diff --git a/usr.sbin/pc-sysinstall/backend-query/xkeyboard-layouts.sh b/usr.sbin/pc-sysinstall/backend-query/xkeyboard-layouts.sh
index 9e2751d036e..bf63a722c38 100755
--- a/usr.sbin/pc-sysinstall/backend-query/xkeyboard-layouts.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/xkeyboard-layouts.sh
@@ -36,7 +36,7 @@ do
     echo $line | grep '! ' >/dev/null 2>/dev/null
     if [ "$?" = "0" ]
     then
-     exit 0
+      exit 0
     else 
       echo "$line"
     fi 
diff --git a/usr.sbin/pc-sysinstall/backend-query/xkeyboard-models.sh b/usr.sbin/pc-sysinstall/backend-query/xkeyboard-models.sh
index 09ba8860f92..c89811e164e 100755
--- a/usr.sbin/pc-sysinstall/backend-query/xkeyboard-models.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/xkeyboard-models.sh
@@ -36,7 +36,7 @@ do
     echo $line | grep '! ' >/dev/null 2>/dev/null
     if [ "$?" = "0" ]
     then
-     exit 0
+      exit 0
     else 
       model="`echo $line | sed 's|(|[|g'`"
       model="`echo $model | sed 's|)|]|g'`"
diff --git a/usr.sbin/pc-sysinstall/backend-query/xkeyboard-variants.sh b/usr.sbin/pc-sysinstall/backend-query/xkeyboard-variants.sh
index 818be54c504..c8c0aa5c9fe 100755
--- a/usr.sbin/pc-sysinstall/backend-query/xkeyboard-variants.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/xkeyboard-variants.sh
@@ -36,7 +36,7 @@ do
     echo $line | grep '! ' >/dev/null 2>/dev/null
     if [ "$?" = "0" ]
     then
-     exit 0
+      exit 0
     else 
       echo "$line"
     fi 
diff --git a/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh b/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
index e645263db0c..42aaec2a520 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
@@ -76,7 +76,6 @@ get_fs_line_xvars()
       return
     fi # End of ZFS block
 
-
   fi # End of xtra-options block
 
   # If we got here, set VAR to empty and export
@@ -86,30 +85,31 @@ get_fs_line_xvars()
 };
 
 # Init each zfs mirror disk with a boot sector so we can failover
-setup_zfs_mirror_parts() {
-	
-	_nZFS=""
-	# Using mirroring, setup boot partitions on each disk
-	_mirrline="`echo ${1} | sed 's|mirror ||g'`"
-	for _zvars in $_mirrline
-	do
-		echo "Looping through _zvars: $_zvars" >>${LOGOUT}
-		echo "$_zvars" | grep "${2}" >/dev/null 2>/dev/null
-		if [ "$?" = "0" ] ; then continue ; fi
-		if [ -z "$_zvars" ] ; then continue ; fi
+setup_zfs_mirror_parts()
+{
+  _nZFS=""
 
-		is_disk "$_zvars" >/dev/null 2>/dev/null
-		if [ "$?" = "0" ] ; then
-		echo "Setting up ZFS mirror disk $_zvars" >>${LOGOUT}
-		init_gpt_full_disk "$_zvars" >/dev/null 2>/dev/null
-          	rc_halt "gpart bootcode -p /boot/gptzfsboot -i 1 ${_zvars}" >/dev/null 2>/dev/null
-          	rc_halt "gpart add -t freebsd-zfs ${_zvars}" >/dev/null 2>/dev/null
-			_nZFS="$_nZFS ${_zvars}p2"	
-		else
-			_nZFS="$_nZFS ${_zvars}"	
-		fi	
-	done
-	echo "mirror $2 `echo $_nZFS | tr -s ' '`"
+  # Using mirroring, setup boot partitions on each disk
+  _mirrline="`echo ${1} | sed 's|mirror ||g'`"
+  for _zvars in $_mirrline
+  do
+    echo "Looping through _zvars: $_zvars" >>${LOGOUT}
+    echo "$_zvars" | grep "${2}" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ] ; then continue ; fi
+    if [ -z "$_zvars" ] ; then continue ; fi
+
+    is_disk "$_zvars" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ] ; then
+      echo "Setting up ZFS mirror disk $_zvars" >>${LOGOUT}
+      init_gpt_full_disk "$_zvars" >/dev/null 2>/dev/null
+      rc_halt "gpart bootcode -p /boot/gptzfsboot -i 1 ${_zvars}" >/dev/null 2>/dev/null
+      rc_halt "gpart add -t freebsd-zfs ${_zvars}" >/dev/null 2>/dev/null
+      _nZFS="$_nZFS ${_zvars}p2"	
+    else
+      _nZFS="$_nZFS ${_zvars}"	
+    fi	
+  done
+  echo "mirror $2 `echo $_nZFS | tr -s ' '`"
 } ;
 
 # Function which creates a unique label name for the specified mount
@@ -161,7 +161,6 @@ gen_glabel_name()
 # Function to setup / stamp a legacy MBR bsdlabel
 setup_mbr_partitions()
 {
-
   DISKTAG="$1"
   WRKSLICE="$2"
   FOUNDPARTS="1"
@@ -218,7 +217,7 @@ setup_mbr_partitions()
           
       # Now check that these values are sane
       case $FS in
-       UFS|UFS+S|UFS+J|ZFS|SWAP) ;;
+        UFS|UFS+S|UFS+J|ZFS|SWAP) ;;
        *) exit_err "ERROR: Invalid file system specified on $line" ;;
       esac
 
@@ -316,16 +315,16 @@ setup_mbr_partitions()
 
       # This partition letter is used, get the next one
       case ${PARTLETTER} in
-          a) PARTLETTER="b" ;;
-          b) # When we hit b, add the special c: setup for bsdlabel 
-             echo "c:	*	*	unused" >>${BSDLABEL}
-             PARTLETTER="d" ;;
-          d) PARTLETTER="e" ;;
-          e) PARTLETTER="f" ;;
-          f) PARTLETTER="g" ;;
-          g) PARTLETTER="h" ;;
-          h) PARTLETTER="ERR" ;;
-          *) exit_err "ERROR: bsdlabel only supports up to letter h for partitions." ;;
+        a) PARTLETTER="b" ;;
+        b) # When we hit b, add the special c: setup for bsdlabel 
+           echo "c:	*	*	unused" >>${BSDLABEL}
+           PARTLETTER="d" ;;
+        d) PARTLETTER="e" ;;
+        e) PARTLETTER="f" ;;
+        f) PARTLETTER="g" ;;
+        g) PARTLETTER="h" ;;
+        h) PARTLETTER="ERR" ;;
+        *) exit_err "ERROR: bsdlabel only supports up to letter h for partitions." ;;
       esac
 
     fi # End of subsection locating a slice in config
@@ -402,7 +401,7 @@ setup_gpt_partitions()
           
       # Now check that these values are sane
       case $FS in
-       UFS|UFS+S|UFS+J|ZFS|SWAP) ;;
+        UFS|UFS+S|UFS+J|ZFS|SWAP) ;;
        *) exit_err "ERROR: Invalid file system specified on $line" ;;
       esac
 
@@ -464,9 +463,9 @@ setup_gpt_partitions()
 
       # Figure out the gpart type to use
       case ${FS} in
-          ZFS) PARTYPE="freebsd-zfs" ;;
-         SWAP) PARTYPE="freebsd-swap" ;;
-            *) PARTYPE="freebsd-ufs" ;;
+        ZFS) PARTYPE="freebsd-zfs" ;;
+        SWAP) PARTYPE="freebsd-swap" ;;
+        *) PARTYPE="freebsd-ufs" ;;
       esac
 
       # Create the partition
@@ -507,8 +506,8 @@ setup_gpt_partitions()
       # If this is the boot disk, stamp the right gptboot
       if [ ! -z "${BOOTTYPE}" ] ; then
         case ${BOOTTYPE} in
-           freebsd-ufs) rc_halt "gpart bootcode -p /boot/gptboot -i 1 ${DISK}" ;;
-           freebsd-zfs) rc_halt "gpart bootcode -p /boot/gptzfsboot -i 1 ${DISK}" ;;
+          freebsd-ufs) rc_halt "gpart bootcode -p /boot/gptboot -i 1 ${DISK}" ;;
+          freebsd-zfs) rc_halt "gpart bootcode -p /boot/gptzfsboot -i 1 ${DISK}" ;;
         esac 
       fi
 
diff --git a/usr.sbin/pc-sysinstall/backend/functions-cleanup.sh b/usr.sbin/pc-sysinstall/backend/functions-cleanup.sh
index f7eedf5996b..56e5389e3e3 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-cleanup.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-cleanup.sh
@@ -166,8 +166,8 @@ setup_fstab()
     # Set mount options for file-systems
     case $PARTFS in
       UFS+J) MNTOPTS="rw,noatime,async" ;;
-       SWAP) MNTOPTS="sw" ;;
-          *) MNTOPTS="rw,noatime" ;;
+      SWAP) MNTOPTS="sw" ;;
+      *) MNTOPTS="rw,noatime" ;;
     esac
 
 
@@ -391,30 +391,28 @@ set_root_pw()
 
 run_final_cleanup()
 {
+  # Check if we need to run any gmirror setup
+  ls ${MIRRORCFGDIR}/* >/dev/null 2>/dev/null
+  if [ "$?" = "0" ]
+  then
+    # Lets setup gmirror now
+    setup_gmirror
+  fi
 
- # Check if we need to run any gmirror setup
- ls ${MIRRORCFGDIR}/* >/dev/null 2>/dev/null
- if [ "$?" = "0" ]
- then
-   # Lets setup gmirror now
-   setup_gmirror
- fi
+  # Check if we need to save any geli keys
+  ls ${GELIKEYDIR}/* >/dev/null 2>/dev/null
+  if [ "$?" = "0" ]
+  then
+    # Lets setup geli loading
+    setup_geli_loading
+  fi
 
- # Check if we need to save any geli keys
- ls ${GELIKEYDIR}/* >/dev/null 2>/dev/null
- if [ "$?" = "0" ]
- then
-   # Lets setup geli loading
-   setup_geli_loading
- fi
+  # Set a hostname on the install system
+  setup_hostname
 
- # Set a hostname on the install system
- setup_hostname
-
- # Set the root_pw if it is specified
- set_root_pw
-
- # Generate the fstab for the installed system
- setup_fstab
+  # Set the root_pw if it is specified
+  set_root_pw
 
+  # Generate the fstab for the installed system
+  setup_fstab
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-disk.sh b/usr.sbin/pc-sysinstall/backend/functions-disk.sh
index bcce58ed20f..6416fe1a478 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-disk.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-disk.sh
@@ -28,13 +28,14 @@
 # Functions related to disk operations using gpart
 
 # See if device is a full disk or partition/slice
-is_disk() {
-	for _dsk in `sysctl -n kern.disks`
-	do
-		if [ "$_dsk" = "${1}" ] ; then return 0 ; fi
-	done
+is_disk()
+{
+  for _dsk in `sysctl -n kern.disks`
+  do
+    if [ "$_dsk" = "${1}" ] ; then return 0 ; fi
+  done
 
-	return 1
+  return 1
 }
 
 # Get a MBR partitions sysid
@@ -190,9 +191,9 @@ get_disk_partitions()
   for i in ${SLICES}
   do
     case $type in
-       MBR) name="${1}s${i}" ;;
-       GPT) name="${1}p${i}";;
-       *) name="${1}s${i}";;
+      MBR) name="${1}s${i}" ;;
+      GPT) name="${1}p${i}";;
+      *) name="${1}s${i}";;
     esac
     if [ -z "${RSLICES}" ]
     then
@@ -226,8 +227,19 @@ get_disk_heads()
   VAL="${head}" ; export VAL
 };
 
+# Function which returns a target disks mediasize in sectors
+get_disk_mediasize()
+{
+  mediasize=`diskinfo -v ${1} | grep "# mediasize in sectors" | tr -s ' ' | cut -f 2`
+
+  # Not sure why this is, memory disks need it though.
+  mediasize=`expr ${mediasize} - 10`
+  VAL="${mediasize}" ; export VAL
+};
+
 # Function which exports all zpools, making them safe to overwrite potentially
-export_all_zpools() {
+export_all_zpools()
+{
   # Export any zpools
   for i in `zpool list -H -o name`
   do
@@ -434,20 +446,30 @@ setup_disk_slice()
        if [ ! -z "${DISK}" -a ! -z "${PTYPE}" ]
        then
          case ${PTYPE} in
-               all|ALL) if [ "$PSCHEME" = "MBR" -o -z "$PSCHEME" ] ; then
-			  PSCHEME="MBR"
-			  tmpSLICE="${DISK}s1"  
-			else
-			  tmpSLICE="${DISK}p1"  
-			fi
-                        run_gpart_full "${DISK}" "${BMANAGER}" "${PSCHEME}" ;;
-           s1|s2|s3|s4) tmpSLICE="${DISK}${PTYPE}" 
-                        # Get the number of the slice we are working on
-                        s="`echo ${PTYPE} | awk '{print substr($0,length,1)}'`" 
-                        run_gpart_slice "${DISK}" "${BMANAGER}" "${s}" ;;
-                 free|FREE) tmpSLICE="${DISK}s${LASTSLICE}"
-                        run_gpart_free "${DISK}" "${LASTSLICE}" "${BMANAGER}" ;;
-                     *) exit_err "ERROR: Unknown PTYPE: $PTYPE" ;;
+           all|ALL)
+		     if [ "$PSCHEME" = "MBR" -o -z "$PSCHEME" ] ; then
+               PSCHEME="MBR"
+               tmpSLICE="${DISK}s1"  
+			 else
+               tmpSLICE="${DISK}p1"  
+			 fi
+
+             run_gpart_full "${DISK}" "${BMANAGER}" "${PSCHEME}"
+			 ;;
+
+           s1|s2|s3|s4)
+			 tmpSLICE="${DISK}${PTYPE}" 
+             # Get the number of the slice we are working on
+             s="`echo ${PTYPE} | awk '{print substr($0,length,1)}'`" 
+             run_gpart_slice "${DISK}" "${BMANAGER}" "${s}"
+			 ;;
+
+           free|FREE)
+			 tmpSLICE="${DISK}s${LASTSLICE}"
+             run_gpart_free "${DISK}" "${LASTSLICE}" "${BMANAGER}"
+			 ;;
+
+           *) exit_err "ERROR: Unknown PTYPE: $PTYPE" ;;
          esac
 
          # Now save which disk this is, so we can parse it later during slice partition setup
@@ -478,7 +500,8 @@ setup_disk_slice()
 };
 
 # Stop all gjournals on disk / slice
-stop_gjournal() {
+stop_gjournal()
+{
   _gdsk="$1"
   # Check if we need to shutdown any journals on this drive
   ls /dev/${_gdsk}*.journal >/dev/null 2>/dev/null
@@ -565,7 +588,11 @@ init_mbr_full_disk()
   # Multiply them all together to get our total blocks
   totalblocks="`expr ${cyl} \* ${head}`"
   totalblocks="`expr ${totalblocks} \* ${sec}`"
-
+  if [ -z "${totalblocks}" ]
+  then
+	get_disk_mediasize "${_intDISK}"
+	totalblocks="${VAL}"
+  fi
 
   # Now set the ending block to the total disk block size
   sizeblock="`expr ${totalblocks} - ${startblock}`"
diff --git a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
index 54a742bcf6f..72a30fb43cd 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
@@ -54,39 +54,41 @@ start_extract_uzip_tar()
   echo_log "pc-sysinstall: Starting Extraction"
 
   case ${PACKAGETYPE} in
-   uzip) # Start by mounting the uzip image
-         MDDEVICE=`mdconfig -a -t vnode -o readonly -f ${INSFILE}`
-         mkdir -p ${FSMNT}.uzip
-         mount -r /dev/${MDDEVICE}.uzip ${FSMNT}.uzip
-         if [ "$?" != "0" ]
-         then
-           exit_err "ERROR: Failed mounting the ${INSFILE}"
-         fi
-         cd ${FSMNT}.uzip
+    uzip)
+	  # Start by mounting the uzip image
+      MDDEVICE=`mdconfig -a -t vnode -o readonly -f ${INSFILE}`
+      mkdir -p ${FSMNT}.uzip
+      mount -r /dev/${MDDEVICE}.uzip ${FSMNT}.uzip
+      if [ "$?" != "0" ]
+      then
+        exit_err "ERROR: Failed mounting the ${INSFILE}"
+      fi
+      cd ${FSMNT}.uzip
 
-         # Copy over all the files now!
-         tar cvf - . 2>/dev/null | tar -xpv -C ${FSMNT} ${TAROPTS} -f - 2>&1 | tee -a ${FSMNT}/.tar-extract.log
-         if [ "$?" != "0" ]
-         then
-           cd /
-           echo "TAR failure occured:" >>${LOGOUT}
-           cat ${FSMNT}/.tar-extract.log | grep "tar:" >>${LOGOUT}
-           umount ${FSMNT}.uzip
-           mdconfig -d -u ${MDDEVICE}
-           exit_err "ERROR: Failed extracting the tar image"
-         fi
+      # Copy over all the files now!
+      tar cvf - . 2>/dev/null | tar -xpv -C ${FSMNT} ${TAROPTS} -f - 2>&1 | tee -a ${FSMNT}/.tar-extract.log
+      if [ "$?" != "0" ]
+      then
+        cd /
+        echo "TAR failure occured:" >>${LOGOUT}
+        cat ${FSMNT}/.tar-extract.log | grep "tar:" >>${LOGOUT}
+        umount ${FSMNT}.uzip
+        mdconfig -d -u ${MDDEVICE}
+        exit_err "ERROR: Failed extracting the tar image"
+      fi
 
-         # All finished, now lets umount and cleanup
-         cd /
-         umount ${FSMNT}.uzip
-         mdconfig -d -u ${MDDEVICE}
-         ;;
-    tar) tar -xpv -C ${FSMNT} -f ${INSFILE} ${TAROPTS} >&1 2>&1
-         if [ "$?" != "0" ]
-         then
-           exit_err "ERROR: Failed extracting the tar image"
-         fi
-         ;;
+      # All finished, now lets umount and cleanup
+      cd /
+      umount ${FSMNT}.uzip
+      mdconfig -d -u ${MDDEVICE}
+       ;;
+    tar)
+	  tar -xpv -C ${FSMNT} -f ${INSFILE} ${TAROPTS} >&1 2>&1
+      if [ "$?" != "0" ]
+      then
+        exit_err "ERROR: Failed extracting the tar image"
+      fi
+      ;;
   esac
 
   # Check if this was a FTP download and clean it up now
@@ -120,10 +122,10 @@ start_extract_split()
   DIRS=`ls -d ${INSDIR}/*|grep -Ev '(uzip|kernels|src)'`
   for dir in ${DIRS}
   do
-	cd "${dir}"
-	if [ -f "install.sh" ]
-	then
-	  echo_log "Extracting" `basename ${dir}`
+    cd "${dir}"
+    if [ -f "install.sh" ]
+    then
+      echo_log "Extracting" `basename ${dir}`
       echo "y" | sh install.sh >/dev/null
       if [ "$?" != "0" ]
       then
@@ -139,13 +141,13 @@ start_extract_split()
   cd "${KERNELS}"
   if [ -f "install.sh" ]
   then
-	echo_log "Extracting" `basename ${KERNELS}`
+    echo_log "Extracting" `basename ${KERNELS}`
     echo "y" | sh install.sh generic >/dev/null
     if [ "$?" != "0" ]
     then
       exit_err "ERROR: Failed extracting ${KERNELS}"
     fi
-	echo 'kernel="GENERIC"' > "${FSMNT}/boot/loader.conf"
+    mv "${FSMNT}/boot/GENERIC" "${FSMNT}/boot/kernel"
   else
     exit_err "ERROR: ${KERNELS}/install.sh does not exist"
   fi
@@ -155,7 +157,7 @@ start_extract_split()
   cd "${SOURCE}"
   if [ -f "install.sh" ]
   then
-	echo_log "Extracting" `basename ${SOURCE}`
+    echo_log "Extracting" `basename ${SOURCE}`
     echo "y" | sh install.sh all >/dev/null
     if [ "$?" != "0" ]
     then
@@ -206,14 +208,14 @@ fetch_install_file()
 # Function which will download freebsd install files
 fetch_split_files()
 {
-  get_value_from_cfg ftpHost
+  get_ftpHost
   if [ -z "$VAL" ]
   then
     exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
   fi
   FTPHOST="${VAL}"
 
-  get_value_from_cfg ftpDir
+  get_ftpDir
   if [ -z "$VAL" ]
   then
     exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
@@ -228,6 +230,18 @@ fetch_split_files()
     OUTFILE="${FSMNT}/.fetch-${INSFILE}"
   fi
 
+  DIRS="base catpages dict doc games info manpages proflibs kernels src"
+  if [ "${FBSD_ARCH}" = "amd64" ]
+  then
+    DIRS="${DIRS} lib32"
+  fi
+
+  for d in ${DIRS}
+  do
+    mkdir -p "${OUTFILE}/${d}"
+  done
+
+
   NETRC="${OUTFILE}/.netrc"
   cat<"${NETRC}"
 machine ${FTPHOST}
@@ -238,22 +252,16 @@ bin
 prompt
 EOF
 
-  DIRS="base catpages dict doc games info manpages proflibs kernels src"
-  if [ "${FBSD_ARCH}" = "amd64" ]
-  then
-	DIRS="${DIRS} lib32"
-  fi
-
   for d in ${DIRS}
   do
-	cat<>"${NETRC}"
+    cat<>"${NETRC}"
 cd ${FTPDIR}/${d}
 lcd ${OUTFILE}/${d}
 mreget *
 EOF
   done
 
-	cat<>"${NETRC}"
+  cat<>"${NETRC}"
 bye
 
 
@@ -335,19 +343,19 @@ init_extraction()
     if [ "$INSTALLTYPE" = "FreeBSD" ]
     then
       case $PACKAGETYPE in
-         uzip) INSFILE="${FBSD_UZIP_FILE}" ;;
-          tar) INSFILE="${FBSD_TAR_FILE}" ;;
-		  split)
-			INSDIR="${FBSD_BRANCH_DIR}"
+        uzip) INSFILE="${FBSD_UZIP_FILE}" ;;
+        tar) INSFILE="${FBSD_TAR_FILE}" ;;
+        split)
+          INSDIR="${FBSD_BRANCH_DIR}"
 
-			# This is to trick opt_mount into not failing
-			INSFILE="${INSDIR}"
-			;;
+          # This is to trick opt_mount into not failing
+          INSFILE="${INSDIR}"
+          ;;
       esac
     else
       case $PACKAGETYPE in
-         uzip) INSFILE="${UZIP_FILE}" ;;
-          tar) INSFILE="${TAR_FILE}" ;;
+        uzip) INSFILE="${UZIP_FILE}" ;;
+        tar) INSFILE="${TAR_FILE}" ;;
       esac
     fi
     export INSFILE
@@ -355,33 +363,37 @@ init_extraction()
 
   # Lets start by figuring out what medium we are using
   case ${INSTALLMEDIUM} in
- dvd|usb) # Lets start by mounting the disk 
-          opt_mount 
-		  if [ ! -z "${INSDIR}" ]
-		  then
-          	INSDIR="${CDMNT}/${INSDIR}" ; export INSDIR
-			start_extract_split
+    dvd|usb)
+      # Lets start by mounting the disk 
+      opt_mount 
+      if [ ! -z "${INSDIR}" ]
+      then
+        INSDIR="${CDMNT}/${INSDIR}" ; export INSDIR
+	    start_extract_split
 
-		  else
-          	INSFILE="${CDMNT}/${INSFILE}" ; export INSFILE
-          	start_extract_uzip_tar
-		  fi
-          ;;
-     ftp)
-		  if [ "$PACKAGETYPE" = "split" ]
-		  then
-			fetch_split_files
+      else
+        INSFILE="${CDMNT}/${INSFILE}" ; export INSFILE
+        start_extract_uzip_tar
+      fi
+      ;;
 
-			INSDIR="${INSFILE}" ; export INSDIR
-			start_extract_split
-		  else
-          	fetch_install_file
-          	start_extract_uzip_tar 
-		  fi
-          ;;
-     rsync) start_rsync_copy
-            ;;
-       *) exit_err "ERROR: Unknown install medium" ;;
+    ftp|sftp)
+      if [ "$PACKAGETYPE" = "split" ]
+      then
+        fetch_split_files
+
+        INSDIR="${INSFILE}" ; export INSDIR
+        start_extract_split
+      else
+        fetch_install_file
+        start_extract_uzip_tar 
+      fi
+      ;;
+
+      rsync) start_rsync_copy ;;
+    img)
+		;;
+    *) exit_err "ERROR: Unknown install medium" ;;
   esac
 
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-ftp.sh b/usr.sbin/pc-sysinstall/backend/functions-ftp.sh
index 3bf95a8cde4..db230f3bf1a 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-ftp.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-ftp.sh
@@ -280,20 +280,43 @@ show_mirrors()
 
 set_ftp_mirror()
 {
-	MIRROR="${1}"
-	echo "${MIRROR}" > "${CONFDIR}/mirrors.conf"
+  MIRROR="${1}"
+  echo "${MIRROR}" > "${CONFDIR}/mirrors.conf"
 };
 
 get_ftp_mirror()
 {
-	MIRROR="${DEFAULT_FTP_SERVER}"
-	if [ -f "${CONFDIR}/mirrors.conf" ]
-	then
-		MIRROR=`cat "${CONFDIR}/mirrors.conf"`
-	fi
+  MIRROR="${DEFAULT_FTP_SERVER}"
+  if [ -f "${CONFDIR}/mirrors.conf" ]
+  then
+    MIRROR=`cat "${CONFDIR}/mirrors.conf"`
+  fi
 
-	VAL="${MIRROR}"
-	export VAL
+  VAL="${MIRROR}"
+  export VAL
+};
+
+
+get_ftpHost()
+{
+  get_value_from_cfg ftpPath
+  ftpPath="$VAL"
+
+  ftpHost=`echo "${ftpPath}" | sed -E 's|^(ftp://)([^/]*)(.*)|\2|'`
+  VAL="${ftpHost}"
+
+  export VAL
+};
+
+get_ftpDir()
+{
+  get_value_from_cfg ftpPath
+  ftpPath="$VAL"
+
+  ftpDir=`echo "${ftpPath}" | sed -E 's|^(ftp://)([^/]*)(.*)|\3|'`
+  VAL="${ftpDir}"
+
+  export VAL
 };
 
 get_ftp_mirrors()
diff --git a/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh b/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh
index 851caab78bb..e8beeda05ee 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh
@@ -52,23 +52,25 @@ copy_component()
     CFILEMD5="`echo $line | cut -d ':' -f 2`"
     CFILE2MD5="`echo $line | cut -d ':' -f 3`"
 
-
     case ${INSTALLMEDIUM} in
-   dvd|usb) # On both dvd / usb, we can just copy the file
-            cp ${CDMNT}/${COMPFILEDIR}/${SUBDIR}/${CFILE} \
-		 ${FSMNT}/${COMPTMPDIR} >>${LOGOUT} 2>>${LOGOUT}
+      dvd|usb)
+        # On both dvd / usb, we can just copy the file
+        cp ${CDMNT}/${COMPFILEDIR}/${SUBDIR}/${CFILE} \
+		  ${FSMNT}/${COMPTMPDIR} >>${LOGOUT} 2>>${LOGOUT}
 	    RESULT="$?"
-            ;;
-       ftp) get_value_from_cfg ftpPath
-            if [ -z "$VAL" ]
-            then
-              exit_err "ERROR: Install medium was set to ftp, but no ftpPath was provided!"
-            fi
-            FTPPATH="${VAL}" 
+        ;;
 
-            fetch_file "${FTPPATH}/${COMPFILEDIR}/${SUBDIR}/${CFILE}" "${FSMNT}/${COMPTMPDIR}/${CFILE}" "0"
-	    RESULT="$?"
-            ;;
+      ftp|sftp)
+        get_value_from_cfg ftpPath
+        if [ -z "$VAL" ]
+        then
+          exit_err "ERROR: Install medium was set to ftp, but no ftpPath was provided!"
+        fi
+        FTPPATH="${VAL}" 
+
+        fetch_file "${FTPPATH}/${COMPFILEDIR}/${SUBDIR}/${CFILE}" "${FSMNT}/${COMPTMPDIR}/${CFILE}" "0"
+        RESULT="$?"
+       ;;
     esac
 
     if [ "${RESULT}" != "0" ]
@@ -120,47 +122,44 @@ export CFILE
 sh ${COMPTMPDIR}/install.sh
 
 " >${FSMNT}/.componentwrapper.sh
-   chmod 755 ${FSMNT}/.componentwrapper.sh
+  chmod 755 ${FSMNT}/.componentwrapper.sh
    
-   # Copy over the install script for this component
-   cp ${COMPDIR}/${COMPONENT}/install.sh ${FSMNT}/${COMPTMPDIR}/
-
-   echo_log "INSTALL COMPONENT: ${i}"
-   chroot ${FSMNT} /.componentwrapper.sh >>${LOGOUT} 2>>${LOGOUT}
-   rm ${FSMNT}/.componentwrapper.sh
+  # Copy over the install script for this component
+  cp ${COMPDIR}/${COMPONENT}/install.sh ${FSMNT}/${COMPTMPDIR}/
 
+  echo_log "INSTALL COMPONENT: ${i}"
+  chroot ${FSMNT} /.componentwrapper.sh >>${LOGOUT} 2>>${LOGOUT}
+  rm ${FSMNT}/.componentwrapper.sh
 
 };
 
 # Check for any modules specified, and begin loading them
 install_components()
 {
-   # First, lets check and see if we even have any optional modules
-   get_value_from_cfg installComponents
-   if [ ! -z "${VAL}" ]
-   then
-      # Lets start by cleaning up the string and getting it ready to parse
-      strip_white_space ${VAL}
-      COMPONENTS=`echo ${VAL} | sed -e "s|,| |g"`
-      for i in $COMPONENTS
-      do
-        if [ ! -e "${COMPDIR}/${i}/install.sh" -o ! -e "${COMPDIR}/${i}/distfiles" ]
-        then
-	  echo_log "WARNING: Component ${i} doesn't seem to exist"
-        else
+  # First, lets check and see if we even have any optional modules
+  get_value_from_cfg installComponents
+  if [ ! -z "${VAL}" ]
+  then
+    # Lets start by cleaning up the string and getting it ready to parse
+    strip_white_space ${VAL}
+    COMPONENTS=`echo ${VAL} | sed -e "s|,| |g"`
+    for i in $COMPONENTS
+    do
+      if [ ! -e "${COMPDIR}/${i}/install.sh" -o ! -e "${COMPDIR}/${i}/distfiles" ]
+      then
+        echo_log "WARNING: Component ${i} doesn't seem to exist"
+      else
 
-          # Make the tmpdir on the disk
-          mkdir -p ${FSMNT}/${COMPTMPDIR} >>${LOGOUT} 2>>${LOGOUT}
+        # Make the tmpdir on the disk
+        mkdir -p ${FSMNT}/${COMPTMPDIR} >>${LOGOUT} 2>>${LOGOUT}
 
-          # Start by grabbing the component files
-          copy_component ${i}
+        # Start by grabbing the component files
+        copy_component ${i}
 
-          # Remove the tmpdir now
-          rm -rf ${FSMNT}/${COMPTMPDIR} >>${LOGOUT} 2>>${LOGOUT}
-
-        fi
-      done
-
-   fi
+        # Remove the tmpdir now
+        rm -rf ${FSMNT}/${COMPTMPDIR} >>${LOGOUT} 2>>${LOGOUT}
+      fi
+    done
+  fi
 
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh b/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
index e967011d64f..3e0a4ba0670 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-installpackages.sh
@@ -33,93 +33,93 @@
 # Recursively determine all dependencies for this package
 determine_package_dependencies()
 {
-	local PKGNAME="${1}"
-	local DEPFILE="${2}"
+  local PKGNAME="${1}"
+  local DEPFILE="${2}"
 
-	grep "${PKGNAME}" "${DEPFILE}" >/dev/null
-	if [ "$?" -ne "0" ]
-	then
-		echo "${PKGNAME}" >> "${DEPFILE}"
-		get_package_dependencies "${PKGNAME}" "1"
-		local DEPS="${VAL}"
+  grep "${PKGNAME}" "${DEPFILE}" >/dev/null
+  if [ "$?" -ne "0" ]
+  then
+    echo "${PKGNAME}" >> "${DEPFILE}"
+    get_package_dependencies "${PKGNAME}" "1"
 
-		for d in ${DEPS}
-		do
-			determine_package_dependencies "${d}" "${DEPFILE}"
-		done
-	fi
+    local DEPS="${VAL}"
+    for d in ${DEPS}
+    do
+      determine_package_dependencies "${d}" "${DEPFILE}"
+    done
+  fi
 };
 
 # Fetch packages dependencies from a file
 fetch_package_dependencies()
 {
-	local DEPFILE
-	local DEPS
-	local SAVEDIR
+  local DEPFILE
+  local DEPS
+  local SAVEDIR
 
-	DEPFILE="${1}"
-	DEPS=`cat "${DEPFILE}"`
-	SAVEDIR="${2}"
+  DEPFILE="${1}"
+  DEPS=`cat "${DEPFILE}"`
+  SAVEDIR="${2}"
 
-	for d in ${DEPS}
-	do
-		get_package_short_name "${d}"
-		SNAME="${VAL}"
+  for d in ${DEPS}
+  do
+    get_package_short_name "${d}"
+    SNAME="${VAL}"
 
-		get_package_category "${SNAME}"
-		CATEGORY="${VAL}"
+    get_package_category "${SNAME}"
+    CATEGORY="${VAL}"
 
-		fetch_package "${CATEGORY}" "${d}" "${SAVEDIR}"
-	done
+    fetch_package "${CATEGORY}" "${d}" "${SAVEDIR}"
+  done
 };
 
 # Check for any packages specified, and begin loading them
 install_packages()
 {
-   # First, lets check and see if we even have any packages to install
-	get_value_from_cfg installPackages
-	if [ ! -z "${VAL}" ]
-	then
-	  HERE=`pwd`
-	  rc_nohalt "mkdir -p ${FSMNT}/${PKGTMPDIR}"
-	  rc_nohalt "cd ${FSMNT}/${PKGTMPDIR}"
+  # First, lets check and see if we even have any packages to install
+  get_value_from_cfg installPackages
+  if [ ! -z "${VAL}" ]
+  then
+    HERE=`pwd`
+    rc_nohalt "mkdir -p ${FSMNT}/${PKGTMPDIR}"
+    rc_nohalt "cd ${FSMNT}/${PKGTMPDIR}"
 
-	  if [ ! -f "${CONFDIR}/INDEX" ]
-	  then
-		get_package_index
-	  fi
+    if [ ! -f "${CONFDIR}/INDEX" ]
+    then
+      get_package_index
+    fi
 
-	  if [ ! -f "${CONFDIR}/INDEX.parsed" ]
-	  then
-		parse_package_index
-	  fi
+    if [ ! -f "${CONFDIR}/INDEX.parsed" ]
+    then
+      parse_package_index
+    fi
 
-      # Lets start by cleaning up the string and getting it ready to parse
-      strip_white_space ${VAL}
-      PACKAGES=`echo ${VAL} | sed -e "s|,| |g"`
-      for i in $PACKAGES
-	  do
-		if get_package_name "${i}"
-		then
-			PKGNAME="${VAL}"
-			DEPFILE="${FSMNT}/${PKGTMPDIR}/.${PKGNAME}.deps"
+    # Lets start by cleaning up the string and getting it ready to parse
+    strip_white_space ${VAL}
+    PACKAGES=`echo ${VAL} | sed -e "s|,| |g"`
+    for i in $PACKAGES
+    do
+      if get_package_name "${i}"
+      then
+        PKGNAME="${VAL}"
+        DEPFILE="${FSMNT}/${PKGTMPDIR}/.${PKGNAME}.deps"
 
-			rc_nohalt "touch ${DEPFILE}"
-			determine_package_dependencies "${PKGNAME}" "${DEPFILE}"
-			fetch_package_dependencies "${DEPFILE}" "${FSMNT}/${PKGTMPDIR}"
+        rc_nohalt "touch ${DEPFILE}"
+        determine_package_dependencies "${PKGNAME}" "${DEPFILE}"
+        fetch_package_dependencies "${DEPFILE}" "${FSMNT}/${PKGTMPDIR}"
 
-			# If the package is not already installed, install it!
-			if ! run_chroot_cmd "pkg_info -e ${PKGNAME}"
-			then
-				rc_nohalt "pkg_add -C ${FSMNT} ${PKGTMPDIR}/${PKGNAME}.tbz"
-			fi
+        # If the package is not already installed, install it!
+        if ! run_chroot_cmd "pkg_info -e ${PKGNAME}"
+        then
+          rc_nohalt "pkg_add -C ${FSMNT} ${PKGTMPDIR}/${PKGNAME}.tbz"
+        fi
 
-			rc_nohalt "rm ${DEPFILE}"
-		fi
+        rc_nohalt "rm ${DEPFILE}"
+      fi
 
-		rc_nohalt "cd ${HERE}"
-	  done
+      rc_nohalt "cd ${HERE}"
+    done
 
-	  #rm -rf "${FSMNT}/${PKGTMPDIR}"
-	fi
+  rm -rf "${FSMNT}/${PKGTMPDIR}"
+  fi
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-localize.sh b/usr.sbin/pc-sysinstall/backend/functions-localize.sh
index 42617da9c41..fd14e8cc2a7 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-localize.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-localize.sh
@@ -63,66 +63,66 @@ localize_pcbsd()
 
 localize_x_keyboard()
 {
-   KEYMOD="$1"
-   KEYLAY="$2"
-   KEYVAR="$3"
-   COUNTRY="$4"
-   OPTION="grp:alt_shift_toggle"
-   SETXKBMAP=""
+  KEYMOD="$1"
+  KEYLAY="$2"
+  KEYVAR="$3"
+  COUNTRY="$4"
+  OPTION="grp:alt_shift_toggle"
+  SETXKBMAP=""
 
-   if [ "${COUNTRY}" = "NONE" -o "${COUNTRY}" = "us" -o "${COUNTRY}" = "C" ] ; then
-     #In this case we don't need any additional language
-     COUNTRY=""
-     OPTION=""
-   else
-     COUNTRY=",${COUNTRY}"
-   fi
+  if [ "${COUNTRY}" = "NONE" -o "${COUNTRY}" = "us" -o "${COUNTRY}" = "C" ] ; then
+    #In this case we don't need any additional language
+    COUNTRY=""
+    OPTION=""
+  else
+    COUNTRY=",${COUNTRY}"
+  fi
 
-   if [ "${KEYMOD}" != "NONE" ]
-   then
-     SETXKBMAP="-model ${KEYMOD}"
-     KXMODEL="${KEYMOD}"
-   else
-     KXMODEL="pc104"
-   fi
+  if [ "${KEYMOD}" != "NONE" ]
+  then
+    SETXKBMAP="-model ${KEYMOD}"
+    KXMODEL="${KEYMOD}"
+  else
+    KXMODEL="pc104"
+  fi
 
-   if [ "${KEYLAY}" != "NONE" ]
-   then
-     localize_key_layout "$KEYLAY"
-     SETXKBMAP="${SETXKBMAP} -layout ${KEYLAY}"
-     KXLAYOUT="${KEYLAY}"
-   else
-     KXLAYOUT="us"
-   fi
+  if [ "${KEYLAY}" != "NONE" ]
+  then
+    localize_key_layout "$KEYLAY"
+    SETXKBMAP="${SETXKBMAP} -layout ${KEYLAY}"
+    KXLAYOUT="${KEYLAY}"
+  else
+    KXLAYOUT="us"
+  fi
 
-   if [ "${KEYVAR}" != "NONE" ]
-   then
-     SETXKBMAP="${SETXKBMAP} -variant ${KEYVAR}"
-     KXVAR="(${KEYVAR})"
-   else
-     KXVAR=""
-   fi
+  if [ "${KEYVAR}" != "NONE" ]
+  then
+    SETXKBMAP="${SETXKBMAP} -variant ${KEYVAR}"
+    KXVAR="(${KEYVAR})"
+  else
+    KXVAR=""
+  fi
 
-   # Setup .xprofile with our setxkbmap call now
-   if [ ! -z "${SETXKBMAP}" ]
-   then
-     if [ ! -e "${FSMNT}/usr/share/skel/.xprofile" ]
-     then
-       echo "#!/bin/sh" >${FSMNT}/usr/share/skel/.xprofile
-     fi
+  # Setup .xprofile with our setxkbmap call now
+  if [ ! -z "${SETXKBMAP}" ]
+  then
+    if [ ! -e "${FSMNT}/usr/share/skel/.xprofile" ]
+    then
+      echo "#!/bin/sh" >${FSMNT}/usr/share/skel/.xprofile
+    fi
 
-     # Save the keyboard layout for user / root X logins
-     echo "setxkbmap ${SETXKBMAP}" >>${FSMNT}/usr/share/skel/.xprofile
-     chmod 755 ${FSMNT}/usr/share/skel/.xprofile
-     cp ${FSMNT}/usr/share/skel/.xprofile ${FSMNT}/root/.xprofile
+    # Save the keyboard layout for user / root X logins
+    echo "setxkbmap ${SETXKBMAP}" >>${FSMNT}/usr/share/skel/.xprofile
+    chmod 755 ${FSMNT}/usr/share/skel/.xprofile
+    cp ${FSMNT}/usr/share/skel/.xprofile ${FSMNT}/root/.xprofile
 
-     # Save it for KDM
-     echo "setxkbmap ${SETXKBMAP}" >>${FSMNT}/usr/local/kde4/share/config/kdm/Xsetup
-   fi
+    # Save it for KDM
+    echo "setxkbmap ${SETXKBMAP}" >>${FSMNT}/usr/local/kde4/share/config/kdm/Xsetup
+  fi
  
 
    # Create the kxkbrc configuration using these options
-   echo "[Layout]
+  echo "[Layout]
 DisplayNames=${KXLAYOUT}${COUNTRY}
 IndicatorOnly=false
 LayoutList=${KXLAYOUT}${KXVAR}${COUNTRY}
@@ -211,157 +211,194 @@ localize_get_codes()
   TARGETLANG="${1}"
   # Setup the presets for the specific lang
   case $TARGETLANG in
-   af) COUNTRY="C"
-       SETLANG="af"
-       LOCALE="af_ZA"
-       ;;
-   ar) COUNTRY="C"
-       SETLANG="ar"
-       LOCALE="en_US"
-       ;;
-   az) COUNTRY="C"
-       SETLANG="az"
-       LOCALE="en_US"
-       ;;
-   ca) COUNTRY="es"
-       SETLANG="es:ca"
-       LOCALE="ca_ES"
-       ;;
-   be) COUNTRY="be"
-       SETLANG="be"
-       LOCALE="be_BY"
-       ;;
-   bn) COUNTRY="bn"
-       SETLANG="bn"
-       LOCALE="en_US"
-       ;;
-   bg) COUNTRY="bg"
-       SETLANG="bg"
-       LOCALE="bg_BG"
-       ;;
-   cs) COUNTRY="cz"
-       SETLANG="cs"
-       LOCALE="cs_CZ"
-       ;;
-   da) COUNTRY="dk"
-       SETLANG="da"
-       LOCALE="da_DK"
-       ;;
-   de) COUNTRY="de"
-       SETLANG="de"
-       LOCALE="de_DE"
-       ;;
-   en_GB) COUNTRY="gb"
-       SETLANG="en_GB:cy"
-       LOCALE="en_GB"
-       ;;
-   el) COUNTRY="gr"
-       SETLANG="el:gr"
-       LOCALE="el_GR"
-       ;;
-   es) COUNTRY="es"
-       SETLANG="es"
-       LOCALE="es_ES"
-       ;;
-   es_LA) COUNTRY="us"
-          SETLANG="es:en_US"
-          LOCALE="es_ES"
-       ;;
-   et) COUNTRY="ee"
-       SETLANG="et"
-       LOCALE="et_EE"
-       ;;
-   fr) COUNTRY="fr"
-       SETLANG="fr"
-       LOCALE="fr_FR"
-       ;;
-   he) COUNTRY="il"
-       SETLANG="he:ar"
-       LOCALE="he_IL"
-       ;;
-   hr) COUNTRY="hr"
-       SETLANG="hr"
-       LOCALE="hr_HR"
-       ;;
-   hu) COUNTRY="hu"
-       SETLANG="hu"
-       LOCALE="hu_HU"
-       ;;
-   it) COUNTRY="it"
-       SETLANG="it"
-       LOCALE="it_IT"
-       ;;
-   ja) COUNTRY="jp"
-       SETLANG="ja"
-       LOCALE="ja_JP"
-       ;;
-   ko) COUNTRY="kr"
-       SETLANG="ko"
-       LOCALE="ko_KR"
-       ;;
-   nl) COUNTRY="nl"
-       SETLANG="nl"
-       LOCALE="nl_NL"
-       ;;
-   nn) COUNTRY="no"
-       SETLANG="nn"
-       LOCALE="en_US"
-       ;;
-   pa) COUNTRY="pa"
-       SETLANG="pa"
-       LOCALE="en_US"
-       ;;
-   pl) COUNTRY="pl"
-       SETLANG="pl"
-       LOCALE="pl_PL"
-       ;;
-   pt) COUNTRY="pt"
-       SETLANG="pt"
-       LOCALE="pt_PT"
-       ;;
-   pt_BR) COUNTRY="br"
-          SETLANG="pt_BR"
-          LOCALE="pt_BR"
-       ;;
-   ru) COUNTRY="ru"
-       SETLANG="ru"
-       LOCALE="ru_RU"
-       ;;
-   sl) COUNTRY="si"
-       SETLANG="sl"
-       LOCALE="sl_SI"
-       ;;
-   sk) COUNTRY="sk"
-       SETLANG="sk"
-       LOCALE="sk_SK"
-       ;;
-   sv) COUNTRY="se"
-       SETLANG="sv"
-       LOCALE="sv_SE"
-       ;;
-   uk) COUNTRY="ua"
-       SETLANG="uk"
-       LOCALE="uk_UA"
-       ;;
-   vi) COUNTRY="vn"
-       SETLANG="vi"
-       LOCALE="en_US"
-       ;;
-   zh_CN) COUNTRY="cn"
-          SETLANG="zh_CN"
-          LOCALE="zh_CN"
-       ;;
-   zh_TW) COUNTRY="tw"
-          SETLANG="zh_TW"
-          LOCALE="zh_TW"
-       ;;
-   *) COUNTRY="C"
+    af)
+      COUNTRY="C"
+      SETLANG="af"
+      LOCALE="af_ZA"
+      ;;
+    ar)
+	  COUNTRY="C"
+      SETLANG="ar"
+      LOCALE="en_US"
+      ;;
+    az)
+	  COUNTRY="C"
+      SETLANG="az"
+      LOCALE="en_US"
+      ;;
+    ca)
+	  COUNTRY="es"
+      SETLANG="es:ca"
+      LOCALE="ca_ES"
+      ;;
+    be)
+	  COUNTRY="be"
+      SETLANG="be"
+      LOCALE="be_BY"
+      ;;
+    bn)
+	  COUNTRY="bn"
+      SETLANG="bn"
+      LOCALE="en_US"
+      ;;
+    bg)
+	  COUNTRY="bg"
+      SETLANG="bg"
+      LOCALE="bg_BG"
+      ;;
+    cs)
+	  COUNTRY="cz"
+      SETLANG="cs"
+      LOCALE="cs_CZ"
+      ;;
+    da)
+	  COUNTRY="dk"
+      SETLANG="da"
+      LOCALE="da_DK"
+      ;;
+    de)
+	  COUNTRY="de"
+      SETLANG="de"
+      LOCALE="de_DE"
+      ;;
+    en_GB)
+	  COUNTRY="gb"
+      SETLANG="en_GB:cy"
+      LOCALE="en_GB"
+      ;;
+    el)
+	  COUNTRY="gr"
+      SETLANG="el:gr"
+      LOCALE="el_GR"
+      ;;
+    es)
+	  COUNTRY="es"
+      SETLANG="es"
+      LOCALE="es_ES"
+      ;;
+    es_LA)
+	  COUNTRY="us"
+      SETLANG="es:en_US"
+      LOCALE="es_ES"
+      ;;
+    et)
+	  COUNTRY="ee"
+      SETLANG="et"
+      LOCALE="et_EE"
+      ;;
+    fr)
+	  COUNTRY="fr"
+      SETLANG="fr"
+      LOCALE="fr_FR"
+      ;;
+    he)
+	  COUNTRY="il"
+      SETLANG="he:ar"
+      LOCALE="he_IL"
+      ;;
+    hr)
+	  COUNTRY="hr"
+      SETLANG="hr"
+      LOCALE="hr_HR"
+      ;;
+    hu)
+	  COUNTRY="hu"
+      SETLANG="hu"
+      LOCALE="hu_HU"
+      ;;
+    it)
+	  COUNTRY="it"
+      SETLANG="it"
+      LOCALE="it_IT"
+      ;;
+    ja)
+	  COUNTRY="jp"
+      SETLANG="ja"
+      LOCALE="ja_JP"
+      ;;
+    ko)
+	  COUNTRY="kr"
+      SETLANG="ko"
+      LOCALE="ko_KR"
+      ;;
+    nl)
+	  COUNTRY="nl"
+      SETLANG="nl"
+      LOCALE="nl_NL"
+      ;;
+    nn)
+	  COUNTRY="no"
+      SETLANG="nn"
+      LOCALE="en_US"
+      ;;
+    pa)
+	  COUNTRY="pa"
+      SETLANG="pa"
+      LOCALE="en_US"
+      ;;
+    pl)
+	  COUNTRY="pl"
+      SETLANG="pl"
+      LOCALE="pl_PL"
+      ;;
+    pt)
+	  COUNTRY="pt"
+      SETLANG="pt"
+      LOCALE="pt_PT"
+      ;;
+    pt_BR)
+	  COUNTRY="br"
+      SETLANG="pt_BR"
+      LOCALE="pt_BR"
+      ;;
+    ru)
+	  COUNTRY="ru"
+      SETLANG="ru"
+      LOCALE="ru_RU"
+      ;;
+    sl)
+	  COUNTRY="si"
+      SETLANG="sl"
+      LOCALE="sl_SI"
+      ;;
+    sk)
+	  COUNTRY="sk"
+      SETLANG="sk"
+      LOCALE="sk_SK"
+      ;;
+    sv)
+	  COUNTRY="se"
+      SETLANG="sv"
+      LOCALE="sv_SE"
+      ;;
+    uk)
+	  COUNTRY="ua"
+      SETLANG="uk"
+      LOCALE="uk_UA"
+      ;;
+    vi)
+	  COUNTRY="vn"
+      SETLANG="vi"
+      LOCALE="en_US"
+      ;;
+    zh_CN)
+	  COUNTRY="cn"
+      SETLANG="zh_CN"
+      LOCALE="zh_CN"
+      ;;
+    zh_TW)
+	  COUNTRY="tw"
+      SETLANG="zh_TW"
+      LOCALE="zh_TW"
+      ;;
+    *)
+	  COUNTRY="C"
       SETLANG="${TARGETLANG}"
       LOCALE="en_US"
       ;;
   esac
 
- export COUNTRY SETLANG LOCALE
+  export COUNTRY SETLANG LOCALE
 
 };
 
diff --git a/usr.sbin/pc-sysinstall/backend/functions-mountdisk.sh b/usr.sbin/pc-sysinstall/backend/functions-mountdisk.sh
index 78ce952836d..4d8d4a43b45 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-mountdisk.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-mountdisk.sh
@@ -52,32 +52,32 @@ mount_partition()
   #We are on ZFS, lets setup this mount-point
   if [ "${PARTFS}" = "ZFS" ]
   then
-     ZPOOLNAME=$(get_zpool_name "${PART}")
+    ZPOOLNAME=$(get_zpool_name "${PART}")
 
-     # Check if we have multiple zfs mounts specified
-     for ZMNT in `echo ${MNTPOINT} | sed 's|,| |g'`
-     do
-       # First make sure we create the mount point
-       if [ ! -d "${FSMNT}${ZMNT}" ] ; then
-         mkdir -p ${FSMNT}${ZMNT} >>${LOGOUT} 2>>${LOGOUT}
-       fi
+    # Check if we have multiple zfs mounts specified
+    for ZMNT in `echo ${MNTPOINT} | sed 's|,| |g'`
+    do
+      # First make sure we create the mount point
+      if [ ! -d "${FSMNT}${ZMNT}" ] ; then
+        mkdir -p ${FSMNT}${ZMNT} >>${LOGOUT} 2>>${LOGOUT}
+      fi
 
-       if [ "${ZMNT}" = "/" ] ; then
-         ZNAME=""
-       else
-         ZNAME="${ZMNT}"
-         echo_log "zfs create -p ${ZPOOLNAME}${ZNAME}"
-         rc_halt "zfs create -p ${ZPOOLNAME}${ZNAME}"
-       fi
-       sleep 2
-       rc_halt "zfs set mountpoint=${FSMNT}${ZNAME} ${ZPOOLNAME}${ZNAME}"
+      if [ "${ZMNT}" = "/" ] ; then
+        ZNAME=""
+      else
+        ZNAME="${ZMNT}"
+        echo_log "zfs create -p ${ZPOOLNAME}${ZNAME}"
+        rc_halt "zfs create -p ${ZPOOLNAME}${ZNAME}"
+      fi
+      sleep 2
+      rc_halt "zfs set mountpoint=${FSMNT}${ZNAME} ${ZPOOLNAME}${ZNAME}"
 
-       # Disable atime for this zfs partition, speed increase
-       rc_nohalt "zfs set atime=off ${ZPOOLNAME}${ZNAME}"
-     done 
+      # Disable atime for this zfs partition, speed increase
+      rc_nohalt "zfs set atime=off ${ZPOOLNAME}${ZNAME}"
+    done 
 
   else
-  # If we are not on ZFS, lets do the mount now
+    # If we are not on ZFS, lets do the mount now
     # First make sure we create the mount point
     if [ ! -d "${FSMNT}${MNTPOINT}" ]
     then
@@ -94,17 +94,17 @@ mount_partition()
 # Mounts all the new file systems to prepare for installation
 mount_all_filesystems()
 {
-   # Make sure our mount point exists
-   mkdir -p ${FSMNT} >/dev/null 2>/dev/null
+  # Make sure our mount point exists
+  mkdir -p ${FSMNT} >/dev/null 2>/dev/null
 
-   # First lets find and mount the / partition
-   #########################################################
-   for PART in `ls ${PARTDIR}`
-   do
-     if [ ! -e "/dev/${PART}" ]
-     then
-       exit_err "ERROR: The partition ${PART} does not exist. Failure in bsdlabel?"
-     fi 
+  # First lets find and mount the / partition
+  #########################################################
+  for PART in `ls ${PARTDIR}`
+  do
+    if [ ! -e "/dev/${PART}" ]
+    then
+      exit_err "ERROR: The partition ${PART} does not exist. Failure in bsdlabel?"
+    fi 
 
     PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
     PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
@@ -122,69 +122,60 @@ mount_all_filesystems()
     if [ "$?" = "0" -o "$PARTMNT" = "/" ]
     then
       case ${PARTFS} in
-         UFS) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime"
-              ;;
-       UFS+S) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime"
-              ;;
-       UFS+J) mount_partition ${PART}${EXT}.journal ${PARTFS} ${PARTMNT} "async,noatime"
-              ;;
-         ZFS) mount_partition ${PART} ${PARTFS} ${PARTMNT}
-              ;;
-           *) exit_err "ERROR: Got unknown file-system type $PARTFS" ;;
+        UFS) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime" ;;
+        UFS+S) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime" ;;
+        UFS+J) mount_partition ${PART}${EXT}.journal ${PARTFS} ${PARTMNT} "async,noatime" ;;
+        ZFS) mount_partition ${PART} ${PARTFS} ${PARTMNT} ;;
+        *) exit_err "ERROR: Got unknown file-system type $PARTFS" ;;
       esac
-
     fi
+  done
+
+  # Now that we've mounted "/" lets do any other remaining mount-points
+  ##################################################################
+  for PART in `ls ${PARTDIR}`
+  do
+    if [ ! -e "/dev/${PART}" ]
+    then
+      exit_err "ERROR: The partition ${PART} does not exist. Failure in bsdlabel?"
+    fi 
      
-   done
+    PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
+    PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
+    PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
 
-   # Now that we've mounted "/" lets do any other remaining mount-points
-   ##################################################################
-   for PART in `ls ${PARTDIR}`
-   do
-     if [ ! -e "/dev/${PART}" ]
-     then
-       exit_err "ERROR: The partition ${PART} does not exist. Failure in bsdlabel?"
-     fi 
-     
-     PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
-     PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
-     PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
+    if [ "${PARTENC}" = "ON" ]
+    then
+      EXT=".eli"
+    else
+      EXT=""
+    fi
 
-     if [ "${PARTENC}" = "ON" ]
-     then
-       EXT=".eli"
-     else
-       EXT=""
-     fi
-
-     # Check if we've found "/" again, don't need to mount it twice
-     echo "$PARTMNT" | grep "/," >/dev/null
-     if [ "$?" != "0" -a "$PARTMNT" != "/" ]
-     then
+    # Check if we've found "/" again, don't need to mount it twice
+    echo "$PARTMNT" | grep "/," >/dev/null
+    if [ "$?" != "0" -a "$PARTMNT" != "/" ]
+    then
        case ${PARTFS} in
-         UFS) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime"
-              ;;
-       UFS+S) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime"
-              ;;
-       UFS+J) mount_partition ${PART}${EXT}.journal ${PARTFS} ${PARTMNT} "async,noatime"
-              ;;
-         ZFS) mount_partition ${PART} ${PARTFS} ${PARTMNT}
-              ;;
-        SWAP) # Lets enable this swap now
-              if [ "$PARTENC" = "ON" ]
-              then
-                echo_log "Enabling encrypted swap on /dev/${PART}"
-                rc_halt "geli onetime -d -e 3des ${PART}"
-                sleep 5
-                rc_halt "swapon /dev/${PART}.eli"
-              else
-                echo_log "swapon ${PART}"
-                sleep 5
-                rc_halt "swapon /dev/${PART}"
-              fi
-              ;;
+         UFS) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime" ;;
+         UFS+S) mount_partition ${PART}${EXT} ${PARTFS} ${PARTMNT} "noatime" ;;
+         UFS+J) mount_partition ${PART}${EXT}.journal ${PARTFS} ${PARTMNT} "async,noatime" ;;
+         ZFS) mount_partition ${PART} ${PARTFS} ${PARTMNT} ;;
+         SWAP)
+		   # Lets enable this swap now
+           if [ "$PARTENC" = "ON" ]
+           then
+             echo_log "Enabling encrypted swap on /dev/${PART}"
+             rc_halt "geli onetime -d -e 3des ${PART}"
+             sleep 5
+             rc_halt "swapon /dev/${PART}.eli"
+           else
+             echo_log "swapon ${PART}"
+             sleep 5
+             rc_halt "swapon /dev/${PART}"
+            fi
+            ;;
           *) exit_err "ERROR: Got unknown file-system type $PARTFS" ;;
-       esac
-     fi
-   done
+      esac
+    fi
+  done
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-mountoptical.sh b/usr.sbin/pc-sysinstall/backend/functions-mountoptical.sh
index a669b9fb5b5..9cf3a6398f0 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-mountoptical.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-mountoptical.sh
@@ -34,114 +34,114 @@
 # Displays an optical failure message
 opt_fail()
 {
-   # If we got here, we must not have a DVD/USB we can find :(
-   get_value_from_cfg installInteractive
-   if [ "${VAL}" = "yes" ]
-   then
-     # We are running interactive, and didn't find a DVD, prompt user again
-     echo_log "DISK ERROR: Unable to find installation disk!"
-     echo_log "Please insert the installation disk and press enter."
-     read tmp
-   else
-    exit_err "ERROR: Unable to locate installation DVD/USB"
-   fi
+  # If we got here, we must not have a DVD/USB we can find :(
+  get_value_from_cfg installInteractive
+  if [ "${VAL}" = "yes" ]
+  then
+    # We are running interactive, and didn't find a DVD, prompt user again
+    echo_log "DISK ERROR: Unable to find installation disk!"
+    echo_log "Please insert the installation disk and press enter."
+    read tmp
+  else
+   exit_err "ERROR: Unable to locate installation DVD/USB"
+  fi
 };
 
 # Performs the extraction of data to disk
 opt_mount()
 {
- FOUND="0"
+  FOUND="0"
 
- # Ensure we have a directory where its supposed to be
- if [ ! -d "${CDMNT}" ]
- then
-   mkdir -p ${CDMNT}
- fi
+  # Ensure we have a directory where its supposed to be
+  if [ ! -d "${CDMNT}" ]
+  then
+    mkdir -p ${CDMNT}
+  fi
 
 
- # Start by checking if we already have a cd mounted at CDMNT
- mount | grep "${CDMNT} " >/dev/null 2>/dev/null
- if [ "$?" = "0" ]
- then
-   if [ -e "${CDMNT}/${INSFILE}" ]
-   then
-     echo "MOUNTED" >${TMPDIR}/cdmnt
-     echo_log "FOUND DVD: MOUNTED"
-     FOUND="1"
-     return
-   fi
+  # Start by checking if we already have a cd mounted at CDMNT
+  mount | grep "${CDMNT} " >/dev/null 2>/dev/null
+  if [ "$?" = "0" ]
+  then
+    if [ -e "${CDMNT}/${INSFILE}" ]
+    then
+      echo "MOUNTED" >${TMPDIR}/cdmnt
+      echo_log "FOUND DVD: MOUNTED"
+      FOUND="1"
+      return
+    fi
 
-   # failed to find optical disk
-   opt_fail
-   return
- fi
+    # failed to find optical disk
+    opt_fail
+    return
+  fi
 
-# Setup our loop to search for installation media
- while
- z=1
- do
+  # Setup our loop to search for installation media
+  while
+  z=1
+  do
 
-   # Loop though and look for an installation disk
-   for i in `ls -1 /dev/acd* /dev/cd* /dev/scd* /dev/rscd* 2>/dev/null`
-   do
-     # Find the CD Device
-     /sbin/mount_cd9660 $i ${CDMNT}
+    # Loop though and look for an installation disk
+    for i in `ls -1 /dev/acd* /dev/cd* /dev/scd* /dev/rscd* 2>/dev/null`
+    do
+      # Find the CD Device
+      /sbin/mount_cd9660 $i ${CDMNT}
 
-     # Check the package type to see if we have our install data
-     if [ -e "${CDMNT}/${INSFILE}" ]
-     then
-       echo "${i}" >${TMPDIR}/cdmnt
-       echo_log "FOUND DVD: ${i}"
-       FOUND="1"
-       break
-     fi
-     /sbin/umount ${CDMNT} >/dev/null 2>/dev/null
-   done
+      # Check the package type to see if we have our install data
+      if [ -e "${CDMNT}/${INSFILE}" ]
+      then
+        echo "${i}" >${TMPDIR}/cdmnt
+        echo_log "FOUND DVD: ${i}"
+        FOUND="1"
+        break
+      fi
+      /sbin/umount ${CDMNT} >/dev/null 2>/dev/null
+    done
 
-   # If no DVD found, try USB
-   if [ "$FOUND" != "1" ]
-   then
-     # Loop though and look for an installation disk
-     for i in `ls -1 /dev/da* 2>/dev/null`
-     do
-       # Check if we can mount this device UFS
-       /sbin/mount -r $i ${CDMNT}
+    # If no DVD found, try USB
+    if [ "$FOUND" != "1" ]
+    then
+      # Loop though and look for an installation disk
+      for i in `ls -1 /dev/da* 2>/dev/null`
+      do
+        # Check if we can mount this device UFS
+        /sbin/mount -r $i ${CDMNT}
 
-       # Check the package type to see if we have our install data
-       if [ -e "${CDMNT}/${INSFILE}" ]
-       then
-         echo "${i}" >${TMPDIR}/cdmnt
-         echo_log "FOUND USB: ${i}"
-         FOUND="1"
-         break
-       fi
-       /sbin/umount ${CDMNT} >/dev/null 2>/dev/null
+        # Check the package type to see if we have our install data
+        if [ -e "${CDMNT}/${INSFILE}" ]
+        then
+          echo "${i}" >${TMPDIR}/cdmnt
+          echo_log "FOUND USB: ${i}"
+          FOUND="1"
+          break
+        fi
+        /sbin/umount ${CDMNT} >/dev/null 2>/dev/null
 
-       # Also check if it is a FAT mount
-       /sbin/mount -r -t msdosfs $i ${CDMNT}
+        # Also check if it is a FAT mount
+        /sbin/mount -r -t msdosfs $i ${CDMNT}
 
-       # Check the package type to see if we have our install data
-       if [ -e "${CDMNT}/${INSFILE}" ]
-       then
-         echo "${i}" >${TMPDIR}/cdmnt
-         echo_log "FOUND USB: ${i}"
-         FOUND="1"
-         break
-       fi
-       /sbin/umount ${CDMNT} >/dev/null 2>/dev/null
-     done
-   fi # End of USB Check
+        # Check the package type to see if we have our install data
+        if [ -e "${CDMNT}/${INSFILE}" ]
+        then
+          echo "${i}" >${TMPDIR}/cdmnt
+          echo_log "FOUND USB: ${i}"
+          FOUND="1"
+          break
+        fi
+        /sbin/umount ${CDMNT} >/dev/null 2>/dev/null
+      done
+    fi # End of USB Check
 
 
-   if [ "$FOUND" = "1" ]
-   then
-     break
-   fi
+    if [ "$FOUND" = "1" ]
+    then
+      break
+    fi
    
-   # Failed to find a disk, take action now
-   opt_fail
+    # Failed to find a disk, take action now
+    opt_fail
 
- done
+  done
 
 };
 
diff --git a/usr.sbin/pc-sysinstall/backend/functions-networking.sh b/usr.sbin/pc-sysinstall/backend/functions-networking.sh
index 900e54aee1d..22602a9f973 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-networking.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-networking.sh
@@ -68,8 +68,8 @@ get_first_wired_nic()
       check_is_wifi ${NIC}
       if [ "$?" != "0" ]
       then
-         VAL="${NIC}" ; export VAL
-         return
+        VAL="${NIC}" ; export VAL
+        return
       fi
     done < ${TMPDIR}/.niclist
   fi
@@ -241,22 +241,23 @@ enable_auto_dhcp()
 
     is_nic_active "${NIC}"
     if [ "$?" = "0" ] ; then
-    	echo_log "Trying DHCP on $NIC $DESC"
-    	dhclient ${NIC} >/dev/null 2>/dev/null
-    	if [ "$?" = "0" ] ; then
-   	   # Got a valid DHCP IP, we can return now
-	   WRKNIC="$NIC" ; export WRKNIC
-   	   return 0
-	fi
+      echo_log "Trying DHCP on $NIC $DESC"
+      dhclient ${NIC} >/dev/null 2>/dev/null
+      if [ "$?" = "0" ] ; then
+        # Got a valid DHCP IP, we can return now
+	    WRKNIC="$NIC" ; export WRKNIC
+   	    return 0
+	  fi
     fi
   done < ${TMPDIR}/.niclist 
 
 };
 
 # Get the mac address of a target NIC
-get_nic_mac() {
-	FOUNDMAC="`ifconfig ${1} | grep 'ether' | tr -d '\t' | cut -d ' ' -f 2`"
-	export FOUNDMAC
+get_nic_mac()
+{
+  FOUNDMAC="`ifconfig ${1} | grep 'ether' | tr -d '\t' | cut -d ' ' -f 2`"
+  export FOUNDMAC
 }
 
 # Function which performs the manual setup of a target nic in the cfg
diff --git a/usr.sbin/pc-sysinstall/backend/functions-newfs.sh b/usr.sbin/pc-sysinstall/backend/functions-newfs.sh
index 84fc1b7e7e8..3963ef7e41a 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-newfs.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-newfs.sh
@@ -81,102 +81,112 @@ setup_zfs_filesystem()
 setup_filesystems()
 {
 
-   # Create the keydir
-   rm -rf ${GELIKEYDIR} >/dev/null 2>/dev/null
-   mkdir ${GELIKEYDIR}
+  # Create the keydir
+  rm -rf ${GELIKEYDIR} >/dev/null 2>/dev/null
+  mkdir ${GELIKEYDIR}
 
-   # Lets go ahead and read through the saved partitions we created, and determine if we need to run
-   # newfs on any of them
-   for PART in `ls ${PARTDIR}`
-   do
-     if [ ! -e "/dev/${PART}" ]
-     then
-       exit_err "ERROR: The partition ${PART} does not exist. Failure in bsdlabel?"
-     fi 
+  # Lets go ahead and read through the saved partitions we created, and determine if we need to run
+  # newfs on any of them
+  for PART in `ls ${PARTDIR}`
+  do
+    if [ ! -e "/dev/${PART}" ]
+    then
+      exit_err "ERROR: The partition ${PART} does not exist. Failure in bsdlabel?"
+    fi 
      
-     PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
-     PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
-     PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
-     PARTLABEL="`cat ${PARTDIR}/${PART} | cut -d ':' -f 4`"
-     PARTGEOM="`cat ${PARTDIR}/${PART} | cut -d ':' -f 5`"
-     PARTXTRAOPTS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 6`"
+    PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
+    PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
+    PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
+    PARTLABEL="`cat ${PARTDIR}/${PART} | cut -d ':' -f 4`"
+    PARTGEOM="`cat ${PARTDIR}/${PART} | cut -d ':' -f 5`"
+    PARTXTRAOPTS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 6`"
 
-     # Make sure journaling isn't enabled on this device
-     if [ -e "/dev/${PART}.journal" ]
-     then
-       rc_nohalt "gjournal stop -f ${PART}.journal"
-       rc_nohalt "gjournal clear ${PART}"
-     fi
+    # Make sure journaling isn't enabled on this device
+    if [ -e "/dev/${PART}.journal" ]
+    then
+      rc_nohalt "gjournal stop -f ${PART}.journal"
+      rc_nohalt "gjournal clear ${PART}"
+    fi
 
-     # Setup encryption if necessary
-     if [ "${PARTENC}" = "ON" -a "${PARTFS}" != "SWAP" ]
-     then
-       echo_log "Creating geli provider for ${PART}"
-       rc_halt "dd if=/dev/random of=${GELIKEYDIR}/${PART}.key bs=64 count=1"
-       rc_halt "geli init -b -s 4096 -P -K ${GELIKEYDIR}/${PART}.key /dev/${PART}"
-       rc_halt "geli attach -p -k ${GELIKEYDIR}/${PART}.key /dev/${PART}"
+    # Setup encryption if necessary
+    if [ "${PARTENC}" = "ON" -a "${PARTFS}" != "SWAP" ]
+    then
+      echo_log "Creating geli provider for ${PART}"
+      rc_halt "dd if=/dev/random of=${GELIKEYDIR}/${PART}.key bs=64 count=1"
+      rc_halt "geli init -b -s 4096 -P -K ${GELIKEYDIR}/${PART}.key /dev/${PART}"
+      rc_halt "geli attach -p -k ${GELIKEYDIR}/${PART}.key /dev/${PART}"
 
-       EXT=".eli"
-     else
-       # No Encryption
-       EXT=""
-     fi
+      EXT=".eli"
+    else
+      # No Encryption
+      EXT=""
+    fi
 
-     case ${PARTFS} in
-         UFS) echo_log "NEWFS: /dev/${PART} - ${PARTFS}"
-              sleep 2
-              rc_halt "newfs /dev/${PART}${EXT}"
-              sleep 2
-              rc_halt "sync"
-              rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}"
-              rc_halt "sync"
+    case ${PARTFS} in
+      UFS)
+        echo_log "NEWFS: /dev/${PART} - ${PARTFS}"
+        sleep 2
+        rc_halt "newfs /dev/${PART}${EXT}"
+        sleep 2
+        rc_halt "sync"
+        rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}"
+        rc_halt "sync"
 
-	      # Set flag that we've found a boot partition
-	      if [ "$PARTMNT" = "/boot" -o "${PARTMNT}" = "/" ] ; then
-		HAVEBOOT="YES"
-  	      fi
-              sleep 2
-              ;;
-       UFS+S) echo_log "NEWFS: /dev/${PART} - ${PARTFS}"
-              sleep 2
-              rc_halt "newfs -U /dev/${PART}${EXT}"
-              sleep 2
-              rc_halt "sync"
-              rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}"
-              rc_halt "sync"
-	      # Set flag that we've found a boot partition
-	      if [ "$PARTMNT" = "/boot" -o "${PARTMNT}" = "/" ] ; then
-		HAVEBOOT="YES"
-  	      fi
-              sleep 2
-              ;;
-       UFS+J) echo_log "NEWFS: /dev/${PART} - ${PARTFS}"
-              sleep 2
-              rc_halt "newfs /dev/${PART}${EXT}"
-              sleep 2
-              rc_halt "gjournal label -f /dev/${PART}${EXT}"
-              sleep 2
-              rc_halt "newfs -O 2 -J /dev/${PART}${EXT}.journal"
-              sleep 2
-              rc_halt "sync"
-              rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}.journal"
-              rc_halt "sync"
-	      # Set flag that we've found a boot partition
-	      if [ "$PARTMNT" = "/boot" -o "${PARTMNT}" = "/" ] ; then
-		HAVEBOOT="YES"
-  	      fi
-              sleep 2
-              ;;
-         ZFS) echo_log "NEWFS: /dev/${PART} - ${PARTFS}" 
-              setup_zfs_filesystem "${PART}" "${PARTFS}" "${PARTMNT}" "${EXT}" "${PARTGEOM}" "${PARTXTRAOPTS}"
-              ;;
-        SWAP) rc_halt "sync"
-              rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}" 
-              rc_halt "sync"
-              sleep 2
-              ;;
-           *) exit_err "ERROR: Got unknown file-system type $PARTFS" ;;
-     esac
+        # Set flag that we've found a boot partition
+        if [ "$PARTMNT" = "/boot" -o "${PARTMNT}" = "/" ] ; then
+		  HAVEBOOT="YES"
+        fi
+        sleep 2
+        ;;
 
-   done
+      UFS+S)
+        echo_log "NEWFS: /dev/${PART} - ${PARTFS}"
+        sleep 2
+        rc_halt "newfs -U /dev/${PART}${EXT}"
+        sleep 2
+        rc_halt "sync"
+        rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}"
+        rc_halt "sync"
+	    # Set flag that we've found a boot partition
+	    if [ "$PARTMNT" = "/boot" -o "${PARTMNT}" = "/" ] ; then
+          HAVEBOOT="YES"
+        fi
+        sleep 2
+        ;;
+
+      UFS+J)
+        echo_log "NEWFS: /dev/${PART} - ${PARTFS}"
+        sleep 2
+        rc_halt "newfs /dev/${PART}${EXT}"
+        sleep 2
+        rc_halt "gjournal label -f /dev/${PART}${EXT}"
+        sleep 2
+        rc_halt "newfs -O 2 -J /dev/${PART}${EXT}.journal"
+        sleep 2
+        rc_halt "sync"
+        rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}.journal"
+        rc_halt "sync"
+	    # Set flag that we've found a boot partition
+	    if [ "$PARTMNT" = "/boot" -o "${PARTMNT}" = "/" ] ; then
+          HAVEBOOT="YES"
+  	    fi
+        sleep 2
+        ;;
+
+      ZFS)
+        echo_log "NEWFS: /dev/${PART} - ${PARTFS}" 
+        setup_zfs_filesystem "${PART}" "${PARTFS}" "${PARTMNT}" "${EXT}" "${PARTGEOM}" "${PARTXTRAOPTS}"
+        ;;
+
+      SWAP)
+        rc_halt "sync"
+        rc_halt "glabel label ${PARTLABEL} /dev/${PART}${EXT}" 
+        rc_halt "sync"
+        sleep 2
+        ;;
+
+      *) exit_err "ERROR: Got unknown file-system type $PARTFS" ;;
+    esac
+
+  done
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-packages.sh b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
index 161a511cf5d..998b7ad13e2 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
@@ -34,347 +34,341 @@
 
 get_package_index_by_ftp()
 {
-	local INDEX_FILE
-	local FTP_SERVER
+  local INDEX_FILE
+  local FTP_SERVER
 
-	FTP_SERVER="${1}"
-	INDEX_FILE="INDEX"
-	USE_BZIP2=0
+  FTP_SERVER="${1}"
+  INDEX_FILE="INDEX"
+  USE_BZIP2=0
 
-	if [ -f "/usr/bin/bzip2" ]
-	then
-		INDEX_FILE="${INDEX_FILE}.bz2"
-		USE_BZIP2=1
-	fi
+  if [ -f "/usr/bin/bzip2" ]
+  then
+    INDEX_FILE="${INDEX_FILE}.bz2"
+    USE_BZIP2=1
+  fi
 
-	INDEX_PATH="${CONFDIR}/${INDEX_FILE}"
-	fetch_file "${FTP_SERVER}/${INDEX_FILE}" "${INDEX_PATH}" "1"
-	if [ -f "${INDEX_PATH}" ] && [ "${USE_BZIP2}" -eq "1" ]
-	then
-		bzip2 -d "${INDEX_PATH}"
-	fi
+  INDEX_PATH="${CONFDIR}/${INDEX_FILE}"
+  fetch_file "${FTP_SERVER}/${INDEX_FILE}" "${INDEX_PATH}" "1"
+  if [ -f "${INDEX_PATH}" ] && [ "${USE_BZIP2}" -eq "1" ]
+  then
+    bzip2 -d "${INDEX_PATH}"
+  fi
 };
 
 get_package_index_by_fs()
 {
-	local INDEX_FILE
+  local INDEX_FILE
 
-	INDEX_FILE="${CDMNT}/packages/INDEX"
-	fetch_file "${INDEX_FILE}" "${CONFDIR}/" "0"
+  INDEX_FILE="${CDMNT}/packages/INDEX"
+  fetch_file "${INDEX_FILE}" "${CONFDIR}/" "0"
 };
 
 get_package_index_size()
 {
-	if [ -f "${CONFDIR}/INDEX" ]
-	then
-		SIZE=`ls -l ${CONFDIR}/INDEX | awk '{ print $5 }'`
-	else
-		get_ftp_mirror
-		FTPHOST="${VAL}"
+  if [ -f "${CONFDIR}/INDEX" ]
+  then
+    SIZE=`ls -l ${CONFDIR}/INDEX | awk '{ print $5 }'`
+  else
+    get_ftp_mirror
+    FTPHOST="${VAL}"
 
-		FTPDIR="/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}"
-		FTPPATH="ftp://${FTPHOST}${FTPDIR}/packages"
+    FTPDIR="/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}"
+    FTPPATH="ftp://${FTPHOST}${FTPDIR}/packages"
 
-		fetch -s "${FTPPATH}/INDEX.bz2"
-	fi
+    fetch -s "${FTPPATH}/INDEX.bz2"
+  fi
 };
 
 get_package_index()
 {
-	RES=0
+  RES=0
 
-	if [ -z "${INSTALLMODE}" ]
-	then
-		get_ftp_mirror
-		FTPHOST="${VAL}"
+  if [ -z "${INSTALLMODE}" ]
+  then
+    get_ftp_mirror
+    FTPHOST="${VAL}"
 
-		FTPDIR="/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}"
-		FTPPATH="ftp://${FTPHOST}${FTPDIR}/packages"
+    FTPDIR="/pub/FreeBSD/releases/${FBSD_ARCH}/${FBSD_BRANCH}"
+    FTPPATH="ftp://${FTPHOST}${FTPDIR}/packages"
 
-		get_package_index_by_ftp "${FTPPATH}"
+    get_package_index_by_ftp "${FTPPATH}"
 
-	else
-		get_value_from_cfg ftpHost
-		if [ -z "$VAL" ]
-		then
-			exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
-		fi
-		FTPHOST="${VAL}"
+  else
+    get_value_from_cfg ftpHost
+    if [ -z "$VAL" ]
+    then
+      exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
+    fi
 
-		get_value_from_cfg ftpDir
-		if [ -z "$VAL" ]
-		then
-			exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
-		fi
-		FTPDIR="${VAL}"
+    FTPHOST="${VAL}"
 
-		FTPPATH="ftp://${FTPHOST}${FTPDIR}"
+    get_value_from_cfg ftpDir
+    if [ -z "$VAL" ]
+    then
+      exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
+    fi
 
-		case "${INSTALLMEDIUM}" in
-		usb|dvd) get_package_index_by_fs
-			;;
-		ftp) get_package_index_by_ftp "${FTPPATH}"
-			;;
-		*) RES=1
-			;;
-		esac
+    FTPDIR="${VAL}"
+    FTPPATH="ftp://${FTPHOST}${FTPDIR}"
 
-	fi
+    case "${INSTALLMEDIUM}" in
+      usb|dvd) get_package_index_by_fs ;;
+      ftp|sftp) get_package_index_by_ftp "${FTPPATH}" ;;
+      *) RES=1 ;;
+    esac
 
-	return ${RES}
+  fi
+
+  return ${RES}
 };
 
 parse_package_index()
 {
-	INDEX_FILE="${PKGDIR}/INDEX"
+  INDEX_FILE="${PKGDIR}/INDEX"
 
-	exec 3<&0
-	exec 0<"${INDEX_FILE}"
+  exec 3<&0
+  exec 0<"${INDEX_FILE}"
 
-	while read -r line
-	do
-		PKGNAME=""
-		CATEGORY=""
-		PACKAGE=""
-		DESC=""
-		DEPS=""
-		i=0
+  while read -r line
+  do
+    PKGNAME=""
+    CATEGORY=""
+    PACKAGE=""
+    DESC=""
+    DEPS=""
+    i=0
 
-		SAVE_IFS="${IFS}"
-		IFS="|"
+    SAVE_IFS="${IFS}"
+    IFS="|"
 
-		for part in ${line}
-		do
-			if [ "${i}" -eq "0" ]
-			then
-				PKGNAME="${part}"
+    for part in ${line}
+    do
+      if [ "${i}" -eq "0" ]
+      then
+        PKGNAME="${part}"
 
-			elif [ "${i}" -eq "1" ]
-			then
-				PACKAGE=`basename "${part}"`
+      elif [ "${i}" -eq "1" ]
+      then
+        PACKAGE=`basename "${part}"`
 
-			elif [ "${i}" -eq "3" ]
-			then
-				DESC="${part}"
+      elif [ "${i}" -eq "3" ]
+      then
+        DESC="${part}"
 
-			elif [ "${i}" -eq "6" ]
-			then
-				CATEGORY=`echo "${part}" | cut -f1 -d' '`
+      elif [ "${i}" -eq "6" ]
+      then
+        CATEGORY=`echo "${part}" | cut -f1 -d' '`
 
-			elif [ "${i}" -eq "8" ]
-			then
-				DEPS="${part}"
-			fi
+      elif [ "${i}" -eq "8" ]
+      then
+        DEPS="${part}"
+      fi
 
-			i=$((i+1))
-		done
+      i=$((i+1))
+    done
 
-		echo "${CATEGORY}|${PACKAGE}|${DESC}" >> "${INDEX_FILE}.parsed"
-		echo "${PACKAGE}|${PKGNAME}|${DEPS}" >> "${INDEX_FILE}.deps"
+    echo "${CATEGORY}|${PACKAGE}|${DESC}" >> "${INDEX_FILE}.parsed"
+    echo "${PACKAGE}|${PKGNAME}|${DEPS}" >> "${INDEX_FILE}.deps"
 
-		IFS="${SAVE_IFS}"
-	done
+    IFS="${SAVE_IFS}"
+  done
 
-	exec 0<&3
+  exec 0<&3
 };
 
 show_package_file()
 {
-	PKGFILE="${1}"
+  PKGFILE="${1}"
 
-	echo "Available Packages:"
+  echo "Available Packages:"
 
-	exec 3<&0
-	exec 0<"${PKGFILE}"
+  exec 3<&0
+  exec 0<"${PKGFILE}"
 
-	while read -r line
-	do
-		CATEGORY=`echo "${line}" | cut -f1 -d'|'`
-		PACKAGE=`echo "${line}" | cut -f2 -d'|'`
-		DESC=`echo "${line}" | cut -f3 -d'|'`
+  while read -r line
+  do
+    CATEGORY=`echo "${line}" | cut -f1 -d'|'`
+    PACKAGE=`echo "${line}" | cut -f2 -d'|'`
+    DESC=`echo "${line}" | cut -f3 -d'|'`
 
-		echo "${CATEGORY}/${PACKAGE}:${DESC}"
-	done
+    echo "${CATEGORY}/${PACKAGE}:${DESC}"
+  done
 
-	exec 0<&3
+  exec 0<&3
 };
 
 show_packages_by_category()
 {
-	CATEGORY="${1}"
-	INDEX_FILE="${PKGDIR}/INDEX.parsed"
-	TMPFILE="/tmp/.pkg.cat"
+  CATEGORY="${1}"
+  INDEX_FILE="${PKGDIR}/INDEX.parsed"
+  TMPFILE="/tmp/.pkg.cat"
 
-	grep "^${CATEGORY}|" "${INDEX_FILE}" > "${TMPFILE}"
-	show_package_file "${TMPFILE}"
-	rm "${TMPFILE}"
+  grep "^${CATEGORY}|" "${INDEX_FILE}" > "${TMPFILE}"
+  show_package_file "${TMPFILE}"
+  rm "${TMPFILE}"
 };
 
 show_package_by_name()
 {
-	CATEGORY="${1}"
-	PACKAGE="${2}"
-	INDEX_FILE="${PKGDIR}/INDEX.parsed"
-	TMPFILE="/tmp/.pkg.cat.pak"
+  CATEGORY="${1}"
+  PACKAGE="${2}"
+  INDEX_FILE="${PKGDIR}/INDEX.parsed"
+  TMPFILE="/tmp/.pkg.cat.pak"
 
-	grep "^${CATEGORY}|${PACKAGE}" "${INDEX_FILE}" > "${TMPFILE}"
-	show_package_file "${TMPFILE}"
-	rm "${TMPFILE}"
+  grep "^${CATEGORY}|${PACKAGE}" "${INDEX_FILE}" > "${TMPFILE}"
+  show_package_file "${TMPFILE}"
+  rm "${TMPFILE}"
 };
 
 show_packages()
 {
-	show_package_file "${PKGDIR}/INDEX.parsed"
+  show_package_file "${PKGDIR}/INDEX.parsed"
 };
 
 get_package_dependencies()
 {
-	PACKAGE="${1}"
-	LONG="${2:-0}"
-	RES=0
+  PACKAGE="${1}"
+  LONG="${2:-0}"
+  RES=0
 
-	INDEX_FILE="${PKGDIR}/INDEX.deps"
-	REGEX="^${PACKAGE}|"
+  INDEX_FILE="${PKGDIR}/INDEX.deps"
+  REGEX="^${PACKAGE}|"
 
-	if [ "${LONG}" -ne "0" ]
-	then
-		REGEX="^.*|${PACKAGE}|"
-	fi
+  if [ "${LONG}" -ne "0" ]
+  then
+    REGEX="^.*|${PACKAGE}|"
+  fi
 
-	LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
-	DEPS=`echo "${LINE}"|cut -f3 -d'|'`
+  LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
+  DEPS=`echo "${LINE}"|cut -f3 -d'|'`
 
-	VAL="${DEPS}"
-	export VAL
+  VAL="${DEPS}"
+  export VAL
 
-	if [ -z "${VAL}" ]
-	then
-		RES=1
-	fi
+  if [ -z "${VAL}" ]
+  then
+    RES=1
+  fi
 
-	return ${RES}
+  return ${RES}
 };
 
 get_package_name()
 {
-	PACKAGE="${1}"
-	RES=0
+  PACKAGE="${1}"
+  RES=0
 
-	INDEX_FILE="${PKGDIR}/INDEX.deps"
-	REGEX="^${PACKAGE}|"
+  INDEX_FILE="${PKGDIR}/INDEX.deps"
+  REGEX="^${PACKAGE}|"
 	
-	LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
-	NAME=`echo "${LINE}"|cut -f2 -d'|'`
+  LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
+  NAME=`echo "${LINE}"|cut -f2 -d'|'`
 
-	VAL="${NAME}"
-	export VAL
+  VAL="${NAME}"
+  export VAL
 
-	if [ -z "${VAL}" ]
-	then
-		RES=1
-	fi
+  if [ -z "${VAL}" ]
+  then
+    RES=1
+  fi
 
-	return ${RES}
+  return ${RES}
 };
 
 get_package_short_name()
 {
-	PACKAGE="${1}"
-	RES=0
+  PACKAGE="${1}"
+  RES=0
 
-	INDEX_FILE="${PKGDIR}/INDEX.deps"
-	REGEX="^.*|${PACKAGE}|"
+  INDEX_FILE="${PKGDIR}/INDEX.deps"
+  REGEX="^.*|${PACKAGE}|"
 	
-	LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
-	NAME=`echo "${LINE}"|cut -f1 -d'|'`
+  LINE=`grep "${REGEX}" "${INDEX_FILE}" 2>/dev/null`
+  NAME=`echo "${LINE}"|cut -f1 -d'|'`
 
-	VAL="${NAME}"
-	export VAL
+  VAL="${NAME}"
+  export VAL
 
-	if [ -z "${VAL}" ]
-	then
-		RES=1
-	fi
+  if [ -z "${VAL}" ]
+  then
+    RES=1
+  fi
 
-	return ${RES}
+  return ${RES}
 };
 
 get_package_category()
 {
-	PACKAGE="${1}"
-	INDEX_FILE="${PKGDIR}/INDEX.parsed"
-	RES=0
+  PACKAGE="${1}"
+  INDEX_FILE="${PKGDIR}/INDEX.parsed"
+  RES=0
 
-	LINE=`grep "|${PACKAGE}|" "${INDEX_FILE}" 2>/dev/null`
-	NAME=`echo "${LINE}"|cut -f1 -d'|'`
+  LINE=`grep "|${PACKAGE}|" "${INDEX_FILE}" 2>/dev/null`
+  NAME=`echo "${LINE}"|cut -f1 -d'|'`
 
-	VAL="${NAME}"
-	export VAL
+  VAL="${NAME}"
+  export VAL
 
-	if [ -z "${VAL}" ]
-	then
-		RES=1
-	fi
+  if [ -z "${VAL}" ]
+  then
+    RES=1
+  fi
 
-	return ${RES}
+  return ${RES}
 };
 
 fetch_package_by_ftp()
 {
-	CATEGORY="${1}"
-	PACKAGE="${2}"
-	SAVEDIR="${3}"
+  CATEGORY="${1}"
+  PACKAGE="${2}"
+  SAVEDIR="${3}"
 
-	get_value_from_cfg ftpHost
-	if [ -z "$VAL" ]
-	then
-		exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
-	fi
-	FTPHOST="${VAL}"
+  get_value_from_cfg ftpHost
+  if [ -z "$VAL" ]
+  then
+    exit_err "ERROR: Install medium was set to ftp, but no ftpHost was provided!" 
+  fi
+  FTPHOST="${VAL}"
 
-	get_value_from_cfg ftpDir
-	if [ -z "$VAL" ]
-	then
-		exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
-	fi
-	FTPDIR="${VAL}"
+  get_value_from_cfg ftpDir
+  if [ -z "$VAL" ]
+  then
+    exit_err "ERROR: Install medium was set to ftp, but no ftpDir was provided!" 
+  fi
+  FTPDIR="${VAL}"
 
-	PACKAGE="${PACKAGE}.tbz"
-	FTP_SERVER="ftp://${FTPHOST}${FTPDIR}"
+  PACKAGE="${PACKAGE}.tbz"
+  FTP_SERVER="ftp://${FTPHOST}${FTPDIR}"
 
-	if [ ! -f "${SAVEDIR}/${PACKAGE}" ]
-	then
-		PKGPATH="${CATEGORY}/${PACKAGE}"
-		FTP_PATH="${FTP_HOST}/packages/${PKGPATH}"
-		fetch_file "${FTP_PATH}" "${SAVEDIR}/" "0"
-	fi
+  if [ ! -f "${SAVEDIR}/${PACKAGE}" ]
+  then
+    PKGPATH="${CATEGORY}/${PACKAGE}"
+    FTP_PATH="${FTP_HOST}/packages/${PKGPATH}"
+    fetch_file "${FTP_PATH}" "${SAVEDIR}/" "0"
+  fi
 };
 
 fetch_package_by_fs()
 {
-	CATEGORY="${1}"
-	PACKAGE="${2}"
-	SAVEDIR="${3}"
+  CATEGORY="${1}"
+  PACKAGE="${2}"
+  SAVEDIR="${3}"
 
-	PACKAGE="${PACKAGE}.tbz"
-	if [ ! -f "${SAVEDIR}/${PACKAGE}" ]
-	then
-		fetch_file "${CDMNT}/packages/${CATEGORY}/${PACKAGE}" "${SAVEDIR}/" "0"
-	fi
+  PACKAGE="${PACKAGE}.tbz"
+  if [ ! -f "${SAVEDIR}/${PACKAGE}" ]
+  then
+    fetch_file "${CDMNT}/packages/${CATEGORY}/${PACKAGE}" "${SAVEDIR}/" "0"
+  fi
 };
 
 fetch_package()
 {
-	CATEGORY="${1}"
-	PACKAGE="${2}"
-	SAVEDIR="${3}"
+  CATEGORY="${1}"
+  PACKAGE="${2}"
+  SAVEDIR="${3}"
 
-	case "${INSTALLMEDIUM}" in
-	usb|dvd)
-		fetch_package_by_fs "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}"
-		;;
-	ftp)
-		fetch_package_by_ftp "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}"
-		;;
-	esac
+  case "${INSTALLMEDIUM}" in
+    usb|dvd) fetch_package_by_fs "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}" ;;
+    ftp|sftp) fetch_package_by_ftp "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}" ;;
+  esac
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-parse.sh b/usr.sbin/pc-sysinstall/backend/functions-parse.sh
index a95cb33d1f7..3604ba4425b 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-parse.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-parse.sh
@@ -132,19 +132,19 @@ file_sanity_check()
   then
     for i in $1
     do
-       grep "^${i}=" $CFGF >/dev/null 2>/dev/null
-       if [ "$?" = "0" ]
-       then
-         LN=`grep "^${i}=" ${CFGF} | head -n 1 | cut -d '=' -f 2 | tr -d ' '`
-         if [ -z "${LN}" ]
-         then
-           echo "Error: Config fails sanity test! ${i}= is empty"
-           exit 1
-         fi
-       else
-         echo "Error: Config fails sanity test! Missing ${i}="
-         exit 1
-       fi
+      grep "^${i}=" $CFGF >/dev/null 2>/dev/null
+      if [ "$?" = "0" ]
+      then
+        LN=`grep "^${i}=" ${CFGF} | head -n 1 | cut -d '=' -f 2 | tr -d ' '`
+        if [ -z "${LN}" ]
+        then
+          echo "Error: Config fails sanity test! ${i}= is empty"
+          exit 1
+        fi
+      else
+        echo "Error: Config fails sanity test! Missing ${i}="
+        exit 1
+      fi
     done
   else
     echo "Error: Missing config file, and / or values to sanity check for!"
diff --git a/usr.sbin/pc-sysinstall/backend/functions-unmount.sh b/usr.sbin/pc-sysinstall/backend/functions-unmount.sh
index 631b0c36e96..a87d9010576 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-unmount.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-unmount.sh
@@ -28,13 +28,14 @@
 # Functions which unmount all mounted disk filesystems
 
 # Unmount all mounted partitions under specified dir
-umount_all_dir() {
-  	_udir="$1"
-	_umntdirs=`mount | sort -r | grep "on $_udir" | cut -d ' ' -f 3`
-	for _ud in $_umntdirs
-	do
-		umount -f ${_ud} 
-	done
+umount_all_dir()
+{
+  _udir="$1"
+  _umntdirs=`mount | sort -r | grep "on $_udir" | cut -d ' ' -f 3`
+  for _ud in $_umntdirs
+  do
+    umount -f ${_ud} 
+  done
 }
 
 # Script that adds our gmirror devices for syncing
@@ -58,93 +59,93 @@ start_gmirror_sync()
 # Unmounts all our mounted file-systems
 unmount_all_filesystems()
 {
-   # Copy the logfile to disk before we unmount
-   cp ${LOGOUT} ${FSMNT}/root/pc-sysinstall.log
-   cd /
+  # Copy the logfile to disk before we unmount
+  cp ${LOGOUT} ${FSMNT}/root/pc-sysinstall.log
+  cd /
 
-   # Start by unmounting any ZFS partitions
-   zfs_cleanup_unmount
+  # Start by unmounting any ZFS partitions
+  zfs_cleanup_unmount
 
-   # Lets read our partition list, and unmount each
-   ##################################################################
-   for PART in `ls ${PARTDIR}`
-   do
-     
-     PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
-     PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
-     PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
-     PARTLABEL="`cat ${PARTDIR}/${PART} | cut -d ':' -f 4`"
+  # Lets read our partition list, and unmount each
+  ##################################################################
+  for PART in `ls ${PARTDIR}`
+  do
+         
+    PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
+    PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
+    PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
+    PARTLABEL="`cat ${PARTDIR}/${PART} | cut -d ':' -f 4`"
 
-     if [ "${PARTENC}" = "ON" ]
-     then
-       EXT=".eli"
-     else
-       EXT=""
-     fi
+    if [ "${PARTENC}" = "ON" ]
+    then
+      EXT=".eli"
+    else
+      EXT=""
+    fi
 
-     #if [ "${PARTFS}" = "SWAP" ]
-     #then
-     #  rc_nohalt "swapoff /dev/${PART}${EXT}"
-     #fi
+    #if [ "${PARTFS}" = "SWAP" ]
+    #then
+    #  rc_nohalt "swapoff /dev/${PART}${EXT}"
+    #fi
 
-     # Check if we've found "/", and unmount that last
-     if [ "$PARTMNT" != "/" -a "${PARTMNT}" != "none" -a "${PARTFS}" != "ZFS" ]
-     then
-       rc_halt "umount -f /dev/${PART}${EXT}"
+    # Check if we've found "/", and unmount that last
+    if [ "$PARTMNT" != "/" -a "${PARTMNT}" != "none" -a "${PARTFS}" != "ZFS" ]
+    then
+      rc_halt "umount -f /dev/${PART}${EXT}"
 
-       # Re-check if we are missing a label for this device and create it again if so
-       if [ ! -e "/dev/label/${PARTLABEL}" ]
-       then
-         case ${PARTFS} in
-             UFS) glabel label ${PARTLABEL} /dev/${PART}${EXT} ;;
-           UFS+S) glabel label ${PARTLABEL} /dev/${PART}${EXT} ;;
-           UFS+J) glabel label ${PARTLABEL} /dev/${PART}${EXT}.journal ;;
-               *) ;;
-         esac 
-       fi
-     fi
+      # Re-check if we are missing a label for this device and create it again if so
+      if [ ! -e "/dev/label/${PARTLABEL}" ]
+      then
+        case ${PARTFS} in
+          UFS) glabel label ${PARTLABEL} /dev/${PART}${EXT} ;;
+          UFS+S) glabel label ${PARTLABEL} /dev/${PART}${EXT} ;;
+          UFS+J) glabel label ${PARTLABEL} /dev/${PART}${EXT}.journal ;;
+          *) ;;
+        esac 
+      fi
+    fi
 
-     # Check if we've found "/" and make sure the label exists
-     if [ "$PARTMNT" = "/" -a "${PARTFS}" != "ZFS" ]
-     then
-       if [ ! -e "/dev/label/${PARTLABEL}" ]
-       then
-         case ${PARTFS} in
-             UFS) ROOTRELABEL="glabel label ${PARTLABEL} /dev/${PART}${EXT}" ;;
-           UFS+S) ROOTRELABEL="glabel label ${PARTLABEL} /dev/${PART}${EXT}" ;;
-           UFS+J) ROOTRELABEL="glabel label ${PARTLABEL} /dev/${PART}${EXT}.journal" ;;
-               *) ;;
-         esac 
-       fi
-     fi
-   done
+    # Check if we've found "/" and make sure the label exists
+    if [ "$PARTMNT" = "/" -a "${PARTFS}" != "ZFS" ]
+    then
+      if [ ! -e "/dev/label/${PARTLABEL}" ]
+      then
+        case ${PARTFS} in
+          UFS) ROOTRELABEL="glabel label ${PARTLABEL} /dev/${PART}${EXT}" ;;
+          UFS+S) ROOTRELABEL="glabel label ${PARTLABEL} /dev/${PART}${EXT}" ;;
+          UFS+J) ROOTRELABEL="glabel label ${PARTLABEL} /dev/${PART}${EXT}.journal" ;;
+          *) ;;
+        esac 
+      fi
+    fi
+  done
 
-   # Last lets the /mnt partition
-   #########################################################
-   rc_nohalt "umount -f ${FSMNT}"
+  # Last lets the /mnt partition
+  #########################################################
+  rc_nohalt "umount -f ${FSMNT}"
 
-    # If are using a ZFS on "/" set it to legacy
-   if [ ! -z "${FOUNDZFSROOT}" ]
-   then
-     rc_halt "zfs set mountpoint=legacy ${FOUNDZFSROOT}"
-   fi
+   # If are using a ZFS on "/" set it to legacy
+  if [ ! -z "${FOUNDZFSROOT}" ]
+  then
+    rc_halt "zfs set mountpoint=legacy ${FOUNDZFSROOT}"
+  fi
 
-   # If we need to relabel "/" do it now
-   if [ ! -z "${ROOTRELABEL}" ]
-   then
-     ${ROOTRELABEL}
-   fi
+  # If we need to relabel "/" do it now
+  if [ ! -z "${ROOTRELABEL}" ]
+  then
+    ${ROOTRELABEL}
+  fi
 
-   # Unmount our CDMNT
-   rc_nohalt "umount -f ${CDMNT}" >/dev/null 2>/dev/null
+  # Unmount our CDMNT
+  rc_nohalt "umount -f ${CDMNT}" >/dev/null 2>/dev/null
 
-   # Check if we need to run any gmirror syncing
-   ls ${MIRRORCFGDIR}/* >/dev/null 2>/dev/null
-   if [ "$?" = "0" ]
-   then
-     # Lets start syncing now
-     start_gmirror_sync
-   fi
+  # Check if we need to run any gmirror syncing
+  ls ${MIRRORCFGDIR}/* >/dev/null 2>/dev/null
+  if [ "$?" = "0" ]
+  then
+    # Lets start syncing now
+    start_gmirror_sync
+  fi
 
 };
 
@@ -164,43 +165,43 @@ unmount_all_filesystems_failure()
     for PART in `ls ${PARTDIR}`
     do
      
-       PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
-       PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
-       PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
+      PARTFS="`cat ${PARTDIR}/${PART} | cut -d ':' -f 1`"
+      PARTMNT="`cat ${PARTDIR}/${PART} | cut -d ':' -f 2`"
+      PARTENC="`cat ${PARTDIR}/${PART} | cut -d ':' -f 3`"
 
-       #if [ "${PARTFS}" = "SWAP" ]
-       #then
-       #  if [ "${PARTENC}" = "ON" ]
-       #  then
-       #    rc_nohalt "swapoff /dev/${PART}.eli"
-       #  else
-       #    rc_nohalt "swapoff /dev/${PART}"
-       #  fi
-       #fi
+      #if [ "${PARTFS}" = "SWAP" ]
+      #then
+      #  if [ "${PARTENC}" = "ON" ]
+      #  then
+      #    rc_nohalt "swapoff /dev/${PART}.eli"
+      #  else
+      #    rc_nohalt "swapoff /dev/${PART}"
+      #  fi
+      #fi
 
-       # Check if we've found "/" again, don't need to mount it twice
-       if [ "$PARTMNT" != "/" -a "${PARTMNT}" != "none" -a "${PARTFS}" != "ZFS" ]
-       then
-         rc_nohalt "umount -f /dev/${PART}"
-         rc_nohalt "umount -f ${FSMNT}${PARTMNT}"
-       fi
-     done
+      # Check if we've found "/" again, don't need to mount it twice
+      if [ "$PARTMNT" != "/" -a "${PARTMNT}" != "none" -a "${PARTFS}" != "ZFS" ]
+      then
+        rc_nohalt "umount -f /dev/${PART}"
+        rc_nohalt "umount -f ${FSMNT}${PARTMNT}"
+      fi
+    done
 
-     # Last lets the /mnt partition
-     #########################################################
-     rc_nohalt "umount -f ${FSMNT}"
+    # Last lets the /mnt partition
+    #########################################################
+    rc_nohalt "umount -f ${FSMNT}"
 
-    fi
-   else
-     # We are doing a upgrade, try unmounting any of these filesystems
-     chroot ${FSMNT} /sbin/umount -a >>${LOGOUT} >>${LOGOUT}
-     umount -f ${FSMNT}/usr >>${LOGOUT} 2>>${LOGOUT}
-     umount -f ${FSMNT}/dev >>${LOGOUT} 2>>${LOGOUT}
-     umount -f ${FSMNT} >>${LOGOUT} 2>>${LOGOUT}
-     rc_nohalt "sh ${TMPDIR}/.upgrade-unmount"
    fi
+  else
+    # We are doing a upgrade, try unmounting any of these filesystems
+    chroot ${FSMNT} /sbin/umount -a >>${LOGOUT} >>${LOGOUT}
+    umount -f ${FSMNT}/usr >>${LOGOUT} 2>>${LOGOUT}
+    umount -f ${FSMNT}/dev >>${LOGOUT} 2>>${LOGOUT}
+    umount -f ${FSMNT} >>${LOGOUT} 2>>${LOGOUT}
+    rc_nohalt "sh ${TMPDIR}/.upgrade-unmount"
+  fi
    
-   # Unmount our CDMNT
-   rc_nohalt "umount ${CDMNT}"
+  # Unmount our CDMNT
+  rc_nohalt "umount ${CDMNT}"
 
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-upgrade.sh b/usr.sbin/pc-sysinstall/backend/functions-upgrade.sh
index 4b9c0c6dce3..fb04bde249e 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-upgrade.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-upgrade.sh
@@ -43,8 +43,8 @@ mount_target_slice()
   if [ -e "/dev/${MPART}" ] ; then
     rc_nohalt "mount /dev/${MPART} ${FSMNT}"
     if [ "$?" != "0" ] ; then
-    	# Check if we have ZFS tank name
-    	rc_halt "mount -t zfs ${MPART} ${FSMNT}"
+      # Check if we have ZFS tank name
+      rc_halt "mount -t zfs ${MPART} ${FSMNT}"
     fi
   else
     # Check if we have ZFS tank name
@@ -104,7 +104,7 @@ done
     run_chroot_cmd "rm -rf /libexec" >/dev/null 2>/dev/null
   fi
 
-}
+};
 
 # Mount the target upgrade partitions
 mount_upgrade()
@@ -116,33 +116,33 @@ mount_upgrade()
   # We are ready to start mounting, lets read the config and do it
   while read line
   do
-     echo $line | grep "^disk0=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
+    echo $line | grep "^disk0=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
 
-       # Found a disk= entry, lets get the disk we are working on
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       DISK="$VAL"
-     fi
+      # Found a disk= entry, lets get the disk we are working on
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      DISK="$VAL"
+    fi
 
-     echo $line | grep "^commitDiskPart" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       # Found our flag to commit this disk setup / lets do sanity check and do it
-       if [ ! -z "${DISK}" ]
-       then
+    echo $line | grep "^commitDiskPart" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      # Found our flag to commit this disk setup / lets do sanity check and do it
+      if [ ! -z "${DISK}" ]
+      then
 
-         # Start mounting this slice
-         mount_target_slice "${DISK}" 
+        # Start mounting this slice
+        mount_target_slice "${DISK}" 
 
-         # Increment our disk counter to look for next disk and unset
-         unset DISK
-	 break
-       else
-         exit_err "ERROR: commitDiskPart was called without procceding disk= and partition= entries!!!" 
-       fi
-     fi
+        # Increment our disk counter to look for next disk and unset
+        unset DISK
+	    break
+      else
+        exit_err "ERROR: commitDiskPart was called without procceding disk= and partition= entries!!!" 
+      fi
+    fi
 
   done <${CFGF}
 
@@ -151,8 +151,8 @@ mount_upgrade()
 copy_skel_files_upgrade()
 {
 
-    # Now make sure we fix any user profile scripts, which cause problems from 7.x->8.x
-    echo '#!/bin/sh
+  # Now make sure we fix any user profile scripts, which cause problems from 7.x->8.x
+  echo '#!/bin/sh
 
 cd /home
 for i in `ls`
@@ -179,17 +179,17 @@ do
 
 done
 ' >${FSMNT}/.fixUserProfile.sh  
-    chmod 755 ${FSMNT}/.fixUserProfile.sh
-    chroot ${FSMNT} /.fixUserProfile.sh >/dev/null 2>/dev/null
-    rm ${FSMNT}/.fixUserProfile.sh
+  chmod 755 ${FSMNT}/.fixUserProfile.sh
+  chroot ${FSMNT} /.fixUserProfile.sh >/dev/null 2>/dev/null
+  rm ${FSMNT}/.fixUserProfile.sh
 
 
 
-    # if the user wants to keep their original .kde4 profile
-    ###########################################################################
-    get_value_from_cfg "upgradeKeepDesktopProfile"
-    if [ "$VAL" = "YES" -o "$VAL" = "yes" ] ; then
-      echo '#!/bin/sh
+  # if the user wants to keep their original .kde4 profile
+  ###########################################################################
+  get_value_from_cfg "upgradeKeepDesktopProfile"
+  if [ "$VAL" = "YES" -o "$VAL" = "yes" ] ; then
+    echo '#!/bin/sh
       cd /home
 for i in `ls`
 do
@@ -202,11 +202,11 @@ do
   fi
 done
 ' >${FSMNT}/.fixUserProfile.sh
-      chmod 755 ${FSMNT}/.fixUserProfile.sh
-      chroot ${FSMNT} /.fixUserProfile.sh >/dev/null 2>/dev/null
-      rm ${FSMNT}/.fixUserProfile.sh
+    chmod 755 ${FSMNT}/.fixUserProfile.sh
+    chroot ${FSMNT} /.fixUserProfile.sh >/dev/null 2>/dev/null
+    rm ${FSMNT}/.fixUserProfile.sh
 
-    fi
+  fi
 
 };
 
@@ -230,18 +230,18 @@ merge_old_configs()
 unmount_upgrade()
 {
 
-   # If on PC-BSD, make sure we copy any fixed skel files
-   if [ "$INSTALLTYPE" != "FreeBSD" ] ; then
-     copy_skel_files_upgrade
-   fi
+  # If on PC-BSD, make sure we copy any fixed skel files
+  if [ "$INSTALLTYPE" != "FreeBSD" ] ; then
+    copy_skel_files_upgrade
+  fi
 
-   cd /
+  cd /
 
-   # Unmount FS
-   umount_all_dir "${FSMNT}"
+  # Unmount FS
+  umount_all_dir "${FSMNT}"
 
-   # Run our saved unmount script for these file-systems
-   rc_nohalt "umount -f ${FSMNT}"
+  # Run our saved unmount script for these file-systems
+  rc_nohalt "umount -f ${FSMNT}"
  
-   umount ${CDMNT} 
+  umount ${CDMNT} 
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-users.sh b/usr.sbin/pc-sysinstall/backend/functions-users.sh
index 12a0fac613c..4ba8de58d17 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-users.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-users.sh
@@ -72,99 +72,99 @@ setup_users()
   while read line
   do
 
-     echo $line | grep "^userName=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       get_value_from_string "${line}"
-       USERNAME="$VAL"
-     fi
+    echo $line | grep "^userName=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      get_value_from_string "${line}"
+      USERNAME="$VAL"
+    fi
 
-     echo $line | grep "^userComment=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       get_value_from_string "${line}"
-       USERCOMMENT="$VAL"
-     fi
+    echo $line | grep "^userComment=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      get_value_from_string "${line}"
+      USERCOMMENT="$VAL"
+    fi
 
-     echo $line | grep "^userPass=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       get_value_from_string "${line}"
-       USERPASS="$VAL"
-     fi
+    echo $line | grep "^userPass=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      get_value_from_string "${line}"
+      USERPASS="$VAL"
+    fi
 
-     echo $line | grep "^userShell=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       USERSHELL="$VAL"
-     fi
+    echo $line | grep "^userShell=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      USERSHELL="$VAL"
+    fi
 
-     echo $line | grep "^userHome=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       get_value_from_string "${line}"
-       USERHOME="$VAL"
-     fi
+    echo $line | grep "^userHome=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      get_value_from_string "${line}"
+      USERHOME="$VAL"
+    fi
 
-     echo $line | grep "^userGroups=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       get_value_from_string "${line}"
-       USERGROUPS="$VAL"
-     fi
+    echo $line | grep "^userGroups=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      get_value_from_string "${line}"
+      USERGROUPS="$VAL"
+    fi
 
 
-     echo $line | grep "^commitUser" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       # Found our flag to commit this user, lets check and do it
-       if [ ! -z "${USERNAME}" ]
-       then
+    echo $line | grep "^commitUser" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      # Found our flag to commit this user, lets check and do it
+      if [ ! -z "${USERNAME}" ]
+      then
 
-         # Now add this user to the system, by building our args list
-         ARGS="-n ${USERNAME}"
+        # Now add this user to the system, by building our args list
+        ARGS="-n ${USERNAME}"
 
-         if [ ! -z "${USERCOMMENT}" ]
-         then
-           ARGS="${ARGS} -c \"${USERCOMMENT}\""
-         fi
+        if [ ! -z "${USERCOMMENT}" ]
+        then
+          ARGS="${ARGS} -c \"${USERCOMMENT}\""
+        fi
          
-         if [ ! -z "${USERPASS}" ]
-         then
-           ARGS="${ARGS} -h 0"
-           echo "${USERPASS}" >${FSMNT}/.tmpPass
-         else
-           ARGS="${ARGS} -h -"
-           rm ${FSMNT}/.tmpPass 2>/dev/null 2>/dev/null
-         fi
+        if [ ! -z "${USERPASS}" ]
+        then
+          ARGS="${ARGS} -h 0"
+          echo "${USERPASS}" >${FSMNT}/.tmpPass
+        else
+          ARGS="${ARGS} -h -"
+          rm ${FSMNT}/.tmpPass 2>/dev/null 2>/dev/null
+        fi
 
-         if [ ! -z "${USERSHELL}" ]
-         then
-           ARGS="${ARGS} -s \"${USERSHELL}\""
-         else
-           ARGS="${ARGS} -s \"/nonexistant\""
-         fi
+        if [ ! -z "${USERSHELL}" ]
+        then
+          ARGS="${ARGS} -s \"${USERSHELL}\""
+        else
+          ARGS="${ARGS} -s \"/nonexistant\""
+        fi
          
-         if [ ! -z "${USERHOME}" ]
-         then
-           ARGS="${ARGS} -m -d \"${USERHOME}\""
-         fi
+        if [ ! -z "${USERHOME}" ]
+        then
+          ARGS="${ARGS} -m -d \"${USERHOME}\""
+        fi
 
-         if [ ! -z "${USERGROUPS}" ]
-         then
-           ARGS="${ARGS} -G \"${USERGROUPS}\""
-         fi
+        if [ ! -z "${USERGROUPS}" ]
+        then
+          ARGS="${ARGS} -G \"${USERGROUPS}\""
+        fi
 
-         add_user "${ARGS}"
+        add_user "${ARGS}"
 
-         # Unset our vars before looking for any more users
-         unset USERNAME USERCOMMENT USERPASS USERSHELL USERHOME USERGROUPS
-       else
-         exit_err "ERROR: commitUser was called without any userName= entry!!!" 
-       fi
-     fi
+        # Unset our vars before looking for any more users
+        unset USERNAME USERCOMMENT USERPASS USERSHELL USERHOME USERGROUPS
+      else
+        exit_err "ERROR: commitUser was called without any userName= entry!!!" 
+      fi
+    fi
 
   done <${CFGF}
 
diff --git a/usr.sbin/pc-sysinstall/backend/functions.sh b/usr.sbin/pc-sysinstall/backend/functions.sh
index 2fb306e410a..f51902a54ea 100755
--- a/usr.sbin/pc-sysinstall/backend/functions.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions.sh
@@ -98,18 +98,18 @@ strip_white_space()
 # Displays an error message and exits with error 1
 exit_err()
 {
-   # Echo the message for the users benefit
-   echo "$1"
+  # Echo the message for the users benefit
+  echo "$1"
 
-   # Save this error to the log file
-   echo "${1}" >>$LOGOUT
+  # Save this error to the log file
+  echo "${1}" >>$LOGOUT
 
-   # Check if we need to unmount any file-systems after this failure
-   unmount_all_filesystems_failure
+  # Check if we need to unmount any file-systems after this failure
+  unmount_all_filesystems_failure
 
-   echo "For more details see log file: $LOGOUT"
+  echo "For more details see log file: $LOGOUT"
 
-   exit 1
+  exit 1
 };
 
 # Run-command, don't halt if command exits with non-0
@@ -195,66 +195,67 @@ echo_log()
 };
 
 # Make sure we have a numeric
-is_num() {
-        expr $1 + 1 2>/dev/null
-        return $?
+is_num()
+{
+  expr $1 + 1 2>/dev/null
+  return $?
 }
 
 # Function which uses "fetch" to download a file, and display a progress report
 fetch_file()
 {
 
-FETCHFILE="$1"
-FETCHOUTFILE="$2"
-EXITFAILED="$3"
+  FETCHFILE="$1"
+  FETCHOUTFILE="$2"
+  EXITFAILED="$3"
 
-SIZEFILE="${TMPDIR}/.fetchSize"
-EXITFILE="${TMPDIR}/.fetchExit"
+  SIZEFILE="${TMPDIR}/.fetchSize"
+  EXITFILE="${TMPDIR}/.fetchExit"
 
-rm ${SIZEFILE} 2>/dev/null >/dev/null
-rm ${FETCHOUTFILE} 2>/dev/null >/dev/null
+  rm ${SIZEFILE} 2>/dev/null >/dev/null
+  rm ${FETCHOUTFILE} 2>/dev/null >/dev/null
 
-fetch -s "${FETCHFILE}" >${SIZEFILE}
-SIZE="`cat ${SIZEFILE}`"
-SIZE="`expr ${SIZE} / 1024`"
-echo "FETCH: ${FETCHFILE}"
-echo "FETCH: ${FETCHOUTFILE}" >>${LOGOUT}
+  fetch -s "${FETCHFILE}" >${SIZEFILE}
+  SIZE="`cat ${SIZEFILE}`"
+  SIZE="`expr ${SIZE} / 1024`"
+  echo "FETCH: ${FETCHFILE}"
+  echo "FETCH: ${FETCHOUTFILE}" >>${LOGOUT}
 
-( fetch -o ${FETCHOUTFILE} "${FETCHFILE}" >/dev/null 2>/dev/null ; echo "$?" > ${EXITFILE} ) &
-PID="$!"
-while
-z=1
-do
+  ( fetch -o ${FETCHOUTFILE} "${FETCHFILE}" >/dev/null 2>/dev/null ; echo "$?" > ${EXITFILE} ) &
+  PID="$!"
+  while
+  z=1
+  do
 
-  if [ -e "${FETCHOUTFILE}" ]
-  then
-    DSIZE=`du -k ${FETCHOUTFILE} | tr -d '\t' | cut -d '/' -f 1`
-    if [ $(is_num "$DSIZE") ] ; then
-	if [ $SIZE -lt $DSIZE ] ; then DSIZE="$SIZE"; fi 
+    if [ -e "${FETCHOUTFILE}" ]
+    then
+      DSIZE=`du -k ${FETCHOUTFILE} | tr -d '\t' | cut -d '/' -f 1`
+      if [ $(is_num "$DSIZE") ] ; then
+      if [ $SIZE -lt $DSIZE ] ; then DSIZE="$SIZE"; fi 
     	echo "SIZE: ${SIZE} DOWNLOADED: ${DSIZE}"
     	echo "SIZE: ${SIZE} DOWNLOADED: ${DSIZE}" >>${LOGOUT}
+      fi
     fi
-  fi
 
-  # Check if the download is finished
-  ps -p ${PID} >/dev/null 2>/dev/null
-  if [ "$?" != "0" ]
+    # Check if the download is finished
+    ps -p ${PID} >/dev/null 2>/dev/null
+    if [ "$?" != "0" ]
+    then
+      break;
+    fi
+
+    sleep 2
+  done
+
+  echo "FETCHDONE"
+
+  EXIT="`cat ${EXITFILE}`"
+  if [ "${EXIT}" != "0" -a "$EXITFAILED" = "1" ]
   then
-   break;
+    exit_err "Error: Failed to download ${FETCHFILE}"
   fi
 
-  sleep 2
-done
-
-echo "FETCHDONE"
-
-EXIT="`cat ${EXITFILE}`"
-if [ "${EXIT}" != "0" -a "$EXITFAILED" = "1" ]
-then
-  exit_err "Error: Failed to download ${FETCHFILE}"
-fi
-
-return $EXIT
+  return $EXIT
 
 };
 
diff --git a/usr.sbin/pc-sysinstall/backend/parseconfig.sh b/usr.sbin/pc-sysinstall/backend/parseconfig.sh
index 89b25eae83c..ff5694ccb3b 100755
--- a/usr.sbin/pc-sysinstall/backend/parseconfig.sh
+++ b/usr.sbin/pc-sysinstall/backend/parseconfig.sh
@@ -73,7 +73,7 @@ file_sanity_check "installMode disk0 installType installMedium packageType"
 check_value installMode "fresh upgrade"
 check_value bootManager "bsd none"
 check_value installType "PCBSD FreeBSD"
-check_value installMedium "dvd usb ftp rsync"
+check_value installMedium "dvd usb ftp rsync img"
 check_value packageType "uzip tar rsync split"
 if_check_value_exists partition "all ALL s1 s2 s3 s4 free FREE"
 if_check_value_exists mirrorbal "load prefer round-robin split"
diff --git a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
index bae78c1f986..088dea7b1af 100755
--- a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
+++ b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
@@ -38,8 +38,8 @@
 # Set this to the program location
 if [ -z "${PROGDIR}" ]
 then
-	PROGDIR="/usr/share/pc-sysinstall"
-	export PROGDIR
+  PROGDIR="/usr/share/pc-sysinstall"
+  export PROGDIR
 fi
 
 # Set this to the components location
@@ -89,29 +89,31 @@ fi
 # Check if we are called without any flags and display help
 if [ -z "${1}" ]
 then
-   # Display the help index
-   display_help
-   exit 0
+  # Display the help index
+  display_help
+  exit 0
 fi
 
 case $1 in
   # The -c flag has been given, time to parse the script
-  -c) if [ -z "${2}" ]
-        then
-          display_help
-        else
-          ${BACKEND}/parseconfig.sh ${2}
-          exit $?
-        fi
+  -c)
+    if [ -z "${2}" ]
+    then
+      display_help
+    else
+      ${BACKEND}/parseconfig.sh ${2}
+      exit $?
+    fi
   ;;
 
   # The user requsted help
-  help) if [ -z "${2}" ]
-        then
-          display_help
-        else
-          display_command_help ${2}
-        fi
+  help)
+    if [ -z "${2}" ]
+    then
+      display_help
+    else
+      display_command_help ${2}
+    fi
   ;;
 
   # Parse an auto-install directive, and begin the installation
@@ -143,7 +145,7 @@ case $1 in
   ;;
 
   # The user is wanting to query which disks are available
-  disk-list) ${QUERYDIR}/disk-list.sh "${2}"
+  disk-list) ${QUERYDIR}/disk-list.sh $*
   ;;
   
   # The user is wanting to query a disk's partitions

From b57429d0820250b6329535bf5a39d60305c79efb Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Tue, 24 Aug 2010 06:30:46 +0000
Subject: [PATCH 0188/1624] Create a checklist and call one of the *printw()
 functions from the selected() callback. When the dialog first appears, you
 will not see the printed statement on the dialog, if you move down one, you
 will, move up again and it now appears. I am assuming that you call a
 *printw() function on a line in the dialog box of course.

The fix, from the pr:
	This is a hack at best, I looked at the redraw code in
	dialog_checklist() and took the minimal amount of it out to do
	a simple "refresh" right after the items are drawn. This
	doesn't hurt anything and makes the library work like it
	should. There is probably a better way however =).

PR:		148609
Submitted by:	John Hixson
---
 gnu/lib/libdialog/checklist.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/gnu/lib/libdialog/checklist.c b/gnu/lib/libdialog/checklist.c
index dc65d755b86..e349ca6bf07 100644
--- a/gnu/lib/libdialog/checklist.c
+++ b/gnu/lib/libdialog/checklist.c
@@ -198,6 +198,24 @@ draw:
     wnoutrefresh(dialog);
     wmove(list, choice, check_x+1);
     wrefresh(list);
+
+    /*
+     *	XXX Black magic voodoo that allows printing to the checklist
+     *	window. For some reason, if this "refresh" code is not in
+     *	place, printing to the window from the selected callback
+     *	prints "behind" the checklist window. There is probably a
+     *	better way to do this.
+     */
+    draw_box(dialog, box_y, box_x, list_height + 2, list_width + 2, menubox_border_attr, menubox_attr);
+
+    for (i = 0; i < max_choice; i++)
+	print_item(list, items[i * 3], items[i * 3 + 1], status[i], i, i == choice, DREF(ditems, i), list_width, item_x, check_x);
+    print_arrows(dialog, scroll, list_height, item_no, box_x, box_y, check_x + 4, cur_x, cur_y);
+
+    wmove(list, choice, check_x+1);
+    wnoutrefresh(dialog);
+    wrefresh(list);
+    /* XXX Black magic XXX */
     
     while (key != ESC) {
 	key = wgetch(dialog);

From baf28b69f43f5e51a5182149c160618fc38669fb Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Tue, 24 Aug 2010 07:22:24 +0000
Subject: [PATCH 0189/1624] - According to specification, SI_USER code should
 only be generated by   standard kill(). On other systems, SI_LWP is generated
 by lwp_kill().   This will allow conforming applications to differentiate
 between   signals generated by standard events and those generated by other  
 implementation events in a manner compatible with existing practice. - Bump
 __FreeBSD_version

---
 sys/kern/kern_thr.c | 4 ++--
 sys/sys/signal.h    | 1 +
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/sys/kern/kern_thr.c b/sys/kern/kern_thr.c
index d8f7a8eb0f8..17b6cd5d3d1 100644
--- a/sys/kern/kern_thr.c
+++ b/sys/kern/kern_thr.c
@@ -312,7 +312,7 @@ thr_kill(struct thread *td, struct thr_kill_args *uap)
 	error = 0;
 	ksiginfo_init(&ksi);
 	ksi.ksi_signo = uap->sig;
-	ksi.ksi_code = SI_USER;
+	ksi.ksi_code = SI_LWP;
 	ksi.ksi_pid = p->p_pid;
 	ksi.ksi_uid = td->td_ucred->cr_ruid;
 	PROC_LOCK(p);
@@ -371,7 +371,7 @@ thr_kill2(struct thread *td, struct thr_kill2_args *uap)
 	if (error == 0) {
 		ksiginfo_init(&ksi);
 		ksi.ksi_signo = uap->sig;
-		ksi.ksi_code = SI_USER;
+		ksi.ksi_code = SI_LWP;
 		ksi.ksi_pid = td->td_proc->p_pid;
 		ksi.ksi_uid = td->td_ucred->cr_ruid;
 		if (uap->id == -1) {
diff --git a/sys/sys/signal.h b/sys/sys/signal.h
index a7ca96e37d2..a8620575572 100644
--- a/sys/sys/signal.h
+++ b/sys/sys/signal.h
@@ -338,6 +338,7 @@ struct sigaction {
 #define	SI_MESGQ	0x10005		/* Signal generated by arrival of a */
 					/* message on an empty message queue. */
 #define	SI_KERNEL	0x10006
+#define	SI_LWP		0x10007		/* Signal sent by thr_kill */
 #endif
 #if __BSD_VISIBLE
 #define	SI_UNDEFINED	0

From 2961a78226146c45dbed5c8f0c66379162087a25 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Tue, 24 Aug 2010 07:29:55 +0000
Subject: [PATCH 0190/1624] Optimize thr_suspend, if timeout is zero, don't
 call msleep, just return immediately.

---
 sys/kern/kern_thr.c | 23 ++++++++++++++---------
 1 file changed, 14 insertions(+), 9 deletions(-)

diff --git a/sys/kern/kern_thr.c b/sys/kern/kern_thr.c
index 17b6cd5d3d1..21f064458bf 100644
--- a/sys/kern/kern_thr.c
+++ b/sys/kern/kern_thr.c
@@ -430,15 +430,12 @@ int
 kern_thr_suspend(struct thread *td, struct timespec *tsp)
 {
 	struct timeval tv;
-	int error = 0, hz = 0;
+	int error = 0;
+	int timo = 0;
 
 	if (tsp != NULL) {
 		if (tsp->tv_nsec < 0 || tsp->tv_nsec > 1000000000)
 			return (EINVAL);
-		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
-			return (ETIMEDOUT);
-		TIMESPEC_TO_TIMEVAL(&tv, tsp);
-		hz = tvtohz(&tv);
 	}
 
 	if (td->td_pflags & TDP_WAKEUP) {
@@ -447,9 +444,17 @@ kern_thr_suspend(struct thread *td, struct timespec *tsp)
 	}
 
 	PROC_LOCK(td->td_proc);
-	if ((td->td_flags & TDF_THRWAKEUP) == 0)
-		error = msleep((void *)td, &td->td_proc->p_mtx, PCATCH, "lthr",
-		    hz);
+	if ((td->td_flags & TDF_THRWAKEUP) == 0) {
+		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
+			error = EWOULDBLOCK;
+		else {
+			TIMESPEC_TO_TIMEVAL(&tv, tsp);
+			timo = tvtohz(&tv);
+			error = msleep((void *)td, &td->td_proc->p_mtx,
+				 PCATCH, "lthr", timo);
+		}
+	}
+
 	if (td->td_flags & TDF_THRWAKEUP) {
 		thread_lock(td);
 		td->td_flags &= ~TDF_THRWAKEUP;
@@ -461,7 +466,7 @@ kern_thr_suspend(struct thread *td, struct timespec *tsp)
 	if (error == EWOULDBLOCK)
 		error = ETIMEDOUT;
 	else if (error == ERESTART) {
-		if (hz != 0)
+		if (timo != 0)
 			error = EINTR;
 	}
 	return (error);

From 3586381d50d246bdc86ca22712db4f0675fc6519 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Tue, 24 Aug 2010 08:09:30 +0000
Subject: [PATCH 0191/1624] Bump __FreeBSD_version for revision 211732.

Noticed by: thompa
---
 sys/sys/param.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/param.h b/sys/sys/param.h
index 8d3e34e28b3..1c1ecec61e8 100644
--- a/sys/sys/param.h
+++ b/sys/sys/param.h
@@ -58,7 +58,7 @@
  *		in the range 5 to 9.
  */
 #undef __FreeBSD_version
-#define __FreeBSD_version 900017	/* Master, propagated to newvers */
+#define __FreeBSD_version 900018	/* Master, propagated to newvers */
 
 #ifndef LOCORE
 #include 

From 5cf22195352544e71d37658bf716f0f4c8570600 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Tue, 24 Aug 2010 09:57:06 +0000
Subject: [PATCH 0192/1624] Add wrapper for setcontext() and swapcontext(), the
 wrappers unblock SIGCANCEL which is needed by thread cancellation.

---
 lib/libthr/pthread.map          |  4 +++
 lib/libthr/thread/thr_private.h |  6 ++++
 lib/libthr/thread/thr_sig.c     | 59 +++++++++++++++++++++++++--------
 3 files changed, 55 insertions(+), 14 deletions(-)

diff --git a/lib/libthr/pthread.map b/lib/libthr/pthread.map
index 8457996825b..4eebb6254d4 100644
--- a/lib/libthr/pthread.map
+++ b/lib/libthr/pthread.map
@@ -342,6 +342,7 @@ FBSDprivate_1.0 {
 	_pthread_timedjoin_np;
 	_pthread_yield;
 	_raise;
+	_setcontext;
 	_sigaction;
 	_sigprocmask;
 	_sigsuspend;
@@ -351,6 +352,7 @@ FBSDprivate_1.0 {
 	_spinlock;
 	_spinlock_debug;
 	_spinunlock;
+	_swapcontext;
 
 	/* Debugger needs these. */
 	_libthr_debug;
@@ -397,4 +399,6 @@ FBSD_1.1 {
 
 FBSD_1.2 {
 	openat;
+	setcontext;
+	swapcontext;
 };
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index f0c3aa0ec9a..c9e14c52351 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -709,6 +709,12 @@ int	__sys_sigwaitinfo(const sigset_t *set, siginfo_t *info);
 int	__sys_nanosleep(const struct timespec *, struct timespec *);
 #endif
 
+/* #include  */
+#ifdef _SYS_UCONTEXT_H_
+int	__sys_setcontext(const ucontext_t *ucp);
+int	__sys_swapcontext(ucontext_t *oucp, const ucontext_t *ucp);
+#endif
+
 /* #include  */
 #ifdef  _UNISTD_H_
 int     __sys_close(int);
diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index 115aa65a1cc..312c15f4a3b 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -59,7 +59,29 @@ int	_sigwaitinfo(const sigset_t *set, siginfo_t *info);
 int	__sigwait(const sigset_t *set, int *sig);
 int	_sigwait(const sigset_t *set, int *sig);
 int	__sigsuspend(const sigset_t *sigmask);
+int	_setcontext(const ucontext_t *);
+int	_swapcontext(ucontext_t *, const ucontext_t *);
 
+static void
+remove_thr_signals(sigset_t *set)
+{
+	if (SIGISMEMBER(*set, SIGCANCEL))
+		SIGDELSET(*set, SIGCANCEL);
+}
+
+static const sigset_t *
+thr_remove_thr_signals(const sigset_t *set, sigset_t *newset)
+{
+	const sigset_t *pset;
+
+	if (SIGISMEMBER(*set, SIGCANCEL)) {
+		*newset = *set;
+		SIGDELSET(*newset, SIGCANCEL);
+		pset = newset;
+	} else
+		pset = set;
+	return (pset);
+}
 
 static void
 sigcancel_handler(int sig __unused,
@@ -268,20 +290,6 @@ _pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
 
 __weak_reference(__sigsuspend, sigsuspend);
 
-static const sigset_t *
-thr_remove_thr_signals(const sigset_t *set, sigset_t *newset)
-{
-	const sigset_t *pset;
-
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		*newset = *set;
-		SIGDELSET(*newset, SIGCANCEL);
-		pset = newset;
-	} else
-		pset = set;
-	return (pset);
-}
-
 int
 _sigsuspend(const sigset_t * set)
 {
@@ -389,3 +397,26 @@ __sigwait(const sigset_t *set, int *sig)
 	_thr_cancel_leave_defer(curthread, (ret != 0));
 	return (ret);
 }
+
+__weak_reference(_setcontext, setcontext);
+int
+_setcontext(const ucontext_t *ucp)
+{
+	ucontext_t uc;
+
+	(void) memcpy(&uc, ucp, sizeof (uc));
+	remove_thr_signals(&uc.uc_sigmask);
+
+	return __sys_setcontext(&uc);
+}
+
+__weak_reference(_swapcontext, swapcontext);
+int
+_swapcontext(ucontext_t *oucp, const ucontext_t *ucp)
+{
+	ucontext_t uc;
+
+	(void) memcpy(&uc, ucp, sizeof (uc));
+	remove_thr_signals(&uc.uc_sigmask);
+	return __sys_swapcontext(oucp, &uc);
+}

From 8605d1ae99a67b8684860204e76598d5f3b0daac Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 11:11:58 +0000
Subject: [PATCH 0193/1624] Port the fasttrap provider to FreeBSD. This
 provider is responsible for injecting debugging probes in the userland
 programs and is the basis for the pid provider and the usdt provider.

Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/uts/common/dtrace/fasttrap.c  | 533 +++++++++++-------
 1 file changed, 323 insertions(+), 210 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
index 45839cbb8f9..eda5b26cc3d 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
@@ -17,6 +17,10 @@
  * information: Portions Copyright [yyyy] [name of copyright owner]
  *
  * CDDL HEADER END
+ *
+ * Portions Copyright 2010 The FreeBSD Foundation
+ *
+ * $FreeBSD$
  */
 
 /*
@@ -24,7 +28,9 @@
  * Use is subject to license terms.
  */
 
+#if defined(sun)
 #pragma ident	"%Z%%M%	%I%	%E% SMI"
+#endif
 
 #include 
 #include 
@@ -32,11 +38,15 @@
 #include 
 #include 
 #include 
+#if defined(sun)
 #include 
+#endif
 #include 
 #include 
 #include 
+#if defined(sun)
 #include 
+#endif
 #include 
 #include 
 #include 
@@ -44,9 +54,17 @@
 #include 
 #include 
 #include 
-#include 
 #include 
+#if defined(sun)
 #include 
+#endif
+#include 
+#include 
+#if !defined(sun)
+#include 
+#include 
+#include 
+#endif
 
 /*
  * User-Land Trap-Based Tracing
@@ -125,11 +143,20 @@
  *	never hold the provider lock and creation lock simultaneously
  */
 
-static dev_info_t *fasttrap_devi;
+static d_open_t fasttrap_open;
+static d_ioctl_t fasttrap_ioctl;
+
+static struct cdevsw fasttrap_cdevsw = {
+	.d_version	= D_VERSION,
+	.d_open		= fasttrap_open,
+	.d_ioctl	= fasttrap_ioctl,
+	.d_name		= "fasttrap",
+};
+static struct cdev *fasttrap_cdev;
 static dtrace_meta_provider_id_t fasttrap_meta_id;
 
-static timeout_id_t fasttrap_timeout;
-static kmutex_t fasttrap_cleanup_mtx;
+static struct callout fasttrap_timeout;
+static struct mtx fasttrap_cleanup_mtx;
 static uint_t fasttrap_cleanup_work;
 
 /*
@@ -229,6 +256,7 @@ fasttrap_hash_str(const char *p)
 void
 fasttrap_sigtrap(proc_t *p, kthread_t *t, uintptr_t pc)
 {
+#if defined(sun)
 	sigqueue_t *sqp = kmem_zalloc(sizeof (sigqueue_t), KM_SLEEP);
 
 	sqp->sq_info.si_signo = SIGTRAP;
@@ -241,6 +269,17 @@ fasttrap_sigtrap(proc_t *p, kthread_t *t, uintptr_t pc)
 
 	if (t != NULL)
 		aston(t);
+#else
+	ksiginfo_t *ksi = kmem_zalloc(sizeof (ksiginfo_t), KM_SLEEP);
+
+	ksiginfo_init(ksi);
+	ksi->ksi_signo = SIGTRAP;
+	ksi->ksi_code = TRAP_DTRACE;
+	ksi->ksi_addr = (caddr_t)pc;
+	PROC_LOCK(p);
+	(void) pksignal(p, SIGTRAP, ksi);
+	PROC_UNLOCK(p);
+#endif
 }
 
 /*
@@ -250,17 +289,24 @@ fasttrap_sigtrap(proc_t *p, kthread_t *t, uintptr_t pc)
 static void
 fasttrap_mod_barrier(uint64_t gen)
 {
+#if defined(sun)
 	int i;
+#endif
 
 	if (gen < fasttrap_mod_gen)
 		return;
 
 	fasttrap_mod_gen++;
 
+#if defined(sun)
 	for (i = 0; i < NCPU; i++) {
 		mutex_enter(&cpu_core[i].cpuc_pid_lock);
 		mutex_exit(&cpu_core[i].cpuc_pid_lock);
 	}
+#else
+	/* XXX */
+	__asm __volatile("": : :"memory");
+#endif
 }
 
 /*
@@ -274,16 +320,15 @@ fasttrap_pid_cleanup_cb(void *data)
 	fasttrap_provider_t **fpp, *fp;
 	fasttrap_bucket_t *bucket;
 	dtrace_provider_id_t provid;
-	int i, later;
+	int i, later = 0;
 
 	static volatile int in = 0;
 	ASSERT(in == 0);
 	in = 1;
 
-	mutex_enter(&fasttrap_cleanup_mtx);
 	while (fasttrap_cleanup_work) {
 		fasttrap_cleanup_work = 0;
-		mutex_exit(&fasttrap_cleanup_mtx);
+		mtx_unlock(&fasttrap_cleanup_mtx);
 
 		later = 0;
 
@@ -349,10 +394,12 @@ fasttrap_pid_cleanup_cb(void *data)
 			mutex_exit(&bucket->ftb_mtx);
 		}
 
-		mutex_enter(&fasttrap_cleanup_mtx);
+		mtx_lock(&fasttrap_cleanup_mtx);
 	}
 
+#if 0
 	ASSERT(fasttrap_timeout != 0);
+#endif
 
 	/*
 	 * If we were unable to remove a retired provider, try again after
@@ -364,14 +411,17 @@ fasttrap_pid_cleanup_cb(void *data)
 	 * get a chance to do that work if and when the timeout is reenabled
 	 * (if detach fails).
 	 */
-	if (later > 0 && fasttrap_timeout != (timeout_id_t)1)
-		fasttrap_timeout = timeout(&fasttrap_pid_cleanup_cb, NULL, hz);
+	if (later > 0 && callout_active(&fasttrap_timeout))
+		callout_reset(&fasttrap_timeout, hz, &fasttrap_pid_cleanup_cb,
+		    NULL);
 	else if (later > 0)
 		fasttrap_cleanup_work = 1;
-	else
-		fasttrap_timeout = 0;
+	else {
+#if !defined(sun)
+		/* Nothing to be done for FreeBSD */
+#endif
+	}
 
-	mutex_exit(&fasttrap_cleanup_mtx);
 	in = 0;
 }
 
@@ -381,11 +431,11 @@ fasttrap_pid_cleanup_cb(void *data)
 static void
 fasttrap_pid_cleanup(void)
 {
-	mutex_enter(&fasttrap_cleanup_mtx);
+
+	mtx_lock(&fasttrap_cleanup_mtx);
 	fasttrap_cleanup_work = 1;
-	if (fasttrap_timeout == 0)
-		fasttrap_timeout = timeout(&fasttrap_pid_cleanup_cb, NULL, 1);
-	mutex_exit(&fasttrap_cleanup_mtx);
+	callout_reset(&fasttrap_timeout, 1, &fasttrap_pid_cleanup_cb, NULL);
+	mtx_unlock(&fasttrap_cleanup_mtx);
 }
 
 /*
@@ -400,9 +450,23 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 	pid_t ppid = p->p_pid;
 	int i;
 
+#if defined(sun)
 	ASSERT(curproc == p);
 	ASSERT(p->p_proc_flag & P_PR_LOCK);
+#else
+	PROC_LOCK_ASSERT(p, MA_OWNED);
+#endif
+#if defined(sun)
 	ASSERT(p->p_dtrace_count > 0);
+#else
+	/*
+	 * This check is purposely here instead of in kern_fork.c because,
+	 * for legal resons, we cannot include the dtrace_cddl.h header
+	 * inside kern_fork.c and insert if-clause there.
+	 */
+	if (p->p_dtrace_count == 0)
+		return;
+#endif
 	ASSERT(cp->p_dtrace_count == 0);
 
 	/*
@@ -419,9 +483,11 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 	 * We don't have to worry about the child process disappearing
 	 * because we're in fork().
 	 */
-	mutex_enter(&cp->p_lock);
+#if defined(sun)
+	mtx_lock_spin(&cp->p_slock);
 	sprlock_proc(cp);
-	mutex_exit(&cp->p_lock);
+	mtx_unlock_spin(&cp->p_slock);
+#endif
 
 	/*
 	 * Iterate over every tracepoint looking for ones that belong to the
@@ -451,8 +517,10 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 		mutex_exit(&bucket->ftb_mtx);
 	}
 
+#if defined(sun)
 	mutex_enter(&cp->p_lock);
 	sprunlock(cp);
+#endif
 }
 
 /*
@@ -463,24 +531,24 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 static void
 fasttrap_exec_exit(proc_t *p)
 {
+#if defined(sun)
 	ASSERT(p == curproc);
-	ASSERT(MUTEX_HELD(&p->p_lock));
-
-	mutex_exit(&p->p_lock);
+#endif
+	PROC_LOCK_ASSERT(p, MA_OWNED);
+	PROC_UNLOCK(p);
 
 	/*
 	 * We clean up the pid provider for this process here; user-land
 	 * static probes are handled by the meta-provider remove entry point.
 	 */
 	fasttrap_provider_retire(p->p_pid, FASTTRAP_PID_NAME, 0);
-
-	mutex_enter(&p->p_lock);
+	PROC_LOCK(p);
 }
 
 
 /*ARGSUSED*/
 static void
-fasttrap_pid_provide(void *arg, const dtrace_probedesc_t *desc)
+fasttrap_pid_provide(void *arg, dtrace_probedesc_t *desc)
 {
 	/*
 	 * There are no "default" pid probes.
@@ -504,7 +572,9 @@ fasttrap_tracepoint_enable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
 
 	ASSERT(probe->ftp_tps[index].fit_tp->ftt_pid == pid);
 
+#if defined(sun)
 	ASSERT(!(p->p_flag & SVFORK));
+#endif
 
 	/*
 	 * Before we make any modifications, make sure we've imposed a barrier
@@ -610,7 +680,11 @@ again:
 		 * Increment the count of the number of tracepoints active in
 		 * the victim process.
 		 */
+#if defined(sun)
 		ASSERT(p->p_proc_flag & P_PR_LOCK);
+#else
+		PROC_LOCK_ASSERT(p, MA_OWNED);
+#endif
 		p->p_dtrace_count++;
 
 		return (rc);
@@ -666,7 +740,7 @@ fasttrap_tracepoint_disable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
 	fasttrap_bucket_t *bucket;
 	fasttrap_provider_t *provider = probe->ftp_prov;
 	fasttrap_tracepoint_t **pp, *tp;
-	fasttrap_id_t *id, **idp;
+	fasttrap_id_t *id, **idp = NULL;
 	pid_t pid;
 	uintptr_t pc;
 
@@ -800,7 +874,11 @@ fasttrap_tracepoint_disable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
 		 * Decrement the count of the number of tracepoints active
 		 * in the victim process.
 		 */
+#if defined(sun)
 		ASSERT(p->p_proc_flag & P_PR_LOCK);
+#else
+		PROC_LOCK_ASSERT(p, MA_OWNED);
+#endif
 		p->p_dtrace_count--;
 	}
 
@@ -851,26 +929,31 @@ fasttrap_enable_callbacks(void)
 static void
 fasttrap_disable_callbacks(void)
 {
+#if defined(sun)
 	ASSERT(MUTEX_HELD(&cpu_lock));
+#endif
+
 
 	mutex_enter(&fasttrap_count_mtx);
 	ASSERT(fasttrap_pid_count > 0);
 	fasttrap_pid_count--;
 	if (fasttrap_pid_count == 0) {
+#if defined(sun)
 		cpu_t *cur, *cpu = CPU;
 
 		for (cur = cpu->cpu_next_onln; cur != cpu;
 		    cur = cur->cpu_next_onln) {
 			rw_enter(&cur->cpu_ft_lock, RW_WRITER);
 		}
-
+#endif
 		dtrace_pid_probe_ptr = NULL;
 		dtrace_return_probe_ptr = NULL;
-
+#if defined(sun)
 		for (cur = cpu->cpu_next_onln; cur != cpu;
 		    cur = cur->cpu_next_onln) {
 			rw_exit(&cur->cpu_ft_lock);
 		}
+#endif
 	}
 	mutex_exit(&fasttrap_count_mtx);
 }
@@ -880,13 +963,16 @@ static void
 fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 {
 	fasttrap_probe_t *probe = parg;
-	proc_t *p;
+	proc_t *p = NULL;
 	int i, rc;
 
+
 	ASSERT(probe != NULL);
 	ASSERT(!probe->ftp_enabled);
 	ASSERT(id == probe->ftp_id);
+#if defined(sun)
 	ASSERT(MUTEX_HELD(&cpu_lock));
+#endif
 
 	/*
 	 * Increment the count of enabled probes on this probe's provider;
@@ -911,6 +997,7 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 	 * a fork in which the traced process is being born and we're copying
 	 * USDT probes. Otherwise, the process is gone so bail.
 	 */
+#if defined(sun)
 	if ((p = sprlock(probe->ftp_pid)) == NULL) {
 		if ((curproc->p_flag & SFORKING) == 0)
 			return;
@@ -934,13 +1021,19 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 
 	ASSERT(!(p->p_flag & SVFORK));
 	mutex_exit(&p->p_lock);
+#else
+	if ((p = pfind(probe->ftp_pid)) == NULL)
+		return;
+#endif
 
 	/*
 	 * We have to enable the trap entry point before any user threads have
 	 * the chance to execute the trap instruction we're about to place
 	 * in their process's text.
 	 */
+	PROC_UNLOCK(p);
 	fasttrap_enable_callbacks();
+	PROC_LOCK(p);
 
 	/*
 	 * Enable all the tracepoints and add this probe's id to each
@@ -967,8 +1060,12 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 				i--;
 			}
 
+#if defined(sun)
 			mutex_enter(&p->p_lock);
 			sprunlock(p);
+#else
+			PROC_UNLOCK(p);
+#endif
 
 			/*
 			 * Since we're not actually enabling this probe,
@@ -978,9 +1075,12 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 			return;
 		}
 	}
-
+#if defined(sun)
 	mutex_enter(&p->p_lock);
 	sprunlock(p);
+#else
+	PROC_UNLOCK(p);
+#endif
 
 	probe->ftp_enabled = 1;
 }
@@ -996,19 +1096,19 @@ fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
 
 	ASSERT(id == probe->ftp_id);
 
+	mutex_enter(&provider->ftp_mtx);
+
 	/*
 	 * We won't be able to acquire a /proc-esque lock on the process
 	 * iff the process is dead and gone. In this case, we rely on the
 	 * provider lock as a point of mutual exclusion to prevent other
 	 * DTrace consumers from disabling this probe.
 	 */
-	if ((p = sprlock(probe->ftp_pid)) != NULL) {
-		ASSERT(!(p->p_flag & SVFORK));
-		mutex_exit(&p->p_lock);
+	if ((p = pfind(probe->ftp_pid)) == NULL) {
+		mutex_exit(&provider->ftp_mtx);
+		return;
 	}
 
-	mutex_enter(&provider->ftp_mtx);
-
 	/*
 	 * Disable all the associated tracepoints (for fully enabled probes).
 	 */
@@ -1030,9 +1130,6 @@ fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
 		if (provider->ftp_retired && !provider->ftp_marked)
 			whack = provider->ftp_marked = 1;
 		mutex_exit(&provider->ftp_mtx);
-
-		mutex_enter(&p->p_lock);
-		sprunlock(p);
 	} else {
 		/*
 		 * If the process is dead, we're just waiting for the
@@ -1042,6 +1139,9 @@ fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
 			whack = provider->ftp_marked = 1;
 		mutex_exit(&provider->ftp_mtx);
 	}
+#if !defined(sun)
+	PROC_UNLOCK(p);
+#endif
 
 	if (whack)
 		fasttrap_pid_cleanup();
@@ -1051,7 +1151,9 @@ fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
 
 	probe->ftp_enabled = 0;
 
+#if defined(sun)
 	ASSERT(MUTEX_HELD(&cpu_lock));
+#endif
 	fasttrap_disable_callbacks();
 }
 
@@ -1163,6 +1265,7 @@ fasttrap_proc_lookup(pid_t pid)
 	fasttrap_bucket_t *bucket;
 	fasttrap_proc_t *fprc, *new_fprc;
 
+
 	bucket = &fasttrap_procs.fth_table[FASTTRAP_PROCS_INDEX(pid)];
 	mutex_enter(&bucket->ftb_mtx);
 
@@ -1189,6 +1292,10 @@ fasttrap_proc_lookup(pid_t pid)
 	new_fprc->ftpc_pid = pid;
 	new_fprc->ftpc_rcount = 1;
 	new_fprc->ftpc_acount = 1;
+#if !defined(sun)
+	mutex_init(&new_fprc->ftpc_mtx, "fasttrap proc mtx", MUTEX_DEFAULT,
+	    NULL);
+#endif
 
 	mutex_enter(&bucket->ftb_mtx);
 
@@ -1311,17 +1418,8 @@ fasttrap_provider_lookup(pid_t pid, const char *name,
 	 * Make sure the process exists, isn't a child created as the result
 	 * of a vfork(2), and isn't a zombie (but may be in fork).
 	 */
-	mutex_enter(&pidlock);
-	if ((p = prfind(pid)) == NULL) {
-		mutex_exit(&pidlock);
+	if ((p = pfind(pid)) == NULL)
 		return (NULL);
-	}
-	mutex_enter(&p->p_lock);
-	mutex_exit(&pidlock);
-	if (p->p_flag & (SVFORK | SEXITING)) {
-		mutex_exit(&p->p_lock);
-		return (NULL);
-	}
 
 	/*
 	 * Increment p_dtrace_probes so that the process knows to inform us
@@ -1334,15 +1432,18 @@ fasttrap_provider_lookup(pid_t pid, const char *name,
 	 * Grab the credentials for this process so we have
 	 * something to pass to dtrace_register().
 	 */
-	mutex_enter(&p->p_crlock);
-	crhold(p->p_cred);
-	cred = p->p_cred;
-	mutex_exit(&p->p_crlock);
-	mutex_exit(&p->p_lock);
+	PROC_LOCK_ASSERT(p, MA_OWNED);
+	crhold(p->p_ucred);
+	cred = p->p_ucred;
+	PROC_UNLOCK(p);
 
 	new_fp = kmem_zalloc(sizeof (fasttrap_provider_t), KM_SLEEP);
 	new_fp->ftp_pid = pid;
 	new_fp->ftp_proc = fasttrap_proc_lookup(pid);
+#if !defined(sun)
+	mutex_init(&new_fp->ftp_mtx, "provider mtx", MUTEX_DEFAULT, NULL);
+	mutex_init(&new_fp->ftp_cmtx, "lock on creating", MUTEX_DEFAULT, NULL);
+#endif
 
 	ASSERT(new_fp->ftp_proc != NULL);
 
@@ -1420,6 +1521,10 @@ fasttrap_provider_free(fasttrap_provider_t *provider)
 
 	fasttrap_proc_release(provider->ftp_proc);
 
+#if !defined(sun)
+	mutex_destroy(&provider->ftp_mtx);
+	mutex_destroy(&provider->ftp_cmtx);
+#endif
 	kmem_free(provider, sizeof (fasttrap_provider_t));
 
 	/*
@@ -1429,17 +1534,14 @@ fasttrap_provider_free(fasttrap_provider_t *provider)
 	 * corresponds to this process's hash chain in the provider hash
 	 * table. Don't sweat it if we can't find the process.
 	 */
-	mutex_enter(&pidlock);
-	if ((p = prfind(pid)) == NULL) {
-		mutex_exit(&pidlock);
+	if ((p = pfind(pid)) == NULL) {
 		return;
 	}
 
-	mutex_enter(&p->p_lock);
-	mutex_exit(&pidlock);
-
 	p->p_dtrace_probes--;
-	mutex_exit(&p->p_lock);
+#if !defined(sun)
+	PROC_UNLOCK(p);
+#endif
 }
 
 static void
@@ -1527,7 +1629,7 @@ fasttrap_add_probe(fasttrap_probe_spec_t *pdata)
 	fasttrap_probe_t *pp;
 	fasttrap_tracepoint_t *tp;
 	char *name;
-	int i, aframes, whack;
+	int i, aframes = 0, whack;
 
 	/*
 	 * There needs to be at least one desired trace point.
@@ -1715,7 +1817,7 @@ fasttrap_meta_provide(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
 	 */
 	if (strlen(dhpv->dthpv_provname) + 10 >=
 	    sizeof (provider->ftp_name)) {
-		cmn_err(CE_WARN, "failed to instantiate provider %s: "
+		printf("failed to instantiate provider %s: "
 		    "name too long to accomodate pid", dhpv->dthpv_provname);
 		return (NULL);
 	}
@@ -1724,7 +1826,7 @@ fasttrap_meta_provide(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
 	 * Don't let folks spoof the true pid provider.
 	 */
 	if (strcmp(dhpv->dthpv_provname, FASTTRAP_PID_NAME) == 0) {
-		cmn_err(CE_WARN, "failed to instantiate provider %s: "
+		printf("failed to instantiate provider %s: "
 		    "%s is an invalid name", dhpv->dthpv_provname,
 		    FASTTRAP_PID_NAME);
 		return (NULL);
@@ -1747,7 +1849,7 @@ fasttrap_meta_provide(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
 
 	if ((provider = fasttrap_provider_lookup(pid, dhpv->dthpv_provname,
 	    &dhpv->dthpv_pattr)) == NULL) {
-		cmn_err(CE_WARN, "failed to instantiate provider %s for "
+		printf("failed to instantiate provider %s for "
 		    "process %u",  dhpv->dthpv_provname, (uint_t)pid);
 		return (NULL);
 	}
@@ -1908,15 +2010,21 @@ static dtrace_mops_t fasttrap_mops = {
 
 /*ARGSUSED*/
 static int
-fasttrap_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
+fasttrap_open(struct cdev *dev __unused, int oflags __unused,
+    int devtype __unused, struct thread *td __unused)
 {
 	return (0);
 }
 
 /*ARGSUSED*/
 static int
-fasttrap_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
+fasttrap_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int fflag,
+    struct thread *td)
 {
+#ifdef notyet
+	struct kinfo_proc kp;
+	const cred_t *cr = td->td_ucred;
+#endif
 	if (!dtrace_attached())
 		return (EAGAIN);
 
@@ -1928,9 +2036,13 @@ fasttrap_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
 		int ret;
 		char *c;
 
+#if defined(sun)
 		if (copyin(&uprobe->ftps_noffs, &noffs,
 		    sizeof (uprobe->ftps_noffs)))
 			return (EFAULT);
+#else
+		noffs = uprobe->ftps_noffs;
+#endif
 
 		/*
 		 * Probes must have at least one tracepoint.
@@ -1946,10 +2058,19 @@ fasttrap_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
 
 		probe = kmem_alloc(size, KM_SLEEP);
 
+#if defined(sun)
 		if (copyin(uprobe, probe, size) != 0) {
 			kmem_free(probe, size);
 			return (EFAULT);
 		}
+#else
+		memcpy(probe, uprobe, sizeof(*probe));
+		if (noffs > 1 && copyin(uprobe + 1, probe + 1, size) != 0) {
+			kmem_free(probe, size);
+			return (EFAULT);
+		}
+#endif
+
 
 		/*
 		 * Verify that the function and module strings contain no
@@ -1969,30 +2090,52 @@ fasttrap_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
 			}
 		}
 
+#ifdef notyet
 		if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
 			proc_t *p;
 			pid_t pid = probe->ftps_pid;
 
+#if defined(sun)
 			mutex_enter(&pidlock);
+#endif
 			/*
 			 * Report an error if the process doesn't exist
 			 * or is actively being birthed.
 			 */
-			if ((p = prfind(pid)) == NULL || p->p_stat == SIDL) {
+			p = pfind(pid);
+			if (p)
+				fill_kinfo_proc(p, &kp);
+			if (p == NULL || kp.ki_stat == SIDL) {
+#if defined(sun)
 				mutex_exit(&pidlock);
+#endif
 				return (ESRCH);
 			}
+#if defined(sun)
 			mutex_enter(&p->p_lock);
 			mutex_exit(&pidlock);
+#else
+			PROC_LOCK_ASSERT(p, MA_OWNED);
+#endif
 
+#ifdef notyet
 			if ((ret = priv_proc_cred_perm(cr, p, NULL,
 			    VREAD | VWRITE)) != 0) {
+#if defined(sun)
 				mutex_exit(&p->p_lock);
+#else
+				PROC_UNLOCK(p);
+#endif
 				return (ret);
 			}
-
+#endif /* notyet */
+#if defined(sun)
 			mutex_exit(&p->p_lock);
+#else
+			PROC_UNLOCK(p);
+#endif
 		}
+#endif /* notyet */
 
 		ret = fasttrap_add_probe(probe);
 err:
@@ -2004,35 +2147,62 @@ err:
 		fasttrap_instr_query_t instr;
 		fasttrap_tracepoint_t *tp;
 		uint_t index;
+#if defined(sun)
 		int ret;
+#endif
 
+#if defined(sun)
 		if (copyin((void *)arg, &instr, sizeof (instr)) != 0)
 			return (EFAULT);
+#endif
 
+#ifdef notyet
 		if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
 			proc_t *p;
 			pid_t pid = instr.ftiq_pid;
 
+#if defined(sun)
 			mutex_enter(&pidlock);
+#endif
 			/*
 			 * Report an error if the process doesn't exist
 			 * or is actively being birthed.
 			 */
-			if ((p = prfind(pid)) == NULL || p->p_stat == SIDL) {
+			p = pfind(pid);
+			if (p)
+				fill_kinfo_proc(p, &kp);
+			if (p == NULL || kp.ki_stat == SIDL) {
+#if defined(sun)
 				mutex_exit(&pidlock);
+#endif
 				return (ESRCH);
 			}
+#if defined(sun)
 			mutex_enter(&p->p_lock);
 			mutex_exit(&pidlock);
+#else
+			PROC_LOCK_ASSERT(p, MA_OWNED);
+#endif
 
+#ifdef notyet
 			if ((ret = priv_proc_cred_perm(cr, p, NULL,
 			    VREAD)) != 0) {
+#if defined(sun)
 				mutex_exit(&p->p_lock);
+#else
+				PROC_UNLOCK(p);
+#endif
 				return (ret);
 			}
+#endif /* notyet */
 
+#if defined(sun)
 			mutex_exit(&p->p_lock);
+#else
+			PROC_UNLOCK(p);
+#endif
 		}
+#endif /* notyet */
 
 		index = FASTTRAP_TPOINTS_INDEX(instr.ftiq_pid, instr.ftiq_pc);
 
@@ -2065,84 +2235,45 @@ err:
 	return (EINVAL);
 }
 
-static struct cb_ops fasttrap_cb_ops = {
-	fasttrap_open,		/* open */
-	nodev,			/* close */
-	nulldev,		/* strategy */
-	nulldev,		/* print */
-	nodev,			/* dump */
-	nodev,			/* read */
-	nodev,			/* write */
-	fasttrap_ioctl,		/* ioctl */
-	nodev,			/* devmap */
-	nodev,			/* mmap */
-	nodev,			/* segmap */
-	nochpoll,		/* poll */
-	ddi_prop_op,		/* cb_prop_op */
-	0,			/* streamtab  */
-	D_NEW | D_MP		/* Driver compatibility flag */
-};
-
-/*ARGSUSED*/
 static int
-fasttrap_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
-{
-	int error;
-
-	switch (infocmd) {
-	case DDI_INFO_DEVT2DEVINFO:
-		*result = (void *)fasttrap_devi;
-		error = DDI_SUCCESS;
-		break;
-	case DDI_INFO_DEVT2INSTANCE:
-		*result = (void *)0;
-		error = DDI_SUCCESS;
-		break;
-	default:
-		error = DDI_FAILURE;
-	}
-	return (error);
-}
-
-static int
-fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
+fasttrap_load(void)
 {
 	ulong_t nent;
+	int i;
 
-	switch (cmd) {
-	case DDI_ATTACH:
-		break;
-	case DDI_RESUME:
-		return (DDI_SUCCESS);
-	default:
-		return (DDI_FAILURE);
-	}
+        /* Create the /dev/dtrace/fasttrap entry. */
+        fasttrap_cdev = make_dev(&fasttrap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
+            "dtrace/fasttrap");
 
-	if (ddi_create_minor_node(devi, "fasttrap", S_IFCHR, 0,
-	    DDI_PSEUDO, NULL) == DDI_FAILURE) {
-		ddi_remove_minor_node(devi, NULL);
-		return (DDI_FAILURE);
-	}
-
-	ddi_report_dev(devi);
-	fasttrap_devi = devi;
+	mtx_init(&fasttrap_cleanup_mtx, "fasttrap clean", "dtrace", MTX_DEF);
+	callout_init_mtx(&fasttrap_timeout, &fasttrap_cleanup_mtx, 0);
+	mutex_init(&fasttrap_count_mtx, "fasttrap count mtx", MUTEX_DEFAULT,
+	    NULL);
 
 	/*
 	 * Install our hooks into fork(2), exec(2), and exit(2).
 	 */
-	dtrace_fasttrap_fork_ptr = &fasttrap_fork;
-	dtrace_fasttrap_exit_ptr = &fasttrap_exec_exit;
-	dtrace_fasttrap_exec_ptr = &fasttrap_exec_exit;
+	dtrace_fasttrap_fork = &fasttrap_fork;
+	dtrace_fasttrap_exit = &fasttrap_exec_exit;
+	dtrace_fasttrap_exec = &fasttrap_exec_exit;
 
+#if defined(sun)
 	fasttrap_max = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
 	    "fasttrap-max-probes", FASTTRAP_MAX_DEFAULT);
+#else
+	fasttrap_max = FASTTRAP_MAX_DEFAULT;
+#endif
 	fasttrap_total = 0;
 
 	/*
 	 * Conjure up the tracepoints hashtable...
 	 */
+#if defined(sun)
 	nent = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
 	    "fasttrap-hash-size", FASTTRAP_TPOINTS_DEFAULT_SIZE);
+#else
+	nent = FASTTRAP_TPOINTS_DEFAULT_SIZE;
+#endif
 
 	if (nent == 0 || nent > 0x1000000)
 		nent = FASTTRAP_TPOINTS_DEFAULT_SIZE;
@@ -2155,6 +2286,11 @@ fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
 	fasttrap_tpoints.fth_mask = fasttrap_tpoints.fth_nent - 1;
 	fasttrap_tpoints.fth_table = kmem_zalloc(fasttrap_tpoints.fth_nent *
 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
+#if !defined(sun)
+	for (i = 0; i < fasttrap_tpoints.fth_nent; i++)
+		mutex_init(&fasttrap_tpoints.fth_table[i].ftb_mtx,
+		    "tracepoints bucket mtx", MUTEX_DEFAULT, NULL);
+#endif
 
 	/*
 	 * ... and the providers hash table...
@@ -2168,6 +2304,11 @@ fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
 	fasttrap_provs.fth_mask = fasttrap_provs.fth_nent - 1;
 	fasttrap_provs.fth_table = kmem_zalloc(fasttrap_provs.fth_nent *
 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
+#if !defined(sun)
+	for (i = 0; i < fasttrap_provs.fth_nent; i++)
+		mutex_init(&fasttrap_provs.fth_table[i].ftb_mtx, 
+		    "providers bucket mtx", MUTEX_DEFAULT, NULL);
+#endif
 
 	/*
 	 * ... and the procs hash table.
@@ -2181,27 +2322,22 @@ fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
 	fasttrap_procs.fth_mask = fasttrap_procs.fth_nent - 1;
 	fasttrap_procs.fth_table = kmem_zalloc(fasttrap_procs.fth_nent *
 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
+#if !defined(sun)
+	for (i = 0; i < fasttrap_procs.fth_nent; i++)
+		mutex_init(&fasttrap_procs.fth_table[i].ftb_mtx,
+		    "processes bucket mtx", MUTEX_DEFAULT, NULL);
+#endif
 
 	(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
 	    &fasttrap_meta_id);
 
-	return (DDI_SUCCESS);
+	return (0);
 }
 
 static int
-fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
+fasttrap_unload(void)
 {
 	int i, fail = 0;
-	timeout_id_t tmp;
-
-	switch (cmd) {
-	case DDI_DETACH:
-		break;
-	case DDI_SUSPEND:
-		return (DDI_SUCCESS);
-	default:
-		return (DDI_FAILURE);
-	}
 
 	/*
 	 * Unregister the meta-provider to make sure no new fasttrap-
@@ -2212,28 +2348,16 @@ fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
 	 */
 	if (fasttrap_meta_id != DTRACE_METAPROVNONE &&
 	    dtrace_meta_unregister(fasttrap_meta_id) != 0)
-		return (DDI_FAILURE);
+		return (-1);
 
 	/*
 	 * Prevent any new timeouts from running by setting fasttrap_timeout
 	 * to a non-zero value, and wait for the current timeout to complete.
 	 */
-	mutex_enter(&fasttrap_cleanup_mtx);
+	mtx_lock(&fasttrap_cleanup_mtx);
 	fasttrap_cleanup_work = 0;
-
-	while (fasttrap_timeout != (timeout_id_t)1) {
-		tmp = fasttrap_timeout;
-		fasttrap_timeout = (timeout_id_t)1;
-
-		if (tmp != 0) {
-			mutex_exit(&fasttrap_cleanup_mtx);
-			(void) untimeout(tmp);
-			mutex_enter(&fasttrap_cleanup_mtx);
-		}
-	}
-
-	fasttrap_cleanup_work = 0;
-	mutex_exit(&fasttrap_cleanup_mtx);
+	callout_drain(&fasttrap_timeout);
+	mtx_unlock(&fasttrap_cleanup_mtx);
 
 	/*
 	 * Iterate over all of our providers. If there's still a process
@@ -2275,10 +2399,10 @@ fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
 		 * and start a new timeout if any work has accumulated while
 		 * we've been unsuccessfully trying to detach.
 		 */
-		mutex_enter(&fasttrap_cleanup_mtx);
-		fasttrap_timeout = 0;
+		mtx_lock(&fasttrap_cleanup_mtx);
 		work = fasttrap_cleanup_work;
-		mutex_exit(&fasttrap_cleanup_mtx);
+		callout_drain(&fasttrap_timeout);
+		mtx_unlock(&fasttrap_cleanup_mtx);
 
 		if (work)
 			fasttrap_pid_cleanup();
@@ -2286,7 +2410,7 @@ fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
 		(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
 		    &fasttrap_meta_id);
 
-		return (DDI_FAILURE);
+		return (-1);
 	}
 
 #ifdef DEBUG
@@ -2314,63 +2438,52 @@ fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
 	 * be executing code in fasttrap_fork(). Similarly for p_dtrace_probes
 	 * and fasttrap_exec() and fasttrap_exit().
 	 */
-	ASSERT(dtrace_fasttrap_fork_ptr == &fasttrap_fork);
-	dtrace_fasttrap_fork_ptr = NULL;
+	ASSERT(dtrace_fasttrap_fork == &fasttrap_fork);
+	dtrace_fasttrap_fork = NULL;
 
-	ASSERT(dtrace_fasttrap_exec_ptr == &fasttrap_exec_exit);
-	dtrace_fasttrap_exec_ptr = NULL;
+	ASSERT(dtrace_fasttrap_exec == &fasttrap_exec_exit);
+	dtrace_fasttrap_exec = NULL;
 
-	ASSERT(dtrace_fasttrap_exit_ptr == &fasttrap_exec_exit);
-	dtrace_fasttrap_exit_ptr = NULL;
+	ASSERT(dtrace_fasttrap_exit == &fasttrap_exec_exit);
+	dtrace_fasttrap_exit = NULL;
 
-	ddi_remove_minor_node(devi, NULL);
+#if !defined(sun)
+	destroy_dev(fasttrap_cdev);
+	mutex_destroy(&fasttrap_count_mtx);
+#endif
 
-	return (DDI_SUCCESS);
+	return (0);
 }
 
-static struct dev_ops fasttrap_ops = {
-	DEVO_REV,		/* devo_rev */
-	0,			/* refcnt */
-	fasttrap_info,		/* get_dev_info */
-	nulldev,		/* identify */
-	nulldev,		/* probe */
-	fasttrap_attach,	/* attach */
-	fasttrap_detach,	/* detach */
-	nodev,			/* reset */
-	&fasttrap_cb_ops,	/* driver operations */
-	NULL,			/* bus operations */
-	nodev			/* dev power */
-};
-
-/*
- * Module linkage information for the kernel.
- */
-static struct modldrv modldrv = {
-	&mod_driverops,		/* module type (this is a pseudo driver) */
-	"Fasttrap Tracing",	/* name of module */
-	&fasttrap_ops,		/* driver ops */
-};
-
-static struct modlinkage modlinkage = {
-	MODREV_1,
-	(void *)&modldrv,
-	NULL
-};
-
-int
-_init(void)
+/* ARGSUSED */
+static int
+fasttrap_modevent(module_t mod __unused, int type, void *data __unused)
 {
-	return (mod_install(&modlinkage));
+	int error = 0;
+
+	switch (type) {
+	case MOD_LOAD:
+		break;
+
+	case MOD_UNLOAD:
+		break;
+
+	case MOD_SHUTDOWN:
+		break;
+
+	default:
+		error = EOPNOTSUPP;
+		break;
+	}
+	return (error);
 }
 
-int
-_info(struct modinfo *modinfop)
-{
-	return (mod_info(&modlinkage, modinfop));
-}
+SYSINIT(fasttrap_load, SI_SUB_DTRACE_PROVIDER, SI_ORDER_ANY, fasttrap_load,
+    NULL);
+SYSUNINIT(fasttrap_unload, SI_SUB_DTRACE_PROVIDER, SI_ORDER_ANY,
+    fasttrap_unload, NULL);
 
-int
-_fini(void)
-{
-	return (mod_remove(&modlinkage));
-}
+DEV_MODULE(fasttrap, fasttrap_modevent, NULL);
+MODULE_VERSION(fasttrap, 1);
+MODULE_DEPEND(fasttrap, dtrace, 1, 1, 1);
+MODULE_DEPEND(fasttrap, opensolaris, 1, 1, 1);

From 4b8c3ea4ba40b269a3d1b7eb83bae0ebbf7b9c8a Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 24 Aug 2010 11:53:30 +0000
Subject: [PATCH 0194/1624] Use preferred spelling for the __attribute__.

MFC after:	3 days
---
 sys/sys/cdefs.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/sys/cdefs.h b/sys/sys/cdefs.h
index f8456d89541..afb609a6356 100644
--- a/sys/sys/cdefs.h
+++ b/sys/sys/cdefs.h
@@ -306,8 +306,8 @@
 #endif
 
 #if __GNUC_PREREQ__(4, 2)
-#define	__hidden	__attribute((visibility("hidden")))
-#define	__exported	__attribute((visibility("default")))
+#define	__hidden	__attribute__((visibility("hidden")))
+#define	__exported	__attribute__((visibility("default")))
 #else
 #define	__hidden
 #define	__exported

From 47536ff629e804cc56abd07bb9ec59259cf7b287 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 24 Aug 2010 11:54:48 +0000
Subject: [PATCH 0195/1624] The __hidden definition is provided by sys/cdefs.h.

MFC after:	2 weeks
---
 lib/libthr/thread/thr_private.h | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index c9e14c52351..fd79b789e6a 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -66,10 +66,6 @@
 	WEAK_REF(func, SYM_FBP10(sym));			\
 	SYM_DEFAULT(sym, SYM_FBP10(sym), FBSDprivate_1.0)
 
-#ifndef __hidden
-#define __hidden		__attribute__((visibility("hidden")))
-#endif
-
 #include "pthread_md.h"
 #include "thr_umtx.h"
 #include "thread_db.h"

From 247a32fac520790524e8adddc2f9a9b1e2e07c16 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 24 Aug 2010 11:55:25 +0000
Subject: [PATCH 0196/1624] Remove unused source.

MFC after:	2 weeks
---
 lib/libthr/thread/thr_atfork.c | 57 ----------------------------------
 1 file changed, 57 deletions(-)
 delete mode 100644 lib/libthr/thread/thr_atfork.c

diff --git a/lib/libthr/thread/thr_atfork.c b/lib/libthr/thread/thr_atfork.c
deleted file mode 100644
index 0c57cc20a27..00000000000
--- a/lib/libthr/thread/thr_atfork.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2003 Daniel Eischen 
- * 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. Neither the name of the author nor the names of any co-contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
- *
- * $FreeBSD$
- */
-
-#include 
-#include 
-#include 
-#include 
-#include "thr_private.h"
-
-__weak_reference(_pthread_atfork, pthread_atfork);
-
-int
-_pthread_atfork(void (*prepare)(void), void (*parent)(void),
-    void (*child)(void))
-{
-	struct pthread *curthread;
-	struct pthread_atfork *af;
-
-	_thr_check_init();
-
-	if ((af = malloc(sizeof(struct pthread_atfork))) == NULL)
-		return (ENOMEM);
-
-	curthread = _get_curthread();
-	af->prepare = prepare;
-	af->parent = parent;
-	af->child = child;
-	THR_UMUTEX_LOCK(curthread, &_thr_atfork_lock);
-	TAILQ_INSERT_TAIL(&_thr_atfork_list, af, qe);
-	THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
-	return (0);
-}

From 625564de6331ac1641e96eb1c507c1bbc198517b Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 12:05:58 +0000
Subject: [PATCH 0197/1624] MD fasttrap implementation.

Sponsored by:	The FreeBSD Foundation
---
 .../uts/intel/dtrace/fasttrap_isa.c           | 389 +++++++++++++-----
 1 file changed, 276 insertions(+), 113 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c b/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
index 1b93869a735..c3990523553 100644
--- a/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
+++ b/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
@@ -17,6 +17,10 @@
  * information: Portions Copyright [yyyy] [name of copyright owner]
  *
  * CDDL HEADER END
+ *
+ * Portions Copyright 2010 The FreeBSD Foundation
+ *
+ * $FreeBSD$
  */
 
 /*
@@ -24,20 +28,86 @@
  * Use is subject to license terms.
  */
 
+#if defined(sun)
 #pragma ident	"%Z%%M%	%I%	%E% SMI"
+#endif
 
 #include 
 #include 
 #include 
 #include 
 #include 
+#if defined(sun)
 #include 
 #include 
 #include 
 #include 
+#else
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#endif
 #include 
+#if defined(sun)
 #include 
 #include 
+#else
+#include 
+
+static int
+proc_ops(int op, proc_t *p, void *kaddr, off_t uaddr, size_t len)
+{
+	struct iovec iov;
+	struct uio uio;
+
+	iov.iov_base = kaddr;
+	iov.iov_len = len;
+	uio.uio_offset = uaddr;
+	uio.uio_iov = &iov;
+	uio.uio_resid = len;
+	uio.uio_iovcnt = 1;
+	uio.uio_segflg = UIO_SYSSPACE;
+	uio.uio_td = curthread;
+	uio.uio_rw = op;
+	_PHOLD(p);
+	PROC_UNLOCK(p);
+	if (proc_rwmem(p, &uio) < 0) {
+		PROC_LOCK(p);
+		_PRELE(p);
+		return (-1);
+	}
+	PROC_LOCK(p);
+	_PRELE(p);
+
+	return (0);
+}
+
+static int
+uread(proc_t *p, void *kaddr, size_t len, uintptr_t uaddr)
+{
+
+	return (proc_ops(UIO_READ, p, kaddr, uaddr, len));
+}
+
+static int
+uwrite(proc_t *p, void *kaddr, size_t len, uintptr_t uaddr)
+{
+
+	return (proc_ops(UIO_WRITE, p, kaddr, uaddr, len));
+}
+#endif
+#ifdef __i386__
+#define	r_rax	r_eax
+#define	r_rbx	r_ebx
+#define	r_rip	r_eip
+#define	r_rflags r_eflags
+#define	r_rsp	r_esp
+#endif
 
 /*
  * Lossless User-Land Tracing on x86
@@ -188,12 +258,12 @@ static const uint8_t regmap[8] = {
 };
 #endif
 
-static ulong_t fasttrap_getreg(struct regs *, uint_t);
+static ulong_t fasttrap_getreg(struct reg *, uint_t);
 
 static uint64_t
-fasttrap_anarg(struct regs *rp, int function_entry, int argno)
+fasttrap_anarg(struct reg *rp, int function_entry, int argno)
 {
-	uint64_t value;
+	uint64_t value = 0;
 	int shift = function_entry ? 1 : 0;
 
 #ifdef __amd64
@@ -207,16 +277,18 @@ fasttrap_anarg(struct regs *rp, int function_entry, int argno)
 		if (argno < 6)
 			return ((&rp->r_rdi)[argno]);
 
-		stack = (uintptr_t *)rp->r_sp;
+		stack = (uintptr_t *)rp->r_rsp;
 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
 		value = dtrace_fulword(&stack[argno - 6 + shift]);
 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT | CPU_DTRACE_BADADDR);
 	} else {
 #endif
-		uint32_t *stack = (uint32_t *)rp->r_sp;
+#ifdef __i386
+		uint32_t *stack = (uint32_t *)rp->r_esp;
 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
 		value = dtrace_fuword32(&stack[argno + shift]);
 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT | CPU_DTRACE_BADADDR);
+#endif
 #ifdef __amd64
 	}
 #endif
@@ -637,35 +709,41 @@ fasttrap_fulword_noerr(const void *uaddr)
 {
 	uintptr_t ret;
 
-	if (fasttrap_fulword(uaddr, &ret) == 0)
+	if ((ret = fasttrap_fulword(uaddr)) != -1)
 		return (ret);
 
 	return (0);
 }
 #endif
 
+#ifdef __i386__
 static uint32_t
 fasttrap_fuword32_noerr(const void *uaddr)
 {
 	uint32_t ret;
 
-	if (fasttrap_fuword32(uaddr, &ret) == 0)
+	if ((ret = fasttrap_fuword32(uaddr)) != -1)
 		return (ret);
 
 	return (0);
 }
+#endif
 
 static void
-fasttrap_return_common(struct regs *rp, uintptr_t pc, pid_t pid,
+fasttrap_return_common(struct reg *rp, uintptr_t pc, pid_t pid,
     uintptr_t new_pc)
 {
 	fasttrap_tracepoint_t *tp;
 	fasttrap_bucket_t *bucket;
 	fasttrap_id_t *id;
+#if defined(sun)
 	kmutex_t *pid_mtx;
+#endif
 
+#if defined(sun)
 	pid_mtx = &cpu_core[CPU->cpu_id].cpuc_pid_lock;
 	mutex_enter(pid_mtx);
+#endif
 	bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
 
 	for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
@@ -680,7 +758,9 @@ fasttrap_return_common(struct regs *rp, uintptr_t pc, pid_t pid,
 	 * is not essential to the correct execution of the process.
 	 */
 	if (tp == NULL) {
+#if defined(sun)
 		mutex_exit(pid_mtx);
+#endif
 		return;
 	}
 
@@ -698,15 +778,18 @@ fasttrap_return_common(struct regs *rp, uintptr_t pc, pid_t pid,
 
 		dtrace_probe(id->fti_probe->ftp_id,
 		    pc - id->fti_probe->ftp_faddr,
-		    rp->r_r0, rp->r_r1, 0, 0);
+		    rp->r_rax, rp->r_rbx, 0, 0);
 	}
 
+#if defined(sun)
 	mutex_exit(pid_mtx);
+#endif
 }
 
 static void
 fasttrap_sigsegv(proc_t *p, kthread_t *t, uintptr_t addr)
 {
+#if defined(sun)
 	sigqueue_t *sqp = kmem_zalloc(sizeof (sigqueue_t), KM_SLEEP);
 
 	sqp->sq_info.si_signo = SIGSEGV;
@@ -719,15 +802,24 @@ fasttrap_sigsegv(proc_t *p, kthread_t *t, uintptr_t addr)
 
 	if (t != NULL)
 		aston(t);
+#else
+	ksiginfo_t *ksi = kmem_zalloc(sizeof (ksiginfo_t), KM_SLEEP);
+
+	ksiginfo_init(ksi);
+	ksi->ksi_signo = SIGSEGV;
+	ksi->ksi_code = SEGV_MAPERR;
+	ksi->ksi_addr = (caddr_t)addr;
+	(void) tdksignal(t, SIGSEGV, ksi);
+#endif
 }
 
 #ifdef __amd64
 static void
-fasttrap_usdt_args64(fasttrap_probe_t *probe, struct regs *rp, int argc,
+fasttrap_usdt_args64(fasttrap_probe_t *probe, struct reg *rp, int argc,
     uintptr_t *argv)
 {
 	int i, x, cap = MIN(argc, probe->ftp_nargs);
-	uintptr_t *stack = (uintptr_t *)rp->r_sp;
+	uintptr_t *stack = (uintptr_t *)rp->r_rsp;
 
 	for (i = 0; i < cap; i++) {
 		x = probe->ftp_argmap[i];
@@ -744,12 +836,13 @@ fasttrap_usdt_args64(fasttrap_probe_t *probe, struct regs *rp, int argc,
 }
 #endif
 
+#ifdef __i386__
 static void
-fasttrap_usdt_args32(fasttrap_probe_t *probe, struct regs *rp, int argc,
+fasttrap_usdt_args32(fasttrap_probe_t *probe, struct reg *rp, int argc,
     uint32_t *argv)
 {
 	int i, x, cap = MIN(argc, probe->ftp_nargs);
-	uint32_t *stack = (uint32_t *)rp->r_sp;
+	uint32_t *stack = (uint32_t *)rp->r_rsp;
 
 	for (i = 0; i < cap; i++) {
 		x = probe->ftp_argmap[i];
@@ -761,13 +854,18 @@ fasttrap_usdt_args32(fasttrap_probe_t *probe, struct regs *rp, int argc,
 		argv[i] = 0;
 	}
 }
+#endif
 
 static int
-fasttrap_do_seg(fasttrap_tracepoint_t *tp, struct regs *rp, uintptr_t *addr)
+fasttrap_do_seg(fasttrap_tracepoint_t *tp, struct reg *rp, uintptr_t *addr)
 {
 	proc_t *p = curproc;
-	user_desc_t *desc;
-	uint16_t sel, ndx, type;
+#ifdef __i386__
+	struct segment_descriptor *desc;
+#else
+	struct user_segment_descriptor *desc;
+#endif
+	uint16_t sel = 0, ndx, type;
 	uintptr_t limit;
 
 	switch (tp->ftt_segment) {
@@ -795,36 +893,49 @@ fasttrap_do_seg(fasttrap_tracepoint_t *tp, struct regs *rp, uintptr_t *addr)
 	 * Make sure the given segment register specifies a user priority
 	 * selector rather than a kernel selector.
 	 */
-	if (!SELISUPL(sel))
+	if (ISPL(sel) != SEL_UPL)
 		return (-1);
 
-	ndx = SELTOIDX(sel);
+	ndx = IDXSEL(sel);
 
 	/*
 	 * Check the bounds and grab the descriptor out of the specified
 	 * descriptor table.
 	 */
-	if (SELISLDT(sel)) {
-		if (ndx > p->p_ldtlimit)
+	if (ISLDT(sel)) {
+#ifdef __i386__
+		if (ndx > p->p_md.md_ldt->ldt_len)
 			return (-1);
 
-		desc = p->p_ldt + ndx;
+		desc = (struct segment_descriptor *)
+		    p->p_md.md_ldt[ndx].ldt_base;
+#else
+		if (ndx > max_ldt_segment)
+			return (-1);
+
+		desc = (struct user_segment_descriptor *)
+		    p->p_md.md_ldt[ndx].ldt_base;
+#endif
 
 	} else {
 		if (ndx >= NGDT)
 			return (-1);
 
-		desc = cpu_get_gdt() + ndx;
+#ifdef __i386__
+		desc = &gdt[ndx].sd;
+#else
+		desc = &gdt[ndx];
+#endif
 	}
 
 	/*
 	 * The descriptor must have user privilege level and it must be
 	 * present in memory.
 	 */
-	if (desc->usd_dpl != SEL_UPL || desc->usd_p != 1)
+	if (desc->sd_dpl != SEL_UPL || desc->sd_p != 1)
 		return (-1);
 
-	type = desc->usd_type;
+	type = desc->sd_type;
 
 	/*
 	 * If the S bit in the type field is not set, this descriptor can
@@ -833,7 +944,7 @@ fasttrap_do_seg(fasttrap_tracepoint_t *tp, struct regs *rp, uintptr_t *addr)
 	if ((type & 0x10) != 0x10)
 		return (-1);
 
-	limit = USEGD_GETLIMIT(desc) * (desc->usd_gran ? PAGESIZE : 1);
+	limit = USD_GETLIMIT(desc) * (desc->sd_gran ? PAGESIZE : 1);
 
 	if (tp->ftt_segment == FASTTRAP_SEG_CS) {
 		/*
@@ -861,7 +972,7 @@ fasttrap_do_seg(fasttrap_tracepoint_t *tp, struct regs *rp, uintptr_t *addr)
 		if ((type & 0x4) == 0) {
 			if (*addr > limit)
 				return (-1);
-		} else if (desc->usd_def32) {
+		} else if (desc->sd_def32) {
 			if (*addr < limit + 1 || 0xffff < *addr)
 				return (-1);
 		} else {
@@ -870,18 +981,21 @@ fasttrap_do_seg(fasttrap_tracepoint_t *tp, struct regs *rp, uintptr_t *addr)
 		}
 	}
 
-	*addr += USEGD_GETBASE(desc);
+	*addr += USD_GETBASE(desc);
 
 	return (0);
 }
 
 int
-fasttrap_pid_probe(struct regs *rp)
+fasttrap_pid_probe(struct reg *rp)
 {
 	proc_t *p = curproc;
-	uintptr_t pc = rp->r_pc - 1, new_pc = 0;
+	uintptr_t pc = rp->r_rip - 1;
+	uintptr_t new_pc = 0;
 	fasttrap_bucket_t *bucket;
+#if defined(sun)
 	kmutex_t *pid_mtx;
+#endif
 	fasttrap_tracepoint_t *tp, tp_local;
 	pid_t pid;
 	dtrace_icookie_t cookie;
@@ -911,6 +1025,7 @@ fasttrap_pid_probe(struct regs *rp)
 	curthread->t_dtrace_regv = 0;
 #endif
 
+#if defined(sun)
 	/*
 	 * Treat a child created by a call to vfork(2) as if it were its
 	 * parent. We know that there's only one thread of control in such a
@@ -919,10 +1034,14 @@ fasttrap_pid_probe(struct regs *rp)
 	while (p->p_flag & SVFORK) {
 		p = p->p_parent;
 	}
+#endif
 
+	PROC_LOCK(p);
 	pid = p->p_pid;
+#if defined(sun)
 	pid_mtx = &cpu_core[CPU->cpu_id].cpuc_pid_lock;
 	mutex_enter(pid_mtx);
+#endif
 	bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
 
 	/*
@@ -940,15 +1059,19 @@ fasttrap_pid_probe(struct regs *rp)
 	 * fasttrap_ioctl), or somehow we have mislaid this tracepoint.
 	 */
 	if (tp == NULL) {
+#if defined(sun)
 		mutex_exit(pid_mtx);
+#endif
+		PROC_UNLOCK(p);
 		return (-1);
 	}
 
+	printf("found tracepoint\n");
 	/*
 	 * Set the program counter to the address of the traced instruction
 	 * so that it looks right in ustack() output.
 	 */
-	rp->r_pc = pc;
+	rp->r_rip = pc;
 
 	if (tp->ftt_ids != NULL) {
 		fasttrap_id_t *id;
@@ -995,9 +1118,9 @@ fasttrap_pid_probe(struct regs *rp)
 				}
 			}
 		} else {
-#endif
+#else /* __amd64 */
 			uintptr_t s0, s1, s2, s3, s4, s5;
-			uint32_t *stack = (uint32_t *)rp->r_sp;
+			uint32_t *stack = (uint32_t *)rp->r_esp;
 
 			/*
 			 * In 32-bit mode, all arguments are passed on the
@@ -1050,6 +1173,7 @@ fasttrap_pid_probe(struct regs *rp)
 					    t[2], t[3], t[4]);
 				}
 			}
+#endif /* __amd64 */
 #ifdef __amd64
 		}
 #endif
@@ -1061,7 +1185,10 @@ fasttrap_pid_probe(struct regs *rp)
 	 * tracepoint again later if we need to light up any return probes.
 	 */
 	tp_local = *tp;
+	PROC_UNLOCK(p);
+#if defined(sun)
 	mutex_exit(pid_mtx);
+#endif
 	tp = &tp_local;
 
 	/*
@@ -1069,7 +1196,7 @@ fasttrap_pid_probe(struct regs *rp)
 	 * had completely executed. This ensures that fasttrap_getreg() will
 	 * report the expected value for REG_RIP.
 	 */
-	rp->r_pc = pc + tp->ftt_size;
+	rp->r_rip = pc + tp->ftt_size;
 
 	/*
 	 * If there's an is-enabled probe connected to this tracepoint it
@@ -1083,8 +1210,8 @@ fasttrap_pid_probe(struct regs *rp)
 	 * exotic way to shoot oneself in the foot.
 	 */
 	if (is_enabled) {
-		rp->r_r0 = 1;
-		new_pc = rp->r_pc;
+		rp->r_rax = 1;
+		new_pc = rp->r_rip;
 		goto done;
 	}
 
@@ -1098,9 +1225,9 @@ fasttrap_pid_probe(struct regs *rp)
 	case FASTTRAP_T_RET:
 	case FASTTRAP_T_RET16:
 	{
-		uintptr_t dst;
-		uintptr_t addr;
-		int ret;
+		uintptr_t dst = 0;
+		uintptr_t addr = 0;
+		int ret = 0;
 
 		/*
 		 * We have to emulate _every_ facet of the behavior of a ret
@@ -1109,20 +1236,22 @@ fasttrap_pid_probe(struct regs *rp)
 		 */
 #ifdef __amd64
 		if (p->p_model == DATAMODEL_NATIVE) {
-#endif
-			ret = fasttrap_fulword((void *)rp->r_sp, &dst);
-			addr = rp->r_sp + sizeof (uintptr_t);
-#ifdef __amd64
+			ret = dst = fasttrap_fulword((void *)rp->r_rsp);
+			addr = rp->r_rsp + sizeof (uintptr_t);
 		} else {
+#endif
+#ifdef __i386__
 			uint32_t dst32;
-			ret = fasttrap_fuword32((void *)rp->r_sp, &dst32);
+			ret = dst32 = fasttrap_fuword32((void *)rp->r_esp);
 			dst = dst32;
-			addr = rp->r_sp + sizeof (uint32_t);
+			addr = rp->r_esp + sizeof (uint32_t);
+#endif
+#ifdef __amd64
 		}
 #endif
 
 		if (ret == -1) {
-			fasttrap_sigsegv(p, curthread, rp->r_sp);
+			fasttrap_sigsegv(p, curthread, rp->r_rsp);
 			new_pc = pc;
 			break;
 		}
@@ -1130,71 +1259,71 @@ fasttrap_pid_probe(struct regs *rp)
 		if (tp->ftt_type == FASTTRAP_T_RET16)
 			addr += tp->ftt_dest;
 
-		rp->r_sp = addr;
+		rp->r_rsp = addr;
 		new_pc = dst;
 		break;
 	}
 
 	case FASTTRAP_T_JCC:
 	{
-		uint_t taken;
+		uint_t taken = 0;
 
 		switch (tp->ftt_code) {
 		case FASTTRAP_JO:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_OF) != 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_OF) != 0;
 			break;
 		case FASTTRAP_JNO:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_OF) == 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_OF) == 0;
 			break;
 		case FASTTRAP_JB:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_CF) != 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_CF) != 0;
 			break;
 		case FASTTRAP_JAE:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_CF) == 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_CF) == 0;
 			break;
 		case FASTTRAP_JE:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_ZF) != 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_ZF) != 0;
 			break;
 		case FASTTRAP_JNE:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_ZF) == 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_ZF) == 0;
 			break;
 		case FASTTRAP_JBE:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_CF) != 0 ||
-			    (rp->r_ps & FASTTRAP_EFLAGS_ZF) != 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_CF) != 0 ||
+			    (rp->r_rflags & FASTTRAP_EFLAGS_ZF) != 0;
 			break;
 		case FASTTRAP_JA:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_CF) == 0 &&
-			    (rp->r_ps & FASTTRAP_EFLAGS_ZF) == 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_CF) == 0 &&
+			    (rp->r_rflags & FASTTRAP_EFLAGS_ZF) == 0;
 			break;
 		case FASTTRAP_JS:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_SF) != 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_SF) != 0;
 			break;
 		case FASTTRAP_JNS:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_SF) == 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_SF) == 0;
 			break;
 		case FASTTRAP_JP:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_PF) != 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_PF) != 0;
 			break;
 		case FASTTRAP_JNP:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_PF) == 0;
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_PF) == 0;
 			break;
 		case FASTTRAP_JL:
-			taken = ((rp->r_ps & FASTTRAP_EFLAGS_SF) == 0) !=
-			    ((rp->r_ps & FASTTRAP_EFLAGS_OF) == 0);
+			taken = ((rp->r_rflags & FASTTRAP_EFLAGS_SF) == 0) !=
+			    ((rp->r_rflags & FASTTRAP_EFLAGS_OF) == 0);
 			break;
 		case FASTTRAP_JGE:
-			taken = ((rp->r_ps & FASTTRAP_EFLAGS_SF) == 0) ==
-			    ((rp->r_ps & FASTTRAP_EFLAGS_OF) == 0);
+			taken = ((rp->r_rflags & FASTTRAP_EFLAGS_SF) == 0) ==
+			    ((rp->r_rflags & FASTTRAP_EFLAGS_OF) == 0);
 			break;
 		case FASTTRAP_JLE:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_ZF) != 0 ||
-			    ((rp->r_ps & FASTTRAP_EFLAGS_SF) == 0) !=
-			    ((rp->r_ps & FASTTRAP_EFLAGS_OF) == 0);
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_ZF) != 0 ||
+			    ((rp->r_rflags & FASTTRAP_EFLAGS_SF) == 0) !=
+			    ((rp->r_rflags & FASTTRAP_EFLAGS_OF) == 0);
 			break;
 		case FASTTRAP_JG:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_ZF) == 0 &&
-			    ((rp->r_ps & FASTTRAP_EFLAGS_SF) == 0) ==
-			    ((rp->r_ps & FASTTRAP_EFLAGS_OF) == 0);
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_ZF) == 0 &&
+			    ((rp->r_rflags & FASTTRAP_EFLAGS_SF) == 0) ==
+			    ((rp->r_rflags & FASTTRAP_EFLAGS_OF) == 0);
 			break;
 
 		}
@@ -1208,7 +1337,7 @@ fasttrap_pid_probe(struct regs *rp)
 
 	case FASTTRAP_T_LOOP:
 	{
-		uint_t taken;
+		uint_t taken = 0;
 #ifdef __amd64
 		greg_t cx = rp->r_rcx--;
 #else
@@ -1217,11 +1346,11 @@ fasttrap_pid_probe(struct regs *rp)
 
 		switch (tp->ftt_code) {
 		case FASTTRAP_LOOPNZ:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_ZF) == 0 &&
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_ZF) == 0 &&
 			    cx != 0;
 			break;
 		case FASTTRAP_LOOPZ:
-			taken = (rp->r_ps & FASTTRAP_EFLAGS_ZF) != 0 &&
+			taken = (rp->r_rflags & FASTTRAP_EFLAGS_ZF) != 0 &&
 			    cx != 0;
 			break;
 		case FASTTRAP_LOOP:
@@ -1253,18 +1382,19 @@ fasttrap_pid_probe(struct regs *rp)
 
 	case FASTTRAP_T_PUSHL_EBP:
 	{
-		int ret;
-		uintptr_t addr;
+		int ret = 0;
+		uintptr_t addr = 0;
 #ifdef __amd64
 		if (p->p_model == DATAMODEL_NATIVE) {
-#endif
-			addr = rp->r_sp - sizeof (uintptr_t);
-			ret = fasttrap_sulword((void *)addr, rp->r_fp);
-#ifdef __amd64
+			addr = rp->r_rsp - sizeof (uintptr_t);
+			ret = fasttrap_sulword((void *)addr, &rp->r_rsp);
 		} else {
-			addr = rp->r_sp - sizeof (uint32_t);
-			ret = fasttrap_suword32((void *)addr,
-			    (uint32_t)rp->r_fp);
+#endif
+#ifdef __i386__
+			addr = rp->r_rsp - sizeof (uint32_t);
+			ret = fasttrap_suword32((void *)addr, &rp->r_rsp);
+#endif
+#ifdef __amd64
 		}
 #endif
 
@@ -1274,7 +1404,7 @@ fasttrap_pid_probe(struct regs *rp)
 			break;
 		}
 
-		rp->r_sp = addr;
+		rp->r_rsp = addr;
 		new_pc = pc + tp->ftt_size;
 		break;
 	}
@@ -1288,7 +1418,10 @@ fasttrap_pid_probe(struct regs *rp)
 		if (tp->ftt_code == 0) {
 			new_pc = tp->ftt_dest;
 		} else {
-			uintptr_t value, addr = tp->ftt_dest;
+#ifdef __amd64
+			uintptr_t value;
+#endif
+			uintptr_t addr = tp->ftt_dest;
 
 			if (tp->ftt_base != FASTTRAP_NOREG)
 				addr += fasttrap_getreg(rp, tp->ftt_base);
@@ -1312,32 +1445,34 @@ fasttrap_pid_probe(struct regs *rp)
 
 #ifdef __amd64
 				if (p->p_model == DATAMODEL_NATIVE) {
-#endif
-					if (fasttrap_fulword((void *)addr,
-					    &value) == -1) {
+					if ((value = fasttrap_fulword((void *)addr))
+					     == -1) {
 						fasttrap_sigsegv(p, curthread,
 						    addr);
 						new_pc = pc;
 						break;
 					}
 					new_pc = value;
-#ifdef __amd64
 				} else {
+#endif
+#ifdef __i386__
 					uint32_t value32;
 					addr = (uintptr_t)(uint32_t)addr;
-					if (fasttrap_fuword32((void *)addr,
-					    &value32) == -1) {
+					if ((value32 = fasttrap_fuword32((void *)addr))
+					    == -1) {
 						fasttrap_sigsegv(p, curthread,
 						    addr);
 						new_pc = pc;
 						break;
 					}
 					new_pc = value32;
-				}
 #endif
+				}
+#ifdef __amd64
 			} else {
 				new_pc = addr;
 			}
+#endif
 		}
 
 		/*
@@ -1347,18 +1482,20 @@ fasttrap_pid_probe(struct regs *rp)
 		 * this instruction weren't traced.
 		 */
 		if (tp->ftt_type == FASTTRAP_T_CALL) {
-			int ret;
-			uintptr_t addr;
+			int ret = 0;
+			uintptr_t addr = 0, pcps;
 #ifdef __amd64
 			if (p->p_model == DATAMODEL_NATIVE) {
-				addr = rp->r_sp - sizeof (uintptr_t);
-				ret = fasttrap_sulword((void *)addr,
-				    pc + tp->ftt_size);
+				addr = rp->r_rsp - sizeof (uintptr_t);
+				pcps = pc + tp->ftt_size;
+				ret = fasttrap_sulword((void *)addr, &pcps);
 			} else {
 #endif
-				addr = rp->r_sp - sizeof (uint32_t);
-				ret = fasttrap_suword32((void *)addr,
-				    (uint32_t)(pc + tp->ftt_size));
+#ifdef __i386__
+				addr = rp->r_rsp - sizeof (uint32_t);
+				pcps = (uint32_t)(pc + tp->ftt_size);
+				ret = fasttrap_suword32((void *)addr, &pcps);
+#endif
 #ifdef __amd64
 			}
 #endif
@@ -1369,7 +1506,7 @@ fasttrap_pid_probe(struct regs *rp)
 				break;
 			}
 
-			rp->r_sp = addr;
+			rp->r_rsp = addr;
 		}
 
 		break;
@@ -1383,7 +1520,9 @@ fasttrap_pid_probe(struct regs *rp)
 		uint8_t scratch[2 * FASTTRAP_MAX_INSTR_SIZE + 7];
 #endif
 		uint_t i = 0;
+#if defined(sun)
 		klwp_t *lwp = ttolwp(curthread);
+#endif
 
 		/*
 		 * Compute the address of the ulwp_t and step over the
@@ -1391,6 +1530,7 @@ fasttrap_pid_probe(struct regs *rp)
 		 * thread pointer is very different on 32- and 64-bit
 		 * kernels.
 		 */
+#if defined(sun)
 #if defined(__amd64)
 		if (p->p_model == DATAMODEL_LP64) {
 			addr = lwp->lwp_pcb.pcb_fsbase;
@@ -1400,9 +1540,16 @@ fasttrap_pid_probe(struct regs *rp)
 			addr += sizeof (caddr32_t);
 		}
 #else
-		addr = USEGD_GETBASE(&lwp->lwp_pcb.pcb_gsdesc);
+		addr = USD_GETBASE(&lwp->lwp_pcb.pcb_gsdesc);
 		addr += sizeof (void *);
 #endif
+#endif /* sun */
+#ifdef __i386__
+		addr = USD_GETBASE(&curthread->td_pcb->pcb_gsd);
+#else
+		addr = curthread->td_pcb->pcb_gsbase;
+#endif
+		addr += sizeof (void *);
 
 		/*
 		 * Generic Instruction Tracing
@@ -1495,7 +1642,7 @@ fasttrap_pid_probe(struct regs *rp)
 
 #ifdef __amd64
 		if (tp->ftt_ripmode != 0) {
-			greg_t *reg;
+			greg_t *reg = NULL;
 
 			ASSERT(p->p_model == DATAMODEL_LP64);
 			ASSERT(tp->ftt_ripmode &
@@ -1566,6 +1713,7 @@ fasttrap_pid_probe(struct regs *rp)
 			i += sizeof (uint64_t);
 		} else {
 #endif
+#ifdef __i386__
 			/*
 			 * Set up the jmp to the next instruction; note that
 			 * the size of the traced instruction cancels out.
@@ -1574,6 +1722,7 @@ fasttrap_pid_probe(struct regs *rp)
 			/* LINTED - alignment */
 			*(uint32_t *)&scratch[i] = pc - addr - 5;
 			i += sizeof (uint32_t);
+#endif
 #ifdef __amd64
 		}
 #endif
@@ -1632,7 +1781,7 @@ done:
 			 * output. We had previously set it to the end of the
 			 * instruction to simplify %rip-relative addressing.
 			 */
-			rp->r_pc = pc;
+			rp->r_rip = pc;
 
 			fasttrap_return_common(rp, pc, pid, new_pc);
 		} else {
@@ -1643,13 +1792,14 @@ done:
 		}
 	}
 
-	rp->r_pc = new_pc;
+	rp->r_rip = new_pc;
+	set_regs(curthread, rp);
 
 	return (0);
 }
 
 int
-fasttrap_return_probe(struct regs *rp)
+fasttrap_return_probe(struct reg *rp)
 {
 	proc_t *p = curproc;
 	uintptr_t pc = curthread->t_dtrace_pc;
@@ -1660,6 +1810,7 @@ fasttrap_return_probe(struct regs *rp)
 	curthread->t_dtrace_scrpc = 0;
 	curthread->t_dtrace_astpc = 0;
 
+#if defined(sun)
 	/*
 	 * Treat a child created by a call to vfork(2) as if it were its
 	 * parent. We know that there's only one thread of control in such a
@@ -1668,15 +1819,16 @@ fasttrap_return_probe(struct regs *rp)
 	while (p->p_flag & SVFORK) {
 		p = p->p_parent;
 	}
+#endif
 
 	/*
-	 * We set rp->r_pc to the address of the traced instruction so
+	 * We set rp->r_rip to the address of the traced instruction so
 	 * that it appears to dtrace_probe() that we're on the original
 	 * instruction, and so that the user can't easily detect our
 	 * complex web of lies. dtrace_return_probe() (our caller)
 	 * will correctly set %pc after we return.
 	 */
-	rp->r_pc = pc;
+	rp->r_rip = pc;
 
 	fasttrap_return_common(rp, pc, p->p_pid, npc);
 
@@ -1688,7 +1840,11 @@ uint64_t
 fasttrap_pid_getarg(void *arg, dtrace_id_t id, void *parg, int argno,
     int aframes)
 {
-	return (fasttrap_anarg(ttolwp(curthread)->lwp_regs, 1, argno));
+	struct reg r;
+
+	fill_regs(curthread, &r);
+
+	return (fasttrap_anarg(&r, 1, argno));
 }
 
 /*ARGSUSED*/
@@ -1696,11 +1852,15 @@ uint64_t
 fasttrap_usdt_getarg(void *arg, dtrace_id_t id, void *parg, int argno,
     int aframes)
 {
-	return (fasttrap_anarg(ttolwp(curthread)->lwp_regs, 0, argno));
+	struct reg r;
+
+	fill_regs(curthread, &r);
+
+	return (fasttrap_anarg(&r, 0, argno));
 }
 
 static ulong_t
-fasttrap_getreg(struct regs *rp, uint_t reg)
+fasttrap_getreg(struct reg *rp, uint_t reg)
 {
 #ifdef __amd64
 	switch (reg) {
@@ -1723,20 +1883,23 @@ fasttrap_getreg(struct regs *rp, uint_t reg)
 	case REG_ERR:		return (rp->r_err);
 	case REG_RIP:		return (rp->r_rip);
 	case REG_CS:		return (rp->r_cs);
+#if defined(sun)
 	case REG_RFL:		return (rp->r_rfl);
+#endif
 	case REG_RSP:		return (rp->r_rsp);
 	case REG_SS:		return (rp->r_ss);
 	case REG_FS:		return (rp->r_fs);
 	case REG_GS:		return (rp->r_gs);
 	case REG_DS:		return (rp->r_ds);
 	case REG_ES:		return (rp->r_es);
-	case REG_FSBASE:	return (rdmsr(MSR_AMD_FSBASE));
-	case REG_GSBASE:	return (rdmsr(MSR_AMD_GSBASE));
+	case REG_FSBASE:	return (rdmsr(MSR_FSBASE));
+	case REG_GSBASE:	return (rdmsr(MSR_GSBASE));
 	}
 
 	panic("dtrace: illegal register constant");
 	/*NOTREACHED*/
 #else
+#define _NGREG 19
 	if (reg >= _NGREG)
 		panic("dtrace: illegal register constant");
 

From 5caab9d4cdc1f5147d5150bad7d3798ca86107e2 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 12:12:03 +0000
Subject: [PATCH 0198/1624] Replace a pksignal() call with tdksignal().

Pointed out by:	kib
---
 sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
index eda5b26cc3d..be07d197f0c 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
@@ -277,7 +277,7 @@ fasttrap_sigtrap(proc_t *p, kthread_t *t, uintptr_t pc)
 	ksi->ksi_code = TRAP_DTRACE;
 	ksi->ksi_addr = (caddr_t)pc;
 	PROC_LOCK(p);
-	(void) pksignal(p, SIGTRAP, ksi);
+	(void) tdksignal(t, SIGTRAP, ksi);
 	PROC_UNLOCK(p);
 #endif
 }

From 4873b1ac4d55e0c456037b9467d5c95ba84bb70a Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 12:18:39 +0000
Subject: [PATCH 0199/1624] Update for the recent location of the fasttrap
 code.

Sponsored by:	The FreeBSD Foundation
---
 sys/modules/dtrace/fasttrap/Makefile | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/sys/modules/dtrace/fasttrap/Makefile b/sys/modules/dtrace/fasttrap/Makefile
index 0af63c4eb03..cf93c153099 100644
--- a/sys/modules/dtrace/fasttrap/Makefile
+++ b/sys/modules/dtrace/fasttrap/Makefile
@@ -1,9 +1,9 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/../../../cddl/dev/fasttrap
+.PATH:	${.CURDIR}/../../../cddl/contrib/opensolaris/uts/common/dtrace
 
 KMOD=		fasttrap
-SRCS=		fasttrap.c
+SRCS=		fasttrap.c fasttrap_isa.c opt_compat.h
 SRCS+=		vnode_if.h
 
 CFLAGS+=	-I${.CURDIR}/../../../cddl/compat/opensolaris \
@@ -12,6 +12,7 @@ CFLAGS+=	-I${.CURDIR}/../../../cddl/compat/opensolaris \
 
 .if ${MACHINE_CPUARCH} == "amd64" ||  ${MACHINE_CPUARCH} == "i386"
 CFLAGS+=	-I${.CURDIR}/../../../cddl/contrib/opensolaris/uts/intel
+.PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/uts/intel/dtrace
 .endif
 
 CFLAGS+=	-DSMP -DDEBUG

From f5a5c5653a99ce0bc36c42fa5ce0244536560023 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 12:56:45 +0000
Subject: [PATCH 0200/1624] Replace structure assignments with explicity memcpy
 calls. This allows Clang to compile this file: it was using the builtin
 memcpy and we want to use the memcpy defined in gptboot.c. (Clang can't
 compile boot2 yet).

Submitted by:	Dimitry Andric 
Reviewed by:	jhb
---
 sys/boot/common/ufsread.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/sys/boot/common/ufsread.c b/sys/boot/common/ufsread.c
index cd3ba4c5d12..5d0e8af56b8 100644
--- a/sys/boot/common/ufsread.c
+++ b/sys/boot/common/ufsread.c
@@ -223,14 +223,19 @@ fsread(ino_t inode, void *buf, size_t nbyte)
 			return -1;
 		n = INO_TO_VBO(n, inode);
 #if defined(UFS1_ONLY)
-		dp1 = ((struct ufs1_dinode *)blkbuf)[n];
+		memcpy(&dp1, (struct ufs1_dinode *)blkbuf + n,
+		    sizeof(struct ufs1_dinode));
 #elif defined(UFS2_ONLY)
-		dp2 = ((struct ufs2_dinode *)blkbuf)[n];
+		memcpy(&dp2, (struct ufs2_dinode *)blkbuf + n,
+		    sizeof(struct ufs2_dinode));
 #else
 		if (fs->fs_magic == FS_UFS1_MAGIC)
-			dp1 = ((struct ufs1_dinode *)blkbuf)[n];
+			memcpy(&dp1, (struct ufs1_dinode *)blkbuf + n,
+			    sizeof(struct ufs1_dinode));
 		else
-			dp2 = ((struct ufs2_dinode *)blkbuf)[n];
+			memcpy(&dp2, (struct ufs2_dinode *)blkbuf + n,
+			    sizeof(struct ufs2_dinode));
+
 #endif
 		inomap = inode;
 		fs_off = 0;

From da2a0df59c215bf19150821eec15440f2db3f932 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 24 Aug 2010 12:58:54 +0000
Subject: [PATCH 0201/1624] Move the __stack_chk_fail_local@FBSD_1.0 compat
 symbol definition into the separate .o for libc_pic.a. This prevents rtld
 from making the symbol global.

Putting the stack_protector_compat.c into the public domain acknowledged
by kan.

Reviewed by:	kan
MFC after:	2 weeks
---
 lib/libc/sys/Makefile.inc             |  2 +-
 lib/libc/sys/stack_protector.c        |  4 +---
 lib/libc/sys/stack_protector_compat.c | 20 ++++++++++++++++++++
 3 files changed, 22 insertions(+), 4 deletions(-)
 create mode 100644 lib/libc/sys/stack_protector_compat.c

diff --git a/lib/libc/sys/Makefile.inc b/lib/libc/sys/Makefile.inc
index 05c3e173d10..dc56429a267 100644
--- a/lib/libc/sys/Makefile.inc
+++ b/lib/libc/sys/Makefile.inc
@@ -18,7 +18,7 @@
 .endif
 
 # Sources common to both syscall interfaces:
-SRCS+=	stack_protector.c __error.c
+SRCS+=	stack_protector.c stack_protector_compat.c __error.c
 .if !defined(WITHOUT_SYSCALL_COMPAT)
 SRCS+=	fcntl.c ftruncate.c lseek.c mmap.c pread.c pwrite.c truncate.c
 PSEUDO+= _fcntl.o
diff --git a/lib/libc/sys/stack_protector.c b/lib/libc/sys/stack_protector.c
index b0108f9ff7a..114972f97b4 100644
--- a/lib/libc/sys/stack_protector.c
+++ b/lib/libc/sys/stack_protector.c
@@ -116,8 +116,6 @@ __chk_fail(void)
 	__fail("buffer overflow detected; terminated");
 }
 
-#ifdef PIC
-__sym_compat(__stack_chk_fail_local, __stack_chk_fail, FBSD_1.0);
-#else
+#ifndef PIC
 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
 #endif
diff --git a/lib/libc/sys/stack_protector_compat.c b/lib/libc/sys/stack_protector_compat.c
new file mode 100644
index 00000000000..cacb863e75e
--- /dev/null
+++ b/lib/libc/sys/stack_protector_compat.c
@@ -0,0 +1,20 @@
+/*
+ * Written by Alexander Kabaev 
+ * The file is in public domain.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+void __stack_chk_fail(void);
+
+#ifdef PIC
+void
+__stack_chk_fail_local_hidden(void)
+{
+
+	__stack_chk_fail();
+}
+
+__sym_compat(__stack_chk_fail_local, __stack_chk_fail_local_hidden, FBSD_1.0);
+#endif

From d4ba3a561930841fc27a6e9c2d3db0c91d38667e Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 24 Aug 2010 13:01:14 +0000
Subject: [PATCH 0202/1624] Remove exports table. Export control by the version
 script is enough.

Reviewed by:	kan
MFC after:	3 weeks
---
 libexec/rtld-elf/rtld.c | 54 +++--------------------------------------
 1 file changed, 4 insertions(+), 50 deletions(-)

diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
index dc5cdca2ee9..a1b95ae612c 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -104,7 +104,6 @@ static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
 static void init_rtld(caddr_t, Elf_Auxinfo **);
 static void initlist_add_neededs(Needed_Entry *, Objlist *);
 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
-static bool is_exported(const Elf_Sym *);
 static void linkmap_add(Obj_Entry *);
 static void linkmap_delete(Obj_Entry *);
 static int load_needed_objects(Obj_Entry *, int);
@@ -196,36 +195,6 @@ extern Elf_Dyn _DYNAMIC;
 
 int osreldate, pagesize;
 
-/*
- * These are the functions the dynamic linker exports to application
- * programs.  They are the only symbols the dynamic linker is willing
- * to export from itself.
- */
-static func_ptr_type exports[] = {
-    (func_ptr_type) &_rtld_error,
-    (func_ptr_type) &dlclose,
-    (func_ptr_type) &dlerror,
-    (func_ptr_type) &dlopen,
-    (func_ptr_type) &dlsym,
-    (func_ptr_type) &dlfunc,
-    (func_ptr_type) &dlvsym,
-    (func_ptr_type) &dladdr,
-    (func_ptr_type) &dllockinit,
-    (func_ptr_type) &dlinfo,
-    (func_ptr_type) &_rtld_thread_init,
-#ifdef __i386__
-    (func_ptr_type) &___tls_get_addr,
-#endif
-    (func_ptr_type) &__tls_get_addr,
-    (func_ptr_type) &_rtld_allocate_tls,
-    (func_ptr_type) &_rtld_free_tls,
-    (func_ptr_type) &dl_iterate_phdr,
-    (func_ptr_type) &_rtld_atfork_pre,
-    (func_ptr_type) &_rtld_atfork_post,
-    (func_ptr_type) &_rtld_addr_phdr,
-    NULL
-};
-
 /*
  * Global declarations normally provided by crt1.  The dynamic linker is
  * not built with crt1, so we have to provide them ourselves.
@@ -1445,19 +1414,6 @@ initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
 #define FPTR_TARGET(f)	((Elf_Addr) (f))
 #endif
 
-static bool
-is_exported(const Elf_Sym *def)
-{
-    Elf_Addr value;
-    const func_ptr_type *p;
-
-    value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
-    for (p = exports;  *p != NULL;  p++)
-	if (FPTR_TARGET(*p) == value)
-	    return true;
-    return false;
-}
-
 /*
  * Given a shared object, traverse its list of needed objects, and load
  * each of them.  Returns 0 on success.  Generates an error message and
@@ -2161,12 +2117,11 @@ do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
 	    /*
 	     * Search the dynamic linker itself, and possibly resolve the
 	     * symbol from there.  This is how the application links to
-	     * dynamic linker services such as dlopen.  Only the values listed
-	     * in the "exports" array can be resolved from the dynamic linker.
+	     * dynamic linker services such as dlopen.
 	     */
 	    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
 		symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
-		if (symp != NULL && is_exported(symp)) {
+		if (symp != NULL) {
 		    def = symp;
 		    defobj = &obj_rtld;
 		}
@@ -2746,12 +2701,11 @@ symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
     /*
      * Search the dynamic linker itself, and possibly resolve the
      * symbol from there.  This is how the application links to
-     * dynamic linker services such as dlopen.  Only the values listed
-     * in the "exports" array can be resolved from the dynamic linker.
+     * dynamic linker services such as dlopen.
      */
     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
 	symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
-	if (symp != NULL && is_exported(symp)) {
+	if (symp != NULL) {
 	    def = symp;
 	    defobj = &obj_rtld;
 	}

From 3e3fbd3f25a24a1ca28a79b86cf067a0189ec406 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 24 Aug 2010 13:02:22 +0000
Subject: [PATCH 0203/1624] Remove extra FreeBSD tag.

MFC after:	3 days
---
 lib/libc/sys/stack_protector.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/lib/libc/sys/stack_protector.c b/lib/libc/sys/stack_protector.c
index 114972f97b4..14e991e3a05 100644
--- a/lib/libc/sys/stack_protector.c
+++ b/lib/libc/sys/stack_protector.c
@@ -1,4 +1,3 @@
-/* $FreeBSD$ */
 /* $NetBSD: stack_protector.c,v 1.4 2006/11/22 17:23:25 christos Exp $	*/
 /* $OpenBSD: stack_protector.c,v 1.10 2006/03/31 05:34:44 deraadt Exp $	*/
 /*

From 12f48a53f99bbb1bef129d87a37ef2b6dad64b85 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 13:11:24 +0000
Subject: [PATCH 0204/1624] Add a trap code for DTrace induced traps.

Sponsored by:	The FreeBSD Foundation
---
 sys/sys/signal.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/sys/signal.h b/sys/sys/signal.h
index a8620575572..85116430fcc 100644
--- a/sys/sys/signal.h
+++ b/sys/sys/signal.h
@@ -266,6 +266,7 @@ typedef	struct __siginfo {
 /* codes for SIGTRAP */
 #define TRAP_BRKPT	1	/* Process breakpoint.			*/
 #define TRAP_TRACE	2	/* Process trace trap.			*/
+#define	TRAP_DTRACE	3	/* DTrace induced trap.			*/
 
 /* codes for SIGCHLD */
 #define CLD_EXITED	1	/* Child has exited			*/

From 8a8d8fa3d1f937b51bad4314d2de6307b5c7ea2e Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 13:13:24 +0000
Subject: [PATCH 0205/1624] Add two DTrace trap type values. Used by fasttrap.

Sponsored by:	The FreeBSD Foundation
---
 sys/amd64/include/trap.h | 2 ++
 sys/i386/include/trap.h  | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/sys/amd64/include/trap.h b/sys/amd64/include/trap.h
index f0176b2c97e..d8e36b5aaf3 100644
--- a/sys/amd64/include/trap.h
+++ b/sys/amd64/include/trap.h
@@ -62,6 +62,8 @@
 #define	T_MCHK		28	/* machine check trap */
 #define	T_XMMFLT	29	/* SIMD floating-point exception */
 #define	T_RESERVED	30	/* reserved (unknown) */
+#define	T_DTRACE_RET	31	/* DTrace pid return */
+#define	T_DTRACE_PROBE	32	/* DTrace fasttrap probe */
 
 /* XXX most of the following codes aren't used, but could be. */
 
diff --git a/sys/i386/include/trap.h b/sys/i386/include/trap.h
index f0176b2c97e..d8e36b5aaf3 100644
--- a/sys/i386/include/trap.h
+++ b/sys/i386/include/trap.h
@@ -62,6 +62,8 @@
 #define	T_MCHK		28	/* machine check trap */
 #define	T_XMMFLT	29	/* SIMD floating-point exception */
 #define	T_RESERVED	30	/* reserved (unknown) */
+#define	T_DTRACE_RET	31	/* DTrace pid return */
+#define	T_DTRACE_PROBE	32	/* DTrace fasttrap probe */
 
 /* XXX most of the following codes aren't used, but could be. */
 

From 4fbdc85400a6de487e542a9664bbae51e254f8aa Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 13:21:05 +0000
Subject: [PATCH 0206/1624] Enable fasttrap and make dtraceall depend on
 fasttrap when building i386 or amd64.

Sponsored by:	The FreeBSD Foundation
---
 sys/modules/dtrace/Makefile              | 2 +-
 sys/modules/dtrace/dtraceall/dtraceall.c | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/modules/dtrace/Makefile b/sys/modules/dtrace/Makefile
index 75d4a44dcab..02c476697c6 100644
--- a/sys/modules/dtrace/Makefile
+++ b/sys/modules/dtrace/Makefile
@@ -15,7 +15,7 @@ SUBDIR=		dtmalloc	\
 		systrace
 
 .if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
-SUBDIR+=	fbt
+SUBDIR+=	fasttrap fbt
 .endif
 
 .include 
diff --git a/sys/modules/dtrace/dtraceall/dtraceall.c b/sys/modules/dtrace/dtraceall/dtraceall.c
index d8d330fda30..ecb5e344b03 100644
--- a/sys/modules/dtrace/dtraceall/dtraceall.c
+++ b/sys/modules/dtrace/dtraceall/dtraceall.c
@@ -68,6 +68,7 @@ MODULE_DEPEND(dtraceall, dtmalloc, 1, 1, 1);
 MODULE_DEPEND(dtraceall, dtnfsclient, 1, 1, 1);
 #if defined(__amd64__) || defined(__i386__)
 MODULE_DEPEND(dtraceall, fbt, 1, 1, 1);
+MODULE_DEPEND(dtraceall, fasttrap, 1, 1, 1);
 #endif
 MODULE_DEPEND(dtraceall, lockstat, 1, 1, 1);
 MODULE_DEPEND(dtraceall, sdt, 1, 1, 1);

From 1fdc87e76de8053f6bba3d19a2efa264d35167ec Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 13:38:53 +0000
Subject: [PATCH 0207/1624] Some fixes so we can build libstdc++ with clang: o
 Make the value_type, vector_type, iterator, __mutex_type types of free_list
 class so we can access them o In some cases template keywords must be
 inserted to treat classes as dependent template names o Remove two 'inline'
 keywords where they do not make sense

Submitted by:	Dimitry Andric 
Reviewed by:	trema
---
 contrib/libstdc++/include/ext/bitmap_allocator.h |  2 ++
 contrib/libstdc++/include/ext/ropeimpl.h         | 12 ++++++------
 contrib/libstdc++/src/locale-inst.cc             |  4 ++--
 3 files changed, 10 insertions(+), 8 deletions(-)

diff --git a/contrib/libstdc++/include/ext/bitmap_allocator.h b/contrib/libstdc++/include/ext/bitmap_allocator.h
index 93fa8e63ad5..ef253faead8 100644
--- a/contrib/libstdc++/include/ext/bitmap_allocator.h
+++ b/contrib/libstdc++/include/ext/bitmap_allocator.h
@@ -549,11 +549,13 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
    */
   class free_list
   {
+  public:
     typedef size_t* 				value_type;
     typedef __detail::__mini_vector vector_type;
     typedef vector_type::iterator 		iterator;
     typedef __mutex				__mutex_type;
 
+  private:
     struct _LT_pointer_compare
     {
       bool
diff --git a/contrib/libstdc++/include/ext/ropeimpl.h b/contrib/libstdc++/include/ext/ropeimpl.h
index bbe6b9970bf..28c0b1fd5ca 100644
--- a/contrib/libstdc++/include/ext/ropeimpl.h
+++ b/contrib/libstdc++/include/ext/ropeimpl.h
@@ -382,7 +382,7 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
 	  {
 	    _Rope_RopeLeaf<_CharT, _Alloc>* __l
 	      = (_Rope_RopeLeaf<_CharT, _Alloc>*)this;
-	    __l->_Rope_RopeLeaf<_CharT, _Alloc>::~_Rope_RopeLeaf();
+	    __l->template _Rope_RopeLeaf<_CharT, _Alloc>::~_Rope_RopeLeaf();
 	    _L_deallocate(__l, 1);
 	    break;
 	  }
@@ -390,7 +390,7 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
 	  {
 	    _Rope_RopeConcatenation<_CharT,_Alloc>* __c
 	      = (_Rope_RopeConcatenation<_CharT, _Alloc>*)this;
-	    __c->_Rope_RopeConcatenation<_CharT, _Alloc>::
+	    __c->template _Rope_RopeConcatenation<_CharT, _Alloc>::
 	      ~_Rope_RopeConcatenation();
 	    _C_deallocate(__c, 1);
 	    break;
@@ -399,7 +399,7 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
 	  {
 	    _Rope_RopeFunction<_CharT, _Alloc>* __f
 	      = (_Rope_RopeFunction<_CharT, _Alloc>*)this;
-	    __f->_Rope_RopeFunction<_CharT, _Alloc>::~_Rope_RopeFunction();
+	    __f->template _Rope_RopeFunction<_CharT, _Alloc>::~_Rope_RopeFunction();
 	    _F_deallocate(__f, 1);
 	    break;
 	  }
@@ -407,7 +407,7 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
 	  {
 	    _Rope_RopeSubstring<_CharT, _Alloc>* __ss =
 	      (_Rope_RopeSubstring<_CharT, _Alloc>*)this;
-	    __ss->_Rope_RopeSubstring<_CharT, _Alloc>::
+	    __ss->template _Rope_RopeSubstring<_CharT, _Alloc>::
 	      ~_Rope_RopeSubstring();
 	    _S_deallocate(__ss, 1);
 	    break;
@@ -433,7 +433,7 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
     {
       size_t __old_len = __r->_M_size;
       _CharT* __new_data = (_CharT*)
-	_Data_allocate(_S_rounded_up_size(__old_len + __len));
+	_Rope_rep_base<_CharT, _Alloc>::_Data_allocate(_S_rounded_up_size(__old_len + __len));
       _RopeLeaf* __result;
 
       uninitialized_copy_n(__r->_M_data, __old_len, __new_data);
@@ -817,7 +817,7 @@ _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
 	    if (__result_len > __lazy_threshold)
 	      goto lazy;
 	    __section = (_CharT*)
-	      _Data_allocate(_S_rounded_up_size(__result_len));
+	      _Rope_rep_base<_CharT, _Alloc>::_Data_allocate(_S_rounded_up_size(__result_len));
 	    try
 	      {	(*(__f->_M_fn))(__start, __result_len, __section); }
 	    catch(...)
diff --git a/contrib/libstdc++/src/locale-inst.cc b/contrib/libstdc++/src/locale-inst.cc
index 790e6146943..c6ab9a46b5a 100644
--- a/contrib/libstdc++/src/locale-inst.cc
+++ b/contrib/libstdc++/src/locale-inst.cc
@@ -180,11 +180,11 @@ _GLIBCXX_END_LDBL_NAMESPACE
   template class messages_byname;
   
   // ctype
-  inline template class __ctype_abstract_base;
+  template class __ctype_abstract_base;
   template class ctype_byname;
   
   // codecvt
-  inline template class __codecvt_abstract_base;
+  template class __codecvt_abstract_base;
   template class codecvt_byname;
 
   // collate

From 733cb5ec9035becde9cd877d865d13961bb8ac88 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Tue, 24 Aug 2010 16:08:01 +0000
Subject: [PATCH 0208/1624] Enable timer interrupt before starting timer. This
 allows to handle very short periods without interrupt loss.

---
 sys/x86/x86/local_apic.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)

diff --git a/sys/x86/x86/local_apic.c b/sys/x86/x86/local_apic.c
index 7d19ec110c4..a05abe4c4a5 100644
--- a/sys/x86/x86/local_apic.c
+++ b/sys/x86/x86/local_apic.c
@@ -369,12 +369,13 @@ lapic_setup(int boot)
 	if (la->la_timer_mode != 0) {
 		KASSERT(la->la_timer_period != 0, ("lapic%u: zero divisor",
 		    lapic_id()));
+		lapic_timer_stop();
 		lapic_timer_set_divisor(lapic_timer_divisor);
+		lapic_timer_enable_intr();
 		if (la->la_timer_mode == 1)
 			lapic_timer_periodic(la->la_timer_period);
 		else
 			lapic_timer_oneshot(la->la_timer_period);
-		lapic_timer_enable_intr();
 	}
 
 	/* Program error LVT and clear any existing errors. */
@@ -505,12 +506,10 @@ lapic_et_start(struct eventtimer *et,
 		et->et_max_period.frac =
 		    ((0xfffffffeLLU << 32) / et->et_frequency) << 32;
 	}
-	la = &lapics[lapic_id()];
-	/*
-	 * Start up the timer on the BSP.  The APs will kick off their
-	 * timer during lapic_setup().
-	 */
+	lapic_timer_stop();
 	lapic_timer_set_divisor(lapic_timer_divisor);
+	lapic_timer_enable_intr();
+	la = &lapics[lapic_id()];
 	if (period != NULL) {
 		la->la_timer_mode = 1;
 		la->la_timer_period =
@@ -526,7 +525,6 @@ lapic_et_start(struct eventtimer *et,
 			la->la_timer_period += et->et_frequency * first->sec;
 		lapic_timer_oneshot(la->la_timer_period);
 	}
-	lapic_timer_enable_intr();
 	return (0);
 }
 
@@ -862,8 +860,9 @@ lapic_timer_stop(void)
 
 	value = lapic->lvt_timer;
 	value &= ~APIC_LVTT_TM;
-	value &= ~APIC_LVT_M;
+	value |= APIC_LVT_M;
 	lapic->lvt_timer = value;
+	lapic->icr_timer = 0;
 }
 
 static void

From dda89c73032549682af56aba2103a3896079bc27 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Tue, 24 Aug 2010 16:29:09 +0000
Subject: [PATCH 0209/1624] The order was correct before.  I'd talked to Nathan
 about this before, so this must have been mismerged into tbemd before I
 merged it back to head.  This unbreaks this on powerpc64

Submitted by:	nathanw@
---
 Makefile.inc1 | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index 36c1a34ba2d..53b43a91e85 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -1131,12 +1131,10 @@ _prereq_libs= gnu/lib/libssp/libssp_nonshared gnu/lib/libgcc
 # all shared libraries for ELF.
 #
 _startup_libs=	gnu/lib/csu
-.if exists(${.CURDIR}/lib/csu/${MACHINE_CPUARCH}-elf)
-_startup_libs+=	lib/csu/${MACHINE_CPUARCH}-elf
+.if exists(${.CURDIR}/lib/csu/${MACHINE_ARCH}-elf)
+_startup_libs+=	lib/csu/${MACHINE_ARCH}-elf
 .elif exists(${.CURDIR}/lib/csu/${MACHINE_CPUARCH}-elf)
 _startup_libs+=	lib/csu/${MACHINE_CPUARCH}-elf
-.elif exists(${.CURDIR}/lib/csu/${MACHINE_ARCH})
-_startup_libs+=	lib/csu/${MACHINE_ARCH}
 .else
 _startup_libs+=	lib/csu/${MACHINE_CPUARCH}
 .endif

From 2bef81cf3a594d8aabb5471bea46b861952059ae Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Tue, 24 Aug 2010 16:35:26 +0000
Subject: [PATCH 0210/1624] Change the logic here to match Makefile.inc1. 
 Having it in two places suggests an opportunity for refactoring :)

Submitted by:	nathanw@
---
 lib/Makefile | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/Makefile b/lib/Makefile
index 6f158a4596b..53248e31659 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -112,7 +112,9 @@ SUBDIR=	${SUBDIR_ORDERED} \
 	${_bind} \
 	${_clang}
 
-.if exists(${.CURDIR}/csu/${MACHINE_CPUARCH}-elf)
+.if exists(${.CURDIR}/csu/${MACHINE_ARCH}-elf)
+_csu=csu/${MACHINE_ARCH}-elf
+.elif exists(${.CURDIR}/csu/${MACHINE_CPUARCH}-elf)
 _csu=csu/${MACHINE_CPUARCH}-elf
 .elif exists(${.CURDIR}/csu/${MACHINE_CPUARCH}/Makefile)
 _csu=csu/${MACHINE_CPUARCH}

From 694a0a8717101341c8de0cc270ac8b9c2188fa9b Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Tue, 24 Aug 2010 17:48:22 +0000
Subject: [PATCH 0211/1624] zfs arc_reclaim_thread: no need to call
 arc_reclaim_needed when resetting needfree

needfree is checked at the very start of arc_reclaim_needed.
This change makes code easier to follow and maintain in face of
potential changed in arc_reclaim_needed.

Also, put the whole sub-block under _KERNEL because needfree can be set
only in kernel code.

To do: rename needfree to something else to aovid confusion with
OpenSolaris global variable of the same name which is used in the same
code, but has different meaning (page deficit).

Note: I have an impression that locking around accesses to this variable
as well as mutual notifications between arc_reclaim_thread and
arc_lowmem are not proper.

MFC after:	1 week
---
 sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c
index 1666e41525b..32c079a9be5 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c
@@ -2317,12 +2317,12 @@ arc_reclaim_thread(void *dummy __unused)
 		if (arc_eviction_list != NULL)
 			arc_do_user_evicts();
 
-		if (arc_reclaim_needed()) {
-			needfree = 0;
 #ifdef _KERNEL
+		if (needfree) {
+			needfree = 0;
 			wakeup(&needfree);
-#endif
 		}
+#endif
 
 		/* block until needed, or one second, whichever is shorter */
 		CALLB_CPR_SAFE_BEGIN(&cpr);

From 9c1af42179e80093c8155e4395092903fb1a6a05 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Tue, 24 Aug 2010 18:07:59 +0000
Subject: [PATCH 0212/1624] When ACPI reports current battery consumption rate
 in mAmps, print it also in mWatts. Values in mAmps are not always suitable,
 because they depend on battery voltage, which depends on battery type and
 charge level.

---
 usr.sbin/acpi/acpiconf/acpiconf.c | 37 ++++++++++++++++++-------------
 1 file changed, 21 insertions(+), 16 deletions(-)

diff --git a/usr.sbin/acpi/acpiconf/acpiconf.c b/usr.sbin/acpi/acpiconf/acpiconf.c
index 87f1c76feba..5ca2f98bdf3 100644
--- a/usr.sbin/acpi/acpiconf/acpiconf.c
+++ b/usr.sbin/acpi/acpiconf/acpiconf.c
@@ -86,7 +86,8 @@ acpi_battinfo(int num)
 {
 	union acpi_battery_ioctl_arg battio;
 	const char *pwr_units;
-	int hours, min;
+	int hours, min, amp;
+	uint32_t volt;
 
 	if (num < 0 || num > 64)
 		err(EX_USAGE, "invalid battery %d", num);
@@ -95,11 +96,8 @@ acpi_battinfo(int num)
 	battio.unit = num;
 	if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1)
 		err(EX_IOERR, "get battery info (%d) failed", num);
-	if (battio.bif.units == 0)
-		pwr_units = "mW";
-	else
-		pwr_units = "mA";
-
+	amp = battio.bif.units;
+	pwr_units = amp ? "mA" : "mW";
 	if (battio.bif.dcap == UNKNOWN_CAP)
 		printf("Design capacity:\tunknown\n");
 	else
@@ -125,6 +123,14 @@ acpi_battinfo(int num)
 	printf("Type:\t\t\t%s\n", battio.bif.type);
 	printf("OEM info:\t\t%s\n", battio.bif.oeminfo);
 
+	/* Fetch battery voltage information. */
+	volt = UNKNOWN_VOLTAGE;
+	battio.unit = num;
+	if (ioctl(acpifd, ACPIIO_BATT_GET_BST, &battio) == -1)
+		err(EX_IOERR, "get battery status (%d) failed", num);
+	if (battio.bst.state != ACPI_BATT_STAT_NOT_PRESENT)
+		volt = battio.bst.volt;
+
 	/* Print current battery state information. */
 	battio.unit = num;
 	if (ioctl(acpifd, ACPIIO_BATT_GET_BATTINFO, &battio) == -1)
@@ -154,22 +160,21 @@ acpi_battinfo(int num)
 		}
 		if (battio.battinfo.rate == -1)
 			printf("Present rate:\t\tunknown\n");
-		else
+		else if (amp && volt != UNKNOWN_VOLTAGE) {
+			printf("Present rate:\t\t%d mA (%d mW)\n",
+			    battio.battinfo.rate,
+			    battio.battinfo.rate * volt / 1000);
+		} else
 			printf("Present rate:\t\t%d %s\n",
 			    battio.battinfo.rate, pwr_units);
 	} else
 		printf("State:\t\t\tnot present\n");
 
 	/* Print battery voltage information. */
-	battio.unit = num;
-	if (ioctl(acpifd, ACPIIO_BATT_GET_BST, &battio) == -1)
-		err(EX_IOERR, "get battery status (%d) failed", num);
-	if (battio.bst.state != ACPI_BATT_STAT_NOT_PRESENT) {
-		if (battio.bst.volt == UNKNOWN_VOLTAGE)
-			printf("Voltage:\t\tunknown\n");
-		else
-			printf("Voltage:\t\t%d mV\n", battio.bst.volt);
-	}
+	if (volt == UNKNOWN_VOLTAGE)
+		printf("Present voltage:\tunknown\n");
+	else
+		printf("Present voltage:\t%d mV\n", volt);
 
 	return (0);
 }

From 7c45b436513c95aed381f020853dc93351ee2f7b Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 24 Aug 2010 18:17:40 +0000
Subject: [PATCH 0213/1624] Add PNP id for Compex RL2000. I'm not sure whether
 adding this logical id is correct or not because Compex RL2000 is in the list
 of supported hardware list. I guess the Compex RL2000 could be PCI variant
 while the controller in question is ISA controller. It seems PNP compat id
 didn't match or it had multiple compat ids so isa_pnp_probe() seemed to
 return ENOENT.

PR:	kern/80853
---
 sys/dev/ed/if_ed_isa.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/dev/ed/if_ed_isa.c b/sys/dev/ed/if_ed_isa.c
index 0d7a583c020..afaa37758a3 100644
--- a/sys/dev/ed/if_ed_isa.c
+++ b/sys/dev/ed/if_ed_isa.c
@@ -58,6 +58,7 @@ static struct isa_pnp_id ed_ids[] = {
 	{ 0x0131d805,	NULL },		/* ANX3101 */
 	{ 0x4cf48906,	NULL },		/* ATIf44c */
 	{ 0x01200507,	NULL },		/* AXE2001 */
+	{ 0x0115180e,	NULL },		/* CPX1501 */
 	{ 0x0090252a,	NULL },		/* JQE9000 */
 	{ 0x0020832e,	NULL },		/* KTC2000 */
 	{ 0xd680d041,	NULL },		/* PNP80d6 */

From 9fb40e0a9bd92a4172e795ce8fc5e0f92c059c62 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 24 Aug 2010 18:40:11 +0000
Subject: [PATCH 0214/1624] Remove unnecessary controller reinitialization. CAM
 filter handling was rewritten long time ago so it should not require
 controller reinitialization.

PR:	kern/87506
---
 sys/dev/vr/if_vr.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/sys/dev/vr/if_vr.c b/sys/dev/vr/if_vr.c
index 954024d7f92..21a74a5dd83 100644
--- a/sys/dev/vr/if_vr.c
+++ b/sys/dev/vr/if_vr.c
@@ -1560,6 +1560,7 @@ vr_tick(void *xsc)
 		sc->vr_stat.num_restart++;
 		vr_stop(sc);
 		vr_reset(sc);
+		sc->vr_ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		vr_init_locked(sc);
 		sc->vr_flags &= ~VR_F_RESTART;
 	}
@@ -2016,6 +2017,9 @@ vr_init_locked(struct vr_softc *sc)
 	ifp = sc->vr_ifp;
 	mii = device_get_softc(sc->vr_miibus);
 
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+		return;
+
 	/* Cancel pending I/O and free all RX/TX buffers. */
 	vr_stop(sc);
 	vr_reset(sc);
@@ -2287,6 +2291,7 @@ vr_watchdog(struct vr_softc *sc)
 			if_printf(sc->vr_ifp, "watchdog timeout "
 			   "(missed link)\n");
 		ifp->if_oerrors++;
+		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		vr_init_locked(sc);
 		return;
 	}
@@ -2296,6 +2301,7 @@ vr_watchdog(struct vr_softc *sc)
 
 	vr_stop(sc);
 	vr_reset(sc);
+	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	vr_init_locked(sc);
 
 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))

From 6a085e6341ce91255775fb4d142a0ef4baf10ca0 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 24 Aug 2010 18:44:12 +0000
Subject: [PATCH 0215/1624] vr_init_locked() will stop and reset the
 controller. Remove unnecessary vr_stop()/vr_reset() calls.

---
 sys/dev/vr/if_vr.c | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/sys/dev/vr/if_vr.c b/sys/dev/vr/if_vr.c
index 21a74a5dd83..e9359aa0964 100644
--- a/sys/dev/vr/if_vr.c
+++ b/sys/dev/vr/if_vr.c
@@ -1558,8 +1558,6 @@ vr_tick(void *xsc)
 	if ((sc->vr_flags & VR_F_RESTART) != 0) {
 		device_printf(sc->vr_dev, "restarting\n");
 		sc->vr_stat.num_restart++;
-		vr_stop(sc);
-		vr_reset(sc);
 		sc->vr_ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		vr_init_locked(sc);
 		sc->vr_flags &= ~VR_F_RESTART;
@@ -2299,8 +2297,6 @@ vr_watchdog(struct vr_softc *sc)
 	ifp->if_oerrors++;
 	if_printf(ifp, "watchdog timeout\n");
 
-	vr_stop(sc);
-	vr_reset(sc);
 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	vr_init_locked(sc);
 

From 2bd45735ea137dfa14cf32ae2aa21639507420be Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 24 Aug 2010 18:52:24 +0000
Subject: [PATCH 0216/1624] Remove unnecessary controller reinitialization.

PR:	kern/87506
---
 sys/pci/if_rl.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/sys/pci/if_rl.c b/sys/pci/if_rl.c
index 110e7058d17..33285bff139 100644
--- a/sys/pci/if_rl.c
+++ b/sys/pci/if_rl.c
@@ -1302,6 +1302,7 @@ rl_rxeof(struct rl_softc *sc)
 		    total_len < ETHER_MIN_LEN ||
 		    total_len > ETHER_MAX_LEN + ETHER_VLAN_ENCAP_LEN) {
 			ifp->if_ierrors++;
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			rl_init_locked(sc);
 			return (rx_npkts);
 		}
@@ -1413,6 +1414,7 @@ rl_txeof(struct rl_softc *sc)
 				CSR_WRITE_4(sc, RL_TXCFG, RL_TXCFG_CONFIG);
 			oldthresh = sc->rl_txthresh;
 			/* error recovery */
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			rl_init_locked(sc);
 			/* restore original threshold */
 			sc->rl_txthresh = oldthresh;
@@ -1606,8 +1608,10 @@ rl_poll_locked(struct ifnet *ifp, enum poll_cmd cmd, int count)
 
 		/* XXX We should check behaviour on receiver stalls. */
 
-		if (status & RL_ISR_SYSTEM_ERR)
+		if (status & RL_ISR_SYSTEM_ERR) {
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			rl_init_locked(sc);
+		}
 	}
 	return (rx_npkts);
 }
@@ -1645,8 +1649,10 @@ rl_intr(void *arg)
 			rl_rxeof(sc);
 		if ((status & RL_ISR_TX_OK) || (status & RL_ISR_TX_ERR))
 			rl_txeof(sc);
-		if (status & RL_ISR_SYSTEM_ERR)
+		if (status & RL_ISR_SYSTEM_ERR) {
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			rl_init_locked(sc);
+		}
 	}
 
 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
@@ -1808,6 +1814,9 @@ rl_init_locked(struct rl_softc *sc)
 
 	mii = device_get_softc(sc->rl_miibus);
 
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+		return;
+
 	/*
 	 * Cancel pending I/O and free all RX/TX buffers.
 	 */
@@ -2036,6 +2045,7 @@ rl_watchdog(struct rl_softc *sc)
 
 	rl_txeof(sc);
 	rl_rxeof(sc);
+	sc->rl_ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	rl_init_locked(sc);
 }
 

From 3ca447da3d751efb0f5427f28c3b52a9b806b912 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 24 Aug 2010 19:41:15 +0000
Subject: [PATCH 0217/1624] Remove unnecessary controller reinitialization.

PR:	kern/87506
---
 sys/dev/age/if_age.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/sys/dev/age/if_age.c b/sys/dev/age/if_age.c
index 15ce0eff851..99c3c431a51 100644
--- a/sys/dev/age/if_age.c
+++ b/sys/dev/age/if_age.c
@@ -1781,6 +1781,7 @@ age_watchdog(struct age_softc *sc)
 	if ((sc->age_flags & AGE_FLAG_LINK) == 0) {
 		if_printf(sc->age_ifp, "watchdog timeout (missed link)\n");
 		ifp->if_oerrors++;
+		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 		age_init_locked(sc);
 		return;
 	}
@@ -1793,6 +1794,7 @@ age_watchdog(struct age_softc *sc)
 	}
 	if_printf(sc->age_ifp, "watchdog timeout\n");
 	ifp->if_oerrors++;
+	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	age_init_locked(sc);
 	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
 		taskqueue_enqueue(sc->age_tq, &sc->age_tx_task);
@@ -1817,8 +1819,10 @@ age_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
 		else if (ifp->if_mtu != ifr->ifr_mtu) {
 			AGE_LOCK(sc);
 			ifp->if_mtu = ifr->ifr_mtu;
-			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
+				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 				age_init_locked(sc);
+			}
 			AGE_UNLOCK(sc);
 		}
 		break;
@@ -2165,6 +2169,7 @@ age_int_task(void *arg, int pending)
 			if ((status & INTR_DMA_WR_TO_RST) != 0)
 				device_printf(sc->age_dev,
 				    "DMA write error! -- resetting\n");
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			age_init_locked(sc);
 		}
 		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
@@ -2529,6 +2534,9 @@ age_init_locked(struct age_softc *sc)
 	ifp = sc->age_ifp;
 	mii = device_get_softc(sc->age_miibus);
 
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+		return;
+
 	/*
 	 * Cancel any pending I/O.
 	 */

From f4fbf9c859df8c382aea624c930eb96557fcb15d Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Tue, 24 Aug 2010 20:50:08 +0000
Subject: [PATCH 0218/1624] Unify 32-bit and 64-bit PowerPC libthr support.
 This reduces code duplication, and simplifies the TBEMD import.

Requested by:	imp
---
 lib/libthr/Makefile                           |  4 +-
 lib/libthr/arch/powerpc/Makefile.inc          |  2 +-
 lib/libthr/arch/powerpc/include/pthread_md.h  | 14 +++-
 lib/libthr/arch/powerpc64/Makefile.inc        |  5 --
 .../arch/powerpc64/include/pthread_md.h       | 84 -------------------
 .../arch/powerpc64/powerpc64/pthread_md.c     | 54 ------------
 6 files changed, 16 insertions(+), 147 deletions(-)
 delete mode 100644 lib/libthr/arch/powerpc64/Makefile.inc
 delete mode 100644 lib/libthr/arch/powerpc64/include/pthread_md.h
 delete mode 100644 lib/libthr/arch/powerpc64/powerpc64/pthread_md.c

diff --git a/lib/libthr/Makefile b/lib/libthr/Makefile
index ee981d8eeb9..6a10ce3ce80 100644
--- a/lib/libthr/Makefile
+++ b/lib/libthr/Makefile
@@ -19,7 +19,7 @@ WARNS?=	3
 CFLAGS+=-DPTHREAD_KERNEL
 CFLAGS+=-I${.CURDIR}/../libc/include -I${.CURDIR}/thread \
 	-I${.CURDIR}/../../include
-CFLAGS+=-I${.CURDIR}/arch/${MACHINE_ARCH}/include
+CFLAGS+=-I${.CURDIR}/arch/${MACHINE_CPUARCH}/include
 CFLAGS+=-I${.CURDIR}/sys
 CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf
 CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf/${MACHINE_ARCH}
@@ -38,7 +38,7 @@ CFLAGS+=-D_PTHREADS_INVARIANTS
 
 PRECIOUSLIB=
 
-.include "${.CURDIR}/arch/${MACHINE_ARCH}/Makefile.inc"
+.include "${.CURDIR}/arch/${MACHINE_CPUARCH}/Makefile.inc"
 .include "${.CURDIR}/sys/Makefile.inc"
 .include "${.CURDIR}/thread/Makefile.inc"
 
diff --git a/lib/libthr/arch/powerpc/Makefile.inc b/lib/libthr/arch/powerpc/Makefile.inc
index b6a4acd6f60..e4dffef84cf 100644
--- a/lib/libthr/arch/powerpc/Makefile.inc
+++ b/lib/libthr/arch/powerpc/Makefile.inc
@@ -1,5 +1,5 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
+.PATH: ${.CURDIR}/arch/${MACHINE_CPUARCH}/${MACHINE_CPUARCH}
 
 SRCS+=	pthread_md.c
diff --git a/lib/libthr/arch/powerpc/include/pthread_md.h b/lib/libthr/arch/powerpc/include/pthread_md.h
index 2abbbdc1fce..91102b4c13a 100644
--- a/lib/libthr/arch/powerpc/include/pthread_md.h
+++ b/lib/libthr/arch/powerpc/include/pthread_md.h
@@ -39,12 +39,16 @@
 #define	CPU_SPINWAIT
 
 #define	DTV_OFFSET		offsetof(struct tcb, tcb_dtv)
+#ifdef __powerpc64__
+#define	TP_OFFSET		0x7010
+#else
 #define	TP_OFFSET		0x7008
+#endif
 
 /*
  * Variant I tcb. The structure layout is fixed, don't blindly
  * change it.
- * %r2 points to end of the structure.
+ * %r2 (32-bit) or %r13 (64-bit) points to end of the structure.
  */
 struct tcb {
 	void			*tcb_dtv;
@@ -57,7 +61,11 @@ void		_tcb_dtor(struct tcb *);
 static __inline void
 _tcb_set(struct tcb *tcb)
 {
+#ifdef __powerpc64__
+	register uint8_t *_tp __asm__("%r13");
+#else
 	register uint8_t *_tp __asm__("%r2");
+#endif
 
 	__asm __volatile("mr %0,%1" : "=r"(_tp) :
 	    "r"((uint8_t *)tcb + TP_OFFSET));
@@ -66,7 +74,11 @@ _tcb_set(struct tcb *tcb)
 static __inline struct tcb *
 _tcb_get(void)
 {
+#ifdef __powerpc64__
+	register uint8_t *_tp __asm__("%r13");
+#else
 	register uint8_t *_tp __asm__("%r2");
+#endif
 
 	return ((struct tcb *)(_tp - TP_OFFSET));
 }
diff --git a/lib/libthr/arch/powerpc64/Makefile.inc b/lib/libthr/arch/powerpc64/Makefile.inc
deleted file mode 100644
index b6a4acd6f60..00000000000
--- a/lib/libthr/arch/powerpc64/Makefile.inc
+++ /dev/null
@@ -1,5 +0,0 @@
-# $FreeBSD$
-
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
-SRCS+=	pthread_md.c
diff --git a/lib/libthr/arch/powerpc64/include/pthread_md.h b/lib/libthr/arch/powerpc64/include/pthread_md.h
deleted file mode 100644
index af6a0afaab5..00000000000
--- a/lib/libthr/arch/powerpc64/include/pthread_md.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2004 by Peter Grehan. 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. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
- *
- * $FreeBSD$
- */
-
-/*
- * Machine-dependent thread prototypes/definitions.
- */
-#ifndef _PTHREAD_MD_H_
-#define	_PTHREAD_MD_H_
-
-#include 
-#include 
-
-#define	CPU_SPINWAIT
-
-#define	DTV_OFFSET		offsetof(struct tcb, tcb_dtv)
-#define	TP_OFFSET		0x7010
-
-/*
- * Variant I tcb. The structure layout is fixed, don't blindly
- * change it.
- * %r13 points to end of the structure.
- */
-struct tcb {
-	void			*tcb_dtv;
-	struct pthread		*tcb_thread;
-};
-
-struct tcb	*_tcb_ctor(struct pthread *, int);
-void		_tcb_dtor(struct tcb *);
-
-static __inline void
-_tcb_set(struct tcb *tcb)
-{
-	register uint8_t *_tp __asm__("%r13");
-
-	__asm __volatile("mr %0,%1" : "=r"(_tp) :
-	    "r"((uint8_t *)tcb + TP_OFFSET));
-}
-
-static __inline struct tcb *
-_tcb_get(void)
-{
-	register uint8_t *_tp __asm__("%r13");
-
-	return ((struct tcb *)(_tp - TP_OFFSET));
-}
-
-extern struct pthread *_thr_initial;
-
-static __inline struct pthread *
-_get_curthread(void)
-{
-	if (_thr_initial)
-		return (_tcb_get()->tcb_thread);
-	return (NULL);
-}
-
-#endif /* _PTHREAD_MD_H_ */
diff --git a/lib/libthr/arch/powerpc64/powerpc64/pthread_md.c b/lib/libthr/arch/powerpc64/powerpc64/pthread_md.c
deleted file mode 100644
index 66f043e294a..00000000000
--- a/lib/libthr/arch/powerpc64/powerpc64/pthread_md.c
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2003 Daniel Eischen 
- * 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. Neither the name of the author 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 AUTHOR ``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 AUTHOR 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.
- *
- * $FreeBSD$
- */
-
-#include 
-#include 
-
-#include "pthread_md.h"
-
-/*
- * The constructors.
- */
-struct tcb *
-_tcb_ctor(struct pthread *thread, int initial)
-{
-	struct tcb *tcb;
-
-	tcb = _rtld_allocate_tls((initial) ? _tcb_get() :  NULL,
-	    sizeof(struct tcb), 1);
-	if (tcb)
-		tcb->tcb_thread = thread;
-	return (tcb);
-
-}
-
-void
-_tcb_dtor(struct tcb *tcb)
-{
-	_rtld_free_tls(tcb, sizeof(struct tcb), 1);
-}

From 2c0959ae6be382e3d2eea4999f537294b9eb3da9 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Tue, 24 Aug 2010 20:54:43 +0000
Subject: [PATCH 0219/1624] Powerpc is special here.  powerpc and powerpc64 use
 different ABIs, so their implementations aren't in the same files.  Introduce
 LIBC_ARCH and use that in preference to MACHINE_CPUARCH.  Tested by amd64 and
 powerpc64 builds (thanks nathanw@)

---
 lib/libc/Makefile               | 33 +++++++++++++++++++++------------
 lib/libc/compat-43/Makefile.inc |  2 +-
 lib/libc/gen/Makefile.inc       |  6 ++----
 lib/libc/locale/Makefile.inc    |  2 +-
 lib/libc/quad/Makefile.inc      |  4 ++--
 lib/libc/softfloat/Makefile.inc |  4 ++--
 lib/libc/stdlib/Makefile.inc    |  4 ++--
 lib/libc/string/Makefile.inc    |  6 ++----
 lib/libc/sys/Makefile.inc       |  6 ++----
 9 files changed, 35 insertions(+), 32 deletions(-)

diff --git a/lib/libc/Makefile b/lib/libc/Makefile
index 8aed00f8ad7..a6071600eca 100644
--- a/lib/libc/Makefile
+++ b/lib/libc/Makefile
@@ -5,6 +5,15 @@ SHLIBDIR?= /lib
 
 .include 
 
+# We have to special case powerpc and powerpc64, since they mostly have
+# the same source implementation.  libc is very different due to large
+# ABI differences.
+.if ${LIBC_ARCH} == "powerpc"
+LIBC_ARCH=${MACHINE_ARCH}
+.else
+LIBC_ARCH=${LIBC_ARCH}
+.endif
+
 # All library objects contain FreeBSD revision strings by default; they may be
 # excluded as a space-saving measure.  To produce a library that does
 # not contain these strings, add -DSTRIP_FBSDID (see ) to CFLAGS
@@ -15,7 +24,7 @@ LIB=c
 SHLIB_MAJOR= 7
 WARNS?=	2
 CFLAGS+=-I${.CURDIR}/include -I${.CURDIR}/../../include
-CFLAGS+=-I${.CURDIR}/${MACHINE_CPUARCH}
+CFLAGS+=-I${.CURDIR}/${LIBC_ARCH}
 CFLAGS+=-DNLS
 CLEANFILES+=tags
 INSTALL_PIC_ARCHIVE=
@@ -36,7 +45,7 @@ MDASM=
 MIASM=
 NOASM=
 
-.include "${.CURDIR}/${MACHINE_CPUARCH}/Makefile.inc"
+.include "${.CURDIR}/${LIBC_ARCH}/Makefile.inc"
 .include "${.CURDIR}/db/Makefile.inc"
 .include "${.CURDIR}/compat-43/Makefile.inc"
 .include "${.CURDIR}/gdtoa/Makefile.inc"
@@ -49,14 +58,14 @@ NOASM=
 .include "${.CURDIR}/net/Makefile.inc"
 .include "${.CURDIR}/nls/Makefile.inc"
 .include "${.CURDIR}/posix1e/Makefile.inc"
-.if ${MACHINE_CPUARCH} != "amd64" && \
-    ${MACHINE_CPUARCH} != "ia64" && \
-    ${MACHINE_ARCH} != "powerpc64" && \
-    ${MACHINE_CPUARCH} != "sparc64" && \
-    ${MACHINE_CPUARCH} != "mips"
+.if ${LIBC_ARCH} != "amd64" && \
+    ${LIBC_ARCH} != "ia64" && \
+    ${LIBC_ARCH} != "powerpc64" && \
+    ${LIBC_ARCH} != "sparc64" && \
+    ${LIBC_ARCH} != "mips"
 .include "${.CURDIR}/quad/Makefile.inc"
 .endif
-.if ${MACHINE_ARCH} == "mips" && \
+.if ${LIBC_ARCH} == "mips" && \
     (!defined(TARGET_ABI) || ${TARGET_ABI} == "o32")
 .include "${.CURDIR}/quad/Makefile.inc"
 .endif
@@ -70,7 +79,7 @@ NOASM=
 .include "${.CURDIR}/rpc/Makefile.inc"
 .include "${.CURDIR}/uuid/Makefile.inc"
 .include "${.CURDIR}/xdr/Makefile.inc"
-.if ${MACHINE_CPUARCH} == "arm" || ${MACHINE_CPUARCH} == "mips"
+.if ${LIBC_ARCH} == "arm" || ${LIBC_ARCH} == "mips"
 .include "${.CURDIR}/softfloat/Makefile.inc"
 .endif
 .if ${MK_NIS} != "no"
@@ -115,14 +124,14 @@ KQSRCS=	adddi3.c anddi3.c ashldi3.c ashrdi3.c cmpdi2.c divdi3.c iordi3.c \
 KSRCS=	bcmp.c ffs.c ffsl.c fls.c flsl.c index.c mcount.c rindex.c \
 	strcat.c strcmp.c strcpy.c strlen.c strncpy.c
 
-libkern: libkern.gen libkern.${MACHINE_CPUARCH}
+libkern: libkern.gen libkern.${LIBC_ARCH}
 
 libkern.gen: ${KQSRCS} ${KSRCS}
 	cp -p ${.CURDIR}/quad/quad.h ${.ALLSRC} ${DESTDIR}/sys/libkern
 
-libkern.${MACHINE_CPUARCH}:: ${KMSRCS}
+libkern.${LIBC_ARCH}:: ${KMSRCS}
 .if defined(KMSRCS) && !empty(KMSRCS)
-	cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${MACHINE_CPUARCH}
+	cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${LIBC_ARCH}
 .endif
 
 .include 
diff --git a/lib/libc/compat-43/Makefile.inc b/lib/libc/compat-43/Makefile.inc
index e8ec364a2cf..867a9d9e9b4 100644
--- a/lib/libc/compat-43/Makefile.inc
+++ b/lib/libc/compat-43/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # compat-43 sources
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/compat-43 ${.CURDIR}/compat-43
+.PATH: ${.CURDIR}/${LIBC_ARCH}/compat-43 ${.CURDIR}/compat-43
 
 SRCS+=	creat.c gethostid.c getwd.c killpg.c sethostid.c setpgrp.c \
 	setrgid.c setruid.c sigcompat.c
diff --git a/lib/libc/gen/Makefile.inc b/lib/libc/gen/Makefile.inc
index 204541e594f..dd4bb5add8a 100644
--- a/lib/libc/gen/Makefile.inc
+++ b/lib/libc/gen/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # machine-independent gen sources
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/gen ${.CURDIR}/gen
+.PATH: ${.CURDIR}/${LIBC_ARCH}/gen ${.CURDIR}/gen
 
 SRCS+=  __getosreldate.c __xuname.c \
 	_once_stub.c _pthread_stubs.c _rand48.c _spinlock_stub.c \
@@ -38,9 +38,7 @@ SRCS+=  __getosreldate.c __xuname.c \
 SYM_MAPS+=${.CURDIR}/gen/Symbol.map
 
 # machine-dependent gen sources
-.if exists(${.CURDIR}/${MACHINE_CPUARCH}/gen/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_CPUARCH}/gen/Makefile.inc"
-.endif
+.sinclude "${.CURDIR}/${LIBC_ARCH}/gen/Makefile.inc"
 
 MAN+=	alarm.3 arc4random.3 \
 	basename.3 check_utility_compat.3 clock.3 \
diff --git a/lib/libc/locale/Makefile.inc b/lib/libc/locale/Makefile.inc
index 8cf5bebd5d7..8fff0589a8d 100644
--- a/lib/libc/locale/Makefile.inc
+++ b/lib/libc/locale/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # locale sources
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/locale ${.CURDIR}/locale
+.PATH: ${.CURDIR}/${LIBC_ARCH}/locale ${.CURDIR}/locale
 
 SRCS+=	ascii.c big5.c btowc.c collate.c collcmp.c euc.c fix_grouping.c \
 	gb18030.c gb2312.c gbk.c isctype.c iswctype.c \
diff --git a/lib/libc/quad/Makefile.inc b/lib/libc/quad/Makefile.inc
index 84723a73658..016fa34dda4 100644
--- a/lib/libc/quad/Makefile.inc
+++ b/lib/libc/quad/Makefile.inc
@@ -2,9 +2,9 @@
 # $FreeBSD$
 
 # Quad support, if needed
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/quad ${.CURDIR}/quad
+.PATH: ${.CURDIR}/${LIBC_ARCH}/quad ${.CURDIR}/quad
 
-.if ${MACHINE_CPUARCH} == "i386"
+.if ${LIBC_ARCH} == "i386"
 
 SRCS+=	cmpdi2.c divdi3.c moddi3.c qdivrem.c ucmpdi2.c udivdi3.c umoddi3.c
 
diff --git a/lib/libc/softfloat/Makefile.inc b/lib/libc/softfloat/Makefile.inc
index c3df0ae69ec..ac7fbf78127 100644
--- a/lib/libc/softfloat/Makefile.inc
+++ b/lib/libc/softfloat/Makefile.inc
@@ -2,10 +2,10 @@
 # $FreeBSD$
 
 SOFTFLOAT_BITS?=64
-.PATH:		${MACHINE_CPUARCH}/softfloat \
+.PATH:		${LIBC_ARCH}/softfloat \
 		${.CURDIR}/softfloat/bits${SOFTFLOAT_BITS} ${.CURDIR}/softfloat
 
-CFLAGS+=	-I${.CURDIR}/${MACHINE_CPUARCH}/softfloat -I${.CURDIR}/softfloat
+CFLAGS+=	-I${.CURDIR}/${LIBC_ARCH}/softfloat -I${.CURDIR}/softfloat
 CFLAGS+=	-DSOFTFLOAT_FOR_GCC
 
 SRCS+=		softfloat.c
diff --git a/lib/libc/stdlib/Makefile.inc b/lib/libc/stdlib/Makefile.inc
index d26f66a09ae..3627294d0b3 100644
--- a/lib/libc/stdlib/Makefile.inc
+++ b/lib/libc/stdlib/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # machine-independent stdlib sources
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/stdlib ${.CURDIR}/stdlib
+.PATH: ${.CURDIR}/${LIBC_ARCH}/stdlib ${.CURDIR}/stdlib
 
 MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \
 	bsearch.c div.c exit.c getenv.c getopt.c getopt_long.c \
@@ -16,7 +16,7 @@ MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \
 SYM_MAPS+= ${.CURDIR}/stdlib/Symbol.map
 
 # machine-dependent stdlib sources
-.sinclude "${.CURDIR}/${MACHINE_CPUARCH}/stdlib/Makefile.inc"
+.sinclude "${.CURDIR}/${LIBC_ARCH}/stdlib/Makefile.inc"
 
 MAN+=	a64l.3 abort.3 abs.3 alloca.3 atexit.3 atof.3 atoi.3 atol.3 bsearch.3 \
 	div.3 exit.3 getenv.3 getopt.3 getopt_long.3 getsubopt.3 \
diff --git a/lib/libc/string/Makefile.inc b/lib/libc/string/Makefile.inc
index 96759d5bd7d..3673a415c2f 100644
--- a/lib/libc/string/Makefile.inc
+++ b/lib/libc/string/Makefile.inc
@@ -1,7 +1,7 @@
 #	@(#)Makefile.inc	8.1 (Berkeley) 6/4/93
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/string ${.CURDIR}/string
+.PATH: ${.CURDIR}/${LIBC_ARCH}/string ${.CURDIR}/string
 
 CFLAGS+= -I${.CURDIR}/locale
 
@@ -26,9 +26,7 @@ SYM_MAPS+=	${.CURDIR}/string/Symbol.map
 
 
 # machine-dependent string sources
-.if exists(${.CURDIR}/${MACHINE_CPUARCH}/string/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_CPUARCH}/string/Makefile.inc"
-.endif
+.sinclude "${.CURDIR}/${LIBC_ARCH}/string/Makefile.inc"
 
 MAN+=	bcmp.3 bcopy.3 bstring.3 bzero.3 ffs.3 index.3 memccpy.3 memchr.3 \
 	memcmp.3 memcpy.3 memmem.3 memmove.3 memset.3 strcasecmp.3 strcat.3 \
diff --git a/lib/libc/sys/Makefile.inc b/lib/libc/sys/Makefile.inc
index dc56429a267..9876bdec34e 100644
--- a/lib/libc/sys/Makefile.inc
+++ b/lib/libc/sys/Makefile.inc
@@ -2,7 +2,7 @@
 # $FreeBSD$
 
 # sys sources
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}/sys ${.CURDIR}/sys
+.PATH: ${.CURDIR}/${LIBC_ARCH}/sys ${.CURDIR}/sys
 
 # Include the generated makefile containing the *complete* list
 # of syscall names in MIASM.
@@ -13,9 +13,7 @@
 # MDASM names override the default syscall names in MIASM.
 # NOASM will prevent the default syscall code from being generated.
 #
-.if exists(${.CURDIR}/${MACHINE_CPUARCH}/sys/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_CPUARCH}/sys/Makefile.inc"
-.endif
+.sinclude "${.CURDIR}/${LIBC_ARCH}/sys/Makefile.inc"
 
 # Sources common to both syscall interfaces:
 SRCS+=	stack_protector.c stack_protector_compat.c __error.c

From bff351d7fe78791d0182da7343cf33a53db688e8 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Tue, 24 Aug 2010 21:28:34 +0000
Subject: [PATCH 0220/1624] Fix an accidental sed...

---
 lib/libc/Makefile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/libc/Makefile b/lib/libc/Makefile
index a6071600eca..e29c7d99b7c 100644
--- a/lib/libc/Makefile
+++ b/lib/libc/Makefile
@@ -8,10 +8,10 @@ SHLIBDIR?= /lib
 # We have to special case powerpc and powerpc64, since they mostly have
 # the same source implementation.  libc is very different due to large
 # ABI differences.
-.if ${LIBC_ARCH} == "powerpc"
+.if ${MACHINE_ARCH} == "powerpc"
 LIBC_ARCH=${MACHINE_ARCH}
 .else
-LIBC_ARCH=${LIBC_ARCH}
+LIBC_ARCH=${MACHINE_CPUARCH}
 .endif
 
 # All library objects contain FreeBSD revision strings by default; they may be

From 6b85cd6ddccf50a2ccff912e679ea39b552a0057 Mon Sep 17 00:00:00 2001
From: Edward Tomasz Napierala 
Date: Tue, 24 Aug 2010 21:38:44 +0000
Subject: [PATCH 0221/1624] s/ithread/interrupt thread/

---
 share/man/man9/locking.9 | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/share/man/man9/locking.9 b/share/man/man9/locking.9
index 005f4768672..bd8a2335cc4 100644
--- a/share/man/man9/locking.9
+++ b/share/man/man9/locking.9
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd February 15, 2010
+.Dd August 24, 2010
 .Dt LOCKING 9
 .Os
 .Sh NAME
@@ -334,7 +334,7 @@ At this time this is a rather easy to remember table.
 .Em "Context:"  Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmlock Ta sleep
 .Xc
 .It interrupt filter:  Ta \&ok Ta \&no Ta \&no Ta \&no Ta \&no Ta \&no 
-.It ithread:    Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&ok Ta \&no 
+.It interrupt thread:  Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&ok Ta \&no 
 .It callout:    Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&no Ta \&no 
 .It syscall:    Ta \&ok Ta \&ok Ta \&ok Ta \&ok Ta \&ok Ta \&ok 
 .El

From 789e85458b0d26acfae7ca2701b2a2e6173d8cc8 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Tue, 24 Aug 2010 23:19:14 +0000
Subject: [PATCH 0223/1624] Make RTLD work on powerpc64 again. If there is a
 sub-directory named MACHINE_ARCH, use that specific one, otherwise use
 MACHINE_CPUARCH.

Reviewed by:	imp
---
 libexec/rtld-elf/Makefile | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)

diff --git a/libexec/rtld-elf/Makefile b/libexec/rtld-elf/Makefile
index 6cf09bed281..a798f3aeaca 100644
--- a/libexec/rtld-elf/Makefile
+++ b/libexec/rtld-elf/Makefile
@@ -10,7 +10,12 @@ SRCS=		rtld_start.S \
 MAN=		rtld.1
 CSTD?=		gnu99
 CFLAGS+=	-Wall -DFREEBSD_ELF -DIN_RTLD
-CFLAGS+=	-I${.CURDIR}/${MACHINE_CPUARCH} -I${.CURDIR}
+.if exists(${.CURDIR}/${MACHINE_ARCH})
+RTLD_ARCH=	${MACHINE_ARCH}
+.else
+RTLD_ARCH=	${MACHINE_CPUARCH}
+.endif
+CFLAGS+=	-I${.CURDIR}/${RTLD_ARCH} -I${.CURDIR}
 .if ${MACHINE_ARCH} == "powerpc64"
 LDFLAGS+=	-nostdlib -e _rtld_start
 .else
@@ -39,15 +44,13 @@ LDFLAGS+=	-Wl,--version-script=${VERSION_MAP}
 
 ${PROG}:	${VERSION_MAP}
 
-.if exists(${.CURDIR}/${MACHINE_CPUARCH}/Symbol.map)
-SYMBOL_MAPS+=	${.CURDIR}/${MACHINE_CPUARCH}/Symbol.map
+.if exists(${.CURDIR}/${RTLD_ARCH}/Symbol.map)
+SYMBOL_MAPS+=	${.CURDIR}/${RTLD_ARCH}/Symbol.map
 .endif
 .endif
 .endif
 
-.if exists(${.CURDIR}/${MACHINE_CPUARCH}/Makefile.inc)
-.include "${.CURDIR}/${MACHINE_CPUARCH}/Makefile.inc"
-.endif
+.sinclude "${.CURDIR}/${RTLD_ARCH}/Makefile.inc"
 
 # Since moving rtld-elf to /libexec, we need to create a symlink.
 # Fixup the existing binary that's there so we can symlink over it.
@@ -56,7 +59,7 @@ beforeinstall:
 	-chflags noschg ${DESTDIR}/usr/libexec/${PROG}
 .endif
 
-.PATH: ${.CURDIR}/${MACHINE_CPUARCH}
+.PATH: ${.CURDIR}/${RTLD_ARCH}
 
 .include 
 .include 

From 482c9aa14d7085acb2a0e070d39d8246e9926e2c Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Tue, 24 Aug 2010 23:24:43 +0000
Subject: [PATCH 0224/1624] Port dtruss to FreeBSD.

Sponsored by:	The FreeBSD Foundation
---
 cddl/contrib/dtracetoolkit/dtruss | 15 ++++++---------
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/cddl/contrib/dtracetoolkit/dtruss b/cddl/contrib/dtracetoolkit/dtruss
index f4b5e45a30d..93b12d3b80c 100755
--- a/cddl/contrib/dtracetoolkit/dtruss
+++ b/cddl/contrib/dtracetoolkit/dtruss
@@ -1,4 +1,4 @@
-#!/usr/bin/sh
+#!/bin/sh
 #
 # dtruss - print process system call time details.
 #          Written using DTrace (Solaris 10 3/05).
@@ -240,7 +240,7 @@ syscall:::entry
  */
 
 /* print 3 args, return as hex */
-syscall::lwp_sigmask:return
+syscall::sigprocmask:return
 /self->start/
 {
 	/* calculate elapsed time */
@@ -268,10 +268,11 @@ syscall::lwp_sigmask:return
 }
 
 /* print 3 args, arg0 as a string */
+syscall::access*:return,
 syscall::stat*:return, 
 syscall::lstat*:return, 
-syscall::open*:return,
-syscall::resolvepath:return
+syscall::readlink*:return,
+syscall::open*:return
 /self->start/
 {
 	/* calculate elapsed time */
@@ -329,7 +330,6 @@ syscall::*read*:return
 }
 
 /* print 0 arg output */
-syscall::gtime:return,
 syscall::*fork*:return
 /self->start/
 {
@@ -357,9 +357,6 @@ syscall::*fork*:return
 }
 
 /* print 1 arg output */
-syscall::brk:return,
-syscall::times:return,
-syscall::stime:return,
 syscall::close:return
 /self->start/
 {
@@ -387,7 +384,7 @@ syscall::close:return
 }
 
 /* print 2 arg output */
-syscall::utime:return,
+syscall::utimes:return,
 syscall::munmap:return
 /self->start/
 {

From 12731c317d54c37a5a380b825925161f1d435516 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Wed, 25 Aug 2010 00:35:58 +0000
Subject: [PATCH 0225/1624] If the first iteration of the do loop in
 replay_prune() succeeded and a subsequent interation failed to find an entry
 to prune, it could loop infinitely, since the "freed" variable wasn't reset
 to FALSE. This patch moves setting freed FALSE to inside the loop to fix the
 problem.

Tested by:	alan.bryan at yahoo.com
MFC after:	2 weeks
---
 sys/rpc/replay.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/rpc/replay.c b/sys/rpc/replay.c
index d82fc2086ef..c89def576a5 100644
--- a/sys/rpc/replay.c
+++ b/sys/rpc/replay.c
@@ -144,8 +144,8 @@ replay_prune(struct replay_cache *rc)
 	bool_t freed_one;
 
 	if (rc->rc_count >= REPLAY_MAX || rc->rc_size > rc->rc_maxsize) {
-		freed_one = FALSE;
 		do {
+			freed_one = FALSE;
 			/*
 			 * Try to free an entry. Don't free in-progress entries
 			 */

From e94b9f21a80388d2ce2b07db43c713f403922777 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Wed, 25 Aug 2010 02:03:48 +0000
Subject: [PATCH 0226/1624] Prodded by Yongari, add support for Holtek HT80232.
  Add the device ID, plus the ability to force '16-bit mode' which really
 means NE-2000 mode.  Other open source drivers suggest that the Holtek
 misbehaves if you allow the 8-bit probe.  Also, all of the PCI chips emulate
 NE-2000ish cards, so always force 16-bit mode for memory transfers.

PR:		84202 (patch not used)
---
 sys/dev/ed/if_ed_novell.c | 59 +++++++++++++++++++++++----------------
 sys/dev/ed/if_ed_pci.c    | 21 +++++++-------
 2 files changed, 46 insertions(+), 34 deletions(-)

diff --git a/sys/dev/ed/if_ed_novell.c b/sys/dev/ed/if_ed_novell.c
index 90f2068dc8f..b1d4fd8dfe2 100644
--- a/sys/dev/ed/if_ed_novell.c
+++ b/sys/dev/ed/if_ed_novell.c
@@ -123,39 +123,50 @@ ed_probe_Novell_generic(device_t dev, int flags)
 	ed_nic_outb(sc, ED_P0_PSTART, 8192 / ED_PAGE_SIZE);
 	ed_nic_outb(sc, ED_P0_PSTOP, 16384 / ED_PAGE_SIZE);
 
-	sc->isa16bit = 0;
-
 	/*
-	 * Write a test pattern in byte mode. If this fails, then there
-	 * probably isn't any memory at 8k - which likely means that the board
-	 * is an NE2000.
+	 * Some devices identify themselves.  Some of those devices
+	 * can't handle being probed, so we allow forcing a mode.  If
+	 * these flags are set, force it, otherwise probe.
 	 */
-	ed_pio_writemem(sc, test_pattern, 8192, sizeof(test_pattern));
-	ed_pio_readmem(sc, 8192, test_buffer, sizeof(test_pattern));
-
-	if (bcmp(test_pattern, test_buffer, sizeof(test_pattern)) == 0) {
+	if (flags & ED_FLAGS_FORCE_8BIT_MODE) {
+		sc->isa16bit = 0;
 		sc->type = ED_TYPE_NE1000;
 		sc->type_str = "NE1000";
-	} else {
-
-		/* Not an NE1000 - try NE2000 */
-		ed_nic_outb(sc, ED_P0_DCR, ED_DCR_WTS | ED_DCR_FT1 | ED_DCR_LS);
-		ed_nic_outb(sc, ED_P0_PSTART, 16384 / ED_PAGE_SIZE);
-		ed_nic_outb(sc, ED_P0_PSTOP, 32768 / ED_PAGE_SIZE);
-
+	} else if (flags & ED_FLAGS_FORCE_16BIT_MODE) {
 		sc->isa16bit = 1;
-
+		sc->type = ED_TYPE_NE2000;
+		sc->type_str = "NE2000";
+	} else {
 		/*
-		 * Write a test pattern in word mode. If this also fails, then
-		 * we don't know what this board is.
+		 * Write a test pattern in byte mode. If this fails, then there
+		 * probably isn't any memory at 8k - which likely means that the board
+		 * is an NE2000.
 		 */
-		ed_pio_writemem(sc, test_pattern, 16384, sizeof(test_pattern));
-		ed_pio_readmem(sc, 16384, test_buffer, sizeof(test_pattern));
+		ed_pio_writemem(sc, test_pattern, 8192, sizeof(test_pattern));
+		ed_pio_readmem(sc, 8192, test_buffer, sizeof(test_pattern));
+
 		if (bcmp(test_pattern, test_buffer, sizeof(test_pattern)) == 0) {
-			sc->type = ED_TYPE_NE2000;
-			sc->type_str = "NE2000";
+			sc->type = ED_TYPE_NE1000;
+			sc->type_str = "NE1000";
+			sc->isa16bit = 0;
 		} else {
-			return (ENXIO);
+			/* Not an NE1000 - try NE2000 */
+			sc->isa16bit = 1;
+			ed_nic_outb(sc, ED_P0_DCR, ED_DCR_WTS | ED_DCR_FT1 | ED_DCR_LS);
+			ed_nic_outb(sc, ED_P0_PSTART, 16384 / ED_PAGE_SIZE);
+			ed_nic_outb(sc, ED_P0_PSTOP, 32768 / ED_PAGE_SIZE);
+			/*
+			 * Write a test pattern in word mode. If this also fails, then
+			 * we don't know what this board is.
+			 */
+			ed_pio_writemem(sc, test_pattern, 16384, sizeof(test_pattern));
+			ed_pio_readmem(sc, 16384, test_buffer, sizeof(test_pattern));
+			if (bcmp(test_pattern, test_buffer, sizeof(test_pattern)) == 0) {
+				sc->type = ED_TYPE_NE2000;
+				sc->type_str = "NE2000";
+			} else {
+				return (ENXIO);
+			}
 		}
 	}
 	sc->chip_type = ED_CHIP_TYPE_DP8390;
diff --git a/sys/dev/ed/if_ed_pci.c b/sys/dev/ed/if_ed_pci.c
index 21ddb741ae8..3cf353c252a 100644
--- a/sys/dev/ed/if_ed_pci.c
+++ b/sys/dev/ed/if_ed_pci.c
@@ -49,18 +49,19 @@ static struct _pcsid
 	const char	*desc;
 } pci_ids[] =
 {
-	{ ED_RTL8029_PCI_ID, "RealTek 8029" }, /* Needs realtek full duplex */
+	{ 0x140111f6, "Compex RL2000" },
+	{ 0x005812c3, "Holtek HT80232" },
+	{ 0x30008e2e, "KTI ET32P2" },
 	{ 0x50004a14, "NetVin NV5000SC" },
 	{ 0x09401050, "ProLAN" },
-	{ 0x140111f6, "Compex RL2000" },
-	{ 0x30008e2e, "KTI ET32P2" },
-	{ 0x19808c4a, "Winbond W89C940" },
+	{ ED_RTL8029_PCI_ID, "RealTek 8029" }, /* Needs realtek full duplex */
 	{ 0x0e3410bd, "Surecom NE-34" },
-	{ 0x09261106, "VIA VT86C926" },		/* only do 16-bit */
+	{ 0x09261106, "VIA VT86C926" },
+	{ 0x19808c4a, "Winbond W89C940" },
 	{ 0x5a5a1050, "Winbond W89C940F" },
 #if 0
-	/* Holtek needs special lovin', disabled by default */
-	{ 0x005812c3, "Holtek HT80232" },	/* Only 16-bit I/O, Holtek fdx */
+	/* some Holtek needs special lovin', disabled by default */
+	/* The Holtek can report/do full duplex, but that's unimplemented */
 	{ 0x559812c3, "Holtek HT80229" },	/* Only 32-bit I/O, Holtek fdx, STOP_PG_60? */
 #endif
 	{ 0x00000000, NULL }
@@ -87,7 +88,6 @@ static int
 ed_pci_attach(device_t dev)
 {
 	struct	ed_softc *sc = device_get_softc(dev);
-	int	flags = 0;
 	int	error = ENXIO;
 
 	/*
@@ -96,9 +96,10 @@ ed_pci_attach(device_t dev)
 	 * are areally just generic ne-2000 cards.
 	 */
 	if (pci_get_devid(dev) == ED_RTL8029_PCI_ID)
-		error = ed_probe_RTL80x9(dev, PCIR_BAR(0), flags);
+		error = ed_probe_RTL80x9(dev, PCIR_BAR(0), 0);
 	if (error)
-		error = ed_probe_Novell(dev, PCIR_BAR(0), flags);
+		error = ed_probe_Novell(dev, PCIR_BAR(0),
+		    ED_FLAGS_FORCE_16BIT_MODE);
 	if (error) {
 		ed_release_resources(dev);
 		return (error);

From 253953cd5bbc76e5a0194f74055b37eb39076b98 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Wed, 25 Aug 2010 02:09:07 +0000
Subject: [PATCH 0227/1624] On second thought, we need to force 16-bit mode

---
 sys/dev/ed/if_ed_novell.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/sys/dev/ed/if_ed_novell.c b/sys/dev/ed/if_ed_novell.c
index b1d4fd8dfe2..d81b50997bc 100644
--- a/sys/dev/ed/if_ed_novell.c
+++ b/sys/dev/ed/if_ed_novell.c
@@ -136,6 +136,9 @@ ed_probe_Novell_generic(device_t dev, int flags)
 		sc->isa16bit = 1;
 		sc->type = ED_TYPE_NE2000;
 		sc->type_str = "NE2000";
+		ed_nic_outb(sc, ED_P0_DCR, ED_DCR_WTS | ED_DCR_FT1 | ED_DCR_LS);
+		ed_nic_outb(sc, ED_P0_PSTART, 16384 / ED_PAGE_SIZE);
+		ed_nic_outb(sc, ED_P0_PSTOP, 32768 / ED_PAGE_SIZE);
 	} else {
 		/*
 		 * Write a test pattern in byte mode. If this fails, then there

From df7442533c8ce3a2b99c795e28780b44afdb2fc6 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 25 Aug 2010 03:14:32 +0000
Subject: [PATCH 0228/1624] If a thread is removed from umtxq while sleeping,
 reset error code to zero, this gives userland a better indication that a
 thread needn't to be cancelled.

---
 sys/kern/kern_umtx.c | 35 ++++++++++++-----------------------
 1 file changed, 12 insertions(+), 23 deletions(-)

diff --git a/sys/kern/kern_umtx.c b/sys/kern/kern_umtx.c
index 42d2761d7cf..bdae3e82756 100644
--- a/sys/kern/kern_umtx.c
+++ b/sys/kern/kern_umtx.c
@@ -1059,8 +1059,10 @@ do_wait(struct thread *td, void *addr, u_long id,
 		umtxq_lock(&uq->uq_key);
 		for (;;) {
 			error = umtxq_sleep(uq, "uwait", tvtohz(&tv));
-			if (!(uq->uq_flags & UQF_UMTXQ))
+			if (!(uq->uq_flags & UQF_UMTXQ)) {
+				error = 0;
 				break;
+			}
 			if (error != ETIMEDOUT)
 				break;
 			umtxq_unlock(&uq->uq_key);
@@ -2404,25 +2406,14 @@ do_cv_wait(struct thread *td, struct ucond *cv, struct umutex *m,
 		}
 	}
 
-	if (error != 0) {
-		if ((uq->uq_flags & UQF_UMTXQ) == 0) {
-			/*
-			 * If we concurrently got do_cv_signal()d
-			 * and we got an error or UNIX signals or a timeout,
-			 * then, perform another umtxq_signal to avoid
-			 * consuming the wakeup. This may cause supurious
-			 * wakeup for another thread which was just queued,
-			 * but SUSV3 explicitly allows supurious wakeup to
-			 * occur, and indeed a kernel based implementation
-			 * can not avoid it.
-			 */ 
-			if (!umtxq_signal(&uq->uq_key, 1))
-				error = 0;
-		}
+	if ((uq->uq_flags & UQF_UMTXQ) == 0)
+		error = 0;
+	else {
+		umtxq_remove(uq);
 		if (error == ERESTART)
 			error = EINTR;
 	}
-	umtxq_remove(uq);
+
 	umtxq_unlock(&uq->uq_key);
 	umtx_key_release(&uq->uq_key);
 	return (error);
@@ -2891,15 +2882,13 @@ do_sem_wait(struct thread *td, struct _usem *sem, struct timespec *timeout)
 		}
 	}
 
-	if (error != 0) {
-		if ((uq->uq_flags & UQF_UMTXQ) == 0) {
-			if (!umtxq_signal(&uq->uq_key, 1))
-				error = 0;
-		}
+	if ((uq->uq_flags & UQF_UMTXQ) == 0)
+		error = 0;
+	else {
+		umtxq_remove(uq);
 		if (error == ERESTART)
 			error = EINTR;
 	}
-	umtxq_remove(uq);
 	umtxq_unlock(&uq->uq_key);
 	umtx_key_release(&uq->uq_key);
 	return (error);

From 871726d7e96a4707cdebe7b0ac3eb15d165abedc Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 25 Aug 2010 07:33:35 +0000
Subject: [PATCH 0229/1624] Sync up XLR tick.c with the new MIPS tick.c

---
 sys/mips/rmi/tick.c | 44 ++++++++++++++++++++++++++------------------
 1 file changed, 26 insertions(+), 18 deletions(-)

diff --git a/sys/mips/rmi/tick.c b/sys/mips/rmi/tick.c
index 7520caca3b7..3b83a5c78d6 100644
--- a/sys/mips/rmi/tick.c
+++ b/sys/mips/rmi/tick.c
@@ -62,8 +62,8 @@ struct timecounter *platform_timecounter;
 static DPCPU_DEFINE(uint32_t, cycles_per_tick);
 static uint32_t cycles_per_usec;
 
-static DPCPU_DEFINE(uint32_t, counter_upper);
-static DPCPU_DEFINE(uint32_t, counter_lower_last);
+static DPCPU_DEFINE(volatile uint32_t, counter_upper);
+static DPCPU_DEFINE(volatile uint32_t, counter_lower_last);
 static DPCPU_DEFINE(uint32_t, compare_ticks);
 static DPCPU_DEFINE(uint32_t, lost_ticks);
 
@@ -108,23 +108,32 @@ tick_ticker(void)
 	uint32_t t_lower_last, t_upper;
 
 	/*
-	 * XXX: MIPS64 platforms can read 64-bits of counter directly.
-	 * Also: the tc code is supposed to cope with things wrapping
-	 * from the time counter, so I'm not sure why all these hoops
-	 * are even necessary.
+	 * Disable preemption because we are working with cpu specific data.
 	 */
-	ticktock = mips_rd_count();
 	critical_enter();
-	t_lower_last = DPCPU_GET(counter_lower_last);
-	t_upper = DPCPU_GET(counter_upper);
-	if (ticktock < t_lower_last)
-		t_upper++;
-	t_lower_last = ticktock;
-	DPCPU_SET(counter_upper, t_upper);
-	DPCPU_SET(counter_lower_last, t_lower_last);
+
+	/*
+	 * Note that even though preemption is disabled, interrupts are
+	 * still enabled. In particular there is a race with clock_intr()
+	 * reading the values of 'counter_upper' and 'counter_lower_last'.
+	 *
+	 * XXX this depends on clock_intr() being executed periodically
+	 * so that 'counter_upper' and 'counter_lower_last' are not stale.
+	 */
+	do {
+		t_upper = DPCPU_GET(counter_upper);
+		t_lower_last = DPCPU_GET(counter_lower_last);
+	} while (t_upper != DPCPU_GET(counter_upper));
+
+	ticktock = mips_rd_count();
+
 	critical_exit();
 
-	ret = ((uint64_t)t_upper << 32) | t_lower_last;
+	/* COUNT register wrapped around */
+	if (ticktock < t_lower_last)
+		t_upper++;
+
+	ret = ((uint64_t)t_upper << 32) | ticktock;
 	return (ret);
 }
 
@@ -268,11 +277,11 @@ clock_intr(void *arg)
 	} else	/* In one-shot mode timer should be stopped after the event. */
 		mips_wr_compare(0xffffffff);
 
-	critical_enter();
+	/* COUNT register wrapped around */
 	if (count < DPCPU_GET(counter_lower_last)) {
 		DPCPU_SET(counter_upper, DPCPU_GET(counter_upper) + 1);
-		DPCPU_SET(counter_lower_last, count);
 	}
+	DPCPU_SET(counter_lower_last, count);
 
 	if (cycles_per_tick > 0) {
 
@@ -302,7 +311,6 @@ clock_intr(void *arg)
 	}
 	if (sc->et.et_active)
 		sc->et.et_event_cb(&sc->et, sc->et.et_arg);
-	critical_exit();
 	return (FILTER_HANDLED);
 }
 

From 3dd9aad2706666a4c78846ae033b5b0d83843e26 Mon Sep 17 00:00:00 2001
From: Alexander Leidinger 
Date: Wed, 25 Aug 2010 08:09:42 +0000
Subject: [PATCH 0230/1624] - Change the threshold from 'running next scrub the
 th day after the   last one' to 'running next scrub the th
 day after the last one'. - Improve wording.

Requested by:	jhell 
MFC after:	1 week
---
 etc/periodic/daily/800.scrub-zfs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/etc/periodic/daily/800.scrub-zfs b/etc/periodic/daily/800.scrub-zfs
index 8c0ece79cb4..f60588abf14 100755
--- a/etc/periodic/daily/800.scrub-zfs
+++ b/etc/periodic/daily/800.scrub-zfs
@@ -53,7 +53,7 @@ case "$daily_scrub_zfs_enable" in
 		# Now minus last scrub (both in seconds) converted to days.
 		_scrub_diff=$(expr -e \( $(date +%s) - \
 		    $(date -j -f %F.%T ${_last_scrub} +%s) \) / 60 / 60 / 24)
-		if [ ${_scrub_diff} -le ${_pool_threshold} ]; then
+		if [ ${_scrub_diff} -lt ${_pool_threshold} ]; then
 			echo "   skipping scrubbing of pool '${pool}':"
 			echo "      last scrubbing is ${_scrub_diff} days ago, threshold is set to ${_pool_threshold} days"
 			continue
@@ -65,11 +65,11 @@ case "$daily_scrub_zfs_enable" in
 				echo "   scrubbing of pool '${pool}' already in progress, skipping:"
 				;;
 			*"none requested"*)
-				echo "   starting first scrubbing (after reboot) of pool '${pool}':"
+				echo "   starting first scrub (since reboot) of pool '${pool}':"
 				zpool scrub ${pool}
 				;;
 			*)
-				echo "   starting scrubbing of pool '${pool}':"
+				echo "   starting scrub of pool '${pool}':"
 				zpool scrub ${pool}
 				;;
 		esac

From e62f433662880ff16203bb314865c3ff51cc24e8 Mon Sep 17 00:00:00 2001
From: Maxim Konovalov 
Date: Wed, 25 Aug 2010 08:37:18 +0000
Subject: [PATCH 0231/1624] o Correct typo.

Submitted by:	Bojidara Marinchovska via -stable
MFC after:	1 week
---
 etc/defaults/rc.conf | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/etc/defaults/rc.conf b/etc/defaults/rc.conf
index 238c907c15c..427fe2d0c16 100644
--- a/etc/defaults/rc.conf
+++ b/etc/defaults/rc.conf
@@ -216,7 +216,7 @@ ifconfig_lo0="inet 127.0.0.1"	# default loopback device configuration.
 #ifconfig_ed0_alias0="inet6 2001:db8:2::1 prefixlen 64" # Sample IPv6 alias
 #ifconfig_fxp0_name="net0"	# Change interface name from fxp0 to net0.
 #vlans_fxp0="101 vlan0"		# vlan(4) interfaces for fxp0 device
-#create_arg_vlan0="vlan 102"	# vlan tag for vlan0 device
+#create_args_vlan0="vlan 102"	# vlan tag for vlan0 device
 #wlans_ath0="wlan0"		# wlan(4) interfaces for ath0 device
 #wlandebug_wlan0="scan+auth+assoc"	# Set debug flags with wlanddebug(8)
 #ipv4_addrs_fxp0="192.168.0.1/24 192.168.1.1-5/28" # example IPv4 address entry.

From 5cdefefaed82497ada795db6af8ae2bcf0137c94 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 25 Aug 2010 08:48:54 +0000
Subject: [PATCH 0232/1624] RMI XLR platform code clean-up.

- move PIC code to xlr_machdep.c
- move fast message ring code completely to on_chip.c
- move memory initialization to a new function xlr_mem_init()
- style fixes
---
 sys/mips/rmi/on_chip.c     |  55 +----------
 sys/mips/rmi/xlr_machdep.c | 182 +++++++++++++++++++++++--------------
 2 files changed, 115 insertions(+), 122 deletions(-)

diff --git a/sys/mips/rmi/on_chip.c b/sys/mips/rmi/on_chip.c
index ec53394f310..afed58ba7c5 100644
--- a/sys/mips/rmi/on_chip.c
+++ b/sys/mips/rmi/on_chip.c
@@ -1,4 +1,4 @@
-/*-
+ /*-
  * Copyright (c) 2003-2009 RMI Corporation
  * All rights reserved.
  *
@@ -57,8 +57,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
-#include 
 #include 
 #include 
 
@@ -102,14 +100,11 @@ do { \
 /* make this a read/write spinlock */
 static struct mtx msgrng_lock;
 static int msgring_int_enabled;
-struct mtx xlr_pic_lock;
-
 static int msgring_pop_num_buckets;
 static uint32_t msgring_pop_bucket_mask;
 static int msgring_int_type;
 static int msgring_watermark_count;
 static uint32_t msgring_thread_mask;
-
 uint32_t msgrng_msg_cycles = 0;
 
 void xlr_msgring_handler(struct trapframe *);
@@ -169,10 +164,11 @@ xlr_msgring_cpu_init(void)
 void 
 xlr_msgring_config(void)
 {
+	mtx_init(&msgrng_lock, "msgring", NULL, MTX_SPIN | MTX_RECURSE);
 	msgring_int_type = 0x02;
 	msgring_pop_num_buckets = 8;
 	msgring_pop_bucket_mask = 0xff;
-
+	msgring_int_enabled = 0;
 	msgring_watermark_count = 1;
 	msgring_thread_mask = 0x01;
 }
@@ -221,9 +217,6 @@ xlr_msgring_handler(struct trapframe *tf)
 			}
 		}
 	}
-
-	xlr_set_counter(MSGRNG_EXIT_STATUS, msgrng_read_status());
-
 	msgrng_flags_restore(mflags);
 }
 
@@ -387,48 +380,6 @@ register_msgring_handler(int major,
 	return 0;
 }
 
-static void 
-pic_init(void)
-{
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	int i = 0;
-	int level;
-
-	dbg_msg("Initializing PIC...\n");
-	for (i = 0; i < PIC_NUM_IRTS; i++) {
-
-		level = PIC_IRQ_IS_EDGE_TRIGGERED(i);
-
-		/* Bind all PIC irqs to cpu 0 */
-		xlr_write_reg(mmio, PIC_IRT_0_BASE + i, 0x01);
-
-		/*
-		 * Use local scheduling and high polarity for all IRTs
-		 * Invalidate all IRTs, by default
-		 */
-		xlr_write_reg(mmio, PIC_IRT_1_BASE + i, (level << 30) | (1 << 6) |
-		    (PIC_IRQ_BASE + i));
-	}
-	dbg_msg("PIC init now done\n");
-}
-
-void 
-on_chip_init(void)
-{
-	/* Set xlr_io_base to the run time value */
-	mtx_init(&msgrng_lock, "msgring", NULL, MTX_SPIN | MTX_RECURSE);
-	mtx_init(&xlr_pic_lock, "pic", NULL, MTX_SPIN);
-
-	xlr_board_info_setup();
-
-	msgring_int_enabled = 0;
-
-	xlr_msgring_config();
-	pic_init();
-
-	xlr_msgring_cpu_init();
-}
-
 static void
 start_msgring_threads(void *arg)
 {
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index 0e2401e84d8..3945e9be116 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -74,6 +74,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 void mpwait(void);
 unsigned long xlr_io_base = (unsigned long)(DEFAULT_XLR_IO_BASE);
@@ -82,6 +83,8 @@ unsigned long xlr_io_base = (unsigned long)(DEFAULT_XLR_IO_BASE);
    the dynamic kenv is setup */
 char boot1_env[4096];
 int rmi_spin_mutex_safe=0;
+struct mtx xlr_pic_lock;
+
 /*
  * Parameters from boot loader
  */
@@ -264,7 +267,6 @@ mips_init(void)
 	init_param1();
 	init_param2(physmem);
 
-	/* XXX: Catch 22. Something touches the tlb. */
 	mips_cpu_init();
 	pmap_bootstrap();
 #ifdef DDB
@@ -277,20 +279,110 @@ mips_init(void)
 	mutex_init();
 }
 
+static void 
+xlr_pic_init(void)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
+	int i, level;
+
+	mtx_init(&xlr_pic_lock, "pic", NULL, MTX_SPIN);
+	xlr_write_reg(mmio, PIC_CTRL, 0);
+	for (i = 0; i < PIC_NUM_IRTS; i++) {
+		level = PIC_IRQ_IS_EDGE_TRIGGERED(i);
+
+		/* Bind all PIC irqs to cpu 0 */
+		xlr_write_reg(mmio, PIC_IRT_0_BASE + i, 0x01);
+
+		/*
+		 * Use local scheduling and high polarity for all IRTs
+		 * Invalidate all IRTs, by default
+		 */
+		xlr_write_reg(mmio, PIC_IRT_1_BASE + i, (level << 30) | (1 << 6) |
+		    (PIC_IRQ_BASE + i));
+	}
+}
+
+static void
+xlr_mem_init(void)
+{
+	struct xlr_boot1_mem_map *boot_map;
+	vm_size_t physsz = 0;
+	int i, j;
+
+	/* get physical memory info from boot loader */
+	boot_map = (struct xlr_boot1_mem_map *)
+	    (unsigned long)xlr_boot1_info.psb_mem_map;
+	for (i = 0, j = 0; i < boot_map->num_entries; i++, j += 2) {
+		if (boot_map->physmem_map[i].type == BOOT1_MEM_RAM) {
+			if (j == 14) {
+				printf("*** ERROR *** memory map too large ***\n");
+				break;
+			}
+			if (j == 0) {
+				/* TODO FIXME  */
+				/* start after kernel end */
+				phys_avail[0] = (vm_paddr_t)
+				    MIPS_KSEG0_TO_PHYS(&_end) + 0x20000;
+				/* boot loader start */
+				/* HACK to Use bootloaders memory region */
+				/* TODO FIXME  */
+				if (boot_map->physmem_map[0].size == 0x0c000000) {
+					boot_map->physmem_map[0].size = 0x0ff00000;
+				}
+				phys_avail[1] = boot_map->physmem_map[0].addr +
+				    boot_map->physmem_map[0].size;
+				printf("First segment: addr:%p -> %p \n",
+				       (void *)phys_avail[0], 
+				       (void *)phys_avail[1]);
+
+			} else {
+/*
+ * Can't use this code yet, because most of the fixed allocations happen from
+ * the biggest physical area. If we have more than 512M memory the kernel will try
+ * to map from the second are which is not in KSEG0 and not mapped
+ */
+				phys_avail[j] = (vm_paddr_t)
+				    boot_map->physmem_map[i].addr;
+				phys_avail[j + 1] = phys_avail[j] +
+				    boot_map->physmem_map[i].size;
+				if (phys_avail[j + 1] < phys_avail[j] ) {
+					/* Houston we have an issue. Memory is
+					 * larger than possible. Its probably in
+					 * 64 bit > 4Gig and we are in 32 bit mode.
+					 */
+					phys_avail[j + 1] = 0xfffff000;
+					printf("boot map size was %jx\n",
+					    (intmax_t)boot_map->physmem_map[i].size);
+					boot_map->physmem_map[i].size = phys_avail[j + 1]
+					    - phys_avail[j];
+					printf("reduced to %jx\n", 
+					    (intmax_t)boot_map->physmem_map[i].size);
+				}
+				printf("Next segment : addr:%p -> %p \n",
+				       (void *)phys_avail[j], 
+				       (void *)phys_avail[j+1]);
+			}
+			physsz += boot_map->physmem_map[i].size;
+		}
+	}
+
+	/* FIXME XLR TODO */
+	phys_avail[j] = phys_avail[j + 1] = 0;
+	realmem = physmem = btoc(physsz);
+}
+
 void
 platform_start(__register_t a0 __unused,
     __register_t a1 __unused,
     __register_t a2 __unused,
     __register_t a3 __unused)
 {
-	vm_size_t physsz = 0;
-	int i, j;
-	struct xlr_boot1_mem_map *boot_map;
+	int i;
 #ifdef SMP
 	uint32_t tmp;
 	void (*wakeup) (void *, void *, unsigned int);
-
 #endif
+
 	/* XXX FIXME the code below is not 64 bit clean */
 	/* Save boot loader and other stuff from scratch regs */
 	xlr_boot1_info = *(struct boot1_info *)(intptr_t)(int)read_c0_register32(MIPS_COP_0_OSSCRATCH, 0);
@@ -345,64 +437,7 @@ platform_start(__register_t a0 __unused,
 	xlr_set_boot_flags();
 	xlr_parse_mmu_options();
 
-	/* get physical memory info from boot loader */
-	boot_map = (struct xlr_boot1_mem_map *)
-	    (unsigned long)xlr_boot1_info.psb_mem_map;
-	for (i = 0, j = 0; i < boot_map->num_entries; i++, j += 2) {
-		if (boot_map->physmem_map[i].type == BOOT1_MEM_RAM) {
-			if (j == 14) {
-				printf("*** ERROR *** memory map too large ***\n");
-				break;
-			}
-			if (j == 0) {
-				/* TODO FIXME  */
-				/* start after kernel end */
-				phys_avail[0] = (vm_paddr_t)
-				    MIPS_KSEG0_TO_PHYS(&_end) + 0x20000;
-				/* boot loader start */
-				/* HACK to Use bootloaders memory region */
-				/* TODO FIXME  */
-				if (boot_map->physmem_map[0].size == 0x0c000000) {
-					boot_map->physmem_map[0].size = 0x0ff00000;
-				}
-				phys_avail[1] = boot_map->physmem_map[0].addr +
-				    boot_map->physmem_map[0].size;
-				printf("First segment: addr:%p -> %p \n",
-				       (void *)phys_avail[0], 
-				       (void *)phys_avail[1]);
-
-			} else {
-/*
- * Can't use this code yet, because most of the fixed allocations happen from
- * the biggest physical area. If we have more than 512M memory the kernel will try
- * to map from the second are which is not in KSEG0 and not mapped
- */
-				phys_avail[j] = (vm_paddr_t)
-				    boot_map->physmem_map[i].addr;
-				phys_avail[j + 1] = phys_avail[j] +
-				    boot_map->physmem_map[i].size;
-				if (phys_avail[j + 1] < phys_avail[j] ) {
-					/* Houston we have an issue. Memory is
-					 * larger than possible. Its probably in
-					 * 64 bit > 4Gig and we are in 32 bit mode.
-					 */
-					phys_avail[j + 1] = 0xfffff000;
-					printf("boot map size was %jx\n", (intmax_t)boot_map->physmem_map[i].size);
-					boot_map->physmem_map[i].size = phys_avail[j + 1] - phys_avail[j];
-					printf("reduced to %jx\n", (intmax_t)boot_map->physmem_map[i].size);
-				}
-				printf("Next segment : addr:%p -> %p \n",
-				       (void *)phys_avail[j], 
-				       (void *)phys_avail[j+1]);
-			}
-			physsz += boot_map->physmem_map[i].size;
-		}
-	}
-
-	/* FIXME XLR TODO */
-	phys_avail[j] = phys_avail[j + 1] = 0;
-	realmem = physmem = btoc(physsz);
-
+	xlr_mem_init();
 	/* Set up hz, among others. */
 	mips_init();
 
@@ -436,14 +471,14 @@ platform_start(__register_t a0 __unused,
 #endif
 
 	/* xlr specific post initialization */
-	/*
-	 * The expectation is that mutex_init() is already done in
-	 * mips_init() XXX NOTE: We may need to move this to SMP based init
-	 * code for each CPU, later.
-	 */
-	rmi_spin_mutex_safe = 1;
-	on_chip_init();
+	/* initialize other on chip stuff */
+	xlr_board_info_setup();
+	xlr_msgring_config();
+	xlr_pic_init();
+	xlr_msgring_cpu_init();
+
 	mips_timer_init_params(xlr_boot1_info.cpu_frequency, 0);
+
 	printf("Platform specific startup now completes\n");
 }
 
@@ -455,6 +490,7 @@ platform_cpu_init()
 void
 platform_identify(void)
 {
+
 	printf("Board [%d:%d], processor 0x%08x\n", (int)xlr_boot1_info.board_major_version,
 	    (int)xlr_boot1_info.board_minor_version, mips_rd_prid());
 }
@@ -530,14 +566,17 @@ platform_init_ap(int cpuid)
 int
 platform_ipi_intrnum(void) 
 {
+
 	return (IRQ_IPI);
 }
 
 void
 platform_ipi_send(int cpuid)
 {
+
 	pic_send_ipi(xlr_cpuid_to_hwtid[cpuid],
 	    platform_ipi_intrnum(), 0);
+
 }
 
 void
@@ -548,18 +587,21 @@ platform_ipi_clear(void)
 int
 platform_processor_id(void)
 {
+
 	return (xlr_hwtid_to_cpuid[xlr_cpu_id()]);
 }
 
 int
 platform_num_processors(void)
 {
+
 	return (xlr_ncores * xlr_threads_per_core);
 }
 
 struct cpu_group *
 platform_smp_topo()
 {
+
 	return (smp_topo_2level(CG_SHARE_L2, xlr_ncores, CG_SHARE_L1,
 		xlr_threads_per_core, CG_FLAG_THREAD));
 }

From 0bc1991a4a4d6186660fe09643d6bc486b70eeb6 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Wed, 25 Aug 2010 09:10:32 +0000
Subject: [PATCH 0233/1624] Call the necessary DTrace function pointers when we
 have different kinds of traps.

Sponsored by:	The FreeBSD Foundation
---
 sys/amd64/amd64/trap.c | 56 ++++++++++++++++++++++++++++++++++++++++++
 sys/i386/i386/trap.c   | 35 ++++++++++++++++++++++++++
 2 files changed, 91 insertions(+)

diff --git a/sys/amd64/amd64/trap.c b/sys/amd64/amd64/trap.c
index f38dbf969e3..69e94d95f90 100644
--- a/sys/amd64/amd64/trap.c
+++ b/sys/amd64/amd64/trap.c
@@ -109,6 +109,13 @@ dtrace_doubletrap_func_t	dtrace_doubletrap_func;
  * implementation opaque. 
  */
 systrace_probe_func_t	systrace_probe_func;
+
+/*
+ * These hooks are necessary for the pid, usdt and fasttrap providers.
+ */
+dtrace_fasttrap_probe_ptr_t	dtrace_fasttrap_probe_ptr;
+dtrace_pid_probe_ptr_t		dtrace_pid_probe_ptr;
+dtrace_return_probe_ptr_t	dtrace_return_probe_ptr;
 #endif
 
 extern void trap(struct trapframe *frame);
@@ -239,6 +246,55 @@ trap(struct trapframe *frame)
 	if (dtrace_trap_func != NULL)
 		if ((*dtrace_trap_func)(frame, type))
 			goto out;
+	if (type == T_DTRACE_PROBE || type == T_DTRACE_RET ||
+	    type == T_BPTFLT) {
+		struct reg regs;
+
+		regs.r_r15 = frame->tf_r15;
+		regs.r_r14 = frame->tf_r14;
+		regs.r_r13 = frame->tf_r13;
+		regs.r_r12 = frame->tf_r12;
+		regs.r_r11 = frame->tf_r11;
+		regs.r_r10 = frame->tf_r10;
+		regs.r_r9  = frame->tf_r9;
+		regs.r_r8  = frame->tf_r8;
+		regs.r_rdi = frame->tf_rdi;
+		regs.r_rsi = frame->tf_rsi;
+		regs.r_rbp = frame->tf_rbp;
+		regs.r_rbx = frame->tf_rbx;
+		regs.r_rdx = frame->tf_rdx;
+		regs.r_rcx = frame->tf_rcx;
+		regs.r_rax = frame->tf_rax;
+		regs.r_rip = frame->tf_rip;
+		regs.r_cs = frame->tf_cs;
+		regs.r_rflags = frame->tf_rflags;
+		regs.r_rsp = frame->tf_rsp;
+		regs.r_ss = frame->tf_ss;
+		if (frame->tf_flags & TF_HASSEGS) {
+			regs.r_ds = frame->tf_ds;
+			regs.r_es = frame->tf_es;
+			regs.r_fs = frame->tf_fs;
+			regs.r_gs = frame->tf_gs;
+		} else {
+			regs.r_ds = 0;
+			regs.r_es = 0;
+			regs.r_fs = 0;
+			regs.r_gs = 0;
+		}
+		if (type == T_DTRACE_PROBE &&
+		    dtrace_fasttrap_probe_ptr != NULL &&
+		    dtrace_fasttrap_probe_ptr(®s) == 0)
+				goto out;
+		if (type == T_BPTFLT &&
+		    dtrace_pid_probe_ptr != NULL &&
+		    dtrace_pid_probe_ptr(®s) == 0)
+				goto out;
+		if (type == T_DTRACE_RET &&
+		    dtrace_return_probe_ptr != NULL &&
+		    dtrace_return_probe_ptr(®s) == 0)
+			goto out;
+
+	}
 #endif
 
 	if ((frame->tf_rflags & PSL_I) == 0) {
diff --git a/sys/i386/i386/trap.c b/sys/i386/i386/trap.c
index 561ce68fe0d..9c580f74ac0 100644
--- a/sys/i386/i386/trap.c
+++ b/sys/i386/i386/trap.c
@@ -118,6 +118,9 @@ dtrace_doubletrap_func_t	dtrace_doubletrap_func;
  * implementation opaque. 
  */
 systrace_probe_func_t	systrace_probe_func;
+
+dtrace_pid_probe_ptr_t	dtrace_pid_probe_ptr;
+dtrace_return_probe_ptr_t dtrace_return_probe_ptr;
 #endif
 
 extern void trap(struct trapframe *frame);
@@ -260,6 +263,38 @@ trap(struct trapframe *frame)
 	    dtrace_trap_func != NULL)
 		if ((*dtrace_trap_func)(frame, type))
 			goto out;
+	if (type == T_DTRACE_PROBE || type == T_DTRACE_RET ||
+	    type == T_BPTFLT) {
+		struct reg regs;
+
+		regs.r_fs = frame->tf_fs;
+		regs.r_es = frame->tf_es;
+		regs.r_ds = frame->tf_ds;
+		regs.r_edi = frame->tf_edi;
+		regs.r_esi = frame->tf_esi;
+		regs.r_ebp = frame->tf_ebp;
+		regs.r_ebx = frame->tf_ebx;
+		regs.r_edx = frame->tf_edx;
+		regs.r_ecx = frame->tf_ecx;
+		regs.r_eax = frame->tf_eax;
+		regs.r_eip = frame->tf_eip;
+		regs.r_cs = frame->tf_cs;
+		regs.r_eflags = frame->tf_eflags;
+		regs.r_esp = frame->tf_esp;
+		regs.r_ss = frame->tf_ss;
+		if (type == T_DTRACE_PROBE &&
+		    dtrace_fasttrap_probe_ptr != NULL &&
+		    dtrace_fasttrap_probe_ptr(®s) == 0)
+			goto out;
+		if (type == T_BPTFLT &&
+		    dtrace_pid_probe_ptr != NULL &&
+		    dtrace_pid_probe_ptr(®s) == 0)
+			goto out;
+		if (type == T_DTRACE_RET &&
+		    dtrace_return_probe_ptr != NULL &&
+		    dtrace_return_probe_ptr(®s) == 0)
+			goto out;
+	}
 #endif
 
 	if ((frame->tf_eflags & PSL_I) == 0) {

From eb0c1bafd0df36f79f5efa32ad184635d90257a4 Mon Sep 17 00:00:00 2001
From: Gabor Kovesdan 
Date: Wed, 25 Aug 2010 09:48:21 +0000
Subject: [PATCH 0234/1624] - Regen after adding WITH_BSD_GREP and removing
 WITH_GNU_GREP

---
 share/man/man5/src.conf.5 | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/share/man/man5/src.conf.5 b/share/man/man5/src.conf.5
index e5eb11f517d..cbd1111bbfe 100644
--- a/share/man/man5/src.conf.5
+++ b/share/man/man5/src.conf.5
@@ -1,7 +1,7 @@
 .\" DO NOT EDIT-- this file is automatically generated.
 .\" from FreeBSD: head/tools/build/options/makeman 188848 2009-02-20 11:09:55Z mtm
 .\" $FreeBSD$
-.Dd July 22, 2010
+.Dd August 25, 2010
 .Dt SRC.CONF 5
 .Os
 .Sh NAME
@@ -214,6 +214,9 @@ Set to not build the boot blocks and loader.
 .\" from FreeBSD: head/tools/build/options/WITHOUT_BSD_CPIO 179813 2008-06-16 05:48:15Z dougb
 Set to not build the BSD licensed version of cpio based on
 .Xr libarchive 3 .
+.It Va WITH_BSD_GREP
+.\" from FreeBSD: head/tools/build/options/WITH_BSD_GREP 211701 2010-08-23 10:04:26Z gabor
+Build BSD-licensed grep instead of GNU grep.
 .It Va WITHOUT_BSNMP
 .\" from FreeBSD: head/tools/build/options/WITHOUT_BSNMP 183306 2008-09-23 16:15:42Z sam
 Set to not build or install
@@ -346,9 +349,6 @@ When set, it also enforces the following options:
 .It
 .Va WITHOUT_GNU_SUPPORT
 .El
-.It Va WITH_GNU_GREP
-.\" from FreeBSD: head/tools/build/options/WITH_GNU_GREP 210389 2010-07-22 19:11:57Z gabor
-Set to build the base system with GNU grep instead of BSD grep
 .It Va WITHOUT_GNU_SUPPORT
 .\" from FreeBSD: head/tools/build/options/WITHOUT_GNU_SUPPORT 156932 2006-03-21 07:50:50Z ru
 Set to build some programs without optional GNU support.

From afc1e710026da514cc2b45297616e4ef0ea07dcc Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 25 Aug 2010 09:53:00 +0000
Subject: [PATCH 0235/1624] Rename on_chip.c to fmn.c, as the file has just the
 fast messaging network code.  The iodi.c has the bus for SoC devices, so the
 name on_chip.c is misleading.

---
 sys/mips/rmi/files.xlr            | 4 +---
 sys/mips/rmi/{on_chip.c => fmn.c} | 2 +-
 2 files changed, 2 insertions(+), 4 deletions(-)
 rename sys/mips/rmi/{on_chip.c => fmn.c} (99%)

diff --git a/sys/mips/rmi/files.xlr b/sys/mips/rmi/files.xlr
index 2444cbd2cb0..06e261ca3ea 100644
--- a/sys/mips/rmi/files.xlr
+++ b/sys/mips/rmi/files.xlr
@@ -7,14 +7,12 @@ mips/rmi/iodi.c					standard
 mips/rmi/msgring.c				standard
 mips/rmi/msgring_xls.c				standard
 mips/rmi/board.c				standard
-mips/rmi/on_chip.c				standard
+mips/rmi/fmn.c					standard
 mips/rmi/intr_machdep.c			        standard
 mips/rmi/mpwait.S			        optional smp
 mips/rmi/xlr_i2c.c              		optional iic
 mips/rmi/uart_bus_xlr_iodi.c			optional uart 
 mips/rmi/uart_cpu_mips_xlr.c			optional uart 
-mips/rmi/perfmon_kern.c				optional xlr_perfmon
-mips/rmi/perfmon_percpu.c			optional xlr_perfmon
 mips/rmi/xlr_pci.c				optional pci
 mips/rmi/xls_ehci.c				optional usb ehci
 mips/rmi/bus_space_rmi.c			standard
diff --git a/sys/mips/rmi/on_chip.c b/sys/mips/rmi/fmn.c
similarity index 99%
rename from sys/mips/rmi/on_chip.c
rename to sys/mips/rmi/fmn.c
index afed58ba7c5..0c0dce10d02 100644
--- a/sys/mips/rmi/on_chip.c
+++ b/sys/mips/rmi/fmn.c
@@ -1,4 +1,4 @@
- /*-
+/*-
  * Copyright (c) 2003-2009 RMI Corporation
  * All rights reserved.
  *

From 30eb8eda729798b6126fe21d664391e006fffcbe Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 25 Aug 2010 11:49:48 +0000
Subject: [PATCH 0236/1624] XLR PIC code update and style(9) fixes.

- style(9) fixes to mips/rmi platform files
- update pic.h to add pic_setup_intr() and use pic_setup_intr() for setting
  up interrupts which are routed thru PIC.
- remove rmi_spin_mutex_safe and haslock, and make sure that the functions
  are called only after mutexes are available.
---
 sys/mips/rmi/fmn.c          |   8 +-
 sys/mips/rmi/intr_machdep.c |   4 +-
 sys/mips/rmi/iodi.c         |  47 ++---
 sys/mips/rmi/msgring.h      |   5 +-
 sys/mips/rmi/pic.h          | 330 +++++++++++++++---------------------
 sys/mips/rmi/xlr_machdep.c  |   4 +-
 sys/mips/rmi/xlr_pci.c      | 120 ++++++-------
 7 files changed, 218 insertions(+), 300 deletions(-)

diff --git a/sys/mips/rmi/fmn.c b/sys/mips/rmi/fmn.c
index 0c0dce10d02..31cb2f0d4d5 100644
--- a/sys/mips/rmi/fmn.c
+++ b/sys/mips/rmi/fmn.c
@@ -362,14 +362,10 @@ register_msgring_handler(int major,
 	if (major >= MAX_TX_STNS)
 		return 1;
 
-	//dbg_msg("major=%d, action=%p, dev_id=%p\n", major, action, dev_id);
-
-	if (rmi_spin_mutex_safe)
-	  mtx_lock_spin(&msgrng_lock);
+	mtx_lock_spin(&msgrng_lock);
 	tx_stn_handlers[major].action = action;
 	tx_stn_handlers[major].dev_id = dev_id;
-	if (rmi_spin_mutex_safe)
-	  mtx_unlock_spin(&msgrng_lock);
+	mtx_unlock_spin(&msgrng_lock);
 
 	if (xlr_test_and_set(&msgring_int_enabled)) {
 		create_msgring_thread(0, 0);
diff --git a/sys/mips/rmi/intr_machdep.c b/sys/mips/rmi/intr_machdep.c
index ef86aac7284..1af15a1502a 100644
--- a/sys/mips/rmi/intr_machdep.c
+++ b/sys/mips/rmi/intr_machdep.c
@@ -168,7 +168,7 @@ cpu_intr(struct trapframe *tf)
 			mips_intrcnt_inc(mips_intr_counters[i]);
 		}
 		write_c0_eirr64(1ULL << i);
-		pic_ack(i, 0);
+		pic_ack(i);
 		if (!ie || TAILQ_EMPTY(&ie->ie_handlers)) {
 			printf("stray interrupt %d\n", i);
 			continue;
@@ -176,7 +176,7 @@ cpu_intr(struct trapframe *tf)
 		if (intr_event_handle(ie, tf) != 0) {
 			printf("stray interrupt %d\n", i);
 		}
-		pic_delayed_ack(i, 0);
+		pic_delayed_ack(i);
 	}
 	critical_exit();
 }
diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index 3f58218fa76..09da00813af 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -91,53 +91,28 @@ struct iodi_softc *iodi_softc;	/* There can be only one. */
 
 static int
 iodi_setup_intr(device_t dev, device_t child,
-    struct resource *ires, int flags, driver_filter_t * filt, driver_intr_t * intr, void *arg,
-    void **cookiep)
+    struct resource *ires, int flags, driver_filter_t * filt,
+    driver_intr_t *intr, void *arg, void **cookiep)
 {
-	int level;
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	xlr_reg_t reg;
 
-	/* FIXME is this the right place to fiddle with PIC? */
 	if (strcmp(device_get_name(child), "uart") == 0) {
 		/* FIXME uart 1? */
-		if (rmi_spin_mutex_safe)
-			mtx_lock_spin(&xlr_pic_lock);
-		level = PIC_IRQ_IS_EDGE_TRIGGERED(PIC_IRT_UART_0_INDEX);
-		xlr_write_reg(mmio, PIC_IRT_0_UART_0, 0x01);
-		xlr_write_reg(mmio, PIC_IRT_1_UART_0, ((1 << 31) | (level << 30) | (1 << 6) | (PIC_UART_0_IRQ)));
-		if (rmi_spin_mutex_safe)
-			mtx_unlock_spin(&xlr_pic_lock);
-		cpu_establish_hardintr("uart", filt,
-		    (driver_intr_t *) intr, (void *)arg, PIC_UART_0_IRQ, flags, cookiep);
-
+		cpu_establish_hardintr("uart", filt, intr, arg,
+		    PIC_UART_0_IRQ, flags, cookiep);
+		pic_setup_intr(PIC_IRT_UART_0_INDEX, PIC_UART_0_IRQ, 0x1);
 	} else if (strcmp(device_get_name(child), "rge") == 0) {
 		int irq;
 
 		/* This is a hack to pass in the irq */
 		irq = (intptr_t)ires->__r_i;
-		if (rmi_spin_mutex_safe)
-			mtx_lock_spin(&xlr_pic_lock);
-		reg = xlr_read_reg(mmio, PIC_IRT_1_BASE + irq - PIC_IRQ_BASE);
-		xlr_write_reg(mmio, PIC_IRT_1_BASE + irq - PIC_IRQ_BASE, reg | (1 << 6) | (1 << 30) | (1 << 31));
-		if (rmi_spin_mutex_safe)
-			mtx_unlock_spin(&xlr_pic_lock);
-		cpu_establish_hardintr("rge", filt, (driver_intr_t *) intr, (void *)arg, irq, flags, cookiep);
-
+		cpu_establish_hardintr("rge", filt, intr, arg, irq, flags,
+		    cookiep);
+		pic_setup_intr(irq - PIC_IRQ_BASE, irq, 0x1);
 	} else if (strcmp(device_get_name(child), "ehci") == 0) {
-		if (rmi_spin_mutex_safe)
-			mtx_lock_spin(&xlr_pic_lock);
-		reg = xlr_read_reg(mmio, PIC_IRT_1_BASE + PIC_USB_IRQ - PIC_IRQ_BASE);
-		xlr_write_reg(mmio, PIC_IRT_1_BASE + PIC_USB_IRQ - PIC_IRQ_BASE, reg | (1 << 6) | (1 << 30) | (1 << 31));
-		if (rmi_spin_mutex_safe)
-			mtx_unlock_spin(&xlr_pic_lock);
-		cpu_establish_hardintr("ehci", filt, (driver_intr_t *) intr, (void *)arg, PIC_USB_IRQ, flags, cookiep);
+		cpu_establish_hardintr("ehci", filt, intr, arg, PIC_USB_IRQ, flags,
+		    cookiep);
+		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1);
 	}
-	/*
-	 * This causes a panic and looks recursive to me (RRS).
-	 * BUS_SETUP_INTR(device_get_parent(dev), child, ires, flags, filt,
-	 * intr, arg, cookiep);
-	 */
 
 	return (0);
 }
diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h
index 43be63899f8..33b23629074 100644
--- a/sys/mips/rmi/msgring.h
+++ b/sys/mips/rmi/msgring.h
@@ -25,6 +25,7 @@
  * 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.
+ * $FreeBSD$
  *
  * RMI_BSD */
 #ifndef _RMI_MSGRING_H_
@@ -471,13 +472,13 @@ extern struct stn_cc xls_cc_table_sec;
 
 
 #define msgrng_access_save(lock, mflags) do {                \
-  if (rmi_spin_mutex_safe) mtx_lock_spin(lock);              \
+  mtx_lock_spin(lock);                                       \
   msgrng_flags_save(mflags);                                 \
  }while(0)
 
 #define msgrng_access_restore(lock, mflags) do {             \
   msgrng_flags_restore(mflags);                              \
-  if (rmi_spin_mutex_safe) mtx_unlock_spin(lock);            \
+  mtx_unlock_spin(lock);                                     \
  }while(0)
 
 #define msgrng_access_enable(mflags) do {   \
diff --git a/sys/mips/rmi/pic.h b/sys/mips/rmi/pic.h
index 05d2741266c..8043bd928df 100644
--- a/sys/mips/rmi/pic.h
+++ b/sys/mips/rmi/pic.h
@@ -32,219 +32,154 @@
 #define _RMI_PIC_H_
 #include 
 
-
-
-
-extern int rmi_spin_mutex_safe;
-
 #include 
 #include 
 #include 
 
-#define PIC_IRT_WD_INDEX     0
-#define PIC_IRT_TIMER_0_INDEX      1
-#define PIC_IRT_TIMER_1_INDEX      2
-#define PIC_IRT_TIMER_2_INDEX      3
-#define PIC_IRT_TIMER_3_INDEX      4
-#define PIC_IRT_TIMER_4_INDEX      5
-#define PIC_IRT_TIMER_5_INDEX      6
-#define PIC_IRT_TIMER_6_INDEX      7
-#define PIC_IRT_TIMER_7_INDEX      8
-#define PIC_IRT_CLOCK_INDEX        PIC_IRT_TIMER_7_INDEX
-#define PIC_IRT_UART_0_INDEX       9
-#define PIC_IRT_UART_1_INDEX       10
-#define PIC_IRT_I2C_0_INDEX       11
-#define PIC_IRT_I2C_1_INDEX       12
-#define PIC_IRT_PCMCIA_INDEX           13
-#define PIC_IRT_GPIO_INDEX             14
-#define PIC_IRT_HYPER_INDEX            15
-#define PIC_IRT_PCIX_INDEX             16
-#define PIC_IRT_GMAC0_INDEX            17
-#define PIC_IRT_GMAC1_INDEX            18
-#define PIC_IRT_GMAC2_INDEX            19
-#define PIC_IRT_GMAC3_INDEX            20
-#define PIC_IRT_XGS0_INDEX             21
-#define PIC_IRT_XGS1_INDEX             22
-#define PIC_IRT_HYPER_FATAL_INDEX      23
-#define PIC_IRT_PCIX_FATAL_INDEX       24
-#define PIC_IRT_BRIDGE_AERR_INDEX      25
-#define PIC_IRT_BRIDGE_BERR_INDEX     26
-#define PIC_IRT_BRIDGE_TB_INDEX        27
-#define PIC_IRT_BRIDGE_AERR_NMI_INDEX  28
+#define	PIC_IRT_WD_INDEX		0
+#define	PIC_IRT_TIMER_INDEX(i)		(1 + (i))
+#define	PIC_IRT_CLOCK_INDEX		PIC_IRT_TIMER_7_INDEX
+#define	PIC_IRT_UART_0_INDEX		9
+#define	PIC_IRT_UART_1_INDEX		10
+#define	PIC_IRT_I2C_0_INDEX		11
+#define	PIC_IRT_I2C_1_INDEX		12
+#define	PIC_IRT_PCMCIA_INDEX		13
+#define	PIC_IRT_GPIO_INDEX		14
+#define	PIC_IRT_HYPER_INDEX		15
+#define	PIC_IRT_PCIX_INDEX		16
+#define	PIC_IRT_GMAC0_INDEX		17
+#define	PIC_IRT_GMAC1_INDEX		18
+#define	PIC_IRT_GMAC2_INDEX		19
+#define	PIC_IRT_GMAC3_INDEX		20
+#define	PIC_IRT_XGS0_INDEX		21
+#define	PIC_IRT_XGS1_INDEX		22
+#define	PIC_IRT_HYPER_FATAL_INDEX	23
+#define	PIC_IRT_PCIX_FATAL_INDEX	24
+#define	PIC_IRT_BRIDGE_AERR_INDEX	25
+#define	PIC_IRT_BRIDGE_BERR_INDEX	26
+#define	PIC_IRT_BRIDGE_TB_INDEX		27
+#define	PIC_IRT_BRIDGE_AERR_NMI_INDEX	28
 
 /* numbering for XLS */
-#define PIC_IRT_BRIDGE_ERR_INDEX       25
-#define PIC_IRT_PCIE_LINK0_INDEX       26
-#define PIC_IRT_PCIE_LINK1_INDEX       27
-#define PIC_IRT_PCIE_LINK2_INDEX       23
-#define PIC_IRT_PCIE_LINK3_INDEX       24
-#define PIC_IRT_PCIE_INT_INDEX         28
-#define PIC_IRT_PCIE_FATAL_INDEX       29
-#define PIC_IRT_GPIO_B_INDEX           30
-#define PIC_IRT_USB_INDEX              31
+#define	PIC_IRT_BRIDGE_ERR_INDEX	25
+#define	PIC_IRT_PCIE_LINK0_INDEX	26
+#define	PIC_IRT_PCIE_LINK1_INDEX	27
+#define	PIC_IRT_PCIE_LINK2_INDEX	23
+#define	PIC_IRT_PCIE_LINK3_INDEX	24
+#define	PIC_IRT_PCIE_INT_INDEX		28
+#define	PIC_IRT_PCIE_FATAL_INDEX	29
+#define	PIC_IRT_GPIO_B_INDEX		30
+#define	PIC_IRT_USB_INDEX		31
 
-#define PIC_NUM_IRTS                   32
+#define	PIC_NUM_IRTS			32
 
-#define PIC_SYS_TIMER_MAXVAL_0_BASE 0x100
-#define PIC_SYS_TIMER_MAXVAL_1_BASE 0x110
+#define	PIC_CLOCK_TIMER			7
 
-#define PIC_SYS_TIMER_0_BASE 0x120
-#define PIC_SYS_TIMER_1_BASE 0x130
+#define	PIC_CTRL			0x00
+#define	PIC_IPI				0x04
+#define	PIC_INT_ACK			0x06
 
-#define PIC_CLOCK_TIMER 7
+#define	WD_MAX_VAL_0			0x08
+#define	WD_MAX_VAL_1			0x09
+#define	WD_MASK_0			0x0a
+#define	WD_MASK_1			0x0b
+#define	WD_HEARBEAT_0			0x0c
+#define	WD_HEARBEAT_1			0x0d
 
-#define PIC_CTRL    0x00
-#define PIC_IPI     0x04
-#define PIC_INT_ACK 0x06
+#define	PIC_IRT_0_BASE			0x40
+#define	PIC_IRT_1_BASE			0x80
+#define	PIC_TIMER_MAXVAL_0_BASE		0x100
+#define	PIC_TIMER_MAXVAL_1_BASE		0x110
+#define	PIC_TIMER_COUNT_0_BASE		0x120
+#define	PIC_TIMER_COUNT_1_BASE		0x130
 
-#define WD_MAX_VAL_0 0x08
-#define WD_MAX_VAL_1 0x09
-#define WD_MASK_0    0x0a
-#define WD_MASK_1    0x0b
-#define WD_HEARBEAT_0 0x0c
-#define WD_HEARBEAT_1 0x0d
 
-#define PIC_IRT_0_BASE 0x40
-#define PIC_IRT_1_BASE 0x80
+#define	PIC_IRT_0(picintr)	(PIC_IRT_0_BASE + (picintr))
+#define	PIC_IRT_1(picintr)	(PIC_IRT_1_BASE + (picintr))
 
-#define PIC_IRT_0_WD     (PIC_IRT_0_BASE   + PIC_IRT_WD_INDEX)
-#define PIC_IRT_1_WD     (PIC_IRT_1_BASE   + PIC_IRT_WD_INDEX)
-#define PIC_IRT_0_TIMER_0     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_0_INDEX)
-#define PIC_IRT_1_TIMER_0     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_0_INDEX)
-#define PIC_IRT_0_TIMER_1     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_1_INDEX)
-#define PIC_IRT_1_TIMER_1     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_1_INDEX)
-#define PIC_IRT_0_TIMER_2     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_2_INDEX)
-#define PIC_IRT_1_TIMER_2     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_2_INDEX)
-#define PIC_IRT_0_TIMER_3     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_3_INDEX)
-#define PIC_IRT_1_TIMER_3     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_3_INDEX)
-#define PIC_IRT_0_TIMER_4     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_4_INDEX)
-#define PIC_IRT_1_TIMER_4     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_4_INDEX)
-#define PIC_IRT_0_TIMER_5     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_5_INDEX)
-#define PIC_IRT_1_TIMER_5     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_5_INDEX)
-#define PIC_IRT_0_TIMER_6     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_6_INDEX)
-#define PIC_IRT_1_TIMER_6     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_6_INDEX)
-#define PIC_IRT_0_TIMER_7     (PIC_IRT_0_BASE   + PIC_IRT_TIMER_7_INDEX)
-#define PIC_IRT_1_TIMER_7     (PIC_IRT_1_BASE   + PIC_IRT_TIMER_7_INDEX)
-#define PIC_IRT_0_CLOCK       (PIC_IRT_0_TIMER_7)
-#define PIC_IRT_1_CLOCK       (PIC_IRT_1_TIMER_7)
-#define PIC_IRT_0_UART_0 (PIC_IRT_0_BASE + PIC_IRT_UART_0_INDEX)
-#define PIC_IRT_1_UART_0 (PIC_IRT_1_BASE + PIC_IRT_UART_0_INDEX)
-#define PIC_IRT_0_UART_1 (PIC_IRT_0_BASE + PIC_IRT_UART_1_INDEX)
-#define PIC_IRT_1_UART_1 (PIC_IRT_1_BASE + PIC_IRT_UART_1_INDEX)
-#define PIC_IRT_0_I2C_0 (PIC_IRT_0_BASE + PIC_IRT_I2C_0_INDEX)
-#define PIC_IRT_1_I2C_0 (PIC_IRT_1_BASE + PIC_IRT_I2C_0_INDEX)
-#define PIC_IRT_0_I2C_1 (PIC_IRT_0_BASE + PIC_IRT_I2C_1_INDEX)
-#define PIC_IRT_1_I2C_1 (PIC_IRT_1_BASE + PIC_IRT_I2C_1_INDEX)
-#define PIC_IRT_0_HYPER       (PIC_IRT_0_BASE + PIC_IRT_HYPER_INDEX)
-#define PIC_IRT_1_HYPER       (PIC_IRT_1_BASE + PIC_IRT_HYPER_INDEX)
-#define PIC_IRT_0_PCIX        (PIC_IRT_0_BASE + PIC_IRT_PCIX_INDEX)
-#define PIC_IRT_1_PCIX        (PIC_IRT_1_BASE + PIC_IRT_PCIX_INDEX)
+#define	PIC_TIMER_MAXVAL_0(i)	(PIC_TIMER_MAXVAL_0_BASE + (i))
+#define	PIC_TIMER_MAXVAL_1(i)	(PIC_TIMER_MAXVAL_1_BASE + (i))
+#define	PIC_TIMER_COUNT_0(i)	(PIC_TIMER_COUNT_0_BASE + (i))
+#define	PIC_TIMER_COUNT_1(i)	(PIC_TIMER_COUNT_0_BASE + (i))
 
-#define PIC_TIMER_0_MAXVAL_0   (PIC_SYS_TIMER_MAXVAL_0_BASE + 0)
-#define PIC_TIMER_0_MAXVAL_1   (PIC_SYS_TIMER_MAXVAL_1_BASE + 0)
-#define PIC_TIMER_0_COUNTER_0  (PIC_SYS_TIMER_0_BASE + 0)
-#define PIC_TIMER_0_COUNTER_1  (PIC_SYS_TIMER_1_BASE + 0)
-#define PIC_TIMER_6_MAXVAL_0   (PIC_SYS_TIMER_MAXVAL_0_BASE + 6)
-#define PIC_TIMER_6_MAXVAL_1   (PIC_SYS_TIMER_MAXVAL_1_BASE + 6)
-#define PIC_TIMER_6_COUNTER_0  (PIC_SYS_TIMER_0_BASE + 6)
-#define PIC_TIMER_6_COUNTER_1  (PIC_SYS_TIMER_1_BASE + 6)
-#define PIC_TIMER_7_MAXVAL_0   (PIC_SYS_TIMER_MAXVAL_0_BASE + 7)
-#define PIC_TIMER_7_MAXVAL_1   (PIC_SYS_TIMER_MAXVAL_1_BASE + 7)
-#define PIC_TIMER_7_COUNTER_0  (PIC_SYS_TIMER_0_BASE + 7)
-#define PIC_TIMER_7_COUNTER_1  (PIC_SYS_TIMER_1_BASE + 7)
+#define	PIC_IRQ_BASE		8
+#define	PIC_IRT_FIRST_IRQ	PIC_IRQ_BASE
 
-#define PIC_IRQ_BASE      8
-#define PIC_IRT_FIRST_IRQ PIC_IRQ_BASE
-#define PIC_WD_IRQ      (PIC_IRQ_BASE + PIC_IRT_WD_INDEX)
-#define PIC_TIMER_0_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_0_INDEX)
-#define PIC_TIMER_1_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_1_INDEX)
-#define PIC_TIMER_2_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_2_INDEX)
-#define PIC_TIMER_3_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_3_INDEX)
-#define PIC_TIMER_4_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_4_INDEX)
-#define PIC_TIMER_5_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_5_INDEX)
-#define PIC_TIMER_6_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_6_INDEX)
-#define PIC_TIMER_7_IRQ (PIC_IRQ_BASE + PIC_IRT_TIMER_7_INDEX)
-#define PIC_CLOCK_IRQ   (PIC_TIMER_7_IRQ)
-#define PIC_UART_0_IRQ  (PIC_IRQ_BASE + PIC_IRT_UART_0_INDEX)
-#define PIC_UART_1_IRQ  (PIC_IRQ_BASE + PIC_IRT_UART_1_INDEX)
-#define PIC_I2C_0_IRQ   (PIC_IRQ_BASE + PIC_IRT_I2C_0_INDEX)
-#define PIC_I2C_1_IRQ   (PIC_IRQ_BASE + PIC_IRT_I2C_1_INDEX)
-#define PIC_PCMCIA_IRQ           (PIC_IRQ_BASE + PIC_IRT_PCMCIA_INDEX)
-#define PIC_GPIO_IRQ             (PIC_IRQ_BASE + PIC_IRT_GPIO_INDEX)
-#define PIC_HYPER_IRQ            (PIC_IRQ_BASE + PIC_IRT_HYPER_INDEX)
-#define PIC_PCIX_IRQ             (PIC_IRQ_BASE + PIC_IRT_PCIX_INDEX)
-#define PIC_GMAC_0_IRQ            (PIC_IRQ_BASE + PIC_IRT_GMAC0_INDEX)
-#define PIC_GMAC_1_IRQ            (PIC_IRQ_BASE + PIC_IRT_GMAC1_INDEX)
-#define PIC_GMAC_2_IRQ            (PIC_IRQ_BASE + PIC_IRT_GMAC2_INDEX)
-#define PIC_GMAC_3_IRQ            (PIC_IRQ_BASE + PIC_IRT_GMAC3_INDEX)
-#define PIC_XGS_0_IRQ             (PIC_IRQ_BASE + PIC_IRT_XGS0_INDEX)
-#define PIC_XGS_1_IRQ             (PIC_IRQ_BASE + PIC_IRT_XGS1_INDEX)
-#define PIC_HYPER_FATAL_IRQ      (PIC_IRQ_BASE + PIC_IRT_HYPER_FATAL_INDEX)
-#define PIC_PCIX_FATAL_IRQ       (PIC_IRQ_BASE + PIC_IRT_PCIX_FATAL_INDEX)
-#define PIC_BRIDGE_AERR_IRQ      (PIC_IRQ_BASE + PIC_IRT_BRIDGE_AERR_INDEX)
-#define PIC_BRIDGE_BERR_IRQ      (PIC_IRQ_BASE + PIC_IRT_BRIDGE_BERR_INDEX)
-#define PIC_BRIDGE_TB_IRQ        (PIC_IRQ_BASE + PIC_IRT_BRIDGE_TB_INDEX)
-#define PIC_BRIDGE_AERR_NMI_IRQ  (PIC_IRQ_BASE + PIC_IRT_BRIDGE_AERR_NMI_INDEX)
+#define	PIC_WD_IRQ		(PIC_IRQ_BASE + PIC_IRT_WD_INDEX)
+#define	PIC_TIMER_IRQ(i)	(PIC_IRQ_BASE + PIC_IRT_TIMER_INDEX(i))
+#define	PIC_CLOCK_IRQ		PIC_TIMER_IRQ(PIC_CLOCK_TIMER)
 
-#define PIC_BRIDGE_ERR_IRQ       (PIC_IRQ_BASE + PIC_IRT_BRIDGE_ERR_INDEX)
-#define PIC_PCIE_LINK0_IRQ       (PIC_IRQ_BASE + PIC_IRT_PCIE_LINK0_INDEX)
-#define PIC_PCIE_LINK1_IRQ       (PIC_IRQ_BASE + PIC_IRT_PCIE_LINK1_INDEX)
-#define PIC_PCIE_LINK2_IRQ       (PIC_IRQ_BASE + PIC_IRT_PCIE_LINK2_INDEX)
-#define PIC_PCIE_LINK3_IRQ       (PIC_IRQ_BASE + PIC_IRT_PCIE_LINK3_INDEX)
-#define PIC_PCIE_INT_IRQ         (PIC_IRQ_BASE + PIC_IRT_PCIE_INT__INDEX)
-#define PIC_PCIE_FATAL_IRQ       (PIC_IRQ_BASE + PIC_IRT_PCIE_FATAL_INDEX)
-#define PIC_GPIO_B_IRQ           (PIC_IRQ_BASE + PIC_IRT_GPIO_B_INDEX)
-#define PIC_USB_IRQ              (PIC_IRQ_BASE + PIC_IRT_USB_INDEX)
+#define	PIC_UART_0_IRQ		(PIC_IRQ_BASE + PIC_IRT_UART_0_INDEX)
+#define	PIC_UART_1_IRQ		(PIC_IRQ_BASE + PIC_IRT_UART_1_INDEX)
+#define	PIC_I2C_0_IRQ		(PIC_IRQ_BASE + PIC_IRT_I2C_0_INDEX)
+#define	PIC_I2C_1_IRQ		(PIC_IRQ_BASE + PIC_IRT_I2C_1_INDEX)
+#define	PIC_PCMCIA_IRQ		(PIC_IRQ_BASE + PIC_IRT_PCMCIA_INDEX)
+#define	PIC_GPIO_IRQ		(PIC_IRQ_BASE + PIC_IRT_GPIO_INDEX)
+#define	PIC_HYPER_IRQ		(PIC_IRQ_BASE + PIC_IRT_HYPER_INDEX)
+#define	PIC_PCIX_IRQ		(PIC_IRQ_BASE + PIC_IRT_PCIX_INDEX)
+#define	PIC_GMAC_0_IRQ		(PIC_IRQ_BASE + PIC_IRT_GMAC0_INDEX)
+#define	PIC_GMAC_1_IRQ		(PIC_IRQ_BASE + PIC_IRT_GMAC1_INDEX)
+#define	PIC_GMAC_2_IRQ		(PIC_IRQ_BASE + PIC_IRT_GMAC2_INDEX)
+#define	PIC_GMAC_3_IRQ		(PIC_IRQ_BASE + PIC_IRT_GMAC3_INDEX)
+#define	PIC_XGS_0_IRQ		(PIC_IRQ_BASE + PIC_IRT_XGS0_INDEX)
+#define	PIC_XGS_1_IRQ		(PIC_IRQ_BASE + PIC_IRT_XGS1_INDEX)
+#define	PIC_HYPER_FATAL_IRQ	(PIC_IRQ_BASE + PIC_IRT_HYPER_FATAL_INDEX)
+#define	PIC_PCIX_FATAL_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIX_FATAL_INDEX)
+#define	PIC_BRIDGE_AERR_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_AERR_INDEX)
+#define	PIC_BRIDGE_BERR_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_BERR_INDEX)
+#define	PIC_BRIDGE_TB_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_TB_INDEX)
+#define	PIC_BRIDGE_AERR_NMI_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_AERR_NMI_INDEX)
 
-#define PIC_IRT_LAST_IRQ         PIC_USB_IRQ
-
-#define PIC_IRQ_IS_EDGE_TRIGGERED(irq) ( ((irq)>=PIC_TIMER_0_IRQ) && ((irq)<=PIC_TIMER_7_IRQ) )
-
-#define PIC_IRQ_IS_IRT(irq) ( ((irq)>=PIC_IRT_FIRST_IRQ) && ((irq)<=PIC_IRT_LAST_IRQ) )
+#define	PIC_BRIDGE_ERR_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_ERR_INDEX)
+#define	PIC_PCIE_LINK0_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_LINK0_INDEX)
+#define	PIC_PCIE_LINK1_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_LINK1_INDEX)
+#define	PIC_PCIE_LINK2_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_LINK2_INDEX)
+#define	PIC_PCIE_LINK3_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_LINK3_INDEX)
+#define	PIC_PCIE_INT_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_INT__INDEX)
+#define	PIC_PCIE_FATAL_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_FATAL_INDEX)
+#define	PIC_GPIO_B_IRQ		(PIC_IRQ_BASE + PIC_IRT_GPIO_B_INDEX)
+#define	PIC_USB_IRQ		(PIC_IRQ_BASE + PIC_IRT_USB_INDEX)
 
+#define	PIC_IRT_LAST_IRQ	PIC_USB_IRQ
+#define	PIC_IRQ_IS_EDGE_TRIGGERED(irq) (((irq) >= PIC_TIMER_IRQ(0)) && ((irq) <= PIC_TIMER_IRQ(7)))
+#define	PIC_IRQ_IS_IRT(irq)	(((irq) >= PIC_IRT_FIRST_IRQ) && ((irq) <= PIC_IRT_LAST_IRQ))
 
 extern struct mtx xlr_pic_lock;
 
-
-static __inline__ __uint32_t 
-pic_read_control(int haslock)
+static __inline uint32_t 
+pic_read_control(void)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	__uint32_t reg;
+	uint32_t reg;
 
-	if ((rmi_spin_mutex_safe) && (haslock == 0))
-	  mtx_lock_spin(&xlr_pic_lock);
+	mtx_lock_spin(&xlr_pic_lock);
 	xlr_read_reg(mmio, PIC_CTRL);
-	if ((rmi_spin_mutex_safe) && (haslock == 0))
-	  mtx_unlock_spin(&xlr_pic_lock);
-	return reg;
+	mtx_unlock_spin(&xlr_pic_lock);
+	return (reg);
 }
 
-static __inline__ void 
-pic_write_control(__uint32_t control, int haslock)
+static __inline void 
+pic_write_control(uint32_t control)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 
-	if ((rmi_spin_mutex_safe) && (haslock == 0))
-	  mtx_lock_spin(&xlr_pic_lock);
+	mtx_lock_spin(&xlr_pic_lock);
 	xlr_write_reg(mmio, PIC_CTRL, control);
-	if ((rmi_spin_mutex_safe) && (haslock == 0))
-	  mtx_unlock_spin(&xlr_pic_lock);
+	mtx_unlock_spin(&xlr_pic_lock);
 }
-static __inline__ void 
-pic_update_control(__uint32_t control, int haslock)
+
+static __inline void 
+pic_update_control(__uint32_t control)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 
-	if ((rmi_spin_mutex_safe) && (haslock == 0))
-	  mtx_lock_spin(&xlr_pic_lock);
+	mtx_lock_spin(&xlr_pic_lock);
 	xlr_write_reg(mmio, PIC_CTRL, (control | xlr_read_reg(mmio, PIC_CTRL)));
-	if ((rmi_spin_mutex_safe) && (haslock == 0))
-	  mtx_unlock_spin(&xlr_pic_lock);
+	mtx_unlock_spin(&xlr_pic_lock);
 }
 
-static __inline__ void 
-pic_ack(int irq, int haslock)
+static __inline void 
+pic_ack(int irq)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 
@@ -253,44 +188,51 @@ pic_ack(int irq, int haslock)
 		return;
 
 	if (PIC_IRQ_IS_EDGE_TRIGGERED(irq)) {
-	  if ((rmi_spin_mutex_safe) && (haslock == 0))
 		mtx_lock_spin(&xlr_pic_lock);
-	  xlr_write_reg(mmio, PIC_INT_ACK, (1 << (irq - PIC_IRQ_BASE)));
-	  if ((rmi_spin_mutex_safe) && (haslock == 0))
+		xlr_write_reg(mmio, PIC_INT_ACK, (1 << (irq - PIC_IRQ_BASE)));
 		mtx_unlock_spin(&xlr_pic_lock);
-		return;
 	}
 	return;
 }
 
-static inline void 
-pic_delayed_ack(int irq, int haslock)
+static __inline void 
+pic_delayed_ack(int irq)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 
 	if (!PIC_IRQ_IS_IRT(irq))
 		return;
-
 	if (!PIC_IRQ_IS_EDGE_TRIGGERED(irq)) {
-		if ((rmi_spin_mutex_safe)&& (haslock == 0))
-		  mtx_lock_spin(&xlr_pic_lock);
+		mtx_lock_spin(&xlr_pic_lock);
 		xlr_write_reg(mmio, PIC_INT_ACK, (1 << (irq - PIC_IRQ_BASE)));
-		if ((rmi_spin_mutex_safe) && (haslock == 0))
-		  mtx_unlock_spin(&xlr_pic_lock);
-		return;
+		mtx_unlock_spin(&xlr_pic_lock);
 	}
+	return;
 }
 
-static inline
-void pic_send_ipi(int cpu, int ipi, int haslock)
+static __inline
+void pic_send_ipi(int cpu, int ipi)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
+	int tid, pid;
+
+	tid = cpu & 0x3;
+	pid = (cpu >> 2) & 0x7;
+	xlr_write_reg(mmio, PIC_IPI, (pid << 20) | (tid << 16) | ipi);
+}
+
+static __inline
+void pic_setup_intr(int picintr, int irq, uint32_t cpumask)
 {
         xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-        int tid, pid;
+	int level;
 
-        tid = cpu & 0x3;
-        pid = (cpu >> 2) & 0x7;
-
-	xlr_write_reg(mmio, PIC_IPI,  (pid << 20) | (tid << 16) | ipi);
+	mtx_lock_spin(&xlr_pic_lock);
+	level = PIC_IRQ_IS_EDGE_TRIGGERED(irq);
+	xlr_write_reg(mmio, PIC_IRT_0(picintr), cpumask);
+	xlr_write_reg(mmio, PIC_IRT_1(picintr), ((1 << 31) | (level << 30) |
+	    (1 << 6) | irq));
+	mtx_unlock_spin(&xlr_pic_lock);
 }
 
-#endif				/* _RMI_PIC_H_ */
+#endif	/* _RMI_PIC_H_ */
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index 3945e9be116..b03275071b7 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -89,7 +89,6 @@ struct mtx xlr_pic_lock;
  * Parameters from boot loader
  */
 struct boot1_info xlr_boot1_info;
-struct xlr_loader_info xlr_loader_info;	/* FIXME : Unused */
 int xlr_run_mode;
 int xlr_argc;
 int32_t *xlr_argv, *xlr_envp;
@@ -574,8 +573,7 @@ void
 platform_ipi_send(int cpuid)
 {
 
-	pic_send_ipi(xlr_cpuid_to_hwtid[cpuid],
-	    platform_ipi_intrnum(), 0);
+	pic_send_ipi(xlr_cpuid_to_hwtid[cpuid], platform_ipi_intrnum());
 
 }
 
diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c
index d70979b80bf..6178985fe16 100644
--- a/sys/mips/rmi/xlr_pci.c
+++ b/sys/mips/rmi/xlr_pci.c
@@ -122,6 +122,7 @@ static struct rman irq_rman, port_rman, mem_rman;
 static void
 xlr_pci_init_resources(void)
 {
+
 	irq_rman.rm_start = 0;
 	irq_rman.rm_end = 255;
 	irq_rman.rm_type = RMAN_ARRAY;
@@ -150,6 +151,7 @@ xlr_pci_init_resources(void)
 static int
 xlr_pcib_probe(device_t dev)
 {
+
 	if (xlr_board_info.is_xls)
 		device_set_desc(dev, "XLS PCIe bus");
 	else
@@ -158,12 +160,13 @@ xlr_pcib_probe(device_t dev)
 	xlr_pci_init_resources();
 	xlr_pci_config_base = (void *)MIPS_PHYS_TO_KSEG1(DEFAULT_PCI_CONFIG_BASE);
 
-	return 0;
+	return (0);
 }
 
 static int
 xlr_pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
 {
+
 	switch (which) {
 	case PCIB_IVAR_DOMAIN:
 		*result = 0;
@@ -190,14 +193,16 @@ xlr_pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t result)
 static int
 xlr_pcib_maxslots(device_t dev)
 {
+
 	return (PCI_SLOTMAX);
 }
 
 static __inline__ void 
 disable_and_clear_cache_error(void)
 {
-	uint64_t lsu_cfg0 = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID);
+	uint64_t lsu_cfg0;
 
+	lsu_cfg0 = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID);
 	lsu_cfg0 = lsu_cfg0 & ~0x2e;
 	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID, lsu_cfg0);
 	/* Clear cache error log */
@@ -227,17 +232,17 @@ pci_cfg_read_32bit(uint32_t addr)
 	uint64_t cerr_cpu_log = 0;
 
 	disable_and_clear_cache_error();
-
 	temp = bswap32(*p);
 
 	/* Read cache err log */
-	cerr_cpu_log = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CERRLOG_REGID);
+	cerr_cpu_log = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU,
+	    LSU_CERRLOG_REGID);
 	if (cerr_cpu_log) {
 		/* Device don't exist. */
 		temp = ~0x0;
 	}
 	clear_and_enable_cache_error();
-	return temp;
+	return (temp);
 }
 
 static u_int32_t
@@ -258,7 +263,7 @@ xlr_pcib_read_config(device_t dev, u_int b, u_int s, u_int f,
 	else if (width == 2)
 		return ((data >> ((reg & 3) << 3)) & 0xffff);
 	else
-		return data;
+		return (data);
 }
 
 static void
@@ -294,14 +299,16 @@ xlr_pcib_write_config(device_t dev, u_int b, u_int s, u_int f,
 static int 
 xlr_pcib_attach(device_t dev)
 {
+
 	device_add_child(dev, "pci", 0);
 	bus_generic_attach(dev);
-	return 0;
+	return (0);
 }
 
 static void
 xlr_pcib_identify(driver_t * driver, device_t parent)
 {
+
 	if (xlr_board_info.is_xls) {
 		xlr_reg_t *pcie_mmio_le = xlr_io_mmio(XLR_IO_PCIE_1_OFFSET);
 		xlr_reg_t reg_link0 = xlr_read_reg(pcie_mmio_le, (0x80 >> 2));
@@ -325,14 +332,13 @@ xlr_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
 	int i;
 	device_t parent, tmp;
 
-
 	/* find the lane on which the slot is connected to */
 	tmp = dev;
 	while (1) {
 		parent = device_get_parent(tmp);
 		if (parent == NULL || parent == pcib) {
 			device_printf(dev, "Cannot find parent bus\n");
-			return ENXIO;
+			return (ENXIO);
 		}
 		if (strcmp(device_get_nameunit(parent), "pci0") == 0)
 			break;
@@ -353,7 +359,7 @@ xlr_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
 		pciirq = PIC_PCIE_LINK3_IRQ;
 		break;
 	default:
-		return ENXIO;
+		return (ENXIO);
 	}
 
 	irqs[0] = pciirq;
@@ -364,45 +370,49 @@ xlr_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
 	for (i = 1; i < count; i++)
 		irqs[i] = pciirq + 64 * i;
 
-	return 0;
+	return (0);
 }
 
 static int
 xlr_release_msi(device_t pcib, device_t dev, int count, int *irqs)
 {
-	device_printf(dev, "%s: msi release %d\n", device_get_nameunit(pcib), count);
-	return 0;
+	device_printf(dev, "%s: msi release %d\n", device_get_nameunit(pcib),
+	    count);
+	return (0);
 }
 
 static int
-xlr_map_msi(device_t pcib, device_t dev, int irq, uint64_t * addr, uint32_t * data)
+xlr_map_msi(device_t pcib, device_t dev, int irq, uint64_t * addr,
+    uint32_t * data)
 {
+
 	switch (irq) {
-		case PIC_PCIE_LINK0_IRQ:
-		case PIC_PCIE_LINK1_IRQ:
-		case PIC_PCIE_LINK2_IRQ:
-		case PIC_PCIE_LINK3_IRQ:
+	case PIC_PCIE_LINK0_IRQ:
+	case PIC_PCIE_LINK1_IRQ:
+	case PIC_PCIE_LINK2_IRQ:
+	case PIC_PCIE_LINK3_IRQ:
 		*addr = MIPS_MSI_ADDR(0);
 		*data = MIPS_MSI_DATA(irq);
-		return 0;
+		return (0);
 
 	default:
-		device_printf(dev, "%s: map_msi for irq %d  - ignored", device_get_nameunit(pcib),
-		    irq);
+		device_printf(dev, "%s: map_msi for irq %d  - ignored", 
+		    device_get_nameunit(pcib), irq);
 		return (ENXIO);
 	}
-
 }
 
 static void
 bridge_pcix_ack(void *arg)
 {
+
 	xlr_read_reg(xlr_io_mmio(XLR_IO_PCIX_OFFSET), 0x140 >> 2);
 }
 
 static void
 bridge_pcix_mask_ack(void *arg)
 {
+
 	xlr_mask_hard_irq(arg);
 	bridge_pcix_ack(arg);
 }
@@ -415,20 +425,28 @@ bridge_pcie_ack(void *arg)
 	xlr_reg_t *pcie_mmio_le = xlr_io_mmio(XLR_IO_PCIE_1_OFFSET);
 
 	switch (irq) {
-	case PIC_PCIE_LINK0_IRQ : reg = PCIE_LINK0_MSI_STATUS; break;
-	case PIC_PCIE_LINK1_IRQ : reg = PCIE_LINK1_MSI_STATUS; break;
-	case PIC_PCIE_LINK2_IRQ : reg = PCIE_LINK2_MSI_STATUS; break;
-	case PIC_PCIE_LINK3_IRQ : reg = PCIE_LINK3_MSI_STATUS; break;
+	case PIC_PCIE_LINK0_IRQ:
+		reg = PCIE_LINK0_MSI_STATUS;
+		break;
+	case PIC_PCIE_LINK1_IRQ:
+		reg = PCIE_LINK1_MSI_STATUS;
+		break;
+	case PIC_PCIE_LINK2_IRQ:
+		reg = PCIE_LINK2_MSI_STATUS;
+		break;
+	case PIC_PCIE_LINK3_IRQ:
+		reg = PCIE_LINK3_MSI_STATUS;
+		break;
 	default:
 		return;
 	}
-
 	xlr_write_reg(pcie_mmio_le, reg>>2, 0xffffffff);
 }
 
 static void
 bridge_pcie_mask_ack(void *arg)
 {
+
 	xlr_mask_hard_irq(arg);
 	bridge_pcie_ack(arg);
 }
@@ -440,8 +458,6 @@ mips_platform_pci_setup_intr(device_t dev, device_t child,
     driver_intr_t * intr, void *arg,
     void **cookiep)
 {
-	int level;
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 	int error = 0;
 	int xlrirq;
 
@@ -451,43 +467,29 @@ mips_platform_pci_setup_intr(device_t dev, device_t child,
 	if (rman_get_start(irq) != rman_get_end(irq)) {
 		device_printf(dev, "Interrupt allocation %lu != %lu\n",
 		    rman_get_start(irq), rman_get_end(irq));
-		return EINVAL;
+		return (EINVAL);
 	}
 	xlrirq = rman_get_start(irq);
 
 	if (strcmp(device_get_name(dev), "pcib") != 0)
-		return 0;
+		return (0);
 
 	if (xlr_board_info.is_xls == 0) {
-		if (rmi_spin_mutex_safe)
-			 mtx_lock_spin(&xlr_pic_lock);
-		level = PIC_IRQ_IS_EDGE_TRIGGERED(PIC_IRT_PCIX_INDEX);
-		xlr_write_reg(mmio, PIC_IRT_0_PCIX, 0x01);
-		xlr_write_reg(mmio, PIC_IRT_1_PCIX, ((1 << 31) | (level << 30) |
-		    (1 << 6) | (PIC_PCIX_IRQ)));
-		if (rmi_spin_mutex_safe)
-			 mtx_unlock_spin(&xlr_pic_lock);
 		xlr_cpu_establish_hardintr(device_get_name(child), filt,
 		    intr, arg, PIC_PCIX_IRQ, flags, cookiep,
 		    bridge_pcix_mask_ack, xlr_unmask_hard_irq,
 		    bridge_pcix_ack, NULL);
+		pic_setup_intr(PIC_IRT_PCIX_INDEX, PIC_PCIX_IRQ, 0x1);
 	} else {
-		if (rmi_spin_mutex_safe)
-			 mtx_lock_spin(&xlr_pic_lock);
-		xlr_write_reg(mmio, PIC_IRT_0_BASE + xlrirq - PIC_IRQ_BASE, 0x01);
-		xlr_write_reg(mmio, PIC_IRT_1_BASE + xlrirq - PIC_IRQ_BASE,
-		    ((1 << 31) | (1 << 30) | (1 << 6) | xlrirq));
-		if (rmi_spin_mutex_safe)
-			 mtx_unlock_spin(&xlr_pic_lock);
-
 		xlr_cpu_establish_hardintr(device_get_name(child), filt,
 		    intr, arg, xlrirq, flags, cookiep,
 	    	    bridge_pcie_mask_ack, xlr_unmask_hard_irq,
 		    bridge_pcie_ack, NULL);
+		pic_setup_intr(xlrirq - PIC_IRQ_BASE, xlrirq, 0x1);
 	}
 
-	return bus_generic_setup_intr(dev, child, irq, flags, filt, intr,
-	    arg, cookiep);
+	return (bus_generic_setup_intr(dev, child, irq, flags, filt, intr,
+	    arg, cookiep));
 }
 
 static int
@@ -498,7 +500,7 @@ mips_platform_pci_teardown_intr(device_t dev, device_t child,
 		/* if needed reprogram the pic to clear pcix related entry */
 		device_printf(dev, "teardown intr\n");
 	}
-	return bus_generic_teardown_intr(dev, child, irq, cookie);
+	return (bus_generic_teardown_intr(dev, child, irq, cookie));
 }
 
 static struct resource *
@@ -524,12 +526,12 @@ xlr_pci_alloc_resource(device_t bus, device_t child, int type, int *rid,
 		break;
 
 	default:
-		return 0;
+		return (0);
 	}
 
 	rv = rman_reserve_resource(rm, start, end, count, flags, child);
 	if (rv == 0)
-		return 0;
+		return (0);
 
 	rman_set_rid(rv, *rid);
 
@@ -547,13 +549,14 @@ xlr_pci_alloc_resource(device_t bus, device_t child, int type, int *rid,
 			return (NULL);
 		}
 	}
-	return rv;
+	return (rv);
 }
 
 static int
 xlr_pci_release_resource(device_t bus, device_t child, int type, int rid,
 		       struct resource *r)
 {
+
 	return (rman_release_resource(r));
 }
 
@@ -561,6 +564,7 @@ static int
 xlr_pci_activate_resource(device_t bus, device_t child, int type, int rid,
                       struct resource *r)
 {
+
 	return (rman_activate_resource(r));
 }
 
@@ -568,12 +572,14 @@ static int
 xlr_pci_deactivate_resource(device_t bus, device_t child, int type, int rid,
                           struct resource *r)
 {
+
 	return (rman_deactivate_resource(r));
 }
 
 static int
 mips_pci_route_interrupt(device_t bus, device_t dev, int pin)
 {
+
 	/*
 	 * Validate requested pin number.
 	 */
@@ -583,13 +589,13 @@ mips_pci_route_interrupt(device_t bus, device_t dev, int pin)
 	if (xlr_board_info.is_xls) {
 		switch (pin) {
 		case 1:
-			return PIC_PCIE_LINK0_IRQ;
+			return (PIC_PCIE_LINK0_IRQ);
 		case 2:
-			return PIC_PCIE_LINK1_IRQ;
+			return (PIC_PCIE_LINK1_IRQ);
 		case 3:
-			return PIC_PCIE_LINK2_IRQ;
+			return (PIC_PCIE_LINK2_IRQ);
 		case 4:
-			return PIC_PCIE_LINK3_IRQ;
+			return (PIC_PCIE_LINK3_IRQ);
 		}
 	} else {
 		if (pin == 1) {

From f6f7fc21c43b149903c13d5fa6f56a6825982cbd Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 25 Aug 2010 12:10:20 +0000
Subject: [PATCH 0237/1624] XLR PIC code update. - Fix a bug in xlr_pic_init
 (use irq in PIC_IRQ_IS_EDGE_TRIGGERED) - use new macro PIC_INTR_TO_IRQ() and
 PIC_IRT_x() in xlr_pic_init

---
 sys/mips/rmi/pic.h         |  8 +++++++-
 sys/mips/rmi/xlr_machdep.c | 11 ++++++-----
 2 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/sys/mips/rmi/pic.h b/sys/mips/rmi/pic.h
index 8043bd928df..35a8cd1ee98 100644
--- a/sys/mips/rmi/pic.h
+++ b/sys/mips/rmi/pic.h
@@ -93,7 +93,6 @@
 #define	PIC_TIMER_COUNT_0_BASE		0x120
 #define	PIC_TIMER_COUNT_1_BASE		0x130
 
-
 #define	PIC_IRT_0(picintr)	(PIC_IRT_0_BASE + (picintr))
 #define	PIC_IRT_1(picintr)	(PIC_IRT_1_BASE + (picintr))
 
@@ -102,7 +101,14 @@
 #define	PIC_TIMER_COUNT_0(i)	(PIC_TIMER_COUNT_0_BASE + (i))
 #define	PIC_TIMER_COUNT_1(i)	(PIC_TIMER_COUNT_0_BASE + (i))
 
+/*
+ * We use a simple mapping form PIC interrupts to CPU IRQs.
+ * The PIC interrupts 0-31 are mapped to CPU irq's 8-39.
+ * this leaves the lower 0-7 for the cpu interrupts (like 
+ * count/compare, msgrng) and 40-63 for IPIs
+ */
 #define	PIC_IRQ_BASE		8
+#define	PIC_INTR_TO_IRQ(i)	(PIC_IRQ_BASE + (i))
 #define	PIC_IRT_FIRST_IRQ	PIC_IRQ_BASE
 
 #define	PIC_WD_IRQ		(PIC_IRQ_BASE + PIC_IRT_WD_INDEX)
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index b03275071b7..f3f380e5b19 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -282,22 +282,23 @@ static void
 xlr_pic_init(void)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	int i, level;
+	int i, level, irq;
 
 	mtx_init(&xlr_pic_lock, "pic", NULL, MTX_SPIN);
 	xlr_write_reg(mmio, PIC_CTRL, 0);
 	for (i = 0; i < PIC_NUM_IRTS; i++) {
-		level = PIC_IRQ_IS_EDGE_TRIGGERED(i);
+		irq = PIC_INTR_TO_IRQ(i);
+		level = PIC_IRQ_IS_EDGE_TRIGGERED(irq);
 
 		/* Bind all PIC irqs to cpu 0 */
-		xlr_write_reg(mmio, PIC_IRT_0_BASE + i, 0x01);
+		xlr_write_reg(mmio, PIC_IRT_0(i), 0x01);
 
 		/*
 		 * Use local scheduling and high polarity for all IRTs
 		 * Invalidate all IRTs, by default
 		 */
-		xlr_write_reg(mmio, PIC_IRT_1_BASE + i, (level << 30) | (1 << 6) |
-		    (PIC_IRQ_BASE + i));
+		xlr_write_reg(mmio, PIC_IRT_1(i), (level << 30) | (1 << 6) |
+		    irq);
 	}
 }
 

From c2f84fc39a8910a53d36e17448a69fb224020888 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Wed, 25 Aug 2010 12:35:36 +0000
Subject: [PATCH 0238/1624] Add the necessary DTrace function pointers.

Sponsored by:	The FreeBSD Foundation
---
 sys/sys/dtrace_bsd.h | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/sys/sys/dtrace_bsd.h b/sys/sys/dtrace_bsd.h
index a14a1a160f3..2eded7b689a 100644
--- a/sys/sys/dtrace_bsd.h
+++ b/sys/sys/dtrace_bsd.h
@@ -37,6 +37,7 @@ struct trapframe;
 struct thread;
 struct vattr;
 struct vnode;
+struct reg;
 
 /*
  * Cyclic clock function type definition used to hook the cyclic
@@ -71,6 +72,14 @@ typedef void (*dtrace_doubletrap_func_t)(void);
 extern	dtrace_invop_func_t	dtrace_invop_func;
 extern	dtrace_doubletrap_func_t	dtrace_doubletrap_func;
 
+/* Pid provider hooks */
+typedef int (*dtrace_fasttrap_probe_ptr_t)(struct reg *);
+extern	dtrace_fasttrap_probe_ptr_t	dtrace_fasttrap_probe_ptr;
+typedef int (*dtrace_pid_probe_ptr_t)(struct reg *);
+extern	dtrace_pid_probe_ptr_t	dtrace_pid_probe_ptr;
+typedef int (*dtrace_return_probe_ptr_t)(struct reg *);
+extern	dtrace_return_probe_ptr_t	dtrace_return_probe_ptr;
+
 /* Virtual time hook function type. */
 typedef	void (*dtrace_vtime_switch_func_t)(struct thread *);
 

From 867a12afe1c75fbff1a1fd6abbd25adfe575562c Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 25 Aug 2010 13:37:55 +0000
Subject: [PATCH 0239/1624] Provide timecounter based on XLR PIC timer.

- Use timer 7 in XLR PIC as a 32 counter
- provide pic_init_timer(), pic_set_timer(), pic_timer_count32() and
  pic_timer_count() PIC timer operations.
- register this timer as platform_timecounter on rmi platform.
---
 sys/mips/rmi/pic.h         | 52 ++++++++++++++++++++++++++++++++++++++
 sys/mips/rmi/xlr_machdep.c | 22 ++++++++++++++++
 2 files changed, 74 insertions(+)

diff --git a/sys/mips/rmi/pic.h b/sys/mips/rmi/pic.h
index 35a8cd1ee98..d8860c5ae84 100644
--- a/sys/mips/rmi/pic.h
+++ b/sys/mips/rmi/pic.h
@@ -100,6 +100,8 @@
 #define	PIC_TIMER_MAXVAL_1(i)	(PIC_TIMER_MAXVAL_1_BASE + (i))
 #define	PIC_TIMER_COUNT_0(i)	(PIC_TIMER_COUNT_0_BASE + (i))
 #define	PIC_TIMER_COUNT_1(i)	(PIC_TIMER_COUNT_0_BASE + (i))
+#define	PIC_TIMER_HZ		66000000U
+
 
 /*
  * We use a simple mapping form PIC interrupts to CPU IRQs.
@@ -241,4 +243,54 @@ void pic_setup_intr(int picintr, int irq, uint32_t cpumask)
 	mtx_unlock_spin(&xlr_pic_lock);
 }
 
+static __inline void 
+pic_init_timer(int timer)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
+	uint32_t val;
+ 
+	mtx_lock_spin(&xlr_pic_lock);
+	val = xlr_read_reg(mmio, PIC_CTRL);
+	val |= (1 << (8 + timer));
+	xlr_write_reg(mmio, PIC_CTRL, val);
+	mtx_unlock_spin(&xlr_pic_lock);
+}
+ 
+static __inline void
+pic_set_timer(int timer, uint64_t maxval)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
+
+	xlr_write_reg(mmio, PIC_TIMER_MAXVAL_0(timer),
+	    (maxval & 0xffffffff)); 
+	xlr_write_reg(mmio, PIC_TIMER_MAXVAL_1(timer), 
+	    (maxval >> 32) & 0xffffffff);
+}
+
+static __inline uint32_t
+pic_timer_count32(int timer)
+ {
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
+
+	return (xlr_read_reg(mmio, PIC_TIMER_COUNT_0(timer))); 
+}
+
+/*
+ * The timer can wrap 32 bits between the two reads, so we
+ * need additional logic to detect that.
+ */
+static __inline uint64_t
+pic_timer_count(int timer)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
+	uint32_t tu1, tu2, tl;
+
+	tu1 = xlr_read_reg(mmio, PIC_TIMER_COUNT_1(timer)); 
+	tl = xlr_read_reg(mmio, PIC_TIMER_COUNT_0(timer)); 
+	tu2 = xlr_read_reg(mmio, PIC_TIMER_COUNT_1(timer)); 
+	if (tu2 != tu1)
+		tl = xlr_read_reg(mmio, PIC_TIMER_COUNT_0(timer));
+	return (((uint64_t)tu2 << 32) | tl);
+}
+
 #endif	/* _RMI_PIC_H_ */
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index f3f380e5b19..dd50b9272b0 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -278,14 +278,31 @@ mips_init(void)
 	mutex_init();
 }
 
+u_int
+platform_get_timecount(struct timecounter *tc __unused)
+{
+
+	return (0xffffffffU - pic_timer_count32(PIC_CLOCK_TIMER));
+}
+
 static void 
 xlr_pic_init(void)
 {
+	struct timecounter pic_timecounter = {
+		platform_get_timecount, /* get_timecount */
+		0,                      /* no poll_pps */
+		~0U,                    /* counter_mask */
+		PIC_TIMER_HZ,           /* frequency */
+		"XLRPIC",               /* name */
+		2000,                   /* quality (adjusted in code) */
+	};
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 	int i, level, irq;
 
 	mtx_init(&xlr_pic_lock, "pic", NULL, MTX_SPIN);
 	xlr_write_reg(mmio, PIC_CTRL, 0);
+
+	/* Initialize all IRT entries */
 	for (i = 0; i < PIC_NUM_IRTS; i++) {
 		irq = PIC_INTR_TO_IRQ(i);
 		level = PIC_IRQ_IS_EDGE_TRIGGERED(irq);
@@ -300,6 +317,11 @@ xlr_pic_init(void)
 		xlr_write_reg(mmio, PIC_IRT_1(i), (level << 30) | (1 << 6) |
 		    irq);
 	}
+
+	/* Setup timer 7 of PIC as a timestamp, no interrupts */
+	pic_init_timer(PIC_CLOCK_TIMER);
+	pic_set_timer(PIC_CLOCK_TIMER, ~UINT64_C(0));
+	platform_timecounter = &pic_timecounter;
 }
 
 static void

From f5efcd64f45b9247578c77e93768c3a2c81f5c86 Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Wed, 25 Aug 2010 15:29:12 +0000
Subject: [PATCH 0240/1624] Call devfs_populate_vp() from devfs_getattr(). It
 was possible that fstat(2) returned stale information through an open file
 descriptor.

---
 sys/fs/devfs/devfs_vnops.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/sys/fs/devfs/devfs_vnops.c b/sys/fs/devfs/devfs_vnops.c
index 2e106fe0af8..dfcdf1ac790 100644
--- a/sys/fs/devfs/devfs_vnops.c
+++ b/sys/fs/devfs/devfs_vnops.c
@@ -618,10 +618,18 @@ devfs_getattr(struct vop_getattr_args *ap)
 {
 	struct vnode *vp = ap->a_vp;
 	struct vattr *vap = ap->a_vap;
-	int error = 0;
+	int error;
 	struct devfs_dirent *de;
+	struct devfs_mount *dmp;
 	struct cdev *dev;
 
+	error = devfs_populate_vp(vp);
+	if (error != 0)
+		return (error);
+
+	dmp = VFSTODEVFS(vp->v_mount);
+	sx_xunlock(&dmp->dm_lock);
+
 	de = vp->v_data;
 	KASSERT(de != NULL, ("Null dirent in devfs_getattr vp=%p", vp));
 	if (vp->v_type == VDIR) {

From 194270c84bf0a529dcaf2161a6a91d3c74e77cd6 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Wed, 25 Aug 2010 16:23:50 +0000
Subject: [PATCH 0241/1624] Fix build of ppc32 loader.

---
 sys/boot/common/Makefile.inc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/boot/common/Makefile.inc b/sys/boot/common/Makefile.inc
index ff3ec3912b7..925e961bb49 100644
--- a/sys/boot/common/Makefile.inc
+++ b/sys/boot/common/Makefile.inc
@@ -9,7 +9,7 @@ SRCS+=	load_elf32.c load_elf32_obj.c reloc_elf32.c
 SRCS+=	load_elf64.c load_elf64_obj.c reloc_elf64.c
 .elif ${MACHINE} == "pc98"
 SRCS+=	load_elf32.c load_elf32_obj.c reloc_elf32.c
-.elif ${MACHINE_ARCH} == "powerpc" || ${MACHINE_CPUARCH} == "arm"
+.elif ${MACHINE_CPUARCH} == "arm"
 SRCS+=	load_elf32.c reloc_elf32.c
 .elif ${MACHINE_CPUARCH} == "powerpc"
 SRCS+=	load_elf32.c reloc_elf32.c

From c2d844d8141c024df011103a9521c23baade28ab Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Wed, 25 Aug 2010 18:09:51 +0000
Subject: [PATCH 0242/1624] If we read zero bytes from the directory, early out
 with ENOENT rather than forging ahead and interpreting garbage buffer content
 and dirent structures.

This change backs out r211684 which was essentially a no-op.

MFC after:	1 week
---
 sys/kern/vfs_default.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/sys/kern/vfs_default.c b/sys/kern/vfs_default.c
index bf037feb744..195e7354a3e 100644
--- a/sys/kern/vfs_default.c
+++ b/sys/kern/vfs_default.c
@@ -281,9 +281,13 @@ get_next_dirent(struct vnode *vp, struct dirent **dpp, char *dirbuf,
 		if (error)
 			return (error);
 
-		*cpos = dirbuf;
-		*len = uio.uio_offset - *off;
 		*off = uio.uio_offset;
+
+		*cpos = dirbuf;
+		*len = (dirbuflen - uio.uio_resid);
+
+		if (*len == 0)
+			return (ENOENT);
 	}
 
 	dp = (struct dirent *)(*cpos);

From 3e1700a5f84b8d583637cdba057d158b6dbac1f7 Mon Sep 17 00:00:00 2001
From: "Sergey A. Osokin" 
Date: Wed, 25 Aug 2010 18:11:01 +0000
Subject: [PATCH 0243/1624] Add one more new memory day for Russian Federation:
 the end of Second World War.

Obtained from:	http://kremlin.ru/acts/8444
---
 usr.bin/calendar/calendars/ru_RU.KOI8-R/calendar.military | 1 +
 1 file changed, 1 insertion(+)

diff --git a/usr.bin/calendar/calendars/ru_RU.KOI8-R/calendar.military b/usr.bin/calendar/calendars/ru_RU.KOI8-R/calendar.military
index 1b4e9c8880f..5188fc0dc57 100644
--- a/usr.bin/calendar/calendars/ru_RU.KOI8-R/calendar.military
+++ b/usr.bin/calendar/calendars/ru_RU.KOI8-R/calendar.military
@@ -16,6 +16,7 @@ LANG=ru_RU.KOI8-R
 10 ÉÀÌ	äÅÎØ ÐÏÂÅÄÙ ÒÕÓÓËÏÊ ÁÒÍÉÉ ÐÏÄ ËÏÍÁÎÄÏ×ÁÎÉÅÍ ðÅÔÒÁ ðÅÒ×ÏÇÏ ÎÁÄ Û×ÅÄÁÍÉ × ðÏÌÔÁ×ÓËÏÍ ÓÒÁÖÅÎÉÉ (1709 ÇÏÄ)
  9 Á×Ç	äÅÎØ ÐÅÒ×ÏÊ × ÒÏÓÓÉÊÓËÏÊ ÉÓÔÏÒÉÉ ÍÏÒÓËÏÊ ÐÏÂÅÄÙ ÒÕÓÓËÏÇÏ ÆÌÏÔÁ ÐÏÄ ËÏÍÁÎÄÏ×ÁÎÉÅÍ ðÅÔÒÁ ðÅÒ×ÏÇÏ ÎÁÄ Û×ÅÄÁÍÉ Õ ÍÙÓÁ çÁÎÇÕÔ (1714 ÇÏÄ)
 23 Á×Ç	äÅÎØ ÒÁÚÇÒÏÍÁ ÓÏ×ÅÔÓËÉÍÉ ×ÏÊÓËÁÍÉ ÎÅÍÅÃËÏ-ÆÁÛÉÓÔÓËÉÈ ×ÏÊÓË × ëÕÒÓËÏÊ ÂÉÔ×Å (1943 ÇÏÄ)
+ 2 ÓÅÎ	äÅÎØ ÏËÏÎÞÁÎÉÑ ÷ÔÏÒÏÊ ÍÉÒÏ×ÏÊ ×ÏÊÎÙ (1945 ÇÏÄ)
  8 ÓÅÎ	äÅÎØ âÏÒÏÄÉÎÓËÏÇÏ ÓÒÁÖÅÎÉÑ ÒÕÓÓËÏÊ ÁÒÍÉÉ ÐÏÄ ËÏÍÁÎÄÏ×ÁÎÉÅÍ í.é. ëÕÔÕÚÏ×Á Ó ÆÒÁÎÃÕÚÓËÏÊ ÁÒÍÉÅÊ (1812 ÇÏÄ)
 11 ÓÅÎ	äÅÎØ ÐÏÂÅÄÙ ÒÕÓÓËÏÊ ÜÓËÁÄÒÙ ÐÏÄ ËÏÍÁÎÄÏ×ÁÎÉÅÍ æ.æ. õÛÁËÏ×Á ÎÁÄ ÔÕÒÅÃËÏÊ ÜÓËÁÄÒÏÊ Õ ÍÙÓÁ ôÅÎÄÒÁ (1790 ÇÏÄ)
 21 ÓÅÎ	äÅÎØ ÐÏÂÅÄÙ ÒÕÓÓËÉÈ ÐÏÌËÏ× ×Ï ÇÌÁ×Å Ó ×ÅÌÉËÉÍ ËÎÑÚÅÍ äÍÉÔÒÉÅÍ äÏÎÓËÉÍ ÎÁÄ ÍÏÎÇÏÌÏ-ÔÁÔÁÒÓËÉÍÉ ×ÏÊÓËÁÍÉ × ëÕÌÉËÏ×ÓËÏÊ ÂÉÔ×Å (1380 ÇÏÄ)

From c2175767b7029b6847ff6a435d6ab7720d8b4a08 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Wed, 25 Aug 2010 19:12:05 +0000
Subject: [PATCH 0244/1624] Intel QPI chipsets actually provide two extra
 "non-core" PCI buses that provide PCI devices for various hardware such as
 memory controllers, etc. These PCI buses are not enumerated via ACPI however.
  Add qpi(4) psuedo bus and Host-PCI bridge drivers to enumerate these buses. 
 Currently the driver uses the CPU ID to determine the bridges' presence.

In collaboration with:	Joseph Golio @ Isilon Systems
MFC after:	2 weeks
---
 sys/conf/files.amd64 |   1 +
 sys/conf/files.i386  |   1 +
 sys/x86/pci/qpi.c    | 286 +++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 288 insertions(+)
 create mode 100644 sys/x86/pci/qpi.c

diff --git a/sys/conf/files.amd64 b/sys/conf/files.amd64
index 14e08d1490a..727a1027d9a 100644
--- a/sys/conf/files.amd64
+++ b/sys/conf/files.amd64
@@ -317,6 +317,7 @@ x86/isa/isa.c			standard
 x86/isa/isa_dma.c		standard
 x86/isa/nmi.c			standard
 x86/isa/orm.c			optional	isa
+x86/pci/qpi.c			standard
 x86/x86/io_apic.c		standard
 x86/x86/local_apic.c		standard
 x86/x86/mca.c			standard
diff --git a/sys/conf/files.i386 b/sys/conf/files.i386
index 078282c222c..f10a234a589 100644
--- a/sys/conf/files.i386
+++ b/sys/conf/files.i386
@@ -394,6 +394,7 @@ x86/isa/isa.c			optional isa
 x86/isa/isa_dma.c		optional isa
 x86/isa/nmi.c			standard
 x86/isa/orm.c			optional isa
+x86/pci/qpi.c			standard
 x86/x86/io_apic.c		optional apic
 x86/x86/local_apic.c		optional apic
 x86/x86/mca.c			standard
diff --git a/sys/x86/pci/qpi.c b/sys/x86/pci/qpi.c
new file mode 100644
index 00000000000..570f913e161
--- /dev/null
+++ b/sys/x86/pci/qpi.c
@@ -0,0 +1,286 @@
+/*-
+ * Copyright (c) 2010 Advanced Computing Technologies LLC
+ * Written by: John H. Baldwin 
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+/*
+ * This driver provides a psuedo-bus to enumerate the PCI buses
+ * present on a sytem using a QPI chipset.  It creates a qpi0 bus that
+ * is a child of nexus0 and then creates two Host-PCI bridges as a
+ * child of that.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include "pcib_if.h"
+
+struct qpi_device {
+	int	qd_pcibus;
+};
+
+static MALLOC_DEFINE(M_QPI, "qpidrv", "qpi system device");
+
+static void
+qpi_identify(driver_t *driver, device_t parent)
+{
+
+        /* Check CPUID to ensure this is an i7 CPU of some sort. */
+        if (!(cpu_vendor_id == CPU_VENDOR_INTEL && CPUID_TO_FAMILY(cpu_id) &&
+	    (CPUID_TO_MODEL(cpu_id) == 0x1a || CPUID_TO_MODEL(cpu_id) == 0x2c)))
+                return;
+
+        /* PCI config register access is required. */
+        if (pci_cfgregopen() == 0)
+                return;
+
+	/* Add a qpi bus device. */
+	if (BUS_ADD_CHILD(parent, 20, "qpi", -1) == NULL)
+		panic("Failed to add qpi bus");
+}
+
+static int
+qpi_probe(device_t dev)
+{
+
+	device_set_desc(dev, "QPI system bus");
+	return (BUS_PROBE_SPECIFIC);
+}
+
+static int
+qpi_attach(device_t dev)
+{
+	struct qpi_device *qdev;
+	device_t child;
+
+	/*
+	 * Add two Host-PCI bridge devices, one for PCI bus 254 and
+	 * one for PCI bus 255.
+	 */
+	child = BUS_ADD_CHILD(dev, 0, "pcib", -1);
+	if (child == NULL)
+		panic("%s: failed to add pci bus 254",
+		    device_get_nameunit(dev));
+	qdev = malloc(sizeof(struct qpi_device), M_QPI, M_WAITOK);
+	qdev->qd_pcibus = 254;
+	device_set_ivars(child, qdev);
+
+	child = BUS_ADD_CHILD(dev, 0, "pcib", -1);
+	if (child == NULL)
+		panic("%s: failed to add pci bus 255",
+		    device_get_nameunit(dev));
+	qdev = malloc(sizeof(struct qpi_device), M_QPI, M_WAITOK);
+	qdev->qd_pcibus = 255;
+	device_set_ivars(child, qdev);
+
+	return (bus_generic_attach(dev));
+}
+
+static int
+qpi_print_child(device_t bus, device_t child)
+{
+	struct qpi_device *qdev;
+	int retval = 0;
+
+	qdev = device_get_ivars(child);
+	retval += bus_print_child_header(bus, child);
+	if (qdev->qd_pcibus != -1)
+		retval += printf(" pcibus %d", qdev->qd_pcibus);
+	retval += bus_print_child_footer(bus, child);
+
+	return (retval);
+}
+
+static int
+qpi_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
+{
+	struct qpi_device *qdev;
+
+	qdev = device_get_ivars(child);
+	switch (which) {
+	case PCIB_IVAR_BUS:
+		*result = qdev->qd_pcibus;
+		break;
+	default:
+		return (ENOENT);
+	}
+	return (0);
+}
+
+static device_method_t qpi_methods[] = {
+	/* Device interface */
+	DEVMETHOD(device_identify,	qpi_identify),
+	DEVMETHOD(device_probe,		qpi_probe),
+	DEVMETHOD(device_attach,	qpi_attach),
+	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
+	DEVMETHOD(device_suspend,	bus_generic_suspend),
+	DEVMETHOD(device_resume,	bus_generic_resume),
+
+	/* Bus interface */
+	DEVMETHOD(bus_print_child,	qpi_print_child),
+	DEVMETHOD(bus_add_child,	bus_generic_add_child),
+	DEVMETHOD(bus_read_ivar,	qpi_read_ivar),
+	DEVMETHOD(bus_alloc_resource,	bus_generic_alloc_resource),
+	DEVMETHOD(bus_release_resource,	bus_generic_release_resource),
+	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
+	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
+	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
+	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
+
+	{ 0, 0 }
+};
+
+static devclass_t qpi_devclass;
+
+DEFINE_CLASS_0(qpi, qpi_driver, qpi_methods, 0);
+DRIVER_MODULE(qpi, nexus, qpi_driver, qpi_devclass, 0, 0);
+
+static int
+qpi_pcib_probe(device_t dev)
+{
+
+	device_set_desc(dev, "QPI Host-PCI bridge");
+	return (BUS_PROBE_SPECIFIC);
+}
+
+static int
+qpi_pcib_attach(device_t dev)
+{
+
+	device_add_child(dev, "pci", pcib_get_bus(dev));      
+        return (bus_generic_attach(dev));
+}
+
+static int
+qpi_pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
+{
+
+	switch (which) {
+	case PCIB_IVAR_DOMAIN:
+		*result = 0;
+		return (0);
+	case PCIB_IVAR_BUS:
+		*result = pcib_get_bus(dev);
+		return (0);
+	default:
+		return (ENOENT);
+	}
+}
+
+static uint32_t
+qpi_pcib_read_config(device_t dev, u_int bus, u_int slot, u_int func,
+    u_int reg, int bytes)
+{
+
+	return (pci_cfgregread(bus, slot, func, reg, bytes));
+}
+
+static void
+qpi_pcib_write_config(device_t dev, u_int bus, u_int slot, u_int func,
+    u_int reg, uint32_t data, int bytes)
+{
+
+	pci_cfgregwrite(bus, slot, func, reg, data, bytes);
+}
+
+static int
+qpi_pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount,
+    int *irqs)
+{
+	device_t bus;
+
+	bus = device_get_parent(pcib);
+	return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount,
+	    irqs));
+}
+
+static int
+qpi_pcib_alloc_msix(device_t pcib, device_t dev, int *irq)
+{
+	device_t bus;
+
+	bus = device_get_parent(pcib);
+	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
+}
+
+static int
+qpi_pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
+    uint32_t *data)
+{
+	device_t bus;
+
+	bus = device_get_parent(pcib);
+	return (PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data));
+}
+
+static device_method_t qpi_pcib_methods[] = {
+	/* Device interface */
+	DEVMETHOD(device_probe,		qpi_pcib_probe),
+	DEVMETHOD(device_attach,	qpi_pcib_attach),
+	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
+	DEVMETHOD(device_suspend,	bus_generic_suspend),
+	DEVMETHOD(device_resume,	bus_generic_resume),
+
+	/* Bus interface */
+	DEVMETHOD(bus_print_child,	bus_generic_print_child),
+	DEVMETHOD(bus_read_ivar,	qpi_pcib_read_ivar),
+	DEVMETHOD(bus_alloc_resource,	bus_generic_alloc_resource),
+	DEVMETHOD(bus_release_resource,	bus_generic_release_resource),
+	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
+	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
+	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
+	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
+
+	/* pcib interface */
+	DEVMETHOD(pcib_maxslots,	pcib_maxslots),
+	DEVMETHOD(pcib_read_config,	qpi_pcib_read_config),
+	DEVMETHOD(pcib_write_config,	qpi_pcib_write_config),
+	DEVMETHOD(pcib_alloc_msi,	qpi_pcib_alloc_msi),
+	DEVMETHOD(pcib_release_msi,	pcib_release_msi),
+	DEVMETHOD(pcib_alloc_msix,	qpi_pcib_alloc_msix),
+	DEVMETHOD(pcib_release_msix,	pcib_release_msix),
+	DEVMETHOD(pcib_map_msi,		qpi_pcib_map_msi),
+
+	{0, 0}
+};
+
+static devclass_t qpi_pcib_devclass;
+
+DEFINE_CLASS_0(pcib, qpi_pcib_driver, qpi_pcib_methods, 0);
+DRIVER_MODULE(pcib, qpi, qpi_pcib_driver, qpi_pcib_devclass, 0, 0);

From 8bddaf900773c80269d0416da191e8b50ff695a3 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Wed, 25 Aug 2010 20:37:58 +0000
Subject: [PATCH 0245/1624] Correctly ensure that the CPU family is 0x6, not
 non-zero.

Submitted by:	Dimitry Andric
---
 sys/x86/pci/qpi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/x86/pci/qpi.c b/sys/x86/pci/qpi.c
index 570f913e161..169c1cd6102 100644
--- a/sys/x86/pci/qpi.c
+++ b/sys/x86/pci/qpi.c
@@ -62,7 +62,8 @@ qpi_identify(driver_t *driver, device_t parent)
 {
 
         /* Check CPUID to ensure this is an i7 CPU of some sort. */
-        if (!(cpu_vendor_id == CPU_VENDOR_INTEL && CPUID_TO_FAMILY(cpu_id) &&
+        if (!(cpu_vendor_id == CPU_VENDOR_INTEL &&
+	    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
 	    (CPUID_TO_MODEL(cpu_id) == 0x1a || CPUID_TO_MODEL(cpu_id) == 0x2c)))
                 return;
 

From f61ce5684543171aecae5890fc2ae9d115441ba6 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Wed, 25 Aug 2010 20:48:24 +0000
Subject: [PATCH 0246/1624] Allow ABIs to provide their own LIBC_ARCH in a more
 generic way. As a side effect, this fixes the build on powerpc64.

Reviewed by:	imp
---
 lib/libc/Makefile | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/lib/libc/Makefile b/lib/libc/Makefile
index e29c7d99b7c..dae4db3c8e6 100644
--- a/lib/libc/Makefile
+++ b/lib/libc/Makefile
@@ -5,10 +5,11 @@ SHLIBDIR?= /lib
 
 .include 
 
-# We have to special case powerpc and powerpc64, since they mostly have
-# the same source implementation.  libc is very different due to large
-# ABI differences.
-.if ${MACHINE_ARCH} == "powerpc"
+# Pick the current architecture directory for libc. In general, this is
+# named MACHINE_CPUARCH, but some ABIs are different enough to require
+# their own libc, so allow a directory named MACHINE_ARCH to override this.
+
+.if exists(${.CURDIR}/${MACHINE_ARCH})
 LIBC_ARCH=${MACHINE_ARCH}
 .else
 LIBC_ARCH=${MACHINE_CPUARCH}

From bc339276fb5a952fe6086608843c60021f90c31b Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Wed, 25 Aug 2010 20:52:40 +0000
Subject: [PATCH 0247/1624] Check opcode for short jump as well.  Some option
 ROMs do short jumps (e.g., some NVIDIA video cards) and we were not able to
 do POST while resuming because we only honored long jump.

MFC after:	3 days
---
 sys/compat/x86bios/x86bios.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/compat/x86bios/x86bios.c b/sys/compat/x86bios/x86bios.c
index 224520c2c4f..a8bd69a3f09 100644
--- a/sys/compat/x86bios/x86bios.c
+++ b/sys/compat/x86bios/x86bios.c
@@ -801,7 +801,8 @@ x86bios_get_orm(uint32_t offset)
 
 	/* Does the shadow ROM contain BIOS POST code for x86? */
 	p = x86bios_offset(offset);
-	if (p == NULL || p[0] != 0x55 || p[1] != 0xaa || p[3] != 0xe9)
+	if (p == NULL || p[0] != 0x55 || p[1] != 0xaa ||
+	    (p[3] != 0xe9 && p[3] != 0xeb))
 		return (NULL);
 
 	return (p);

From 97e6525d6a6cb1ef5b1b65b3f7b3c74a051c8e2b Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Wed, 25 Aug 2010 21:03:50 +0000
Subject: [PATCH 0248/1624] Add x86bios_set_intr() to set interrupt vectors for
 real mode and simplify x86bios_get_intr() a little.

---
 sys/compat/x86bios/x86bios.c | 17 ++++++++++++++---
 sys/compat/x86bios/x86bios.h |  1 +
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/sys/compat/x86bios/x86bios.c b/sys/compat/x86bios/x86bios.c
index a8bd69a3f09..465a076e16f 100644
--- a/sys/compat/x86bios/x86bios.c
+++ b/sys/compat/x86bios/x86bios.c
@@ -203,6 +203,13 @@ x86bios_get_intr(int intno)
 	return (readl(BIOS_PADDRTOVADDR(intno * 4)));
 }
 
+void
+x86bios_set_intr(int intno, uint32_t saddr)
+{
+
+	writel(BIOS_PADDRTOVADDR(intno * 4), saddr);
+}
+
 void
 x86bios_intr(struct x86regs *regs, int intno)
 {
@@ -619,11 +626,15 @@ x86bios_call(struct x86regs *regs, uint16_t seg, uint16_t off)
 uint32_t
 x86bios_get_intr(int intno)
 {
-	uint32_t *iv;
 
-	iv = (uint32_t *)((vm_offset_t)x86bios_ivt + intno * 4);
+	return (le32toh(*((uint32_t *)x86bios_ivt + intno)));
+}
 
-	return (le32toh(*iv));
+void
+x86bios_set_intr(int intno, uint32_t saddr)
+{
+
+	*((uint32_t *)x86bios_ivt + intno) = htole32(saddr);
 }
 
 void
diff --git a/sys/compat/x86bios/x86bios.h b/sys/compat/x86bios/x86bios.h
index f4749329f89..491367de4f1 100644
--- a/sys/compat/x86bios/x86bios.h
+++ b/sys/compat/x86bios/x86bios.h
@@ -151,6 +151,7 @@ void	 x86bios_init_regs(struct x86regs *regs);
 void	 x86bios_intr(struct x86regs *regs, int intno);
 int	 x86bios_match_device(uint32_t offset, device_t dev);
 void	*x86bios_offset(uint32_t offset);
+void	 x86bios_set_intr(int intno, uint32_t saddr);
 __END_DECLS
 
 #endif /* !_X86BIOS_H_ */

From db1cea00adfce315c94c26966f56e7ec3977f624 Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Wed, 25 Aug 2010 21:13:23 +0000
Subject: [PATCH 0249/1624] Increase maximum number of page table entries per
 VM86 context from 8 to 24 pages, yet again.  Now we can allocate a whole
 segment, which is required for shadowing option ROM images, for example.

---
 sys/i386/include/vm86.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/i386/include/vm86.h b/sys/i386/include/vm86.h
index b574e58e23e..e33d72008f2 100644
--- a/sys/i386/include/vm86.h
+++ b/sys/i386/include/vm86.h
@@ -100,7 +100,7 @@ struct vm86frame {
 #define vmf_eflags	eflags.r_ex
 };
 
-#define VM86_PMAPSIZE	8
+#define VM86_PMAPSIZE	24
 #define VMAP_MALLOC	1	/* page was malloced by us */
 
 struct vm86context {

From 81f6480d42b7f4ee008398fcc839c489bc1a140f Mon Sep 17 00:00:00 2001
From: Edward Tomasz Napierala 
Date: Wed, 25 Aug 2010 21:32:08 +0000
Subject: [PATCH 0250/1624] Revert r210194, adding a comment explaining why
 calls to chgproccnt() in unionfs are actually needed.  I have a better fix in
 trasz_hrl p4 branch, but now is not a good moment to commit it.

Reported by:	Alex Kozlov
---
 sys/fs/unionfs/union_subr.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/sys/fs/unionfs/union_subr.c b/sys/fs/unionfs/union_subr.c
index dbed54e6298..2e74844d4d4 100644
--- a/sys/fs/unionfs/union_subr.c
+++ b/sys/fs/unionfs/union_subr.c
@@ -775,6 +775,11 @@ unionfs_mkshadowdir(struct unionfs_mount *ump, struct vnode *udvp,
 	/* Authority change to root */
 	rootinfo = uifind((uid_t)0);
 	cred = crdup(cnp->cn_cred);
+	/*
+	 * The calls to chgproccnt() are needed to compensate for change_ruid()
+	 * calling chgproccnt().
+	 */
+	chgproccnt(cred->cr_ruidinfo, 1, 0);
 	change_euid(cred, rootinfo);
 	change_ruid(cred, rootinfo);
 	change_svuid(cred, (uid_t)0);
@@ -824,6 +829,7 @@ unionfs_mkshadowdir_free_out:
 
 unionfs_mkshadowdir_abort:
 	cnp->cn_cred = credbk;
+	chgproccnt(cred->cr_ruidinfo, -1, 0);
 	crfree(cred);
 
 	return (error);

From a73f383ee91d6e75879bc16d7dd2a91a0630b369 Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Wed, 25 Aug 2010 22:09:02 +0000
Subject: [PATCH 0251/1624] Add an experimental feature to shadow video BIOS. 
 Long ago, this trick was supported by many BIOSes to improve performance of
 VESA BIOS calls for real mode OSes but it is not our intention here. 
 However, this may help some platforms where the video ROMs are inaccessible
 after suspend, for example. Note it may consume up to 64K bytes of contiguous
 memory depending on video controller model when it is enabled.  This feature
 can be disabled by setting zero to 'debug.vesa.shadow_rom' loader tunable via
 loader(8) or loader.conf(5).  The default is 1 (enabled), for now.

---
 sys/dev/fb/vesa.c | 67 ++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 57 insertions(+), 10 deletions(-)

diff --git a/sys/dev/fb/vesa.c b/sys/dev/fb/vesa.c
index d369175bb92..96a8aaa8c92 100644
--- a/sys/dev/fb/vesa.c
+++ b/sys/dev/fb/vesa.c
@@ -42,6 +42,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -61,6 +62,8 @@ __FBSDID("$FreeBSD$");
 
 #include 
 
+#define	VESA_BIOS_OFFSET	0xc0000
+#define	VESA_PALETTE_SIZE	(256 * 4)
 #define	VESA_VIA_CLE266		"VIA CLE266\r\n"
 
 #ifndef VESA_DEBUG
@@ -83,11 +86,21 @@ static ssize_t vesa_state_buf_size = 0;
 
 static u_char *vesa_palette = NULL;
 static uint32_t vesa_palette_offs = 0;
-#define	VESA_PALETTE_SIZE	(256 * 4)
+
+static void *vesa_bios = NULL;
+static uint32_t vesa_bios_offs = VESA_BIOS_OFFSET;
+static uint32_t vesa_bios_int10 = 0;
+static size_t vesa_bios_size = 0;
 
 /* VESA video adapter */
 static video_adapter_t *vesa_adp = NULL;
 
+SYSCTL_NODE(_debug, OID_AUTO, vesa, CTLFLAG_RD, NULL, "VESA debugging");
+static int vesa_shadow_rom = 1;
+TUNABLE_INT("debug.vesa.shadow_rom", &vesa_shadow_rom);
+SYSCTL_INT(_debug_vesa, OID_AUTO, shadow_rom, CTLFLAG_RDTUN, &vesa_shadow_rom,
+    1, "Enable video BIOS shadow");
+
 /* VESA functions */
 #if 0
 static int			vesa_nop(void);
@@ -242,7 +255,7 @@ vesa_bios_post(void)
 	device_t dev;
 	int count, i, is_pci;
 
-	if (x86bios_get_orm(0xc0000) == NULL)
+	if (x86bios_get_orm(vesa_bios_offs) == NULL)
 		return (1);
 
 	dev = NULL;
@@ -253,7 +266,7 @@ vesa_bios_post(void)
 	if (dc != NULL && devclass_get_devices(dc, &devs, &count) == 0) {
 		for (i = 0; i < count; i++)
 			if (device_get_flags(devs[i]) != 0 &&
-			    x86bios_match_device(0xc0000, devs[i])) {
+			    x86bios_match_device(vesa_bios_offs, devs[i])) {
 				dev = devs[i];
 				is_pci = 1;
 				break;
@@ -279,7 +292,8 @@ vesa_bios_post(void)
 		    (pci_get_function(dev) & 0x07);
 	}
 	regs.R_DL = 0x80;
-	x86bios_call(®s, 0xc000, 0x0003);
+	x86bios_call(®s, X86BIOS_PHYSTOSEG(vesa_bios_offs + 3),
+	    X86BIOS_PHYSTOOFF(vesa_bios_offs + 3));
 
 	if (x86bios_get_intr(0x10) == 0)
 		return (1);
@@ -754,6 +768,7 @@ vesa_bios_init(void)
 	size_t bsize;
 	size_t msize;
 	void *vmbuf;
+	uint8_t *vbios;
 	uint32_t offs;
 	uint16_t vers;
 	int is_via_cle266;
@@ -765,22 +780,44 @@ vesa_bios_init(void)
 
 	has_vesa_bios = FALSE;
 	vesa_adp_info = NULL;
+	vesa_bios_offs = VESA_BIOS_OFFSET;
 	vesa_vmode_max = 0;
 	vesa_vmode[0].vi_mode = EOT;
 
 	/*
 	 * If the VBE real mode interrupt vector is not found, try BIOS POST.
 	 */
-	if (x86bios_get_intr(0x10) == 0) {
+	vesa_bios_int10 = x86bios_get_intr(0x10);
+	if (vesa_bios_int10 == 0) {
 		if (vesa_bios_post() != 0)
 			return (1);
-		if (bootverbose) {
-			offs = x86bios_get_intr(0x10);
-			printf("VESA: interrupt vector installed (0x%x)\n",
-			    BIOS_SADDRTOLADDR(offs));
-		}
+		vesa_bios_int10 = x86bios_get_intr(0x10);
+		if (vesa_bios_int10 == 0)
+			return (1);
 	}
 
+	/*
+	 * Shadow video ROM.
+	 */
+	offs = BIOS_SADDRTOLADDR(vesa_bios_int10);
+	if (vesa_shadow_rom) {
+		vbios = x86bios_get_orm(vesa_bios_offs);
+		if (vbios != NULL) {
+			vesa_bios_size = vbios[2] * 512;
+			vesa_bios = x86bios_alloc(&vesa_bios_offs,
+			    vesa_bios_size, M_WAITOK);
+			memcpy(vesa_bios, vbios, vesa_bios_size);
+			offs = offs - VESA_BIOS_OFFSET + vesa_bios_offs;
+			offs = (X86BIOS_PHYSTOSEG(offs) << 16) +
+			    X86BIOS_PHYSTOOFF(offs);
+			x86bios_set_intr(0x10, offs);
+		} else
+			printf("VESA: failed to shadow video ROM\n");
+	}
+	if (bootverbose)
+		printf("VESA: INT 0x10 vector 0x%04x:0x%04x\n",
+		    X86BIOS_PHYSTOSEG(offs), X86BIOS_PHYSTOOFF(offs));
+
 	x86bios_init_regs(®s);
 	regs.R_AX = 0x4f00;
 
@@ -1011,6 +1048,12 @@ vesa_bios_init(void)
 	return (0);
 
 fail:
+	if (vesa_bios != NULL) {
+		x86bios_set_intr(0x10, vesa_bios_int10);
+		vesa_bios_offs = VESA_BIOS_OFFSET;
+		x86bios_free(vesa_bios, vesa_bios_size);
+		vesa_bios = NULL;
+	}
 	if (vmbuf != NULL)
 		x86bios_free(vmbuf, sizeof(buf));
 	if (vesa_adp_info != NULL) {
@@ -1862,6 +1905,10 @@ vesa_unload(void)
 		}
 	}
 
+	if (vesa_bios != NULL) {
+		x86bios_set_intr(0x10, vesa_bios_int10);
+		x86bios_free(vesa_bios, vesa_bios_size);
+	}
 	if (vesa_adp_info != NULL)
 		free(vesa_adp_info, M_DEVBUF);
 	if (vesa_oemstr != NULL)

From 2b137859310f69bd48e2f5784336c3ae4fa70d6a Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Wed, 25 Aug 2010 22:48:18 +0000
Subject: [PATCH 0252/1624] Fix a debugging message under bootverbose.  This
 address is not linear.

---
 sys/dev/fb/vesa.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/fb/vesa.c b/sys/dev/fb/vesa.c
index 96a8aaa8c92..5fa4eb42ef2 100644
--- a/sys/dev/fb/vesa.c
+++ b/sys/dev/fb/vesa.c
@@ -816,7 +816,7 @@ vesa_bios_init(void)
 	}
 	if (bootverbose)
 		printf("VESA: INT 0x10 vector 0x%04x:0x%04x\n",
-		    X86BIOS_PHYSTOSEG(offs), X86BIOS_PHYSTOOFF(offs));
+		    (offs >> 16) & 0xffff, offs & 0xffff);
 
 	x86bios_init_regs(®s);
 	regs.R_AX = 0x4f00;

From d7dc2db43420265b37084554b5dd55887fcd8c87 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Wed, 25 Aug 2010 23:23:00 +0000
Subject: [PATCH 0253/1624] Add mutex locking for the call to replay_prune() in
 replay_setsize(), since replay_prune() expects the rc_lock to be held when it
 is called.

MFC after:	2 weeks
---
 sys/rpc/replay.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/rpc/replay.c b/sys/rpc/replay.c
index c89def576a5..2e92017689a 100644
--- a/sys/rpc/replay.c
+++ b/sys/rpc/replay.c
@@ -90,8 +90,10 @@ void
 replay_setsize(struct replay_cache *rc, size_t newmaxsize)
 {
 
+	mtx_lock(&rc->rc_lock);
 	rc->rc_maxsize = newmaxsize;
 	replay_prune(rc);
+	mtx_unlock(&rc->rc_lock);
 }
 
 void

From 4d7ba083240e94eef3d676beb195eb44ed0b9af6 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 26 Aug 2010 05:16:00 +0000
Subject: [PATCH 0254/1624] Rescue doesn't work for n64.

---
 Makefile.mips | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/Makefile.mips b/Makefile.mips
index b720e3de68b..7b70b9d3fcc 100644
--- a/Makefile.mips
+++ b/Makefile.mips
@@ -1,2 +1,5 @@
 # $FreeBSD$
 
+.if ${TARGET_ABI} == "n64"
+MK_RESCUE=no
+.endif

From b86e178f05e0750a77e2321395ac2d2b1b9a5940 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 26 Aug 2010 05:25:51 +0000
Subject: [PATCH 0255/1624] Ugly kludge to paper over some kind of ld bug
 and/or misuse: don't build uathload on mips n64 either.

---
 usr.sbin/Makefile | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/usr.sbin/Makefile b/usr.sbin/Makefile
index e658fedb9bd..37ab863030c 100644
--- a/usr.sbin/Makefile
+++ b/usr.sbin/Makefile
@@ -412,7 +412,8 @@ _crunch=	crunch
 .endif
 
 .if ${MK_USB} != "no"
-.if ${MACHINE_ARCH} != "ia64"
+.if ${MACHINE_ARCH} != "ia64" && \
+	!(${MACHINE_ARCH} == "mips" && ${TARGET_ABI} == "n64")
 _uathload=	uathload
 .endif
 _uhsoctl=	uhsoctl

From 6b932eca796b2b80b5295abc853f56cb3f8a15f9 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Thu, 26 Aug 2010 07:09:48 +0000
Subject: [PATCH 0256/1624] Decrease rdlock count only when thread unlocked a
 reader lock.

MFC after:	3 days
---
 lib/libthr/thread/thr_rtld.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libthr/thread/thr_rtld.c b/lib/libthr/thread/thr_rtld.c
index 4db08bd617c..2560a941d3a 100644
--- a/lib/libthr/thread/thr_rtld.c
+++ b/lib/libthr/thread/thr_rtld.c
@@ -149,8 +149,8 @@ _thr_rtld_lock_release(void *lock)
 	
 	state = l->lock.rw_state;
 	if (_thr_rwlock_unlock(&l->lock) == 0) {
-		curthread->rdlock_count--;
 		if ((state & URWLOCK_WRITE_OWNER) == 0) {
+			curthread->rdlock_count--;
 			THR_CRITICAL_LEAVE(curthread);
 		} else {
 			_thr_signal_unblock(curthread);

From 1ac3d5022cacf6981a390ced873868224eef85ff Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Thu, 26 Aug 2010 09:04:27 +0000
Subject: [PATCH 0257/1624] eliminate unused code.

---
 lib/libthr/thread/thr_exit.c    | 12 ------------
 lib/libthr/thread/thr_private.h |  5 -----
 2 files changed, 17 deletions(-)

diff --git a/lib/libthr/thread/thr_exit.c b/lib/libthr/thread/thr_exit.c
index a875d14a27c..e6facd9d85b 100644
--- a/lib/libthr/thread/thr_exit.c
+++ b/lib/libthr/thread/thr_exit.c
@@ -55,16 +55,6 @@ _thread_exit(const char *fname, int lineno, const char *msg)
 	abort();
 }
 
-/*
- * Only called when a thread is cancelled.  It may be more useful
- * to call it from pthread_exit() if other ways of asynchronous or
- * abnormal thread termination can be found.
- */
-void
-_thr_exit_cleanup(void)
-{
-}
-
 void
 _pthread_exit(void *status)
 {
@@ -84,8 +74,6 @@ _pthread_exit(void *status)
 	curthread->cancel_enable = 0;
 	curthread->cancel_async = 0;
 	
-	_thr_exit_cleanup();
-
 	/* Save the return value: */
 	curthread->ret = status;
 	while (curthread->cleanup != NULL) {
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index fd79b789e6a..f92913bc92b 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -623,7 +623,6 @@ void	_mutex_fork(struct pthread *curthread) __hidden;
 void	_libpthread_init(struct pthread *) __hidden;
 struct pthread *_thr_alloc(struct pthread *) __hidden;
 void	_thread_exit(const char *, int, const char *) __hidden __dead2;
-void	_thr_exit_cleanup(void) __hidden;
 int	_thr_ref_add(struct pthread *, struct pthread *, int) __hidden;
 void	_thr_ref_delete(struct pthread *, struct pthread *) __hidden;
 void	_thr_ref_delete_unlocked(struct pthread *, struct pthread *) __hidden;
@@ -635,7 +634,6 @@ void	_thr_stack_free(struct pthread_attr *) __hidden;
 void	_thr_free(struct pthread *, struct pthread *) __hidden;
 void	_thr_gc(struct pthread *) __hidden;
 void    _thread_cleanupspecific(void) __hidden;
-void    _thread_dump_info(void) __hidden;
 void	_thread_printf(int, const char *, ...) __hidden;
 void	_thr_spinlock_init(void) __hidden;
 void	_thr_cancel_enter(struct pthread *) __hidden;
@@ -671,9 +669,6 @@ int	_schedparam_to_rtp(int policy, const struct sched_param *param,
 void	_thread_bp_create(void);
 void	_thread_bp_death(void);
 int	_sched_yield(void);
-void	_thr_sem_prefork(void);
-void	_thr_sem_postfork(void);
-void	_thr_sem_child_postfork(void);
 
 void	_pthread_cleanup_push(void (*)(void *), void *);
 void	_pthread_cleanup_pop(int);

From 13561ed4ed3f8417caa22edac93e952220416bb5 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Thu, 26 Aug 2010 11:20:57 +0000
Subject: [PATCH 0258/1624] Fix typo.

Submitted by:	Ben Kaduk 
---
 sys/kern/syscalls.master | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/kern/syscalls.master b/sys/kern/syscalls.master
index 8e11134d06e..75f775a62e0 100644
--- a/sys/kern/syscalls.master
+++ b/sys/kern/syscalls.master
@@ -40,7 +40,7 @@
 ;	NOPROTO	same as STD except do not create structure or
 ;		function prototype in sys/sysproto.h.  Does add a
 ;		definition to syscall.h besides adding a sysent.
-;	NONSTATIC syscall is loadable
+;	NOTSTATIC syscall is loadable
 ;
 ; Please copy any additions and changes to the following compatability tables:
 ; sys/compat/freebsd32/syscalls.master

From 6bf9fb35e54f68acb6c4f8e3af8cee7fd4c38a31 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 26 Aug 2010 11:22:12 +0000
Subject: [PATCH 0259/1624] Sync DTrace bits with amd64 and fix the build.

Sponsored by:	The FreeBSD Foundation
---
 sys/i386/i386/trap.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/sys/i386/i386/trap.c b/sys/i386/i386/trap.c
index 9c580f74ac0..7b7bdc498ca 100644
--- a/sys/i386/i386/trap.c
+++ b/sys/i386/i386/trap.c
@@ -119,8 +119,12 @@ dtrace_doubletrap_func_t	dtrace_doubletrap_func;
  */
 systrace_probe_func_t	systrace_probe_func;
 
-dtrace_pid_probe_ptr_t	dtrace_pid_probe_ptr;
-dtrace_return_probe_ptr_t dtrace_return_probe_ptr;
+/*
+ * These hooks are necessary for the pid, usdt and fasttrap providers.
+ */
+dtrace_fasttrap_probe_ptr_t	dtrace_fasttrap_probe_ptr;
+dtrace_pid_probe_ptr_t		dtrace_pid_probe_ptr;
+dtrace_return_probe_ptr_t	dtrace_return_probe_ptr;
 #endif
 
 extern void trap(struct trapframe *frame);

From 568e7099581254aa60e5e3aac1b942e7a27363ef Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 26 Aug 2010 11:45:39 +0000
Subject: [PATCH 0260/1624] Add a man page for dtruss.

Sponsored by:	The FreeBSD Foundation
---
 cddl/usr.sbin/dtruss/Makefile |  2 +-
 cddl/usr.sbin/dtruss/dtruss.1 | 89 +++++++++++++++++++++++++++++++++++
 2 files changed, 90 insertions(+), 1 deletion(-)
 create mode 100644 cddl/usr.sbin/dtruss/dtruss.1

diff --git a/cddl/usr.sbin/dtruss/Makefile b/cddl/usr.sbin/dtruss/Makefile
index e09ed2e830d..39161ec0f8d 100644
--- a/cddl/usr.sbin/dtruss/Makefile
+++ b/cddl/usr.sbin/dtruss/Makefile
@@ -3,6 +3,6 @@
 .PATH: ${.CURDIR}/../../../cddl/contrib/dtracetoolkit
 
 SCRIPTS=dtruss
-NO_MAN=
+MAN=dtruss.1
 
 .include 
diff --git a/cddl/usr.sbin/dtruss/dtruss.1 b/cddl/usr.sbin/dtruss/dtruss.1
new file mode 100644
index 00000000000..d408e81bd80
--- /dev/null
+++ b/cddl/usr.sbin/dtruss/dtruss.1
@@ -0,0 +1,89 @@
+.\"
+.\" Copyright (c) 2010 The FreeBSD Foundation 
+.\" All rights reserved. 
+.\" 
+.\" This software was developed by Rui Paulo under sponsorship from the
+.\" FreeBSD Foundation. 
+.\"  
+.\" 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. 
+.\" 
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. 
+.\"
+.\" $FreeBSD$
+.\"
+.Dd August 26, 2010
+.Dt DTRUSS 1
+.Os
+.Sh NAME
+.Nm dtruss 
+.Nd Trace system calls and userland stacks using DTrace
+.Sh SYNOPSIS
+.Nm
+.Op Fl acdefholLs
+.Op Fl t Ar syscall
+.Op Fl n Ar name Fl p Ar pid Ar command
+.Sh DESCRIPTION
+The
+.Nm
+utility traces system calls and (optionally) userland stack traces for the
+specified programs.
+.Pp
+The following options are available:
+.Bl -tag -width indent
+.It Fl p Ar pid
+Trace the process with PID
+.Ar pid .
+.It Fl n Ar name
+Trace the process with name
+.Ar name .
+.It Fl t Ar syscall
+Trace the specified syscall only.
+.It Fl a
+Print all details.
+.It Fl c
+Print syscall counts.
+.It Fl d
+Print relative times (in microseconds).
+.It Fl e
+Print elapsed times (in microseconds).
+.It Fl f
+Follow the children processes.
+.It Fl l
+Force printing PID / TID.
+.It Fl o
+Print time spent on CPU.
+.It Fl s
+Print userland stack backtraces.
+.It Fl L
+Don't print PID / TID.
+.It Fl b Ar bufsize
+Specify the DTrace buffer size.
+.El
+.Sh EXIT STATUS
+.Ex -std
+.Sh SEE ALSO
+.Xr dtrace 1 
+.Sh HISTORY
+The
+.Nm
+utility comes from the DTraceToolkit and was first imported into
+.Fx 9.0 .
+.Sh AUTHORS
+.An Brendan Gregg

From e48ccbb261df9ec6f421241c160a5dd3595d1cf2 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 26 Aug 2010 11:46:38 +0000
Subject: [PATCH 0261/1624] Install dtruss.

Sponsored by:	The FreeBSD Foundation
---
 cddl/usr.sbin/Makefile | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/cddl/usr.sbin/Makefile b/cddl/usr.sbin/Makefile
index fe72665a36f..49db06b6108 100644
--- a/cddl/usr.sbin/Makefile
+++ b/cddl/usr.sbin/Makefile
@@ -3,6 +3,7 @@
 .include 
 
 SUBDIR=	${_dtrace} \
+	${_dtruss} \
 	${_lockstat} \
 	${_zdb}
 
@@ -14,6 +15,7 @@ _zdb=	zdb
 
 .if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386"
 _dtrace=	dtrace
+_dtruss=	dtruss
 _lockstat=	lockstat
 .endif
 

From 30ca19f436bae80643110d874f81347befef57cc Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 26 Aug 2010 13:00:29 +0000
Subject: [PATCH 0262/1624] Mark __JCR_LIST__, __DTOR_END__, __JCR_END__,
 __FRAME_END__ as used to avoid segfaults when building with clang.

Permission to backport given by Jan hubicka .
---
 contrib/gcc/crtstuff.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/contrib/gcc/crtstuff.c b/contrib/gcc/crtstuff.c
index 706528060ca..be41d96dc15 100644
--- a/contrib/gcc/crtstuff.c
+++ b/contrib/gcc/crtstuff.c
@@ -211,7 +211,7 @@ STATIC EH_FRAME_SECTION_CONST char __EH_FRAME_BEGIN__[]
 /* Stick a label at the beginning of the java class registration info
    so we can register them properly.  */
 STATIC void *__JCR_LIST__[]
-  __attribute__ ((unused, section(JCR_SECTION_NAME), aligned(sizeof(void*))))
+  __attribute__ ((used, section(JCR_SECTION_NAME), aligned(sizeof(void*))))
   = { };
 #endif /* JCR_SECTION_NAME */
 
@@ -472,11 +472,11 @@ DTOR_LIST_END;
 #elif defined(DTORS_SECTION_ASM_OP)
 asm (DTORS_SECTION_ASM_OP);
 STATIC func_ptr __DTOR_END__[1]
-  __attribute__ ((unused, aligned(sizeof(func_ptr))))
+  __attribute__ ((used, aligned(sizeof(func_ptr))))
   = { (func_ptr) 0 };
 #else
 STATIC func_ptr __DTOR_END__[1]
-  __attribute__((unused, section(".dtors"), aligned(sizeof(func_ptr))))
+  __attribute__((used, section(".dtors"), aligned(sizeof(func_ptr))))
   = { (func_ptr) 0 };
 #endif
 
@@ -493,7 +493,7 @@ typedef short int32;
 #  error "Missing a 4 byte integer"
 # endif
 STATIC EH_FRAME_SECTION_CONST int32 __FRAME_END__[]
-     __attribute__ ((unused, section(EH_FRAME_SECTION_NAME),
+     __attribute__ ((used, section(EH_FRAME_SECTION_NAME),
 		     aligned(sizeof(int32))))
      = { 0 };
 #endif /* EH_FRAME_SECTION_NAME */
@@ -501,7 +501,7 @@ STATIC EH_FRAME_SECTION_CONST int32 __FRAME_END__[]
 #ifdef JCR_SECTION_NAME
 /* Null terminate the .jcr section array.  */
 STATIC void *__JCR_END__[1] 
-   __attribute__ ((unused, section(JCR_SECTION_NAME),
+   __attribute__ ((used, section(JCR_SECTION_NAME),
 		   aligned(sizeof(void *))))
    = { 0 };
 #endif /* JCR_SECTION_NAME */

From ed5d0307885dc431a8f394bb00e5a468d7e93a59 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 26 Aug 2010 13:04:16 +0000
Subject: [PATCH 0263/1624] Mark __DTOR_LIST__, __EH_FRAME_BEGIN__ and
 __CTOR_END__ as used to avoid segfaults when building with clang.

This comes (partly) from the LLVM svn r41105.
---
 contrib/gcc/crtstuff.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/contrib/gcc/crtstuff.c b/contrib/gcc/crtstuff.c
index be41d96dc15..d4f54b91a60 100644
--- a/contrib/gcc/crtstuff.c
+++ b/contrib/gcc/crtstuff.c
@@ -191,11 +191,11 @@ DTOR_LIST_BEGIN;
 #elif defined(DTORS_SECTION_ASM_OP)
 asm (DTORS_SECTION_ASM_OP);
 STATIC func_ptr __DTOR_LIST__[1]
-  __attribute__ ((aligned(sizeof(func_ptr))))
+  __attribute__ ((used, aligned(sizeof(func_ptr))))
   = { (func_ptr) (-1) };
 #else
 STATIC func_ptr __DTOR_LIST__[1]
-  __attribute__((section(".dtors"), aligned(sizeof(func_ptr))))
+  __attribute__((used, section(".dtors"), aligned(sizeof(func_ptr))))
   = { (func_ptr) (-1) };
 #endif /* __DTOR_LIST__ alternatives */
 
@@ -203,7 +203,7 @@ STATIC func_ptr __DTOR_LIST__[1]
 /* Stick a label at the beginning of the frame unwind info so we can register
    and deregister it with the exception handling library code.  */
 STATIC EH_FRAME_SECTION_CONST char __EH_FRAME_BEGIN__[]
-     __attribute__((section(EH_FRAME_SECTION_NAME), aligned(4)))
+     __attribute__((used, section(EH_FRAME_SECTION_NAME), aligned(4)))
      = { };
 #endif /* USE_EH_FRAME_REGISTRY */
 
@@ -459,11 +459,11 @@ CTOR_LIST_END;
 static func_ptr force_to_data[1] __attribute__ ((__used__)) = { };
 asm (CTORS_SECTION_ASM_OP);
 STATIC func_ptr __CTOR_END__[1]
-  __attribute__((aligned(sizeof(func_ptr))))
+  __attribute__((used, aligned(sizeof(func_ptr))))
   = { (func_ptr) 0 };
 #else
 STATIC func_ptr __CTOR_END__[1]
-  __attribute__((section(".ctors"), aligned(sizeof(func_ptr))))
+  __attribute__((used, section(".ctors"), aligned(sizeof(func_ptr))))
   = { (func_ptr) 0 };
 #endif
 

From 982850de57b6ca48894161c64de6d3016a48fc9d Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 26 Aug 2010 14:54:12 +0000
Subject: [PATCH 0264/1624] Guard against TARGET_ABI being undefined
 (TARGET_ABI will go away soon)

---
 Makefile.mips | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Makefile.mips b/Makefile.mips
index 7b70b9d3fcc..cc08a592337 100644
--- a/Makefile.mips
+++ b/Makefile.mips
@@ -1,5 +1,5 @@
 # $FreeBSD$
 
-.if ${TARGET_ABI} == "n64"
+.if defined(TARGET_ABI) && ${TARGET_ABI} == "n64"
 MK_RESCUE=no
 .endif

From 3a1d56f9a4f089f1aea3af7bfcb840282136858a Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 26 Aug 2010 15:49:52 +0000
Subject: [PATCH 0265/1624] Make sure TARGET_ABI is defined.  TARGET_ABI will
 die a horrible death after we get all of TBEMD merged back into head, and
 make mips64 imply n64, so don't bother to make this 100% pretty.  You'll have
 to settle for only 64% pretty.

---
 usr.sbin/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/usr.sbin/Makefile b/usr.sbin/Makefile
index 37ab863030c..3012da0fb37 100644
--- a/usr.sbin/Makefile
+++ b/usr.sbin/Makefile
@@ -413,7 +413,7 @@ _crunch=	crunch
 
 .if ${MK_USB} != "no"
 .if ${MACHINE_ARCH} != "ia64" && \
-	!(${MACHINE_ARCH} == "mips" && ${TARGET_ABI} == "n64")
+   !(${MACHINE_ARCH} == "mips" && defined(TARGET_ABI) && ${TARGET_ABI} == "n64")
 _uathload=	uathload
 .endif
 _uhsoctl=	uhsoctl

From 4136388a1815ef48cd2b2005b254293a0986c376 Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Thu, 26 Aug 2010 16:01:29 +0000
Subject: [PATCH 0266/1624] Set de_dir for user created symbolic links. This
 will be needed to be able to resolve their parent directories.

---
 sys/fs/devfs/devfs_vnops.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/fs/devfs/devfs_vnops.c b/sys/fs/devfs/devfs_vnops.c
index dfcdf1ac790..943742e6fc8 100644
--- a/sys/fs/devfs/devfs_vnops.c
+++ b/sys/fs/devfs/devfs_vnops.c
@@ -1539,6 +1539,7 @@ devfs_symlink(struct vop_symlink_args *ap)
 	de->de_gid = 0;
 	de->de_mode = 0755;
 	de->de_inode = alloc_unr(devfs_inos);
+	de->de_dir = dd;
 	de->de_dirent->d_type = DT_LNK;
 	i = strlen(ap->a_target) + 1;
 	de->de_symlink = malloc(i, M_DEVFS, M_WAITOK);

From 0778b1d117532b23072229cc35a664c9ba5c8544 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 26 Aug 2010 23:33:04 +0000
Subject: [PATCH 0267/1624] - Check the result of malloc(M_NOWAIT) in
 replay_alloc(). The caller   (replay_alloc()) knows how to handle
 replay_alloc() failure. - Eliminate 'freed_one' variable, it is not needed -
 when no entry is found   rce will be NULL. - Add locking assertions where we
 expect a rc_lock to be held.

Reviewed by:	rmacklem
MFC after:	2 weeks
---
 sys/rpc/replay.c | 43 ++++++++++++++++++++++++-------------------
 1 file changed, 24 insertions(+), 19 deletions(-)

diff --git a/sys/rpc/replay.c b/sys/rpc/replay.c
index 2e92017689a..1bd5378d9fb 100644
--- a/sys/rpc/replay.c
+++ b/sys/rpc/replay.c
@@ -113,8 +113,12 @@ replay_alloc(struct replay_cache *rc,
 {
 	struct replay_cache_entry *rce;
 
+	mtx_assert(&rc->rc_lock, MA_OWNED);
+
 	rc->rc_count++;
 	rce = malloc(sizeof(*rce), M_RPC, M_NOWAIT|M_ZERO);
+	if (!rce)
+		return (NULL);
 	rce->rce_hash = h;
 	rce->rce_msg = *msg;
 	bcopy(addr, &rce->rce_addr, addr->sa_len);
@@ -129,6 +133,8 @@ static void
 replay_free(struct replay_cache *rc, struct replay_cache_entry *rce)
 {
 
+	mtx_assert(&rc->rc_lock, MA_OWNED);
+
 	rc->rc_count--;
 	TAILQ_REMOVE(&rc->rc_cache[rce->rce_hash], rce, rce_link);
 	TAILQ_REMOVE(&rc->rc_all, rce, rce_alllink);
@@ -143,26 +149,25 @@ static void
 replay_prune(struct replay_cache *rc)
 {
 	struct replay_cache_entry *rce;
-	bool_t freed_one;
 
-	if (rc->rc_count >= REPLAY_MAX || rc->rc_size > rc->rc_maxsize) {
-		do {
-			freed_one = FALSE;
-			/*
-			 * Try to free an entry. Don't free in-progress entries
-			 */
-			TAILQ_FOREACH_REVERSE(rce, &rc->rc_all,
-			    replay_cache_list, rce_alllink) {
-				if (rce->rce_repmsg.rm_xid) {
-					replay_free(rc, rce);
-					freed_one = TRUE;
-					break;
-				}
-			}
-		} while (freed_one
-		    && (rc->rc_count >= REPLAY_MAX
-			|| rc->rc_size > rc->rc_maxsize));
-	}
+	mtx_assert(&rc->rc_lock, MA_OWNED);
+
+	if (rc->rc_count < REPLAY_MAX && rc->rc_size <= rc->rc_maxsize)
+		return;
+
+	do {
+		/*
+		 * Try to free an entry. Don't free in-progress entries.
+		 */
+		TAILQ_FOREACH_REVERSE(rce, &rc->rc_all, replay_cache_list,
+		    rce_alllink) {
+			if (rce->rce_repmsg.rm_xid)
+				break;
+		}
+		if (rce)
+			replay_free(rc, rce);
+	} while (rce && (rc->rc_count >= REPLAY_MAX
+	    || rc->rc_size > rc->rc_maxsize));
 }
 
 enum replay_state

From 203a3b911e225e6a31be045bb0810160bebd26fc Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 26 Aug 2010 23:41:40 +0000
Subject: [PATCH 0268/1624] - When VFS_VGET() is not supported, switch to
 VOP_LOOKUP(). - We are fine by only share-locking the vnode. - Remove
 assertion that doesn't hold for ZFS where we cross mount points   boundaries
 by going into .zfs/snapshot//.

Reviewed by:	rmacklem
MFC after:	1 month
---
 sys/nfsserver/nfs_serv.c | 88 ++++++++++++++++++++++------------------
 1 file changed, 48 insertions(+), 40 deletions(-)

diff --git a/sys/nfsserver/nfs_serv.c b/sys/nfsserver/nfs_serv.c
index d1be5e55333..833bfc7ba4d 100644
--- a/sys/nfsserver/nfs_serv.c
+++ b/sys/nfsserver/nfs_serv.c
@@ -3041,7 +3041,8 @@ nfsrv_readdirplus(struct nfsrv_descript *nfsd, struct nfssvc_sock *slp,
 	u_quad_t off, toff, verf;
 	u_long *cookies = NULL, *cookiep; /* needs to be int64_t or off_t */
 	int v3 = (nfsd->nd_flag & ND_NFSV3);
-	int vfslocked;
+	int usevget = 1, vfslocked;
+	struct componentname cn;
 
 	nfsdbprintf(("%s %d\n", __FILE__, __LINE__));
 	vfslocked = 0;
@@ -3186,28 +3187,6 @@ again:
 		goto again;
 	}
 
-	/*
-	 * Probe one of the directory entries to see if the filesystem
-	 * supports VGET.
-	 */
-	error = VFS_VGET(vp->v_mount, dp->d_fileno, LK_EXCLUSIVE, &nvp);
-	if (error) {
-		if (error == EOPNOTSUPP)
-			error = NFSERR_NOTSUPP;
-		else
-			error = NFSERR_SERVERFAULT;
-		vrele(vp);
-		vp = NULL;
-		free((caddr_t)cookies, M_TEMP);
-		free((caddr_t)rbuf, M_TEMP);
-		nfsm_reply(NFSX_V3POSTOPATTR);
-		nfsm_srvpostop_attr(getret, &at);
-		error = 0;
-		goto nfsmout;
-	}
-	vput(nvp);
-	nvp = NULL;
-
 	dirlen = len = NFSX_V3POSTOPATTR + NFSX_V3COOKIEVERF +
 	    2 * NFSX_UNSIGNED;
 	nfsm_reply(cnt);
@@ -3224,23 +3203,49 @@ again:
 			nlen = dp->d_namlen;
 			rem = nfsm_rndup(nlen)-nlen;
 
-			/*
-			 * For readdir_and_lookup get the vnode using
-			 * the file number.
-			 */
-			if (VFS_VGET(vp->v_mount, dp->d_fileno, LK_EXCLUSIVE,
-			    &nvp))
-				goto invalid;
+			if (usevget) {
+				/*
+				 * For readdir_and_lookup get the vnode using
+				 * the file number.
+				 */
+				error = VFS_VGET(vp->v_mount, dp->d_fileno,
+				    LK_SHARED, &nvp);
+				if (error != 0 && error != EOPNOTSUPP) {
+					error = 0;
+					goto invalid;
+				} else if (error == EOPNOTSUPP) {
+					/*
+					 * VFS_VGET() not supported?
+					 * Let's switch to VOP_LOOKUP().
+					 */
+					error = 0;
+					usevget = 0;
+					cn.cn_nameiop = LOOKUP;
+					cn.cn_flags = ISLASTCN | NOFOLLOW | \
+					    LOCKSHARED | LOCKLEAF | MPSAFE;
+					cn.cn_lkflags = LK_SHARED | LK_RETRY;
+					cn.cn_cred = cred;
+					cn.cn_thread = curthread;
+				}
+			}
+			if (!usevget) {
+				cn.cn_nameptr = dp->d_name;
+				cn.cn_namelen = dp->d_namlen;
+				if (dp->d_namlen == 2 &&
+				    dp->d_name[0] == '.' &&
+				    dp->d_name[1] == '.') {
+					cn.cn_flags |= ISDOTDOT;
+				} else {
+					cn.cn_flags &= ~ISDOTDOT;
+				}
+				if (!VOP_ISLOCKED(vp))
+					vn_lock(vp, LK_SHARED | LK_RETRY);
+				if (VOP_LOOKUP(vp, &nvp, &cn) != 0)
+					goto invalid;
+			}
+
 			bzero((caddr_t)nfhp, NFSX_V3FH);
-			nfhp->fh_fsid =
-				nvp->v_mount->mnt_stat.f_fsid;
-			/*
-			 * XXXRW: Assert the mountpoints are the same so that
-			 * we know that acquiring Giant based on the
-			 * directory is the right thing for the child.
-			 */
-			KASSERT(nvp->v_mount == vp->v_mount,
-			    ("nfsrv_readdirplus: nvp mount != vp mount"));
+			nfhp->fh_fsid = nvp->v_mount->mnt_stat.f_fsid;
 			if (VOP_VPTOFH(nvp, &nfhp->fh_fid)) {
 				vput(nvp);
 				nvp = NULL;
@@ -3336,7 +3341,10 @@ invalid:
 		cookiep++;
 		ncookies--;
 	}
-	vrele(vp);
+	if (!usevget && VOP_ISLOCKED(vp))
+		vput(vp);
+	else
+		vrele(vp);
 	vp = NULL;
 	nfsm_clget;
 	*tl = nfsrv_nfs_false;

From 8733ff6e11836be5991e6b9b771c29cf198333f0 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 26 Aug 2010 23:44:32 +0000
Subject: [PATCH 0269/1624] Update comment now that I finally committed
 r211854.

MFC after:	1 month
---
 .../opensolaris/uts/common/fs/zfs/zfs_vfsops.c       | 12 +++---------
 1 file changed, 3 insertions(+), 9 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
index d2bd7ad0b7b..624c16e1680 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
@@ -1563,15 +1563,9 @@ zfs_vget(vfs_t *vfsp, ino_t ino, int flags, vnode_t **vpp)
 	int 		err;
 
 	/*
-	 * XXXPJD: zfs_zget() can't operate on virtual entires like .zfs/ or
-	 * .zfs/snapshot/ directories, so for now just return EOPNOTSUPP.
-	 * This will make NFS to fall back to using READDIR instead of
-	 * READDIRPLUS.
-	 * Also snapshots are stored in AVL tree, but based on their names,
-	 * not inode numbers, so it will be very inefficient to iterate
-	 * over all snapshots to find the right one.
-	 * Note that OpenSolaris READDIRPLUS implementation does LOOKUP on
-	 * d_name, and not VGET on d_fileno as we do.
+	 * zfs_zget() can't operate on virtual entires like .zfs/ or
+	 * .zfs/snapshot/ directories, that's why we return EOPNOTSUPP.
+	 * This will make NFS to switch to LOOKUP instead of using VGET.
 	 */
 	if (ino == ZFSCTL_INO_ROOT || ino == ZFSCTL_INO_SNAPDIR)
 		return (EOPNOTSUPP);

From 8e60ce996b14d8d41112ad374e3b2d6fc02b6823 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 27 Aug 2010 03:23:07 +0000
Subject: [PATCH 0270/1624] clear lock to zero state if it is destroyed.

---
 lib/libthr/thread/thr_rtld.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/lib/libthr/thread/thr_rtld.c b/lib/libthr/thread/thr_rtld.c
index 2560a941d3a..d9041adcfb9 100644
--- a/lib/libthr/thread/thr_rtld.c
+++ b/lib/libthr/thread/thr_rtld.c
@@ -81,8 +81,11 @@ static void
 _thr_rtld_lock_destroy(void *lock)
 {
 	int locki;
+	size_t i;
 
 	locki = (struct rtld_lock *)lock - &lock_place[0];
+	for (i = 0; i < sizeof(struct rtld_lock); ++i)
+		((char *)lock)[i] = 0;
 	busy_places &= ~(1 << locki);
 }
 

From ed0ee6af2e78cc10527d2c26abbe1946e54f3c98 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 27 Aug 2010 05:20:22 +0000
Subject: [PATCH 0271/1624] Unregister thread specific data destructor when a
 corresponding dso is unloaded.

---
 lib/libthr/thread/thr_fork.c    |  1 +
 lib/libthr/thread/thr_private.h |  1 +
 lib/libthr/thread/thr_spec.c    | 21 +++++++++++++++++++++
 3 files changed, 23 insertions(+)

diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index b1c221eca83..f20942d42be 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -114,6 +114,7 @@ __pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
 		}
 	}
 	THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
+	_thr_tsd_unload(phdr_info);
 }
 
 __weak_reference(_fork, fork);
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index f92913bc92b..f261810e7e9 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -739,6 +739,7 @@ _thr_check_init(void)
 
 struct dl_phdr_info;
 void __pthread_cxa_finalize(struct dl_phdr_info *phdr_info);
+void _thr_tsd_unload(struct dl_phdr_info *phdr_info) __hidden;
 
 __END_DECLS
 
diff --git a/lib/libthr/thread/thr_spec.c b/lib/libthr/thread/thr_spec.c
index 0740d6bac85..86dc79430f1 100644
--- a/lib/libthr/thread/thr_spec.c
+++ b/lib/libthr/thread/thr_spec.c
@@ -36,6 +36,7 @@
 #include 
 #include 
 #include "un-namespace.h"
+#include "libc_private.h"
 
 #include "thr_private.h"
 
@@ -235,3 +236,23 @@ _pthread_getspecific(pthread_key_t key)
 		data = NULL;
 	return (__DECONST(void *, data));
 }
+
+void
+_thr_tsd_unload(struct dl_phdr_info *phdr_info)
+{
+	struct pthread *curthread = _get_curthread();
+	void (*destructor)(void *);
+	int key;
+
+	THR_LOCK_ACQUIRE(curthread, &_keytable_lock);
+	for (key = 0; key < PTHREAD_KEYS_MAX; key++) {
+		if (_thread_keytable[key].allocated) {
+			destructor = _thread_keytable[key].destructor;
+			if (destructor != NULL) {
+				if (__elf_phdr_match_addr(phdr_info, destructor))
+					_thread_keytable[key].destructor = NULL;
+			}
+		}
+	}
+	THR_LOCK_RELEASE(curthread, &_keytable_lock);
+}

From 50e64c14a25e35466b3e2024713dcc2dfa4c9235 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Fri, 27 Aug 2010 05:29:59 +0000
Subject: [PATCH 0272/1624] pmap_mapdev() does not appear to actually need
 GIANT to be held here, and asserting that is held breaks drm.

MFC after:	2 weeks
---
 sys/powerpc/aim/mmu_oea.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea.c b/sys/powerpc/aim/mmu_oea.c
index 2d090db5ea9..da83538b462 100644
--- a/sys/powerpc/aim/mmu_oea.c
+++ b/sys/powerpc/aim/mmu_oea.c
@@ -2436,8 +2436,6 @@ moea_mapdev(mmu_t mmu, vm_offset_t pa, vm_size_t size)
 	offset = pa & PAGE_MASK;
 	size = roundup(offset + size, PAGE_SIZE);
 	
-	GIANT_REQUIRED;
-
 	/*
 	 * If the physical address lies within a valid BAT table entry,
 	 * return the 1:1 mapping. This currently doesn't work

From 37b3715cdbf54604b08979378c1e80bdccf3afac Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Fri, 27 Aug 2010 07:45:50 +0000
Subject: [PATCH 0273/1624] Whitespace fixes in mips/include, remove unused
 'struct tlb' from locore.h

PR:		misc/147471
---
 sys/mips/include/atomic.h   |  2 +-
 sys/mips/include/locore.h   | 32 +++++++++++++++-----------------
 sys/mips/include/memdev.h   |  2 +-
 sys/mips/include/pcb.h      | 28 ++++++++++++++--------------
 sys/mips/include/regnum.h   | 28 ++++++++++++++--------------
 sys/mips/include/ucontext.h |  8 ++++----
 6 files changed, 49 insertions(+), 51 deletions(-)

diff --git a/sys/mips/include/atomic.h b/sys/mips/include/atomic.h
index 4b87738cf90..7b4a82cb06a 100644
--- a/sys/mips/include/atomic.h
+++ b/sys/mips/include/atomic.h
@@ -48,7 +48,7 @@
 static __inline  void
 mips_sync(void)
 {
-        __asm __volatile (".set noreorder\n\t"
+	__asm __volatile (".set noreorder\n\t"
 			"sync\n\t"
 			"nop\n\t"
 			"nop\n\t"
diff --git a/sys/mips/include/locore.h b/sys/mips/include/locore.h
index 7cc72c7ceff..34c9afc5975 100644
--- a/sys/mips/include/locore.h
+++ b/sys/mips/include/locore.h
@@ -24,15 +24,13 @@
  */
 
 #ifndef _MIPS_LOCORE_H
-#define  _MIPS_LOCORE_H
+#define	_MIPS_LOCORE_H
 
 #include 
 #include 
 #include 
 #include 
 
-struct tlb;
-
 /*
  * CPU identification, from PRID register.
  */
@@ -47,22 +45,22 @@ typedef int mips_prid_t;
 #define MIPS_PRID_REV_MAJ(x)	((MIPS_PRID_REV(x) >> 4) & 0x0f)
 
 /* MIPS32/64 */
-#define MIPS_PRID_CID(x)	(((x) >> 16) & 0x00ff)	/* Company ID */
-#define     MIPS_PRID_CID_PREHISTORIC	0x00	/* Not MIPS32/64 */
-#define     MIPS_PRID_CID_MTI		0x01	/* MIPS Technologies, Inc. */
-#define     MIPS_PRID_CID_BROADCOM	0x02	/* Broadcom */
-#define     MIPS_PRID_CID_ALCHEMY	0x03	/* Alchemy Semiconductor */
-#define     MIPS_PRID_CID_SIBYTE	0x04	/* SiByte */
-#define     MIPS_PRID_CID_SANDCRAFT	0x05	/* SandCraft */
-#define     MIPS_PRID_CID_PHILIPS	0x06	/* Philips */
-#define     MIPS_PRID_CID_TOSHIBA	0x07	/* Toshiba */
-#define     MIPS_PRID_CID_LSI		0x08	/* LSI */
+#define	MIPS_PRID_CID(x)	(((x) >> 16) & 0x00ff)	/* Company ID */
+#define	MIPS_PRID_CID_PREHISTORIC	0x00	/* Not MIPS32/64 */
+#define	MIPS_PRID_CID_MTI		0x01	/* MIPS Technologies, Inc. */
+#define	MIPS_PRID_CID_BROADCOM		0x02	/* Broadcom */
+#define	MIPS_PRID_CID_ALCHEMY		0x03	/* Alchemy Semiconductor */
+#define	MIPS_PRID_CID_SIBYTE		0x04	/* SiByte */
+#define	MIPS_PRID_CID_SANDCRAFT		0x05	/* SandCraft */
+#define	MIPS_PRID_CID_PHILIPS		0x06	/* Philips */
+#define	MIPS_PRID_CID_TOSHIBA		0x07	/* Toshiba */
+#define	MIPS_PRID_CID_LSI		0x08	/* LSI */
 				/*	0x09	unannounced */
 				/*	0x0a	unannounced */
-#define     MIPS_PRID_CID_LEXRA		0x0b	/* Lexra */
-#define     MIPS_PRID_CID_RMI		0x0c	/* RMI */
-#define     MIPS_PRID_CID_CAVIUM	0x0d	/* Cavium */
-#define MIPS_PRID_COPTS(x)	(((x) >> 24) & 0x00ff)	/* Company Options */
+#define	MIPS_PRID_CID_LEXRA		0x0b	/* Lexra */
+#define	MIPS_PRID_CID_RMI		0x0c	/* RMI */
+#define	MIPS_PRID_CID_CAVIUM		0x0d	/* Cavium */
+#define	MIPS_PRID_COPTS(x)	(((x) >> 24) & 0x00ff)	/* Company Options */
 
 #ifdef _KERNEL
 #ifdef __HAVE_MIPS_MACHDEP_CACHE_CONFIG
diff --git a/sys/mips/include/memdev.h b/sys/mips/include/memdev.h
index 2872fb07298..8cca4610093 100644
--- a/sys/mips/include/memdev.h
+++ b/sys/mips/include/memdev.h
@@ -28,7 +28,7 @@
  */
 
 #define	CDEV_MINOR_MEM	0
-#define	CDEV_MINOR_KMEM 1
+#define	CDEV_MINOR_KMEM	1
 
 d_open_t	memopen;
 d_read_t	memrw;
diff --git a/sys/mips/include/pcb.h b/sys/mips/include/pcb.h
index e0982e35f24..99113396277 100644
--- a/sys/mips/include/pcb.h
+++ b/sys/mips/include/pcb.h
@@ -58,20 +58,20 @@ struct pcb
 /* these match the regnum's in regnum.h
  * used by switch.S
  */
-#define PCB_REG_S0   0
-#define PCB_REG_S1   1
-#define PCB_REG_S2   2
-#define PCB_REG_S3   3
-#define PCB_REG_S4   4
-#define PCB_REG_S5   5
-#define PCB_REG_S6   6
-#define PCB_REG_S7   7
-#define PCB_REG_SP   8
-#define PCB_REG_S8   9
-#define PCB_REG_RA   10
-#define PCB_REG_SR   11
-#define PCB_REG_GP   12
-#define PCB_REG_PC   13
+#define	PCB_REG_S0	0
+#define	PCB_REG_S1	1
+#define	PCB_REG_S2	2
+#define	PCB_REG_S3	3
+#define	PCB_REG_S4	4
+#define	PCB_REG_S5	5
+#define	PCB_REG_S6	6
+#define	PCB_REG_S7	7
+#define	PCB_REG_SP	8
+#define	PCB_REG_S8	9
+#define	PCB_REG_RA	10
+#define	PCB_REG_SR	11
+#define	PCB_REG_GP	12
+#define	PCB_REG_PC	13
 
 
 #ifdef _KERNEL
diff --git a/sys/mips/include/regnum.h b/sys/mips/include/regnum.h
index 1c22bb96961..ae7cf4bc112 100644
--- a/sys/mips/include/regnum.h
+++ b/sys/mips/include/regnum.h
@@ -46,20 +46,20 @@
  * in pcb.h and is used by
  * swtch.S
  */
-#define PREG_S0   0
-#define PREG_S1   1
-#define PREG_S2   2
-#define PREG_S3   3
-#define PREG_S4   4
-#define PREG_S5   5
-#define PREG_S6   6
-#define PREG_S7   7
-#define PREG_SP   8
-#define PREG_S8   9
-#define PREG_RA   10
-#define PREG_SR   11
-#define PREG_GP   12
-#define PREG_PC   13
+#define PREG_S0	0
+#define PREG_S1	1
+#define PREG_S2	2
+#define PREG_S3	3
+#define PREG_S4	4
+#define PREG_S5	5
+#define PREG_S6	6
+#define PREG_S7	7
+#define PREG_SP	8
+#define PREG_S8	9
+#define PREG_RA	10
+#define PREG_SR	11
+#define PREG_GP	12
+#define PREG_PC	13
 
 /*
  * Location of the saved registers relative to ZERO.
diff --git a/sys/mips/include/ucontext.h b/sys/mips/include/ucontext.h
index 7d4c2e46d4a..72f07b402e2 100644
--- a/sys/mips/include/ucontext.h
+++ b/sys/mips/include/ucontext.h
@@ -48,13 +48,13 @@ typedef struct	__mcontext {
 	int		mc_onstack;	/* sigstack state to restore */
 	register_t	mc_pc;		/* pc at time of signal */
 	register_t	mc_regs[32];	/* processor regs 0 to 31 */
-        register_t      sr;             /* status register */
-        register_t	mullo, mulhi;	/* mullo and mulhi registers... */
+	register_t	sr;		/* status register */
+	register_t	mullo, mulhi;	/* mullo and mulhi registers... */
 	int		mc_fpused;	/* fp has been used */
 	f_register_t	mc_fpregs[33];	/* fp regs 0 to 31 and csr */
 	register_t	mc_fpc_eir;	/* fp exception instruction reg */
 	void		*mc_tls;	/* pointer to TLS area */
-	int	__spare__[8];	/* XXX reserved */ 
+	int		__spare__[8];	/* XXX reserved */ 
 } mcontext_t;
 #endif
 
@@ -101,7 +101,7 @@ typedef struct	__mcontext {
 #define	UCR_SP		UCTX_REG(29)
 #define	UCR_S8		UCTX_REG(30)
 #define	UCR_RA		UCTX_REG(31)
-#define UCR_SR          UCTX_REG(32)
+#define	UCR_SR		UCTX_REG(32)
 #define	UCR_MDLO	UCTX_REG(33)
 #define	UCR_MDHI	UCTX_REG(34)
 

From f77b6c6a25e69047d8191baed596f0f2244041ff Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Fri, 27 Aug 2010 08:54:40 +0000
Subject: [PATCH 0274/1624] Fix an off-by-one error where we try to split a
 path name that's more than 100 characters long and the 101th last character
 is a '/'.

MFC after:	3 weeks
---
 bin/pax/tar.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/bin/pax/tar.c b/bin/pax/tar.c
index ab5bd3b12ad..e274df47cf7 100644
--- a/bin/pax/tar.c
+++ b/bin/pax/tar.c
@@ -1095,7 +1095,7 @@ name_split(char *name, int len)
 	 * to find the biggest piece to fit in the name field (or the smallest
 	 * prefix we can find)
 	 */
-	start = name + len - TNMSZ - 1;
+	start = name + len - TNMSZ;
 	while ((*start != '\0') && (*start != '/'))
 		++start;
 

From 8f0e6fd35b281854fb5b20604ad4e4a77d110cd8 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Fri, 27 Aug 2010 09:55:51 +0000
Subject: [PATCH 0275/1624] Use private namespace for visibility keyword.

Noted by:	bde
MFC after:	3 days
---
 sys/sys/cdefs.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/sys/cdefs.h b/sys/sys/cdefs.h
index afb609a6356..bcb4367f30c 100644
--- a/sys/sys/cdefs.h
+++ b/sys/sys/cdefs.h
@@ -306,8 +306,8 @@
 #endif
 
 #if __GNUC_PREREQ__(4, 2)
-#define	__hidden	__attribute__((visibility("hidden")))
-#define	__exported	__attribute__((visibility("default")))
+#define	__hidden	__attribute__((__visibility__("hidden")))
+#define	__exported	__attribute__((__visibility__("default")))
 #else
 #define	__hidden
 #define	__exported

From e45d37b2e9c144cf1038b626a63843089ea3ebfe Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Fri, 27 Aug 2010 11:08:11 +0000
Subject: [PATCH 0276/1624] Don't attempt to write label with GEOM_BSD based
 method if the class is not available. This improves error reporting when
 bsdlabel(8) is unable to open a device for writing. If GEOM_BSD was
 unavailable, only a rather obscure error message "Class not found" was
 printed.

PR:		bin/58390
Reviewed by:	ae
Discussed with:	marcel
MFC after:	1 month
---
 sbin/bsdlabel/bsdlabel.c | 33 ++++++++++++++++++++++++++++++++-
 1 file changed, 32 insertions(+), 1 deletion(-)

diff --git a/sbin/bsdlabel/bsdlabel.c b/sbin/bsdlabel/bsdlabel.c
index fb1d8b0d86e..b671821f5ab 100644
--- a/sbin/bsdlabel/bsdlabel.c
+++ b/sbin/bsdlabel/bsdlabel.c
@@ -80,6 +80,7 @@ __FBSDID("$FreeBSD$");
 #include "pathnames.h"
 
 static void	makelabel(const char *, struct disklabel *);
+static int	geom_bsd_available(void);
 static int	writelabel(void);
 static int	readlabel(int flag);
 static void	display(FILE *, const struct disklabel *);
@@ -378,11 +379,34 @@ readboot(void)
 	errx(1, "boot code %s is wrong size", xxboot);
 }
 
+static int
+geom_bsd_available(void)
+{
+	struct gclass *class;
+	struct gmesh mesh;
+	int error;
+
+	error = geom_gettree(&mesh);
+	if (error != 0)
+		errc(1, error, "Cannot get GEOM tree");
+
+	LIST_FOREACH(class, &mesh.lg_class, lg_class) {
+		if (strcmp(class->lg_name, "BSD") == 0) {
+			geom_deletetree(&mesh);
+			return (1);
+		}
+	}
+
+	geom_deletetree(&mesh);
+
+	return (0);
+}
+
 static int
 writelabel(void)
 {
 	uint64_t *p, sum;
-	int i, fd;
+	int i, fd, serrno;
 	struct gctl_req *grq;
 	char const *errstr;
 	struct disklabel *lp = &lab;
@@ -416,6 +440,13 @@ writelabel(void)
 		if (is_file) {
 			warn("cannot open file %s for writing label", specname);
 			return(1);
+		} else
+			serrno = errno;
+
+		/* Give up if GEOM_BSD is not available. */
+		if (geom_bsd_available() == 0) {
+			warnc(serrno, "%s", specname);
+			return (1);
 		}
 
 		grq = gctl_get_handle();

From 8502ec25dc00de82ed22788bb5d0360b5db70b07 Mon Sep 17 00:00:00 2001
From: Andre Oppermann 
Date: Fri, 27 Aug 2010 12:34:53 +0000
Subject: [PATCH 0277/1624] Use timestamp modulo comparison macro for automatic
 receive buffer scaling to correctly handle wrapping of ticks value.

MFC after:	1 week
---
 sys/netinet/tcp_input.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/netinet/tcp_input.c b/sys/netinet/tcp_input.c
index 05671ce0052..e4bddb90525 100644
--- a/sys/netinet/tcp_input.c
+++ b/sys/netinet/tcp_input.c
@@ -1441,7 +1441,7 @@ tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
 			if (V_tcp_do_autorcvbuf &&
 			    to.to_tsecr &&
 			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
-				if (to.to_tsecr > tp->rfbuf_ts &&
+				if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
 				    to.to_tsecr - tp->rfbuf_ts < hz) {
 					if (tp->rfbuf_cnt >
 					    (so->so_rcv.sb_hiwat / 8 * 7) &&

From 7087d13faef825073ce286632daac107bdff7728 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 13:54:17 +0000
Subject: [PATCH 0278/1624] Make comment more readable.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/proto_tcp4.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sbin/hastd/proto_tcp4.c b/sbin/hastd/proto_tcp4.c
index bfbae8c1c1e..9bb5c62375b 100644
--- a/sbin/hastd/proto_tcp4.c
+++ b/sbin/hastd/proto_tcp4.c
@@ -242,8 +242,8 @@ tcp4_connect(void *ctx)
 		return (errno);
 	}
 	/*
-	 * We make socket non-blocking so we have decided about connection
-	 * timeout.
+	 * We make socket non-blocking so we can handle connection timeout
+	 * manually.
 	 */
 	flags |= O_NONBLOCK;
 	if (fcntl(tctx->tc_fd, F_SETFL, flags) == -1) {

From 6e5f008ac4c8cdfd9f2b08b25ef80d75d284cf2e Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 13:58:38 +0000
Subject: [PATCH 0279/1624] Add mtx_owned() implementation.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/synch.h | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/sbin/hastd/synch.h b/sbin/hastd/synch.h
index 7269aea6607..006b0e74ee4 100644
--- a/sbin/hastd/synch.h
+++ b/sbin/hastd/synch.h
@@ -33,7 +33,9 @@
 #define	_SYNCH_H_
 
 #include 
+#include 
 #include 
+#include 
 #include 
 #include 
 
@@ -70,6 +72,12 @@ mtx_unlock(pthread_mutex_t *lock)
 	error = pthread_mutex_unlock(lock);
 	assert(error == 0);
 }
+static __inline bool
+mtx_owned(pthread_mutex_t *lock)
+{
+
+	return (pthread_mutex_isowned_np(lock) != 0);
+}
 
 static __inline void
 rw_init(pthread_rwlock_t *lock)

From 16bd7026a2ab80a8540a9444af9a75ab3d5ead96 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:01:28 +0000
Subject: [PATCH 0280/1624] Add QUEUE_INSERT() and QUEUE_TAKE() macros that
 simplify the code a bit.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/secondary.c | 89 +++++++++++++++++-------------------------
 1 file changed, 35 insertions(+), 54 deletions(-)

diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index a0fae637587..c5394ff82ce 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -1,5 +1,6 @@
 /*-
  * Copyright (c) 2009-2010 The FreeBSD Foundation
+ * Copyright (c) 2010 Pawel Jakub Dawidek 
  * All rights reserved.
  *
  * This software was developed by Pawel Jakub Dawidek under sponsorship from
@@ -102,6 +103,26 @@ static void *recv_thread(void *arg);
 static void *disk_thread(void *arg);
 static void *send_thread(void *arg);
 
+#define	QUEUE_INSERT(name, hio)	do {					\
+	bool _wakeup;							\
+									\
+	mtx_lock(&hio_##name##_list_lock);				\
+	_wakeup = TAILQ_EMPTY(&hio_##name##_list);			\
+	TAILQ_INSERT_TAIL(&hio_##name##_list, (hio), hio_next);		\
+	mtx_unlock(&hio_##name##_list_lock);				\
+	if (_wakeup)							\
+		cv_signal(&hio_##name##_list_cond);			\
+} while (0)
+#define	QUEUE_TAKE(name, hio)	do {					\
+	mtx_lock(&hio_##name##_list_lock);				\
+	while (((hio) = TAILQ_FIRST(&hio_##name##_list)) == NULL) {	\
+		cv_wait(&hio_##name##_list_cond,			\
+		    &hio_##name##_list_lock);				\
+	}								\
+	TAILQ_REMOVE(&hio_##name##_list, (hio), hio_next);		\
+	mtx_unlock(&hio_##name##_list_lock);				\
+} while (0)
+
 static void
 init_environment(void)
 {
@@ -478,24 +499,22 @@ recv_thread(void *arg)
 {
 	struct hast_resource *res = arg;
 	struct hio *hio;
-	bool wakeup;
 
 	for (;;) {
 		pjdlog_debug(2, "recv: Taking free request.");
-		mtx_lock(&hio_free_list_lock);
-		while ((hio = TAILQ_FIRST(&hio_free_list)) == NULL) {
-			pjdlog_debug(2, "recv: No free requests, waiting.");
-			cv_wait(&hio_free_list_cond, &hio_free_list_lock);
-		}
-		TAILQ_REMOVE(&hio_free_list, hio, hio_next);
-		mtx_unlock(&hio_free_list_lock);
+		QUEUE_TAKE(free, hio);
 		pjdlog_debug(2, "recv: (%p) Got request.", hio);
 		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
 			pjdlog_exit(EX_TEMPFAIL,
 			    "Unable to receive request header");
 		}
-		if (requnpack(res, hio) != 0)
-			goto send_queue;
+		if (requnpack(res, hio) != 0) {
+			pjdlog_debug(2,
+			    "recv: (%p) Moving request to the send queue.",
+			    hio);
+			QUEUE_INSERT(send, hio);
+			continue;
+		}
 		reqlog(LOG_DEBUG, 2, -1, hio,
 		    "recv: (%p) Got request header: ", hio);
 		if (hio->hio_cmd == HIO_WRITE) {
@@ -507,22 +526,7 @@ recv_thread(void *arg)
 		}
 		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",
 		    hio);
-		mtx_lock(&hio_disk_list_lock);
-		wakeup = TAILQ_EMPTY(&hio_disk_list);
-		TAILQ_INSERT_TAIL(&hio_disk_list, hio, hio_next);
-		mtx_unlock(&hio_disk_list_lock);
-		if (wakeup)
-			cv_signal(&hio_disk_list_cond);
-		continue;
-send_queue:
-		pjdlog_debug(2, "recv: (%p) Moving request to the send queue.",
-		    hio);
-		mtx_lock(&hio_send_list_lock);
-		wakeup = TAILQ_EMPTY(&hio_send_list);
-		TAILQ_INSERT_TAIL(&hio_send_list, hio, hio_next);
-		mtx_unlock(&hio_send_list_lock);
-		if (wakeup)
-			cv_signal(&hio_send_list_cond);
+		QUEUE_INSERT(disk, hio);
 	}
 	/* NOTREACHED */
 	return (NULL);
@@ -538,19 +542,13 @@ disk_thread(void *arg)
 	struct hast_resource *res = arg;
 	struct hio *hio;
 	ssize_t ret;
-	bool clear_activemap, wakeup;
+	bool clear_activemap;
 
 	clear_activemap = true;
 
 	for (;;) {
 		pjdlog_debug(2, "disk: Taking request.");
-		mtx_lock(&hio_disk_list_lock);
-		while ((hio = TAILQ_FIRST(&hio_disk_list)) == NULL) {
-			pjdlog_debug(2, "disk: No requests, waiting.");
-			cv_wait(&hio_disk_list_cond, &hio_disk_list_lock);
-		}
-		TAILQ_REMOVE(&hio_disk_list, hio, hio_next);
-		mtx_unlock(&hio_disk_list_lock);
+		QUEUE_TAKE(disk, hio);
 		while (clear_activemap) {
 			unsigned char *map;
 			size_t mapsize;
@@ -628,12 +626,7 @@ disk_thread(void *arg)
 		}
 		pjdlog_debug(2, "disk: (%p) Moving request to the send queue.",
 		    hio);
-		mtx_lock(&hio_send_list_lock);
-		wakeup = TAILQ_EMPTY(&hio_send_list);
-		TAILQ_INSERT_TAIL(&hio_send_list, hio, hio_next);
-		mtx_unlock(&hio_send_list_lock);
-		if (wakeup)
-			cv_signal(&hio_send_list_cond);
+		QUEUE_INSERT(send, hio);
 	}
 	/* NOTREACHED */
 	return (NULL);
@@ -650,17 +643,10 @@ send_thread(void *arg)
 	struct hio *hio;
 	void *data;
 	size_t length;
-	bool wakeup;
 
 	for (;;) {
 		pjdlog_debug(2, "send: Taking request.");
-		mtx_lock(&hio_send_list_lock);
-		while ((hio = TAILQ_FIRST(&hio_send_list)) == NULL) {
-			pjdlog_debug(2, "send: No requests, waiting.");
-			cv_wait(&hio_send_list_cond, &hio_send_list_lock);
-		}
-		TAILQ_REMOVE(&hio_send_list, hio, hio_next);
-		mtx_unlock(&hio_send_list_lock);
+		QUEUE_TAKE(send, hio);
 		reqlog(LOG_DEBUG, 2, -1, hio, "send: (%p) Got request: ", hio);
 		nvout = nv_alloc();
 		/* Copy sequence number. */
@@ -697,12 +683,7 @@ send_thread(void *arg)
 		    hio);
 		nv_free(hio->hio_nv);
 		hio->hio_error = 0;
-		mtx_lock(&hio_free_list_lock);
-		wakeup = TAILQ_EMPTY(&hio_free_list);
-		TAILQ_INSERT_TAIL(&hio_free_list, hio, hio_next);
-		mtx_unlock(&hio_free_list_lock);
-		if (wakeup)
-			cv_signal(&hio_free_list_cond);
+		QUEUE_INSERT(free, hio);
 	}
 	/* NOTREACHED */
 	return (NULL);

From 55ce1e7c8bda46c5d9e7e7e146bb38567c8251bf Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:06:00 +0000
Subject: [PATCH 0281/1624] We have sync_start() function to start
 synchronization, introduce sync_stop() function to stop it.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index a5e5d6e78be..1b08585822f 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -685,6 +685,16 @@ sync_start(void)
 	cv_signal(&sync_cond);
 }
 
+static void
+sync_stop(void)
+{
+
+	mtx_lock(&sync_lock);
+	if (sync_inprogress)
+		sync_inprogress = false;
+	mtx_unlock(&sync_lock);
+}
+
 static void
 init_ggate(struct hast_resource *res)
 {
@@ -871,10 +881,7 @@ remote_close(struct hast_resource *res, int ncomp)
 	/*
 	 * Stop synchronization if in-progress.
 	 */
-	mtx_lock(&sync_lock);
-	if (sync_inprogress)
-		sync_inprogress = false;
-	mtx_unlock(&sync_lock);
+	sync_stop();
 
 	/*
 	 * Wake up guard thread, so it can immediately start reconnect.
@@ -1526,9 +1533,7 @@ sync_thread(void *arg __unused)
 			}
 		}
 		if (offset < 0) {
-			mtx_lock(&sync_lock);
-			sync_inprogress = false;
-			mtx_unlock(&sync_lock);
+			sync_stop();
 			pjdlog_debug(1, "Nothing to synchronize.");
 			/*
 			 * Synchronization complete, make both localcnt and

From 53d9b386eb6b7829a132261f847c3cbe60752ec8 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:08:10 +0000
Subject: [PATCH 0282/1624] Log that synchronization was interrupted in a
 proper place.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 1b08585822f..429e914aa4a 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1495,10 +1495,17 @@ sync_thread(void *arg __unused)
 
 	ncomps = HAST_NCOMPONENTS;
 	dorewind = true;
-	synced = 0;
+	synced = -1;
 
 	for (;;) {
 		mtx_lock(&sync_lock);
+		if (synced == -1)
+			synced = 0;
+		else if (!sync_inprogress) {
+			pjdlog_info("Synchronization interrupted. "
+			    "%jd bytes synchronized so far.",
+			    (intmax_t)synced);
+		}
 		while (!sync_inprogress) {
 			dorewind = true;
 			synced = 0;
@@ -1559,10 +1566,6 @@ sync_thread(void *arg __unused)
 				    (uintmax_t)res->hr_secondary_localcnt);
 				(void)metadata_write(res);
 				mtx_unlock(&metadata_lock);
-			} else if (synced > 0) {
-				pjdlog_info("Synchronization interrupted. "
-				    "%jd bytes synchronized so far.",
-				    (intmax_t)synced);
 			}
 			rw_unlock(&hio_remote_lock[ncomp]);
 			continue;

From e23d2d0187abad36bdebaadc03432a2b8d2ab296 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:10:25 +0000
Subject: [PATCH 0283/1624] Don't increase number synchronized bytes in case of
 an error.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 429e914aa4a..8f96804406b 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1699,15 +1699,14 @@ sync_thread(void *arg __unused)
 			    strerror(hio->hio_errors[ncomp]));
 			goto free_queue;
 		}
+
+		synced += length;
 free_queue:
 		mtx_lock(&range_lock);
 		rangelock_del(range_sync, offset, length);
 		if (range_regular_wait)
 			cv_signal(&range_regular_cond);
 		mtx_unlock(&range_lock);
-
-		synced += length;
-
 		pjdlog_debug(2, "sync: (%p) Moving request to the free queue.",
 		    hio);
 		QUEUE_INSERT2(hio, free);

From 8f8c798c136bc9983a4825bad12078ae969b3de4 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:12:53 +0000
Subject: [PATCH 0284/1624] - Remove redundant and incorrect 'old' word from
 debug message. - Log disconnects as warnings.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 8f96804406b..52ac594ba6d 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -867,17 +867,19 @@ remote_close(struct hast_resource *res, int ncomp)
 	assert(res->hr_remotein != NULL);
 	assert(res->hr_remoteout != NULL);
 
-	pjdlog_debug(2, "Closing old incoming connection to %s.",
+	pjdlog_debug(2, "Closing incoming connection to %s.",
 	    res->hr_remoteaddr);
 	proto_close(res->hr_remotein);
 	res->hr_remotein = NULL;
-	pjdlog_debug(2, "Closing old outgoing connection to %s.",
+	pjdlog_debug(2, "Closing outgoing connection to %s.",
 	    res->hr_remoteaddr);
 	proto_close(res->hr_remoteout);
 	res->hr_remoteout = NULL;
 
 	rw_unlock(&hio_remote_lock[ncomp]);
 
+	pjdlog_warning("Disconnected from %s.", res->hr_remoteaddr);
+
 	/*
 	 * Stop synchronization if in-progress.
 	 */

From f7fe83f9f8a5bb345cc88fb2d230a2ceb8209584 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:26:37 +0000
Subject: [PATCH 0285/1624] Implement keepalive mechanism inside HAST protocol
 so we can detect secondary node failures quickly for HAST resources that are
 rarely modified.

Remove XXX from a comment now that the guard thread never sleeps infinitely.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hast.h      |  8 +++++-
 sbin/hastd/primary.c   | 60 ++++++++++++++++++++++++++++++++----------
 sbin/hastd/secondary.c | 14 +++++++++-
 3 files changed, 66 insertions(+), 16 deletions(-)

diff --git a/sbin/hastd/hast.h b/sbin/hastd/hast.h
index fda62c0814f..1f3b3860ed7 100644
--- a/sbin/hastd/hast.h
+++ b/sbin/hastd/hast.h
@@ -48,7 +48,12 @@
 
 #include "proto.h"
 
-#define	HAST_PROTO_VERSION	0
+/*
+ * Version history:
+ * 0 - initial version
+ * 1 - HIO_KEEPALIVE added
+ */
+#define	HAST_PROTO_VERSION	1
 
 #define	EHAST_OK		0
 #define	EHAST_NOENTRY		1
@@ -74,6 +79,7 @@
 #define	HIO_WRITE		2
 #define	HIO_DELETE		3
 #define	HIO_FLUSH		4
+#define	HIO_KEEPALIVE		5
 
 #define	HAST_TIMEOUT	5
 #define	HAST_CONFIG	"/etc/hast.conf"
diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 52ac594ba6d..dd26f4affb1 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -151,7 +151,11 @@ static pthread_mutex_t metadata_lock;
  */
 #define	HAST_NCOMPONENTS	2
 /*
- * Number of seconds to sleep before next reconnect try.
+ * Number of seconds to sleep between keepalive packets.
+ */
+#define	KEEPALIVE_SLEEP		10
+/*
+ * Number of seconds to sleep between reconnect retries.
  */
 #define	RECONNECT_SLEEP		5
 
@@ -886,11 +890,14 @@ remote_close(struct hast_resource *res, int ncomp)
 	sync_stop();
 
 	/*
-	 * Wake up guard thread, so it can immediately start reconnect.
+	 * Wake up guard thread (if we are not called from within guard thread),
+	 * so it can immediately start reconnect.
 	 */
-	mtx_lock(&hio_guard_lock);
-	cv_signal(&hio_guard_cond);
-	mtx_unlock(&hio_guard_lock);
+	if (!mtx_owned(&hio_guard_lock)) {
+		mtx_lock(&hio_guard_lock);
+		cv_signal(&hio_guard_cond);
+		mtx_unlock(&hio_guard_lock);
+	}
 }
 
 /*
@@ -1734,7 +1741,7 @@ sighandler(int sig)
 		assert(!"invalid condition");
 	}
 	/*
-	 * XXX: Racy, but if we cannot obtain hio_guard_lock here, we don't
+	 * Racy, but if we cannot obtain hio_guard_lock here, we don't
 	 * want to risk deadlock.
 	 */
 	unlock = mtx_trylock(&hio_guard_lock);
@@ -1851,6 +1858,32 @@ failed:
 	pjdlog_warning("Configuration not reloaded.");
 }
 
+static void
+keepalive_send(struct hast_resource *res, unsigned int ncomp)
+{
+	struct nv *nv;
+
+	nv = nv_alloc();
+	nv_add_uint8(nv, HIO_KEEPALIVE, "cmd");
+	if (nv_error(nv) != 0) {
+		nv_free(nv);
+		pjdlog_debug(1,
+		    "keepalive_send: Unable to prepare header to send.");
+		return;
+	}
+	if (hast_proto_send(res, res->hr_remoteout, nv, NULL, 0) < 0) {
+		pjdlog_common(LOG_DEBUG, 1, errno,
+		    "keepalive_send: Unable to send request");
+		nv_free(nv);
+		rw_unlock(&hio_remote_lock[ncomp]);
+		remote_close(res, ncomp);
+		rw_rlock(&hio_remote_lock[ncomp]);
+		return;
+	}
+	nv_free(nv);
+	pjdlog_debug(2, "keepalive_send: Request sent.");
+}
+
 /*
  * Thread guards remote connections and reconnects when needed, handles
  * signals, etc.
@@ -1874,20 +1907,19 @@ guard_thread(void *arg)
 			sighup_received = false;
 			config_reload();
 		}
-		/*
-		 * If all the connection will be fine, we will sleep until
-		 * someone wakes us up.
-		 * If any of the connections will be broken and we won't be
-		 * able to connect, we will sleep only for RECONNECT_SLEEP
-		 * seconds so we can retry soon.
-		 */
-		timeout = 0;
+
+		timeout = KEEPALIVE_SLEEP;
 		pjdlog_debug(2, "remote_guard: Checking connections.");
 		mtx_lock(&hio_guard_lock);
 		for (ii = 0; ii < ncomps; ii++) {
 			if (!ISREMOTE(ii))
 				continue;
 			rw_rlock(&hio_remote_lock[ii]);
+			if (ISCONNECTED(res, ii)) {
+				assert(res->hr_remotein != NULL);
+				assert(res->hr_remoteout != NULL);
+				keepalive_send(res, ii);
+			}
 			if (ISCONNECTED(res, ii)) {
 				assert(res->hr_remotein != NULL);
 				assert(res->hr_remoteout != NULL);
diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index c5394ff82ce..b76f6804891 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -413,6 +413,9 @@ reqlog(int loglevel, int debuglevel, int error, struct hio *hio, const char *fmt
 			    "WRITE(%ju, %ju).", (uintmax_t)hio->hio_offset,
 			    (uintmax_t)hio->hio_length);
 			break;
+		case HIO_KEEPALIVE:
+			(void)snprintf(msg + len, sizeof(msg) - len, "KEEPALIVE.");
+			break;
 		default:
 			(void)snprintf(msg + len, sizeof(msg) - len,
 			    "UNKNOWN(%u).", (unsigned int)hio->hio_cmd);
@@ -433,6 +436,8 @@ requnpack(struct hast_resource *res, struct hio *hio)
 		goto end;
 	}
 	switch (hio->hio_cmd) {
+	case HIO_KEEPALIVE:
+		break;
 	case HIO_READ:
 	case HIO_WRITE:
 	case HIO_DELETE:
@@ -517,7 +522,14 @@ recv_thread(void *arg)
 		}
 		reqlog(LOG_DEBUG, 2, -1, hio,
 		    "recv: (%p) Got request header: ", hio);
-		if (hio->hio_cmd == HIO_WRITE) {
+		if (hio->hio_cmd == HIO_KEEPALIVE) {
+			pjdlog_debug(2,
+			    "recv: (%p) Moving request to the free queue.",
+			    hio);
+			nv_free(hio->hio_nv);
+			QUEUE_INSERT(free, hio);
+			continue;
+		} else if (hio->hio_cmd == HIO_WRITE) {
 			if (hast_proto_recv_data(res, res->hr_remotein,
 			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
 				pjdlog_exit(EX_TEMPFAIL,

From 3f828c18e53c8f171c0a7385dfda6f3ffcf5e95a Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:28:39 +0000
Subject: [PATCH 0286/1624] Reduce indent where possible.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/parse.y | 60 +++++++++++++++++++++++-----------------------
 1 file changed, 30 insertions(+), 30 deletions(-)

diff --git a/sbin/hastd/parse.y b/sbin/hastd/parse.y
index b205dda7caf..5b4f3e5ac08 100644
--- a/sbin/hastd/parse.y
+++ b/sbin/hastd/parse.y
@@ -256,13 +256,13 @@ control_statement:	CONTROL STR
 			}
 			break;
 		case 1:
-			if (mynode) {
-				if (strlcpy(lconfig->hc_controladdr, $2,
-				    sizeof(lconfig->hc_controladdr)) >=
-				    sizeof(lconfig->hc_controladdr)) {
-					pjdlog_error("control argument is too long.");
-					return (1);
-				}
+			if (!mynode)
+				break;
+			if (strlcpy(lconfig->hc_controladdr, $2,
+			    sizeof(lconfig->hc_controladdr)) >=
+			    sizeof(lconfig->hc_controladdr)) {
+				pjdlog_error("control argument is too long.");
+				return (1);
 			}
 			break;
 		default:
@@ -283,13 +283,13 @@ listen_statement:	LISTEN STR
 			}
 			break;
 		case 1:
-			if (mynode) {
-				if (strlcpy(lconfig->hc_listenaddr, $2,
-				    sizeof(lconfig->hc_listenaddr)) >=
-				    sizeof(lconfig->hc_listenaddr)) {
-					pjdlog_error("listen argument is too long.");
-					return (1);
-				}
+			if (!mynode)
+				break;
+			if (strlcpy(lconfig->hc_listenaddr, $2,
+			    sizeof(lconfig->hc_listenaddr)) >=
+			    sizeof(lconfig->hc_listenaddr)) {
+				pjdlog_error("listen argument is too long.");
+				return (1);
 			}
 			break;
 		default:
@@ -493,14 +493,14 @@ name_statement:		NAME STR
 			}
 			break;
 		case 2:
-			if (mynode) {
-				assert(curres != NULL);
-				if (strlcpy(curres->hr_provname, $2,
-				    sizeof(curres->hr_provname)) >=
-				    sizeof(curres->hr_provname)) {
-					pjdlog_error("name argument is too long.");
-					return (1);
-				}
+			if (!mynode)
+				break;
+			assert(curres != NULL);
+			if (strlcpy(curres->hr_provname, $2,
+			    sizeof(curres->hr_provname)) >=
+			    sizeof(curres->hr_provname)) {
+				pjdlog_error("name argument is too long.");
+				return (1);
 			}
 			break;
 		default:
@@ -521,14 +521,14 @@ local_statement:	LOCAL STR
 			}
 			break;
 		case 2:
-			if (mynode) {
-				assert(curres != NULL);
-				if (strlcpy(curres->hr_localpath, $2,
-				    sizeof(curres->hr_localpath)) >=
-				    sizeof(curres->hr_localpath)) {
-					pjdlog_error("local argument is too long.");
-					return (1);
-				}
+			if (!mynode)
+				break;
+			assert(curres != NULL);
+			if (strlcpy(curres->hr_localpath, $2,
+			    sizeof(curres->hr_localpath)) >=
+			    sizeof(curres->hr_localpath)) {
+				pjdlog_error("local argument is too long.");
+				return (1);
 			}
 			break;
 		default:

From e64887c4d6e714b07a3706210700682925cd393a Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:35:39 +0000
Subject: [PATCH 0287/1624] When logging to stdout/stderr don't close those
 descriptors after fork().

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hooks.c | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)

diff --git a/sbin/hastd/hooks.c b/sbin/hastd/hooks.c
index 1fdeb750085..617e05143f2 100644
--- a/sbin/hastd/hooks.c
+++ b/sbin/hastd/hooks.c
@@ -61,8 +61,21 @@ descriptors(void)
 		pjdlog_errno(LOG_WARNING, "sysconf(_SC_OPEN_MAX) failed");
 		maxfd = 1024;
 	}
-	for (fd = 0; fd <= maxfd; fd++)
-		close(fd);
+	for (fd = 0; fd <= maxfd; fd++) {
+		switch (fd) {
+		case STDIN_FILENO:
+		case STDOUT_FILENO:
+		case STDERR_FILENO:
+			if (pjdlog_mode_get() == PJDLOG_MODE_STD)
+				break;
+			/* FALLTHROUGH */
+		default:
+			close(fd);
+			break;
+		}
+	}
+	if (pjdlog_mode_get() == PJDLOG_MODE_STD)
+		return;
 	/*
 	 * Redirect stdin, stdout and stderr to /dev/null.
 	 */

From 1cdaf10c4536eb8daa6823d069efbe4d32dcb1b4 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 14:38:12 +0000
Subject: [PATCH 0288/1624] - Run hooks in background - don't block waiting for
 them to finish. - Keep all hooks we're running in a global list, so we can
 report when   they finish and also report when they are running for too long.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hooks.c | 244 +++++++++++++++++++++++++++++++++++++++++----
 sbin/hastd/hooks.h |   8 +-
 2 files changed, 230 insertions(+), 22 deletions(-)

diff --git a/sbin/hastd/hooks.c b/sbin/hastd/hooks.c
index 617e05143f2..11ede20c78f 100644
--- a/sbin/hastd/hooks.c
+++ b/sbin/hastd/hooks.c
@@ -1,5 +1,6 @@
 /*-
  * Copyright (c) 2010 The FreeBSD Foundation
+ * Copyright (c) 2010 Pawel Jakub Dawidek 
  * All rights reserved.
  *
  * This software was developed by Pawel Jakub Dawidek under sponsorship from
@@ -31,21 +32,55 @@
 __FBSDID("$FreeBSD$");
 
 #include 
+#include 
 #include 
 
 #include 
+#include 
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
 
 #include 
 
 #include "hooks.h"
+#include "synch.h"
+
+/* Report processes that are running for too long not often than this value. */
+#define	REPORT_INTERVAL	60
+
+/* Are we initialized? */
+static bool hooks_initialized = false;
+
+/*
+ * Keep all processes we forked on a global queue, so we can report nicely
+ * when they finish or report that they are running for a long time.
+ */
+#define	HOOKPROC_MAGIC_ALLOCATED	0x80090ca
+#define	HOOKPROC_MAGIC_ONLIST		0x80090c0
+struct hookproc {
+	/* Magic. */
+	int	hp_magic;
+	/* PID of a forked child. */
+	pid_t	hp_pid;
+	/* When process were forked? */
+	time_t	hp_birthtime;
+	/* When we logged previous reported? */
+	time_t	hp_lastreport;
+	/* Path to executable and all the arguments we passed. */
+	char	hp_comm[PATH_MAX];
+	TAILQ_ENTRY(hookproc) hp_next;
+};
+static TAILQ_HEAD(, hookproc) hookprocs;
+static pthread_mutex_t hookprocs_lock;
 
 static void
 descriptors(void)
@@ -108,28 +143,197 @@ descriptors(void)
 	}
 }
 
-int
+void
+hook_init(void)
+{
+
+	mtx_init(&hookprocs_lock);
+	TAILQ_INIT(&hookprocs);
+	hooks_initialized = true;
+}
+
+static struct hookproc *
+hook_alloc(const char *path, char **args)
+{
+	struct hookproc *hp;
+	unsigned int ii;
+
+	hp = malloc(sizeof(*hp));
+	if (hp == NULL) {
+		pjdlog_error("Unable to allocate %zu bytes of memory for a hook.",
+		    sizeof(*hp));
+		return (NULL);
+	}
+
+	hp->hp_pid = 0;
+	hp->hp_birthtime = hp->hp_lastreport = time(NULL);
+	(void)strlcpy(hp->hp_comm, path, sizeof(hp->hp_comm));
+	/* We start at 2nd argument as we don't want to have exec name twice. */
+	for (ii = 1; args[ii] != NULL; ii++) {
+		(void)strlcat(hp->hp_comm, " ", sizeof(hp->hp_comm));
+		(void)strlcat(hp->hp_comm, args[ii], sizeof(hp->hp_comm));
+	}
+	if (strlen(hp->hp_comm) >= sizeof(hp->hp_comm) - 1) {
+		pjdlog_error("Exec path too long, correct configuration file.");
+		free(hp);
+		return (NULL);
+	}
+	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
+	return (hp);
+}
+
+static void
+hook_add(struct hookproc *hp, pid_t pid)
+{
+
+	assert(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
+	assert(hp->hp_pid == 0);
+
+	hp->hp_pid = pid;
+	mtx_lock(&hookprocs_lock);
+	hp->hp_magic = HOOKPROC_MAGIC_ONLIST;
+	TAILQ_INSERT_TAIL(&hookprocs, hp, hp_next);
+	mtx_unlock(&hookprocs_lock);
+}
+
+static void
+hook_remove(struct hookproc *hp)
+{
+
+	assert(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
+	assert(hp->hp_pid > 0);
+	assert(mtx_owned(&hookprocs_lock));
+
+	TAILQ_REMOVE(&hookprocs, hp, hp_next);
+	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
+}
+
+static void
+hook_free(struct hookproc *hp)
+{
+
+	assert(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
+	assert(hp->hp_pid > 0);
+
+	hp->hp_magic = 0;
+	free(hp);
+}
+
+static struct hookproc *
+hook_find(pid_t pid)
+{
+	struct hookproc *hp;
+
+	assert(mtx_owned(&hookprocs_lock));
+
+	TAILQ_FOREACH(hp, &hookprocs, hp_next) {
+		assert(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
+		assert(hp->hp_pid > 0);
+
+		if (hp->hp_pid == pid)
+			break;
+	}
+
+	return (hp);
+}
+
+void
+hook_check(bool sigchld)
+{
+	struct hookproc *hp, *hp2;
+	int status;
+	time_t now;
+	pid_t pid;
+
+	assert(hooks_initialized);
+
+	/*
+	 * If SIGCHLD was received, garbage collect finished processes.
+	 */
+	while (sigchld && (pid = wait3(&status, WNOHANG, NULL)) > 0) {
+		mtx_lock(&hookprocs_lock);
+		hp = hook_find(pid);
+		if (hp == NULL) {
+			mtx_unlock(&hookprocs_lock);
+			pjdlog_warning("Unknown process pid=%u", pid);
+			continue;
+		}
+		hook_remove(hp);
+		mtx_unlock(&hookprocs_lock);
+		if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
+			pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).",
+			    pid, hp->hp_comm);
+		} else if (WIFSIGNALED(status)) {
+			pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).",
+			    pid, WTERMSIG(status), hp->hp_comm);
+		} else {
+			pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).",
+			    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1,
+			    hp->hp_comm);
+		}
+		hook_free(hp);
+	}
+
+	/*
+	 * Report about processes that are running for a long time.
+	 */
+	now = time(NULL);
+	mtx_lock(&hookprocs_lock);
+	TAILQ_FOREACH_SAFE(hp, &hookprocs, hp_next, hp2) {
+		assert(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
+		assert(hp->hp_pid > 0);
+
+		/*
+		 * If process doesn't exists we somehow missed it.
+		 * Not much can be done expect for logging this situation.
+		 */
+		if (kill(hp->hp_pid, 0) == -1 && errno == ESRCH) {
+			pjdlog_warning("Hook disappeared (pid=%u, cmd=[%s]).",
+			    hp->hp_pid, hp->hp_comm);
+			hook_remove(hp);
+			hook_free(hp);
+			continue;
+		}
+
+		/*
+		 * Skip proccesses younger than 1 minute.
+		 */
+		if (now - hp->hp_lastreport < REPORT_INTERVAL)
+			continue;
+
+		/*
+		 * Hook is running for too long, report it.
+		 */
+		pjdlog_warning("Hook is running for %ju seconds (pid=%u, cmd=[%s]).",
+		    (uintmax_t)(now - hp->hp_birthtime), hp->hp_pid,
+		    hp->hp_comm);
+		hp->hp_lastreport = now;
+	}
+	mtx_unlock(&hookprocs_lock);
+}
+
+void
 hook_exec(const char *path, ...)
 {
 	va_list ap;
-	int ret;
 
 	va_start(ap, path);
-	ret = hook_execv(path, ap);
+	hook_execv(path, ap);
 	va_end(ap);
-	return (ret);
 }
 
-int
+void
 hook_execv(const char *path, va_list ap)
 {
+	struct hookproc *hp;
 	char *args[64];
 	unsigned int ii;
-	pid_t pid, wpid;
-	int status;
+	pid_t pid;
+
+	assert(hooks_initialized);
 
 	if (path == NULL || path[0] == '\0')
-		return (0);
+		return;
 
 	memset(args, 0, sizeof(args));
 	args[0] = basename(path);
@@ -140,22 +344,22 @@ hook_execv(const char *path, va_list ap)
 	}
 	assert(ii < sizeof(args) / sizeof(args[0]));
 
+	hp = hook_alloc(path, args);
+	if (hp == NULL)
+		return;
+
 	pid = fork();
 	switch (pid) {
 	case -1:	/* Error. */
-		pjdlog_errno(LOG_ERR, "Unable to fork %s", path);
-		return (-1);
+		pjdlog_errno(LOG_ERR, "Unable to fork to execute %s", path);
+		return;
 	case 0:		/* Child. */
 		descriptors();
 		execv(path, args);
 		pjdlog_errno(LOG_ERR, "Unable to execute %s", path);
 		exit(EX_SOFTWARE);
 	default:	/* Parent. */
+		hook_add(hp, pid);
 		break;
 	}
-
-	wpid = waitpid(pid, &status, 0);
-	assert(wpid == pid);
-
-	return (WEXITSTATUS(status));
 }
diff --git a/sbin/hastd/hooks.h b/sbin/hastd/hooks.h
index 799b781d319..d18ddc496a2 100644
--- a/sbin/hastd/hooks.h
+++ b/sbin/hastd/hooks.h
@@ -1,5 +1,6 @@
 /*-
  * Copyright (c) 2010 The FreeBSD Foundation
+ * Copyright (c) 2010 Pawel Jakub Dawidek 
  * All rights reserved.
  *
  * This software was developed by Pawel Jakub Dawidek under sponsorship from
@@ -33,8 +34,11 @@
 #define	_HOOKS_H_
 
 #include 
+#include 
 
-int hook_exec(const char *path, ...);
-int hook_execv(const char *path, va_list ap);
+void hook_init(void);
+void hook_check(bool sigchld);
+void hook_exec(const char *path, ...);
+void hook_execv(const char *path, va_list ap);
 
 #endif	/* !_HOOKS_H_ */

From 0becad39a71834f12c09c16070e20b9a0f70f5af Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 15:16:52 +0000
Subject: [PATCH 0289/1624] Allow to execute specified program on various HAST
 events.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hast.h    |  2 ++
 sbin/hastd/hastd.c   |  6 +++++-
 sbin/hastd/hastd.h   |  2 +-
 sbin/hastd/parse.y   | 43 ++++++++++++++++++++++++++++++++++++++++++-
 sbin/hastd/primary.c | 18 +++++++++++++++++-
 sbin/hastd/token.l   |  1 +
 6 files changed, 68 insertions(+), 4 deletions(-)

diff --git a/sbin/hastd/hast.h b/sbin/hastd/hast.h
index 1f3b3860ed7..71379178e76 100644
--- a/sbin/hastd/hast.h
+++ b/sbin/hastd/hast.h
@@ -127,6 +127,8 @@ struct hast_resource {
 	int	hr_extentsize;
 	/* Maximum number of extents that are kept dirty. */
 	int	hr_keepdirty;
+	/* Path to a program to execute on various events. */
+	char	hr_exec[PATH_MAX];
 
 	/* Path to local component. */
 	char	hr_localpath[PATH_MAX];
diff --git a/sbin/hastd/hastd.c b/sbin/hastd/hastd.c
index 31fc3bf22cc..c5eebf4a5b4 100644
--- a/sbin/hastd/hastd.c
+++ b/sbin/hastd/hastd.c
@@ -62,7 +62,7 @@ const char *cfgpath = HAST_CONFIG;
 /* Hastd configuration. */
 static struct hastd_config *cfg;
 /* Was SIGCHLD signal received? */
-static bool sigchld_received = false;
+bool sigchld_received = false;
 /* Was SIGHUP signal received? */
 bool sighup_received = false;
 /* Was SIGINT or SIGTERM signal received? */
@@ -189,6 +189,8 @@ resource_needs_restart(const struct hast_resource *res0,
 			return (true);
 		if (res0->hr_timeout != res1->hr_timeout)
 			return (true);
+		if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
+			return (true);
 	}
 	return (false);
 }
@@ -211,6 +213,8 @@ resource_needs_reload(const struct hast_resource *res0,
 		return (true);
 	if (res0->hr_timeout != res1->hr_timeout)
 		return (true);
+	if (strcmp(res0->hr_exec, res1->hr_exec) != 0)
+		return (true);
 	return (false);
 }
 
diff --git a/sbin/hastd/hastd.h b/sbin/hastd/hastd.h
index 12b384de6ed..a32e512411e 100644
--- a/sbin/hastd/hastd.h
+++ b/sbin/hastd/hastd.h
@@ -40,7 +40,7 @@
 #include "hast.h"
 
 extern const char *cfgpath;
-extern bool sigexit_received, sighup_received;
+extern bool sigchld_received, sigexit_received, sighup_received;
 extern struct pidfh *pfh;
 
 void hastd_primary(struct hast_resource *res);
diff --git a/sbin/hastd/parse.y b/sbin/hastd/parse.y
index 5b4f3e5ac08..ca575cf1238 100644
--- a/sbin/hastd/parse.y
+++ b/sbin/hastd/parse.y
@@ -61,6 +61,7 @@ static char depth0_control[HAST_ADDRSIZE];
 static char depth0_listen[HAST_ADDRSIZE];
 static int depth0_replication;
 static int depth0_timeout;
+static char depth0_exec[PATH_MAX];
 
 static char depth1_provname[PATH_MAX];
 static char depth1_localpath[PATH_MAX];
@@ -130,6 +131,7 @@ yy_config_parse(const char *config, bool exitonerror)
 	depth0_replication = HAST_REPLICATION_MEMSYNC;
 	strlcpy(depth0_control, HAST_CONTROL, sizeof(depth0_control));
 	strlcpy(depth0_listen, HASTD_LISTEN, sizeof(depth0_listen));
+	depth0_exec[0] = '\0';
 
 	lconfig = calloc(1, sizeof(*lconfig));
 	if (lconfig == NULL) {
@@ -190,6 +192,14 @@ yy_config_parse(const char *config, bool exitonerror)
 			 */
 			curres->hr_timeout = depth0_timeout;
 		}
+		if (curres->hr_exec[0] == '\0') {
+			/*
+			 * Exec is not set at resource-level.
+			 * Use global or default setting.
+			 */
+			strlcpy(curres->hr_exec, depth0_exec,
+			    sizeof(curres->hr_exec));
+		}
 	}
 
 	return (lconfig);
@@ -208,7 +218,7 @@ yy_config_free(struct hastd_config *config)
 }
 %}
 
-%token CONTROL LISTEN PORT REPLICATION TIMEOUT EXTENTSIZE RESOURCE NAME LOCAL REMOTE ON
+%token CONTROL LISTEN PORT REPLICATION TIMEOUT EXEC EXTENTSIZE RESOURCE NAME LOCAL REMOTE ON
 %token FULLSYNC MEMSYNC ASYNC
 %token NUM STR OB CB
 
@@ -239,6 +249,8 @@ statement:
 	|
 	timeout_statement
 	|
+	exec_statement
+	|
 	node_statement
 	|
 	resource_statement
@@ -338,6 +350,32 @@ timeout_statement:	TIMEOUT NUM
 	}
 	;
 
+exec_statement:		EXEC STR
+	{
+		switch (depth) {
+		case 0:
+			if (strlcpy(depth0_exec, $2, sizeof(depth0_exec)) >=
+			    sizeof(depth0_exec)) {
+				pjdlog_error("Exec path is too long.");
+				return (1);
+			}
+			break;
+		case 1:
+			if (curres == NULL)
+				break;
+			if (strlcpy(curres->hr_exec, $2,
+			    sizeof(curres->hr_exec)) >=
+			    sizeof(curres->hr_exec)) {
+				pjdlog_error("Exec path is too long.");
+				return (1);
+			}
+			break;
+		default:
+			assert(!"exec at wrong depth level");
+		}
+	}
+	;
+
 node_statement:		ON node_start OB node_entries CB
 	{
 		mynode = false;
@@ -456,6 +494,7 @@ resource_start:	STR
 		curres->hr_previous_role = HAST_ROLE_INIT;
 		curres->hr_replication = -1;
 		curres->hr_timeout = -1;
+		curres->hr_exec[0] = '\0';
 		curres->hr_provname[0] = '\0';
 		curres->hr_localpath[0] = '\0';
 		curres->hr_localfd = -1;
@@ -474,6 +513,8 @@ resource_entry:
 	|
 	timeout_statement
 	|
+	exec_statement
+	|
 	name_statement
 	|
 	local_statement
diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index dd26f4affb1..bc91266f2c8 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -60,6 +60,7 @@ __FBSDID("$FreeBSD$");
 #include "hast.h"
 #include "hast_proto.h"
 #include "hastd.h"
+#include "hooks.h"
 #include "metadata.h"
 #include "proto.h"
 #include "pjdlog.h"
@@ -433,6 +434,7 @@ init_environment(struct hast_resource *res __unused)
 	signal(SIGINT, sighandler);
 	signal(SIGTERM, sighandler);
 	signal(SIGHUP, sighandler);
+	signal(SIGCHLD, sighandler);
 }
 
 static void
@@ -791,6 +793,7 @@ hastd_primary(struct hast_resource *res)
 	signal(SIGHUP, SIG_DFL);
 	signal(SIGCHLD, SIG_DFL);
 
+	hook_init();
 	init_local(res);
 	if (real_remote(res) && init_remote(res, NULL, NULL))
 		sync_start();
@@ -1737,6 +1740,9 @@ sighandler(int sig)
 	case SIGHUP:
 		sighup_received = true;
 		break;
+	case SIGCHLD:
+		sigchld_received = true;
+		break;
 	default:
 		assert(!"invalid condition");
 	}
@@ -1788,6 +1794,7 @@ config_reload(void)
 #define MODIFIED_REMOTEADDR	0x1
 #define MODIFIED_REPLICATION	0x2
 #define MODIFIED_TIMEOUT	0x4
+#define MODIFIED_EXEC		0x8
 	modified = 0;
 	if (strcmp(gres->hr_remoteaddr, res->hr_remoteaddr) != 0) {
 		/*
@@ -1805,6 +1812,10 @@ config_reload(void)
 		gres->hr_timeout = res->hr_timeout;
 		modified |= MODIFIED_TIMEOUT;
 	}
+	if (strcmp(gres->hr_exec, res->hr_exec) != 0) {
+		strlcpy(gres->hr_exec, res->hr_exec, sizeof(gres->hr_exec));
+		modified |= MODIFIED_EXEC;
+	}
 	/*
 	 * If only timeout was modified we only need to change it without
 	 * reconnecting.
@@ -1830,7 +1841,8 @@ config_reload(void)
 				    "Unable to set connection timeout");
 			}
 		}
-	} else {
+	} else if ((modified &
+	    (MODIFIED_REMOTEADDR | MODIFIED_REPLICATION)) != 0) {
 		for (ii = 0; ii < ncomps; ii++) {
 			if (!ISREMOTE(ii))
 				continue;
@@ -1844,6 +1856,7 @@ config_reload(void)
 #undef	MODIFIED_REMOTEADDR
 #undef	MODIFIED_REPLICATION
 #undef	MODIFIED_TIMEOUT
+#undef	MODIFIED_EXEC
 
 	pjdlog_info("Configuration reloaded successfully.");
 	return;
@@ -1907,6 +1920,9 @@ guard_thread(void *arg)
 			sighup_received = false;
 			config_reload();
 		}
+		hook_check(sigchld_received);
+		if (sigchld_received)
+			sigchld_received = false;
 
 		timeout = KEEPALIVE_SLEEP;
 		pjdlog_debug(2, "remote_guard: Checking connections.");
diff --git a/sbin/hastd/token.l b/sbin/hastd/token.l
index e5d4ca10df2..05d600c6ef1 100644
--- a/sbin/hastd/token.l
+++ b/sbin/hastd/token.l
@@ -49,6 +49,7 @@ listen			{ DP; return LISTEN; }
 port			{ DP; return PORT; }
 replication		{ DP; return REPLICATION; }
 timeout			{ DP; return TIMEOUT; }
+exec			{ DP; return EXEC; }
 resource		{ DP; return RESOURCE; }
 name			{ DP; return NAME; }
 local			{ DP; return LOCAL; }

From ac59403c39fd73c5e43e81694398c00071d8355a Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 15:20:31 +0000
Subject: [PATCH 0290/1624] Document new 'exec' parameter.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hast.conf.5 | 40 +++++++++++++++++++++++++++++++++++++++-
 1 file changed, 39 insertions(+), 1 deletion(-)

diff --git a/sbin/hastd/hast.conf.5 b/sbin/hastd/hast.conf.5
index 11f7244e21e..f312648f9b9 100644
--- a/sbin/hastd/hast.conf.5
+++ b/sbin/hastd/hast.conf.5
@@ -1,4 +1,5 @@
 .\" Copyright (c) 2010 The FreeBSD Foundation
+.\" Copyright (c) 2010 Pawel Jakub Dawidek 
 .\" All rights reserved.
 .\"
 .\" This software was developed by Pawel Jakub Dawidek under sponsorship from
@@ -27,7 +28,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd August 5, 2010
+.Dd August 27, 2010
 .Dt HAST.CONF 5
 .Os
 .Sh NAME
@@ -59,6 +60,7 @@ control 
 listen 
 replication 
 timeout 
+exec 
 
 on  {
 	# Node section
@@ -78,6 +80,7 @@ resource  {
 	name 
 	local 
 	timeout 
+	exec 
 
 	on  {
 		# Resource-node section
@@ -203,6 +206,41 @@ replication mode is currently not implemented.
 Connection timeout in seconds.
 The default value is
 .Va 5 .
+.It Ic exec Aq path
+.Pp
+Execute the given program on various HAST events.
+Below is the list of currently implemented events and arguments the given
+program is executed with:
+.Bl -tag -width ".Ic xxxx"
+.It Ic " syncstart "
+.Pp
+Executed on primary node when synchronization process of secondary node is
+started.
+.Pp
+.It Ic " syncdone "
+.Pp
+Executed on primary node when synchronization process of secondary node is
+completed successfully.
+.Pp
+.It Ic " syncintr "
+.Pp
+Executed on primary node when synchronization process of secondary node is
+interrupted, most likely due to secondary node outage or connection failure
+between the nodes.
+.Pp
+.El
+The
+.Aq path
+argument should contain full path to executable program.
+If the given program exits with code different than
+.Va 0 ,
+.Nm hastd
+will log it as an error.
+.Pp
+The
+.Aq resource
+argument is resource name from the configuration file.
+.Pp
 .It Ic name Aq name
 .Pp
 GEOM provider name that will appear as

From 98b9eb0db20f0f604d3879a668824de9024fd49c Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Fri, 27 Aug 2010 18:17:46 +0000
Subject: [PATCH 0291/1624] Simplify the tcp pcblist estimate logic slightly.

MFC after:	3 days
---
 sys/netinet/tcp_subr.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/sys/netinet/tcp_subr.c b/sys/netinet/tcp_subr.c
index fe8f79a61ed..b537fb94958 100644
--- a/sys/netinet/tcp_subr.c
+++ b/sys/netinet/tcp_subr.c
@@ -1022,11 +1022,9 @@ tcp_pcblist(SYSCTL_HANDLER_ARGS)
 	 * resource-intensive to repeat twice on every request.
 	 */
 	if (req->oldptr == NULL) {
-		m = syncache_pcbcount();
-		n = V_tcbinfo.ipi_count;
-		n += imax((m + n) / 8, 10);
-		req->oldidx = 2 * (sizeof xig) +
-		    (m + n) * sizeof(struct xtcpcb);
+		n = V_tcbinfo.ipi_count + syncache_pcbcount();
+		n += imax(n / 8, 10);
+		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
 		return (0);
 	}
 

From b47f51b4a0739e624c34677044a6a5cc5b8faeb3 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Fri, 27 Aug 2010 19:53:57 +0000
Subject: [PATCH 0292/1624] Revamp XLR interrupt handling, the previous scheme
 does not work well on SMP.

We used to route all PIC based interrupts to cpu 0, and used the per-CPU
interrupt mask to enable/disable interrupts. But the interrupt threads can
run on any cpu on SMP, and the interrupt thread will re-enable the interrupts
on the CPU it runs on when it is done, and not on cpu0 where the PIC will
still send interrupts to.

The fix is move the disable/enable for PIC based interrupts to PIC, we will
ack on PIC only when the interrupt thread is done, and we do not use the
per-CPU interrupt mask.

The changes also introduce a way for subsystems to add a function that
will be called to clear the interrupt on the subsystem. Currently This is
used by the PCI/PCIe for doing additional work during the interrupt
handling.
---
 sys/mips/rmi/interrupt.h    |   9 ++-
 sys/mips/rmi/intr_machdep.c | 138 ++++++++++++++++++++++--------------
 sys/mips/rmi/iodi.c         |   6 +-
 sys/mips/rmi/pic.h          |  49 +++----------
 sys/mips/rmi/xlr_machdep.c  |   8 +--
 sys/mips/rmi/xlr_pci.c      |  37 +++-------
 6 files changed, 114 insertions(+), 133 deletions(-)

diff --git a/sys/mips/rmi/interrupt.h b/sys/mips/rmi/interrupt.h
index edb475a3270..8573338e45d 100644
--- a/sys/mips/rmi/interrupt.h
+++ b/sys/mips/rmi/interrupt.h
@@ -40,10 +40,9 @@
  * XLR needs custom pre and post handlers for PCI/PCI-e interrupts
  * XXX: maybe follow i386 intsrc model
  */
-void xlr_cpu_establish_hardintr(const char *, driver_filter_t *,
-    driver_intr_t *, void *, int, int, void **, void (*)(void *),
-    void (*)(void *), void (*)(void *), int (*)(void *, u_char));
-void xlr_mask_hard_irq(void *);
-void xlr_unmask_hard_irq(void *);
+void xlr_establish_intr(const char *name, driver_filter_t filt,
+    driver_intr_t handler, void *arg, int irq, int flags,
+    void **cookiep, void (*busack)(int));
+void xlr_enable_irq(int irq);
 
 #endif				/* _RMI_INTERRUPT_H_ */
diff --git a/sys/mips/rmi/intr_machdep.c b/sys/mips/rmi/intr_machdep.c
index 1af15a1502a..cf6df1ddbe3 100644
--- a/sys/mips/rmi/intr_machdep.c
+++ b/sys/mips/rmi/intr_machdep.c
@@ -49,34 +49,76 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 
-/*#include */
+struct xlr_intrsrc {
+	void (*busack)(int);		/* Additional ack */
+	struct intr_event *ie;		/* event corresponding to intr */
+	int irq;
+};
+	
+static struct xlr_intrsrc xlr_interrupts[XLR_MAX_INTR];
 static mips_intrcnt_t mips_intr_counters[XLR_MAX_INTR];
-static struct intr_event *mips_intr_events[XLR_MAX_INTR];
 static int intrcnt_index;
 
 void
-xlr_mask_hard_irq(void *source)
+xlr_enable_irq(int irq)
 {
-	uintptr_t irq = (uintptr_t) source;
-
-	write_c0_eimr64(read_c0_eimr64() & ~(1ULL << irq));
-}
-
-void
-xlr_unmask_hard_irq(void *source)
-{
-	uintptr_t irq = (uintptr_t) source;
 
 	write_c0_eimr64(read_c0_eimr64() | (1ULL << irq));
 }
 
 void
-xlr_cpu_establish_hardintr(const char *name, driver_filter_t * filt,
-    void (*handler) (void *), void *arg, int irq, int flags, void **cookiep,
-    void (*pre_ithread)(void *), void (*post_ithread)(void *),
-    void (*post_filter)(void *), int (*assign_cpu)(void *, u_char))
+cpu_establish_softintr(const char *name, driver_filter_t * filt,
+    void (*handler) (void *), void *arg, int irq, int flags,
+    void **cookiep)
+{
+
+	panic("Soft interrupts unsupported!\n");
+}
+
+void
+cpu_establish_hardintr(const char *name, driver_filter_t * filt,
+    void (*handler) (void *), void *arg, int irq, int flags,
+    void **cookiep)
+{
+
+	xlr_establish_intr(name, filt, handler, arg, irq, flags,
+	    cookiep, NULL);
+}
+
+static void
+xlr_post_filter(void *source)
+{
+	struct xlr_intrsrc *src = source;
+	
+	if (src->busack)
+		src->busack(src->irq);
+	pic_ack(PIC_IRQ_TO_INTR(src->irq));
+}
+
+static void
+xlr_pre_ithread(void *source)
+{
+	struct xlr_intrsrc *src = source;
+
+	if (src->busack)
+		src->busack(src->irq);
+}
+
+static void
+xlr_post_ithread(void *source)
+{
+	struct xlr_intrsrc *src = source;
+
+	pic_ack(PIC_IRQ_TO_INTR(src->irq));
+}
+
+void
+xlr_establish_intr(const char *name, driver_filter_t filt,
+    driver_intr_t handler, void *arg, int irq, int flags,
+    void **cookiep, void (*busack)(int))
 {
 	struct intr_event *ie;	/* descriptor for the IRQ */
+	struct xlr_intrsrc *src = NULL;
 	int errcode;
 
 	if (irq < 0 || irq > XLR_MAX_INTR)
@@ -86,43 +128,37 @@ xlr_cpu_establish_hardintr(const char *name, driver_filter_t * filt,
 	 * FIXME locking - not needed now, because we do this only on
 	 * startup from CPU0
 	 */
-	ie = mips_intr_events[irq];
-	/* mih->cntp = &intrcnt[irq]; */
-	if (ie == NULL) {
-		errcode = intr_event_create(&ie, (void *)(uintptr_t) irq, 0,
-		    irq, pre_ithread, post_ithread, post_filter, assign_cpu,
-		    "hard intr%d:", irq);
+	printf("[%s] Setup intr %d called on cpu %d (%d)\n", name, irq,
+	    xlr_cpu_id(), PCPU_GET(cpuid));
 
+	src = &xlr_interrupts[irq];
+	ie = src->ie;
+	if (ie == NULL) {
+		/*
+		 * PIC based interrupts need ack in PIC, and some SoC
+		 * components need additional acks (e.g. PCI)
+		 */
+		if (PIC_IRQ_IS_PICINTR(irq))
+			errcode = intr_event_create(&ie, src, 0, irq,
+			    xlr_pre_ithread, xlr_post_ithread, xlr_post_filter,
+			    NULL, "hard intr%d:", irq);
+		else {
+			if (filt == NULL)
+				panic("Not supported - non filter percpu intr");
+			errcode = intr_event_create(&ie, src, 0, irq,
+			    NULL, NULL, NULL, NULL, "hard intr%d:", irq);
+		}
 		if (errcode) {
 			printf("Could not create event for intr %d\n", irq);
 			return;
 		}
-		mips_intr_events[irq] = ie;
+		src->irq = irq;
+		src->busack = busack;
+		src->ie = ie;
 	}
-
 	intr_event_add_handler(ie, name, filt, handler, arg,
 	    intr_priority(flags), flags, cookiep);
-	xlr_unmask_hard_irq((void *)(uintptr_t) irq);
-}
-
-void
-cpu_establish_hardintr(const char *name, driver_filter_t * filt,
-    void (*handler) (void *), void *arg, int irq, int flags, void **cookiep)
-{
-	xlr_cpu_establish_hardintr(name, filt, handler, arg, irq,
-		flags, cookiep, xlr_mask_hard_irq, xlr_unmask_hard_irq,
-		NULL, NULL);
-}
-
-void
-cpu_establish_softintr(const char *name, driver_filter_t * filt,
-    void (*handler) (void *), void *arg, int irq, int flags,
-    void **cookiep)
-{
-	/* we don't separate them into soft/hard like other mips */
-	xlr_cpu_establish_hardintr(name, filt, handler, arg, irq,
-		flags, cookiep, xlr_mask_hard_irq, xlr_unmask_hard_irq,
-		NULL, NULL);
+	xlr_enable_irq(irq);
 }
 
 void
@@ -148,7 +184,7 @@ cpu_intr(struct trapframe *tf)
 	 * compare which ACKs the interrupt.
 	 */
 	if (eirr & (1 << IRQ_TIMER)) {
-		intr_event_handle(mips_intr_events[IRQ_TIMER], tf);
+		intr_event_handle(xlr_interrupts[IRQ_TIMER].ie, tf);
 		critical_exit();
 		return;
 	}
@@ -158,7 +194,7 @@ cpu_intr(struct trapframe *tf)
 		if ((eirr & (1ULL << i)) == 0)
 			continue;
 
-		ie = mips_intr_events[i];
+		ie = xlr_interrupts[i].ie;
 		/* Don't account special IRQs */
 		switch (i) {
 		case IRQ_IPI:
@@ -167,16 +203,12 @@ cpu_intr(struct trapframe *tf)
 		default:
 			mips_intrcnt_inc(mips_intr_counters[i]);
 		}
+
+		/* Ack the IRQ on the CPU */
 		write_c0_eirr64(1ULL << i);
-		pic_ack(i);
-		if (!ie || TAILQ_EMPTY(&ie->ie_handlers)) {
-			printf("stray interrupt %d\n", i);
-			continue;
-		}
 		if (intr_event_handle(ie, tf) != 0) {
 			printf("stray interrupt %d\n", i);
 		}
-		pic_delayed_ack(i);
 	}
 	critical_exit();
 }
diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index 09da00813af..5ee961f88b9 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -99,7 +99,7 @@ iodi_setup_intr(device_t dev, device_t child,
 		/* FIXME uart 1? */
 		cpu_establish_hardintr("uart", filt, intr, arg,
 		    PIC_UART_0_IRQ, flags, cookiep);
-		pic_setup_intr(PIC_IRT_UART_0_INDEX, PIC_UART_0_IRQ, 0x1);
+		pic_setup_intr(PIC_IRT_UART_0_INDEX, PIC_UART_0_IRQ, 0x1, 0);
 	} else if (strcmp(device_get_name(child), "rge") == 0) {
 		int irq;
 
@@ -107,11 +107,11 @@ iodi_setup_intr(device_t dev, device_t child,
 		irq = (intptr_t)ires->__r_i;
 		cpu_establish_hardintr("rge", filt, intr, arg, irq, flags,
 		    cookiep);
-		pic_setup_intr(irq - PIC_IRQ_BASE, irq, 0x1);
+		pic_setup_intr(irq - PIC_IRQ_BASE, irq, 0x1, 0);
 	} else if (strcmp(device_get_name(child), "ehci") == 0) {
 		cpu_establish_hardintr("ehci", filt, intr, arg, PIC_USB_IRQ, flags,
 		    cookiep);
-		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1);
+		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1, 0);
 	}
 
 	return (0);
diff --git a/sys/mips/rmi/pic.h b/sys/mips/rmi/pic.h
index d8860c5ae84..3c777d8f5d7 100644
--- a/sys/mips/rmi/pic.h
+++ b/sys/mips/rmi/pic.h
@@ -29,16 +29,15 @@
  *
  * RMI_BSD */
 #ifndef _RMI_PIC_H_
-#define _RMI_PIC_H_
-#include 
+#define	_RMI_PIC_H_
 
+#include 
 #include 
 #include 
 #include 
 
 #define	PIC_IRT_WD_INDEX		0
 #define	PIC_IRT_TIMER_INDEX(i)		(1 + (i))
-#define	PIC_IRT_CLOCK_INDEX		PIC_IRT_TIMER_7_INDEX
 #define	PIC_IRT_UART_0_INDEX		9
 #define	PIC_IRT_UART_1_INDEX		10
 #define	PIC_IRT_I2C_0_INDEX		11
@@ -70,7 +69,6 @@
 #define	PIC_IRT_PCIE_FATAL_INDEX	29
 #define	PIC_IRT_GPIO_B_INDEX		30
 #define	PIC_IRT_USB_INDEX		31
-
 #define	PIC_NUM_IRTS			32
 
 #define	PIC_CLOCK_TIMER			7
@@ -102,7 +100,6 @@
 #define	PIC_TIMER_COUNT_1(i)	(PIC_TIMER_COUNT_0_BASE + (i))
 #define	PIC_TIMER_HZ		66000000U
 
-
 /*
  * We use a simple mapping form PIC interrupts to CPU IRQs.
  * The PIC interrupts 0-31 are mapped to CPU irq's 8-39.
@@ -111,7 +108,7 @@
  */
 #define	PIC_IRQ_BASE		8
 #define	PIC_INTR_TO_IRQ(i)	(PIC_IRQ_BASE + (i))
-#define	PIC_IRT_FIRST_IRQ	PIC_IRQ_BASE
+#define	PIC_IRQ_TO_INTR(i)	((i) - PIC_IRQ_BASE)
 
 #define	PIC_WD_IRQ		(PIC_IRQ_BASE + PIC_IRT_WD_INDEX)
 #define	PIC_TIMER_IRQ(i)	(PIC_IRQ_BASE + PIC_IRT_TIMER_INDEX(i))
@@ -137,7 +134,6 @@
 #define	PIC_BRIDGE_BERR_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_BERR_INDEX)
 #define	PIC_BRIDGE_TB_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_TB_INDEX)
 #define	PIC_BRIDGE_AERR_NMI_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_AERR_NMI_INDEX)
-
 #define	PIC_BRIDGE_ERR_IRQ	(PIC_IRQ_BASE + PIC_IRT_BRIDGE_ERR_INDEX)
 #define	PIC_PCIE_LINK0_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_LINK0_INDEX)
 #define	PIC_PCIE_LINK1_IRQ	(PIC_IRQ_BASE + PIC_IRT_PCIE_LINK1_INDEX)
@@ -148,9 +144,10 @@
 #define	PIC_GPIO_B_IRQ		(PIC_IRQ_BASE + PIC_IRT_GPIO_B_INDEX)
 #define	PIC_USB_IRQ		(PIC_IRQ_BASE + PIC_IRT_USB_INDEX)
 
-#define	PIC_IRT_LAST_IRQ	PIC_USB_IRQ
-#define	PIC_IRQ_IS_EDGE_TRIGGERED(irq) (((irq) >= PIC_TIMER_IRQ(0)) && ((irq) <= PIC_TIMER_IRQ(7)))
-#define	PIC_IRQ_IS_IRT(irq)	(((irq) >= PIC_IRT_FIRST_IRQ) && ((irq) <= PIC_IRT_LAST_IRQ))
+#define	PIC_IRQ_IS_PICINTR(irq)	((irq) >= PIC_IRQ_BASE && 		\
+				 (irq) < PIC_IRQ_BASE + PIC_NUM_IRTS)
+#define	PIC_IS_EDGE_TRIGGERED(i) ((i) >= PIC_IRT_TIMER_INDEX(0) &&	\
+				  (i) <= PIC_IRT_TIMER_INDEX(7))
 
 extern struct mtx xlr_pic_lock;
 
@@ -187,35 +184,11 @@ pic_update_control(__uint32_t control)
 }
 
 static __inline void 
-pic_ack(int irq)
+pic_ack(int picintr)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 
-	/* ack the pic, if needed */
-	if (!PIC_IRQ_IS_IRT(irq))
-		return;
-
-	if (PIC_IRQ_IS_EDGE_TRIGGERED(irq)) {
-		mtx_lock_spin(&xlr_pic_lock);
-		xlr_write_reg(mmio, PIC_INT_ACK, (1 << (irq - PIC_IRQ_BASE)));
-		mtx_unlock_spin(&xlr_pic_lock);
-	}
-	return;
-}
-
-static __inline void 
-pic_delayed_ack(int irq)
-{
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-
-	if (!PIC_IRQ_IS_IRT(irq))
-		return;
-	if (!PIC_IRQ_IS_EDGE_TRIGGERED(irq)) {
-		mtx_lock_spin(&xlr_pic_lock);
-		xlr_write_reg(mmio, PIC_INT_ACK, (1 << (irq - PIC_IRQ_BASE)));
-		mtx_unlock_spin(&xlr_pic_lock);
-	}
-	return;
+	xlr_write_reg(mmio, PIC_INT_ACK, 1 << picintr);
 }
 
 static __inline
@@ -230,13 +203,11 @@ void pic_send_ipi(int cpu, int ipi)
 }
 
 static __inline
-void pic_setup_intr(int picintr, int irq, uint32_t cpumask)
+void pic_setup_intr(int picintr, int irq, uint32_t cpumask, int level)
 {
         xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	int level;
 
 	mtx_lock_spin(&xlr_pic_lock);
-	level = PIC_IRQ_IS_EDGE_TRIGGERED(irq);
 	xlr_write_reg(mmio, PIC_IRT_0(picintr), cpumask);
 	xlr_write_reg(mmio, PIC_IRT_1(picintr), ((1 << 31) | (level << 30) |
 	    (1 << 6) | irq));
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index dd50b9272b0..dec8bc6bbf4 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -305,7 +305,7 @@ xlr_pic_init(void)
 	/* Initialize all IRT entries */
 	for (i = 0; i < PIC_NUM_IRTS; i++) {
 		irq = PIC_INTR_TO_IRQ(i);
-		level = PIC_IRQ_IS_EDGE_TRIGGERED(irq);
+		level = PIC_IS_EDGE_TRIGGERED(i);
 
 		/* Bind all PIC irqs to cpu 0 */
 		xlr_write_reg(mmio, PIC_IRT_0(i), 0x01);
@@ -575,11 +575,11 @@ platform_init_ap(int cpuid)
 	stat |= MIPS_SR_COP_2_BIT | MIPS_SR_COP_0_BIT;
 	mips_wr_status(stat);
 
-	xlr_unmask_hard_irq((void *)IRQ_IPI);
-	xlr_unmask_hard_irq((void *)IRQ_TIMER);
+	xlr_enable_irq(IRQ_IPI);
+	xlr_enable_irq(IRQ_TIMER);
 	if (xlr_thr_id() == 0) {
 		xlr_msgring_cpu_init(); 
-	 	xlr_unmask_hard_irq((void *)IRQ_MSGRING);
+	 	xlr_enable_irq(IRQ_MSGRING);
 	}
 
 	return;
diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c
index 6178985fe16..aa1458929a8 100644
--- a/sys/mips/rmi/xlr_pci.c
+++ b/sys/mips/rmi/xlr_pci.c
@@ -403,24 +403,15 @@ xlr_map_msi(device_t pcib, device_t dev, int irq, uint64_t * addr,
 }
 
 static void
-bridge_pcix_ack(void *arg)
+bridge_pcix_ack(int irq)
 {
 
 	xlr_read_reg(xlr_io_mmio(XLR_IO_PCIX_OFFSET), 0x140 >> 2);
 }
 
 static void
-bridge_pcix_mask_ack(void *arg)
+bridge_pcie_ack(int irq)
 {
-
-	xlr_mask_hard_irq(arg);
-	bridge_pcix_ack(arg);
-}
-	
-static void
-bridge_pcie_ack(void *arg)
-{
-	int irq = (intptr_t)arg;
 	uint32_t reg;
 	xlr_reg_t *pcie_mmio_le = xlr_io_mmio(XLR_IO_PCIE_1_OFFSET);
 
@@ -443,14 +434,6 @@ bridge_pcie_ack(void *arg)
 	xlr_write_reg(pcie_mmio_le, reg>>2, 0xffffffff);
 }
 
-static void
-bridge_pcie_mask_ack(void *arg)
-{
-
-	xlr_mask_hard_irq(arg);
-	bridge_pcie_ack(arg);
-}
-
 static int
 mips_platform_pci_setup_intr(device_t dev, device_t child,
     struct resource *irq, int flags,
@@ -475,17 +458,13 @@ mips_platform_pci_setup_intr(device_t dev, device_t child,
 		return (0);
 
 	if (xlr_board_info.is_xls == 0) {
-		xlr_cpu_establish_hardintr(device_get_name(child), filt,
-		    intr, arg, PIC_PCIX_IRQ, flags, cookiep,
-		    bridge_pcix_mask_ack, xlr_unmask_hard_irq,
-		    bridge_pcix_ack, NULL);
-		pic_setup_intr(PIC_IRT_PCIX_INDEX, PIC_PCIX_IRQ, 0x1);
+		xlr_establish_intr(device_get_name(child), filt,
+		    intr, arg, PIC_PCIX_IRQ, flags, cookiep, bridge_pcix_ack);
+		pic_setup_intr(PIC_IRT_PCIX_INDEX, PIC_PCIX_IRQ, 0x1, 0);
 	} else {
-		xlr_cpu_establish_hardintr(device_get_name(child), filt,
-		    intr, arg, xlrirq, flags, cookiep,
-	    	    bridge_pcie_mask_ack, xlr_unmask_hard_irq,
-		    bridge_pcie_ack, NULL);
-		pic_setup_intr(xlrirq - PIC_IRQ_BASE, xlrirq, 0x1);
+		xlr_establish_intr(device_get_name(child), filt,
+		    intr, arg, xlrirq, flags, cookiep, bridge_pcie_ack);
+		pic_setup_intr(xlrirq - PIC_IRQ_BASE, xlrirq, 0x1, 0);
 	}
 
 	return (bus_generic_setup_intr(dev, child, irq, flags, filt, intr,

From 3eaca8526c379d09c13e9a30f45cd7ea6ce886f1 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Fri, 27 Aug 2010 19:57:17 +0000
Subject: [PATCH 0293/1624] Do not call __pthread_cxa_finalize with invalid
 struct dl_phdr_info.

Reported and tested by:	Fabian Keil 
MFC after:	17 days
---
 lib/libc/stdlib/atexit.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libc/stdlib/atexit.c b/lib/libc/stdlib/atexit.c
index 97cf2344659..511172aef9a 100644
--- a/lib/libc/stdlib/atexit.c
+++ b/lib/libc/stdlib/atexit.c
@@ -200,6 +200,6 @@ __cxa_finalize(void *dso)
 	if (dso == NULL)
 		_MUTEX_DESTROY(&atexit_mutex);
 
-	if (&__pthread_cxa_finalize != NULL)
+	if (has_phdr && &__pthread_cxa_finalize != NULL)
 		__pthread_cxa_finalize(&phdr_info);
 }

From 01125a9381b76afcb1caf86121b7b62124ce4ffd Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 20:48:12 +0000
Subject: [PATCH 0294/1624] Add hooks execution.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index bc91266f2c8..0b02065c24f 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1517,6 +1517,8 @@ sync_thread(void *arg __unused)
 			pjdlog_info("Synchronization interrupted. "
 			    "%jd bytes synchronized so far.",
 			    (intmax_t)synced);
+			hook_exec(res->hr_exec, "syncintr",
+			    res->hr_name, NULL);
 		}
 		while (!sync_inprogress) {
 			dorewind = true;
@@ -1549,6 +1551,8 @@ sync_thread(void *arg __unused)
 				pjdlog_info("Synchronization started. %ju bytes to go.",
 				    (uintmax_t)(res->hr_extentsize *
 				    activemap_ndirty(res->hr_amp)));
+				hook_exec(res->hr_exec, "syncstart",
+				    res->hr_name, NULL);
 			}
 		}
 		if (offset < 0) {
@@ -1565,6 +1569,8 @@ sync_thread(void *arg __unused)
 					pjdlog_info("Synchronization complete. "
 					    "%jd bytes synchronized.",
 					    (intmax_t)synced);
+					hook_exec(res->hr_exec, "syncdone",
+					    res->hr_name, NULL);
 				}
 				mtx_lock(&metadata_lock);
 				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;

From eba09893fd90450b6cde213f481404218d8e0d5d Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 20:49:06 +0000
Subject: [PATCH 0295/1624] Check if no signals were delivered just before
 going to sleep.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 0b02065c24f..2d8a0e48412 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1988,7 +1988,9 @@ guard_thread(void *arg)
 				rw_unlock(&hio_remote_lock[ii]);
 			}
 		}
-		(void)cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
+		/* Sleep only if a signal wasn't delivered in the meantime. */
+		if (!sigexit_received && !sighup_received && !sigchld_received)
+			cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
 		mtx_unlock(&hio_guard_lock);
 	}
 	/* NOTREACHED */

From b9cf0cf5fa7d96a24b2195a649b205b1edb8460e Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 21:20:32 +0000
Subject: [PATCH 0296/1624] Correct when we log interrupted synchronization.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 2d8a0e48412..c495f1093bc 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1507,18 +1507,16 @@ sync_thread(void *arg __unused)
 
 	ncomps = HAST_NCOMPONENTS;
 	dorewind = true;
-	synced = -1;
+	synced = 0;
+	offset = -1;
 
 	for (;;) {
 		mtx_lock(&sync_lock);
-		if (synced == -1)
-			synced = 0;
-		else if (!sync_inprogress) {
+		if (offset >= 0 && !sync_inprogress) {
 			pjdlog_info("Synchronization interrupted. "
 			    "%jd bytes synchronized so far.",
 			    (intmax_t)synced);
-			hook_exec(res->hr_exec, "syncintr",
-			    res->hr_name, NULL);
+			hook_exec(res->hr_exec, "syncintr", res->hr_name, NULL);
 		}
 		while (!sync_inprogress) {
 			dorewind = true;

From 4767ee29f149c9a34379763e7b537ee821639b3a Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 21:26:55 +0000
Subject: [PATCH 0297/1624] When logging to stdout/stderr, flush after each
 log.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/pjdlog.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sbin/hastd/pjdlog.c b/sbin/hastd/pjdlog.c
index 6891893cea8..ef3026f7745 100644
--- a/sbin/hastd/pjdlog.c
+++ b/sbin/hastd/pjdlog.c
@@ -217,6 +217,7 @@ pjdlogv_common(int loglevel, int debuglevel, int error, const char *fmt,
 		if (error != -1)
 			fprintf(out, ": %s.", strerror(error));
 		fprintf(out, "\n");
+		fflush(out);
 		break;
 	    }
 	case PJDLOG_MODE_SYSLOG:

From 5da2320932afb7ad2f17125b8d07a9ed82c3cacc Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 21:28:02 +0000
Subject: [PATCH 0298/1624] When SIGTERM or SIGINT is received, terminate
 worker processes.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hastd.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/sbin/hastd/hastd.c b/sbin/hastd/hastd.c
index c5eebf4a5b4..785798ad768 100644
--- a/sbin/hastd/hastd.c
+++ b/sbin/hastd/hastd.c
@@ -82,6 +82,10 @@ sighandler(int sig)
 {
 
 	switch (sig) {
+	case SIGINT:
+	case SIGTERM:
+		sigexit_received = true;
+		break;
 	case SIGCHLD:
 		sigchld_received = true;
 		break;
@@ -373,6 +377,25 @@ failed:
 	pjdlog_warning("Configuration not reloaded.");
 }
 
+static void
+terminate_workers(void)
+{
+	struct hast_resource *res;
+
+	pjdlog_info("Termination signal received, exiting.");
+	TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
+		if (res->hr_workerpid == 0)
+			continue;
+		pjdlog_info("Terminating worker process (resource=%s, role=%s, pid=%u).",
+		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
+		if (kill(res->hr_workerpid, SIGTERM) == 0)
+			continue;
+		pjdlog_errno(LOG_WARNING,
+		    "Unable to send signal to worker process (resource=%s, role=%s, pid=%u).",
+		    res->hr_name, role2str(res->hr_role), res->hr_workerpid);
+	}
+}
+
 static void
 listen_accept(void)
 {
@@ -599,6 +622,11 @@ main_loop(void)
 	int cfd, lfd, maxfd, ret;
 
 	for (;;) {
+		if (sigexit_received) {
+			sigexit_received = false;
+			terminate_workers();
+			exit(EX_OK);
+		}
 		if (sigchld_received) {
 			sigchld_received = false;
 			child_exit();
@@ -692,6 +720,8 @@ main(int argc, char *argv[])
 	cfg = yy_config_parse(cfgpath, true);
 	assert(cfg != NULL);
 
+	signal(SIGINT, sighandler);
+	signal(SIGTERM, sighandler);
 	signal(SIGHUP, sighandler);
 	signal(SIGCHLD, sighandler);
 

From 4e52cdd0f7a493995d94ed3bc5ca92c08b4a99db Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 27 Aug 2010 21:31:15 +0000
Subject: [PATCH 0299/1624] Use ZFS_CTLDIR_NAME instead of hardcoding ".zfs".

---
 sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
index 361b17d0763..ab1ba02d705 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
@@ -965,9 +965,10 @@ zfsctl_snapdir_lookup(ap)
 	dmu_objset_close(snap);
 domount:
 	mountpoint_len = strlen(dvp->v_vfsp->mnt_stat.f_mntonname) +
-	    strlen("/.zfs/snapshot/") + strlen(nm) + 1;
+	    strlen("/" ZFS_CTLDIR_NAME "/snapshot/") + strlen(nm) + 1;
 	mountpoint = kmem_alloc(mountpoint_len, KM_SLEEP);
-	(void) snprintf(mountpoint, mountpoint_len, "%s/.zfs/snapshot/%s",
+	(void) snprintf(mountpoint, mountpoint_len,
+	    "%s/" ZFS_CTLDIR_NAME "/snapshot/%s",
 	    dvp->v_vfsp->mnt_stat.f_mntonname, nm);
 	err = mount_snapshot(curthread, vpp, "zfs", mountpoint, snapname, 0);
 	kmem_free(mountpoint, mountpoint_len);

From c749353940a485fab91e92345ea2cf416eef750c Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Fri, 27 Aug 2010 23:22:58 +0000
Subject: [PATCH 0300/1624] MFp4 CH=182972:

Add explicit linkstate UP/DOWN for the epair.  This is needed by carp(4)
and other things to work.

MFC after:	5 days
---
 sys/net/if_epair.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/sys/net/if_epair.c b/sys/net/if_epair.c
index 13907e42461..ac0c8018702 100644
--- a/sys/net/if_epair.c
+++ b/sys/net/if_epair.c
@@ -832,6 +832,8 @@ epair_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
 	/* Tell the world, that we are ready to rock. */
 	sca->ifp->if_drv_flags |= IFF_DRV_RUNNING;
 	scb->ifp->if_drv_flags |= IFF_DRV_RUNNING;
+	if_link_state_change(sca->ifp, LINK_STATE_UP);
+	if_link_state_change(scb->ifp, LINK_STATE_UP);
 
 	return (0);
 }
@@ -859,6 +861,8 @@ epair_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
 	scb = oifp->if_softc;
 
 	DPRINTF("ifp=%p oifp=%p\n", ifp, oifp);
+	if_link_state_change(ifp, LINK_STATE_DOWN);
+	if_link_state_change(oifp, LINK_STATE_DOWN);
 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	oifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	ether_ifdetach(oifp);

From dce8a362dfbf2315872013c9ae6f1c3369d59bf3 Mon Sep 17 00:00:00 2001
From: Jack F Vogel 
Date: Fri, 27 Aug 2010 23:24:08 +0000
Subject: [PATCH 0301/1624] Add support for Intel Cougar Point SMBus
 controller.

MFC afer 1 week
---
 sys/dev/ichsmb/ichsmb_pci.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/sys/dev/ichsmb/ichsmb_pci.c b/sys/dev/ichsmb/ichsmb_pci.c
index 0843afe40cf..c90b7059f0c 100644
--- a/sys/dev/ichsmb/ichsmb_pci.c
+++ b/sys/dev/ichsmb/ichsmb_pci.c
@@ -81,6 +81,7 @@ __FBSDID("$FreeBSD$");
 #define ID_PCH				0x3b308086
 #define ID_6300ESB			0x25a48086
 #define	ID_631xESB			0x269b8086
+#define ID_CPT				0x1c228086
 
 #define PCIS_SERIALBUS_SMBUS_PROGIF	0x00
 
@@ -174,6 +175,9 @@ ichsmb_pci_probe(device_t dev)
 	case ID_631xESB:
 		device_set_desc(dev, "Intel 631xESB/6321ESB (ESB2) SMBus controller");
 		break;
+	case ID_CPT:
+		device_set_desc(dev, "Intel Cougar Point SMBus controller");
+		break;
 	default:
 		return (ENXIO);
 	}

From 5c8080f0d940f38ed1f5e1c017f7cb5a55b8b775 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Fri, 27 Aug 2010 23:50:13 +0000
Subject: [PATCH 0302/1624] Make sure not to access unallocated stats memory.

Reviewed by:	jfv
---
 sys/dev/e1000/if_igb.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/sys/dev/e1000/if_igb.c b/sys/dev/e1000/if_igb.c
index 412ea9e8e0d..fd8804abde3 100644
--- a/sys/dev/e1000/if_igb.c
+++ b/sys/dev/e1000/if_igb.c
@@ -509,6 +509,11 @@ igb_attach(device_t dev)
 		adapter->stats =
 		    (struct e1000_hw_stats *)malloc(sizeof \
 		    (struct e1000_hw_stats), M_DEVBUF, M_NOWAIT | M_ZERO);
+	if (adapter->stats == NULL) {
+		device_printf(dev, "Can not allocate stats memory\n");
+		error = ENOMEM;
+		goto err_late;
+	}
 
 	/*
 	** Start from a known state, this is
@@ -4893,7 +4898,8 @@ igb_vf_init_stats(struct adapter *adapter)
 	struct e1000_vf_stats	*stats;
 
 	stats = (struct e1000_vf_stats	*)adapter->stats;
-
+	if (stats == NULL)
+		return;
         stats->last_gprc = E1000_READ_REG(hw, E1000_VFGPRC);
         stats->last_gorc = E1000_READ_REG(hw, E1000_VFGORC);
         stats->last_gptc = E1000_READ_REG(hw, E1000_VFGPTC);

From ad1917be3760d5441402a0fe6403662671faed3e Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sat, 28 Aug 2010 00:09:19 +0000
Subject: [PATCH 0303/1624] Do not call voluntary panic(9) in case of
 if_alloc() failure.

Reviewed by:	jfv
---
 sys/dev/e1000/if_em.c  | 16 +++++++++++-----
 sys/dev/e1000/if_igb.c | 16 +++++++++++-----
 sys/dev/e1000/if_lem.c | 16 +++++++++++-----
 sys/dev/ixgb/if_ixgb.c | 17 +++++++++++------
 sys/dev/ixgbe/ixgbe.c  | 17 +++++++++++------
 5 files changed, 55 insertions(+), 27 deletions(-)

diff --git a/sys/dev/e1000/if_em.c b/sys/dev/e1000/if_em.c
index e520512b20f..86f28e31020 100644
--- a/sys/dev/e1000/if_em.c
+++ b/sys/dev/e1000/if_em.c
@@ -213,7 +213,7 @@ static int	em_setup_msix(struct adapter *);
 static void	em_free_pci_resources(struct adapter *);
 static void	em_local_timer(void *);
 static void	em_reset(struct adapter *);
-static void	em_setup_interface(device_t, struct adapter *);
+static int	em_setup_interface(device_t, struct adapter *);
 
 static void	em_setup_transmit_structures(struct adapter *);
 static void	em_initialize_transmit_unit(struct adapter *);
@@ -628,7 +628,8 @@ em_attach(device_t dev)
 	em_get_wakeup(dev);
 
 	/* Setup OS specific network interface */
-	em_setup_interface(dev, adapter);
+	if (em_setup_interface(dev, adapter) != 0)
+		goto err_late;
 
 	em_reset(adapter);
 
@@ -669,6 +670,8 @@ err_late:
 	em_free_transmit_structures(adapter);
 	em_free_receive_structures(adapter);
 	em_release_hw_control(adapter);
+	if (adapter->ifp != NULL)
+		if_free(adapter->ifp);
 err_pci:
 	em_free_pci_resources(adapter);
 	EM_CORE_LOCK_DESTROY(adapter);
@@ -2646,7 +2649,7 @@ em_reset(struct adapter *adapter)
  *  Setup networking device structure and register an interface.
  *
  **********************************************************************/
-static void
+static int
 em_setup_interface(device_t dev, struct adapter *adapter)
 {
 	struct ifnet   *ifp;
@@ -2654,8 +2657,10 @@ em_setup_interface(device_t dev, struct adapter *adapter)
 	INIT_DEBUGOUT("em_setup_interface: begin");
 
 	ifp = adapter->ifp = if_alloc(IFT_ETHER);
-	if (ifp == NULL)
-		panic("%s: can not if_alloc()", device_get_nameunit(dev));
+	if (ifp == NULL) {
+		device_printf(dev, "can not allocate ifnet structure\n");
+		return (-1);
+	}
 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
 	ifp->if_mtu = ETHERMTU;
 	ifp->if_init =  em_init;
@@ -2742,6 +2747,7 @@ em_setup_interface(device_t dev, struct adapter *adapter)
 	}
 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
+	return (0);
 }
 
 
diff --git a/sys/dev/e1000/if_igb.c b/sys/dev/e1000/if_igb.c
index fd8804abde3..d8371af8d8f 100644
--- a/sys/dev/e1000/if_igb.c
+++ b/sys/dev/e1000/if_igb.c
@@ -178,7 +178,7 @@ static int	igb_setup_msix(struct adapter *);
 static void	igb_free_pci_resources(struct adapter *);
 static void	igb_local_timer(void *);
 static void	igb_reset(struct adapter *);
-static void	igb_setup_interface(device_t, struct adapter *);
+static int	igb_setup_interface(device_t, struct adapter *);
 static int	igb_allocate_queues(struct adapter *);
 static void	igb_configure_queues(struct adapter *);
 
@@ -564,7 +564,8 @@ igb_attach(device_t dev)
 		goto err_late;
 
 	/* Setup OS specific network interface */
-	igb_setup_interface(dev, adapter);
+	if (igb_setup_interface(dev, adapter) != 0)
+		goto err_late;
 
 	/* Now get a good starting state */
 	igb_reset(adapter);
@@ -613,6 +614,8 @@ err_late:
 	igb_free_transmit_structures(adapter);
 	igb_free_receive_structures(adapter);
 	igb_release_hw_control(adapter);
+	if (adapter->ifp != NULL)
+		if_free(adapter->ifp);
 err_pci:
 	igb_free_pci_resources(adapter);
 	IGB_CORE_LOCK_DESTROY(adapter);
@@ -2658,7 +2661,7 @@ igb_reset(struct adapter *adapter)
  *  Setup networking device structure and register an interface.
  *
  **********************************************************************/
-static void
+static int
 igb_setup_interface(device_t dev, struct adapter *adapter)
 {
 	struct ifnet   *ifp;
@@ -2666,8 +2669,10 @@ igb_setup_interface(device_t dev, struct adapter *adapter)
 	INIT_DEBUGOUT("igb_setup_interface: begin");
 
 	ifp = adapter->ifp = if_alloc(IFT_ETHER);
-	if (ifp == NULL)
-		panic("%s: can not if_alloc()", device_get_nameunit(dev));
+	if (ifp == NULL) {
+		device_printf(dev, "can not allocate ifnet structure\n");
+		return (-1);
+	}
 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
 	ifp->if_mtu = ETHERMTU;
 	ifp->if_init =  igb_init;
@@ -2744,6 +2749,7 @@ igb_setup_interface(device_t dev, struct adapter *adapter)
 	}
 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
+	return (0);
 }
 
 
diff --git a/sys/dev/e1000/if_lem.c b/sys/dev/e1000/if_lem.c
index 1f03f7b46d2..f5c9e2932a3 100644
--- a/sys/dev/e1000/if_lem.c
+++ b/sys/dev/e1000/if_lem.c
@@ -186,7 +186,7 @@ static int	lem_allocate_irq(struct adapter *adapter);
 static void	lem_free_pci_resources(struct adapter *);
 static void	lem_local_timer(void *);
 static int	lem_hardware_init(struct adapter *);
-static void	lem_setup_interface(device_t, struct adapter *);
+static int	lem_setup_interface(device_t, struct adapter *);
 static void	lem_setup_transmit_structures(struct adapter *);
 static void	lem_initialize_transmit_unit(struct adapter *);
 static int	lem_setup_receive_structures(struct adapter *);
@@ -620,7 +620,8 @@ lem_attach(device_t dev)
 	lem_get_wakeup(dev);
 
 	/* Setup OS specific network interface */
-	lem_setup_interface(dev, adapter);
+	if (lem_setup_interface(dev, adapter) != 0)
+		goto err_rx_struct;
 
 	/* Initialize statistics */
 	lem_update_stats_counters(adapter);
@@ -672,6 +673,8 @@ err_rx_desc:
 	lem_dma_free(adapter, &adapter->txdma);
 err_tx_desc:
 err_pci:
+	if (adapter->ifp != NULL)
+		if_free(adapter->ifp);
 	lem_free_pci_resources(adapter);
 	EM_TX_LOCK_DESTROY(adapter);
 	EM_RX_LOCK_DESTROY(adapter);
@@ -2388,7 +2391,7 @@ lem_hardware_init(struct adapter *adapter)
  *  Setup networking device structure and register an interface.
  *
  **********************************************************************/
-static void
+static int
 lem_setup_interface(device_t dev, struct adapter *adapter)
 {
 	struct ifnet   *ifp;
@@ -2396,8 +2399,10 @@ lem_setup_interface(device_t dev, struct adapter *adapter)
 	INIT_DEBUGOUT("lem_setup_interface: begin");
 
 	ifp = adapter->ifp = if_alloc(IFT_ETHER);
-	if (ifp == NULL)
-		panic("%s: can not if_alloc()", device_get_nameunit(dev));
+	if (ifp == NULL) {
+		device_printf(dev, "can not allocate ifnet structure\n");
+		return (-1);
+	}
 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
 	ifp->if_mtu = ETHERMTU;
 	ifp->if_init =  lem_init;
@@ -2473,6 +2478,7 @@ lem_setup_interface(device_t dev, struct adapter *adapter)
 	}
 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
+	return (0);
 }
 
 
diff --git a/sys/dev/ixgb/if_ixgb.c b/sys/dev/ixgb/if_ixgb.c
index 990f791dfbd..edb352f4b77 100644
--- a/sys/dev/ixgb/if_ixgb.c
+++ b/sys/dev/ixgb/if_ixgb.c
@@ -108,7 +108,7 @@ static int      ixgb_allocate_pci_resources(struct adapter *);
 static void     ixgb_free_pci_resources(struct adapter *);
 static void     ixgb_local_timer(void *);
 static int      ixgb_hardware_init(struct adapter *);
-static void     ixgb_setup_interface(device_t, struct adapter *);
+static int      ixgb_setup_interface(device_t, struct adapter *);
 static int      ixgb_setup_transmit_structures(struct adapter *);
 static void     ixgb_initialize_transmit_unit(struct adapter *);
 static int      ixgb_setup_receive_structures(struct adapter *);
@@ -331,7 +331,8 @@ ixgb_attach(device_t dev)
 		goto err_hw_init;
 	}
 	/* Setup OS specific network interface */
-	ixgb_setup_interface(dev, adapter);
+	if (ixgb_setup_interface(dev, adapter) != 0)
+		goto err_hw_init;
 
 	/* Initialize statistics */
 	ixgb_clear_hw_cntrs(&adapter->hw);
@@ -346,6 +347,8 @@ err_rx_desc:
 	ixgb_dma_free(adapter, &adapter->txdma);
 err_tx_desc:
 err_pci:
+	if (adapter->ifp != NULL)
+		if_free(adapter->ifp);
 	ixgb_free_pci_resources(adapter);
 	sysctl_ctx_free(&adapter->sysctl_ctx);
 	return (error);
@@ -1319,15 +1322,17 @@ ixgb_hardware_init(struct adapter * adapter)
  *  Setup networking device structure and register an interface.
  *
  **********************************************************************/
-static void
+static int
 ixgb_setup_interface(device_t dev, struct adapter * adapter)
 {
 	struct ifnet   *ifp;
 	INIT_DEBUGOUT("ixgb_setup_interface: begin");
 
 	ifp = adapter->ifp = if_alloc(IFT_ETHER);
-	if (ifp == NULL)
-		panic("%s: can not if_alloc()\n", device_get_nameunit(dev));
+	if (ifp == NULL) {
+		device_printf(dev, "can not allocate ifnet structure\n");
+		return (-1);
+	}
 #if __FreeBSD_version >= 502000
 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
 #else
@@ -1379,7 +1384,7 @@ ixgb_setup_interface(device_t dev, struct adapter * adapter)
 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
 
-	return;
+	return (0);
 }
 
 /********************************************************************
diff --git a/sys/dev/ixgbe/ixgbe.c b/sys/dev/ixgbe/ixgbe.c
index c514dc34f13..e7ecff8c8c8 100644
--- a/sys/dev/ixgbe/ixgbe.c
+++ b/sys/dev/ixgbe/ixgbe.c
@@ -119,7 +119,7 @@ static int	ixgbe_allocate_queues(struct adapter *);
 static int	ixgbe_setup_msix(struct adapter *);
 static void	ixgbe_free_pci_resources(struct adapter *);
 static void     ixgbe_local_timer(void *);
-static void     ixgbe_setup_interface(device_t, struct adapter *);
+static int      ixgbe_setup_interface(device_t, struct adapter *);
 static void     ixgbe_config_link(struct adapter *);
 
 static int      ixgbe_allocate_transmit_buffers(struct tx_ring *);
@@ -586,7 +586,8 @@ ixgbe_attach(device_t dev)
 		goto err_late;
 
 	/* Setup OS specific network interface */
-	ixgbe_setup_interface(dev, adapter);
+	if (ixgbe_setup_interface(dev, adapter) != 0)
+		goto err_late;
 
 	/* Sysctl for limiting the amount of work done in the taskqueue */
 	ixgbe_add_rx_process_limit(adapter, "rx_processing_limit",
@@ -632,6 +633,8 @@ err_late:
 	ixgbe_free_transmit_structures(adapter);
 	ixgbe_free_receive_structures(adapter);
 err_out:
+	if (adapter->ifp != NULL)
+		if_free(adapter->ifp);
 	ixgbe_free_pci_resources(adapter);
 	return (error);
 
@@ -2357,7 +2360,7 @@ mem:
  *  Setup networking device structure and register an interface.
  *
  **********************************************************************/
-static void
+static int
 ixgbe_setup_interface(device_t dev, struct adapter *adapter)
 {
 	struct ixgbe_hw *hw = &adapter->hw;
@@ -2366,8 +2369,10 @@ ixgbe_setup_interface(device_t dev, struct adapter *adapter)
 	INIT_DEBUGOUT("ixgbe_setup_interface: begin");
 
 	ifp = adapter->ifp = if_alloc(IFT_ETHER);
-	if (ifp == NULL)
-		panic("%s: can not if_alloc()\n", device_get_nameunit(dev));
+	if (ifp == NULL) {
+		device_printf(dev, "can not allocate ifnet structure\n");
+		return (-1);
+	}
 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
 	ifp->if_mtu = ETHERMTU;
 	ifp->if_baudrate = 1000000000;
@@ -2415,7 +2420,7 @@ ixgbe_setup_interface(device_t dev, struct adapter *adapter)
 	ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
 	ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
 
-	return;
+	return (0);
 }
 
 static void

From 6d23f8741b47a825ea2e20f0eef4a41e25872710 Mon Sep 17 00:00:00 2001
From: Jack F Vogel 
Date: Sat, 28 Aug 2010 00:09:46 +0000
Subject: [PATCH 0304/1624] Add Intel Cougar Point PCH LPC Controller Device
 IDs for watchdog support. Also add additional Intel Ibex Peak (5 Series/3400
 Series) PCH IDs.

MFC after a week
---
 sys/dev/ichwd/ichwd.c | 46 +++++++++++++++++++++++++++++++++++++++++++
 sys/dev/ichwd/ichwd.h | 46 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 92 insertions(+)

diff --git a/sys/dev/ichwd/ichwd.c b/sys/dev/ichwd/ichwd.c
index a3b112f06b2..727b96d3006 100644
--- a/sys/dev/ichwd/ichwd.c
+++ b/sys/dev/ichwd/ichwd.c
@@ -110,7 +110,53 @@ static struct ichwd_device ichwd_devices[] = {
 	{ DEVICEID_ICH10D,   "Intel ICH10D watchdog timer",	10 },
 	{ DEVICEID_ICH10DO,  "Intel ICH10DO watchdog timer",	10 },
 	{ DEVICEID_ICH10R,   "Intel ICH10R watchdog timer",	10 },
+	{ DEVICEID_PCH,      "Intel PCH watchdog timer",	10 },
+	{ DEVICEID_PCHM,     "Intel PCH watchdog timer",	10 },
+	{ DEVICEID_P55,      "Intel P55 watchdog timer",	10 },
+	{ DEVICEID_PM55,     "Intel PM55 watchdog timer",	10 },
 	{ DEVICEID_H55,      "Intel H55 watchdog timer",	10 },
+	{ DEVICEID_QM57,     "Intel QM57 watchdog timer",       10 },
+	{ DEVICEID_H57,      "Intel H57 watchdog timer",        10 },
+	{ DEVICEID_HM55,     "Intel HM55 watchdog timer",       10 },
+	{ DEVICEID_Q57,      "Intel Q57 watchdog timer",        10 },
+	{ DEVICEID_HM57,     "Intel HM57 watchdog timer",       10 },
+	{ DEVICEID_PCHMSFF,  "Intel PCHMSFF watchdog timer",    10 },
+	{ DEVICEID_QS57,     "Intel QS57 watchdog timer",       10 },
+	{ DEVICEID_3400,     "Intel 3400 watchdog timer",       10 },
+	{ DEVICEID_3420,     "Intel 3420 watchdog timer",       10 },
+	{ DEVICEID_3450,     "Intel 3450 watchdog timer",       10 },
+	{ DEVICEID_CPT0,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT1,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT2,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT3,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT4,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT5,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT6,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT7,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT8,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT9,     "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT10,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT11,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT12,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT13,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT14,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT15,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT16,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT17,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT18,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT19,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT20,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT21,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT22,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT23,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT23,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT25,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT26,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT27,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT28,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT29,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT30,    "Intel Cougar Point watchdog timer",	10 },
+	{ DEVICEID_CPT31,    "Intel Cougar Point watchdog timer",	10 },
 	{ 0, NULL, 0 },
 };
 
diff --git a/sys/dev/ichwd/ichwd.h b/sys/dev/ichwd/ichwd.h
index 9cc8f1b65d4..c0a11414468 100644
--- a/sys/dev/ichwd/ichwd.h
+++ b/sys/dev/ichwd/ichwd.h
@@ -64,6 +64,38 @@ struct ichwd_softc {
 };
 
 #define VENDORID_INTEL		0x8086
+#define DEVICEID_CPT0		0x1c40
+#define DEVICEID_CPT1		0x1c41
+#define DEVICEID_CPT2		0x1c42
+#define DEVICEID_CPT3		0x1c43
+#define DEVICEID_CPT4		0x1c44
+#define DEVICEID_CPT5		0x1c45
+#define DEVICEID_CPT6		0x1c46
+#define DEVICEID_CPT7		0x1c47
+#define DEVICEID_CPT8		0x1c48
+#define DEVICEID_CPT9		0x1c49
+#define DEVICEID_CPT10		0x1c4a
+#define DEVICEID_CPT11		0x1c4b
+#define DEVICEID_CPT12		0x1c4c
+#define DEVICEID_CPT13		0x1c4d
+#define DEVICEID_CPT14		0x1c4e
+#define DEVICEID_CPT15		0x1c4f
+#define DEVICEID_CPT16		0x1c50
+#define DEVICEID_CPT17		0x1c51
+#define DEVICEID_CPT18		0x1c52
+#define DEVICEID_CPT19		0x1c53
+#define DEVICEID_CPT20		0x1c54
+#define DEVICEID_CPT21		0x1c55
+#define DEVICEID_CPT22		0x1c56
+#define DEVICEID_CPT23		0x1c57
+#define DEVICEID_CPT24		0x1c58
+#define DEVICEID_CPT25		0x1c59
+#define DEVICEID_CPT26		0x1c5a
+#define DEVICEID_CPT27		0x1c5b
+#define DEVICEID_CPT28		0x1c5c
+#define DEVICEID_CPT29		0x1c5d
+#define DEVICEID_CPT30		0x1c5e
+#define DEVICEID_CPT31		0x1c5f
 #define DEVICEID_82801AA	0x2410
 #define DEVICEID_82801AB	0x2420
 #define DEVICEID_82801BA	0x2440
@@ -100,7 +132,21 @@ struct ichwd_softc {
 #define DEVICEID_ICH10D		0x3a1a
 #define DEVICEID_ICH10DO	0x3a14
 #define DEVICEID_ICH10R		0x3a16
+#define DEVICEID_PCH		0x3b00
+#define DEVICEID_PCHM		0x3b01
+#define DEVICEID_P55		0x3b02
+#define DEVICEID_PM55		0x3b03
 #define DEVICEID_H55		0x3b06
+#define DEVICEID_QM57		0x3b07
+#define DEVICEID_H57		0x3b08
+#define DEVICEID_HM55		0x3b09
+#define DEVICEID_Q57		0x3b0a
+#define DEVICEID_HM57		0x3b0b
+#define DEVICEID_PCHMSFF	0x3b0d
+#define DEVICEID_QS57		0x3b0f
+#define DEVICEID_3400		0x3b12
+#define DEVICEID_3420		0x3b14
+#define DEVICEID_3450		0x3b16
 
 /* ICH LPC Interface Bridge Registers (ICH5 and older) */
 #define ICH_GEN_STA		0xd4

From 880a50b5136d8a44bf1ff6938cf93f2ffbdf603a Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sat, 28 Aug 2010 00:16:49 +0000
Subject: [PATCH 0305/1624] If em(4) failed to allocate RX buffers, do not call
 panic(9). Just showing some buffer allocation error is more appropriate
 action for drivers. This should fix occasional panic reported on em(4) when
 driver encountered resource shortage.

Reviewed by:	jfv
---
 sys/dev/e1000/if_em.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/sys/dev/e1000/if_em.c b/sys/dev/e1000/if_em.c
index 86f28e31020..56859ea3739 100644
--- a/sys/dev/e1000/if_em.c
+++ b/sys/dev/e1000/if_em.c
@@ -3843,7 +3843,7 @@ em_setup_receive_ring(struct rx_ring *rxr)
 		rxbuf = &rxr->rx_buffers[j];
 		rxbuf->m_head = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
 		if (rxbuf->m_head == NULL)
-			panic("RX ring hdr initialization failed!\n");
+			return (ENOBUFS);
 		rxbuf->m_head->m_len = MCLBYTES;
 		rxbuf->m_head->m_flags &= ~M_HASFCS; /* we strip it */
 		rxbuf->m_head->m_pkthdr.len = MCLBYTES;
@@ -3852,8 +3852,11 @@ em_setup_receive_ring(struct rx_ring *rxr)
 		error = bus_dmamap_load_mbuf_sg(rxr->rxtag,
 		    rxbuf->map, rxbuf->m_head, seg,
 		    &nsegs, BUS_DMA_NOWAIT);
-		if (error != 0)
-			panic("RX ring dma initialization failed!\n");
+		if (error != 0) {
+			m_freem(rxbuf->m_head);
+			rxbuf->m_head = NULL;
+			return (error);
+		}
 		bus_dmamap_sync(rxr->rxtag,
 		    rxbuf->map, BUS_DMASYNC_PREREAD);
 

From f0d5a975b3910c46fd5101bca109dd69461bfc7b Mon Sep 17 00:00:00 2001
From: Jack F Vogel 
Date: Sat, 28 Aug 2010 00:23:13 +0000
Subject: [PATCH 0306/1624] Add Intel Cougar Point PCH HD Audio Controller ID

MFC in a week
---
 sys/dev/sound/pci/hda/hdac.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/dev/sound/pci/hda/hdac.c b/sys/dev/sound/pci/hda/hdac.c
index a0b1dc7d6c7..2175f371a2a 100644
--- a/sys/dev/sound/pci/hda/hdac.c
+++ b/sys/dev/sound/pci/hda/hdac.c
@@ -140,6 +140,7 @@ SND_DECLARE_FILE("$FreeBSD$");
 
 /* Intel */
 #define INTEL_VENDORID		0x8086
+#define HDA_INTEL_CPT		HDA_MODEL_CONSTRUCT(INTEL, 0x1c20)
 #define HDA_INTEL_82801F	HDA_MODEL_CONSTRUCT(INTEL, 0x2668)
 #define HDA_INTEL_63XXESB	HDA_MODEL_CONSTRUCT(INTEL, 0x269a)
 #define HDA_INTEL_82801G	HDA_MODEL_CONSTRUCT(INTEL, 0x27d8)
@@ -486,6 +487,7 @@ static const struct {
 	char		*desc;
 	char		flags;
 } hdac_devices[] = {
+	{ HDA_INTEL_CPT,     "Intel Cougar Point",	0 },
 	{ HDA_INTEL_82801F,  "Intel 82801F",	0 },
 	{ HDA_INTEL_63XXESB, "Intel 631x/632xESB",	0 },
 	{ HDA_INTEL_82801G,  "Intel 82801G",	0 },

From dd20cce19a1bfdc0e0697a40d219d43ca4a87081 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Sat, 28 Aug 2010 00:34:22 +0000
Subject: [PATCH 0307/1624] Do not allocate multicast array memory in multicast
 filter configuration function. For failed memory allocations, em(4)/lem(4)
 called panic(9) which is not acceptable on production box.
 igb(4)/ixgb(4)/ix(4) allocated the required memory in stack which consumed
 768 bytes of stack memory which looks too big.

To address these issues, allocate multicast array memory in device
attach time and make multicast configuration success under any
conditions. This change also removes the excessive use of memory in
stack.

Reviewed by:	jfv
---
 sys/dev/e1000/if_em.c  | 22 ++++++++++++++--------
 sys/dev/e1000/if_em.h  |  2 ++
 sys/dev/e1000/if_igb.c | 17 ++++++++++++++++-
 sys/dev/e1000/if_igb.h |  2 ++
 sys/dev/e1000/if_lem.c | 22 ++++++++++++++--------
 sys/dev/e1000/if_lem.h |  2 ++
 sys/dev/ixgb/if_ixgb.c | 17 ++++++++++++++++-
 sys/dev/ixgb/if_ixgb.h |  2 ++
 sys/dev/ixgbe/ixgbe.c  | 17 ++++++++++++++++-
 sys/dev/ixgbe/ixgbe.h  |  2 ++
 10 files changed, 86 insertions(+), 19 deletions(-)

diff --git a/sys/dev/e1000/if_em.c b/sys/dev/e1000/if_em.c
index 56859ea3739..e5dfa36416a 100644
--- a/sys/dev/e1000/if_em.c
+++ b/sys/dev/e1000/if_em.c
@@ -576,6 +576,15 @@ em_attach(device_t dev)
 		goto err_pci;
 	}
 
+	/* Allocate multicast array memory. */
+	adapter->mta = malloc(sizeof(u8) * ETH_ADDR_LEN *
+	    MAX_NUM_MULTICAST_ADDRESSES, M_DEVBUF, M_NOWAIT);
+	if (adapter->mta == NULL) {
+		device_printf(dev, "Can not allocate multicast setup array\n");
+		error = ENOMEM;
+		goto err_late;
+	}
+
 	/*
 	** Start from a known state, this is
 	** important in reading the nvm and
@@ -674,6 +683,7 @@ err_late:
 		if_free(adapter->ifp);
 err_pci:
 	em_free_pci_resources(adapter);
+	free(adapter->mta, M_DEVBUF);
 	EM_CORE_LOCK_DESTROY(adapter);
 
 	return (error);
@@ -739,6 +749,7 @@ em_detach(device_t dev)
 	em_free_receive_structures(adapter);
 
 	em_release_hw_control(adapter);
+	free(adapter->mta, M_DEVBUF);
 
 	return (0);
 }
@@ -1998,6 +2009,9 @@ em_set_multi(struct adapter *adapter)
 
 	IOCTL_DEBUGOUT("em_set_multi: begin");
 
+	mta = adapter->mta;
+	bzero(mta, sizeof(u8) * ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES);
+
 	if (adapter->hw.mac.type == e1000_82542 && 
 	    adapter->hw.revision_id == E1000_REVISION_2) {
 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
@@ -2008,13 +2022,6 @@ em_set_multi(struct adapter *adapter)
 		msec_delay(5);
 	}
 
-	/* Allocate temporary memory to setup array */
-	mta = malloc(sizeof(u8) *
-	    (ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES),
-	    M_DEVBUF, M_NOWAIT | M_ZERO);
-	if (mta == NULL)
-		panic("em_set_multi memory failure\n");
-
 #if __FreeBSD_version < 800000
 	IF_ADDR_LOCK(ifp);
 #else
@@ -2052,7 +2059,6 @@ em_set_multi(struct adapter *adapter)
 		if (adapter->hw.bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
 			e1000_pci_set_mwi(&adapter->hw);
 	}
-	free(mta, M_DEVBUF);
 }
 
 
diff --git a/sys/dev/e1000/if_em.h b/sys/dev/e1000/if_em.h
index 225a8d08b8e..d164edb1859 100644
--- a/sys/dev/e1000/if_em.h
+++ b/sys/dev/e1000/if_em.h
@@ -391,6 +391,8 @@ struct adapter {
 	bool		has_manage;
 	bool		has_amt;
 
+	/* Multicast array memory */
+	u8		*mta;
 	/* Info about the board itself */
 	uint8_t		link_active;
 	uint16_t	link_speed;
diff --git a/sys/dev/e1000/if_igb.c b/sys/dev/e1000/if_igb.c
index d8371af8d8f..3e14f248e12 100644
--- a/sys/dev/e1000/if_igb.c
+++ b/sys/dev/e1000/if_igb.c
@@ -515,6 +515,15 @@ igb_attach(device_t dev)
 		goto err_late;
 	}
 
+	/* Allocate multicast array memory. */
+	adapter->mta = malloc(sizeof(u8) * ETH_ADDR_LEN *
+	    MAX_NUM_MULTICAST_ADDRESSES, M_DEVBUF, M_NOWAIT);
+	if (adapter->mta == NULL) {
+		device_printf(dev, "Can not allocate multicast setup array\n");
+		error = ENOMEM;
+		goto err_late;
+	}
+
 	/*
 	** Start from a known state, this is
 	** important in reading the nvm and
@@ -618,6 +627,7 @@ err_late:
 		if_free(adapter->ifp);
 err_pci:
 	igb_free_pci_resources(adapter);
+	free(adapter->mta, M_DEVBUF);
 	IGB_CORE_LOCK_DESTROY(adapter);
 
 	return (error);
@@ -688,6 +698,7 @@ igb_detach(device_t dev)
 
 	igb_free_transmit_structures(adapter);
 	igb_free_receive_structures(adapter);
+	free(adapter->mta, M_DEVBUF);
 
 	IGB_CORE_LOCK_DESTROY(adapter);
 
@@ -1861,12 +1872,16 @@ igb_set_multi(struct adapter *adapter)
 	struct ifnet	*ifp = adapter->ifp;
 	struct ifmultiaddr *ifma;
 	u32 reg_rctl = 0;
-	u8  mta[MAX_NUM_MULTICAST_ADDRESSES * ETH_ADDR_LEN];
+	u8  *mta;
 
 	int mcnt = 0;
 
 	IOCTL_DEBUGOUT("igb_set_multi: begin");
 
+	mta = adapter->mta;
+	bzero(mta, sizeof(uint8_t) * ETH_ADDR_LEN *
+	    MAX_NUM_MULTICAST_ADDRESSES);
+
 #if __FreeBSD_version < 800000
 	IF_ADDR_LOCK(ifp);
 #else
diff --git a/sys/dev/e1000/if_igb.h b/sys/dev/e1000/if_igb.h
index 4388e0769f2..28f5d32eeb6 100644
--- a/sys/dev/e1000/if_igb.h
+++ b/sys/dev/e1000/if_igb.h
@@ -422,6 +422,8 @@ struct adapter {
 	u32			rx_mbuf_sz;
 	u32			rx_mask;
 
+	/* Multicast array memory */
+	u8		*mta;
 	/* Misc stats maintained by the driver */
 	unsigned long	dropped_pkts;
 	unsigned long	mbuf_defrag_failed;
diff --git a/sys/dev/e1000/if_lem.c b/sys/dev/e1000/if_lem.c
index f5c9e2932a3..71a82e50417 100644
--- a/sys/dev/e1000/if_lem.c
+++ b/sys/dev/e1000/if_lem.c
@@ -550,6 +550,15 @@ lem_attach(device_t dev)
 	adapter->rx_desc_base =
 	    (struct e1000_rx_desc *)adapter->rxdma.dma_vaddr;
 
+	/* Allocate multicast array memory. */
+	adapter->mta = malloc(sizeof(u8) * ETH_ADDR_LEN *
+	    MAX_NUM_MULTICAST_ADDRESSES, M_DEVBUF, M_NOWAIT);
+	if (adapter->mta == NULL) {
+		device_printf(dev, "Can not allocate multicast setup array\n");
+		error = ENOMEM;
+		goto err_hw_init;
+	}
+
 	/*
 	** Start from a known state, this is
 	** important in reading the nvm and
@@ -676,6 +685,7 @@ err_pci:
 	if (adapter->ifp != NULL)
 		if_free(adapter->ifp);
 	lem_free_pci_resources(adapter);
+	free(adapter->mta, M_DEVBUF);
 	EM_TX_LOCK_DESTROY(adapter);
 	EM_RX_LOCK_DESTROY(adapter);
 	EM_CORE_LOCK_DESTROY(adapter);
@@ -762,6 +772,7 @@ lem_detach(device_t dev)
 	}
 
 	lem_release_hw_control(adapter);
+	free(adapter->mta, M_DEVBUF);
 	EM_TX_LOCK_DESTROY(adapter);
 	EM_RX_LOCK_DESTROY(adapter);
 	EM_CORE_LOCK_DESTROY(adapter);
@@ -1942,6 +1953,9 @@ lem_set_multi(struct adapter *adapter)
 
 	IOCTL_DEBUGOUT("lem_set_multi: begin");
 
+	mta = adapter->mta;
+	bzero(mta, sizeof(u8) * ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES);
+
 	if (adapter->hw.mac.type == e1000_82542 && 
 	    adapter->hw.revision_id == E1000_REVISION_2) {
 		reg_rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
@@ -1952,13 +1966,6 @@ lem_set_multi(struct adapter *adapter)
 		msec_delay(5);
 	}
 
-	/* Allocate temporary memory to setup array */
-	mta = malloc(sizeof(u8) *
-	    (ETH_ADDR_LEN * MAX_NUM_MULTICAST_ADDRESSES),
-	    M_DEVBUF, M_NOWAIT | M_ZERO);
-	if (mta == NULL)
-		panic("lem_set_multi memory failure\n");
-
 #if __FreeBSD_version < 800000
 	IF_ADDR_LOCK(ifp);
 #else
@@ -1996,7 +2003,6 @@ lem_set_multi(struct adapter *adapter)
 		if (adapter->hw.bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
 			e1000_pci_set_mwi(&adapter->hw);
 	}
-	free(mta, M_DEVBUF);
 }
 
 
diff --git a/sys/dev/e1000/if_lem.h b/sys/dev/e1000/if_lem.h
index 13c2cbc4dd3..0ada7dfa48a 100644
--- a/sys/dev/e1000/if_lem.h
+++ b/sys/dev/e1000/if_lem.h
@@ -339,6 +339,8 @@ struct adapter {
 	bool		has_manage;
 	bool		has_amt;
 
+	/* Multicast array memory */
+	u8		*mta;
 	/* Info about the board itself */
 	uint8_t		link_active;
 	uint16_t	link_speed;
diff --git a/sys/dev/ixgb/if_ixgb.c b/sys/dev/ixgb/if_ixgb.c
index edb352f4b77..e5cddb31b37 100644
--- a/sys/dev/ixgb/if_ixgb.c
+++ b/sys/dev/ixgb/if_ixgb.c
@@ -324,6 +324,15 @@ ixgb_attach(device_t dev)
 	}
 	adapter->rx_desc_base = (struct ixgb_rx_desc *) adapter->rxdma.dma_vaddr;
 
+	/* Allocate multicast array memory. */
+	adapter->mta = malloc(sizeof(u_int8_t) * IXGB_ETH_LENGTH_OF_ADDRESS *
+	    MAX_NUM_MULTICAST_ADDRESSES, M_DEVBUF, M_NOWAIT);
+	if (adapter->mta == NULL) {
+		device_printf(dev, "Can not allocate multicast setup array\n");
+		error = ENOMEM;
+		goto err_hw_init;
+	}
+
 	/* Initialize the hardware */
 	if (ixgb_hardware_init(adapter)) {
 		device_printf(dev, "Unable to initialize the hardware\n");
@@ -351,6 +360,7 @@ err_pci:
 		if_free(adapter->ifp);
 	ixgb_free_pci_resources(adapter);
 	sysctl_ctx_free(&adapter->sysctl_ctx);
+	free(adapter->mta, M_DEVBUF);
 	return (error);
 
 }
@@ -412,6 +422,7 @@ ixgb_detach(device_t dev)
 		adapter->next->prev = adapter->prev;
 	if (adapter->prev != NULL)
 		adapter->prev->next = adapter->next;
+	free(adapter->mta, M_DEVBUF);
 
 	IXGB_LOCK_DESTROY(adapter);
 	return (0);
@@ -1069,13 +1080,17 @@ static void
 ixgb_set_multi(struct adapter * adapter)
 {
 	u_int32_t       reg_rctl = 0;
-	u_int8_t        mta[MAX_NUM_MULTICAST_ADDRESSES * IXGB_ETH_LENGTH_OF_ADDRESS];
+	u_int8_t        *mta;
 	struct ifmultiaddr *ifma;
 	int             mcnt = 0;
 	struct ifnet   *ifp = adapter->ifp;
 
 	IOCTL_DEBUGOUT("ixgb_set_multi: begin");
 
+	mta = adapter->mta;
+	bzero(mta, sizeof(u_int8_t) * IXGB_ETH_LENGTH_OF_ADDRESS *
+	    MAX_NUM_MULTICAST_ADDRESSES);
+
 	if_maddr_rlock(ifp);
 #if __FreeBSD_version < 500000
 	LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
diff --git a/sys/dev/ixgb/if_ixgb.h b/sys/dev/ixgb/if_ixgb.h
index 9e5355a25dd..4e88db79a86 100644
--- a/sys/dev/ixgb/if_ixgb.h
+++ b/sys/dev/ixgb/if_ixgb.h
@@ -344,6 +344,8 @@ struct adapter {
 	struct sysctl_ctx_list sysctl_ctx;
 	struct sysctl_oid *sysctl_tree;
 
+	/* Multicast array memory */
+	u_int8_t	*mta;
 	/* Misc stats maintained by the driver */
 	unsigned long   dropped_pkts;
 	unsigned long   mbuf_alloc_failed;
diff --git a/sys/dev/ixgbe/ixgbe.c b/sys/dev/ixgbe/ixgbe.c
index e7ecff8c8c8..37b98df20ed 100644
--- a/sys/dev/ixgbe/ixgbe.c
+++ b/sys/dev/ixgbe/ixgbe.c
@@ -524,6 +524,15 @@ ixgbe_attach(device_t dev)
 		goto err_out;
 	}
 
+	/* Allocate multicast array memory. */
+	adapter->mta = malloc(sizeof(u8) * IXGBE_ETH_LENGTH_OF_ADDRESS *
+	    MAX_NUM_MULTICAST_ADDRESSES, M_DEVBUF, M_NOWAIT);
+	if (adapter->mta == NULL) {
+		device_printf(dev, "Can not allocate multicast setup array\n");
+		error = ENOMEM;
+		goto err_late;
+	}
+
 	/* Initialize the shared code */
 	error = ixgbe_init_shared_code(hw);
 	if (error == IXGBE_ERR_SFP_NOT_PRESENT) {
@@ -636,6 +645,7 @@ err_out:
 	if (adapter->ifp != NULL)
 		if_free(adapter->ifp);
 	ixgbe_free_pci_resources(adapter);
+	free(adapter->mta, M_DEVBUF);
 	return (error);
 
 }
@@ -706,6 +716,7 @@ ixgbe_detach(device_t dev)
 
 	ixgbe_free_transmit_structures(adapter);
 	ixgbe_free_receive_structures(adapter);
+	free(adapter->mta, M_DEVBUF);
 
 	IXGBE_CORE_LOCK_DESTROY(adapter);
 	return (0);
@@ -1808,7 +1819,7 @@ static void
 ixgbe_set_multi(struct adapter *adapter)
 {
 	u32	fctrl;
-	u8	mta[MAX_NUM_MULTICAST_ADDRESSES * IXGBE_ETH_LENGTH_OF_ADDRESS];
+	u8	*mta;
 	u8	*update_ptr;
 	struct	ifmultiaddr *ifma;
 	int	mcnt = 0;
@@ -1816,6 +1827,10 @@ ixgbe_set_multi(struct adapter *adapter)
 
 	IOCTL_DEBUGOUT("ixgbe_set_multi: begin");
 
+	mta = adapter->mta;
+	bzero(mta, sizeof(u8) * IXGBE_ETH_LENGTH_OF_ADDRESS *
+	    MAX_NUM_MULTICAST_ADDRESSES);
+
 	fctrl = IXGBE_READ_REG(&adapter->hw, IXGBE_FCTRL);
 	fctrl |= (IXGBE_FCTRL_UPE | IXGBE_FCTRL_MPE);
 	if (ifp->if_flags & IFF_PROMISC)
diff --git a/sys/dev/ixgbe/ixgbe.h b/sys/dev/ixgbe/ixgbe.h
index 6aa32e4a391..abfdfa10e6d 100644
--- a/sys/dev/ixgbe/ixgbe.h
+++ b/sys/dev/ixgbe/ixgbe.h
@@ -421,6 +421,8 @@ struct adapter {
 	u64			que_mask;
 	u32			rx_process_limit;
 
+	/* Multicast array memory */
+	u8			*mta;
 	/* Misc stats maintained by the driver */
 	unsigned long   	dropped_pkts;
 	unsigned long   	mbuf_defrag_failed;

From bfc8500c3439f899e7797defa244542abb67daf3 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 28 Aug 2010 07:10:51 +0000
Subject: [PATCH 0308/1624] Add Intel Cougar Point PCH SATA Controller
 DeviceIDs. Correct some existing entries for Intel Ibex Peak (5 Series/3400
 Series) PCH SATA controllers.

Submitted by:	jfv@
MFC after:	1 week
---
 sys/dev/ata/ata-pci.h            | 23 ++++++++++++++++++++
 sys/dev/ata/chipsets/ata-intel.c | 36 ++++++++++++++++++--------------
 2 files changed, 43 insertions(+), 16 deletions(-)

diff --git a/sys/dev/ata/ata-pci.h b/sys/dev/ata/ata-pci.h
index 7fa76440ed6..258212eb9b6 100644
--- a/sys/dev/ata/ata-pci.h
+++ b/sys/dev/ata/ata-pci.h
@@ -204,6 +204,29 @@ struct ata_pci_controller {
 #define ATA_I82801JI_AH         0x3a228086
 #define ATA_I82801JI_R1         0x3a258086
 #define ATA_I82801JI_S2         0x3a268086
+
+#define ATA_5Series_S1          0x3b208086
+#define ATA_5Series_S2          0x3b218086
+#define ATA_5Series_AH1         0x3b228086
+#define ATA_5Series_AH2         0x3b238086
+#define ATA_5Series_R1          0x3b258086
+#define ATA_5Series_S3          0x3b268086
+#define ATA_5Series_S4          0x3b288086
+#define ATA_5Series_AH3         0x3b298086
+#define ATA_5Series_R2          0x3b2c8086
+#define ATA_5Series_S5          0x3b2d8086
+#define ATA_5Series_S6          0x3b2e8086
+#define ATA_5Series_AH4         0x3b2f8086
+
+#define ATA_CPT_S1              0x1c008086
+#define ATA_CPT_S2              0x1c018086
+#define ATA_CPT_AH1             0x1c028086
+#define ATA_CPT_AH2             0x1c038086
+#define ATA_CPT_R1              0x1c048086
+#define ATA_CPT_R2              0x1c058086
+#define ATA_CPT_S3              0x1c088086
+#define ATA_CPT_S4              0x1c098086
+
 #define ATA_I31244              0x32008086
 #define ATA_ISCH                0x811a8086
 
diff --git a/sys/dev/ata/chipsets/ata-intel.c b/sys/dev/ata/chipsets/ata-intel.c
index 0638b39c907..0f47bc781b2 100644
--- a/sys/dev/ata/chipsets/ata-intel.c
+++ b/sys/dev/ata/chipsets/ata-intel.c
@@ -140,22 +140,26 @@ ata_intel_probe(device_t dev)
      { ATA_I82801JI_AH,  0, INTEL_AHCI, 0, ATA_SA300, "ICH10" },
      { ATA_I82801JI_R1,  0, INTEL_AHCI, 0, ATA_SA300, "ICH10" },
      { ATA_I82801JI_S2,  0, INTEL_AHCI, 0, ATA_SA300, "ICH10" },
-     { 0x3b208086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b218086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b228086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b238086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b248086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b258086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b268086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b278086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b288086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b298086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b2a8086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b2b8086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b2c8086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b2d8086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b2e8086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
-     { 0x3b2f8086,       0, INTEL_AHCI, 0, ATA_SA300, "PCH" },
+     { ATA_5Series_S1,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_S2,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_AH1,  0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_AH2,  0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_R1,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_S3,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_S4,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_AH3,  0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_R2,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_S5,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_S6,   0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_5Series_AH4,  0, INTEL_AHCI, 0, ATA_SA300, "5 Series/3400 Series PCH" },
+     { ATA_CPT_S1,       0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_S2,       0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_AH1,      0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_AH2,      0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_R1,       0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_R2,       0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_S3,       0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
+     { ATA_CPT_S4,       0, INTEL_AHCI, 0, ATA_SA300, "Cougar Point" },
      { ATA_I31244,       0,          0, 2, ATA_SA150, "31244" },
      { ATA_ISCH,         0,          0, 1, ATA_UDMA5, "SCH" },
      { 0, 0, 0, 0, 0, 0}};

From 90400bed63a5dd61ffece484521630caff5a87f3 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 28 Aug 2010 07:24:45 +0000
Subject: [PATCH 0309/1624] MFata(4): Add Intel Cougar Point PCH SATA
 Controller DeviceIDs. Correct some existing entries for Intel Ibex Peak (5
 Series/3400 Series) PCH SATA controllers.

---
 sys/dev/ahci/ahci.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)

diff --git a/sys/dev/ahci/ahci.c b/sys/dev/ahci/ahci.c
index 2f53f822a9d..54e787ab1dd 100644
--- a/sys/dev/ahci/ahci.c
+++ b/sys/dev/ahci/ahci.c
@@ -151,14 +151,16 @@ static struct {
 	{0x3a058086, 0x00, "Intel ICH10",	0},
 	{0x3a228086, 0x00, "Intel ICH10",	0},
 	{0x3a258086, 0x00, "Intel ICH10",	0},
-	{0x3b228086, 0x00, "Intel PCH",		0},
-	{0x3b238086, 0x00, "Intel PCH",		0},
-	{0x3b248086, 0x00, "Intel PCH",		0},
-	{0x3b258086, 0x00, "Intel PCH",		0},
-	{0x3b298086, 0x00, "Intel PCH",		0},
-	{0x3b2b8086, 0x00, "Intel PCH",		0},
-	{0x3b2c8086, 0x00, "Intel PCH",		0},
-	{0x3b2f8086, 0x00, "Intel PCH",		0},
+	{0x3b228086, 0x00, "Intel 5 Series/3400 Series",	0},
+	{0x3b238086, 0x00, "Intel 5 Series/3400 Series",	0},
+	{0x3b258086, 0x00, "Intel 5 Series/3400 Series",	0},
+	{0x3b298086, 0x00, "Intel 5 Series/3400 Series",	0},
+	{0x3b2c8086, 0x00, "Intel 5 Series/3400 Series",	0},
+	{0x3b2f8086, 0x00, "Intel 5 Series/3400 Series",	0},
+	{0x1c028086, 0x00, "Intel Cougar Point",	0},
+	{0x1c038086, 0x00, "Intel Cougar Point",	0},
+	{0x1c048086, 0x00, "Intel Cougar Point",	0},
+	{0x1c058086, 0x00, "Intel Cougar Point",	0},
 	{0x2361197b, 0x00, "JMicron JMB361",	AHCI_Q_NOFORCE},
 	{0x2363197b, 0x00, "JMicron JMB363",	AHCI_Q_NOFORCE},
 	{0x2365197b, 0x00, "JMicron JMB365",	AHCI_Q_NOFORCE},

From 97f047a80b855cb78606cc05a2d7f89e186fa27f Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Sat, 28 Aug 2010 07:58:10 +0000
Subject: [PATCH 0310/1624] Initial code for XLR CompactFlash driver.

Submitted by:	Sreekanth M. S. 
---
 sys/mips/rmi/board.c      |  12 +++
 sys/mips/rmi/board.h      |   3 +-
 sys/mips/rmi/files.xlr    |   1 +
 sys/mips/rmi/iodi.c       |  24 ++++++
 sys/mips/rmi/xlr_pcmcia.c | 149 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 188 insertions(+), 1 deletion(-)
 create mode 100644 sys/mips/rmi/xlr_pcmcia.c

diff --git a/sys/mips/rmi/board.c b/sys/mips/rmi/board.c
index d346a9c274d..ab55e05bbe2 100644
--- a/sys/mips/rmi/board.c
+++ b/sys/mips/rmi/board.c
@@ -88,6 +88,16 @@ struct stn_cc *xls_core_cc_configs[] = {&xls_cc_table_cpu_0, &xls_cc_table_cpu_1
 
 struct xlr_board_info xlr_board_info;
 
+static int
+xlr_pcmcia_present(void)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_GPIO_OFFSET);
+	uint32_t resetconf;
+
+	resetconf = xlr_read_reg(mmio, 21);
+	return ((resetconf & 0x4000) != 0);
+}
+
 /*
  * All our knowledge of chip and board that cannot be detected by probing
  * at run-time goes here
@@ -103,6 +113,7 @@ xlr_board_info_setup()
 		/* Board version 8 has NAND flash */
 		xlr_board_info.cfi =
 		    (xlr_boot1_info.board_major_version != RMI_XLR_BOARD_ARIZONA_VIII);
+		xlr_board_info.ata = xlr_pcmcia_present();
 		xlr_board_info.pci_irq = 0;
 		xlr_board_info.credit_configs = xls_core_cc_configs;
 		xlr_board_info.bucket_sizes = &xls_bucket_sizes;
@@ -155,6 +166,7 @@ xlr_board_info_setup()
 		xlr_board_info.nr_cpus = 32;
 		xlr_board_info.usb = 0;
 		xlr_board_info.cfi = 1;
+		xlr_board_info.ata = xlr_pcmcia_present();
 		xlr_board_info.pci_irq = 0;
 		xlr_board_info.credit_configs = xlr_core_cc_configs;
 		xlr_board_info.bucket_sizes = &bucket_sizes;
diff --git a/sys/mips/rmi/board.h b/sys/mips/rmi/board.h
index 0092fea25d3..a584af53f71 100644
--- a/sys/mips/rmi/board.h
+++ b/sys/mips/rmi/board.h
@@ -147,7 +147,8 @@ struct xlr_board_info {
 	int is_xls;
 	int nr_cpus;
 	int usb;		/* usb enabled ? */
-	int cfi;		/* compact flash driver for NOR? */
+	int cfi;		/* NOR flash */
+	int ata;		/* PCMCIA/compactflash driver */
 	int pci_irq;
 	struct stn_cc **credit_configs;	/* pointer to Core station credits */
 	struct bucket_size *bucket_sizes;	/* pointer to Core station
diff --git a/sys/mips/rmi/files.xlr b/sys/mips/rmi/files.xlr
index 06e261ca3ea..ace84421cb5 100644
--- a/sys/mips/rmi/files.xlr
+++ b/sys/mips/rmi/files.xlr
@@ -14,6 +14,7 @@ mips/rmi/xlr_i2c.c              		optional iic
 mips/rmi/uart_bus_xlr_iodi.c			optional uart 
 mips/rmi/uart_cpu_mips_xlr.c			optional uart 
 mips/rmi/xlr_pci.c				optional pci
+mips/rmi/xlr_pcmcia.c				optional ata
 mips/rmi/xls_ehci.c				optional usb ehci
 mips/rmi/bus_space_rmi.c			standard
 mips/rmi/bus_space_rmi_pci.c			standard
diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index 5ee961f88b9..fc18732488b 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -89,6 +89,20 @@ iodi_setup_intr(device_t, device_t, struct resource *, int,
 
 struct iodi_softc *iodi_softc;	/* There can be only one. */
 
+/*
+ * We will manage the Flash/PCMCIA devices in IODI for now.
+ * The NOR flash, Compact flash etc. which can be connected on 
+ * various chip selects on the peripheral IO, should have a 
+ * separate bus later.
+ */
+static void
+bridge_pcmcia_ack(int irq)
+{
+	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_FLASH_OFFSET);
+
+	xlr_write_reg(mmio, 0x60, 0xffffffff);
+}
+
 static int
 iodi_setup_intr(device_t dev, device_t child,
     struct resource *ires, int flags, driver_filter_t * filt,
@@ -112,6 +126,10 @@ iodi_setup_intr(device_t dev, device_t child,
 		cpu_establish_hardintr("ehci", filt, intr, arg, PIC_USB_IRQ, flags,
 		    cookiep);
 		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1, 0);
+	} else if (strcmp(device_get_name(child), "ata") == 0) {
+		xlr_establish_intr("ata", filt, intr, arg, PIC_PCMCIA_IRQ, flags,
+		    cookiep, bridge_pcmcia_ack);
+		pic_setup_intr(PIC_PCMCIA_IRQ - PIC_IRQ_BASE, PIC_PCMCIA_IRQ, 0x1, 0);
 	}
 
 	return (0);
@@ -158,6 +176,9 @@ iodi_alloc_resource(device_t bus, device_t child, int type, int *rid,
 	} else if (strcmp(device_get_name(child), "cfi") == 0) {
 		res->r_bushandle = MIPS_PHYS_TO_KSEG1(0x1c000000);
 		res->r_bustag = 0;
+	} else if (strcmp(device_get_name(child), "ata") == 0) {
+		res->r_bushandle = MIPS_PHYS_TO_KSEG1(0x1d000000);
+		res->r_bustag = rmi_pci_bus_space;  /* byte swapping (not really PCI) */
 	}
 	/* res->r_start = *rid; */
 	return (res);
@@ -206,6 +227,9 @@ iodi_attach(device_t dev)
 	if (xlr_board_info.cfi)
 		device_add_child(dev, "cfi", 0);
 
+	if (xlr_board_info.ata)
+		device_add_child(dev, "ata", 0);
+
 	if (xlr_board_info.gmac_block[0].enabled) {
 		tmpd = device_add_child(dev, "rge", 0);
 		device_set_ivars(tmpd, &xlr_board_info.gmac_block[0]);
diff --git a/sys/mips/rmi/xlr_pcmcia.c b/sys/mips/rmi/xlr_pcmcia.c
new file mode 100644
index 00000000000..86322669c8b
--- /dev/null
+++ b/sys/mips/rmi/xlr_pcmcia.c
@@ -0,0 +1,149 @@
+/*-
+ * Copyright (c) 2003-2009 RMI Corporation
+ * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
+ *
+ * RMI_BSD */
+/*
+ * ATA driver for the XLR_PCMCIA Host adapter on the RMI XLR/XLS/.
+ */
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+#include 
+#include 
+#include  
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#define	XLR_PCMCIA_DATA_REG		0x1f0
+#define	XLR_PCMCIA_ERROR_REG		0x1f1
+#define	XLR_PCMCIA_SECT_CNT_REG		0x1f2
+#define	XLR_PCMCIA_SECT_NUM_REG		0x1f3
+#define	XLR_PCMCIA_CYLINDER_LOW_REG	0x1f4
+#define	XLR_PCMCIA_CYLINDER_HIGH_REG	0x1f5
+#define	XLR_PCMCIA_SECT_DRIVE_HEAD_REG	0x1f6
+#define	XLR_PCMCIA_CMD_STATUS_REG	0x1f7
+#define	XLR_PCMCIA_ALT_STATUS_REG	0x3f6
+#define	XLR_PCMCIA_CONTROL_REG		0x3f6
+
+/*
+ * Device methods
+ */
+static int xlr_pcmcia_probe(device_t);
+static int xlr_pcmcia_attach(device_t);
+static int xlr_pcmcia_detach(device_t);
+
+static int
+xlr_pcmcia_probe(device_t dev)
+{
+	struct ata_channel *ch = device_get_softc(dev);
+
+	ch->unit = 0;
+	ch->flags |= ATA_USE_16BIT | ATA_NO_SLAVE ;
+	device_set_desc(dev, "PCMCIA ATA controller");
+
+	return (ata_probe(dev));
+}
+
+/*
+ * We add all the devices which we know about.
+ * The generic attach routine will attach them if they are alive.
+ */
+static int
+xlr_pcmcia_attach(device_t dev)
+{
+	struct ata_channel *ch = device_get_softc(dev);
+	int i;
+	int rid =0;
+	struct resource *mem_res;
+
+
+	mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,  RF_ACTIVE);
+	for (i = 0; i < ATA_MAX_RES; i++)
+		ch->r_io[i].res = mem_res;
+
+	/*
+	 * CF+ Specification.
+	 */
+	ch->r_io[ATA_DATA].offset 	= XLR_PCMCIA_DATA_REG;
+	ch->r_io[ATA_FEATURE].offset 	= XLR_PCMCIA_ERROR_REG;
+	ch->r_io[ATA_COUNT].offset 	= XLR_PCMCIA_SECT_CNT_REG;
+	ch->r_io[ATA_SECTOR].offset 	= XLR_PCMCIA_SECT_NUM_REG;
+	ch->r_io[ATA_CYL_LSB].offset 	= XLR_PCMCIA_CYLINDER_LOW_REG;
+	ch->r_io[ATA_CYL_MSB].offset 	= XLR_PCMCIA_CYLINDER_HIGH_REG;
+	ch->r_io[ATA_DRIVE].offset 	= XLR_PCMCIA_SECT_DRIVE_HEAD_REG;
+	ch->r_io[ATA_COMMAND].offset 	= XLR_PCMCIA_CMD_STATUS_REG;
+	ch->r_io[ATA_ERROR].offset 	= XLR_PCMCIA_ERROR_REG;
+	ch->r_io[ATA_IREASON].offset 	= XLR_PCMCIA_SECT_CNT_REG;
+	ch->r_io[ATA_STATUS].offset 	= XLR_PCMCIA_CMD_STATUS_REG;
+	ch->r_io[ATA_ALTSTAT].offset 	= XLR_PCMCIA_ALT_STATUS_REG;
+	ch->r_io[ATA_CONTROL].offset 	= XLR_PCMCIA_CONTROL_REG;
+
+	/* Should point at the base of registers. */
+	ch->r_io[ATA_IDX_ADDR].offset = XLR_PCMCIA_DATA_REG;
+
+	ata_generic_hw(dev);
+
+	return (ata_attach(dev)); 
+}
+
+static int
+xlr_pcmcia_detach(device_t dev)
+{
+	bus_generic_detach(dev);
+  
+	return (0);
+}
+
+static device_method_t xlr_pcmcia_methods[] = {
+    /* device interface */
+    DEVMETHOD(device_probe,         xlr_pcmcia_probe),
+    DEVMETHOD(device_attach,        xlr_pcmcia_attach),
+    DEVMETHOD(device_detach,        xlr_pcmcia_detach),
+
+    { 0, 0 }
+};
+
+static driver_t xlr_pcmcia_driver = {
+        "ata",
+        xlr_pcmcia_methods,
+        sizeof(struct ata_channel),
+};
+
+DRIVER_MODULE(ata, iodi, xlr_pcmcia_driver, ata_devclass, 0, 0);

From cba3269417700074ea9ae6286ef31b1d17524c4d Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 28 Aug 2010 08:03:29 +0000
Subject: [PATCH 0311/1624] Register an interrupt vector for DTrace return
 probes. There is some code missing in lapic to make sure that we don't
 overwrite this entry, but this will be done on a sequent commit.

Sponsored by:	The FreeBSD Foundation
---
 sys/amd64/amd64/exception.S  |  4 ++++
 sys/amd64/amd64/machdep.c    |  7 +++++++
 sys/amd64/include/segments.h |  1 +
 sys/i386/i386/exception.s    |  2 ++
 sys/i386/i386/machdep.c      | 11 ++++++++++-
 sys/i386/include/segments.h  |  1 +
 6 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/sys/amd64/amd64/exception.S b/sys/amd64/amd64/exception.S
index c18f27f8e40..37e89a00744 100644
--- a/sys/amd64/amd64/exception.S
+++ b/sys/amd64/amd64/exception.S
@@ -108,6 +108,10 @@ IDTVEC(dbg)
 	TRAP_NOEN(T_TRCTRAP)
 IDTVEC(bpt)
 	TRAP_NOEN(T_BPTFLT)
+#ifdef KDTRACE_HOOKS
+IDTVEC(dtrace_ret)
+	TRAP_NOEN(T_DTRACE_RET)
+#endif
 
 /* Regular traps; The cpu does not supply tf_err for these. */
 #define	TRAP(a)	 \
diff --git a/sys/amd64/amd64/machdep.c b/sys/amd64/amd64/machdep.c
index 6bec71b5be6..fe6860084f9 100644
--- a/sys/amd64/amd64/machdep.c
+++ b/sys/amd64/amd64/machdep.c
@@ -54,6 +54,7 @@ __FBSDID("$FreeBSD$");
 #include "opt_msgbuf.h"
 #include "opt_perfmon.h"
 #include "opt_sched.h"
+#include "opt_kdtrace.h"
 
 #include 
 #include 
@@ -1089,6 +1090,9 @@ extern inthand_t
 	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
 	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
 	IDTVEC(xmm), IDTVEC(dblfault),
+#ifdef KDTRACE_HOOKS
+	IDTVEC(dtrace_ret),
+#endif
 	IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
 
 #ifdef DDB
@@ -1617,6 +1621,9 @@ hammer_time(u_int64_t modulep, u_int64_t physfree)
 	setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
 	setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYSIGT, SEL_KPL, 0);
 	setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
+#ifdef KDTRACE_HOOKS
+	setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYSIGT, SEL_UPL, 0);
+#endif
 
 	r_idt.rd_limit = sizeof(idt0) - 1;
 	r_idt.rd_base = (long) idt;
diff --git a/sys/amd64/include/segments.h b/sys/amd64/include/segments.h
index 282c1aeda15..22dc95ab057 100644
--- a/sys/amd64/include/segments.h
+++ b/sys/amd64/include/segments.h
@@ -214,6 +214,7 @@ struct region_descriptor {
 #define	IDT_XF		19	/* #XF: SIMD Floating-Point Exception */
 #define	IDT_IO_INTS	NRSVIDT	/* Base of IDT entries for I/O interrupts. */
 #define	IDT_SYSCALL	0x80	/* System Call Interrupt Vector */
+#define	IDT_DTRACE_RET	0x92	/* DTrace pid provider Interrupt Vector */
 
 /*
  * Entries in the Global Descriptor Table (GDT)
diff --git a/sys/i386/i386/exception.s b/sys/i386/i386/exception.s
index 575b98dcc7a..13562fa6e99 100644
--- a/sys/i386/i386/exception.s
+++ b/sys/i386/i386/exception.s
@@ -108,6 +108,8 @@ IDTVEC(nmi)
 	pushl $0; TRAP(T_NMI)
 IDTVEC(bpt)
 	pushl $0; TRAP(T_BPTFLT)
+IDTVEC(dtrace_ret)
+	pushl $0; TRAP(T_DTRACE_RET)
 IDTVEC(ofl)
 	pushl $0; TRAP(T_OFLOW)
 IDTVEC(bnd)
diff --git a/sys/i386/i386/machdep.c b/sys/i386/i386/machdep.c
index 872d09b3609..ef229ca6f5b 100644
--- a/sys/i386/i386/machdep.c
+++ b/sys/i386/i386/machdep.c
@@ -54,6 +54,7 @@ __FBSDID("$FreeBSD$");
 #include "opt_npx.h"
 #include "opt_perfmon.h"
 #include "opt_xbox.h"
+#include "opt_kdtrace.h"
 
 #include 
 #include 
@@ -1876,7 +1877,11 @@ extern inthand_t
 	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
 	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
 	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
-	IDTVEC(xmm), IDTVEC(lcall_syscall), IDTVEC(int0x80_syscall);
+	IDTVEC(xmm),
+#ifdef KDTRACE_HOOKS
+	IDTVEC(dtrace_ret),
+#endif
+	IDTVEC(lcall_syscall), IDTVEC(int0x80_syscall);
 
 #ifdef DDB
 /*
@@ -2825,6 +2830,10 @@ init386(first)
 	    GSEL(GCODE_SEL, SEL_KPL));
  	setidt(IDT_SYSCALL, &IDTVEC(int0x80_syscall), SDT_SYS386TGT, SEL_UPL,
 	    GSEL(GCODE_SEL, SEL_KPL));
+#ifdef KDTRACE_HOOKS
+	setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYS386TGT, SEL_UPL,
+	    GSEL(GCODE_SEL, SEL_KPL));
+#endif
 
 	r_idt.rd_limit = sizeof(idt0) - 1;
 	r_idt.rd_base = (int) idt;
diff --git a/sys/i386/include/segments.h b/sys/i386/include/segments.h
index 0b12f622c31..deeaf76ccbc 100644
--- a/sys/i386/include/segments.h
+++ b/sys/i386/include/segments.h
@@ -207,6 +207,7 @@ struct region_descriptor {
 #define	IDT_XF		19	/* #XF: SIMD Floating-Point Exception */
 #define	IDT_IO_INTS	NRSVIDT	/* Base of IDT entries for I/O interrupts. */
 #define	IDT_SYSCALL	0x80	/* System Call Interrupt Vector */
+#define	IDT_DTRACE_RET	0x92	/* DTrace pid provider Interrupt Vector */
 
 /*
  * Entries in the Global Descriptor Table (GDT)

From 9f4ee6172d6f3e622337f8e7381f8eeef9e8ca4f Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 28 Aug 2010 08:13:38 +0000
Subject: [PATCH 0312/1624] Replace a memory barrier with a mutex barrier.

Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/uts/common/dtrace/fasttrap.c  | 25 +++++++++++--------
 1 file changed, 15 insertions(+), 10 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
index be07d197f0c..ba8abb323fb 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
@@ -208,6 +208,10 @@ static void fasttrap_proc_release(fasttrap_proc_t *);
 
 #define	FASTTRAP_PROCS_INDEX(pid) ((pid) & fasttrap_procs.fth_mask)
 
+#if !defined(sun)
+static kmutex_t fasttrap_cpuc_pid_lock[MAXCPU];
+#endif
+
 static int
 fasttrap_highbit(ulong_t i)
 {
@@ -289,24 +293,17 @@ fasttrap_sigtrap(proc_t *p, kthread_t *t, uintptr_t pc)
 static void
 fasttrap_mod_barrier(uint64_t gen)
 {
-#if defined(sun)
 	int i;
-#endif
 
 	if (gen < fasttrap_mod_gen)
 		return;
 
 	fasttrap_mod_gen++;
 
-#if defined(sun)
-	for (i = 0; i < NCPU; i++) {
-		mutex_enter(&cpu_core[i].cpuc_pid_lock);
-		mutex_exit(&cpu_core[i].cpuc_pid_lock);
+	CPU_FOREACH(i) {
+		mutex_enter(&fasttrap_cpuc_pid_lock[i]);
+		mutex_exit(&fasttrap_cpuc_pid_lock[i]);
 	}
-#else
-	/* XXX */
-	__asm __volatile("": : :"memory");
-#endif
 }
 
 /*
@@ -2326,6 +2323,11 @@ fasttrap_load(void)
 	for (i = 0; i < fasttrap_procs.fth_nent; i++)
 		mutex_init(&fasttrap_procs.fth_table[i].ftb_mtx,
 		    "processes bucket mtx", MUTEX_DEFAULT, NULL);
+
+	CPU_FOREACH(i) {
+		mutex_init(&fasttrap_cpuc_pid_lock[i], "fasttrap barrier",
+		    MUTEX_DEFAULT, NULL);
+	}
 #endif
 
 	(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
@@ -2450,6 +2452,9 @@ fasttrap_unload(void)
 #if !defined(sun)
 	destroy_dev(fasttrap_cdev);
 	mutex_destroy(&fasttrap_count_mtx);
+	CPU_FOREACH(i) {
+		mutex_destroy(&fasttrap_cpuc_pid_lock[i]);
+	}
 #endif
 
 	return (0);

From 915af965a2ec0ed2dc15519451c8c620ab087272 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 28 Aug 2010 08:18:20 +0000
Subject: [PATCH 0313/1624] Add the path necessary to find fasttrap_isa.h to
 CFLAGS.

Sponsored by:	The FreeBSD Foundation
---
 sys/modules/dtrace/dtrace/Makefile | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/modules/dtrace/dtrace/Makefile b/sys/modules/dtrace/dtrace/Makefile
index 5f10e925af3..f359f8d9009 100644
--- a/sys/modules/dtrace/dtrace/Makefile
+++ b/sys/modules/dtrace/dtrace/Makefile
@@ -15,6 +15,7 @@ SRCS=		dtrace.c \
 .if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 SRCS+=		dis_tables.c \
 		instr_size.c
+CFLAGS+=	-I${.CURDIR}/../../../cddl/contrib/opensolaris/uts/intel
 .endif
 
 SRCS+=		bus_if.h device_if.h vnode_if.h

From efb46508cec0d26422d5a38c3587e65e19691093 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sat, 28 Aug 2010 08:30:20 +0000
Subject: [PATCH 0314/1624] Correct offset conversion to little endian. It was
 implemented in version 2, but because of a bug it was a no-op, so we were
 still using offsets in native byte order for the host. Do it properly this
 time, bump version to 4 and set the G_ELI_FLAG_NATIVE_BYTE_ORDER flag when
 version is under 4.

MFC after:	2 weeks
---
 sys/geom/eli/g_eli.c | 8 +++++---
 sys/geom/eli/g_eli.h | 8 ++++----
 2 files changed, 9 insertions(+), 7 deletions(-)

diff --git a/sys/geom/eli/g_eli.c b/sys/geom/eli/g_eli.c
index a3746c09e1a..eb10b172fd9 100644
--- a/sys/geom/eli/g_eli.c
+++ b/sys/geom/eli/g_eli.c
@@ -384,11 +384,13 @@ g_eli_crypto_ivgen(struct g_eli_softc *sc, off_t offset, u_char *iv,
 	u_char off[8], hash[SHA256_DIGEST_LENGTH];
 	SHA256_CTX ctx;
 
-	if (!(sc->sc_flags & G_ELI_FLAG_NATIVE_BYTE_ORDER))
+	if ((sc->sc_flags & G_ELI_FLAG_NATIVE_BYTE_ORDER) != 0)
+		bcopy(&offset, off, sizeof(off));
+	else
 		le64enc(off, (uint64_t)offset);
 	/* Copy precalculated SHA256 context for IV-Key. */
 	bcopy(&sc->sc_ivctx, &ctx, sizeof(ctx));
-	SHA256_Update(&ctx, (uint8_t *)&offset, sizeof(offset));
+	SHA256_Update(&ctx, off, sizeof(off));
 	SHA256_Final(hash, &ctx);
 	bcopy(hash, iv, size);
 }
@@ -544,7 +546,7 @@ g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
 	sc->sc_crypto = G_ELI_CRYPTO_SW;
 	sc->sc_flags = md->md_flags;
 	/* Backward compatibility. */
-	if (md->md_version < 2)
+	if (md->md_version < 4)
 		sc->sc_flags |= G_ELI_FLAG_NATIVE_BYTE_ORDER;
 	sc->sc_ealgo = md->md_ealgo;
 	sc->sc_nkey = nkey;
diff --git a/sys/geom/eli/g_eli.h b/sys/geom/eli/g_eli.h
index 8079c9dd4a1..8f9c5ca7180 100644
--- a/sys/geom/eli/g_eli.h
+++ b/sys/geom/eli/g_eli.h
@@ -57,11 +57,11 @@
  * 1 - Added data authentication support (md_aalgo field and
  *     G_ELI_FLAG_AUTH flag).
  * 2 - Added G_ELI_FLAG_READONLY.
- *   - IV is generated from offset converted to little-endian
- *     (flag G_ELI_FLAG_NATIVE_BYTE_ORDER will be set for older versions).
  * 3 - Added 'configure' subcommand.
+ * 4 - IV is generated from offset converted to little-endian
+ *     (flag G_ELI_FLAG_NATIVE_BYTE_ORDER will be set for older versions).
  */
-#define	G_ELI_VERSION		3
+#define	G_ELI_VERSION		4
 
 /* ON DISK FLAGS. */
 /* Use random, onetime keys. */
@@ -394,7 +394,7 @@ g_eli_keylen(u_int algo, u_int keylen)
 				keylen = 0;
 		}
 		return (keylen);
-	case CRYPTO_AES_CBC: /* FALLTHROUGH */
+	case CRYPTO_AES_CBC:
 	case CRYPTO_CAMELLIA_CBC:
 		switch (keylen) {
 		case 0:

From 646c3b21ae0fd0e1b4cd168fa28f44db916d875a Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sat, 28 Aug 2010 08:38:03 +0000
Subject: [PATCH 0315/1624] Run all tasks from a proper context, with proper
 priority, etc.

Reviewed by:	jhb
MFC after:	1 month
---
 sys/kern/subr_taskqueue.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/kern/subr_taskqueue.c b/sys/kern/subr_taskqueue.c
index fcf235c85ed..c0b1dd1970e 100644
--- a/sys/kern/subr_taskqueue.c
+++ b/sys/kern/subr_taskqueue.c
@@ -141,7 +141,6 @@ taskqueue_free(struct taskqueue *queue)
 
 	TQ_LOCK(queue);
 	queue->tq_flags &= ~TQ_FLAGS_ACTIVE;
-	taskqueue_run(queue, &queue->tq_running);
 	taskqueue_terminate(queue->tq_threads, queue);
 	mtx_destroy(&queue->tq_mutex);
 	free(queue->tq_threads, M_TASKQUEUE);
@@ -372,6 +371,7 @@ taskqueue_thread_loop(void *arg)
 			break;
 		TQ_SLEEP(tq, tq, &tq->tq_mutex, 0, "-", 0);
 	}
+	taskqueue_run(tq, &running);
 
 	/* rendezvous with thread that asked us to terminate */
 	tq->tq_tcount--;

From 4d02a00a57d8ce2bd81efc6c9b65ab7ce241bc5e Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 28 Aug 2010 08:39:37 +0000
Subject: [PATCH 0316/1624] Remove debugging.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c b/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
index c3990523553..dba77ce5d0c 100644
--- a/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
+++ b/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
@@ -1066,7 +1066,6 @@ fasttrap_pid_probe(struct reg *rp)
 		return (-1);
 	}
 
-	printf("found tracepoint\n");
 	/*
 	 * Set the program counter to the address of the traced instruction
 	 * so that it looks right in ustack() output.

From c87f1ad43ce664de499084f7662dd59b1c180eff Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sat, 28 Aug 2010 08:57:15 +0000
Subject: [PATCH 0317/1624] There is a bug in vfs_allocate_syncvnode() failure
 handling in mount code. Actually it is hard to properly handle such a
 failure, especially in MNT_UPDATE case. The only reason for the
 vfs_allocate_syncvnode() function to fail is getnewvnode() failure.
 Fortunately it is impossible for current implementation of getnewvnode() to
 fail, so we can assert this and make vfs_allocate_syncvnode() void. This in
 turn free us from handling its failures in the mount code.

Reviewed by:	kib
MFC after:	1 month
---
 sys/kern/vfs_mount.c |  8 +++-----
 sys/kern/vfs_subr.c  | 12 +++++-------
 sys/sys/mount.h      |  2 +-
 3 files changed, 9 insertions(+), 13 deletions(-)

diff --git a/sys/kern/vfs_mount.c b/sys/kern/vfs_mount.c
index 088d93973bd..fe9f16c3355 100644
--- a/sys/kern/vfs_mount.c
+++ b/sys/kern/vfs_mount.c
@@ -1036,7 +1036,7 @@ vfs_domount(
 		MNT_IUNLOCK(mp);
 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
 			if (mp->mnt_syncer == NULL)
-				error = vfs_allocate_syncvnode(mp);
+				vfs_allocate_syncvnode(mp);
 		} else {
 			if (mp->mnt_syncer != NULL)
 				vrele(mp->mnt_syncer);
@@ -1078,10 +1078,8 @@ vfs_domount(
 		mountcheckdirs(vp, newdp);
 		vrele(newdp);
 		if ((mp->mnt_flag & MNT_RDONLY) == 0)
-			error = vfs_allocate_syncvnode(mp);
+			vfs_allocate_syncvnode(mp);
 		vfs_unbusy(mp);
-		if (error)
-			vrele(vp);
 	} else {
 		vfs_unbusy(mp);
 		vfs_mount_destroy(mp);
@@ -1311,7 +1309,7 @@ dounmount(mp, flags, td)
 		mp->mnt_kern_flag &= ~MNTK_NOINSMNTQ;
 		if ((mp->mnt_flag & MNT_RDONLY) == 0 && mp->mnt_syncer == NULL) {
 			MNT_IUNLOCK(mp);
-			(void) vfs_allocate_syncvnode(mp);
+			vfs_allocate_syncvnode(mp);
 			MNT_ILOCK(mp);
 		}
 		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
diff --git a/sys/kern/vfs_subr.c b/sys/kern/vfs_subr.c
index 985d73bc54f..9bb365fcaae 100644
--- a/sys/kern/vfs_subr.c
+++ b/sys/kern/vfs_subr.c
@@ -3365,7 +3365,7 @@ static struct vop_vector sync_vnodeops = {
 /*
  * Create a new filesystem syncer vnode for the specified mount point.
  */
-int
+void
 vfs_allocate_syncvnode(struct mount *mp)
 {
 	struct vnode *vp;
@@ -3374,16 +3374,15 @@ vfs_allocate_syncvnode(struct mount *mp)
 	int error;
 
 	/* Allocate a new vnode */
-	if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
-		mp->mnt_syncer = NULL;
-		return (error);
-	}
+	error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
+	if (error != 0)
+		panic("vfs_allocate_syncvnode: getnewvnode() failed");
 	vp->v_type = VNON;
 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 	vp->v_vflag |= VV_FORCEINSMQ;
 	error = insmntque(vp, mp);
 	if (error != 0)
-		panic("vfs_allocate_syncvnode: insmntque failed");
+		panic("vfs_allocate_syncvnode: insmntque() failed");
 	vp->v_vflag &= ~VV_FORCEINSMQ;
 	VOP_UNLOCK(vp, 0);
 	/*
@@ -3411,7 +3410,6 @@ vfs_allocate_syncvnode(struct mount *mp)
 	mtx_unlock(&sync_mtx);
 	BO_UNLOCK(bo);
 	mp->mnt_syncer = vp;
-	return (0);
 }
 
 /*
diff --git a/sys/sys/mount.h b/sys/sys/mount.h
index 20dcf641c7b..85f16ff2802 100644
--- a/sys/sys/mount.h
+++ b/sys/sys/mount.h
@@ -730,7 +730,7 @@ void	vfs_msync(struct mount *, int);
 int	vfs_busy(struct mount *, int);
 int	vfs_export			 /* process mount export info */
 	    (struct mount *, struct export_args *);
-int	vfs_allocate_syncvnode(struct mount *);
+void	vfs_allocate_syncvnode(struct mount *);
 int	vfs_donmount(struct thread *td, int fsflags, struct uio *fsoptions);
 void	vfs_getnewfsid(struct mount *);
 struct cdev *vfs_getrootfsid(struct mount *);

From abe5837f7c1e08e17c954dba7dd4d52b137a0083 Mon Sep 17 00:00:00 2001
From: Martin Matuska 
Date: Sat, 28 Aug 2010 08:59:55 +0000
Subject: [PATCH 0318/1624] Update ZFS metaslab code from OpenSolaris. This
 provides a noticeable write speedup, especially on pools with less than 30%
 of free space.

Detailed information (OpenSolaris onnv changesets and Bug IDs):

11146:7e58f40bcb1c
6826241	Sync write IOPS drops dramatically during TXG sync
6869229	zfs should switch to shiny new metaslabs more frequently

11728:59fdb3b856f6
6918420	zdb -m has issues printing metaslab statistics

12047:7c1fcc8419ca
6917066	zfs block picking can be improved

Approved by:	delphij (mentor)
Obtained from:	OpenSolaris (Bug ID 6826241, 6869229, 6918420, 6917066)
MFC after:	2 weeks
---
 cddl/contrib/opensolaris/cmd/zdb/zdb.c        |  24 +-
 .../opensolaris/uts/common/fs/zfs/metaslab.c  | 468 +++++++++++++-----
 .../opensolaris/uts/common/fs/zfs/spa.c       |  54 +-
 .../opensolaris/uts/common/fs/zfs/space_map.c |   6 +-
 .../uts/common/fs/zfs/sys/metaslab.h          |   1 +
 .../uts/common/fs/zfs/sys/metaslab_impl.h     |   1 +
 .../uts/common/fs/zfs/sys/spa_impl.h          |   2 +
 .../uts/common/fs/zfs/sys/space_map.h         |   1 +
 .../opensolaris/uts/common/fs/zfs/sys/zio.h   |  17 +-
 .../opensolaris/uts/common/fs/zfs/vdev.c      |   4 +
 .../uts/common/fs/zfs/vdev_queue.c            |   2 +-
 .../opensolaris/uts/common/fs/zfs/zio.c       |  24 +-
 12 files changed, 424 insertions(+), 180 deletions(-)

diff --git a/cddl/contrib/opensolaris/cmd/zdb/zdb.c b/cddl/contrib/opensolaris/cmd/zdb/zdb.c
index 7106beebdca..915ea1917a0 100644
--- a/cddl/contrib/opensolaris/cmd/zdb/zdb.c
+++ b/cddl/contrib/opensolaris/cmd/zdb/zdb.c
@@ -491,35 +491,37 @@ dump_metaslab_stats(metaslab_t *msp)
 static void
 dump_metaslab(metaslab_t *msp)
 {
-	char freebuf[5];
-	space_map_obj_t *smo = &msp->ms_smo;
 	vdev_t *vd = msp->ms_group->mg_vd;
 	spa_t *spa = vd->vdev_spa;
+	space_map_t *sm = &msp->ms_map;
+	space_map_obj_t *smo = &msp->ms_smo;
+	char freebuf[5];
 
-	nicenum(msp->ms_map.sm_size - smo->smo_alloc, freebuf);
+	nicenum(sm->sm_size - smo->smo_alloc, freebuf);
 
 	(void) printf(
 	    "\tvdev %5llu   offset %12llx   spacemap %6llu   free    %5s\n",
-	    (u_longlong_t)vd->vdev_id, (u_longlong_t)msp->ms_map.sm_start,
-	    (u_longlong_t)smo->smo_object, freebuf);
+	    (u_longlong_t)(sm->sm_start / sm->sm_size),
+	    (u_longlong_t)sm->sm_start, (u_longlong_t)smo->smo_object, freebuf);
 
 	if (dump_opt['m'] > 1) {
 		mutex_enter(&msp->ms_lock);
-		VERIFY(space_map_load(&msp->ms_map, zfs_metaslab_ops,
-		    SM_FREE, &msp->ms_smo, spa->spa_meta_objset) == 0);
+		space_map_load_wait(sm);
+		if (!sm->sm_loaded)
+			VERIFY(space_map_load(sm, zfs_metaslab_ops,
+			    SM_FREE, smo, spa->spa_meta_objset) == 0);
 		dump_metaslab_stats(msp);
-		space_map_unload(&msp->ms_map);
+		space_map_unload(sm);
 		mutex_exit(&msp->ms_lock);
 	}
 
 	if (dump_opt['d'] > 5 || dump_opt['m'] > 2) {
-		ASSERT(msp->ms_map.sm_size == (1ULL << vd->vdev_ms_shift));
+		ASSERT(sm->sm_size == (1ULL << vd->vdev_ms_shift));
 
 		mutex_enter(&msp->ms_lock);
-		dump_spacemap(spa->spa_meta_objset, smo, &msp->ms_map);
+		dump_spacemap(spa->spa_meta_objset, smo, sm);
 		mutex_exit(&msp->ms_lock);
 	}
-
 }
 
 static void
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c
index d216154db04..c5ce27cb677 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c
@@ -19,8 +19,7 @@
  * CDDL HEADER END
  */
 /*
- * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
- * Use is subject to license terms.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  */
 
 #include 
@@ -37,7 +36,7 @@ uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1;	/* force gang blocks */
 
 /*
  * Minimum size which forces the dynamic allocator to change
- * it's allocation strategy. Once the space map cannot satisfy
+ * it's allocation strategy.  Once the space map cannot satisfy
  * an allocation of this size then it switches to using more
  * aggressive strategy (i.e search by size rather than offset).
  */
@@ -49,7 +48,23 @@ uint64_t metaslab_df_alloc_threshold = SPA_MAXBLOCKSIZE;
  * Once the space_map's free space drops below this level we dynamically
  * switch to using best-fit allocations.
  */
-int metaslab_df_free_pct = 30;
+int metaslab_df_free_pct = 4;
+
+/*
+ * A metaslab is considered "free" if it contains a contiguous
+ * segment which is greater than metaslab_min_alloc_size.
+ */
+uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
+
+/*
+ * Max number of space_maps to prefetch.
+ */
+int metaslab_prefetch_limit = SPA_DVAS_PER_BP;
+
+/*
+ * Percentage bonus multiplier for metaslabs that are in the bonus area.
+ */
+int metaslab_smo_bonus_pct = 150;
 
 /*
  * ==========================================================================
@@ -218,6 +233,32 @@ metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
 	mutex_exit(&mg->mg_lock);
 }
 
+/*
+ * ==========================================================================
+ * Common allocator routines
+ * ==========================================================================
+ */
+static int
+metaslab_segsize_compare(const void *x1, const void *x2)
+{
+	const space_seg_t *s1 = x1;
+	const space_seg_t *s2 = x2;
+	uint64_t ss_size1 = s1->ss_end - s1->ss_start;
+	uint64_t ss_size2 = s2->ss_end - s2->ss_start;
+
+	if (ss_size1 < ss_size2)
+		return (-1);
+	if (ss_size1 > ss_size2)
+		return (1);
+
+	if (s1->ss_start < s2->ss_start)
+		return (-1);
+	if (s1->ss_start > s2->ss_start)
+		return (1);
+
+	return (0);
+}
+
 /*
  * This is a helper function that can be used by the allocator to find
  * a suitable block to allocate. This will search the specified AVL
@@ -258,101 +299,8 @@ metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
 	return (metaslab_block_picker(t, cursor, size, align));
 }
 
-/*
- * ==========================================================================
- * The first-fit block allocator
- * ==========================================================================
- */
 static void
-metaslab_ff_load(space_map_t *sm)
-{
-	ASSERT(sm->sm_ppd == NULL);
-	sm->sm_ppd = kmem_zalloc(64 * sizeof (uint64_t), KM_SLEEP);
-	sm->sm_pp_root = NULL;
-}
-
-static void
-metaslab_ff_unload(space_map_t *sm)
-{
-	kmem_free(sm->sm_ppd, 64 * sizeof (uint64_t));
-	sm->sm_ppd = NULL;
-}
-
-static uint64_t
-metaslab_ff_alloc(space_map_t *sm, uint64_t size)
-{
-	avl_tree_t *t = &sm->sm_root;
-	uint64_t align = size & -size;
-	uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
-
-	return (metaslab_block_picker(t, cursor, size, align));
-}
-
-/* ARGSUSED */
-static void
-metaslab_ff_claim(space_map_t *sm, uint64_t start, uint64_t size)
-{
-	/* No need to update cursor */
-}
-
-/* ARGSUSED */
-static void
-metaslab_ff_free(space_map_t *sm, uint64_t start, uint64_t size)
-{
-	/* No need to update cursor */
-}
-
-static space_map_ops_t metaslab_ff_ops = {
-	metaslab_ff_load,
-	metaslab_ff_unload,
-	metaslab_ff_alloc,
-	metaslab_ff_claim,
-	metaslab_ff_free,
-	NULL	/* maxsize */
-};
-
-/*
- * Dynamic block allocator -
- * Uses the first fit allocation scheme until space get low and then
- * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
- * and metaslab_df_free_pct to determine when to switch the allocation scheme.
- */
-
-uint64_t
-metaslab_df_maxsize(space_map_t *sm)
-{
-	avl_tree_t *t = sm->sm_pp_root;
-	space_seg_t *ss;
-
-	if (t == NULL || (ss = avl_last(t)) == NULL)
-		return (0ULL);
-
-	return (ss->ss_end - ss->ss_start);
-}
-
-static int
-metaslab_df_seg_compare(const void *x1, const void *x2)
-{
-	const space_seg_t *s1 = x1;
-	const space_seg_t *s2 = x2;
-	uint64_t ss_size1 = s1->ss_end - s1->ss_start;
-	uint64_t ss_size2 = s2->ss_end - s2->ss_start;
-
-	if (ss_size1 < ss_size2)
-		return (-1);
-	if (ss_size1 > ss_size2)
-		return (1);
-
-	if (s1->ss_start < s2->ss_start)
-		return (-1);
-	if (s1->ss_start > s2->ss_start)
-		return (1);
-
-	return (0);
-}
-
-static void
-metaslab_df_load(space_map_t *sm)
+metaslab_pp_load(space_map_t *sm)
 {
 	space_seg_t *ss;
 
@@ -360,7 +308,7 @@ metaslab_df_load(space_map_t *sm)
 	sm->sm_ppd = kmem_zalloc(64 * sizeof (uint64_t), KM_SLEEP);
 
 	sm->sm_pp_root = kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
-	avl_create(sm->sm_pp_root, metaslab_df_seg_compare,
+	avl_create(sm->sm_pp_root, metaslab_segsize_compare,
 	    sizeof (space_seg_t), offsetof(struct space_seg, ss_pp_node));
 
 	for (ss = avl_first(&sm->sm_root); ss; ss = AVL_NEXT(&sm->sm_root, ss))
@@ -368,7 +316,7 @@ metaslab_df_load(space_map_t *sm)
 }
 
 static void
-metaslab_df_unload(space_map_t *sm)
+metaslab_pp_unload(space_map_t *sm)
 {
 	void *cookie = NULL;
 
@@ -384,13 +332,82 @@ metaslab_df_unload(space_map_t *sm)
 	sm->sm_pp_root = NULL;
 }
 
+/* ARGSUSED */
+static void
+metaslab_pp_claim(space_map_t *sm, uint64_t start, uint64_t size)
+{
+	/* No need to update cursor */
+}
+
+/* ARGSUSED */
+static void
+metaslab_pp_free(space_map_t *sm, uint64_t start, uint64_t size)
+{
+	/* No need to update cursor */
+}
+
+/*
+ * Return the maximum contiguous segment within the metaslab.
+ */
+uint64_t
+metaslab_pp_maxsize(space_map_t *sm)
+{
+	avl_tree_t *t = sm->sm_pp_root;
+	space_seg_t *ss;
+
+	if (t == NULL || (ss = avl_last(t)) == NULL)
+		return (0ULL);
+
+	return (ss->ss_end - ss->ss_start);
+}
+
+/*
+ * ==========================================================================
+ * The first-fit block allocator
+ * ==========================================================================
+ */
+static uint64_t
+metaslab_ff_alloc(space_map_t *sm, uint64_t size)
+{
+	avl_tree_t *t = &sm->sm_root;
+	uint64_t align = size & -size;
+	uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
+
+	return (metaslab_block_picker(t, cursor, size, align));
+}
+
+/* ARGSUSED */
+boolean_t
+metaslab_ff_fragmented(space_map_t *sm)
+{
+	return (B_TRUE);
+}
+
+static space_map_ops_t metaslab_ff_ops = {
+	metaslab_pp_load,
+	metaslab_pp_unload,
+	metaslab_ff_alloc,
+	metaslab_pp_claim,
+	metaslab_pp_free,
+	metaslab_pp_maxsize,
+	metaslab_ff_fragmented
+};
+
+/*
+ * ==========================================================================
+ * Dynamic block allocator -
+ * Uses the first fit allocation scheme until space get low and then
+ * adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
+ * and metaslab_df_free_pct to determine when to switch the allocation scheme.
+ * ==========================================================================
+ */
 static uint64_t
 metaslab_df_alloc(space_map_t *sm, uint64_t size)
 {
 	avl_tree_t *t = &sm->sm_root;
 	uint64_t align = size & -size;
 	uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
-	uint64_t max_size = metaslab_df_maxsize(sm);
+	uint64_t max_size = metaslab_pp_maxsize(sm);
 	int free_pct = sm->sm_space * 100 / sm->sm_size;
 
 	ASSERT(MUTEX_HELD(sm->sm_lock));
@@ -412,30 +429,158 @@ metaslab_df_alloc(space_map_t *sm, uint64_t size)
 	return (metaslab_block_picker(t, cursor, size, 1ULL));
 }
 
-/* ARGSUSED */
-static void
-metaslab_df_claim(space_map_t *sm, uint64_t start, uint64_t size)
+static boolean_t
+metaslab_df_fragmented(space_map_t *sm)
 {
-	/* No need to update cursor */
-}
+	uint64_t max_size = metaslab_pp_maxsize(sm);
+	int free_pct = sm->sm_space * 100 / sm->sm_size;
 
-/* ARGSUSED */
-static void
-metaslab_df_free(space_map_t *sm, uint64_t start, uint64_t size)
-{
-	/* No need to update cursor */
+	if (max_size >= metaslab_df_alloc_threshold &&
+	    free_pct >= metaslab_df_free_pct)
+		return (B_FALSE);
+
+	return (B_TRUE);
 }
 
 static space_map_ops_t metaslab_df_ops = {
-	metaslab_df_load,
-	metaslab_df_unload,
+	metaslab_pp_load,
+	metaslab_pp_unload,
 	metaslab_df_alloc,
-	metaslab_df_claim,
-	metaslab_df_free,
-	metaslab_df_maxsize
+	metaslab_pp_claim,
+	metaslab_pp_free,
+	metaslab_pp_maxsize,
+	metaslab_df_fragmented
 };
 
-space_map_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
+/*
+ * ==========================================================================
+ * Other experimental allocators
+ * ==========================================================================
+ */
+static uint64_t
+metaslab_cdf_alloc(space_map_t *sm, uint64_t size)
+{
+	avl_tree_t *t = &sm->sm_root;
+	uint64_t *cursor = (uint64_t *)sm->sm_ppd;
+	uint64_t *extent_end = (uint64_t *)sm->sm_ppd + 1;
+	uint64_t max_size = metaslab_pp_maxsize(sm);
+	uint64_t rsize = size;
+	uint64_t offset = 0;
+
+	ASSERT(MUTEX_HELD(sm->sm_lock));
+	ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
+
+	if (max_size < size)
+		return (-1ULL);
+
+	ASSERT3U(*extent_end, >=, *cursor);
+
+	/*
+	 * If we're running low on space switch to using the size
+	 * sorted AVL tree (best-fit).
+	 */
+	if ((*cursor + size) > *extent_end) {
+
+		t = sm->sm_pp_root;
+		*cursor = *extent_end = 0;
+
+		if (max_size > 2 * SPA_MAXBLOCKSIZE)
+			rsize = MIN(metaslab_min_alloc_size, max_size);
+		offset = metaslab_block_picker(t, extent_end, rsize, 1ULL);
+		if (offset != -1)
+			*cursor = offset + size;
+	} else {
+		offset = metaslab_block_picker(t, cursor, rsize, 1ULL);
+	}
+	ASSERT3U(*cursor, <=, *extent_end);
+	return (offset);
+}
+
+static boolean_t
+metaslab_cdf_fragmented(space_map_t *sm)
+{
+	uint64_t max_size = metaslab_pp_maxsize(sm);
+
+	if (max_size > (metaslab_min_alloc_size * 10))
+		return (B_FALSE);
+	return (B_TRUE);
+}
+
+static space_map_ops_t metaslab_cdf_ops = {
+	metaslab_pp_load,
+	metaslab_pp_unload,
+	metaslab_cdf_alloc,
+	metaslab_pp_claim,
+	metaslab_pp_free,
+	metaslab_pp_maxsize,
+	metaslab_cdf_fragmented
+};
+
+uint64_t metaslab_ndf_clump_shift = 4;
+
+static uint64_t
+metaslab_ndf_alloc(space_map_t *sm, uint64_t size)
+{
+	avl_tree_t *t = &sm->sm_root;
+	avl_index_t where;
+	space_seg_t *ss, ssearch;
+	uint64_t hbit = highbit(size);
+	uint64_t *cursor = (uint64_t *)sm->sm_ppd + hbit - 1;
+	uint64_t max_size = metaslab_pp_maxsize(sm);
+
+	ASSERT(MUTEX_HELD(sm->sm_lock));
+	ASSERT3U(avl_numnodes(&sm->sm_root), ==, avl_numnodes(sm->sm_pp_root));
+
+	if (max_size < size)
+		return (-1ULL);
+
+	ssearch.ss_start = *cursor;
+	ssearch.ss_end = *cursor + size;
+
+	ss = avl_find(t, &ssearch, &where);
+	if (ss == NULL || (ss->ss_start + size > ss->ss_end)) {
+		t = sm->sm_pp_root;
+
+		ssearch.ss_start = 0;
+		ssearch.ss_end = MIN(max_size,
+		    1ULL << (hbit + metaslab_ndf_clump_shift));
+		ss = avl_find(t, &ssearch, &where);
+		if (ss == NULL)
+			ss = avl_nearest(t, where, AVL_AFTER);
+		ASSERT(ss != NULL);
+	}
+
+	if (ss != NULL) {
+		if (ss->ss_start + size <= ss->ss_end) {
+			*cursor = ss->ss_start + size;
+			return (ss->ss_start);
+		}
+	}
+	return (-1ULL);
+}
+
+static boolean_t
+metaslab_ndf_fragmented(space_map_t *sm)
+{
+	uint64_t max_size = metaslab_pp_maxsize(sm);
+
+	if (max_size > (metaslab_min_alloc_size << metaslab_ndf_clump_shift))
+		return (B_FALSE);
+	return (B_TRUE);
+}
+
+
+static space_map_ops_t metaslab_ndf_ops = {
+	metaslab_pp_load,
+	metaslab_pp_unload,
+	metaslab_ndf_alloc,
+	metaslab_pp_claim,
+	metaslab_pp_free,
+	metaslab_pp_maxsize,
+	metaslab_ndf_fragmented
+};
+
+space_map_ops_t *zfs_metaslab_ops = &metaslab_ndf_ops;
 
 /*
  * ==========================================================================
@@ -522,7 +667,6 @@ metaslab_fini(metaslab_t *msp)
 #define	METASLAB_WEIGHT_SECONDARY	(1ULL << 62)
 #define	METASLAB_ACTIVE_MASK		\
 	(METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
-#define	METASLAB_SMO_BONUS_MULTIPLIER	2
 
 static uint64_t
 metaslab_weight(metaslab_t *msp)
@@ -555,25 +699,60 @@ metaslab_weight(metaslab_t *msp)
 	ASSERT(weight >= space && weight <= 2 * space);
 
 	/*
-	 * For locality, assign higher weight to metaslabs we've used before.
+	 * For locality, assign higher weight to metaslabs which have
+	 * a lower offset than what we've already activated.
 	 */
-	if (smo->smo_object != 0)
-		weight *= METASLAB_SMO_BONUS_MULTIPLIER;
+	if (sm->sm_start <= mg->mg_bonus_area)
+		weight *= (metaslab_smo_bonus_pct / 100);
 	ASSERT(weight >= space &&
-	    weight <= 2 * METASLAB_SMO_BONUS_MULTIPLIER * space);
+	    weight <= 2 * (metaslab_smo_bonus_pct / 100) * space);
+
+	if (sm->sm_loaded && !sm->sm_ops->smop_fragmented(sm)) {
+		/*
+		 * If this metaslab is one we're actively using, adjust its
+		 * weight to make it preferable to any inactive metaslab so
+		 * we'll polish it off.
+		 */
+		weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
+	}
+	return (weight);
+}
+
+static void
+metaslab_prefetch(metaslab_group_t *mg)
+{
+	spa_t *spa = mg->mg_vd->vdev_spa;
+	metaslab_t *msp;
+	avl_tree_t *t = &mg->mg_metaslab_tree;
+	int m;
+
+	mutex_enter(&mg->mg_lock);
 
 	/*
-	 * If this metaslab is one we're actively using, adjust its weight to
-	 * make it preferable to any inactive metaslab so we'll polish it off.
+	 * Prefetch the next potential metaslabs
 	 */
-	weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
+	for (msp = avl_first(t), m = 0; msp; msp = AVL_NEXT(t, msp), m++) {
+		space_map_t *sm = &msp->ms_map;
+		space_map_obj_t *smo = &msp->ms_smo;
 
-	return (weight);
+		/* If we have reached our prefetch limit then we're done */
+		if (m >= metaslab_prefetch_limit)
+			break;
+
+		if (!sm->sm_loaded && smo->smo_object != 0) {
+			mutex_exit(&mg->mg_lock);
+			dmu_prefetch(spa->spa_meta_objset, smo->smo_object,
+			    0ULL, smo->smo_objsize);
+			mutex_enter(&mg->mg_lock);
+		}
+	}
+	mutex_exit(&mg->mg_lock);
 }
 
 static int
 metaslab_activate(metaslab_t *msp, uint64_t activation_weight, uint64_t size)
 {
+	metaslab_group_t *mg = msp->ms_group;
 	space_map_t *sm = &msp->ms_map;
 	space_map_ops_t *sm_ops = msp->ms_group->mg_class->mc_ops;
 
@@ -587,6 +766,15 @@ metaslab_activate(metaslab_t *msp, uint64_t activation_weight, uint64_t size)
 			return (error);
 		}
 
+		/*
+		 * Track the bonus area as we activate new metaslabs.
+		 */
+		if (sm->sm_start > mg->mg_bonus_area) {
+			mutex_enter(&mg->mg_lock);
+			mg->mg_bonus_area = sm->sm_start;
+			mutex_exit(&mg->mg_lock);
+		}
+
 		/*
 		 * If we were able to load the map then make sure
 		 * that this map is still able to satisfy our request.
@@ -773,6 +961,32 @@ metaslab_sync_done(metaslab_t *msp, uint64_t txg)
 	mutex_exit(&msp->ms_lock);
 }
 
+void
+metaslab_sync_reassess(metaslab_group_t *mg)
+{
+	vdev_t *vd = mg->mg_vd;
+
+	/*
+	 * Re-evaluate all metaslabs which have lower offsets than the
+	 * bonus area.
+	 */
+	for (int m = 0; m < vd->vdev_ms_count; m++) {
+		metaslab_t *msp = vd->vdev_ms[m];
+
+		if (msp->ms_map.sm_start > mg->mg_bonus_area)
+			break;
+
+		mutex_enter(&msp->ms_lock);
+		metaslab_group_sort(mg, msp, metaslab_weight(msp));
+		mutex_exit(&msp->ms_lock);
+	}
+
+	/*
+	 * Prefetch the next potential metaslabs
+	 */
+	metaslab_prefetch(mg);
+}
+
 static uint64_t
 metaslab_distance(metaslab_t *msp, dva_t *dva)
 {
@@ -868,7 +1082,7 @@ metaslab_group_alloc(metaslab_group_t *mg, uint64_t size, uint64_t txg,
 		if ((offset = space_map_alloc(&msp->ms_map, size)) != -1ULL)
 			break;
 
-		metaslab_passivate(msp, size - 1);
+		metaslab_passivate(msp, space_map_maxsize(&msp->ms_map));
 
 		mutex_exit(&msp->ms_lock);
 	}
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c
index cb6f413c640..da030f1084e 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c
@@ -74,35 +74,38 @@ enum zti_modes {
 	zti_mode_fixed,			/* value is # of threads (min 1) */
 	zti_mode_online_percent,	/* value is % of online CPUs */
 	zti_mode_tune,			/* fill from zio_taskq_tune_* */
+	zti_mode_null,			/* don't create a taskq */
 	zti_nmodes
 };
 
-#define	ZTI_THREAD_FIX(n)	{ zti_mode_fixed, (n) }
-#define	ZTI_THREAD_PCT(n)	{ zti_mode_online_percent, (n) }
-#define	ZTI_THREAD_TUNE		{ zti_mode_tune, 0 }
+#define	ZTI_FIX(n)	{ zti_mode_fixed, (n) }
+#define	ZTI_PCT(n)	{ zti_mode_online_percent, (n) }
+#define	ZTI_TUNE	{ zti_mode_tune, 0 }
+#define	ZTI_NULL	{ zti_mode_null, 0 }
 
-#define	ZTI_THREAD_ONE		ZTI_THREAD_FIX(1)
+#define	ZTI_ONE		ZTI_FIX(1)
 
 typedef struct zio_taskq_info {
-	const char *zti_name;
-	struct {
-		enum zti_modes zti_mode;
-		uint_t zti_value;
-	} zti_nthreads[ZIO_TASKQ_TYPES];
+	enum zti_modes zti_mode;
+	uint_t zti_value;
 } zio_taskq_info_t;
 
 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
-				"issue",		"intr"
+		"issue", "issue_high", "intr", "intr_high"
 };
 
-const zio_taskq_info_t zio_taskqs[ZIO_TYPES] = {
-	/*			ISSUE			INTR		*/
-	{ "spa_zio_null",	{ ZTI_THREAD_ONE,	ZTI_THREAD_ONE } },
-	{ "spa_zio_read",	{ ZTI_THREAD_FIX(8),	ZTI_THREAD_TUNE } },
-	{ "spa_zio_write",	{ ZTI_THREAD_TUNE,	ZTI_THREAD_FIX(8) } },
-	{ "spa_zio_free",	{ ZTI_THREAD_ONE,	ZTI_THREAD_ONE } },
-	{ "spa_zio_claim",	{ ZTI_THREAD_ONE,	ZTI_THREAD_ONE } },
-	{ "spa_zio_ioctl",	{ ZTI_THREAD_ONE,	ZTI_THREAD_ONE } },
+/*
+ * Define the taskq threads for the following I/O types:
+ * 	NULL, READ, WRITE, FREE, CLAIM, and IOCTL
+ */
+const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
+	/* ISSUE	ISSUE_HIGH	INTR		INTR_HIGH */
+	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
+	{ ZTI_FIX(8),	ZTI_NULL,	ZTI_TUNE,	ZTI_NULL },
+	{ ZTI_TUNE,	ZTI_FIX(5),	ZTI_FIX(8),	ZTI_FIX(5) },
+	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
+	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
+	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL },
 };
 
 enum zti_modes zio_taskq_tune_mode = zti_mode_online_percent;
@@ -581,14 +584,14 @@ spa_activate(spa_t *spa, int mode)
 	spa->spa_log_class = metaslab_class_create(zfs_metaslab_ops);
 
 	for (int t = 0; t < ZIO_TYPES; t++) {
-		const zio_taskq_info_t *ztip = &zio_taskqs[t];
 		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
-			enum zti_modes mode = ztip->zti_nthreads[q].zti_mode;
-			uint_t value = ztip->zti_nthreads[q].zti_value;
+			const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
+			enum zti_modes mode = ztip->zti_mode;
+			uint_t value = ztip->zti_value;
 			char name[32];
 
 			(void) snprintf(name, sizeof (name),
-			    "%s_%s", ztip->zti_name, zio_taskq_types[q]);
+			    "%s_%s", zio_type_name[t], zio_taskq_types[q]);
 
 			if (mode == zti_mode_tune) {
 				mode = zio_taskq_tune_mode;
@@ -613,6 +616,10 @@ spa_activate(spa_t *spa, int mode)
 				    TASKQ_PREPOPULATE | TASKQ_THREADS_CPU_PCT);
 				break;
 
+			case zti_mode_null:
+				spa->spa_zio_taskq[t][q] = NULL;
+				break;
+
 			case zti_mode_tune:
 			default:
 				panic("unrecognized mode for "
@@ -659,7 +666,8 @@ spa_deactivate(spa_t *spa)
 
 	for (int t = 0; t < ZIO_TYPES; t++) {
 		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
-			taskq_destroy(spa->spa_zio_taskq[t][q]);
+			if (spa->spa_zio_taskq[t][q] != NULL)
+				taskq_destroy(spa->spa_zio_taskq[t][q]);
 			spa->spa_zio_taskq[t][q] = NULL;
 		}
 	}
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/space_map.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/space_map.c
index 75b55d5c1ca..d0251419cbc 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/space_map.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/space_map.c
@@ -368,10 +368,8 @@ space_map_unload(space_map_t *sm)
 uint64_t
 space_map_maxsize(space_map_t *sm)
 {
-	if (sm->sm_loaded && sm->sm_ops != NULL)
-		return (sm->sm_ops->smop_max(sm));
-	else
-		return (-1ULL);
+	ASSERT(sm->sm_ops != NULL);
+	return (sm->sm_ops->smop_max(sm));
 }
 
 uint64_t
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab.h
index 5d3e11c971f..c77b7720549 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab.h
@@ -46,6 +46,7 @@ extern metaslab_t *metaslab_init(metaslab_group_t *mg, space_map_obj_t *smo,
 extern void metaslab_fini(metaslab_t *msp);
 extern void metaslab_sync(metaslab_t *msp, uint64_t txg);
 extern void metaslab_sync_done(metaslab_t *msp, uint64_t txg);
+extern void metaslab_sync_reassess(metaslab_group_t *mg);
 
 #define	METASLAB_HINTBP_FAVOR	0x0
 #define	METASLAB_HINTBP_AVOID	0x1
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab_impl.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab_impl.h
index d67dea7e975..5f0b77086b0 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab_impl.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/metaslab_impl.h
@@ -46,6 +46,7 @@ struct metaslab_group {
 	kmutex_t		mg_lock;
 	avl_tree_t		mg_metaslab_tree;
 	uint64_t		mg_aliquot;
+	uint64_t		mg_bonus_area;
 	int64_t			mg_bias;
 	metaslab_class_t	*mg_class;
 	vdev_t			*mg_vd;
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h
index f3124b1ecc0..ecb065c3f98 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h
@@ -87,7 +87,9 @@ typedef enum spa_log_state {
 
 enum zio_taskq_type {
 	ZIO_TASKQ_ISSUE = 0,
+	ZIO_TASKQ_ISSUE_HIGH,
 	ZIO_TASKQ_INTERRUPT,
+	ZIO_TASKQ_INTERRUPT_HIGH,
 	ZIO_TASKQ_TYPES
 };
 
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/space_map.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/space_map.h
index a682bbd409e..6f935c9db27 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/space_map.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/space_map.h
@@ -77,6 +77,7 @@ struct space_map_ops {
 	void	(*smop_claim)(space_map_t *sm, uint64_t start, uint64_t size);
 	void	(*smop_free)(space_map_t *sm, uint64_t start, uint64_t size);
 	uint64_t (*smop_max)(space_map_t *sm);
+	boolean_t (*smop_fragmented)(space_map_t *sm);
 };
 
 /*
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zio.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zio.h
index d7c0febdfc7..109b64ea9d0 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zio.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zio.h
@@ -107,14 +107,15 @@ enum zio_compress {
 #define	ZIO_PRIORITY_NOW		(zio_priority_table[0])
 #define	ZIO_PRIORITY_SYNC_READ		(zio_priority_table[1])
 #define	ZIO_PRIORITY_SYNC_WRITE		(zio_priority_table[2])
-#define	ZIO_PRIORITY_ASYNC_READ		(zio_priority_table[3])
-#define	ZIO_PRIORITY_ASYNC_WRITE	(zio_priority_table[4])
-#define	ZIO_PRIORITY_FREE		(zio_priority_table[5])
-#define	ZIO_PRIORITY_CACHE_FILL		(zio_priority_table[6])
-#define	ZIO_PRIORITY_LOG_WRITE		(zio_priority_table[7])
-#define	ZIO_PRIORITY_RESILVER		(zio_priority_table[8])
-#define	ZIO_PRIORITY_SCRUB		(zio_priority_table[9])
-#define	ZIO_PRIORITY_TABLE_SIZE		10
+#define	ZIO_PRIORITY_LOG_WRITE		(zio_priority_table[3])
+#define	ZIO_PRIORITY_CACHE_FILL		(zio_priority_table[4])
+#define	ZIO_PRIORITY_AGG		(zio_priority_table[5])
+#define	ZIO_PRIORITY_FREE		(zio_priority_table[6])
+#define	ZIO_PRIORITY_ASYNC_WRITE	(zio_priority_table[7])
+#define	ZIO_PRIORITY_ASYNC_READ		(zio_priority_table[8])
+#define	ZIO_PRIORITY_RESILVER		(zio_priority_table[9])
+#define	ZIO_PRIORITY_SCRUB		(zio_priority_table[10])
+#define	ZIO_PRIORITY_TABLE_SIZE		11
 
 #define	ZIO_FLAG_MUSTSUCCEED		0x00000
 #define	ZIO_FLAG_CANFAIL		0x00001
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c
index befc8b36bc3..140deed7a5b 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c
@@ -1773,9 +1773,13 @@ void
 vdev_sync_done(vdev_t *vd, uint64_t txg)
 {
 	metaslab_t *msp;
+	boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
 
 	while (msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
 		metaslab_sync_done(msp, txg);
+
+	if (reassess)
+		metaslab_sync_reassess(vd->vdev_mg);
 }
 
 void
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_queue.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_queue.c
index ac8404e36ac..de3f1db7596 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_queue.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_queue.c
@@ -233,7 +233,7 @@ vdev_queue_io_to_issue(vdev_queue_t *vq, uint64_t pending_limit)
 		ASSERT(size <= zfs_vdev_aggregation_limit);
 
 		aio = zio_vdev_delegated_io(fio->io_vd, fio->io_offset,
-		    zio_buf_alloc(size), size, fio->io_type, ZIO_PRIORITY_NOW,
+		    zio_buf_alloc(size), size, fio->io_type, ZIO_PRIORITY_AGG,
 		    flags | ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE,
 		    vdev_queue_agg_io_done, NULL);
 
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
index 75b76171156..8ddf7cdd654 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
@@ -49,11 +49,12 @@ uint8_t zio_priority_table[ZIO_PRIORITY_TABLE_SIZE] = {
 	0,	/* ZIO_PRIORITY_NOW		*/
 	0,	/* ZIO_PRIORITY_SYNC_READ	*/
 	0,	/* ZIO_PRIORITY_SYNC_WRITE	*/
-	6,	/* ZIO_PRIORITY_ASYNC_READ	*/
-	4,	/* ZIO_PRIORITY_ASYNC_WRITE	*/
-	4,	/* ZIO_PRIORITY_FREE		*/
-	0,	/* ZIO_PRIORITY_CACHE_FILL	*/
 	0,	/* ZIO_PRIORITY_LOG_WRITE	*/
+	1,	/* ZIO_PRIORITY_CACHE_FILL	*/
+	1,	/* ZIO_PRIORITY_AGG		*/
+	4,	/* ZIO_PRIORITY_FREE		*/
+	4,	/* ZIO_PRIORITY_ASYNC_WRITE	*/
+	6,	/* ZIO_PRIORITY_ASYNC_READ	*/
 	10,	/* ZIO_PRIORITY_RESILVER	*/
 	20,	/* ZIO_PRIORITY_SCRUB		*/
 };
@@ -64,7 +65,9 @@ uint8_t zio_priority_table[ZIO_PRIORITY_TABLE_SIZE] = {
  * ==========================================================================
  */
 char *zio_type_name[ZIO_TYPES] = {
-	"null", "read", "write", "free", "claim", "ioctl" };
+	"zio_null", "zio_read", "zio_write", "zio_free", "zio_claim",
+	"zio_ioctl"
+};
 
 #define	SYNC_PASS_DEFERRED_FREE	1	/* defer frees after this pass */
 #define	SYNC_PASS_DONT_COMPRESS	4	/* don't compress after this pass */
@@ -942,6 +945,7 @@ zio_write_bp_init(zio_t *zio)
 static void
 zio_taskq_dispatch(zio_t *zio, enum zio_taskq_type q)
 {
+	spa_t *spa = zio->io_spa;
 	zio_type_t t = zio->io_type;
 
 	/*
@@ -958,7 +962,15 @@ zio_taskq_dispatch(zio_t *zio, enum zio_taskq_type q)
 	if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
 		t = ZIO_TYPE_NULL;
 
-	(void) taskq_dispatch_safe(zio->io_spa->spa_zio_taskq[t][q],
+	/*
+	 * If this is a high priority I/O, then use the high priority taskq.
+	 */
+	if (zio->io_priority == ZIO_PRIORITY_NOW &&
+	    spa->spa_zio_taskq[t][q + 1] != NULL)
+		q++;
+
+	ASSERT3U(q, <, ZIO_TASKQ_TYPES);
+	(void) taskq_dispatch_safe(spa->spa_zio_taskq[t][q],
 	    (task_func_t *)zio_execute, zio, &zio->io_task);
 }
 

From 8d87b396f88f65cb394afe718aa1b4ecc4ebddeb Mon Sep 17 00:00:00 2001
From: Martin Matuska 
Date: Sat, 28 Aug 2010 09:24:11 +0000
Subject: [PATCH 0319/1624] Import changes from OpenSolaris that provide -
 better ACL caching and speedup of ACL permission checks - faster handling of
 stat() - lowered mutex contention in the read/writer lock (rrwlock) - several
 related bugfixes

Detailed information (OpenSolaris onnv changesets and Bug IDs):

9749:105f407a2680
6802734	Support for Access Based Enumeration (not used on FreeBSD)
6844861	inconsistent xattr readdir behavior with too-small buffer

9866:ddc5f1d8eb4e
6848431	zfs with rstchown=0 or file_chown_self privilege allows user to "take" ownership

9981:b4907297e740
6775100	stat() performance on files on zfs should be improved
6827779	rrwlock is overly protective of its counters

10143:d2d432dfe597
6857433	memory leaks found at: zfs_acl_alloc/zfs_acl_node_alloc
6860318	truncate() on zfsroot succeeds when file has a component of its path set without access permission

10232:f37b85f7e03e
6865875	zfs sometimes incorrectly giving search access to a dir

10250:b179ceb34b62
6867395	zpool_upgrade_007_pos testcase panic'd with BAD TRAP: type=e (#pf Page fault)

10269:2788675568fd
6868276	zfs_rezget() can be hazardous when znode has a cached ACL

10295:f7a18a1e9610
6870564	panic in zfs_getsecattr

Approved by:	delphij (mentor)
Obtained from:	OpenSolaris (multiple Bug IDs)
MFC after:	2 weeks
---
 .../opensolaris/kern/opensolaris_policy.c     |   2 +-
 sys/cddl/compat/opensolaris/sys/policy.h      |   3 +-
 .../opensolaris/uts/common/Makefile.files     |   3 +
 .../opensolaris/uts/common/fs/zfs/rrwlock.c   |  39 +-
 .../uts/common/fs/zfs/sys/zfs_acl.h           |   2 +
 .../uts/common/fs/zfs/sys/zfs_znode.h         |   2 +
 .../opensolaris/uts/common/fs/zfs/zfs_acl.c   | 337 ++++++++++++++----
 .../uts/common/fs/zfs/zfs_vfsops.c            |   1 +
 .../opensolaris/uts/common/fs/zfs/zfs_vnops.c | 118 ++++--
 .../opensolaris/uts/common/fs/zfs/zfs_znode.c |  24 ++
 .../opensolaris/uts/common/sys/vnode.h        |   1 +
 11 files changed, 412 insertions(+), 120 deletions(-)

diff --git a/sys/cddl/compat/opensolaris/kern/opensolaris_policy.c b/sys/cddl/compat/opensolaris/kern/opensolaris_policy.c
index c6347c25158..3b22c44082e 100644
--- a/sys/cddl/compat/opensolaris/kern/opensolaris_policy.c
+++ b/sys/cddl/compat/opensolaris/kern/opensolaris_policy.c
@@ -332,7 +332,7 @@ secpolicy_vnode_owner(struct vnode *vp, cred_t *cred, uid_t owner)
 }
 
 int
-secpolicy_vnode_chown(struct vnode *vp, cred_t *cred, boolean_t check_self)
+secpolicy_vnode_chown(struct vnode *vp, cred_t *cred, uid_t owner)
 {
 
 	if (secpolicy_fs_owner(vp->v_mount, cred) == 0)
diff --git a/sys/cddl/compat/opensolaris/sys/policy.h b/sys/cddl/compat/opensolaris/sys/policy.h
index 9fd2092fd7d..f61859b557e 100644
--- a/sys/cddl/compat/opensolaris/sys/policy.h
+++ b/sys/cddl/compat/opensolaris/sys/policy.h
@@ -47,8 +47,7 @@ int	secpolicy_zinject(struct ucred *cred);
 int	secpolicy_fs_unmount(struct ucred *cred, struct mount *vfsp);
 int	secpolicy_basic_link(struct vnode *vp, struct ucred *cred);
 int	secpolicy_vnode_owner(struct vnode *vp, cred_t *cred, uid_t owner);
-int	secpolicy_vnode_chown(struct vnode *vp, cred_t *cred,
-	    boolean_t check_self);
+int	secpolicy_vnode_chown(struct vnode *vp, cred_t *cred, uid_t owner);
 int	secpolicy_vnode_stky_modify(struct ucred *cred);
 int	secpolicy_vnode_remove(struct vnode *vp, struct ucred *cred);
 int	secpolicy_vnode_access(struct ucred *cred, struct vnode *vp,
diff --git a/sys/cddl/contrib/opensolaris/uts/common/Makefile.files b/sys/cddl/contrib/opensolaris/uts/common/Makefile.files
index cf49c78a5b0..3761d5ed31f 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/Makefile.files
+++ b/sys/cddl/contrib/opensolaris/uts/common/Makefile.files
@@ -19,6 +19,9 @@
 # CDDL HEADER END
 #
 
+ZUT_OBJS +=			\
+	zut.o
+
 #
 # Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 # Use is subject to license terms.
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c
index db3b70fc68b..f09c984651e 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c
@@ -19,12 +19,10 @@
  * CDDL HEADER END
  */
 /*
- * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
  * Use is subject to license terms.
  */
 
-#pragma ident	"%Z%%M%	%I%	%E% SMI"
-
 #include 
 #include 
 
@@ -84,7 +82,7 @@ rrn_find(rrwlock_t *rrl)
 	rrw_node_t *rn;
 
 	if (refcount_count(&rrl->rr_linked_rcount) == 0)
-		return (NULL);
+		return (B_FALSE);
 
 	for (rn = tsd_get(rrw_tsd_key); rn != NULL; rn = rn->rn_next) {
 		if (rn->rn_rrl == rrl)
@@ -159,6 +157,14 @@ static void
 rrw_enter_read(rrwlock_t *rrl, void *tag)
 {
 	mutex_enter(&rrl->rr_lock);
+#if !defined(DEBUG) && defined(_KERNEL)
+	if (!rrl->rr_writer && !rrl->rr_writer_wanted) {
+		rrl->rr_anon_rcount.rc_count++;
+		mutex_exit(&rrl->rr_lock);
+		return;
+	}
+	DTRACE_PROBE(zfs__rrwfastpath__rdmiss);
+#endif
 	ASSERT(rrl->rr_writer != curthread);
 	ASSERT(refcount_count(&rrl->rr_anon_rcount) >= 0);
 
@@ -208,19 +214,28 @@ void
 rrw_exit(rrwlock_t *rrl, void *tag)
 {
 	mutex_enter(&rrl->rr_lock);
+#if !defined(DEBUG) && defined(_KERNEL)
+	if (!rrl->rr_writer && rrl->rr_linked_rcount.rc_count == 0) {
+		rrl->rr_anon_rcount.rc_count--;
+		if (rrl->rr_anon_rcount.rc_count == 0)
+			cv_broadcast(&rrl->rr_cv);
+		mutex_exit(&rrl->rr_lock);
+		return;
+	}
+	DTRACE_PROBE(zfs__rrwfastpath__exitmiss);
+#endif
 	ASSERT(!refcount_is_zero(&rrl->rr_anon_rcount) ||
 	    !refcount_is_zero(&rrl->rr_linked_rcount) ||
 	    rrl->rr_writer != NULL);
 
 	if (rrl->rr_writer == NULL) {
-		if (rrn_find_and_remove(rrl)) {
-			if (refcount_remove(&rrl->rr_linked_rcount, tag) == 0)
-				cv_broadcast(&rrl->rr_cv);
-
-		} else {
-			if (refcount_remove(&rrl->rr_anon_rcount, tag) == 0)
-				cv_broadcast(&rrl->rr_cv);
-		}
+		int64_t count;
+		if (rrn_find_and_remove(rrl))
+			count = refcount_remove(&rrl->rr_linked_rcount, tag);
+		else
+			count = refcount_remove(&rrl->rr_anon_rcount, tag);
+		if (count == 0)
+			cv_broadcast(&rrl->rr_cv);
 	} else {
 		ASSERT(rrl->rr_writer == curthread);
 		ASSERT(refcount_is_zero(&rrl->rr_anon_rcount) &&
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_acl.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_acl.h
index 3607e1f3c93..ea150950430 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_acl.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_acl.h
@@ -200,7 +200,9 @@ int zfs_setacl(struct znode *, vsecattr_t *, boolean_t, cred_t *);
 void zfs_acl_rele(void *);
 void zfs_oldace_byteswap(ace_t *, int);
 void zfs_ace_byteswap(void *, size_t, boolean_t);
+extern boolean_t zfs_has_access(struct znode *zp, cred_t *cr);
 extern int zfs_zaccess(struct znode *, int, int, boolean_t, cred_t *);
+int zfs_fastaccesschk_execute(struct znode *, cred_t *);
 extern int zfs_zaccess_rwx(struct znode *, mode_t, int, cred_t *);
 extern int zfs_zaccess_unix(struct znode *, mode_t, cred_t *);
 extern int zfs_acl_access(struct znode *, int, cred_t *);
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_znode.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_znode.h
index 47072fb3bfd..6f0a4363601 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_znode.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_znode.h
@@ -74,6 +74,7 @@ extern "C" {
 #define	ZFS_ACL_DEFAULTED	0x20		/* ACL should be defaulted */
 #define	ZFS_ACL_AUTO_INHERIT	0x40		/* ACL should be inherited */
 #define	ZFS_BONUS_SCANSTAMP	0x80		/* Scanstamp in bonus area */
+#define	ZFS_NO_EXECS_DENIED	0x100		/* exec was given to everyone */
 
 /*
  * Is ID ephemeral?
@@ -202,6 +203,7 @@ typedef struct znode {
 	uint64_t	z_gen;		/* generation (same as zp_gen) */
 	uint32_t	z_sync_cnt;	/* synchronous open count */
 	kmutex_t	z_acl_lock;	/* acl data lock */
+	zfs_acl_t	*z_acl_cached;	/* cached acl */
 	list_node_t	z_link_node;	/* all znodes in fs link */
 	/*
 	 * These are dmu managed fields.
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_acl.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_acl.c
index c42f0941e75..fc25bfe1de1 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_acl.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_acl.c
@@ -91,6 +91,8 @@
 #define	ZFS_ACL_WIDE_FLAGS (V4_ACL_WIDE_FLAGS|ZFS_ACL_TRIVIAL|ZFS_INHERIT_ACE|\
     ZFS_ACL_OBJ_ACE)
 
+#define	ALL_MODE_EXECS (S_IXUSR | S_IXGRP | S_IXOTH)
+
 static uint16_t
 zfs_ace_v0_get_type(void *acep)
 {
@@ -779,6 +781,7 @@ zfs_mode_compute(znode_t *zp, zfs_acl_t *aclp)
 	uint64_t	who;
 	uint16_t	iflags, type;
 	uint32_t	access_mask;
+	boolean_t	an_exec_denied = B_FALSE;
 
 	mode = (zp->z_phys->zp_mode & (S_IFMT | S_ISUID | S_ISGID | S_ISVTX));
 
@@ -903,8 +906,32 @@ zfs_mode_compute(znode_t *zp, zfs_acl_t *aclp)
 					}
 				}
 			}
+		} else {
+			/*
+			 * Only care if this IDENTIFIER_GROUP or
+			 * USER ACE denies execute access to someone,
+			 * mode is not affected
+			 */
+			if ((access_mask & ACE_EXECUTE) && type == DENY)
+				an_exec_denied = B_TRUE;
 		}
 	}
+
+	/*
+	 * Failure to allow is effectively a deny, so execute permission
+	 * is denied if it was never mentioned or if we explicitly
+	 * weren't allowed it.
+	 */
+	if (!an_exec_denied &&
+	    ((seen & ALL_MODE_EXECS) != ALL_MODE_EXECS ||
+	    (mode & ALL_MODE_EXECS) != ALL_MODE_EXECS))
+		an_exec_denied = B_TRUE;
+
+	if (an_exec_denied)
+		zp->z_phys->zp_flags &= ~ZFS_NO_EXECS_DENIED;
+	else
+		zp->z_phys->zp_flags |= ZFS_NO_EXECS_DENIED;
+
 	return (mode);
 }
 
@@ -944,7 +971,8 @@ zfs_acl_node_read_internal(znode_t *zp, boolean_t will_modify)
 }
 
 /*
- * Read an external acl object.
+ * Read an external acl object.  If the intent is to modify, always
+ * create a new acl and leave any cached acl in place.
  */
 static int
 zfs_acl_node_read(znode_t *zp, zfs_acl_t **aclpp, boolean_t will_modify)
@@ -958,8 +986,15 @@ zfs_acl_node_read(znode_t *zp, zfs_acl_t **aclpp, boolean_t will_modify)
 
 	ASSERT(MUTEX_HELD(&zp->z_acl_lock));
 
+	if (zp->z_acl_cached && !will_modify) {
+		*aclpp = zp->z_acl_cached;
+		return (0);
+	}
+
 	if (zp->z_phys->zp_acl.z_acl_extern_obj == 0) {
 		*aclpp = zfs_acl_node_read_internal(zp, will_modify);
+		if (!will_modify)
+			zp->z_acl_cached = *aclpp;
 		return (0);
 	}
 
@@ -993,6 +1028,8 @@ zfs_acl_node_read(znode_t *zp, zfs_acl_t **aclpp, boolean_t will_modify)
 	}
 
 	*aclpp = aclp;
+	if (!will_modify)
+		zp->z_acl_cached = aclp;
 	return (0);
 }
 
@@ -1017,11 +1054,16 @@ zfs_aclset_common(znode_t *zp, zfs_acl_t *aclp, cred_t *cr, dmu_tx_t *tx)
 
 	dmu_buf_will_dirty(zp->z_dbuf, tx);
 
+	if (zp->z_acl_cached) {
+		zfs_acl_free(zp->z_acl_cached);
+		zp->z_acl_cached = NULL;
+	}
+
 	zphys->zp_mode = zfs_mode_compute(zp, aclp);
 
 	/*
-	 * Decide which opbject type to use.  If we are forced to
-	 * use old ACL format than transform ACL into zfs_oldace_t
+	 * Decide which object type to use.  If we are forced to
+	 * use old ACL format then transform ACL into zfs_oldace_t
 	 * layout.
 	 */
 	if (!zfsvfs->z_use_fuids) {
@@ -1871,7 +1913,6 @@ zfs_acl_ids_create(znode_t *dzp, int flag, vattr_t *vap, cred_t *cr,
 			mutex_exit(&dzp->z_acl_lock);
 			acl_ids->z_aclp = zfs_acl_inherit(zfsvfs,
 			    vap->va_type, paclp, acl_ids->z_mode, &need_chmod);
-			zfs_acl_free(paclp);
 		} else {
 			acl_ids->z_aclp =
 			    zfs_acl_alloc(zfs_acl_version_zp(dzp));
@@ -1972,8 +2013,6 @@ zfs_getacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr)
 	if (mask & VSA_ACE) {
 		size_t aclsz;
 
-		zfs_acl_node_t *aclnode = list_head(&aclp->z_acl);
-
 		aclsz = count * sizeof (ace_t) +
 		    sizeof (ace_object_t) * largeace;
 
@@ -1984,8 +2023,17 @@ zfs_getacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr)
 			zfs_copy_fuid_2_ace(zp->z_zfsvfs, aclp, cr,
 			    vsecp->vsa_aclentp, !(mask & VSA_ACE_ALLTYPES));
 		else {
-			bcopy(aclnode->z_acldata, vsecp->vsa_aclentp,
-			    count * sizeof (ace_t));
+			zfs_acl_node_t *aclnode;
+			void *start = vsecp->vsa_aclentp;
+
+			for (aclnode = list_head(&aclp->z_acl); aclnode;
+			    aclnode = list_next(&aclp->z_acl, aclnode)) {
+				bcopy(aclnode->z_acldata, start,
+				    aclnode->z_size);
+				start = (caddr_t)start + aclnode->z_size;
+			}
+			ASSERT((caddr_t)start - (caddr_t)vsecp->vsa_aclentp ==
+			    aclp->z_acl_bytes);
 		}
 	}
 	if (mask & VSA_ACE_ACLFLAGS) {
@@ -2000,8 +2048,6 @@ zfs_getacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr)
 
 	mutex_exit(&zp->z_acl_lock);
 
-	zfs_acl_free(aclp);
-
 	return (0);
 }
 
@@ -2097,11 +2143,6 @@ zfs_setacl(znode_t *zp, vsecattr_t *vsecp, boolean_t skipaclchk, cred_t *cr)
 		aclp->z_hints |= (zp->z_phys->zp_flags & V4_ACL_WIDE_FLAGS);
 	}
 top:
-	if (error = zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr)) {
-		zfs_acl_free(aclp);
-		return (error);
-	}
-
 	mutex_enter(&zp->z_lock);
 	mutex_enter(&zp->z_acl_lock);
 
@@ -2147,6 +2188,7 @@ top:
 
 	error = zfs_aclset_common(zp, aclp, cr, tx);
 	ASSERT(error == 0);
+	zp->z_acl_cached = aclp;
 
 	if (fuid_dirtied)
 		zfs_fuid_sync(zfsvfs, tx);
@@ -2156,7 +2198,6 @@ top:
 
 	if (fuidp)
 		zfs_fuid_info_free(fuidp);
-	zfs_acl_free(aclp);
 	dmu_tx_commit(tx);
 done:
 	mutex_exit(&zp->z_acl_lock);
@@ -2166,46 +2207,17 @@ done:
 }
 
 /*
- * working_mode returns the permissions that were not granted
+ * Check accesses of interest (AoI) against attributes of the dataset
+ * such as read-only.  Returns zero if no AoI conflict with dataset
+ * attributes, otherwise an appropriate errno is returned.
  */
 static int
-zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
-    boolean_t *check_privs, boolean_t skipaclchk, cred_t *cr)
+zfs_zaccess_dataset_check(znode_t *zp, uint32_t v4_mode)
 {
-	zfs_acl_t	*aclp;
-	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
-	int		error;
-	uid_t		uid = crgetuid(cr);
-	uint64_t 	who;
-	uint16_t	type, iflags;
-	uint16_t	entry_type;
-	uint32_t	access_mask;
-	uint32_t	deny_mask = 0;
-	zfs_ace_hdr_t	*acep = NULL;
-	boolean_t	checkit;
-	uid_t		fowner;
-	uid_t		gowner;
-
-	/*
-	 * Short circuit empty requests
-	 */
-	if (v4_mode == 0)
-		return (0);
-
-	*check_privs = B_TRUE;
-
-	if (zfsvfs->z_replay) {
-		*working_mode = 0;
-		return (0);
-	}
-
-	*working_mode = v4_mode;
-
 	if ((v4_mode & WRITE_MASK) &&
 	    (zp->z_zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) &&
 	    (!IS_DEVVP(ZTOV(zp)) ||
 	    (IS_DEVVP(ZTOV(zp)) && (v4_mode & WRITE_MASK_ATTRS)))) {
-		*check_privs = B_FALSE;
 		return (EROFS);
 	}
 
@@ -2217,14 +2229,12 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 	    (zp->z_phys->zp_flags & (ZFS_READONLY | ZFS_IMMUTABLE))) ||
 	    (ZTOV(zp)->v_type == VDIR &&
 	    (zp->z_phys->zp_flags & ZFS_IMMUTABLE)))) {
-		*check_privs = B_FALSE;
 		return (EPERM);
 	}
 
 #ifdef sun
 	if ((v4_mode & (ACE_DELETE | ACE_DELETE_CHILD)) &&
 	    (zp->z_phys->zp_flags & ZFS_NOUNLINK)) {
-		*check_privs = B_FALSE;
 		return (EPERM);
 	}
 #else
@@ -2235,26 +2245,60 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 	 */
 	if ((v4_mode & ACE_DELETE) &&
 	    (zp->z_phys->zp_flags & ZFS_NOUNLINK)) {
-		*check_privs = B_FALSE;
 		return (EPERM);
 	}
 #endif
 
 	if (((v4_mode & (ACE_READ_DATA|ACE_EXECUTE)) &&
 	    (zp->z_phys->zp_flags & ZFS_AV_QUARANTINED))) {
-		*check_privs = B_FALSE;
 		return (EACCES);
 	}
 
-	/*
-	 * The caller requested that the ACL check be skipped.  This
-	 * would only happen if the caller checked VOP_ACCESS() with a
-	 * 32 bit ACE mask and already had the appropriate permissions.
-	 */
-	if (skipaclchk) {
-		*working_mode = 0;
-		return (0);
-	}
+	return (0);
+}
+
+/*
+ * The primary usage of this function is to loop through all of the
+ * ACEs in the znode, determining what accesses of interest (AoI) to
+ * the caller are allowed or denied.  The AoI are expressed as bits in
+ * the working_mode parameter.  As each ACE is processed, bits covered
+ * by that ACE are removed from the working_mode.  This removal
+ * facilitates two things.  The first is that when the working mode is
+ * empty (= 0), we know we've looked at all the AoI. The second is
+ * that the ACE interpretation rules don't allow a later ACE to undo
+ * something granted or denied by an earlier ACE.  Removing the
+ * discovered access or denial enforces this rule.  At the end of
+ * processing the ACEs, all AoI that were found to be denied are
+ * placed into the working_mode, giving the caller a mask of denied
+ * accesses.  Returns:
+ *	0		if all AoI granted
+ *	EACCESS 	if the denied mask is non-zero
+ *	other error	if abnormal failure (e.g., IO error)
+ *
+ * A secondary usage of the function is to determine if any of the
+ * AoI are granted.  If an ACE grants any access in
+ * the working_mode, we immediately short circuit out of the function.
+ * This mode is chosen by setting anyaccess to B_TRUE.  The
+ * working_mode is not a denied access mask upon exit if the function
+ * is used in this manner.
+ */
+static int
+zfs_zaccess_aces_check(znode_t *zp, uint32_t *working_mode,
+    boolean_t anyaccess, cred_t *cr)
+{
+	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
+	zfs_acl_t	*aclp;
+	int		error;
+	uid_t		uid = crgetuid(cr);
+	uint64_t 	who;
+	uint16_t	type, iflags;
+	uint16_t	entry_type;
+	uint32_t	access_mask;
+	uint32_t	deny_mask = 0;
+	zfs_ace_hdr_t	*acep = NULL;
+	boolean_t	checkit;
+	uid_t		fowner;
+	uid_t		gowner;
 
 	zfs_fuid_map_ids(zp, cr, &fowner, &gowner);
 
@@ -2268,6 +2312,7 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 
 	while (acep = zfs_acl_next_ace(aclp, acep, &who, &access_mask,
 	    &iflags, &type)) {
+		uint32_t mask_matched;
 
 		if (!zfs_acl_valid_ace_type(type, iflags))
 			continue;
@@ -2275,6 +2320,11 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 		if (ZTOV(zp)->v_type == VDIR && (iflags & ACE_INHERIT_ONLY_ACE))
 			continue;
 
+		/* Skip ACE if it does not affect any AoI */
+		mask_matched = (access_mask & *working_mode);
+		if (!mask_matched)
+			continue;
+
 		entry_type = (iflags & ACE_TYPE_FLAGS);
 
 		checkit = B_FALSE;
@@ -2306,21 +2356,29 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 					checkit = B_TRUE;
 				break;
 			} else {
-				zfs_acl_free(aclp);
 				mutex_exit(&zp->z_acl_lock);
 				return (EIO);
 			}
 		}
 
 		if (checkit) {
-			uint32_t mask_matched = (access_mask & *working_mode);
-
-			if (mask_matched) {
-				if (type == DENY)
-					deny_mask |= mask_matched;
-
-				*working_mode &= ~mask_matched;
+			if (type == DENY) {
+				DTRACE_PROBE3(zfs__ace__denies,
+				    znode_t *, zp,
+				    zfs_ace_hdr_t *, acep,
+				    uint32_t, mask_matched);
+				deny_mask |= mask_matched;
+			} else {
+				DTRACE_PROBE3(zfs__ace__allows,
+				    znode_t *, zp,
+				    zfs_ace_hdr_t *, acep,
+				    uint32_t, mask_matched);
+				if (anyaccess) {
+					mutex_exit(&zp->z_acl_lock);
+					return (0);
+				}
 			}
+			*working_mode &= ~mask_matched;
 		}
 
 		/* Are we done? */
@@ -2329,7 +2387,6 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 	}
 
 	mutex_exit(&zp->z_acl_lock);
-	zfs_acl_free(aclp);
 
 	/* Put the found 'denies' back on the working mode */
 	if (deny_mask) {
@@ -2342,6 +2399,68 @@ zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
 	return (0);
 }
 
+/*
+ * Return true if any access whatsoever granted, we don't actually
+ * care what access is granted.
+ */
+boolean_t
+zfs_has_access(znode_t *zp, cred_t *cr)
+{
+	uint32_t have = ACE_ALL_PERMS;
+
+	if (zfs_zaccess_aces_check(zp, &have, B_TRUE, cr) != 0) {
+		uid_t		owner;
+
+		owner = zfs_fuid_map_id(zp->z_zfsvfs,
+		    zp->z_phys->zp_uid, cr, ZFS_OWNER);
+
+		return (
+		    secpolicy_vnode_access(cr, ZTOV(zp), owner, VREAD) == 0 ||
+		    secpolicy_vnode_access(cr, ZTOV(zp), owner, VWRITE) == 0 ||
+		    secpolicy_vnode_access(cr, ZTOV(zp), owner, VEXEC) == 0 ||
+		    secpolicy_vnode_chown(ZTOV(zp), cr, owner) == 0 ||
+		    secpolicy_vnode_setdac(ZTOV(zp), cr, owner) == 0 ||
+		    secpolicy_vnode_remove(ZTOV(zp), cr) == 0);
+	}
+	return (B_TRUE);
+}
+
+static int
+zfs_zaccess_common(znode_t *zp, uint32_t v4_mode, uint32_t *working_mode,
+    boolean_t *check_privs, boolean_t skipaclchk, cred_t *cr)
+{
+	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
+	int err;
+
+	*working_mode = v4_mode;
+	*check_privs = B_TRUE;
+
+	/*
+	 * Short circuit empty requests
+	 */
+	if (v4_mode == 0 || zfsvfs->z_replay) {
+		*working_mode = 0;
+		return (0);
+	}
+
+	if ((err = zfs_zaccess_dataset_check(zp, v4_mode)) != 0) {
+		*check_privs = B_FALSE;
+		return (err);
+	}
+
+	/*
+	 * The caller requested that the ACL check be skipped.  This
+	 * would only happen if the caller checked VOP_ACCESS() with a
+	 * 32 bit ACE mask and already had the appropriate permissions.
+	 */
+	if (skipaclchk) {
+		*working_mode = 0;
+		return (0);
+	}
+
+	return (zfs_zaccess_aces_check(zp, working_mode, B_FALSE, cr));
+}
+
 static int
 zfs_zaccess_append(znode_t *zp, uint32_t *working_mode, boolean_t *check_privs,
     cred_t *cr)
@@ -2353,6 +2472,78 @@ zfs_zaccess_append(znode_t *zp, uint32_t *working_mode, boolean_t *check_privs,
 	    check_privs, B_FALSE, cr));
 }
 
+int
+zfs_fastaccesschk_execute(znode_t *zdp, cred_t *cr)
+{
+	boolean_t owner = B_FALSE;
+	boolean_t groupmbr = B_FALSE;
+	boolean_t is_attr;
+	uid_t fowner;
+	uid_t gowner;
+	uid_t uid = crgetuid(cr);
+	int error;
+
+	if (zdp->z_phys->zp_flags & ZFS_AV_QUARANTINED)
+		return (EACCES);
+
+	is_attr = ((zdp->z_phys->zp_flags & ZFS_XATTR) &&
+	    (ZTOV(zdp)->v_type == VDIR));
+	if (is_attr)
+		goto slow;
+
+	mutex_enter(&zdp->z_acl_lock);
+
+	if (zdp->z_phys->zp_flags & ZFS_NO_EXECS_DENIED) {
+		mutex_exit(&zdp->z_acl_lock);
+		return (0);
+	}
+
+	if (FUID_INDEX(zdp->z_phys->zp_uid) != 0 ||
+	    FUID_INDEX(zdp->z_phys->zp_gid) != 0) {
+		mutex_exit(&zdp->z_acl_lock);
+		goto slow;
+	}
+
+	fowner = (uid_t)zdp->z_phys->zp_uid;
+	gowner = (uid_t)zdp->z_phys->zp_gid;
+
+	if (uid == fowner) {
+		owner = B_TRUE;
+		if (zdp->z_phys->zp_mode & S_IXUSR) {
+			mutex_exit(&zdp->z_acl_lock);
+			return (0);
+		} else {
+			mutex_exit(&zdp->z_acl_lock);
+			goto slow;
+		}
+	}
+	if (groupmember(gowner, cr)) {
+		groupmbr = B_TRUE;
+		if (zdp->z_phys->zp_mode & S_IXGRP) {
+			mutex_exit(&zdp->z_acl_lock);
+			return (0);
+		} else {
+			mutex_exit(&zdp->z_acl_lock);
+			goto slow;
+		}
+	}
+	if (!owner && !groupmbr) {
+		if (zdp->z_phys->zp_mode & S_IXOTH) {
+			mutex_exit(&zdp->z_acl_lock);
+			return (0);
+		}
+	}
+
+	mutex_exit(&zdp->z_acl_lock);
+
+slow:
+	DTRACE_PROBE(zfs__fastpath__execute__access__miss);
+	ZFS_ENTER(zdp->z_zfsvfs);
+	error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr);
+	ZFS_EXIT(zdp->z_zfsvfs);
+	return (error);
+}
+
 /*
  * Determine whether Access should be granted/denied, invoking least
  * priv subsytem when a deny is determined.
@@ -2457,7 +2648,7 @@ zfs_zaccess(znode_t *zp, int mode, int flags, boolean_t skipaclchk, cred_t *cr)
 			    owner, checkmode);
 
 		if (error == 0 && (working_mode & ACE_WRITE_OWNER))
-			error = secpolicy_vnode_chown(ZTOV(check_zp), cr, B_TRUE);
+			error = secpolicy_vnode_chown(ZTOV(check_zp), cr, owner);
 		if (error == 0 && (working_mode & ACE_WRITE_ACL))
 			error = secpolicy_vnode_setdac(ZTOV(check_zp), cr, owner);
 
@@ -2466,7 +2657,7 @@ zfs_zaccess(znode_t *zp, int mode, int flags, boolean_t skipaclchk, cred_t *cr)
 			error = secpolicy_vnode_remove(ZTOV(check_zp), cr);
 
 		if (error == 0 && (working_mode & ACE_SYNCHRONIZE)) {
-			error = secpolicy_vnode_chown(ZTOV(check_zp), cr, B_FALSE);
+			error = secpolicy_vnode_chown(ZTOV(check_zp), cr, owner);
 		}
 		if (error == 0) {
 			/*
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
index 624c16e1680..15f8767738f 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
@@ -994,6 +994,7 @@ zfs_set_fuid_feature(zfsvfs_t *zfsvfs)
 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_SYSATTR_VIEWS);
 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACEMASKONACCESS);
 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACLONCREATE);
+		vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACCESS_FILTER);
 	}
 }
 
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 8ba0843161a..1eeac3839de 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -1163,6 +1163,27 @@ zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
 	return (error);
 }
 
+/*
+ * If vnode is for a device return a specfs vnode instead.
+ */
+static int
+specvp_check(vnode_t **vpp, cred_t *cr)
+{
+	int error = 0;
+
+	if (IS_DEVVP(*vpp)) {
+		struct vnode *svp;
+
+		svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
+		VN_RELE(*vpp);
+		if (svp == NULL)
+			error = ENOSYS;
+		*vpp = svp;
+	}
+	return (error);
+}
+
+
 /*
  * Lookup an entry in a directory, or an extended attribute directory.
  * If it exists, return a held vnode reference for it.
@@ -1192,10 +1213,49 @@ zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct componentname *cnp,
 {
 	znode_t *zdp = VTOZ(dvp);
 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
-	int	error;
+	int	error = 0;
 	int *direntflags = NULL;
 	void *realpnp = NULL;
 
+	/* fast path */
+	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
+
+		if (dvp->v_type != VDIR) {
+			return (ENOTDIR);
+		} else if (zdp->z_dbuf == NULL) {
+			return (EIO);
+		}
+
+		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
+			error = zfs_fastaccesschk_execute(zdp, cr);
+			if (!error) {
+				*vpp = dvp;
+				VN_HOLD(*vpp);
+				return (0);
+			}
+			return (error);
+		} else {
+			vnode_t *tvp = dnlc_lookup(dvp, nm);
+
+			if (tvp) {
+				error = zfs_fastaccesschk_execute(zdp, cr);
+				if (error) {
+					VN_RELE(tvp);
+					return (error);
+				}
+				if (tvp == DNLC_NO_VNODE) {
+					VN_RELE(tvp);
+					return (ENOENT);
+				} else {
+					*vpp = tvp;
+					return (specvp_check(vpp, cr));
+				}
+			}
+		}
+	}
+
+	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
+
 	ZFS_ENTER(zfsvfs);
 	ZFS_VERIFY_ZP(zdp);
 
@@ -1261,21 +1321,8 @@ zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct componentname *cnp,
 	}
 
 	error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
-	if (error == 0) {
-		/*
-		 * Convert device special files
-		 */
-		if (IS_DEVVP(*vpp)) {
-			vnode_t	*svp;
-
-			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
-			VN_RELE(*vpp);
-			if (svp == NULL)
-				error = ENOSYS;
-			else
-				*vpp = svp;
-		}
-	}
+	if (error == 0)
+		error = specvp_check(vpp, cr);
 
 	/* Translate errors and add SAVENAME when needed. */
 	if (cnp->cn_flags & ISLASTCN) {
@@ -1468,6 +1515,7 @@ top:
 		    &acl_ids)) != 0)
 			goto out;
 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
+			zfs_acl_ids_free(&acl_ids);
 			error = EDQUOT;
 			goto out;
 		}
@@ -1564,19 +1612,7 @@ out:
 			VN_RELE(ZTOV(zp));
 	} else {
 		*vpp = ZTOV(zp);
-		/*
-		 * If vnode is for a device return a specfs vnode instead.
-		 */
-		if (IS_DEVVP(*vpp)) {
-			struct vnode *svp;
-
-			svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
-			VN_RELE(*vpp);
-			if (svp == NULL) {
-				error = ENOSYS;
-			}
-			*vpp = svp;
-		}
+		error = specvp_check(vpp, cr);
 	}
 
 	ZFS_EXIT(zfsvfs);
@@ -1883,6 +1919,7 @@ top:
 		return (error);
 	}
 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
+		zfs_acl_ids_free(&acl_ids);
 		zfs_dirent_unlock(dl);
 		ZFS_EXIT(zfsvfs);
 		return (EDQUOT);
@@ -2274,6 +2311,21 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp, int *ncookies, u_lon
 			}
 		}
 
+		if (flags & V_RDDIR_ACCFILTER) {
+			/*
+			 * If we have no access at all, don't include
+			 * this entry in the returned information
+			 */
+			znode_t	*ezp;
+			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
+				goto skip_entry;
+			if (!zfs_has_access(ezp, cr)) {
+				VN_RELE(ZTOV(ezp));
+				goto skip_entry;
+			}
+			VN_RELE(ZTOV(ezp));
+		}
+
 		if (flags & V_RDDIR_ENTFLAGS)
 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
 		else
@@ -2324,6 +2376,7 @@ zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp, int *ncookies, u_lon
 		if (prefetch)
 			dmu_prefetch(os, objnum, 0, 0);
 
+	skip_entry:
 		/*
 		 * Move to the next entry, fill in the previous offset.
 		 */
@@ -2712,6 +2765,7 @@ zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
 top:
 	attrzp = NULL;
 
+	/* Can this be moved to before the top label? */
 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
 		ZFS_EXIT(zfsvfs);
 		return (EROFS);
@@ -3036,6 +3090,8 @@ top:
 		zp->z_phys->zp_mode = new_mode;
 		err = zfs_aclset_common(zp, aclp, cr, tx);
 		ASSERT3U(err, ==, 0);
+		zp->z_acl_cached = aclp;
+		aclp = NULL;
 		mutex_exit(&zp->z_acl_lock);
 	}
 
@@ -3127,10 +3183,8 @@ out:
 	if (attrzp)
 		VN_RELE(ZTOV(attrzp));
 
-	if (aclp) {
+	if (aclp)
 		zfs_acl_free(aclp);
-		aclp = NULL;
-	}
 
 	if (fuidp) {
 		zfs_fuid_info_free(fuidp);
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c
index 7b50f242e1d..dbee467dbc2 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c
@@ -177,6 +177,7 @@ zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
 
 	zp->z_dbuf = NULL;
 	zp->z_dirlocks = NULL;
+	zp->z_acl_cached = NULL;
 	return (0);
 }
 
@@ -199,6 +200,7 @@ zfs_znode_cache_destructor(void *buf, void *arg)
 
 	ASSERT(zp->z_dbuf == NULL);
 	ASSERT(zp->z_dirlocks == NULL);
+	ASSERT(zp->z_acl_cached == NULL);
 }
 
 #ifdef	ZNODE_STATS
@@ -244,6 +246,15 @@ zfs_znode_move_impl(znode_t *ozp, znode_t *nzp)
 	nzp->z_phys = ozp->z_phys;
 	nzp->z_dbuf = ozp->z_dbuf;
 
+	/*
+	 * Since this is just an idle znode and kmem is already dealing with
+	 * memory pressure, release any cached ACL.
+	 */
+	if (ozp->z_acl_cached) {
+		zfs_acl_free(ozp->z_acl_cached);
+		ozp->z_acl_cached = NULL;
+	}
+
 	/* Update back pointers. */
 	(void) dmu_buf_update_user(nzp->z_dbuf, ozp, nzp, &nzp->z_phys,
 	    znode_evict_error);
@@ -497,6 +508,7 @@ zfs_znode_dmu_init(zfsvfs_t *zfsvfs, znode_t *zp, dmu_buf_t *db)
 	mutex_enter(&zp->z_lock);
 
 	ASSERT(zp->z_dbuf == NULL);
+	ASSERT(zp->z_acl_cached == NULL);
 	zp->z_dbuf = db;
 	nzp = dmu_buf_set_user_ie(db, zp, &zp->z_phys, znode_evict_error);
 
@@ -980,6 +992,13 @@ zfs_rezget(znode_t *zp)
 		return (EIO);
 	}
 
+	mutex_enter(&zp->z_acl_lock);
+	if (zp->z_acl_cached) {
+		zfs_acl_free(zp->z_acl_cached);
+		zp->z_acl_cached = NULL;
+	}
+	mutex_exit(&zp->z_acl_lock);
+
 	zfs_znode_dmu_init(zfsvfs, zp, db);
 	zp->z_unlinked = (zp->z_phys->zp_links == 0);
 	zp->z_blksz = doi.doi_data_block_size;
@@ -1065,6 +1084,11 @@ zfs_znode_free(znode_t *zp)
 	list_remove(&zfsvfs->z_all_znodes, zp);
 	mutex_exit(&zfsvfs->z_znodes_lock);
 
+	if (zp->z_acl_cached) {
+		zfs_acl_free(zp->z_acl_cached);
+		zp->z_acl_cached = NULL;
+	}
+
 	kmem_cache_free(znode_cache, zp);
 
 	VFS_RELE(zfsvfs->z_vfs);
diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/vnode.h b/sys/cddl/contrib/opensolaris/uts/common/sys/vnode.h
index 5a7c9e628e3..ab95b99b9ce 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/vnode.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/vnode.h
@@ -378,6 +378,7 @@ struct taskq;
  * Flags for VOP_READDIR
  */
 #define	V_RDDIR_ENTFLAGS	0x01	/* request dirent flags */
+#define	V_RDDIR_ACCFILTER	0x02	/* filter out inaccessible dirents */
 
 /*
  * Public vnode manipulation functions.

From b12277d1d4e4c21e5d7c96841948fd0c802ecd1b Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Sat, 28 Aug 2010 15:03:11 +0000
Subject: [PATCH 0320/1624] Repair some build breakage introduced in r211725
 and garbage collect some code made obsolete in the same commit.

---
 Makefile.inc1                                 |   4 +-
 gnu/lib/libgomp/Makefile                      |   2 +-
 lib/Makefile                                  |   4 +-
 lib/libkvm/Makefile                           |  10 +-
 .../arch/powerpc64/libpthread_md.c            |  83 -------
 lib/msun/Makefile                             |   7 +-
 secure/lib/libcrypto/Makefile                 |   2 +-
 secure/lib/libcrypto/opensslconf-powerpc.h    |  13 +-
 secure/lib/libcrypto/opensslconf-powerpc64.h  | 217 ------------------
 usr.sbin/kldxref/Makefile                     |   2 +-
 10 files changed, 32 insertions(+), 312 deletions(-)
 delete mode 100644 lib/libthread_db/arch/powerpc64/libpthread_md.c
 delete mode 100644 secure/lib/libcrypto/opensslconf-powerpc64.h

diff --git a/Makefile.inc1 b/Makefile.inc1
index 53b43a91e85..ef732de99e2 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -1133,8 +1133,8 @@ _prereq_libs= gnu/lib/libssp/libssp_nonshared gnu/lib/libgcc
 _startup_libs=	gnu/lib/csu
 .if exists(${.CURDIR}/lib/csu/${MACHINE_ARCH}-elf)
 _startup_libs+=	lib/csu/${MACHINE_ARCH}-elf
-.elif exists(${.CURDIR}/lib/csu/${MACHINE_CPUARCH}-elf)
-_startup_libs+=	lib/csu/${MACHINE_CPUARCH}-elf
+.elif exists(${.CURDIR}/lib/csu/${MACHINE_ARCH})
+_startup_libs+=	lib/csu/${MACHINE_ARCH}
 .else
 _startup_libs+=	lib/csu/${MACHINE_CPUARCH}
 .endif
diff --git a/gnu/lib/libgomp/Makefile b/gnu/lib/libgomp/Makefile
index da28f8999fd..1489a30e87c 100644
--- a/gnu/lib/libgomp/Makefile
+++ b/gnu/lib/libgomp/Makefile
@@ -24,7 +24,7 @@ VERSION_MAP=	${SRCDIR}/libgomp.map
 
 # Target-specific OpenMP configuration
 .if ${MACHINE_CPUARCH} == arm || ${MACHINE_CPUARCH} == i386 || \
-    ${MACHINE_CPUARCH} == powerpc || \
+    ${MACHINE_ARCH} == powerpc || \
     (${MACHINE_CPUARCH} == mips && \
 	(!defined(TARGET_ABI) || ${TARGET_ABI} != "n64"))
 OMP_LOCK_ALIGN	=	4
diff --git a/lib/Makefile b/lib/Makefile
index 53248e31659..75de0925f42 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -114,8 +114,8 @@ SUBDIR=	${SUBDIR_ORDERED} \
 
 .if exists(${.CURDIR}/csu/${MACHINE_ARCH}-elf)
 _csu=csu/${MACHINE_ARCH}-elf
-.elif exists(${.CURDIR}/csu/${MACHINE_CPUARCH}-elf)
-_csu=csu/${MACHINE_CPUARCH}-elf
+.elif exists(${.CURDIR}/csu/${MACHINE_ARCH})
+_csu=csu/${MACHINE_ARCH}
 .elif exists(${.CURDIR}/csu/${MACHINE_CPUARCH}/Makefile)
 _csu=csu/${MACHINE_CPUARCH}
 .else
diff --git a/lib/libkvm/Makefile b/lib/libkvm/Makefile
index bf464eddc4f..ea5e09f312c 100644
--- a/lib/libkvm/Makefile
+++ b/lib/libkvm/Makefile
@@ -9,13 +9,19 @@ CFLAGS+=-DLIBC_SCCS -I${.CURDIR}
 CFLAGS+=-DSUN4V
 .endif
 
+.if exists(${.CURDIR}/kvm_${MACHINE_ARCH}.c)
+KVM_ARCH=${MACHINE_ARCH}
+.else
+KVM_ARCH=${MACHINE_CPUARCH}
+.endif
+
 WARNS?=	0
 
-SRCS=	kvm.c kvm_${MACHINE_CPUARCH}.c kvm_cptime.c kvm_file.c kvm_getloadavg.c \
+SRCS=	kvm.c kvm_${KVM_ARCH}.c kvm_cptime.c kvm_file.c kvm_getloadavg.c \
 	kvm_getswapinfo.c kvm_pcpu.c kvm_proc.c kvm_vnet.c
 .if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386" || \
     ${MACHINE_CPUARCH} == "arm"
-SRCS+=	kvm_minidump_${MACHINE_CPUARCH}.c
+SRCS+=	kvm_minidump_${KVM_ARCH}.c
 .endif
 INCS=	kvm.h
 
diff --git a/lib/libthread_db/arch/powerpc64/libpthread_md.c b/lib/libthread_db/arch/powerpc64/libpthread_md.c
deleted file mode 100644
index fbe77f4dcbe..00000000000
--- a/lib/libthread_db/arch/powerpc64/libpthread_md.c
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2006 Marcel Moolenaar
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
- */
-
-#include 
-__FBSDID("$FreeBSD$");
-
-#include 
-#include 
-#include 
-
-#include "libpthread_db.h"
-
-void
-pt_reg_to_ucontext(const struct reg *r, ucontext_t *uc)
-{
-	mcontext_t *mc = &uc->uc_mcontext;
-
-	memcpy(mc->mc_frame, r, MIN(sizeof(mc->mc_frame), sizeof(*r)));
-}
-
-void
-pt_ucontext_to_reg(const ucontext_t *uc, struct reg *r)
-{
-	const mcontext_t *mc = &uc->uc_mcontext;
-
-	memcpy(r, mc->mc_frame, MIN(sizeof(mc->mc_frame), sizeof(*r)));
-}
-
-void
-pt_fpreg_to_ucontext(const struct fpreg *r, ucontext_t *uc)
-{
-	mcontext_t *mc = &uc->uc_mcontext;
-
-	memcpy(mc->mc_fpreg, r, MIN(sizeof(mc->mc_fpreg), sizeof(*r)));
-	mc->mc_flags |= _MC_FP_VALID;
-}
-
-void
-pt_ucontext_to_fpreg(const ucontext_t *uc, struct fpreg *r)
-{
-	const mcontext_t *mc = &uc->uc_mcontext;
-
-	if (mc->mc_flags & _MC_FP_VALID)
-		memcpy(r, mc->mc_fpreg, MIN(sizeof(mc->mc_fpreg), sizeof(*r)));
-	else
-		memset(r, 0, sizeof(*r));
-}
-
-void
-pt_md_init(void)
-{
-}
-
-int
-pt_reg_sstep(struct reg *reg __unused, int step __unused)
-{
-
-	/* XXX */
-	return (0);
-}
diff --git a/lib/msun/Makefile b/lib/msun/Makefile
index 38ce172cb3d..5a31f5cd918 100644
--- a/lib/msun/Makefile
+++ b/lib/msun/Makefile
@@ -75,8 +75,13 @@ COMMON_SRCS= b_exp.c b_log.c b_tgamma.c \
 
 # Location of fpmath.h and _fpmath.h
 LIBCDIR=	${.CURDIR}/../libc
+.if exists(${LIBCDIR}/${MACHINE_ARCH})
+LIBC_ARCH=${MACHINE_ARCH}
+.else
+LIBC_ARCH=${MACHINE_CPUARCH}
+.endif
 CFLAGS+=	-I${.CURDIR}/src -I${LIBCDIR}/include \
-	-I${LIBCDIR}/${MACHINE_CPUARCH}
+	-I${LIBCDIR}/${LIBC_ARCH}
 SYM_MAPS+=	${.CURDIR}/Symbol.map
 
 VERSION_DEF=	${LIBCDIR}/Versions.def
diff --git a/secure/lib/libcrypto/Makefile b/secure/lib/libcrypto/Makefile
index af48d7061f4..0c019055d68 100644
--- a/secure/lib/libcrypto/Makefile
+++ b/secure/lib/libcrypto/Makefile
@@ -351,7 +351,7 @@ buildinf.h: ${.CURDIR}/Makefile
 	( echo "#ifndef MK1MF_BUILD"; \
 	echo "  /* auto-generated by crypto/Makefile.ssl for crypto/cversion.c */"; \
 	echo "  #define CFLAGS \"$(CC)\""; \
-	echo "  #define PLATFORM \"FreeBSD-${MACHINE_CPUARCH}\""; \
+	echo "  #define PLATFORM \"FreeBSD-${MACHINE_ARCH}\""; \
 	echo "#endif" ) > ${.TARGET}
 
 opensslconf.h: opensslconf-${MACHINE_CPUARCH}.h
diff --git a/secure/lib/libcrypto/opensslconf-powerpc.h b/secure/lib/libcrypto/opensslconf-powerpc.h
index d6debd72fb7..70800fed088 100644
--- a/secure/lib/libcrypto/opensslconf-powerpc.h
+++ b/secure/lib/libcrypto/opensslconf-powerpc.h
@@ -110,13 +110,17 @@
 /* If this is set to 'unsigned int' on a DEC Alpha, this gives about a
  * %20 speed up (longs are 8 bytes, int's are 4). */
 #ifndef DES_LONG
-#define DES_LONG unsigned long
+#define DES_LONG unsigned int
 #endif
 #endif
 
 #if defined(HEADER_BN_H) && !defined(CONFIG_HEADER_BN_H)
 #define CONFIG_HEADER_BN_H
+#ifdef __powerpc64__
+#undef BN_LLONG
+#else
 #define BN_LLONG
+#endif
 
 /* Should we define BN_DIV2W here? */
 
@@ -124,9 +128,14 @@
 /* The prime number generation stuff may not work when
  * EIGHT_BIT but I don't care since I've only used this mode
  * for debuging the bignum libraries */
+#ifdef __powerpc64__
+#define SIXTY_FOUR_BIT_LONG
+#undef THIRTY_TWO_BIT
+#else
 #undef SIXTY_FOUR_BIT_LONG
-#undef SIXTY_FOUR_BIT
 #define THIRTY_TWO_BIT
+#endif
+#undef SIXTY_FOUR_BIT
 #undef SIXTEEN_BIT
 #undef EIGHT_BIT
 #endif
diff --git a/secure/lib/libcrypto/opensslconf-powerpc64.h b/secure/lib/libcrypto/opensslconf-powerpc64.h
deleted file mode 100644
index 795c6a97cd8..00000000000
--- a/secure/lib/libcrypto/opensslconf-powerpc64.h
+++ /dev/null
@@ -1,217 +0,0 @@
-/* $FreeBSD$ */
-/* opensslconf.h */
-/* WARNING: Generated automatically from opensslconf.h.in by Configure. */
-
-/* OpenSSL was configured with the following options: */
-#ifndef OPENSSL_DOING_MAKEDEPEND
-
-/* Disabled by default in OpenSSL 0.9.8. */
-#ifndef OPENSSL_NO_CAMELLIA
-# define OPENSSL_NO_CAMELLIA
-#endif
-/* Disabled by default in OpenSSL 0.9.8. */
-#ifndef OPENSSL_NO_CMS
-# define OPENSSL_NO_CMS
-#endif
-/* Disabled by default in OpenSSL 0.9.8. */
-#ifndef OPENSSL_NO_SEED
-# define OPENSSL_NO_SEED
-#endif
-/* jpake is marked experimental in OpenSSL 0.9.8. */
-#ifndef OPENSSL_NO_JPAKE
-# define OPENSSL_NO_JPAKE
-#endif
-/* libgmp is not in the FreeBSD base system. */
-#ifndef OPENSSL_NO_GMP
-# define OPENSSL_NO_GMP
-#endif
-/* The Kerberos 5 support is MIT-specific. */
-#ifndef OPENSSL_NO_KRB5
-# define OPENSSL_NO_KRB5
-#endif
-
-#endif /* OPENSSL_DOING_MAKEDEPEND */
-#ifndef OPENSSL_THREADS
-# define OPENSSL_THREADS
-#endif
-#ifndef OPENSSL_NO_STATIC_ENGINE
-# define OPENSSL_NO_STATIC_ENGINE
-#endif
-
-/* The OPENSSL_NO_* macros are also defined as NO_* if the application
-   asks for it.  This is a transient feature that is provided for those
-   who haven't had the time to do the appropriate changes in their
-   applications.  */
-#ifdef OPENSSL_ALGORITHM_DEFINES
-# if defined(OPENSSL_NO_GMP) && !defined(NO_GMP)
-#  define NO_GMP
-# endif
-# if defined(OPENSSL_NO_KRB5) && !defined(NO_KRB5)
-#  define NO_KRB5
-# endif
-# endif
-#ifdef OPENSSL_OTHER_DEFINES
-# ifndef NO_ASM
-#  define NO_ASM
-# endif
-#endif
-
-/* crypto/opensslconf.h.in */
-
-/* Generate 80386 code? */
-#undef I386_ONLY
-
-#if !(defined(VMS) || defined(__VMS)) /* VMS uses logical names instead */
-#if defined(HEADER_CRYPTLIB_H) && !defined(OPENSSLDIR)
-#define ENGINESDIR "/usr/lib/engines"
-#define OPENSSLDIR "/etc/ssl"
-#endif
-#endif
-
-#undef OPENSSL_UNISTD
-#define OPENSSL_UNISTD 
-
-#undef OPENSSL_EXPORT_VAR_AS_FUNCTION
-
-#if defined(HEADER_IDEA_H) && !defined(IDEA_INT)
-#define IDEA_INT unsigned int
-#endif
-
-#if defined(HEADER_MD2_H) && !defined(MD2_INT)
-#define MD2_INT unsigned int
-#endif
-
-#if defined(HEADER_RC2_H) && !defined(RC2_INT)
-/* I need to put in a mod for the alpha - eay */
-#define RC2_INT unsigned int
-#endif
-
-#if defined(HEADER_RC4_H)
-#if !defined(RC4_INT)
-/* using int types make the structure larger but make the code faster
- * on most boxes I have tested - up to %20 faster. */
-/*
- * I don't know what does "most" mean, but declaring "int" is a must on:
- * - Intel P6 because partial register stalls are very expensive;
- * - elder Alpha because it lacks byte load/store instructions;
- */
-#define RC4_INT unsigned int
-#endif
-#if !defined(RC4_CHUNK)
-/*
- * This enables code handling data aligned at natural CPU word
- * boundary. See crypto/rc4/rc4_enc.c for further details.
- */
-#undef RC4_CHUNK
-#endif
-#endif
-
-#if (defined(HEADER_NEW_DES_H) || defined(HEADER_DES_H)) && !defined(DES_LONG)
-/* If this is set to 'unsigned int' on a DEC Alpha, this gives about a
- * %20 speed up (longs are 8 bytes, int's are 4). */
-#ifndef DES_LONG
-#define DES_LONG unsigned int
-#endif
-#endif
-
-#if defined(HEADER_BN_H) && !defined(CONFIG_HEADER_BN_H)
-#define CONFIG_HEADER_BN_H
-#undef BN_LLONG
-
-/* Should we define BN_DIV2W here? */
-
-/* Only one for the following should be defined */
-/* The prime number generation stuff may not work when
- * EIGHT_BIT but I don't care since I've only used this mode
- * for debuging the bignum libraries */
-#define SIXTY_FOUR_BIT_LONG
-#undef SIXTY_FOUR_BIT
-#undef THIRTY_TWO_BIT
-#undef SIXTEEN_BIT
-#undef EIGHT_BIT
-#endif
-
-#if defined(HEADER_RC4_LOCL_H) && !defined(CONFIG_HEADER_RC4_LOCL_H)
-#define CONFIG_HEADER_RC4_LOCL_H
-/* if this is defined data[i] is used instead of *data, this is a %20
- * speedup on x86 */
-#define RC4_INDEX
-#endif
-
-#if defined(HEADER_BF_LOCL_H) && !defined(CONFIG_HEADER_BF_LOCL_H)
-#define CONFIG_HEADER_BF_LOCL_H
-#undef BF_PTR
-#endif /* HEADER_BF_LOCL_H */
-
-#if defined(HEADER_DES_LOCL_H) && !defined(CONFIG_HEADER_DES_LOCL_H)
-#define CONFIG_HEADER_DES_LOCL_H
-#ifndef DES_DEFAULT_OPTIONS
-/* the following is tweaked from a config script, that is why it is a
- * protected undef/define */
-#ifndef DES_PTR
-#define DES_PTR
-#endif
-
-/* This helps C compiler generate the correct code for multiple functional
- * units.  It reduces register dependancies at the expense of 2 more
- * registers */
-#ifndef DES_RISC1
-#define DES_RISC1
-#endif
-
-#ifndef DES_RISC2
-#undef DES_RISC2
-#endif
-
-#if defined(DES_RISC1) && defined(DES_RISC2)
-YOU SHOULD NOT HAVE BOTH DES_RISC1 AND DES_RISC2 DEFINED!!!!!
-#endif
-
-/* Unroll the inner loop, this sometimes helps, sometimes hinders.
- * Very mucy CPU dependant */
-#ifndef DES_UNROLL
-#define DES_UNROLL
-#endif
-
-/* These default values were supplied by
- * Peter Gutman 
- * They are only used if nothing else has been defined */
-#if !defined(DES_PTR) && !defined(DES_RISC1) && !defined(DES_RISC2) && !defined(DES_UNROLL)
-/* Special defines which change the way the code is built depending on the
-   CPU and OS.  For SGI machines you can use _MIPS_SZLONG (32 or 64) to find
-   even newer MIPS CPU's, but at the moment one size fits all for
-   optimization options.  Older Sparc's work better with only UNROLL, but
-   there's no way to tell at compile time what it is you're running on */
- 
-#if defined( sun )		/* Newer Sparc's */
-#  define DES_PTR
-#  define DES_RISC1
-#  define DES_UNROLL
-#elif defined( __ultrix )	/* Older MIPS */
-#  define DES_PTR
-#  define DES_RISC2
-#  define DES_UNROLL
-#elif defined( __osf1__ )	/* Alpha */
-#  define DES_PTR
-#  define DES_RISC2
-#elif defined ( _AIX )		/* RS6000 */
-  /* Unknown */
-#elif defined( __hpux )		/* HP-PA */
-  /* Unknown */
-#elif defined( __aux )		/* 68K */
-  /* Unknown */
-#elif defined( __dgux )		/* 88K (but P6 in latest boxes) */
-#  define DES_UNROLL
-#elif defined( __sgi )		/* Newer MIPS */
-#  define DES_PTR
-#  define DES_RISC2
-#  define DES_UNROLL
-#elif defined( i386 )		/* x86 boxes, should be gcc */
-#  define DES_PTR
-#  define DES_RISC1
-#  define DES_UNROLL
-#endif /* Systems-specific speed defines */
-#endif
-
-#endif /* DES_DEFAULT_OPTIONS */
-#endif /* HEADER_DES_LOCL_H */
diff --git a/usr.sbin/kldxref/Makefile b/usr.sbin/kldxref/Makefile
index c877a8a57ff..767cc23cea2 100644
--- a/usr.sbin/kldxref/Makefile
+++ b/usr.sbin/kldxref/Makefile
@@ -7,7 +7,7 @@ SRCS=	kldxref.c ef.c ef_obj.c
 WARNS?=	2
 CFLAGS+=-fno-strict-aliasing
 
-.if exists(ef_${MACHINE_CPUARCH}.c)
+.if exists(ef_${MACHINE_CPUARCH}.c) && ${MACHINE_ARCH} != "powerpc64"
 SRCS+=	ef_${MACHINE_CPUARCH}.c
 .else
 SRCS+=	ef_nop.c

From 4e5833219ab708ca2c6b6e626ee2079f2edcf9a3 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Sat, 28 Aug 2010 15:04:53 +0000
Subject: [PATCH 0321/1624] Fix breakage introduced in r211725 and improve
 functionality of truss on 64-bit powerpc by adding 32-bit compatibility
 features.

---
 usr.bin/truss/Makefile         | 20 +++++++++++++++++++-
 usr.bin/truss/extern.h         |  2 ++
 usr.bin/truss/main.c           |  3 +++
 usr.bin/truss/powerpc-fbsd.c   |  5 +++++
 usr.bin/truss/powerpc64-fbsd.c |  4 ++--
 5 files changed, 31 insertions(+), 3 deletions(-)

diff --git a/usr.bin/truss/Makefile b/usr.bin/truss/Makefile
index ca0ce9234a2..f80ac0367ea 100644
--- a/usr.bin/truss/Makefile
+++ b/usr.bin/truss/Makefile
@@ -2,7 +2,13 @@
 
 NO_WERROR=
 PROG=	truss
-SRCS=	main.c setup.c syscalls.c syscalls.h ioctl.c ${MACHINE_CPUARCH}-fbsd.c
+SRCS=	main.c setup.c syscalls.c syscalls.h ioctl.c
+
+.if exists(${.CURDIR}/${MACHINE_ARCH}-fbsd.c)
+SRCS+= ${MACHINE_ARCH}-fbsd.c
+.else
+SRCS+= ${MACHINE_CPUARCH}-fbsd.c
+.endif
 
 CFLAGS+= -I${.CURDIR} -I.
 CLEANFILES= syscalls.master syscalls.h ioctl.c
@@ -53,4 +59,16 @@ freebsd32_syscalls.h:	fbsd32-syscalls.master
 		${.CURDIR}/fbsd32.conf
 .endif
 
+.if ${MACHINE_ARCH} == "powerpc64"
+SRCS+=	powerpc-fbsd.c freebsd32_syscalls.h
+CLEANFILES+=fbsd32-syscalls.master freebsd32_syscalls.h
+
+fbsd32-syscalls.master: ${.CURDIR}/../../sys/compat/freebsd32/syscalls.master
+	cat ${.ALLSRC} > ${.TARGET}
+
+freebsd32_syscalls.h:	fbsd32-syscalls.master
+	/bin/sh ${.CURDIR}/../../sys/kern/makesyscalls.sh ${.ALLSRC} \
+		${.CURDIR}/fbsd32.conf
+.endif
+
 .include 
diff --git a/usr.bin/truss/extern.h b/usr.bin/truss/extern.h
index 322e2913169..e3ffc4f566a 100644
--- a/usr.bin/truss/extern.h
+++ b/usr.bin/truss/extern.h
@@ -58,6 +58,8 @@ extern long ia64_syscall_exit(struct trussinfo *, int);
 #ifdef __powerpc__
 extern void powerpc_syscall_entry(struct trussinfo *, int);
 extern long powerpc_syscall_exit(struct trussinfo *, int);
+extern void powerpc64_syscall_entry(struct trussinfo *, int);
+extern long powerpc64_syscall_exit(struct trussinfo *, int);
 #endif
 #ifdef __sparc64__
 extern void sparc64_syscall_entry(struct trussinfo *, int);
diff --git a/usr.bin/truss/main.c b/usr.bin/truss/main.c
index 5c7da1d4a6b..b9dcfe4e7fe 100644
--- a/usr.bin/truss/main.c
+++ b/usr.bin/truss/main.c
@@ -97,6 +97,9 @@ struct ex_types {
 #ifdef __powerpc__
 	{ "FreeBSD ELF", powerpc_syscall_entry, powerpc_syscall_exit },
 	{ "FreeBSD ELF32", powerpc_syscall_entry, powerpc_syscall_exit },
+#ifdef __powerpc64__
+	{ "FreeBSD ELF64", powerpc64_syscall_entry, powerpc64_syscall_exit },
+#endif
 #endif
 #ifdef __sparc64__
 	{ "FreeBSD ELF64", sparc64_syscall_entry, sparc64_syscall_exit },
diff --git a/usr.bin/truss/powerpc-fbsd.c b/usr.bin/truss/powerpc-fbsd.c
index ab5b9a48982..d2c1db81026 100644
--- a/usr.bin/truss/powerpc-fbsd.c
+++ b/usr.bin/truss/powerpc-fbsd.c
@@ -63,7 +63,12 @@ static const char rcsid[] =
 
 static int cpid = -1;
 
+#ifdef __powerpc64__	/* 32-bit compatibility */
+#include "freebsd32_syscalls.h"
+#define  syscallnames freebsd32_syscallnames
+#else			/* native 32-bit */
 #include "syscalls.h"
+#endif
 
 static int nsyscalls = sizeof(syscallnames) / sizeof(syscallnames[0]);
 
diff --git a/usr.bin/truss/powerpc64-fbsd.c b/usr.bin/truss/powerpc64-fbsd.c
index a929d0fa9c7..ffa34f256e2 100644
--- a/usr.bin/truss/powerpc64-fbsd.c
+++ b/usr.bin/truss/powerpc64-fbsd.c
@@ -109,7 +109,7 @@ clear_fsc(void) {
  */
 
 void
-powerpc_syscall_entry(struct trussinfo *trussinfo, int nargs) {
+powerpc64_syscall_entry(struct trussinfo *trussinfo, int nargs) {
   char buf[32];
   struct reg regs;
   void *args;
@@ -254,7 +254,7 @@ powerpc_syscall_entry(struct trussinfo *trussinfo, int nargs) {
  */
 
 long
-powerpc_syscall_exit(struct trussinfo *trussinfo, int syscall_num __unused)
+powerpc64_syscall_exit(struct trussinfo *trussinfo, int syscall_num __unused)
 {
   struct reg regs;
   long retval;

From e7f8dd75b3c11bd606a3a4fa82a3bd7834f65421 Mon Sep 17 00:00:00 2001
From: Rebecca Cran 
Date: Sat, 28 Aug 2010 16:32:01 +0000
Subject: [PATCH 0322/1624] Fix incorrect usage of 'assure' and 'insure'.

Approved by: rrs (mentor)
---
 bin/test/test.1                      | 2 +-
 lib/libc/net/ethers.3                | 2 +-
 lib/libc/net/eui64.3                 | 2 +-
 lib/libc/net/sctp_send.3             | 4 ++--
 lib/libc/net/sctp_sendmsg.3          | 4 ++--
 lib/libc/stdio/printf.3              | 2 +-
 lib/libc/stdlib/malloc.3             | 4 ++--
 lib/libc/sys/semop.2                 | 2 +-
 lib/libipx/ipx.3                     | 2 +-
 libexec/ypxfr/ypxfr.8                | 2 +-
 sbin/ipfw/ipfw.8                     | 2 +-
 secure/lib/libcrypto/man/BIO_s_bio.3 | 2 +-
 share/man/man4/ata.4                 | 2 +-
 share/man/man4/bpf.4                 | 2 +-
 share/man/man4/netgraph.4            | 2 +-
 share/man/man4/ng_hci.4              | 2 +-
 share/man/man4/re.4                  | 2 +-
 share/man/man9/devstat.9             | 2 +-
 share/man/man9/ieee80211_node.9      | 2 +-
 usr.sbin/IPXrouted/IPXrouted.8       | 2 +-
 usr.sbin/ypbind/ypbind.8             | 2 +-
 21 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/bin/test/test.1 b/bin/test/test.1
index 6b0ca789cd5..726542da4f1 100644
--- a/bin/test/test.1
+++ b/bin/test/test.1
@@ -302,7 +302,7 @@ manual page.
 The
 .Nm
 grammar is inherently ambiguous.
-In order to assure a degree of consistency,
+In order to ensure a degree of consistency,
 the cases described in the
 .St -p1003.2 ,
 section D11.2/4.62.4, standard
diff --git a/lib/libc/net/ethers.3 b/lib/libc/net/ethers.3
index 3148b6cb009..c8aa51a1f48 100644
--- a/lib/libc/net/ethers.3
+++ b/lib/libc/net/ethers.3
@@ -189,7 +189,7 @@ unable to find a match in the
 .Pa /etc/ethers
 database.
 .Sh NOTES
-The user must insure that the hostname strings passed to the
+The user must ensure that the hostname strings passed to the
 .Fn ether_line ,
 .Fn ether_ntohost
 and
diff --git a/lib/libc/net/eui64.3 b/lib/libc/net/eui64.3
index 3000c74e6d0..7cc5718ca96 100644
--- a/lib/libc/net/eui64.3
+++ b/lib/libc/net/eui64.3
@@ -189,7 +189,7 @@ unable to find a match in the
 .Pa /etc/eui64
 database.
 .Sh NOTES
-The user must insure that the hostname strings passed to the
+The user must ensure that the hostname strings passed to the
 .\" .Fn eui64_line ,
 .Fn eui64_ntohost
 and
diff --git a/lib/libc/net/sctp_send.3 b/lib/libc/net/sctp_send.3
index 9acb616be5b..8d860dfb318 100644
--- a/lib/libc/net/sctp_send.3
+++ b/lib/libc/net/sctp_send.3
@@ -191,7 +191,7 @@ If that many milliseconds elapse
 and the peer has not acknowledged the data, the data will be
 skipped and no longer transmitted.
 Note that this policy does
-not even assure that the data will ever be sent.
+not even ensure that the data will ever be sent.
 In times of a congestion
 with large amounts of data being queued, the 
 .Fa sinfo->sinfo_timetolive
@@ -218,7 +218,7 @@ policy transforms the
 .Fa sinfo->sinfo_timetolive 
 into a number of retransmissions to allow.
 This policy
-always assures that at a minimum one send attempt is
+always ensures that at a minimum one send attempt is
 made of the data.
 After which no more than 
 .Fa sinfo->sinfo_timetolive
diff --git a/lib/libc/net/sctp_sendmsg.3 b/lib/libc/net/sctp_sendmsg.3
index ddd88b43c9f..10155580195 100644
--- a/lib/libc/net/sctp_sendmsg.3
+++ b/lib/libc/net/sctp_sendmsg.3
@@ -203,7 +203,7 @@ If that many milliseconds elapse
 and the peer has not acknowledged the data, the data will be
 skipped and no longer transmitted.
 Note that this policy does
-not even assure that the data will ever be sent.
+not even ensure that the data will ever be sent.
 In times of a congestion
 with large amounts of data being queued, the 
 .Fa timetolive
@@ -230,7 +230,7 @@ policy transforms the
 .Fa timetolive 
 into a number of retransmissions to allow.
 This policy
-always assures that at a minimum one send attempt is
+always ensures that at a minimum one send attempt is
 made of the data.
 After which no more than 
 .Fa timetolive
diff --git a/lib/libc/stdio/printf.3 b/lib/libc/stdio/printf.3
index 90a8ed8b02e..a0d2613da66 100644
--- a/lib/libc/stdio/printf.3
+++ b/lib/libc/stdio/printf.3
@@ -849,7 +849,7 @@ and
 .Fn vsprintf
 assume an infinitely long string,
 callers must be careful not to overflow the actual space;
-this is often hard to assure.
+this is often hard to ensure.
 For safety, programmers should use the
 .Fn snprintf
 interface instead.
diff --git a/lib/libc/stdlib/malloc.3 b/lib/libc/stdlib/malloc.3
index 2f21b6a5294..90781a10961 100644
--- a/lib/libc/stdlib/malloc.3
+++ b/lib/libc/stdlib/malloc.3
@@ -266,7 +266,7 @@ options are enabled, the allocator prefers anonymous mappings over the DSS,
 but allocation only fails if memory cannot be acquired via either method.
 If neither option is enabled, then the
 .Dq M
-option is implicitly enabled in order to assure that there is a method for
+option is implicitly enabled in order to ensure that there is a method for
 acquiring memory.
 .It N
 Double/halve the number of arenas.
@@ -437,7 +437,7 @@ rounded up to the nearest multiple of the chunk size.
 .Pp
 Allocations are packed tightly together, which can be an issue for
 multi-threaded applications.
-If you need to assure that allocations do not suffer from cacheline sharing,
+If you need to ensure that allocations do not suffer from cacheline sharing,
 round your allocation requests up to the nearest multiple of the cacheline
 size.
 .Sh DEBUGGING MALLOC PROBLEMS
diff --git a/lib/libc/sys/semop.2 b/lib/libc/sys/semop.2
index 86200ee967a..a08f65e8e8b 100644
--- a/lib/libc/sys/semop.2
+++ b/lib/libc/sys/semop.2
@@ -222,7 +222,7 @@ When a process
 exits, either voluntarily or involuntarily, the adjust on exit value
 for each semaphore is added to the semaphore's value.
 This can
-be used to insure that a resource is released if a process terminates
+be used to ensure that a resource is released if a process terminates
 unexpectedly.
 .Sh RETURN VALUES
 .Rv -std semop
diff --git a/lib/libipx/ipx.3 b/lib/libipx/ipx.3
index b38683dff8c..ab6de2dae8b 100644
--- a/lib/libipx/ipx.3
+++ b/lib/libipx/ipx.3
@@ -70,7 +70,7 @@ trailing
 .Ql H
 appended.
 .Pp
-An effort has been made to insure that
+An effort has been made to ensure that
 .Fn ipx_addr
 be compatible with most formats in common use.
 It will first separate an address into 1 to 3 fields using a single delimiter
diff --git a/libexec/ypxfr/ypxfr.8 b/libexec/ypxfr/ypxfr.8
index 8985bcb893f..281e31a5754 100644
--- a/libexec/ypxfr/ypxfr.8
+++ b/libexec/ypxfr/ypxfr.8
@@ -234,7 +234,7 @@ Specify the name of the host from which to copy the
 .Tn NIS
 maps.
 This option
-is used to insure that
+is used to ensure that
 .Nm
 only copies maps from the
 .Tn NIS
diff --git a/sbin/ipfw/ipfw.8 b/sbin/ipfw/ipfw.8
index b8e94f5acb0..a7efd6f9eac 100644
--- a/sbin/ipfw/ipfw.8
+++ b/sbin/ipfw/ipfw.8
@@ -2303,7 +2303,7 @@ Information necessary to route link-local packets to an
 interface is not available after processing by
 .Nm dummynet
 so those packets are dropped in the output path.
-Care should be taken to insure that link-local packets are not passed to
+Care should be taken to ensure that link-local packets are not passed to
 .Nm dummynet .
 .Sh CHECKLIST
 Here are some important points to consider when designing your
diff --git a/secure/lib/libcrypto/man/BIO_s_bio.3 b/secure/lib/libcrypto/man/BIO_s_bio.3
index 34345d112a8..956f3f6d13e 100644
--- a/secure/lib/libcrypto/man/BIO_s_bio.3
+++ b/secure/lib/libcrypto/man/BIO_s_bio.3
@@ -317,7 +317,7 @@ find out, how many bytes must be written into the buffer before the
 .IX Header "WARNING"
 As the data is buffered, \fISSL_operation()\fR may return with a \s-1ERROR_SSL_WANT_READ\s0
 condition, but there is still data in the write buffer. An application must
-not rely on the error value of \fISSL_operation()\fR but must assure that the
+not rely on the error value of \fISSL_operation()\fR but must ensure that the
 write buffer is always flushed first. Otherwise a deadlock may occur as
 the peer might be waiting for the data before being able to continue.
 .SH "SEE ALSO"
diff --git a/share/man/man4/ata.4 b/share/man/man4/ata.4
index ba67991dd2a..22de1a96d97 100644
--- a/share/man/man4/ata.4
+++ b/share/man/man4/ata.4
@@ -243,7 +243,7 @@ based systems
 Please remember that in order to use UDMA4/ATA66 and above modes you
 .Em must
 use 80 conductor cables.
-Please assure that ribbon cables are no longer than 45cm.
+Please ensure that ribbon cables are no longer than 45cm.
 In case of rounded ATA cables, the length depends on the
 quality of the cables.
 SATA cables can be up to 1m long according to the specification.
diff --git a/share/man/man4/bpf.4 b/share/man/man4/bpf.4
index 4051cb92ab4..85beb07cd68 100644
--- a/share/man/man4/bpf.4
+++ b/share/man/man4/bpf.4
@@ -683,7 +683,7 @@ padding between the header and the link level protocol.
 The purpose here is to guarantee proper alignment of the packet
 data structures, which is required on alignment sensitive
 architectures and improves performance on many other architectures.
-The packet filter insures that the
+The packet filter ensures that the
 .Vt bpf_xhdr ,
 .Vt bpf_hdr
 and the network layer
diff --git a/share/man/man4/netgraph.4 b/share/man/man4/netgraph.4
index db5f3ffb566..ebd0aa5fdac 100644
--- a/share/man/man4/netgraph.4
+++ b/share/man/man4/netgraph.4
@@ -892,7 +892,7 @@ by returning
 Each type should have an include file that defines the commands,
 argument format, and cookie for its own messages.
 The typecookie
-insures that the same header file was included by both sender and
+ensures that the same header file was included by both sender and
 receiver; when an incompatible change in the header file is made,
 the typecookie
 .Em must
diff --git a/share/man/man4/ng_hci.4 b/share/man/man4/ng_hci.4
index 28de180c242..5d8dab3e9a8 100644
--- a/share/man/man4/ng_hci.4
+++ b/share/man/man4/ng_hci.4
@@ -108,7 +108,7 @@ piconet.
 Both asynchronous and isochronous services are supported.
 Between a master and a slave only a single ACL link can exist.
 For most ACL packets,
-packet retransmission is applied to assure data integrity.
+packet retransmission is applied to ensure data integrity.
 .Sh HOST CONTROLLER INTERFACE (HCI)
 The HCI provides a command interface to the baseband controller and link
 manager, and access to hardware status and control registers.
diff --git a/share/man/man4/re.4 b/share/man/man4/re.4
index 7911014a7db..689a59106a2 100644
--- a/share/man/man4/re.4
+++ b/share/man/man4/re.4
@@ -248,7 +248,7 @@ be echoed back unmodified.
 If the echoed data is corrupt, the driver
 will print an error message on the console and abort the device attach.
 The
-user should insure the NIC is installed in a 32-bit PCI slot to
+user should ensure the NIC is installed in a 32-bit PCI slot to
 avoid this problem.
 .Pp
 The RealTek 8169, 8169S and 8110S chips appear to only be capable of
diff --git a/share/man/man9/devstat.9 b/share/man/man9/devstat.9
index 45e17b7bb0a..fa378560564 100644
--- a/share/man/man9/devstat.9
+++ b/share/man/man9/devstat.9
@@ -437,7 +437,7 @@ There may be a need for
 .Fn spl
 protection around some of the
 .Nm
-list manipulation code to insure, for example, that the list of devices
+list manipulation code to ensure, for example, that the list of devices
 is not changed while someone is fetching the
 .Va kern.devstat.all
 .Nm sysctl
diff --git a/share/man/man9/ieee80211_node.9 b/share/man/man9/ieee80211_node.9
index 9389411a2ff..180d8c4931a 100644
--- a/share/man/man9/ieee80211_node.9
+++ b/share/man/man9/ieee80211_node.9
@@ -101,7 +101,7 @@ Node table entries are reference counted.
 That is, there is a count of all long term references that determines
 when an entry may be reclaimed.
 References are held by every in-flight frame sent to a station to
-insure the entry is not reclaimed while the frame is queued or otherwise
+ensure the entry is not reclaimed while the frame is queued or otherwise
 held by a driver.
 Routines that lookup a table entry return a
 .Dq held reference
diff --git a/usr.sbin/IPXrouted/IPXrouted.8 b/usr.sbin/IPXrouted/IPXrouted.8
index 6c3bd542e8d..f5d0e13c988 100644
--- a/usr.sbin/IPXrouted/IPXrouted.8
+++ b/usr.sbin/IPXrouted/IPXrouted.8
@@ -198,7 +198,7 @@ also periodically checks the routing table entries.
 If an entry has not been updated for 3 minutes, the entry's metric
 is set to infinity and marked for deletion.
 Deletions are delayed
-an additional 60 seconds to insure the invalidation is propagated
+an additional 60 seconds to ensure the invalidation is propagated
 to other routers.
 .Pp
 Hosts acting as internetwork routers gratuitously supply their
diff --git a/usr.sbin/ypbind/ypbind.8 b/usr.sbin/ypbind/ypbind.8
index 4608814d864..34ce2175a9f 100644
--- a/usr.sbin/ypbind/ypbind.8
+++ b/usr.sbin/ypbind/ypbind.8
@@ -123,7 +123,7 @@ domain and group of NIS servers.
 Up to ten servers can be specified.
 There must not be any spaces between the commas in the domain/server
 specification.
-This option is used to insure that the system binds
+This option is used to ensure that the system binds
 only to one domain and only to one of the specified servers, which
 is useful for systems that are both NIS servers and NIS
 clients: it provides a way to restrict what machines the system can

From 74ffb9af155f0dfd90fd0da97382817f3a3d5df1 Mon Sep 17 00:00:00 2001
From: Alan Cox 
Date: Sat, 28 Aug 2010 16:57:07 +0000
Subject: [PATCH 0323/1624] Add the MAP_PREFAULT_READ option to mmap(2).

Reviewed by:	jhb, kib
---
 lib/libc/sys/mmap.2 | 15 ++++++++++++++-
 sys/sys/mman.h      |  1 +
 sys/sys/param.h     |  2 +-
 sys/vm/vm_mmap.c    |  5 +++--
 4 files changed, 19 insertions(+), 4 deletions(-)

diff --git a/lib/libc/sys/mmap.2 b/lib/libc/sys/mmap.2
index b633cb11942..0b1f35fedca 100644
--- a/lib/libc/sys/mmap.2
+++ b/lib/libc/sys/mmap.2
@@ -28,7 +28,7 @@
 .\"	@(#)mmap.2	8.4 (Berkeley) 5/11/95
 .\" $FreeBSD$
 .\"
-.Dd November 6, 2009
+.Dd August 28, 2010
 .Dt MMAP 2
 .Os
 .Sh NAME
@@ -211,6 +211,19 @@ implements a coherent file system buffer cache.
 However, it may be
 used to associate dirty VM pages with file system buffers and thus cause
 them to be flushed to physical media sooner rather than later.
+.It Dv MAP_PREFAULT_READ
+Immediately update the calling process's lowest-level virtual address
+translation structures, such as its page table, so that every memory
+resident page within the region is mapped for read access.
+Ordinarily these structures are updated lazily.
+The effect of this option is to eliminate any soft faults that would
+otherwise occur on the initial read accesses to the region.
+Although this option does not preclude
+.Fa prot
+from including
+.Dv PROT_WRITE ,
+it does not eliminate soft faults on the initial write accesses to the
+region.
 .It Dv MAP_PRIVATE
 Modifications are private.
 .It Dv MAP_SHARED
diff --git a/sys/sys/mman.h b/sys/sys/mman.h
index 12c013383de..379ed14b72b 100644
--- a/sys/sys/mman.h
+++ b/sys/sys/mman.h
@@ -90,6 +90,7 @@
  * Extended flags
  */
 #define	MAP_NOCORE	 0x00020000 /* dont include these pages in a coredump */
+#define	MAP_PREFAULT_READ 0x00040000 /* prefault mapping for reading */
 #endif /* __BSD_VISIBLE */
 
 #if __POSIX_VISIBLE >= 199309
diff --git a/sys/sys/param.h b/sys/sys/param.h
index 1c1ecec61e8..fec4b46336d 100644
--- a/sys/sys/param.h
+++ b/sys/sys/param.h
@@ -58,7 +58,7 @@
  *		in the range 5 to 9.
  */
 #undef __FreeBSD_version
-#define __FreeBSD_version 900018	/* Master, propagated to newvers */
+#define __FreeBSD_version 900019	/* Master, propagated to newvers */
 
 #ifndef LOCORE
 #include 
diff --git a/sys/vm/vm_mmap.c b/sys/vm/vm_mmap.c
index bd9f98fd588..2071cc7772d 100644
--- a/sys/vm/vm_mmap.c
+++ b/sys/vm/vm_mmap.c
@@ -1467,9 +1467,10 @@ vm_mmap(vm_map_t map, vm_offset_t *addr, vm_size_t size, vm_prot_t prot,
 		 */
 		if (handle == 0)
 			foff = 0;
-	} else {
+	} else if (flags & MAP_PREFAULT_READ)
+		docow = MAP_PREFAULT;
+	else
 		docow = MAP_PREFAULT_PARTIAL;
-	}
 
 	if ((flags & (MAP_ANON|MAP_SHARED)) == 0)
 		docow |= MAP_COPY_ON_WRITE;

From 42992a3a9cd2ee5e99e15f5cfa6d217f773513b4 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sat, 28 Aug 2010 17:38:40 +0000
Subject: [PATCH 0324/1624] Test the poll(2) return value.

MFC after:	2 weeks
---
 tools/regression/poll/pipepoll.c | 85 +++++++++++++++++++-------------
 1 file changed, 52 insertions(+), 33 deletions(-)

diff --git a/tools/regression/poll/pipepoll.c b/tools/regression/poll/pipepoll.c
index 1cdcbea2fd0..5ca064bf6bf 100644
--- a/tools/regression/poll/pipepoll.c
+++ b/tools/regression/poll/pipepoll.c
@@ -44,16 +44,34 @@ decode_events(int events)
 }
 
 static void
-report(int num, const char *state, int expected, int got)
+report_state(const char *state)
 {
-	if (expected == got)
-		printf("ok %-2d    ", num);
-	else
-		printf("not ok %-2d", num);
-	printf(" %s state %s: expected %s; got %s\n",
+
+	printf(" %s state %s: ",
 	    filetype == FT_PIPE ? "Pipe" :
 	    filetype == FT_SOCKETPAIR ? "Sock" : "FIFO",
-	    state, decode_events(expected), decode_events(got));
+	    state);
+}
+
+static void
+report(int num, const char *state, int expected, int got, int res,
+    int res_expected)
+{
+
+	if (res != res_expected) {
+		printf("not ok %-2d", num);
+		report_state(state);
+		printf("poll result %d expected %d. ",
+		    res, res_expected);
+	} else {
+		if (expected == got)
+			printf("ok %-2d    ", num);
+		else
+			printf("not ok %-2d", num);
+		report_state(state);
+	}
+	printf("expected %s; got %s\n", decode_events(expected),
+	    decode_events(got));
 	fflush(stdout);
 }
 
@@ -62,8 +80,9 @@ static pid_t ppid;
 static volatile sig_atomic_t state;
 
 static void
-catch(int sig)
+catch(int sig __unused)
 {
+
 	state++;
 }
 
@@ -71,7 +90,7 @@ static void
 child(int fd, int num)
 {
 	struct pollfd pfd;
-	int fd2;
+	int fd2, res;
 	char buf[256];
 
 	if (filetype == FT_FIFO) {
@@ -83,9 +102,9 @@ child(int fd, int num)
 	pfd.events = POLLIN;
 
 	if (filetype == FT_FIFO) {
-		if (poll(&pfd, 1, 0) < 0)
+		if ((res = poll(&pfd, 1, 0)) < 0)
 			err(1, "poll");
-		report(num++, "0", 0, pfd.revents);
+		report(num++, "0", 0, pfd.revents, res, 0);
 	}
 	kill(ppid, SIGUSR1);
 
@@ -101,30 +120,30 @@ child(int fd, int num)
 		state = 4;
 		goto state4;
 	}
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "1", 0, pfd.revents);
+	report(num++, "1", 0, pfd.revents, res, 0);
 	kill(ppid, SIGUSR1);
 
 	usleep(1);
 	while (state != 2)
 		;
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "2", POLLIN, pfd.revents);
+	report(num++, "2", POLLIN, pfd.revents, res, 1);
 	if (read(fd, buf, sizeof buf) != 1)
 		err(1, "read");
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "2a", 0, pfd.revents);
+	report(num++, "2a", 0, pfd.revents, res, 0);
 	kill(ppid, SIGUSR1);
 
 	usleep(1);
 	while (state != 3)
 		;
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "3", POLLHUP, pfd.revents);
+	report(num++, "3", POLLHUP, pfd.revents, res, 1);
 	kill(ppid, SIGUSR1);
 
 	/*
@@ -137,17 +156,17 @@ child(int fd, int num)
 	while (state != 4)
 		;
 state4:
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "4", 0, pfd.revents);
+	report(num++, "4", 0, pfd.revents, res, 0);
 	kill(ppid, SIGUSR1);
 
 	usleep(1);
 	while (state != 5)
 		;
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "5", POLLIN, pfd.revents);
+	report(num++, "5", POLLIN, pfd.revents, res, 1);
 	kill(ppid, SIGUSR1);
 
 	usleep(1);
@@ -163,14 +182,14 @@ state4:
 	 * is an example of a broken program that quits on POLLHUP only --
 	 * see its event-loop.c.
 	 */
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "6", POLLIN | POLLHUP, pfd.revents);
+	report(num++, "6", POLLIN | POLLHUP, pfd.revents, res, 1);
 	if (read(fd, buf, sizeof buf) != 1)
 		err(1, "read");
-	if (poll(&pfd, 1, 0) < 0)
+	if ((res = poll(&pfd, 1, 0)) < 0)
 		err(1, "poll");
-	report(num++, "6a", POLLHUP, pfd.revents);
+	report(num++, "6a", POLLHUP, pfd.revents, res, 1);
 	if (filetype == FT_FIFO) {
 		/*
 		 * Check that POLLHUP is sticky for a new reader and for
@@ -180,17 +199,17 @@ state4:
 		if (fd2 < 0)
 			err(1, "open for read");
 		pfd.fd = fd2;
-		if (poll(&pfd, 1, 0) < 0)
+		if ((res = poll(&pfd, 1, 0)) < 0)
 			err(1, "poll");
-		report(num++, "6b", POLLHUP, pfd.revents);
+		report(num++, "6b", POLLHUP, pfd.revents, res, 1);
 		pfd.fd = fd;
-		if (poll(&pfd, 1, 0) < 0)
+		if ((res = poll(&pfd, 1, 0)) < 0)
 			err(1, "poll");
-		report(num++, "6c", POLLHUP, pfd.revents);
+		report(num++, "6c", POLLHUP, pfd.revents, res, 1);
 		close(fd2);
-		if (poll(&pfd, 1, 0) < 0)
+		if ((res = poll(&pfd, 1, 0)) < 0)
 			err(1, "poll");
-		report(num++, "6d", POLLHUP, pfd.revents);
+		report(num++, "6d", POLLHUP, pfd.revents, res, 1);
 	}
 	close(fd);
 	kill(ppid, SIGUSR1);

From 6d8fedda2ce56c34d484708c7ba4ce5019c5a620 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sat, 28 Aug 2010 17:42:08 +0000
Subject: [PATCH 0325/1624] For some file types, select code registers two
 selfd structures. E.g., for socket, when specified POLLIN|POLLOUT in events,
 you would have one selfd registered for receiving socket buffer, and one for
 sending. Now, if both events are not ready to fire at the time of the initial
 scan, but are simultaneously ready after the sleep, pollrescan() would
 iterate over the pollfd struct twice. Since both times revents is not zero,
 returned value would be off by one.

Fix this by recalculating the return value in pollout().

PR:	kern/143029
MFC after:	2 weeks
---
 sys/kern/sys_generic.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/sys/kern/sys_generic.c b/sys/kern/sys_generic.c
index a1a7086dd03..1a2685cc1f0 100644
--- a/sys/kern/sys_generic.c
+++ b/sys/kern/sys_generic.c
@@ -76,7 +76,8 @@ static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
 
-static int	pollout(struct pollfd *, struct pollfd *, u_int);
+static int	pollout(struct thread *, struct pollfd *, struct pollfd *,
+		    u_int);
 static int	pollscan(struct thread *, struct pollfd *, u_int);
 static int	pollrescan(struct thread *);
 static int	selscan(struct thread *, fd_mask **, fd_mask **, int);
@@ -1207,7 +1208,7 @@ done:
 	if (error == EWOULDBLOCK)
 		error = 0;
 	if (error == 0) {
-		error = pollout(bits, uap->fds, nfds);
+		error = pollout(td, bits, uap->fds, nfds);
 		if (error)
 			goto out;
 	}
@@ -1262,22 +1263,27 @@ pollrescan(struct thread *td)
 
 
 static int
-pollout(fds, ufds, nfd)
+pollout(td, fds, ufds, nfd)
+	struct thread *td;
 	struct pollfd *fds;
 	struct pollfd *ufds;
 	u_int nfd;
 {
 	int error = 0;
 	u_int i = 0;
+	u_int n = 0;
 
 	for (i = 0; i < nfd; i++) {
 		error = copyout(&fds->revents, &ufds->revents,
 		    sizeof(ufds->revents));
 		if (error)
 			return (error);
+		if (fds->revents != 0)
+			n++;
 		fds++;
 		ufds++;
 	}
+	td->td_retval[0] = n;
 	return (0);
 }
 

From 20083c2eb1bd25b9fd56671c6c6463ae8b949727 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Sat, 28 Aug 2010 17:59:51 +0000
Subject: [PATCH 0326/1624] Fix the switching on/off of CMT using sysctl and
 socket option. Fix the switching on/off of PF and NR-SACKs using sysctl. Add
 minor improvement in handling malloc failures. Improve the address checks
 when sending.

MFC after: 4 weeks
---
 sys/netinet/sctp.h              |   4 +-
 sys/netinet/sctp_cc_functions.c |  48 +++++++++------
 sys/netinet/sctp_indata.c       |  27 +++++----
 sys/netinet/sctp_input.c        |  28 ++++-----
 sys/netinet/sctp_output.c       | 100 ++++++++++++++++++--------------
 sys/netinet/sctp_pcb.c          |   6 +-
 sys/netinet/sctp_pcb.h          |   1 +
 sys/netinet/sctp_peeloff.c      |   2 +
 sys/netinet/sctp_timer.c        |  16 +++--
 sys/netinet/sctp_usrreq.c       |  95 +++++++++---------------------
 sys/netinet/sctputil.c          |   6 +-
 sys/netinet6/sctp6_usrreq.c     |   7 ++-
 12 files changed, 165 insertions(+), 175 deletions(-)

diff --git a/sys/netinet/sctp.h b/sys/netinet/sctp.h
index ce5ac0a07cb..1335e82fb1a 100644
--- a/sys/netinet/sctp.h
+++ b/sys/netinet/sctp.h
@@ -155,10 +155,8 @@ struct sctp_paramhdr {
 /* CMT ON/OFF socket option */
 #define SCTP_CMT_ON_OFF                 0x00001200
 #define SCTP_CMT_USE_DAC                0x00001201
-/* EY - NR_SACK on/off socket option */
-#define SCTP_NR_SACK_ON_OFF                 0x00001300
 /* JRS - Pluggable Congestion Control Socket option */
-#define SCTP_PLUGGABLE_CC				0x00001202
+#define SCTP_PLUGGABLE_CC               0x00001202
 
 /* read only */
 #define SCTP_GET_SNDBUF_USE		0x00001101
diff --git a/sys/netinet/sctp_cc_functions.c b/sys/netinet/sctp_cc_functions.c
index 8beff191628..1cba25a2de3 100644
--- a/sys/netinet/sctp_cc_functions.c
+++ b/sys/netinet/sctp_cc_functions.c
@@ -71,7 +71,8 @@ sctp_cwnd_update_after_fr(struct sctp_tcb *stcb,
 	 * (net->fast_retran_loss_recovery == 0)))
 	 */
 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
-		if ((asoc->fast_retran_loss_recovery == 0) || (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 1)) {
+		if ((asoc->fast_retran_loss_recovery == 0) ||
+		    (asoc->sctp_cmt_on_off == 1)) {
 			/* out of a RFC2582 Fast recovery window? */
 			if (net->net_ack > 0) {
 				/*
@@ -232,11 +233,11 @@ sctp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 			 * 
 			 * Should we stop any running T3 timer here?
 			 */
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-			    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
+			if ((asoc->sctp_cmt_on_off == 1) &&
+			    (asoc->sctp_cmt_pf > 0) &&
 			    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
 				net->dest_state &= ~SCTP_ADDR_PF;
-				net->cwnd = net->mtu * SCTP_BASE_SYSCTL(sctp_cmt_pf);
+				net->cwnd = net->mtu * asoc->sctp_cmt_pf;
 				SCTPDBG(SCTP_DEBUG_INDATA1, "Destination %p moved from PF to reachable with cwnd %d.\n",
 				    net, net->cwnd);
 				/*
@@ -260,7 +261,9 @@ sctp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 		 */
 #endif
 
-		if (asoc->fast_retran_loss_recovery && will_exit == 0 && SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) {
+		if (asoc->fast_retran_loss_recovery &&
+		    (will_exit == 0) &&
+		    (asoc->sctp_cmt_on_off == 0)) {
 			/*
 			 * If we are in loss recovery we skip any cwnd
 			 * update
@@ -271,7 +274,8 @@ sctp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 		 * CMT: CUC algorithm. Update cwnd if pseudo-cumack has
 		 * moved.
 		 */
-		if (accum_moved || (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && net->new_pseudo_cumack)) {
+		if (accum_moved ||
+		    ((asoc->sctp_cmt_on_off == 1) && net->new_pseudo_cumack)) {
 			/* If the cumulative ack moved we can proceed */
 			if (net->cwnd <= net->ssthresh) {
 				/* We are in slow start */
@@ -697,7 +701,8 @@ sctp_hs_cwnd_update_after_fr(struct sctp_tcb *stcb,
 	 * (net->fast_retran_loss_recovery == 0)))
 	 */
 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
-		if ((asoc->fast_retran_loss_recovery == 0) || (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 1)) {
+		if ((asoc->fast_retran_loss_recovery == 0) ||
+		    (asoc->sctp_cmt_on_off == 1)) {
 			/* out of a RFC2582 Fast recovery window? */
 			if (net->net_ack > 0) {
 				/*
@@ -850,11 +855,11 @@ sctp_hs_cwnd_update_after_sack(struct sctp_tcb *stcb,
 			 * 
 			 * Should we stop any running T3 timer here?
 			 */
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-			    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
+			if ((asoc->sctp_cmt_on_off == 1) &&
+			    (asoc->sctp_cmt_pf > 0) &&
 			    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
 				net->dest_state &= ~SCTP_ADDR_PF;
-				net->cwnd = net->mtu * SCTP_BASE_SYSCTL(sctp_cmt_pf);
+				net->cwnd = net->mtu * asoc->sctp_cmt_pf;
 				SCTPDBG(SCTP_DEBUG_INDATA1, "Destination %p moved from PF to reachable with cwnd %d.\n",
 				    net, net->cwnd);
 				/*
@@ -878,7 +883,9 @@ sctp_hs_cwnd_update_after_sack(struct sctp_tcb *stcb,
 		 */
 #endif
 
-		if (asoc->fast_retran_loss_recovery && will_exit == 0 && SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) {
+		if (asoc->fast_retran_loss_recovery &&
+		    (will_exit == 0) &&
+		    (asoc->sctp_cmt_on_off == 0)) {
 			/*
 			 * If we are in loss recovery we skip any cwnd
 			 * update
@@ -889,7 +896,8 @@ sctp_hs_cwnd_update_after_sack(struct sctp_tcb *stcb,
 		 * CMT: CUC algorithm. Update cwnd if pseudo-cumack has
 		 * moved.
 		 */
-		if (accum_moved || (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && net->new_pseudo_cumack)) {
+		if (accum_moved ||
+		    ((asoc->sctp_cmt_on_off == 1) && net->new_pseudo_cumack)) {
 			/* If the cumulative ack moved we can proceed */
 			if (net->cwnd <= net->ssthresh) {
 				/* We are in slow start */
@@ -1333,11 +1341,11 @@ sctp_htcp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 			 * 
 			 * Should we stop any running T3 timer here?
 			 */
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-			    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
+			if ((asoc->sctp_cmt_on_off == 1) &&
+			    (asoc->sctp_cmt_pf > 0) &&
 			    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
 				net->dest_state &= ~SCTP_ADDR_PF;
-				net->cwnd = net->mtu * SCTP_BASE_SYSCTL(sctp_cmt_pf);
+				net->cwnd = net->mtu * asoc->sctp_cmt_pf;
 				SCTPDBG(SCTP_DEBUG_INDATA1, "Destination %p moved from PF to reachable with cwnd %d.\n",
 				    net, net->cwnd);
 				/*
@@ -1361,7 +1369,9 @@ sctp_htcp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 		 */
 #endif
 
-		if (asoc->fast_retran_loss_recovery && will_exit == 0 && SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) {
+		if (asoc->fast_retran_loss_recovery &&
+		    will_exit == 0 &&
+		    (asoc->sctp_cmt_on_off == 0)) {
 			/*
 			 * If we are in loss recovery we skip any cwnd
 			 * update
@@ -1372,7 +1382,8 @@ sctp_htcp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 		 * CMT: CUC algorithm. Update cwnd if pseudo-cumack has
 		 * moved.
 		 */
-		if (accum_moved || (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && net->new_pseudo_cumack)) {
+		if (accum_moved ||
+		    ((asoc->sctp_cmt_on_off == 1) && net->new_pseudo_cumack)) {
 			htcp_cong_avoid(stcb, net);
 			measure_achieved_throughput(stcb, net);
 		} else {
@@ -1412,7 +1423,8 @@ sctp_htcp_cwnd_update_after_fr(struct sctp_tcb *stcb,
 	 * (net->fast_retran_loss_recovery == 0)))
 	 */
 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
-		if ((asoc->fast_retran_loss_recovery == 0) || (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 1)) {
+		if ((asoc->fast_retran_loss_recovery == 0) ||
+		    (asoc->sctp_cmt_on_off == 1)) {
 			/* out of a RFC2582 Fast recovery window? */
 			if (net->net_ack > 0) {
 				/*
diff --git a/sys/netinet/sctp_indata.c b/sys/netinet/sctp_indata.c
index e429da8793e..12fba8bd60e 100644
--- a/sys/netinet/sctp_indata.c
+++ b/sys/netinet/sctp_indata.c
@@ -2475,7 +2475,7 @@ sctp_sack_check(struct sctp_tcb *stcb, int was_a_gap, int *abort_flag)
 		    (stcb->asoc.data_pkts_seen >= stcb->asoc.sack_freq)	/* hit limit of pkts */
 		    ) {
 
-			if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off)) &&
+			if ((stcb->asoc.sctp_cmt_on_off == 1) &&
 			    (SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) &&
 			    (stcb->asoc.send_sack == 0) &&
 			    (stcb->asoc.numduptsns == 0) &&
@@ -3265,7 +3265,8 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 	}
 
 	/* CMT DAC algo: finding out if SACK is a mixed SACK */
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
+	if ((asoc->sctp_cmt_on_off == 1) &&
+	    SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
 		TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
 			if (net->saw_newack)
 				num_dests_sacked++;
@@ -3381,7 +3382,8 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 			if (tp1->sent < SCTP_DATAGRAM_RESEND) {
 				tp1->sent++;
 			}
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
+			if ((asoc->sctp_cmt_on_off == 1) &&
+			    SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
 				/*
 				 * CMT DAC algorithm: If SACK flag is set to
 				 * 0, then lowest_newack test will not pass
@@ -3405,7 +3407,8 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 					tp1->sent++;
 				}
 			}
-		} else if ((tp1->rec.data.doing_fast_retransmit) && (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
+		} else if ((tp1->rec.data.doing_fast_retransmit) &&
+		    (asoc->sctp_cmt_on_off == 0)) {
 			/*
 			 * For those that have done a FR we must take
 			 * special consideration if we strike. I.e the
@@ -3445,7 +3448,8 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 						tp1->sent++;
 					}
 					strike_flag = 1;
-					if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
+					if ((asoc->sctp_cmt_on_off == 1) &&
+					    SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
 						/*
 						 * CMT DAC algorithm: If
 						 * SACK flag is set to 0,
@@ -3505,7 +3509,8 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 			if (tp1->sent < SCTP_DATAGRAM_RESEND) {
 				tp1->sent++;
 			}
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
+			if ((asoc->sctp_cmt_on_off == 1) &&
+			    SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
 				/*
 				 * CMT DAC algorithm: If SACK flag is set to
 				 * 0, then lowest_newack test will not pass
@@ -3584,7 +3589,7 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 				SCTP_STAT_INCR(sctps_sendmultfastretrans);
 			}
 			sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
+			if (asoc->sctp_cmt_on_off == 1) {
 				/*
 				 * CMT: Using RTX_SSTHRESH policy for CMT.
 				 * If CMT is being used, then pick dest with
@@ -3593,7 +3598,7 @@ sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
 				tp1->no_fr_allowed = 1;
 				alt = tp1->whoTo;
 				/* sa_ignore NO_NULL_CHK */
-				if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+				if (asoc->sctp_cmt_pf > 0) {
 					/*
 					 * JRS 5/18/07 - If CMT PF is on,
 					 * use the PF version of
@@ -4800,7 +4805,7 @@ sctp_handle_sack(struct mbuf *m, int offset_seg, int offset_dup,
 	/*******************************************/
 	/* cancel ALL T3-send timer if accum moved */
 	/*******************************************/
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
+	if (asoc->sctp_cmt_on_off == 1) {
 		TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
 			if (net->new_pseudo_cumack)
 				sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
@@ -5100,7 +5105,9 @@ done_with_it:
 	 * to be done. Setting this_sack_lowest_newack to the cum_ack will
 	 * automatically ensure that.
 	 */
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac) && (cmt_dac_flag == 0)) {
+	if ((asoc->sctp_cmt_on_off == 1) &&
+	    SCTP_BASE_SYSCTL(sctp_cmt_use_dac) &&
+	    (cmt_dac_flag == 0)) {
 		this_sack_lowest_newack = cum_ack;
 	}
 	if ((num_seg > 0) || (num_nr_seg > 0)) {
diff --git a/sys/netinet/sctp_input.c b/sys/netinet/sctp_input.c
index 8b2a9d598db..089c9b6834c 100644
--- a/sys/netinet/sctp_input.c
+++ b/sys/netinet/sctp_input.c
@@ -618,16 +618,16 @@ sctp_handle_heartbeat_ack(struct sctp_heartbeat_chunk *cp,
 	 * timer is running, for the destination, stop the timer because a
 	 * PF-heartbeat was received.
 	 */
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-	    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
-	    (net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF) {
+	if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+	    (stcb->asoc.sctp_cmt_pf > 0) &&
+	    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
 		if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
 			sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
 			    stcb, net,
 			    SCTP_FROM_SCTP_INPUT + SCTP_LOC_5);
 		}
 		net->dest_state &= ~SCTP_ADDR_PF;
-		net->cwnd = net->mtu * SCTP_BASE_SYSCTL(sctp_cmt_pf);
+		net->cwnd = net->mtu * stcb->asoc.sctp_cmt_pf;
 		SCTPDBG(SCTP_DEBUG_INPUT1, "Destination %p moved from PF to reachable with cwnd %d.\n",
 		    net, net->cwnd);
 	}
@@ -2723,6 +2723,7 @@ sctp_handle_cookie_echo(struct mbuf *m, int iphlen, int offset,
 			inp->sctp_mobility_features = (*inp_p)->sctp_mobility_features;
 			inp->sctp_socket = so;
 			inp->sctp_frag_point = (*inp_p)->sctp_frag_point;
+			inp->sctp_cmt_on_off = (*inp_p)->sctp_cmt_on_off;
 			inp->partial_delivery_point = (*inp_p)->partial_delivery_point;
 			inp->sctp_context = (*inp_p)->sctp_context;
 			inp->inp_starting_point_for_iterator = NULL;
@@ -3067,7 +3068,7 @@ process_chunk_drop(struct sctp_tcb *stcb, struct sctp_chunk_desc *desc,
     struct sctp_nets *net, uint8_t flg)
 {
 	switch (desc->chunk_type) {
-	case SCTP_DATA:
+		case SCTP_DATA:
 		/* find the tsn to resend (possibly */
 		{
 			uint32_t tsn;
@@ -4586,8 +4587,6 @@ process_control_chunks:
 			return (NULL);
 			break;
 		case SCTP_SELECTIVE_ACK:
-			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SACK\n");
-			SCTP_STAT_INCR(sctps_recvsacks);
 			{
 				struct sctp_sack_chunk *sack;
 				int abort_now = 0;
@@ -4597,6 +4596,8 @@ process_control_chunks:
 				int offset_seg, offset_dup;
 				int nonce_sum_flag;
 
+				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SACK\n");
+				SCTP_STAT_INCR(sctps_recvsacks);
 				if (stcb == NULL) {
 					SCTPDBG(SCTP_DEBUG_INDATA1, "No stcb when processing SACK chunk\n");
 					break;
@@ -4673,8 +4674,6 @@ process_control_chunks:
 			 * nr_sack chunk
 			 */
 		case SCTP_NR_SELECTIVE_ACK:
-			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_NR_SACK\n");
-			SCTP_STAT_INCR(sctps_recvsacks);
 			{
 				struct sctp_nr_sack_chunk *nr_sack;
 				int abort_now = 0;
@@ -4684,13 +4683,10 @@ process_control_chunks:
 				int offset_seg, offset_dup;
 				int nonce_sum_flag;
 
-				/*
-				 * EY nr_sacks have not been negotiated but
-				 * the peer end sent an nr_sack, silently
-				 * discard the chunk
-				 */
-				if (!(SCTP_BASE_SYSCTL(sctp_nr_sack_on_off) &&
-				    stcb->asoc.peer_supports_nr_sack)) {
+				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_NR_SACK\n");
+				SCTP_STAT_INCR(sctps_recvsacks);
+				if ((stcb->asoc.sctp_nr_sack_on_off == 0) ||
+				    (stcb->asoc.peer_supports_nr_sack == 0)) {
 					goto unknown_chunk;
 				}
 				if (stcb == NULL) {
diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index 7038067bcd1..aa771a65899 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -3686,7 +3686,8 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 						 * Stop any running T3
 						 * timers here?
 						 */
-						if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+						if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+						    (stcb->asoc.sctp_cmt_pf > 0)) {
 							net->dest_state &= ~SCTP_ADDR_PF;
 							SCTPDBG(SCTP_DEBUG_OUTPUT1, "Destination %p moved from PF to unreachable.\n",
 							    net);
@@ -4323,11 +4324,7 @@ sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int so_locked
 	if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
 		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
 	}
-	/*
-	 * EY  if the initiator supports nr_sacks, need to report that to
-	 * responder in INIT chunk
-	 */
-	if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off)) {
+	if (stcb->asoc.sctp_nr_sack_on_off == 1) {
 		pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
 	}
 	p_len = sizeof(*pr_supported) + num_ext;
@@ -5447,10 +5444,6 @@ do_a_abort:
 	pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
 	if (!SCTP_BASE_SYSCTL(sctp_auth_disable))
 		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
-	/*
-	 * EY  if the sysctl variable is set, tell the assoc. initiator that
-	 * we do nr_sack
-	 */
 	if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off))
 		pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
 	p_len = sizeof(*pr_supported) + num_ext;
@@ -7267,7 +7260,8 @@ sctp_fill_outqueue(struct sctp_tcb *stcb,
 		if (sp == NULL) {
 			break;
 		}
-		if ((sp->net != net) && (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
+		if ((sp->net != net) &&
+		    (asoc->sctp_cmt_on_off == 0)) {
 			/* none for this network */
 			if (locked) {
 				break;
@@ -7326,11 +7320,11 @@ sctp_fill_outqueue(struct sctp_tcb *stcb,
 		*quit_now = 1;
 
 	if (total_moved == 0) {
-		if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) &&
+		if ((stcb->asoc.sctp_cmt_on_off == 0) &&
 		    (net == stcb->asoc.primary_destination)) {
 			/* ran dry for primary network net */
 			SCTP_STAT_INCR(sctps_primary_randry);
-		} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
+		} else if (stcb->asoc.sctp_cmt_on_off == 1) {
 			/* ran dry with CMT on */
 			SCTP_STAT_INCR(sctps_cmt_randry);
 		}
@@ -7363,7 +7357,8 @@ sctp_move_to_an_alt(struct sctp_tcb *stcb,
 	 * destination using the PF algorithm for finding alternate
 	 * destinations.
 	 */
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+	if ((asoc->sctp_cmt_on_off == 1) &&
+	    (asoc->sctp_cmt_pf > 0)) {
 		a_net = sctp_find_alternate_net(stcb, net, 2);
 	} else {
 		a_net = sctp_find_alternate_net(stcb, net, 0);
@@ -7499,7 +7494,8 @@ sctp_med_chunk_output(struct sctp_inpcb *inp,
 				}
 				continue;
 			}
-			if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) && (net->ref_count < 2)) {
+			if ((asoc->sctp_cmt_on_off == 0) &&
+			    (net->ref_count < 2)) {
 				/* nothing can be in queue for this guy */
 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
 					sctp_log_cwnd(stcb, net, 2,
@@ -7534,7 +7530,7 @@ sctp_med_chunk_output(struct sctp_inpcb *inp,
 		*reason_code = 8;
 		return (0);
 	}
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
+	if (asoc->sctp_cmt_on_off == 1) {
 		/* get the last start point */
 		start_at = asoc->last_net_cmt_send_started;
 		if (start_at == NULL) {
@@ -7560,7 +7556,7 @@ again_one_more_time:
 			break;
 		}
 		tsns_sent = 0xa;
-		if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) && (net->ref_count < 2)) {
+		if ((asoc->sctp_cmt_on_off == 0) && (net->ref_count < 2)) {
 			/*
 			 * Ref-count of 1 so we cannot have data or control
 			 * queued to this address. Skip it (non-CMT).
@@ -8034,15 +8030,15 @@ again_one_more_time:
 			}
 		}
 		/* JRI: if dest is in PF state, do not send data to it */
-		if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-		    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
+		if ((asoc->sctp_cmt_on_off == 1) &&
+		    (asoc->sctp_cmt_pf > 0) &&
 		    (net->dest_state & SCTP_ADDR_PF)) {
 			goto no_data_fill;
 		}
 		if (net->flight_size >= net->cwnd) {
 			goto no_data_fill;
 		}
-		if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off)) &&
+		if ((asoc->sctp_cmt_on_off == 1) &&
 		    (net->flight_size > max_rwnd_per_dest)) {
 			goto no_data_fill;
 		}
@@ -8096,7 +8092,7 @@ again_one_more_time:
 					break;
 				}
 				nchk = TAILQ_NEXT(chk, sctp_next);
-				if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
+				if (asoc->sctp_cmt_on_off == 1) {
 					if (chk->whoTo != net) {
 						/*
 						 * For CMT, steal the data
@@ -8271,8 +8267,8 @@ no_data_fill:
 				 * restart it.
 				 */
 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
-			} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-				    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
+			} else if ((asoc->sctp_cmt_on_off == 1) &&
+				    (asoc->sctp_cmt_pf > 0) &&
 				    pf_hbflag &&
 				    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF) &&
 			    (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
@@ -9579,8 +9575,8 @@ sctp_chunk_output(struct sctp_inpcb *inp,
 			 */
 			if (net->ref_count > 1)
 				sctp_move_to_an_alt(stcb, asoc, net);
-		} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
-			    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
+		} else if ((asoc->sctp_cmt_on_off == 1) &&
+			    (asoc->sctp_cmt_pf > 0) &&
 		    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
 			/*
 			 * JRS 5/14/07 - If CMT PF is on and the current
@@ -9926,8 +9922,8 @@ sctp_send_sack(struct sctp_tcb *stcb)
 	uint8_t flags;
 	uint8_t type;
 
-	if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off) &&
-	    stcb->asoc.peer_supports_nr_sack) {
+	if ((stcb->asoc.sctp_nr_sack_on_off == 1) &&
+	    (stcb->asoc.peer_supports_nr_sack == 1)) {
 		type = SCTP_NR_SELECTIVE_ACK;
 	} else {
 		type = SCTP_SELECTIVE_ACK;
@@ -10071,7 +10067,8 @@ sctp_send_sack(struct sctp_tcb *stcb)
 	else
 		flags = 0;
 
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
+	if ((asoc->sctp_cmt_on_off == 1) &&
+	    SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
 		/*-
 		 * CMT DAC algorithm: If 2 (i.e., 0x10) packets have been
 		 * received, then set high bit to 1, else 0. Reset
@@ -10839,7 +10836,8 @@ sctp_send_hb(struct sctp_tcb *stcb, int user_req, struct sctp_nets *u_net)
 	 * heartbeat is being sent is in PF state, do NOT do threshold
 	 * management.
 	 */
-	if ((SCTP_BASE_SYSCTL(sctp_cmt_pf) == 0) || ((net->dest_state & SCTP_ADDR_PF) != SCTP_ADDR_PF)) {
+	if ((stcb->asoc.sctp_cmt_pf == 0) ||
+	    ((net->dest_state & SCTP_ADDR_PF) != SCTP_ADDR_PF)) {
 		/* ok we have a destination that needs a beat */
 		/* lets do the theshold management Qiaobing style */
 		if (sctp_threshold_management(stcb->sctp_ep, stcb, net,
@@ -12105,7 +12103,7 @@ sctp_sosend(struct socket *so,
 	struct sctp_sndrcvinfo srcv;
 	struct sockaddr *addr_to_use;
 
-#ifdef INET6
+#if defined(INET) && defined(INET6)
 	struct sockaddr_in sin;
 
 #endif
@@ -12120,7 +12118,7 @@ sctp_sosend(struct socket *so,
 		}
 	}
 	addr_to_use = addr;
-#if defined(INET6)  && !defined(__Userspace__)	/* TODO port in6_sin6_2_sin */
+#if defined(INET) && defined(INET6)
 	if ((addr) && (addr->sa_family == AF_INET6)) {
 		struct sockaddr_in6 *sin6;
 
@@ -12212,20 +12210,33 @@ sctp_lower_sosend(struct socket *so,
 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Send called addr:%p send length %d\n",
 	    addr,
 	    sndlen);
-	/*-
+	/**
 	 * Pre-screen address, if one is given the sin-len
 	 * must be set correctly!
 	 */
 	if (addr) {
-		if ((addr->sa_family == AF_INET) &&
-		    (addr->sa_len != sizeof(struct sockaddr_in))) {
-			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-			error = EINVAL;
-			goto out_unlocked;
-		} else if ((addr->sa_family == AF_INET6) &&
-		    (addr->sa_len != sizeof(struct sockaddr_in6))) {
-			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-			error = EINVAL;
+		switch (addr->sa_family) {
+#if defined(INET)
+		case AF_INET:
+			if (addr->sa_len != sizeof(struct sockaddr_in)) {
+				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
+				error = EINVAL;
+				goto out_unlocked;
+			}
+			break;
+#endif
+#if defined(INET6)
+		case AF_INET6:
+			if (addr->sa_len != sizeof(struct sockaddr_in6)) {
+				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
+				error = EINVAL;
+				goto out_unlocked;
+			}
+			break;
+#endif
+		default:
+			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAFNOSUPPORT);
+			error = EAFNOSUPPORT;
 			goto out_unlocked;
 		}
 	}
@@ -12657,7 +12668,8 @@ sctp_lower_sosend(struct socket *so,
 		error = EINVAL;
 		goto out_unlocked;
 	}
-	if ((net->flight_size > net->cwnd) && (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
+	if ((net->flight_size > net->cwnd) &&
+	    (asoc->sctp_cmt_on_off == 0)) {
 		/*-
 		 * CMT: Added check for CMT above. net above is the primary
 		 * dest. If CMT is ON, sender should always attempt to send
@@ -13075,7 +13087,7 @@ skip_preblock:
 				goto skip_out_eof;
 			}
 			if ((net->flight_size > net->cwnd) &&
-			    (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
+			    (asoc->sctp_cmt_on_off == 0)) {
 				queue_only = 1;
 			} else if (asoc->ifp_had_enobuf) {
 				SCTP_STAT_INCR(sctps_ifnomemqueued);
@@ -13349,7 +13361,7 @@ skip_out_eof:
 		some_on_control = 1;
 	}
 	if ((net->flight_size > net->cwnd) &&
-	    (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
+	    (stcb->asoc.sctp_cmt_on_off == 0)) {
 		queue_only = 1;
 	} else if (asoc->ifp_had_enobuf) {
 		SCTP_STAT_INCR(sctps_ifnomemqueued);
diff --git a/sys/netinet/sctp_pcb.c b/sys/netinet/sctp_pcb.c
index ad8bc520433..846f55d8024 100644
--- a/sys/netinet/sctp_pcb.c
+++ b/sys/netinet/sctp_pcb.c
@@ -2385,6 +2385,7 @@ sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id)
 	inp->sctp_associd_counter = 1;
 	inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT;
 	inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
+	inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off);
 	/* init the small hash table we use to track asocid <-> tcb */
 	inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark);
 	if (inp->sctp_asocidhash == NULL) {
@@ -6241,10 +6242,7 @@ sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
 					stcb->asoc.peer_supports_pktdrop = 1;
 					break;
 				case SCTP_NR_SELECTIVE_ACK:
-					if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off))
-						stcb->asoc.peer_supports_nr_sack = 1;
-					else
-						stcb->asoc.peer_supports_nr_sack = 0;
+					stcb->asoc.peer_supports_nr_sack = 1;
 					break;
 				case SCTP_STREAM_RESET:
 					stcb->asoc.peer_supports_strreset = 1;
diff --git a/sys/netinet/sctp_pcb.h b/sys/netinet/sctp_pcb.h
index 318b0125814..23ebc4f1756 100644
--- a/sys/netinet/sctp_pcb.h
+++ b/sys/netinet/sctp_pcb.h
@@ -389,6 +389,7 @@ struct sctp_inpcb {
 	uint32_t sctp_frag_point;
 	uint32_t partial_delivery_point;
 	uint32_t sctp_context;
+	uint32_t sctp_cmt_on_off;
 	struct sctp_nonpad_sndrcvinfo def_send;
 	/*-
 	 * These three are here for the sosend_dgram
diff --git a/sys/netinet/sctp_peeloff.c b/sys/netinet/sctp_peeloff.c
index 6f899b406ca..69d04c0be31 100644
--- a/sys/netinet/sctp_peeloff.c
+++ b/sys/netinet/sctp_peeloff.c
@@ -112,6 +112,7 @@ sctp_do_peeloff(struct socket *head, struct socket *so, sctp_assoc_t assoc_id)
 	n_inp->sctp_features = inp->sctp_features;
 	n_inp->sctp_mobility_features = inp->sctp_mobility_features;
 	n_inp->sctp_frag_point = inp->sctp_frag_point;
+	n_inp->sctp_cmt_on_off = inp->sctp_cmt_on_off;
 	n_inp->partial_delivery_point = inp->partial_delivery_point;
 	n_inp->sctp_context = inp->sctp_context;
 	n_inp->inp_starting_point_for_iterator = NULL;
@@ -183,6 +184,7 @@ sctp_get_peeloff(struct socket *head, sctp_assoc_t assoc_id, int *error)
 	    (SCTP_PCB_COPY_FLAGS & inp->sctp_flags));
 	n_inp->sctp_features = inp->sctp_features;
 	n_inp->sctp_frag_point = inp->sctp_frag_point;
+	n_inp->sctp_cmt_on_off = inp->sctp_cmt_on_off;
 	n_inp->partial_delivery_point = inp->partial_delivery_point;
 	n_inp->sctp_context = inp->sctp_context;
 	n_inp->inp_starting_point_for_iterator = NULL;
diff --git a/sys/netinet/sctp_timer.c b/sys/netinet/sctp_timer.c
index 292127275dd..e2bd5bb5f56 100644
--- a/sys/netinet/sctp_timer.c
+++ b/sys/netinet/sctp_timer.c
@@ -215,7 +215,8 @@ sctp_threshold_management(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
 				 * not in PF state.
 				 */
 				/* Stop any running T3 timers here? */
-				if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+				if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+				    (stcb->asoc.sctp_cmt_pf > 0)) {
 					net->dest_state &= ~SCTP_ADDR_PF;
 					SCTPDBG(SCTP_DEBUG_TIMER4, "Destination %p moved from PF to unreachable.\n",
 					    net);
@@ -419,7 +420,7 @@ sctp_find_alternate_net(struct sctp_tcb *stcb,
 				return (net);
 			}
 			min_errors_net->dest_state &= ~SCTP_ADDR_PF;
-			min_errors_net->cwnd = min_errors_net->mtu * SCTP_BASE_SYSCTL(sctp_cmt_pf);
+			min_errors_net->cwnd = min_errors_net->mtu * stcb->asoc.sctp_cmt_pf;
 			if (SCTP_OS_TIMER_PENDING(&min_errors_net->rxt_timer.timer)) {
 				sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
 				    stcb, min_errors_net,
@@ -843,7 +844,7 @@ start_again:
 			/*
 			 * CMT: Do not allow FRs on retransmitted TSNs.
 			 */
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 1) {
+			if (stcb->asoc.sctp_cmt_on_off == 1) {
 				chk->no_fr_allowed = 1;
 			}
 #ifdef THIS_SHOULD_NOT_BE_DONE
@@ -1038,7 +1039,8 @@ sctp_t3rxt_timer(struct sctp_inpcb *inp,
 	 * addition, find an alternate destination with PF-based
 	 * find_alt_net().
 	 */
-	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+	if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+	    (stcb->asoc.sctp_cmt_pf > 0)) {
 		if ((net->dest_state & SCTP_ADDR_PF) != SCTP_ADDR_PF) {
 			net->dest_state |= SCTP_ADDR_PF;
 			net->last_active = sctp_get_tick_count();
@@ -1046,7 +1048,7 @@ sctp_t3rxt_timer(struct sctp_inpcb *inp,
 			    net);
 		}
 		alt = sctp_find_alternate_net(stcb, net, 2);
-	} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
+	} else if (stcb->asoc.sctp_cmt_on_off == 1) {
 		/*
 		 * CMT: Using RTX_SSTHRESH policy for CMT. If CMT is being
 		 * used, then pick dest with largest ssthresh for any
@@ -1162,7 +1164,9 @@ sctp_t3rxt_timer(struct sctp_inpcb *inp,
 				net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
 			}
 		}
-	} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf) && (net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF) {
+	} else if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+		    (stcb->asoc.sctp_cmt_pf > 0) &&
+	    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
 		/*
 		 * JRS 5/14/07 - If the destination hasn't failed completely
 		 * but is in PF state, a PF-heartbeat needs to be sent
diff --git a/sys/netinet/sctp_usrreq.c b/sys/netinet/sctp_usrreq.c
index 46cfa3dcf8c..2ed66af0433 100644
--- a/sys/netinet/sctp_usrreq.c
+++ b/sys/netinet/sctp_usrreq.c
@@ -300,7 +300,8 @@ sctp_notify(struct sctp_inpcb *inp,
 			 * PF state.
 			 */
 			/* Stop any running T3 timers here? */
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+			if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+			    (stcb->asoc.sctp_cmt_pf > 0)) {
 				net->dest_state &= ~SCTP_ADDR_PF;
 				SCTPDBG(SCTP_DEBUG_TIMER4, "Destination %p moved from PF to unreachable.\n",
 				    net);
@@ -1736,42 +1737,14 @@ flags_out:
 			struct sctp_assoc_value *av;
 
 			SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, *optsize);
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
-				SCTP_FIND_STCB(inp, stcb, av->assoc_id);
-				if (stcb) {
-					av->assoc_value = stcb->asoc.sctp_cmt_on_off;
-					SCTP_TCB_UNLOCK(stcb);
-
-				} else {
-					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOTCONN);
-					error = ENOTCONN;
-				}
+			SCTP_FIND_STCB(inp, stcb, av->assoc_id);
+			if (stcb) {
+				av->assoc_value = stcb->asoc.sctp_cmt_on_off;
+				SCTP_TCB_UNLOCK(stcb);
 			} else {
-				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOPROTOOPT);
-				error = ENOPROTOOPT;
-			}
-			*optsize = sizeof(*av);
-		}
-		break;
-		/* EY - set socket option for nr_sacks  */
-	case SCTP_NR_SACK_ON_OFF:
-		{
-			struct sctp_assoc_value *av;
-
-			SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, *optsize);
-			if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off)) {
-				SCTP_FIND_STCB(inp, stcb, av->assoc_id);
-				if (stcb) {
-					av->assoc_value = stcb->asoc.sctp_nr_sack_on_off;
-					SCTP_TCB_UNLOCK(stcb);
-
-				} else {
-					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOTCONN);
-					error = ENOTCONN;
-				}
-			} else {
-				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOPROTOOPT);
-				error = ENOPROTOOPT;
+				SCTP_INP_RLOCK(inp);
+				av->assoc_value = inp->sctp_cmt_on_off;
+				SCTP_INP_RUNLOCK(inp);
 			}
 			*optsize = sizeof(*av);
 		}
@@ -2846,44 +2819,28 @@ sctp_setopt(struct socket *so, int optname, void *optval, size_t optsize,
 		}
 		break;
 	case SCTP_CMT_ON_OFF:
-		{
+		if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
 			struct sctp_assoc_value *av;
 
 			SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, optsize);
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
-				SCTP_FIND_STCB(inp, stcb, av->assoc_id);
-				if (stcb) {
-					stcb->asoc.sctp_cmt_on_off = (uint8_t) av->assoc_value;
-					SCTP_TCB_UNLOCK(stcb);
-				} else {
-					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOTCONN);
-					error = ENOTCONN;
-				}
+			SCTP_FIND_STCB(inp, stcb, av->assoc_id);
+			if (stcb) {
+				if (av->assoc_value != 0)
+					stcb->asoc.sctp_cmt_on_off = 1;
+				else
+					stcb->asoc.sctp_cmt_on_off = 0;
+				SCTP_TCB_UNLOCK(stcb);
 			} else {
-				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOPROTOOPT);
-				error = ENOPROTOOPT;
-			}
-		}
-		break;
-		/* EY nr_sack_on_off socket option */
-	case SCTP_NR_SACK_ON_OFF:
-		{
-			struct sctp_assoc_value *av;
-
-			SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, optsize);
-			if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off)) {
-				SCTP_FIND_STCB(inp, stcb, av->assoc_id);
-				if (stcb) {
-					stcb->asoc.sctp_nr_sack_on_off = (uint8_t) av->assoc_value;
-					SCTP_TCB_UNLOCK(stcb);
-				} else {
-					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOTCONN);
-					error = ENOTCONN;
-				}
-			} else {
-				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOPROTOOPT);
-				error = ENOPROTOOPT;
+				SCTP_INP_WLOCK(inp);
+				if (av->assoc_value != 0)
+					inp->sctp_cmt_on_off = 1;
+				else
+					inp->sctp_cmt_on_off = 0;
+				SCTP_INP_WUNLOCK(inp);
 			}
+		} else {
+			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOPROTOOPT);
+			error = ENOPROTOOPT;
 		}
 		break;
 		/* JRS - Set socket option for pluggable congestion control */
diff --git a/sys/netinet/sctputil.c b/sys/netinet/sctputil.c
index e390fb1cde2..95bbe362117 100644
--- a/sys/netinet/sctputil.c
+++ b/sys/netinet/sctputil.c
@@ -893,10 +893,8 @@ sctp_init_asoc(struct sctp_inpcb *m, struct sctp_tcb *stcb,
 	asoc->max_burst = m->sctp_ep.max_burst;
 	asoc->heart_beat_delay = TICKS_TO_MSEC(m->sctp_ep.sctp_timeoutticks[SCTP_TIMER_HEARTBEAT]);
 	asoc->cookie_life = m->sctp_ep.def_cookie_life;
-	asoc->sctp_cmt_on_off = (uint8_t) SCTP_BASE_SYSCTL(sctp_cmt_on_off);
-	/* EY Init nr_sack variable */
+	asoc->sctp_cmt_on_off = m->sctp_cmt_on_off;
 	asoc->sctp_nr_sack_on_off = (uint8_t) SCTP_BASE_SYSCTL(sctp_nr_sack_on_off);
-	/* JRS 5/21/07 - Init CMT PF variables */
 	asoc->sctp_cmt_pf = (uint8_t) SCTP_BASE_SYSCTL(sctp_cmt_pf);
 	asoc->sctp_frag_point = m->sctp_frag_point;
 #ifdef INET
@@ -4213,7 +4211,7 @@ void
 sctp_print_address_pkt(struct ip *iph, struct sctphdr *sh)
 {
 	switch (iph->ip_v) {
-	case IPVERSION:
+		case IPVERSION:
 		{
 			struct sockaddr_in lsa, fsa;
 
diff --git a/sys/netinet6/sctp6_usrreq.c b/sys/netinet6/sctp6_usrreq.c
index 02e28802320..1fce08e2eca 100644
--- a/sys/netinet6/sctp6_usrreq.c
+++ b/sys/netinet6/sctp6_usrreq.c
@@ -414,7 +414,8 @@ sctp6_notify(struct sctp_inpcb *inp,
 			 * PF state.
 			 */
 			/* Stop any running T3 timers here? */
-			if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
+			if ((stcb->asoc.sctp_cmt_on_off == 1) &&
+			    (stcb->asoc.sctp_cmt_pf > 0)) {
 				net->dest_state &= ~SCTP_ADDR_PF;
 				SCTPDBG(SCTP_DEBUG_TIMER4, "Destination %p moved from PF to unreachable.\n",
 				    net);
@@ -1069,6 +1070,8 @@ sctp6_getaddr(struct socket *so, struct sockaddr **addr)
 	 * Do the malloc first in case it blocks.
 	 */
 	SCTP_MALLOC_SONAME(sin6, struct sockaddr_in6 *, sizeof *sin6);
+	if (sin6 == NULL)
+		return ENOMEM;
 	sin6->sin6_family = AF_INET6;
 	sin6->sin6_len = sizeof(*sin6);
 
@@ -1173,6 +1176,8 @@ sctp6_peeraddr(struct socket *so, struct sockaddr **addr)
 		return (ENOTCONN);
 	}
 	SCTP_MALLOC_SONAME(sin6, struct sockaddr_in6 *, sizeof *sin6);
+	if (sin6 == NULL)
+		return (ENOMEM);
 	sin6->sin6_family = AF_INET6;
 	sin6->sin6_len = sizeof(*sin6);
 

From d12f1e190eb338a1ef1ad48e3e972bdf81de0155 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Sat, 28 Aug 2010 19:02:51 +0000
Subject: [PATCH 0327/1624] New driver nlge for XLR/XLS Network Accelerator.
 This will support the XGMAC and XAUI 10G interfaces in addition RGMII/SGMII
 1G interfaces.  This driver is work in progress.

board.c and board.h expanded to include more info.

Only one of rge and nlge can be enabled at a time, rge will be deprecated
when nlge stabilizes.

Submitted by:	Sriram Gorti 
---
 sys/mips/rmi/board.c            |  442 ++++--
 sys/mips/rmi/board.h            |   68 +-
 sys/mips/rmi/dev/nlge/if_nlge.c | 2444 +++++++++++++++++++++++++++++++
 sys/mips/rmi/dev/nlge/if_nlge.h | 1180 +++++++++++++++
 sys/mips/rmi/files.xlr          |    1 +
 sys/mips/rmi/iodi.c             |   46 +-
 6 files changed, 4062 insertions(+), 119 deletions(-)
 create mode 100644 sys/mips/rmi/dev/nlge/if_nlge.c
 create mode 100644 sys/mips/rmi/dev/nlge/if_nlge.h

diff --git a/sys/mips/rmi/board.c b/sys/mips/rmi/board.c
index ab55e05bbe2..ac36755a1d8 100644
--- a/sys/mips/rmi/board.c
+++ b/sys/mips/rmi/board.c
@@ -78,13 +78,12 @@ static int xls_rxstn_to_txstn_map[128] = {
 	[120 ... 127] = TX_STN_SAE
 };
 
-struct stn_cc *xlr_core_cc_configs[] = {&cc_table_cpu_0, &cc_table_cpu_1,
-	&cc_table_cpu_2, &cc_table_cpu_3,
-	&cc_table_cpu_4, &cc_table_cpu_5,
-&cc_table_cpu_6, &cc_table_cpu_7};
+struct stn_cc *xlr_core_cc_configs[] = { &cc_table_cpu_0, &cc_table_cpu_1,
+    &cc_table_cpu_2, &cc_table_cpu_3, &cc_table_cpu_4, &cc_table_cpu_5,
+    &cc_table_cpu_6, &cc_table_cpu_7};
 
-struct stn_cc *xls_core_cc_configs[] = {&xls_cc_table_cpu_0, &xls_cc_table_cpu_1,
-&xls_cc_table_cpu_2, &xls_cc_table_cpu_3};
+struct stn_cc *xls_core_cc_configs[] = { &xls_cc_table_cpu_0, &xls_cc_table_cpu_1,
+   &xls_cc_table_cpu_2, &xls_cc_table_cpu_3 };
 
 struct xlr_board_info xlr_board_info;
 
@@ -98,6 +97,174 @@ xlr_pcmcia_present(void)
 	return ((resetconf & 0x4000) != 0);
 }
 
+static void
+xlr_board_specific_overrides(struct xlr_board_info* board)
+{
+	struct xlr_gmac_block_t *blk1, *blk2;
+
+	blk1 = &board->gmac_block[1];
+	blk2 = &board->gmac_block[2];
+
+	switch (xlr_boot1_info.board_major_version) {
+	case RMI_XLR_BOARD_ARIZONA_I: 
+		/* ATX-I has SPI-4, not XGMAC */
+		blk1->type = XLR_SPI4;
+		blk1->enabled = 0;     /* nlge does not
+							 support SPI-4 */
+		blk2->type = XLR_SPI4;
+		blk2->enabled = 0;
+		break;
+
+	case RMI_XLR_BOARD_ARIZONA_II:
+		/* XGMII_A --> VSC7281, XGMII_B --> VSC7281 */
+		blk1->enabled = 1;
+		blk1->num_ports = 1;
+		blk1->gmac_port[0].valid = 1;
+
+		blk2->enabled = 1;
+		blk2->num_ports = 1;
+		blk2->gmac_port[0].valid = 1;
+	default:
+		break;
+	}
+}
+
+static int
+quad0_xaui(void)
+{
+	xlr_reg_t *gpio_mmio =
+	    (unsigned int *)(DEFAULT_XLR_IO_BASE + XLR_IO_GPIO_OFFSET);
+	uint32_t bit24;
+
+	bit24 = (xlr_read_reg(gpio_mmio, 0x15) >> 24) & 0x1;
+	return (bit24);
+}
+
+static int
+quad1_xaui(void)
+{
+	xlr_reg_t *gpio_mmio =
+	    (unsigned int *)(DEFAULT_XLR_IO_BASE + XLR_IO_GPIO_OFFSET);
+	uint32_t bit25;
+
+	bit25 = (xlr_read_reg(gpio_mmio, 0x15) >> 25) & 0x1;
+	return (bit25);
+}
+
+static void
+xls_board_specific_overrides(struct xlr_board_info* board)
+{
+	struct xlr_gmac_block_t *blk0, *blk1;
+	int i;
+
+	blk0 = &board->gmac_block[0];
+	blk1 = &board->gmac_block[1];
+
+	switch (xlr_boot1_info.board_major_version) {
+	case RMI_XLR_BOARD_ARIZONA_VI:
+		blk0->mode = XLR_PORT0_RGMII;
+		blk0->gmac_port[0].type = XLR_RGMII;
+		blk0->gmac_port[0].phy_addr = 0;
+		blk0->gmac_port[0].mii_addr = XLR_IO_GMAC_4_OFFSET;
+		/* Because of the Octal PHY, SGMII Quad1 is MII is also bound
+		 * to the PHY attached to SGMII0_MDC/MDIO/MDINT. */
+		for (i = 0; i < 4; i++) {
+			blk1->gmac_port[i].mii_addr = XLR_IO_GMAC_0_OFFSET;
+			blk1->gmac_port[i].serdes_addr = XLR_IO_GMAC_0_OFFSET;
+		}
+		blk1->gmac_port[1].mii_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[2].mii_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[3].mii_addr = XLR_IO_GMAC_0_OFFSET;
+
+		blk1->gmac_port[1].serdes_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[2].serdes_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[3].serdes_addr = XLR_IO_GMAC_0_OFFSET;
+
+		/* RGMII MDIO interrupt is thru NA1 and SGMII MDIO 
+		 * interrupts for ports in blk1 are from NA0 */
+		blk0->gmac_port[0].mdint_id = 1;
+
+		blk1->gmac_port[0].mdint_id = 0;
+		blk1->gmac_port[1].mdint_id = 0;
+		blk1->gmac_port[2].mdint_id = 0;
+		blk1->gmac_port[3].mdint_id = 0;
+		break;
+
+	case RMI_XLR_BOARD_ARIZONA_VIII:
+		/* There is just one Octal PHY on the board and it is 
+		 * connected to the MII interface for NA Quad 0. */
+		blk1->gmac_port[0].mii_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[1].mii_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[2].mii_addr = XLR_IO_GMAC_0_OFFSET;
+		blk1->gmac_port[3].mii_addr = XLR_IO_GMAC_0_OFFSET;
+
+		/* Board 8.3 (Lite) has XLS108 */
+		if (xlr_boot1_info.board_minor_version == 3) {
+			/* NA0 has 3 ports */
+			blk0->gmac_port[3].valid = 1;
+			blk0->num_ports--;
+			/* NA1 is completely disabled */
+			blk1->enabled = 0;
+		}
+
+		break;
+
+	case RMI_XLR_BOARD_ARIZONA_XI:
+	case RMI_XLR_BOARD_ARIZONA_XII:
+		if (quad0_xaui()) { /* GMAC ports 0-3 are set to XAUI */
+			/* only GMAC0 is active i.e, the 0-th port on this quad.
+			 * Disable all the other 7 possible ports. */
+			for (i = 1; i < MAX_NA_PORTS; i++) {
+				memset(&blk0->gmac_port[i], 0,
+				    sizeof(blk0->gmac_port[i]));
+			}
+			/* Setup for XAUI on N/w Acc0: gmac0 */
+			blk0->type 		= XLR_XGMAC;
+			blk0->mode 		= XLR_XAUI;
+			blk0->num_ports 	= 1;
+			blk0->gmac_port[0].type = XLR_XAUI;
+			blk1->gmac_port[0].phy_addr = 16;
+			blk0->gmac_port[0].tx_bucket_id = blk0->station_txbase;
+			/* Other addresses etc need not be modified as XAUI_0
+			 * shares its addresses with SGMII GMAC_0, which was 
+			 * set in the caller. */
+		}
+		else {
+			blk0->num_ports 	= 1;  /* only 1 RGMII port */ 
+			blk0->mode = XLR_PORT0_RGMII;
+			blk0->gmac_port[0].type = XLR_RGMII;
+			blk0->gmac_port[0].phy_addr = 0;
+			blk0->gmac_port[0].mii_addr = XLR_IO_GMAC_0_OFFSET;
+		}
+
+		if (quad1_xaui()) { /* GMAC ports 4-7 are used for XAUI */
+			/* only GMAC4 is active i.e, the 0-th port on this quad.
+			 * Disable all the other 7 possible ports. */
+			for (i = 1; i < MAX_NA_PORTS; i++) {
+				memset(&blk1->gmac_port[i], 0,
+				    sizeof(blk1->gmac_port[i]));
+			}
+			/* Setup for XAUI on N/w Acc1: gmac4 */
+			blk1->type 		= XLR_XGMAC;
+			blk1->mode 		= XLR_XAUI;
+			blk1->num_ports 	= 1;
+			/* XAUI and SGMII ports share FMN buckets on N/w Acc 1;
+			   so, station_txbase, station_rfr need not be
+			   patched up. */
+			blk1->gmac_port[0].type = XLR_XAUI;
+			blk1->gmac_port[0].phy_addr = 16;
+			blk1->gmac_port[0].tx_bucket_id = blk1->station_txbase;
+			/* Other addresses etc need not be modified as XAUI_1
+			 * shares its addresses with SGMII GMAC_4, which was 
+			 * set in the caller. */
+		}
+		break;
+
+	default:
+		break;
+	}
+}
+
 /*
  * All our knowledge of chip and board that cannot be detected by probing
  * at run-time goes here
@@ -105,6 +272,57 @@ xlr_pcmcia_present(void)
 int 
 xlr_board_info_setup()
 {
+	struct xlr_gmac_block_t *blk0, *blk1, *blk2;
+	int i;
+
+	/* This setup code is long'ish because the same base driver
+	 * (if_nlge.c) is used for different: 
+	 *    - CPUs (XLR/XLS)
+	 *    - boards (for each CPU, multiple board configs are possible
+	 *	        and available).
+	 *
+	 * At the time of writing, there are atleast 12 boards, 4 with XLR 
+	 * and 8 with XLS. This means that the base driver needs to work with
+	 * 12 different configurations, with varying levels of differences. 
+	 * To accomodate the different configs, the xlr_board_info struct
+	 * has various attributes for paramters that could be different. 
+	 * These attributes are setup here and can be used directly in the 
+	 * base driver. 
+	 * It was seen that the setup code is not entirely trivial and
+	 * it is possible to organize it in different ways. In the following,
+	 * we choose an approach that sacrifices code-compactness/speed for
+	 * readability. This is because configuration code executes once
+	 * per reboot and hence has a minimal performance impact.
+	 * On the other hand, driver debugging/enhancements require 
+	 * that different engineers can quickly comprehend the setup 
+	 * sequence. Hence, readability is seen as the key requirement for
+	 * this code. It is for the reader to decide how much of this
+	 * requirement is met with the current code organization !!
+	 *
+	 * The initialization is organized thus: 
+	 *
+	 * if (CPU is XLS) {
+	 *    // initialize per XLS architecture
+	 *       // default inits (per chip spec)
+	 *       // board-specific overrides
+	 * } else if (CPU is XLR) {
+	 *    // initialize per XLR architecture
+	 *       // default inits (per chip spec)
+	 *       // board-specific overrides
+	 * }
+	 * 
+	 * Within each CPU-specific initialization, all the default 
+	 * initializations are done first. This is followed up with 
+	 * board specific overrides. 
+	 */
+
+	/* start with a clean slate */
+	memset(&xlr_board_info, 0, sizeof(xlr_board_info));
+	xlr_board_info.ata =  xlr_pcmcia_present();
+
+	blk0 = &xlr_board_info.gmac_block[0];
+	blk1 = &xlr_board_info.gmac_block[1];
+	blk2 = &xlr_board_info.gmac_block[2];
 
 	if (xlr_is_xls()) {
 		xlr_board_info.is_xls = 1;
@@ -113,98 +331,154 @@ xlr_board_info_setup()
 		/* Board version 8 has NAND flash */
 		xlr_board_info.cfi =
 		    (xlr_boot1_info.board_major_version != RMI_XLR_BOARD_ARIZONA_VIII);
-		xlr_board_info.ata = xlr_pcmcia_present();
 		xlr_board_info.pci_irq = 0;
 		xlr_board_info.credit_configs = xls_core_cc_configs;
-		xlr_board_info.bucket_sizes = &xls_bucket_sizes;
-		xlr_board_info.msgmap = xls_rxstn_to_txstn_map;
-		xlr_board_info.gmacports = 8;
+		xlr_board_info.bucket_sizes   = &xls_bucket_sizes;
+		xlr_board_info.msgmap         = xls_rxstn_to_txstn_map;
+		xlr_board_info.gmacports      = MAX_NA_PORTS;
 
-		/* network block 0 */
-		xlr_board_info.gmac_block[0].type = XLR_GMAC;
-		xlr_board_info.gmac_block[0].enabled = 0xf;
-		xlr_board_info.gmac_block[0].credit_config = &xls_cc_table_gmac0;
-		xlr_board_info.gmac_block[0].station_txbase = MSGRNG_STNID_GMACTX0;
-		xlr_board_info.gmac_block[0].station_rfr = MSGRNG_STNID_GMACRFR_0;
-		if (xlr_boot1_info.board_major_version == RMI_XLR_BOARD_ARIZONA_VI ||
-		    xlr_boot1_info.board_major_version == RMI_XLR_BOARD_ARIZONA_XI ||
-		    xlr_boot1_info.board_major_version == RMI_XLR_BOARD_ARIZONA_XII)
-			xlr_board_info.gmac_block[0].mode = XLR_PORT0_RGMII;
-		else
-			xlr_board_info.gmac_block[0].mode = XLR_SGMII;
-		xlr_board_info.gmac_block[0].baseaddr = XLR_IO_GMAC_0_OFFSET;
-		xlr_board_info.gmac_block[0].baseirq = PIC_GMAC_0_IRQ;
-		xlr_board_info.gmac_block[0].baseinst = 0;
+		/* ---------------- Network Acc 0 ---------------- */
 
-		/* network block 1 */
-		xlr_board_info.gmac_block[1].type = XLR_GMAC;
-		xlr_board_info.gmac_block[1].enabled = xlr_is_xls1xx() ? 0 : 0xf;
-		if (xlr_is_xls4xx_lite()) {
-			xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_GPIO_OFFSET);
-			uint32_t tmp;
+		blk0->type 		= XLR_GMAC;
+		blk0->enabled 		= 0xf;
+		blk0->credit_config 	= &xls_cc_table_gmac0;
+		blk0->station_id 	= TX_STN_GMAC0;
+		blk0->station_txbase 	= MSGRNG_STNID_GMACTX0;
+		blk0->station_rfr 	= MSGRNG_STNID_GMACRFR_0;
+		blk0->mode 		= XLR_SGMII;
+		blk0->baseaddr 		= XLR_IO_GMAC_0_OFFSET;
+		blk0->baseirq 		= PIC_GMAC_0_IRQ;
+		blk0->baseinst 		= 0;
 
-			/* some ports are not enabled on the condor 4xx, figure this
-			   out from the GPIO fuse bank */
-			tmp = xlr_read_reg(mmio, 35);
-			if (tmp & (1<<28))
-				xlr_board_info.gmac_block[1].enabled &= ~0x8;
-			if (tmp & (1<<29))
-				xlr_board_info.gmac_block[1].enabled &= ~0x4;
+		/* By default, assume SGMII is setup. But this can change based 
+		   on board-specific or setting-specific info. */
+		for (i = 0; i < 4; i++) {
+			blk0->gmac_port[i].valid = 1;
+			blk0->gmac_port[i].instance = i + blk0->baseinst;
+			blk0->gmac_port[i].type = XLR_SGMII;
+			blk0->gmac_port[i].phy_addr = i + 16;
+			blk0->gmac_port[i].tx_bucket_id = 
+			    blk0->station_txbase + i;
+			blk0->gmac_port[i].mdint_id = 0;
+			blk0->num_ports++;
+			blk0->gmac_port[i].base_addr = XLR_IO_GMAC_0_OFFSET + i * 0x1000;
+			blk0->gmac_port[i].mii_addr = XLR_IO_GMAC_0_OFFSET;
+			blk0->gmac_port[i].pcs_addr = XLR_IO_GMAC_0_OFFSET;
+			blk0->gmac_port[i].serdes_addr = XLR_IO_GMAC_0_OFFSET;
 		}
-		xlr_board_info.gmac_block[1].credit_config = &xls_cc_table_gmac1;
-		xlr_board_info.gmac_block[1].station_txbase = MSGRNG_STNID_GMAC1_TX0;
-		xlr_board_info.gmac_block[1].station_rfr = MSGRNG_STNID_GMAC1_FR_0;
-		xlr_board_info.gmac_block[1].mode = XLR_SGMII;
-		xlr_board_info.gmac_block[1].baseaddr = XLR_IO_GMAC_4_OFFSET;
-		xlr_board_info.gmac_block[1].baseirq = PIC_XGS_0_IRQ;
-		xlr_board_info.gmac_block[1].baseinst = 4;
 
-		/* network block 2 */
-		xlr_board_info.gmac_block[2].enabled = 0;	/* disabled on XLS */
-	} else {
+		/* ---------------- Network Acc 1 ---------------- */
+		blk1->type 		= XLR_GMAC;
+		blk1->enabled 		= 0xf;
+		blk1->credit_config 	= &xls_cc_table_gmac1;
+		blk1->station_id 	= TX_STN_GMAC1;
+		blk1->station_txbase 	= MSGRNG_STNID_GMAC1_TX0;
+		blk1->station_rfr 	= MSGRNG_STNID_GMAC1_FR_0;
+		blk1->mode 		= XLR_SGMII;
+		blk1->baseaddr 		= XLR_IO_GMAC_4_OFFSET;
+		blk1->baseirq 		= PIC_XGS_0_IRQ;
+		blk1->baseinst 		= 4;
+
+		for (i = 0; i < 4; i++) {
+			blk1->gmac_port[i].valid = 1;
+			blk1->gmac_port[i].instance = i + blk1->baseinst;
+			blk1->gmac_port[i].type = XLR_SGMII;
+			blk1->gmac_port[i].phy_addr = i + 20;
+			blk1->gmac_port[i].tx_bucket_id = 
+			    blk1->station_txbase + i;
+			blk1->gmac_port[i].mdint_id = 1;
+			blk1->num_ports++;
+			blk1->gmac_port[i].base_addr = XLR_IO_GMAC_4_OFFSET +  i * 0x1000;
+			blk1->gmac_port[i].mii_addr = XLR_IO_GMAC_4_OFFSET;
+			blk1->gmac_port[i].pcs_addr = XLR_IO_GMAC_4_OFFSET;
+			blk1->gmac_port[i].serdes_addr = XLR_IO_GMAC_0_OFFSET;
+		}
+
+		/* ---------------- Network Acc 2 ---------------- */
+		xlr_board_info.gmac_block[2].enabled = 0;  /* disabled on XLS */
+
+		xls_board_specific_overrides(&xlr_board_info);
+
+	} else {	/* XLR */
 		xlr_board_info.is_xls = 0;
 		xlr_board_info.nr_cpus = 32;
 		xlr_board_info.usb = 0;
 		xlr_board_info.cfi = 1;
-		xlr_board_info.ata = xlr_pcmcia_present();
 		xlr_board_info.pci_irq = 0;
 		xlr_board_info.credit_configs = xlr_core_cc_configs;
-		xlr_board_info.bucket_sizes = &bucket_sizes;
-		xlr_board_info.msgmap = xlr_rxstn_to_txstn_map;
-		xlr_board_info.gmacports = 4;
+		xlr_board_info.bucket_sizes   = &bucket_sizes;
+		xlr_board_info.msgmap         =  xlr_rxstn_to_txstn_map;
+		xlr_board_info.gmacports         = 4;
 
-		/* GMAC0 */
-		xlr_board_info.gmac_block[0].type = XLR_GMAC;
-		xlr_board_info.gmac_block[0].enabled = 0xf;
-		xlr_board_info.gmac_block[0].credit_config = &cc_table_gmac;
-		xlr_board_info.gmac_block[0].station_txbase = MSGRNG_STNID_GMACTX0;
-		xlr_board_info.gmac_block[0].station_rfr = MSGRNG_STNID_GMACRFR_0;
-		xlr_board_info.gmac_block[0].mode = XLR_RGMII;
-		xlr_board_info.gmac_block[0].baseaddr = XLR_IO_GMAC_0_OFFSET;
-		xlr_board_info.gmac_block[0].baseirq = PIC_GMAC_0_IRQ;
-		xlr_board_info.gmac_block[0].baseinst = 0;
+		/* ---------------- GMAC0 ---------------- */
+		blk0->type 		= XLR_GMAC;
+		blk0->enabled 		= 0xf;
+		blk0->credit_config 	= &cc_table_gmac;
+		blk0->station_id 	= TX_STN_GMAC;
+		blk0->station_txbase 	= MSGRNG_STNID_GMACTX0;
+		blk0->station_rfr 	= MSGRNG_STNID_GMACRFR_0;
+		blk0->mode 		= XLR_RGMII;
+		blk0->baseaddr 		= XLR_IO_GMAC_0_OFFSET;
+		blk0->baseirq 		= PIC_GMAC_0_IRQ;
+		blk0->baseinst 		= 0;
 
-		/* XGMAC0  */
-		xlr_board_info.gmac_block[1].type = XLR_XGMAC;
-		xlr_board_info.gmac_block[1].enabled = 1;
-		xlr_board_info.gmac_block[1].credit_config = &cc_table_xgs_0;
-		xlr_board_info.gmac_block[1].station_txbase = MSGRNG_STNID_XGS0_TX;
-		xlr_board_info.gmac_block[1].station_rfr = MSGRNG_STNID_XGS0FR;
-		xlr_board_info.gmac_block[1].mode = -1;
-		xlr_board_info.gmac_block[1].baseaddr = XLR_IO_XGMAC_0_OFFSET;
-		xlr_board_info.gmac_block[1].baseirq = PIC_XGS_0_IRQ;
-		xlr_board_info.gmac_block[1].baseinst = 4;
+		/* first, do the common/easy stuff for all the ports */
+		for (i = 0; i < 4; i++) {
+			blk0->gmac_port[i].valid = 1;
+			blk0->gmac_port[i].instance = i + blk0->baseinst;
+			blk0->gmac_port[i].type = XLR_RGMII;
+			blk0->gmac_port[i].phy_addr = i;
+			blk0->gmac_port[i].tx_bucket_id = 
+			    blk0->station_txbase + i;
+			blk0->gmac_port[i].mdint_id = 0;
+			blk0->gmac_port[i].base_addr = XLR_IO_GMAC_0_OFFSET + i * 0x1000;
+			blk0->gmac_port[i].mii_addr = XLR_IO_GMAC_0_OFFSET;
+			/* RGMII ports, no PCS/SERDES */
+			blk0->num_ports++;
+		}
 
-		/* XGMAC1 */
-		xlr_board_info.gmac_block[2].type = XLR_XGMAC;
-		xlr_board_info.gmac_block[2].enabled = 1;
-		xlr_board_info.gmac_block[2].credit_config = &cc_table_xgs_1;
-		xlr_board_info.gmac_block[2].station_txbase = MSGRNG_STNID_XGS1_TX;
-		xlr_board_info.gmac_block[2].station_rfr = MSGRNG_STNID_XGS1FR;
-		xlr_board_info.gmac_block[2].mode = -1;
-		xlr_board_info.gmac_block[2].baseaddr = XLR_IO_XGMAC_1_OFFSET;
-		xlr_board_info.gmac_block[2].baseirq = PIC_XGS_1_IRQ;
-		xlr_board_info.gmac_block[2].baseinst = 5;
-	}
-	return 0;
+		/* ---------------- XGMAC0 ---------------- */
+		blk1->type 		= XLR_XGMAC;
+		blk1->mode 		= XLR_XGMII;
+		blk1->enabled 		= 0;
+		blk1->credit_config 	= &cc_table_xgs_0;
+		blk1->station_txbase 	= MSGRNG_STNID_XGS0_TX;
+		blk1->station_rfr 	= MSGRNG_STNID_XMAC0RFR;
+		blk1->station_id 	= TX_STN_XGS_0;	/* TBD: is this correct ? */
+		blk1->baseaddr 		= XLR_IO_XGMAC_0_OFFSET;
+		blk1->baseirq 		= PIC_XGS_0_IRQ;
+		blk1->baseinst 		= 4;
+
+		blk1->gmac_port[0].type 	= XLR_XGMII;
+		blk1->gmac_port[0].instance 	= 0;
+		blk1->gmac_port[0].phy_addr 	= 0;
+		blk1->gmac_port[0].base_addr 	= XLR_IO_XGMAC_0_OFFSET;
+		blk1->gmac_port[0].mii_addr 	= XLR_IO_XGMAC_0_OFFSET;
+		blk1->gmac_port[0].tx_bucket_id = blk1->station_txbase;
+		blk1->gmac_port[0].mdint_id 	= 1;
+
+		/* ---------------- XGMAC1 ---------------- */
+		blk2->type 		= XLR_XGMAC;
+		blk2->mode 		= XLR_XGMII;
+		blk2->enabled 		= 0;
+		blk2->credit_config 	= &cc_table_xgs_1;
+		blk2->station_txbase 	= MSGRNG_STNID_XGS1_TX;
+		blk2->station_rfr 	= MSGRNG_STNID_XMAC1RFR;
+		blk2->station_id 	= TX_STN_XGS_1;	/* TBD: is this correct ? */
+		blk2->baseaddr 		= XLR_IO_XGMAC_1_OFFSET;
+		blk2->baseirq 		= PIC_XGS_1_IRQ;
+		blk2->baseinst 		= 5;
+
+		blk2->gmac_port[0].type 	= XLR_XGMII;
+		blk2->gmac_port[0].instance 	= 0;
+		blk2->gmac_port[0].phy_addr 	= 0;
+		blk2->gmac_port[0].base_addr 	= XLR_IO_XGMAC_1_OFFSET;
+		blk2->gmac_port[0].mii_addr 	= XLR_IO_XGMAC_1_OFFSET;
+		blk2->gmac_port[0].tx_bucket_id = blk2->station_txbase;
+		blk2->gmac_port[0].mdint_id 	= 2;
+
+		/* Done with default setup. Now do board-specific tweaks. */
+		xlr_board_specific_overrides(&xlr_board_info);
+  	}
+  	return 0;
 }
diff --git a/sys/mips/rmi/board.h b/sys/mips/rmi/board.h
index a584af53f71..ed2c04533f9 100644
--- a/sys/mips/rmi/board.h
+++ b/sys/mips/rmi/board.h
@@ -132,41 +132,53 @@ xlr_is_xls4xx_lite(void)
 	uint32_t chipid = xlr_processor_id();
 
 	return (chipid == 0x88 || chipid == 0x8c);
-}
+  }
+  
+/* SPI-4 --> 8 ports, 1G MAC --> 4 ports and 10G MAC --> 1 port */
+#define	MAX_NA_PORTS					8
 
 /* all our knowledge of chip and board that cannot be detected run-time goes here */
-enum gmac_block_types {
-	XLR_GMAC, XLR_XGMAC, XLR_SPI4
-};
-
-enum gmac_block_modes {
-	XLR_RGMII, XLR_SGMII, XLR_PORT0_RGMII
-};
+enum gmac_block_types { XLR_GMAC, XLR_XGMAC, XLR_SPI4};
+enum gmac_port_types  { XLR_RGMII, XLR_SGMII, XLR_PORT0_RGMII, XLR_XGMII, XLR_XAUI };
 
 struct xlr_board_info {
 	int is_xls;
 	int nr_cpus;
-	int usb;		/* usb enabled ? */
-	int cfi;		/* NOR flash */
-	int ata;		/* PCMCIA/compactflash driver */
+	int usb;                               /* usb enabled ? */
+	int cfi;                               /* compact flash driver for NOR? */
+	int ata;                               /* ata driver */
 	int pci_irq;
-	struct stn_cc **credit_configs;	/* pointer to Core station credits */
-	struct bucket_size *bucket_sizes;	/* pointer to Core station
-						 * bucket */
-	int *msgmap;		/* mapping of message station to devices */
-	int gmacports;		/* number of gmac ports on the board */
-	struct xlr_gmac_block_t {
-		int type;	/* see  enum gmac_block_types */
-		unsigned int enabled;	/* mask of ports enabled */
-		struct stn_cc *credit_config;	/* credit configuration */
-		int station_txbase;	/* station id for tx */
-		int station_rfr;/* free desc bucket */
-		int mode;	/* see gmac_block_modes */
-		uint32_t baseaddr;	/* IO base */
-		int baseirq;	/* first irq for this block, the rest are in
-				 * sequence */
-		int baseinst;	/* the first rge unit for this block */
-	}  gmac_block[3];
+	struct stn_cc **credit_configs;        /* pointer to Core station credits */
+	struct bucket_size *bucket_sizes;      /* pointer to Core station bucket */
+	int *msgmap;                           /* mapping of message station to devices */
+	int gmacports;                         /* number of gmac ports on the board */
+	struct xlr_gmac_block_t {              /* refers to the set of GMACs controlled by a 
+                                                  network accelarator */
+		int  type;                     /* see  enum gmac_block_types */
+		unsigned int enabled;          /* mask of ports enabled */   
+		struct stn_cc *credit_config;  /* credit configuration */
+		int station_id;		       /* station id for sending msgs */
+		int station_txbase;            /* station id for tx */
+		int station_rfr;               /* free desc bucket */
+		int  mode;                     /* see gmac_block_modes */
+		uint32_t baseaddr;             /* IO base */
+		int baseirq;        /* first irq for this block, the rest are in sequence */
+		int baseinst;       /* the first rge unit for this block */
+		int num_ports;
+		struct xlr_gmac_port {
+			int valid;
+			int type;		/* see enum gmac_port_types */
+			uint32_t instance;	/* identifies the GMAC to which
+						   this port is bound to. */
+			uint32_t phy_addr;
+			uint32_t base_addr;
+			uint32_t mii_addr;
+			uint32_t pcs_addr;
+			uint32_t serdes_addr;
+			uint32_t tx_bucket_id;
+			uint32_t mdint_id;
+		} gmac_port[MAX_NA_PORTS];
+	} gmac_block [3];
 };
 
 extern struct xlr_board_info xlr_board_info;
diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
new file mode 100644
index 00000000000..ec476ad7fbe
--- /dev/null
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -0,0 +1,2444 @@
+/*-
+ * Copyright (c) 2003-2009 RMI Corporation
+ * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
+ *
+ * RMI_BSD */
+
+/*
+ * The XLR device supports upto four 10/100/1000 Ethernet MACs and upto
+ * two 10G Ethernet MACs (of XGMII). Alternatively, each 10G port can used
+ * as a SPI-4 interface, with 8 ports per such interface. The MACs are
+ * encapsulated in another hardware block referred to as network accelerator,
+ * such that there are three instances of these in a XLR. One of them controls
+ * the four 1G RGMII ports while one each of the others controls an XGMII port.
+ * Enabling MACs requires configuring the corresponding network accelerator
+ * and the individual port.
+ * The XLS device supports upto 8 10/100/1000 Ethernet MACs or max 2 10G
+ * Ethernet MACs. The 1G MACs are of SGMII and 10G MACs are of XAUI
+ * interface. These ports are part of two network accelerators.
+ * The nlge driver configures and initializes non-SPI4 Ethernet ports in the
+ * XLR/XLS devices and enables data transfer on them.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#ifdef HAVE_KERNEL_OPTION_HEADERS
+#include "opt_device_polling.h"
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#define __RMAN_RESOURCE_VISIBLE
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 	/* for DELAY */
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include "miidevs.h"
+#include 
+#include "miibus_if.h"
+
+#include 
+
+MODULE_DEPEND(nlna, nlge, 1, 1, 1);
+MODULE_DEPEND(nlge, ether, 1, 1, 1);
+MODULE_DEPEND(nlge, miibus, 1, 1, 1);
+
+/* Network accelarator entry points */
+static int      nlna_probe(device_t);
+static int      nlna_attach(device_t);
+static int      nlna_detach(device_t);
+static int      nlna_suspend(device_t);
+static int      nlna_resume(device_t);
+static int 	nlna_shutdown(device_t);
+
+/* GMAC port entry points */
+static int	nlge_probe(device_t);
+static int	nlge_attach(device_t);
+static int	nlge_detach(device_t);
+static int	nlge_suspend(device_t);
+static int	nlge_resume(device_t);
+static void	nlge_init(void *);
+static int	nlge_ioctl(struct ifnet *, u_long, caddr_t);
+static void	nlge_start(struct ifnet *);
+static void 	nlge_rx(struct nlge_softc *sc, vm_paddr_t paddr, int len);
+
+static int	nlge_mii_write(struct device *, int, int, int);
+static int	nlge_mii_read(struct device *, int, int);
+static void	nlge_mac_mii_statchg(device_t);
+static int	nlge_mediachange(struct ifnet *ifp);
+static void	nlge_mediastatus(struct ifnet *ifp, struct ifmediareq *ifmr);
+
+/* Other internal/helper functions */
+static void 	*get_buf(void);
+static struct mbuf *get_mbuf(void);
+
+static void	nlna_add_to_port_set(struct nlge_port_set *pset,
+    struct nlge_softc *sc);
+static void	nlna_config_pde(struct nlna_softc *);
+static void	nlna_config_parser(struct nlna_softc *);
+static void	nlna_config_classifier(struct nlna_softc *);
+static void	nlna_config_fifo_spill_area(struct nlna_softc *sc);
+static void	nlna_config_common(struct nlna_softc *);
+static void	nlna_disable_ports(struct nlna_softc *sc);
+static void	nlna_enable_intr(struct nlna_softc *sc);
+static void	nlna_disable_intr(struct nlna_softc *sc);
+static void	nlna_enable_ports(struct nlna_softc *sc);
+static void	nlna_get_all_softc(device_t iodi_dev,
+    struct nlna_softc **sc_vec, uint32_t vec_sz);
+static void 	nlna_hw_init(struct nlna_softc *sc);
+static int 	nlna_is_last_active_na(struct nlna_softc *sc);
+static void	nlna_media_specific_config(struct nlna_softc *sc);
+static void 	nlna_reset_ports(struct nlna_softc *sc,
+    struct xlr_gmac_block_t *blk);
+static struct nlna_softc *nlna_sc_init(device_t dev,
+    struct xlr_gmac_block_t *blk);
+static __inline__ int nlna_send_free_desc(struct nlna_softc *nlna,
+    vm_paddr_t addr);
+static void	nlna_setup_intr(struct nlna_softc *sc);
+static void	nlna_smp_update_pde(void *dummy __unused);
+static void	nlna_submit_rx_free_desc(struct nlna_softc *sc,
+    uint32_t n_desc);
+
+static int	nlge_gmac_config_speed(struct nlge_softc *, int quick);
+static void	nlge_hw_init(struct nlge_softc *sc);
+static int	nlge_if_init(struct nlge_softc *sc);
+static void	nlge_intr(void *arg);
+static int	nlge_irq_init(struct nlge_softc *sc);
+static void	nlge_irq_fini(struct nlge_softc *sc);
+static void	nlge_media_specific_init(struct nlge_softc *sc);
+static void	nlge_mii_init(device_t dev, struct nlge_softc *sc);
+static int	nlge_mii_read_internal(xlr_reg_t *mii_base, int phyaddr,
+    int regidx);
+static void 	nlge_mii_write_internal(xlr_reg_t *mii_base, int phyaddr,
+    int regidx, int regval);
+void 		nlge_msgring_handler(int bucket, int size, int code,
+    int stid, struct msgrng_msg *msg, void *data);
+static void 	nlge_port_disable(int id, xlr_reg_t *base, int port_type);
+static void 	nlge_port_enable(struct nlge_softc *sc);
+static void 	nlge_read_mac_addr(struct nlge_softc *sc);
+static void	nlge_sc_init(struct nlge_softc *sc, device_t dev,
+    struct xlr_gmac_port *port_info);
+static void 	nlge_set_mac_addr(struct nlge_softc *sc);
+static void	nlge_set_port_attribs(struct nlge_softc *,
+    struct xlr_gmac_port *);
+static void 	nlge_sgmii_init(struct nlge_softc *sc);
+static void	nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc);
+
+static int	prepare_fmn_message(struct nlge_softc *sc,
+    struct msgrng_msg *msg, uint32_t *n_entries, struct mbuf *m_head,
+    uint64_t fr_stid, struct nlge_tx_desc **tx_desc);
+
+static void	release_mbuf(uint64_t phy_addr);
+static void 	release_tx_desc(struct msgrng_msg *msg, int rel_buf);
+static int	send_fmn_msg_tx(struct nlge_softc *, struct msgrng_msg *,
+    uint32_t n_entries);
+
+//#define DEBUG
+#ifdef DEBUG
+static int	mac_debug = 1;
+static int 	reg_dump = 0;
+#undef PDEBUG
+#define PDEBUG(fmt, args...) \
+        do {\
+            if (mac_debug) {\
+                printf("[%s@%d|%s]: cpu_%d: " fmt, \
+                __FILE__, __LINE__, __FUNCTION__,  PCPU_GET(cpuid), ##args);\
+            }\
+        } while(0);
+
+/* Debug/dump functions */
+static void 	dump_reg(xlr_reg_t *addr, uint32_t offset, char *name);
+static void	dump_gmac_registers(struct nlge_softc *);
+static void	dump_na_registers(xlr_reg_t *base, int port_id);
+static void	dump_mac_stats(struct nlge_softc *sc);
+static void 	dump_mii_regs(struct nlge_softc *sc) __attribute__((used));
+static void 	dump_mii_data(struct mii_data *mii) __attribute__((used));
+static void	dump_board_info(struct xlr_board_info *);
+static void	dump_pcs_regs(struct nlge_softc *sc, int phy);
+
+#else
+#undef PDEBUG
+#define PDEBUG(fmt, args...)
+#define dump_reg(a, o, n)		/* nop */
+#define dump_gmac_registers(a)		/* nop */
+#define dump_na_registers(a, p)	/* nop */
+#define dump_board_info(b)		/* nop */
+#define dump_mac_stats(sc)		/* nop */
+#define dump_mii_regs(sc)		/* nop */
+#define dump_mii_data(mii)		/* nop */
+#define dump_pcs_regs(sc, phy)		/* nop */
+#endif
+
+/* Wrappers etc. to export the driver entry points. */
+static device_method_t nlna_methods[] = {
+	/* Device interface */
+	DEVMETHOD(device_probe,         nlna_probe),
+	DEVMETHOD(device_attach,        nlna_attach),
+	DEVMETHOD(device_detach,        nlna_detach),
+	DEVMETHOD(device_shutdown,      nlna_shutdown),
+	DEVMETHOD(device_suspend,       nlna_suspend),
+	DEVMETHOD(device_resume,        nlna_resume),
+
+	/* bus interface : TBD : what are these for ? */
+	DEVMETHOD(bus_setup_intr,       bus_generic_setup_intr),
+	DEVMETHOD(bus_print_child,	bus_generic_print_child),
+	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
+
+	{ 0, 0 }
+};
+
+static driver_t	nlna_driver = {
+	"nlna",
+	nlna_methods,
+	sizeof(struct nlna_softc)
+};
+
+static devclass_t nlna_devclass;
+
+static device_method_t nlge_methods[] = {
+	/* Device interface */
+	DEVMETHOD(device_probe,         nlge_probe),
+	DEVMETHOD(device_attach,        nlge_attach),
+	DEVMETHOD(device_detach,        nlge_detach),
+	DEVMETHOD(device_shutdown,      bus_generic_shutdown),
+	DEVMETHOD(device_suspend,       nlge_suspend),
+	DEVMETHOD(device_resume,        nlge_resume),
+
+	/* MII interface */
+	DEVMETHOD(miibus_readreg, nlge_mii_read),
+	DEVMETHOD(miibus_writereg, nlge_mii_write),
+	DEVMETHOD(miibus_statchg, nlge_mac_mii_statchg),
+
+	{0, 0}
+};
+
+static driver_t	nlge_driver = {
+	"nlge",
+	nlge_methods,
+	sizeof(struct nlge_softc)
+};
+
+static devclass_t nlge_devclass;
+
+DRIVER_MODULE(nlna, iodi, nlna_driver, nlna_devclass, 0, 0);
+DRIVER_MODULE(nlge, nlna,  nlge_driver, nlge_devclass, 0, 0);
+DRIVER_MODULE(miibus, nlge, miibus_driver, miibus_devclass, 0, 0);
+
+static uma_zone_t nl_tx_desc_zone;
+
+/* Function to atomically increment an integer with the given value. */
+static __inline__ unsigned int
+ldadd_wu(unsigned int value, unsigned long *addr)
+{
+	__asm__	 __volatile__( ".set push\n"
+			       ".set noreorder\n"
+			       "move $8, %2\n"
+			       "move $9, %3\n"
+			       /* "ldaddwu $8, $9\n" */
+			       ".word 0x71280011\n"
+			       "move %0, $8\n"
+			       ".set pop\n"
+			       : "=&r"(value), "+m"(*addr)
+			       : "0"(value), "r" ((unsigned long)addr)
+			       :  "$8", "$9");
+	return value;
+}
+
+static __inline__ uint32_t
+xlr_enable_kx(void)
+{
+	uint32_t sr = mips_rd_status();
+
+	mips_wr_status((sr & ~MIPS_SR_INT_IE) | MIPS_SR_KX);
+	return sr;
+}
+
+static int
+nlna_probe(device_t dev)
+{
+	return (BUS_PROBE_DEFAULT);
+}
+
+/*
+ * Add all attached GMAC/XGMAC ports to the device tree. Port
+ * configuration is spread in two regions - common configuration
+ * for all ports in the NA and per-port configuration in MAC-specific
+ * region. This function does the following:
+ *  - adds the ports to the device tree
+ *  - reset the ports
+ *  - do all the common initialization
+ *  - invoke bus_generic_attach for per-port configuration
+ *  - supply initial free rx descriptors to ports
+ *  - initialize s/w data structures
+ *  - finally, enable interrupts (only in the last NA).
+ *
+ * For reference, sample address space for common and per-port
+ * registers is given below.
+ *
+ * The address map for RNA0 is:                           (typical value)
+ *
+ * XLR_IO_BASE +--------------------------------------+   0xbef0_0000
+ *             |                                      |
+ *             |                                      |
+ *             |                                      |
+ *             |                                      |
+ *             |                                      |
+ *             |                                      |
+ * GMAC0  ---> +--------------------------------------+   0xbef0_c000
+ *             |                                      |
+ *             |                                      |
+ * (common) -> |......................................|   0xbef0_c400
+ *             |                                      |
+ *             |   (RGMII/SGMII: common registers)    |
+ *             |                                      |
+ * GMAC1  ---> |--------------------------------------|   0xbef0_d000
+ *             |                                      |
+ *             |                                      |
+ * (common) -> |......................................|   0xbef0_d400
+ *             |                                      |
+ *             |   (RGMII/SGMII: common registers)    |
+ *             |                                      |
+ *             |......................................|
+ *       and so on ....
+ *
+ * Ref: Figure 14-3 and Table 14-1 of XLR PRM
+ */
+static int
+nlna_attach(device_t dev)
+{
+	struct xlr_gmac_block_t *block_info;
+	device_t		 gmac_dev;
+	struct nlna_softc	*sc;
+	int			 error;
+	int			 i;
+	int			 id;
+
+	id = device_get_unit(dev);
+	block_info = device_get_ivars(dev);
+	if (!block_info->enabled) {
+		return 0;
+	}
+
+#ifdef DEBUG
+	dump_board_info(&xlr_board_info);
+#endif
+	block_info->baseaddr += DEFAULT_XLR_IO_BASE;
+
+	/* Initialize nlna state in softc structure */
+	sc = nlna_sc_init(dev, block_info);
+
+	/* Add device's for the ports controlled by this NA. */
+	if (block_info->type == XLR_GMAC) {
+		KASSERT(id < 2, ("No GMACs supported with this network"
+		    "accelerator: %d", id));
+		for (i = 0; i < sc->num_ports; i++) {
+			gmac_dev = device_add_child(dev, "nlge", -1);
+			device_set_ivars(gmac_dev, &block_info->gmac_port[i]);
+		}
+	} else if (block_info->type == XLR_XGMAC) {
+		KASSERT(id > 0 && id <= 2, ("No XGMACs supported with this"
+		    "network accelerator: %d", id));
+		gmac_dev = device_add_child(dev, "nlge", -1);
+		device_set_ivars(gmac_dev, &block_info->gmac_port[0]);
+	} else if (block_info->type == XLR_SPI4) {
+		/* SPI4 is not supported here */
+		device_printf(dev, "Unsupported: NA with SPI4 type");
+		return (ENOTSUP);
+	}
+
+	nlna_reset_ports(sc, block_info);
+
+	/* Initialize Network Accelarator registers. */
+	nlna_hw_init(sc);
+
+	error = bus_generic_attach(dev);
+	if (error) {
+		device_printf(dev, "failed to attach port(s)\n");
+		goto fail;
+	}
+
+	/* Send out the initial pool of free-descriptors for the rx path */
+	nlna_submit_rx_free_desc(sc, MAX_FRIN_SPILL);
+
+	/* S/w data structure initializations shared by all NA's. */
+	if (nl_tx_desc_zone == NULL) {
+		/* Create a zone for allocating tx descriptors */
+		nl_tx_desc_zone = uma_zcreate("NL Tx Desc",
+		    sizeof(struct nlge_tx_desc), NULL, NULL, NULL, NULL,
+		    XLR_CACHELINE_SIZE, 0);
+	}
+
+	/* Enable NA interrupts */
+	nlna_setup_intr(sc);
+
+	return (0);
+
+fail:
+	return (error);
+}
+
+static int
+nlna_detach(device_t dev)
+{
+	struct nlna_softc *sc;
+
+	sc = device_get_softc(dev);
+	if (device_is_alive(dev)) {
+		nlna_disable_intr(sc);
+		/* This will make sure that per-port detach is complete
+		 * and all traffic on the ports has been stopped. */
+		bus_generic_detach(dev);
+		uma_zdestroy(nl_tx_desc_zone);
+	}
+
+	return (0);
+}
+
+static int
+nlna_suspend(device_t dev)
+{
+
+	return (0);
+}
+
+static int
+nlna_resume(device_t dev)
+{
+
+	return (0);
+}
+
+static int
+nlna_shutdown(device_t dev)
+{
+	return (0);
+}
+
+
+/* GMAC port entry points */
+static int
+nlge_probe(device_t dev)
+{
+	struct nlge_softc	*sc;
+	struct xlr_gmac_port	*port_info;
+	int index;
+	char *desc[] = { "RGMII", "SGMII", "RGMII/SGMII", "XGMAC", "XAUI",
+	    "Unknown"};
+
+	port_info = device_get_ivars(dev);
+	index = (port_info->type < XLR_RGMII || port_info->type > XLR_XAUI) ?
+	    5 : port_info->type;
+	device_set_desc_copy(dev, desc[index]);
+
+	sc = device_get_softc(dev);
+	nlge_sc_init(sc, dev, port_info);
+
+	nlge_port_disable(sc->id, sc->base, sc->port_type);
+
+	return (0);
+}
+
+static int
+nlge_attach(device_t dev)
+{
+	struct nlge_softc *sc;
+	struct nlna_softc *nsc;
+	int error;
+
+	sc = device_get_softc(dev);
+
+	nlge_if_init(sc);
+	nlge_mii_init(dev, sc);
+	error = nlge_irq_init(sc);
+	if (error)
+		return error;
+	nlge_hw_init(sc);
+
+	nsc = (struct nlna_softc *)device_get_softc(device_get_parent(dev));
+	nsc->child_sc[sc->instance] = sc;
+
+	return (0);
+}
+
+static int
+nlge_detach(device_t dev)
+{
+	struct nlge_softc *sc;
+	struct ifnet   *ifp;
+	
+	sc = device_get_softc(dev);
+	ifp = sc->nlge_if;
+
+	if (device_is_attached(dev)) {
+		ifp->if_drv_flags &= ~(IFF_DRV_OACTIVE | IFF_DRV_RUNNING);
+		nlge_port_disable(sc->id, sc->base, sc->port_type);
+		nlge_irq_fini(sc);
+		ether_ifdetach(ifp);
+		bus_generic_detach(dev);
+	}
+	if (ifp)
+		if_free(ifp);
+
+	return (0);
+}
+
+static int
+nlge_suspend(device_t dev)
+{
+	return (0);
+}
+
+static int
+nlge_resume(device_t dev)
+{
+	return (0);
+}
+
+static void
+nlge_init(void *addr)
+{
+	struct nlge_softc *sc;
+	struct ifnet   *ifp;
+
+	sc = (struct nlge_softc *)addr;
+	ifp = sc->nlge_if;
+
+	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
+		return;
+
+	nlge_gmac_config_speed(sc, 0);
+	ifp->if_drv_flags |= IFF_DRV_RUNNING;
+	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
+	nlge_port_enable(sc);
+
+	if (sc->port_type == XLR_SGMII) {
+		dump_pcs_regs(sc, 27);
+	}
+	dump_gmac_registers(sc);
+	dump_mac_stats(sc);
+}
+
+static int
+nlge_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
+{
+	struct mii_data 	*mii;
+	struct nlge_softc 	*sc;
+	struct ifreq 		*ifr;
+	int 			error;
+
+	sc = ifp->if_softc;
+	error = 0;
+	ifr = (struct ifreq *)data;
+	switch(command) {
+	case SIOCSIFFLAGS:
+		break;
+	case SIOCSIFMEDIA:
+	case SIOCGIFMEDIA:
+		if (sc->mii_bus != NULL) {
+			mii = (struct mii_data *)device_get_softc(sc->mii_bus);
+			error = ifmedia_ioctl(ifp, ifr, &mii->mii_media,
+			    command);
+		}
+		break;
+	case SIOCSIFADDR:
+			// intentional fall thru
+	case SIOCSIFMTU:
+	default:
+		error = ether_ioctl(ifp, command, data);
+		break;
+	}
+
+	return (error);
+}
+
+/* This function is called from an interrupt handler */
+void
+nlge_msgring_handler(int bucket, int size, int code, int stid,
+		    struct msgrng_msg *msg, void *data)
+{
+	struct nlna_softc *na_sc;
+	struct nlge_softc *sc;
+	struct ifnet   *ifp;
+	uint64_t	phys_addr;
+	unsigned long	addr;
+	uint32_t	length;
+	int		ctrl;
+	int		cpu;
+	int		tx_error;
+	int		port;
+	int 		vcpu;
+	int		is_p2p;
+
+	cpu = xlr_core_id();
+	vcpu = (cpu << 2) + xlr_thr_id();
+
+	addr = 0;
+	is_p2p = 0;
+	tx_error = 0;
+	length = (msg->msg0 >> 40) & 0x3fff;
+	na_sc = (struct nlna_softc *)data;
+	phys_addr = (uint64_t) (msg->msg0 & 0xffffffffe0ULL);
+	if (length == 0) {
+		ctrl = CTRL_REG_FREE;
+		port = (msg->msg0 >> 54) & 0x0f;
+		is_p2p = (msg->msg0 >> 62) & 0x1;
+		tx_error = (msg->msg0 >> 58) & 0xf;
+	} else {
+		ctrl = CTRL_SNGL;
+		length = length - BYTE_OFFSET - MAC_CRC_LEN;
+		port = msg->msg0 & 0x0f;
+	}
+
+	sc = na_sc->child_sc[port];
+	if (sc == NULL) {
+		printf("Message (of %d len) with softc=NULL on %d port (type=%s)\n",
+		    length, port, (ctrl == CTRL_SNGL ? "Pkt rx" :
+		    "Freeback for tx packet"));
+		return;
+	}
+
+	if (ctrl == CTRL_REG_FREE || ctrl == CTRL_JUMBO_FREE) {
+		if (is_p2p)
+			release_tx_desc(msg, 1);
+		else {
+			release_mbuf(msg->msg0 & 0xffffffffffULL);
+		}
+		ifp = sc->nlge_if;
+		if (ifp->if_drv_flags & IFF_DRV_OACTIVE){
+			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
+		}
+		ldadd_wu(1, (tx_error) ? &ifp->if_oerrors: &ifp->if_opackets);
+	} else if (ctrl == CTRL_SNGL || ctrl == CTRL_START) {
+		/* Rx Packet */
+
+		nlge_rx(sc, phys_addr, length);
+		nlna_submit_rx_free_desc(na_sc, 1);	/* return free descr to NA */
+	} else {
+		printf("[%s]: unrecognized ctrl=%d!\n", __FUNCTION__, ctrl);
+	}
+
+}
+
+static void
+nlge_start(struct ifnet *ifp)
+{
+	struct nlge_softc	*sc;
+
+	sc = ifp->if_softc;
+	//NLGE_LOCK(sc);
+	nlge_start_locked(ifp, sc);
+	//NLGE_UNLOCK(sc);
+}
+	
+static void
+nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc)
+{
+	struct msgrng_msg 	msg;
+	struct mbuf  		*m;
+	struct nlge_tx_desc 	*tx_desc;
+	uint64_t		fr_stid;
+	uint32_t		cpu;	
+	uint32_t		n_entries;	
+	uint32_t		tid;
+	int 			ret;
+	int 			sent;
+
+	cpu = xlr_core_id();	
+	tid = xlr_thr_id();
+	fr_stid = (cpu << 3) + tid + 4;	/* Each CPU has 8 buckets. */
+
+	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
+		return;
+	}
+
+	do {
+		/* Grab a packet off the queue. */
+		IF_DEQUEUE(&ifp->if_snd, m);
+		if (m == NULL) {
+			return;
+		}
+
+		tx_desc = NULL;
+		ret = prepare_fmn_message(sc, &msg, &n_entries, m, fr_stid, &tx_desc);
+		if (ret) {
+			goto fail;
+		}
+		sent = send_fmn_msg_tx(sc, &msg, n_entries);
+		if (!sent) {
+			goto fail;
+		}
+	} while(1);
+
+	return;
+
+fail:
+	if (tx_desc != NULL) {
+		uma_zfree(nl_tx_desc_zone, tx_desc);
+	}
+	if (m != NULL) {
+		/*
+		 * TBD: It is observed that only when both of the statements
+		 * below are not enabled, traffic continues till the end.
+		 * Otherwise, the port locks up in the middle and never
+		 * recovers from it. The current theory for this behavior
+		 * is that the queue is full and the upper layer is neither
+		 * able to add to it not invoke nlge_start to drian the
+		 * queue. The driver may have to do something in addition
+		 * to reset'ing the OACTIVE bit when a trasnmit free-back
+		 * is received.
+		 */
+		//ifp->if_drv_flags |= IFF_DRV_OACTIVE;
+		//IF_PREPEND(&ifp->if_snd, m);
+		m_freem(m);
+		ldadd_wu(1, &ifp->if_iqdrops);
+	}
+	return;
+}
+
+static void
+nlge_rx(struct nlge_softc *sc, vm_paddr_t paddr, int len)
+{
+	struct ifnet   *ifp;
+	struct mbuf    *m;
+	uint32_t tm, mag, sr;
+
+	sr = xlr_enable_kx();
+	tm = xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE);
+	mag = xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE + sizeof(uint32_t));
+	mips_wr_status(sr);
+
+	m = (struct mbuf *)(intptr_t)tm;
+	if (mag != 0xf00bad) {
+		/* somebody else's packet. Error - FIXME in intialization */
+		printf("cpu %d: *ERROR* Not my packet paddr %llx\n",
+		    xlr_core_id(), (uint64_t) paddr);
+		return;
+	}
+
+	ifp = sc->nlge_if;
+	/* align the data */
+	m->m_data += BYTE_OFFSET;
+	m->m_pkthdr.len = m->m_len = len;
+	m->m_pkthdr.rcvif = ifp;
+
+	ldadd_wu(1, &ifp->if_ipackets);
+	(*ifp->if_input)(ifp, m);
+}
+
+static int
+nlge_mii_write(struct device *dev, int phyaddr, int regidx, int regval)
+{
+	struct nlge_softc *sc;
+
+	sc = device_get_softc(dev);
+	if (sc->phy_addr == phyaddr && sc->port_type != XLR_XGMII)
+		nlge_mii_write_internal(sc->mii_base, phyaddr, regidx, regval);
+
+	return (0);
+}
+
+static int
+nlge_mii_read(struct device *dev, int phyaddr, int regidx)
+{
+	struct nlge_softc *sc;
+	int val;
+
+	sc = device_get_softc(dev);
+	val = (sc->phy_addr != phyaddr && sc->port_type != XLR_XGMII) ? (0xffff) :
+	    nlge_mii_read_internal(sc->mii_base, phyaddr, regidx);
+
+	return (val);
+}
+
+static void
+nlge_mac_mii_statchg(device_t dev)
+{
+}
+
+static int
+nlge_mediachange(struct ifnet *ifp)
+{
+	return 0;
+}
+
+static void
+nlge_mediastatus(struct ifnet *ifp, struct ifmediareq *ifmr)
+{
+	struct nlge_softc *sc;
+	struct mii_data *md;
+	
+	md = NULL;
+	sc = ifp->if_softc;
+	if (sc->mii_bus)
+		md = device_get_softc(sc->mii_bus);
+
+	ifmr->ifm_status = IFM_AVALID;
+	ifmr->ifm_active = IFM_ETHER;
+
+	if (sc->link == xlr_mac_link_down)
+		return;
+
+	if (md != NULL)
+		ifmr->ifm_active = md->mii_media.ifm_cur->ifm_media;
+	ifmr->ifm_status |= IFM_ACTIVE;
+}
+
+static struct nlna_softc *
+nlna_sc_init(device_t dev, struct xlr_gmac_block_t *blk)
+{
+	struct nlna_softc	*sc;
+
+	sc = device_get_softc(dev);
+	memset(sc, 0, sizeof(*sc));
+	sc->nlna_dev = dev;
+	sc->base = (xlr_reg_t *) blk->baseaddr;
+	sc->rfrbucket = blk->station_rfr;
+	sc->station_id = blk->station_id;
+	sc->na_type = blk->type;
+	sc->mac_type = blk->mode;
+	sc->num_ports = blk->num_ports;
+
+	sc->mdio_set.port_vec 	= sc->mdio_sc;
+	sc->mdio_set.vec_sz   	= XLR_MAX_MACS;
+
+	return (sc);
+}
+
+/*
+ * Do:
+ *     - Initialize common GMAC registers (index range 0x100-0x3ff).
+ */
+static void
+nlna_hw_init(struct nlna_softc *sc)
+{
+
+	/*
+	 * It is seen that this is a critical function in bringing up FreeBSD.
+	 * When it is not invoked, FreeBSD panics and fails during the
+	 * multi-processor init (SI_SUB_SMP of * mi_startup). The key function
+	 * in this sequence seems to be platform_prep_smp_launch. */
+	if (register_msgring_handler(sc->station_id, nlge_msgring_handler, sc)) {
+		panic("Couldn't register msgring handler\n");
+	}
+	nlna_config_fifo_spill_area(sc);
+	nlna_config_pde(sc);
+	nlna_config_common(sc);
+	nlna_config_parser(sc);
+	nlna_config_classifier(sc);
+}
+
+/*
+ * Enable interrupts on all the ports controlled by this NA. For now, we
+ * only care about the MII interrupt and this has to be enabled only
+ * on the port id0.
+ *
+ * This function is not in-sync with the regular way of doing things - it
+ * executes only in the context of the last active network accelerator (and
+ * thereby has some ugly accesses in the device tree). Though inelegant, it
+ * is necessary to do it this way as the per-port interrupts can be
+ * setup/enabled only after all the network accelerators have been
+ * initialized.
+ */
+static void
+nlna_setup_intr(struct nlna_softc *sc)
+{
+	struct nlna_softc *na_sc[XLR_MAX_NLNA];
+	struct nlge_port_set *pset;
+	struct xlr_gmac_port *port_info;
+	device_t	iodi_dev;
+	int 		i, j;
+
+	if (!nlna_is_last_active_na(sc))
+		return ;
+
+	/* Collect all nlna softc pointers */
+	memset(na_sc, 0, sizeof(*na_sc) * XLR_MAX_NLNA);
+	iodi_dev = device_get_parent(sc->nlna_dev);
+	nlna_get_all_softc(iodi_dev, na_sc, XLR_MAX_NLNA);
+
+	/* Setup the MDIO interrupt lists. */
+	/*
+	 * MDIO interrupts are coarse - a single interrupt line provides
+	 * information about one of many possible ports. To figure out the
+	 * exact port on which action is to be taken, all of the ports
+	 * linked to an MDIO interrupt should be read. To enable this,
+	 * ports need to add themselves to port sets.
+	 */
+	for (i = 0; i < XLR_MAX_NLNA; i++) {
+		if (na_sc[i] == NULL)
+			continue;
+		for (j = 0; j < na_sc[i]->num_ports; j++) {
+			/* processing j-th port on i-th NA */
+			port_info = device_get_ivars(
+			    na_sc[i]->child_sc[j]->nlge_dev);	
+			pset = &na_sc[port_info->mdint_id]->mdio_set;
+			nlna_add_to_port_set(pset, na_sc[i]->child_sc[j]);
+		}
+	}
+
+	/* Enable interrupts */
+	for (i = 0; i < XLR_MAX_NLNA; i++) {
+		if (na_sc[i] != NULL && na_sc[i]->na_type != XLR_XGMAC) {
+			nlna_enable_intr(na_sc[i]);
+		}
+	}
+}
+
+static void
+nlna_add_to_port_set(struct nlge_port_set *pset, struct nlge_softc *sc)
+{
+	int i;
+
+	/* step past the non-NULL elements */
+	for (i = 0; i < pset->vec_sz && pset->port_vec[i] != NULL; i++) ;
+	if (i < pset->vec_sz)
+		pset->port_vec[i] = sc;
+	else
+		printf("warning: internal error: out-of-bounds for MDIO array");
+}
+
+static void
+nlna_enable_intr(struct nlna_softc *sc)
+{
+	int i;
+
+	for (i = 0; i < sc->num_ports; i++) {
+		if (sc->child_sc[i]->instance == 0)
+			NLGE_WRITE(sc->child_sc[i]->base, R_INTMASK,
+			    (1 << O_INTMASK__MDInt));
+	}
+}
+
+static void
+nlna_disable_intr(struct nlna_softc *sc)
+{
+	int i;
+
+	for (i = 0; i < sc->num_ports; i++) {
+		if (sc->child_sc[i]->instance == 0)
+			NLGE_WRITE(sc->child_sc[i]->base, R_INTMASK, 0);
+	}
+}
+
+static int
+nlna_is_last_active_na(struct nlna_softc *sc)
+{
+	int id;
+
+	id = device_get_unit(sc->nlna_dev);
+	return (id == 2 || xlr_board_info.gmac_block[id + 1].enabled == 0);
+}
+
+static __inline__ int
+nlna_send_free_desc(struct nlna_softc *sc, vm_paddr_t addr)
+{
+	struct msgrng_msg msg;
+	int	stid;
+	int	code;
+	int 	i;
+
+	stid = sc->rfrbucket;
+	memset(&msg, 0, sizeof(msg));
+	msg.msg0 = (uint64_t) addr & 0xffffffffe0ULL;
+
+	code = (sc->na_type == XLR_XGMAC) ? MSGRNG_CODE_XGMAC : MSGRNG_CODE_MAC;
+	for (i = 0; i < MAX_MSG_SND_ATTEMPTS; i++) {
+		if (message_send(1, code, stid, &msg) == 0)
+			return (0);
+	}
+	printf("Error: failed to send free desc to station %d\n", stid);
+	return (1);
+}
+
+static void
+nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc)
+{
+	void           *ptr;
+	unsigned long	msgrng_flags;
+	int		i;
+	int		ret;
+
+	if (n_desc > 1) {
+		PDEBUG("Sending %d free-in descriptors to station=%d\n", n_desc,
+		    sc->rfrbucket);
+	}
+
+	for (i = 0; i < n_desc; i++) {
+		ptr = get_buf();
+		if (!ptr) {
+			ret = -ENOMEM;
+			device_printf(sc->nlna_dev, "Cannot allocate mbuf\n");
+			break;
+		}
+
+		/* Send the free Rx desc to the MAC */
+		msgrng_access_enable(msgrng_flags);
+		ret = nlna_send_free_desc(sc, vtophys(ptr));
+		msgrng_access_disable(msgrng_flags);
+		if (ret)  /* no point trying other descriptors after
+		             a failure. */
+			break;
+	}
+}
+
+static __inline__ void *
+nlna_config_spill(xlr_reg_t *base, int reg_start_0, int reg_start_1,
+    int reg_size, int size)
+{
+	void	*spill;
+	uint64_t phys_addr;
+	uint32_t spill_size;
+
+	spill_size = size;
+	spill = contigmalloc((spill_size + XLR_CACHELINE_SIZE), M_DEVBUF,
+	    M_NOWAIT | M_ZERO, 0, 0xffffffff, XLR_CACHELINE_SIZE, 0);
+	if (spill == NULL || ((vm_offset_t) spill & (XLR_CACHELINE_SIZE - 1))) {
+		panic("Unable to allocate memory for spill area!\n");
+	}
+	phys_addr = vtophys(spill);
+	PDEBUG("Allocated spill %d bytes at %llx\n", size, phys_addr);
+	NLGE_WRITE(base, reg_start_0, (phys_addr >> 5) & 0xffffffff);
+	NLGE_WRITE(base, reg_start_1, (phys_addr >> 37) & 0x07);
+	NLGE_WRITE(base, reg_size, spill_size);
+
+	return (spill);
+}
+
+/*
+ * Configure the 6 FIFO's that are used by the network accelarator to
+ * communicate with the rest of the XLx device. 4 of the FIFO's are for
+ * packets from NA --> cpu (called Class FIFO's) and 2 are for feeding
+ * the NA with free descriptors.
+ */
+static void
+nlna_config_fifo_spill_area(struct nlna_softc *sc)
+{
+	sc->frin_spill = nlna_config_spill(sc->base,
+				     	R_REG_FRIN_SPILL_MEM_START_0,
+				     	R_REG_FRIN_SPILL_MEM_START_1,
+				     	R_REG_FRIN_SPILL_MEM_SIZE,
+				     	MAX_FRIN_SPILL *
+				     	sizeof(struct fr_desc));
+	sc->frout_spill = nlna_config_spill(sc->base,
+				     	R_FROUT_SPILL_MEM_START_0,
+				     	R_FROUT_SPILL_MEM_START_1,
+				     	R_FROUT_SPILL_MEM_SIZE,
+				     	MAX_FROUT_SPILL *
+				     	sizeof(struct fr_desc));
+	sc->class_0_spill = nlna_config_spill(sc->base,
+				     	R_CLASS0_SPILL_MEM_START_0,
+				     	R_CLASS0_SPILL_MEM_START_1,
+				     	R_CLASS0_SPILL_MEM_SIZE,
+				     	MAX_CLASS_0_SPILL *
+				     	sizeof(union rx_tx_desc));
+	sc->class_1_spill = nlna_config_spill(sc->base,
+				     	R_CLASS1_SPILL_MEM_START_0,
+				     	R_CLASS1_SPILL_MEM_START_1,
+				     	R_CLASS1_SPILL_MEM_SIZE,
+				     	MAX_CLASS_1_SPILL *
+				     	sizeof(union rx_tx_desc));
+	sc->class_2_spill = nlna_config_spill(sc->base,
+				     	R_CLASS2_SPILL_MEM_START_0,
+				     	R_CLASS2_SPILL_MEM_START_1,
+				     	R_CLASS2_SPILL_MEM_SIZE,
+				     	MAX_CLASS_2_SPILL *
+				     	sizeof(union rx_tx_desc));
+	sc->class_3_spill = nlna_config_spill(sc->base,
+				     	R_CLASS3_SPILL_MEM_START_0,
+				     	R_CLASS3_SPILL_MEM_START_1,
+				     	R_CLASS3_SPILL_MEM_SIZE,
+				     	MAX_CLASS_3_SPILL *
+				     	sizeof(union rx_tx_desc));
+}
+
+/* Set the CPU buckets that receive packets from the NA class FIFOs. */
+static void
+nlna_config_pde(struct nlna_softc *sc)
+{
+	uint64_t	bucket_map;
+	uint32_t	cpumask;
+	int		i, cpu, bucket;
+
+	cpumask = 0x1;
+#ifdef SMP
+	/*
+         * rge may be called before SMP start in a BOOTP/NFSROOT
+         * setup. we will distribute packets to other cpus only when
+         * the SMP is started.
+	 */
+	if (smp_started)
+		cpumask = xlr_hw_thread_mask;
+#endif
+
+	bucket_map = 0;
+	for (i = 0; i < 32; i++) {
+		if (cpumask & (1 << i)) {
+			cpu = i;
+			bucket = ((cpu >> 2) << 3);
+			bucket_map |= (1ULL << bucket);
+		}
+	}
+	NLGE_WRITE(sc->base, R_PDE_CLASS_0, (bucket_map & 0xffffffff));
+	NLGE_WRITE(sc->base, R_PDE_CLASS_0 + 1, ((bucket_map >> 32) & 0xffffffff));
+
+	NLGE_WRITE(sc->base, R_PDE_CLASS_1, (bucket_map & 0xffffffff));
+	NLGE_WRITE(sc->base, R_PDE_CLASS_1 + 1, ((bucket_map >> 32) & 0xffffffff));
+
+	NLGE_WRITE(sc->base, R_PDE_CLASS_2, (bucket_map & 0xffffffff));
+	NLGE_WRITE(sc->base, R_PDE_CLASS_2 + 1, ((bucket_map >> 32) & 0xffffffff));
+
+	NLGE_WRITE(sc->base, R_PDE_CLASS_3, (bucket_map & 0xffffffff));
+	NLGE_WRITE(sc->base, R_PDE_CLASS_3 + 1, ((bucket_map >> 32) & 0xffffffff));
+}
+
+static void
+nlna_smp_update_pde(void *dummy __unused)
+{
+	device_t	   iodi_dev;
+	struct nlna_softc *na_sc[XLR_MAX_NLNA];
+	int i;
+
+	printf("Updating packet distribution for SMP\n");
+
+	iodi_dev = devclass_get_device(devclass_find("iodi"), 0);
+	nlna_get_all_softc(iodi_dev, na_sc, XLR_MAX_NLNA);
+
+	for (i = 0; i < XLR_MAX_NLNA; i++) {
+		if (na_sc[i] == NULL)
+			continue;
+		nlna_disable_ports(na_sc[i]);
+		nlna_config_pde(na_sc[i]);
+		nlna_enable_ports(na_sc[i]);
+	}
+}
+
+SYSINIT(nlna_smp_update_pde, SI_SUB_SMP, SI_ORDER_ANY, nlna_smp_update_pde,
+    NULL);
+
+static void
+nlna_config_parser(struct nlna_softc *sc)
+{
+	/*
+	 * Mark it as no classification. The parser extract is gauranteed to
+	 * be zero with no classfication
+	 */
+	NLGE_WRITE(sc->base, R_L2TYPE_0, 0x00);
+	NLGE_WRITE(sc->base, R_L2TYPE_0, 0x01);
+
+	/* configure the parser : L2 Type is configured in the bootloader */
+	/* extract IP: src, dest protocol */
+	NLGE_WRITE(sc->base, R_L3CTABLE,
+	    (9 << 20) | (1 << 19) | (1 << 18) | (0x01 << 16) |
+	    (0x0800 << 0));
+	NLGE_WRITE(sc->base, R_L3CTABLE + 1,
+	    (12 << 25) | (4 << 21) | (16 << 14) | (4 << 10));
+}
+
+static void
+nlna_config_classifier(struct nlna_softc *sc)
+{
+	int i;
+
+	if (sc->mac_type == XLR_XGMII) {	/* TBD: XGMII init sequence */
+		/* xgmac translation table doesn't have sane values on reset */
+		for (i = 0; i < 64; i++)
+			NLGE_WRITE(sc->base, R_TRANSLATETABLE + i, 0x0);
+
+		/*
+		 * use upper 7 bits of the parser extract to index the
+		 * translate table
+		 */
+		NLGE_WRITE(sc->base, R_PARSERCONFIGREG, 0x0);
+	}
+}
+
+/*
+ * Complete a bunch of h/w register initializations that are common for all the
+ * ports controlled by a NA.
+ */
+static void
+nlna_config_common(struct nlna_softc *sc)
+{
+	struct xlr_gmac_block_t *block_info;
+	struct stn_cc 		*gmac_cc_config;
+	int			i, id;
+
+	block_info = device_get_ivars(sc->nlna_dev);
+
+	id = device_get_unit(sc->nlna_dev);
+	gmac_cc_config = block_info->credit_config;
+	for (i = 0; i < MAX_NUM_MSGRNG_STN_CC; i++) {
+		NLGE_WRITE(sc->base, R_CC_CPU0_0 + i,
+		    gmac_cc_config->counters[i >> 3][i & 0x07]);
+	}
+
+	NLGE_WRITE(sc->base, R_MSG_TX_THRESHOLD, 3);
+
+	NLGE_WRITE(sc->base, R_DMACR0, 0xffffffff);
+	NLGE_WRITE(sc->base, R_DMACR1, 0xffffffff);
+	NLGE_WRITE(sc->base, R_DMACR2, 0xffffffff);
+	NLGE_WRITE(sc->base, R_DMACR3, 0xffffffff);
+	NLGE_WRITE(sc->base, R_FREEQCARVE, 0);
+
+	nlna_media_specific_config(sc);
+}
+
+static void
+nlna_media_specific_config(struct nlna_softc *sc)
+{
+	struct bucket_size *bucket_sizes;
+
+	bucket_sizes = xlr_board_info.bucket_sizes;
+	switch (sc->mac_type) {
+	case XLR_RGMII:
+	case XLR_SGMII:
+	case XLR_XAUI:
+		NLGE_WRITE(sc->base, R_GMAC_JFR0_BUCKET_SIZE,
+		    bucket_sizes->bucket[MSGRNG_STNID_GMACJFR_0]);
+		NLGE_WRITE(sc->base, R_GMAC_RFR0_BUCKET_SIZE,
+		    bucket_sizes->bucket[MSGRNG_STNID_GMACRFR_0]);
+		NLGE_WRITE(sc->base, R_GMAC_JFR1_BUCKET_SIZE,
+		    bucket_sizes->bucket[MSGRNG_STNID_GMACJFR_1]);
+		NLGE_WRITE(sc->base, R_GMAC_RFR1_BUCKET_SIZE,
+		    bucket_sizes->bucket[MSGRNG_STNID_GMACRFR_1]);
+
+		if (sc->mac_type == XLR_XAUI) {
+			NLGE_WRITE(sc->base, R_TXDATAFIFO0, (224 << 16));
+		}
+		break;
+	
+	case XLR_XGMII:
+		NLGE_WRITE(sc->base, R_XGS_RFR_BUCKET_SIZE,
+		    bucket_sizes->bucket[sc->rfrbucket]);
+
+	default:
+		break;
+	}
+}
+
+static void
+nlna_reset_ports(struct nlna_softc *sc, struct xlr_gmac_block_t *blk)
+{
+	xlr_reg_t *addr;
+	int i;
+	uint32_t   rx_ctrl;
+
+	/* Refer Section 13.9.3 in the PRM for the reset sequence */
+
+	for (i = 0; i < sc->num_ports; i++) {
+		uint32_t base = (uint32_t)DEFAULT_XLR_IO_BASE;
+
+		base += blk->gmac_port[i].base_addr;
+		addr = (xlr_reg_t *) base;
+
+		/* 1. Reset RxEnable in MAC_CONFIG */
+		switch (sc->mac_type) {
+		case XLR_RGMII:
+		case XLR_SGMII:
+			NLGE_UPDATE(addr, R_MAC_CONFIG_1, 0,
+			    (1 << O_MAC_CONFIG_1__rxen));
+			break;
+		case XLR_XAUI:
+		case XLR_XGMII:
+			NLGE_UPDATE(addr, R_RX_CONTROL, 0,
+			   (1 << O_RX_CONTROL__RxEnable));
+			break;
+		default:
+			printf("Error: Unsupported port_type=%d\n",
+			    sc->mac_type);
+		}
+
+		/* 1.1 Wait for RxControl.RxHalt to be set */
+		do {
+			rx_ctrl = NLGE_READ(addr, R_RX_CONTROL);
+		} while (!(rx_ctrl & 0x2));
+
+		/* 2. Set the soft reset bit in RxControl */
+		NLGE_UPDATE(addr, R_RX_CONTROL, (1 << O_RX_CONTROL__SoftReset),
+		    (1 << O_RX_CONTROL__SoftReset));
+
+		/* 2.1 Wait for RxControl.SoftResetDone to be set */
+		do {
+			rx_ctrl = NLGE_READ(addr, R_RX_CONTROL);
+		} while (!(rx_ctrl & 0x8));
+
+		/* 3. Clear the soft reset bit in RxControl */
+		NLGE_UPDATE(addr, R_RX_CONTROL, 0,
+		    (1 << O_RX_CONTROL__SoftReset));
+
+		/* Turn off tx/rx on the port. */
+		NLGE_UPDATE(addr, R_RX_CONTROL, 0,
+		    (1 << O_RX_CONTROL__RxEnable));
+		NLGE_UPDATE(addr, R_TX_CONTROL, 0,
+		    (1 << O_TX_CONTROL__TxEnable));
+	}
+}
+
+static void
+nlna_disable_ports(struct nlna_softc *sc)
+{
+	struct xlr_gmac_block_t *blk;
+	xlr_reg_t *addr;
+	int i;
+
+	blk = device_get_ivars(sc->nlna_dev);
+	for (i = 0; i < sc->num_ports; i++) {
+		uint32_t base = (uint32_t)DEFAULT_XLR_IO_BASE;
+
+		base += blk->gmac_port[i].base_addr;
+		addr = (xlr_reg_t *) base;
+		nlge_port_disable(i, addr, blk->gmac_port[i].type);
+	}
+}
+
+static void
+nlna_enable_ports(struct nlna_softc *sc)
+{
+	device_t		nlge_dev, *devlist;
+	struct nlge_softc 	*port_sc;
+	int 			i, numdevs;
+
+	device_get_children(sc->nlna_dev, &devlist, &numdevs);
+	for (i = 0; i < numdevs; i++) {
+		nlge_dev = devlist[i];
+		if (nlge_dev == NULL)
+			continue;
+		port_sc = device_get_softc(nlge_dev);
+		if (port_sc->nlge_if->if_drv_flags & IFF_DRV_RUNNING)
+			nlge_port_enable(port_sc);
+	}
+	free(devlist, M_TEMP);
+}
+
+static void
+nlna_get_all_softc(device_t iodi_dev, struct nlna_softc **sc_vec,
+		   uint32_t vec_sz)
+{
+	device_t  na_dev;
+	int       i;
+
+	for (i = 0; i < vec_sz; i++) {
+		sc_vec[i] = NULL;
+		na_dev = device_find_child(iodi_dev, "nlna", i);
+		if (na_dev != NULL)
+			sc_vec[i] = device_get_softc(na_dev);
+	}
+}
+
+static void
+nlge_port_disable(int id, xlr_reg_t *base, int port_type)
+{
+	uint32_t rd;
+
+	NLGE_UPDATE(base, R_RX_CONTROL, 0x0, 1 << O_RX_CONTROL__RxEnable);
+	do {
+		rd = NLGE_READ(base, R_RX_CONTROL);
+	} while (!(rd & (1 << O_RX_CONTROL__RxHalt)));
+
+	NLGE_UPDATE(base, R_TX_CONTROL, 0, 1 << O_TX_CONTROL__TxEnable);
+	do {
+		rd = NLGE_READ(base, R_TX_CONTROL);
+	} while (!(rd & (1 << O_TX_CONTROL__TxIdle)));
+
+	switch (port_type) {
+	case XLR_RGMII:
+	case XLR_SGMII:
+		NLGE_UPDATE(base, R_MAC_CONFIG_1, 0,
+		   ((1 << O_MAC_CONFIG_1__rxen) |
+		   (1 << O_MAC_CONFIG_1__txen)));
+		break;
+	case XLR_XGMII:
+	case XLR_XAUI:
+		NLGE_UPDATE(base, R_XGMAC_CONFIG_1, 0,
+		   ((1 << O_XGMAC_CONFIG_1__hsttfen) |
+		   (1 << O_XGMAC_CONFIG_1__hstrfen)));
+		break;
+	default:
+		panic("Unknown MAC type on port %d\n", id);
+	}
+}
+
+static void
+nlge_port_enable(struct nlge_softc *sc)
+{
+	struct xlr_gmac_port  *self;
+	xlr_reg_t *base;
+
+	base = sc->base;
+	self = device_get_ivars(sc->nlge_dev);
+	if (xlr_board_info.is_xls && sc->port_type == XLR_RGMII)
+		NLGE_UPDATE(base, R_RX_CONTROL, (1 << O_RX_CONTROL__RGMII),
+	    	    (1 << O_RX_CONTROL__RGMII));
+
+	NLGE_UPDATE(base, R_RX_CONTROL, (1 << O_RX_CONTROL__RxEnable),
+	    (1 << O_RX_CONTROL__RxEnable));
+	NLGE_UPDATE(base, R_TX_CONTROL,
+	    (1 << O_TX_CONTROL__TxEnable | RGE_TX_THRESHOLD_BYTES),
+	    (1 << O_TX_CONTROL__TxEnable | 0x3fff));
+	switch (sc->port_type) {
+	case XLR_RGMII:
+	case XLR_SGMII:
+		NLGE_UPDATE(base, R_MAC_CONFIG_1,
+		    ((1 << O_MAC_CONFIG_1__rxen) | (1 << O_MAC_CONFIG_1__txen)),
+		    ((1 << O_MAC_CONFIG_1__rxen) | (1 << O_MAC_CONFIG_1__txen)));
+		break;
+	case XLR_XGMII:
+	case XLR_XAUI:
+		NLGE_UPDATE(base, R_XGMAC_CONFIG_1,
+		    ((1 << O_XGMAC_CONFIG_1__hsttfen) | (1 << O_XGMAC_CONFIG_1__hstrfen)),
+		    ((1 << O_XGMAC_CONFIG_1__hsttfen) | (1 << O_XGMAC_CONFIG_1__hstrfen)));
+		break;
+	default:
+		panic("Unknown MAC type on port %d\n", sc->id);
+	}
+}
+
+static void
+nlge_sgmii_init(struct nlge_softc *sc)
+{
+	xlr_reg_t *mmio_gpio;
+	int i;
+	int phy;
+
+	if (sc->port_type != XLR_SGMII)
+		return;
+
+	nlge_mii_write_internal(sc->serdes_addr, 26, 0, 0x6DB0);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 1, 0xFFFF);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 2, 0xB6D0);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 3, 0x00FF);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 4, 0x0000);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 5, 0x0000);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 6, 0x0005);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 7, 0x0001);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 8, 0x0000);
+	nlge_mii_write_internal(sc->serdes_addr, 26, 9, 0x0000);
+	nlge_mii_write_internal(sc->serdes_addr, 26,10, 0x0000);
+
+	for(i=0;i<10000000;i++){}	/* delay */
+	/* program  GPIO values for serdes init parameters */
+	mmio_gpio = (xlr_reg_t *) (DEFAULT_XLR_IO_BASE + XLR_IO_GPIO_OFFSET);
+	mmio_gpio[0x20] = 0x7e6802;
+	mmio_gpio[0x10] = 0x7104;
+	for(i=0;i<100000000;i++){}
+
+	/* enable autoneg - more magic */
+	phy = sc->phy_addr % 4 + 27;
+	nlge_mii_write_internal(sc->pcs_addr, phy, 0, 0x1000);
+	DELAY(100000);
+	nlge_mii_write_internal(sc->pcs_addr, phy, 0, 0x0200);
+	DELAY(100000);
+}
+
+static void
+nlge_intr(void *arg)
+{
+	struct nlge_port_set    *pset;
+	struct nlge_softc 	*sc;
+	struct nlge_softc 	*port_sc;
+	xlr_reg_t 		*base;
+	uint32_t		intreg;
+	uint32_t		intr_status;
+	int 			i;
+
+	sc = arg;
+	if (sc == NULL) {
+		printf("warning: No port registered for interrupt\n");
+		return;
+	}
+	base = sc->base;
+
+	intreg = NLGE_READ(base, R_INTREG);
+	if (intreg & (1 << O_INTREG__MDInt)) {
+		pset = sc->mdio_pset;
+		if (pset == NULL) {
+			printf("warning: No ports for MDIO interrupt\n");
+			return;
+		}
+		for (i = 0; i < pset->vec_sz; i++) {
+			port_sc = pset->port_vec[i];
+
+			if (port_sc == NULL)
+				continue;
+
+			/* Ack phy interrupt - clear on read*/
+			intr_status = nlge_mii_read_internal(port_sc->mii_base,
+			    port_sc->phy_addr, 26);
+			PDEBUG("Phy_%d: int_status=0x%08x\n", port_sc->phy_addr,
+			    intr_status);
+
+			if (!(intr_status & 0x8000)) {
+				/* no interrupt for this port */
+				continue;
+			}
+
+			if (intr_status & 0x2410) {
+				/* update link status for port */
+				nlge_gmac_config_speed(port_sc, 0);
+			} else {
+				printf("%s: Unsupported phy interrupt"
+				    " (0x%08x)\n",
+				    device_get_nameunit(port_sc->nlge_dev),
+				    intr_status);
+			}
+		}
+	}
+
+	/* Clear the NA interrupt */
+	xlr_write_reg(base, R_INTREG, 0xffffffff);
+
+	return;
+}
+
+static int
+nlge_irq_init(struct nlge_softc *sc)
+{
+	struct resource		irq_res;
+	struct nlna_softc  	*na_sc;
+	struct xlr_gmac_block_t *block_info;
+	device_t		na_dev;
+	int			ret;
+	int			irq_num;
+
+	na_dev = device_get_parent(sc->nlge_dev);
+	block_info = device_get_ivars(na_dev);
+
+	irq_num = block_info->baseirq + sc->instance;
+	irq_res.__r_i = (struct resource_i *)(intptr_t) (irq_num);
+	ret = bus_setup_intr(sc->nlge_dev, &irq_res, (INTR_FAST |
+	    INTR_TYPE_NET | INTR_MPSAFE), NULL, nlge_intr, sc, NULL);
+	if (ret) {
+		nlge_detach(sc->nlge_dev);
+		device_printf(sc->nlge_dev, "couldn't set up irq: error=%d\n",
+		    ret);
+		return (ENXIO);
+	}
+	PDEBUG("Setup intr for dev=%s, irq=%d\n",
+	    device_get_nameunit(sc->nlge_dev), irq_num);
+	
+	if (sc->instance == 0) {
+		na_sc = device_get_softc(na_dev);
+		sc->mdio_pset = &na_sc->mdio_set;
+	}
+	return (0);
+}
+
+static void
+nlge_irq_fini(struct nlge_softc *sc)
+{
+}
+
+static void
+nlge_hw_init(struct nlge_softc *sc)
+{
+	struct xlr_gmac_port  *port_info;
+	xlr_reg_t *base;
+
+	base = sc->base;
+	port_info = device_get_ivars(sc->nlge_dev);
+	sc->tx_bucket_id = port_info->tx_bucket_id;
+
+	/* each packet buffer is 1536 bytes */
+	NLGE_WRITE(base, R_DESC_PACK_CTRL,
+		  (1 << O_DESC_PACK_CTRL__MaxEntry) |
+		  (MAX_FRAME_SIZE << O_DESC_PACK_CTRL__RegularSize));
+	NLGE_WRITE(base, R_STATCTRL, ((1 << O_STATCTRL__Sten) |
+	    (1 << O_STATCTRL__ClrCnt)));
+	NLGE_WRITE(base, R_L2ALLOCCTRL, 0xffffffff);
+	NLGE_WRITE(base, R_INTMASK, 0);
+	nlge_set_mac_addr(sc);
+	nlge_media_specific_init(sc);
+}
+
+static void
+nlge_sc_init(struct nlge_softc *sc, device_t dev,
+    struct xlr_gmac_port *port_info)
+{
+	memset(sc, 0, sizeof(*sc));
+	sc->nlge_dev = dev;
+	sc->id = device_get_unit(dev);
+	nlge_set_port_attribs(sc, port_info);
+}
+
+static void
+nlge_media_specific_init(struct nlge_softc *sc)
+{
+	struct mii_data *media;
+	struct bucket_size *bucket_sizes;
+
+	bucket_sizes = xlr_board_info.bucket_sizes;
+	switch (sc->port_type) {
+	case XLR_RGMII:
+	case XLR_SGMII:
+	case XLR_XAUI:
+		NLGE_UPDATE(sc->base, R_DESC_PACK_CTRL,
+		    (BYTE_OFFSET << O_DESC_PACK_CTRL__ByteOffset),
+		    (W_DESC_PACK_CTRL__ByteOffset <<
+		        O_DESC_PACK_CTRL__ByteOffset));
+		NLGE_WRITE(sc->base, R_GMAC_TX0_BUCKET_SIZE + sc->instance,
+		    bucket_sizes->bucket[sc->tx_bucket_id]);
+		if (sc->port_type != XLR_XAUI) {
+			nlge_gmac_config_speed(sc, 1);
+			if (sc->mii_bus) {
+				media = (struct mii_data *)device_get_softc(
+				    sc->mii_bus);
+			}
+		}
+		break;
+
+	case XLR_XGMII:
+		NLGE_WRITE(sc->base, R_BYTEOFFSET0, 0x2);
+		NLGE_WRITE(sc->base, R_XGMACPADCALIBRATION, 0x30);
+		NLGE_WRITE(sc->base, R_XGS_TX0_BUCKET_SIZE,
+		    bucket_sizes->bucket[sc->tx_bucket_id]);
+		break;
+	default:
+		break;
+	}
+}
+
+/*
+ * Read the MAC address from the XLR boot registers. All port addresses
+ * are identical except for the lowest octet.
+ */
+static void
+nlge_read_mac_addr(struct nlge_softc *sc)
+{
+	int i, j;
+
+	for (i = 0, j = 40; i < ETHER_ADDR_LEN && j >= 0; i++, j-= 8)
+		sc->dev_addr[i] = (xlr_boot1_info.mac_addr >> j) & 0xff;
+
+	sc->dev_addr[i - 1] +=  sc->id;	/* last octet is port-specific */
+}
+
+/*
+ * Write the MAC address to the XLR MAC port. Also, set the address
+ * masks and MAC filter configuration.
+ */
+static void
+nlge_set_mac_addr(struct nlge_softc *sc)
+{
+	NLGE_WRITE(sc->base, R_MAC_ADDR0,
+		  ((sc->dev_addr[5] << 24) | (sc->dev_addr[4] << 16) |
+		   (sc->dev_addr[3] << 8) | (sc->dev_addr[2])));
+	NLGE_WRITE(sc->base, R_MAC_ADDR0 + 1,
+		  ((sc->dev_addr[1] << 24) | (sc-> dev_addr[0] << 16)));
+
+	NLGE_WRITE(sc->base, R_MAC_ADDR_MASK2, 0xffffffff);
+	NLGE_WRITE(sc->base, R_MAC_ADDR_MASK2 + 1, 0xffffffff);
+	NLGE_WRITE(sc->base, R_MAC_ADDR_MASK3, 0xffffffff);
+	NLGE_WRITE(sc->base, R_MAC_ADDR_MASK3 + 1, 0xffffffff);
+
+	NLGE_WRITE(sc->base, R_MAC_FILTER_CONFIG,
+		  (1 << O_MAC_FILTER_CONFIG__BROADCAST_EN) |
+		  (1 << O_MAC_FILTER_CONFIG__ALL_MCAST_EN) |
+		  (1 << O_MAC_FILTER_CONFIG__MAC_ADDR0_VALID));
+
+	if (sc->port_type == XLR_RGMII || sc->port_type == XLR_SGMII) {
+		NLGE_UPDATE(sc->base, R_IPG_IFG, MAC_B2B_IPG, 0x7f);
+	}
+}
+
+static int
+nlge_if_init(struct nlge_softc *sc)
+{
+	struct ifnet 	*ifp;
+	device_t	dev;
+	int error;
+
+	error = 0;
+	dev = sc->nlge_dev;
+	NLGE_LOCK_INIT(sc, device_get_nameunit(dev));
+
+	ifp = sc->nlge_if = if_alloc(IFT_ETHER);
+	if (ifp == NULL) {
+		device_printf(dev, "can not if_alloc()\n");
+		error = ENOSPC;
+		goto fail;
+	}
+	ifp->if_softc = sc;
+	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
+	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
+	ifp->if_capabilities = IFCAP_TXCSUM | IFCAP_VLAN_HWTAGGING;
+	ifp->if_capenable = ifp->if_capabilities;
+	ifp->if_ioctl = nlge_ioctl;
+	ifp->if_start = nlge_start;
+	ifp->if_init = nlge_init;
+	ifp->if_hwassist = 0;
+	ifp->if_snd.ifq_drv_maxlen = RGE_TX_Q_SIZE;
+	IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
+	IFQ_SET_READY(&ifp->if_snd);
+
+	ifmedia_init(&sc->nlge_mii.mii_media, 0, nlge_mediachange,
+	    nlge_mediastatus);
+	ifmedia_add(&sc->nlge_mii.mii_media, IFM_ETHER | IFM_AUTO, 0, NULL);
+	ifmedia_set(&sc->nlge_mii.mii_media, IFM_ETHER | IFM_AUTO);
+	sc->nlge_mii.mii_media.ifm_media = sc->nlge_mii.mii_media.ifm_cur->ifm_media;
+	nlge_read_mac_addr(sc);
+
+	ether_ifattach(ifp, sc->dev_addr);
+
+fail:
+	return (error);
+}
+
+static void
+nlge_mii_init(device_t dev, struct nlge_softc *sc)
+{
+	int error;
+
+	if (sc->port_type != XLR_XAUI && sc->port_type != XLR_XGMII) {
+		NLGE_WRITE(sc->mii_base, R_MII_MGMT_CONFIG, 0x07);
+	}
+	error = mii_phy_probe(dev, &sc->mii_bus, nlge_mediachange, nlge_mediastatus);
+	if (error) {
+		device_printf(dev, "no PHY device found\n");
+		sc->mii_bus = NULL;
+	}
+	if (sc->mii_bus != NULL) {
+		/*
+		 * Enable all MDIO interrupts in the phy. RX_ER bit seems to get
+		 * set about every 1 sec in GigE mode, ignore it for now...
+		 */
+		nlge_mii_write_internal(sc->mii_base, sc->phy_addr, 25,
+		    0xfffffffe);
+	}
+}
+
+/*
+ *  Read a PHY register.
+ *
+ *  Input parameters:
+ *  	   mii_base - Base address of MII
+ *  	   phyaddr - PHY's address
+ *  	   regidx = index of register to read
+ *
+ *  Return value:
+ *  	   value read, or 0 if an error occurred.
+ */
+
+static int
+nlge_mii_read_internal(xlr_reg_t *mii_base, int phyaddr, int regidx)
+{
+	int i, val;
+
+	/* setup the phy reg to be used */
+	NLGE_WRITE(mii_base, R_MII_MGMT_ADDRESS,
+	    (phyaddr << 8) | (regidx << 0));
+	/* Issue the read command */
+	NLGE_WRITE(mii_base, R_MII_MGMT_COMMAND,
+	    (1 << O_MII_MGMT_COMMAND__rstat));
+
+	/* poll for the read cycle to complete */
+	for (i = 0; i < PHY_STATUS_RETRIES; i++) {
+		if (NLGE_READ(mii_base, R_MII_MGMT_INDICATORS) == 0)
+			break;
+	}
+
+	/* clear the read cycle */
+	NLGE_WRITE(mii_base, R_MII_MGMT_COMMAND, 0);
+
+	if (i == PHY_STATUS_RETRIES) {
+		return (0xffffffff);
+	}
+
+	val = NLGE_READ(mii_base, R_MII_MGMT_STATUS);
+
+	return (val);
+}
+
+/*
+ *  Write a value to a PHY register.
+ *
+ *  Input parameters:
+ *  	   mii_base - Base address of MII
+ *  	   phyaddr - PHY to use
+ *  	   regidx - register within the PHY
+ *  	   regval - data to write to register
+ *
+ *  Return value:
+ *  	   nothing
+ */
+static void
+nlge_mii_write_internal(xlr_reg_t *mii_base, int phyaddr, int regidx,
+    int regval)
+{
+	int i;
+
+	NLGE_WRITE(mii_base, R_MII_MGMT_ADDRESS,
+	   (phyaddr << 8) | (regidx << 0));
+
+	/* Write the data which starts the write cycle */
+	NLGE_WRITE(mii_base, R_MII_MGMT_WRITE_DATA, regval);
+
+	/* poll for the write cycle to complete */
+	for (i = 0; i < PHY_STATUS_RETRIES; i++) {
+		if (NLGE_READ(mii_base, R_MII_MGMT_INDICATORS) == 0)
+			break;
+	}
+}
+
+/*
+ * Function to optimize the use of p2d descriptors for the given PDU.
+ * As it is on the fast-path (called during packet transmission), it
+ * described in more detail than the initialization functions.
+ *
+ * Input: mbuf chain (MC), pointer to fmn message
+ * Input constraints: None
+ * Output: FMN message to transmit the data in MC
+ * Return values: 0 - success
+ *                1 - MC cannot be handled (see Limitations below)
+ *                2 - MC cannot be handled presently (maybe worth re-trying)
+ * Other output: Number of entries filled in the FMN message
+ *
+ * Output structure/constraints:
+ *     1. Max 3 p2d's + 1 zero-len (ZL) p2d with virtual address of MC.
+ *     2. 3 p2d's + 1 p2p with max 14 p2d's (ZL p2d not required in this case).
+ *     3. Each p2d points to physically contiguous chunk of data (subject to
+ *        entire MC requiring max 17 p2d's).
+ * Limitations:
+ *     1. MC's that require more than 17 p2d's are not handled.
+ * Benefits: MC's that require <= 3 p2d's avoid the overhead of allocating
+ *           the p2p structure. Small packets (which typically give low
+ *           performance) are expected to have a small MC that takes
+ *           advantage of this.
+ */
+static int
+prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg,
+    uint32_t *n_entries, struct mbuf *mbuf_chain, uint64_t fb_stn_id, 
+    struct nlge_tx_desc **tx_desc)
+{
+	struct mbuf     *m;
+	struct nlge_tx_desc *p2p;
+	uint64_t        *cur_p2d;
+	vm_offset_t	buf;
+	vm_paddr_t      paddr;
+	int             msg_sz, p2p_sz, is_p2p;
+	int             len, frag_sz;
+	/* Num entries per FMN msg is 4 for XLR/XLS */
+	const int       FMN_SZ = sizeof(*fmn_msg) / sizeof(uint64_t);
+
+	msg_sz = p2p_sz = is_p2p = 0;
+	p2p = NULL;
+	cur_p2d = &fmn_msg->msg0;
+
+	for (m = mbuf_chain; m != NULL; m = m->m_next) {
+		buf = (vm_offset_t) m->m_data;
+		len = m->m_len;
+
+		while (len) {
+			if (msg_sz == (FMN_SZ - 1)) {
+				p2p = uma_zalloc(nl_tx_desc_zone, M_NOWAIT);
+			if (p2p == NULL)
+				return 2;
+				/*
+				 * As we currently use xlr_paddr_lw on a 32-bit
+				 * OS, both the pointers are laid out in one
+				 * 64-bit location - this makes it easy to
+				 * retrieve the pointers when processing the
+				 * tx free-back descriptor.
+				 */
+				p2p->frag[XLR_MAX_TX_FRAGS] =
+				    (((uint64_t) (vm_offset_t) p2p) << 32) |
+				    ((vm_offset_t) mbuf_chain);
+				cur_p2d = &p2p->frag[0];
+				is_p2p = 1;
+			} else if (msg_sz == (FMN_SZ - 1 + XLR_MAX_TX_FRAGS)) {
+				uma_zfree(nl_tx_desc_zone, p2p);
+				return 1;
+			}
+			paddr = vtophys(buf);
+			frag_sz = PAGE_SIZE - (buf & PAGE_MASK) ;
+			if (len < frag_sz)
+				frag_sz = len;
+			*cur_p2d++ = (127ULL << 54) | ((uint64_t)frag_sz << 40)
+			    | paddr;
+			msg_sz++;
+			if (is_p2p)
+				p2p_sz++;
+			len -= frag_sz;
+			buf += frag_sz;
+		}
+	}
+
+	if (msg_sz > 0) {
+		cur_p2d[-1] |= (1ULL << 63); /* set eop in most-recent p2d */
+	} else {
+		printf("Zero-length mbuf chain ??\n");
+		*n_entries = msg_sz ;
+		return 0;
+	}
+
+	*tx_desc = p2p;
+
+	if (is_p2p) {
+		paddr = vtophys(p2p);
+		fmn_msg->msg3 = (1ULL << 63) | (1ULL << 62) |
+		    ((uint64_t)fb_stn_id << 54) |
+		    ((uint64_t)(p2p_sz * 8) << 40) | paddr;
+		*n_entries = FMN_SZ;
+	} else {
+		/* zero-len p2d */
+		*cur_p2d = (1ULL << 63) | ((uint64_t)fb_stn_id << 54) |
+		     (vm_offset_t) mbuf_chain;
+		*n_entries = msg_sz + 1;
+	}
+
+	return (0);
+}
+
+static int
+send_fmn_msg_tx(struct nlge_softc *sc, struct msgrng_msg *msg,
+    uint32_t n_entries)
+{
+	unsigned long mflags;
+	int ret;
+
+	mflags = 0;
+	msgrng_access_enable(mflags);
+	ret = message_send_retry(n_entries, MSGRNG_CODE_MAC, sc->tx_bucket_id,
+	    msg);
+	msgrng_access_disable(mflags);
+	return (!ret);
+}
+
+static void
+release_mbuf(uint64_t phy_addr)
+{
+	struct mbuf	*m;
+
+	m = (struct mbuf *)((uint32_t) phy_addr);
+	m_freem(m);
+}
+
+static void
+release_tx_desc(struct msgrng_msg *msg, int rel_buf)
+{
+	vm_paddr_t	paddr;
+	uint64_t	temp;
+	struct nlge_tx_desc *tx_desc;
+	struct mbuf	*m;
+	uint32_t 	sr;
+
+	paddr = msg->msg0 & 0xffffffffffULL;
+	paddr += (XLR_MAX_TX_FRAGS * sizeof(uint64_t));
+	sr = xlr_enable_kx();
+	temp = xlr_paddr_lw(paddr);
+	mips_wr_status(sr);
+	tx_desc = (struct nlge_tx_desc*)((intptr_t) temp);
+
+	if (rel_buf) {
+		paddr += sizeof(void *);
+		sr = xlr_enable_kx();
+		temp = xlr_paddr_lw(paddr);
+		mips_wr_status(sr);
+		m = (struct mbuf *)((intptr_t) temp);
+		m_freem(m);
+	}
+
+	uma_zfree(nl_tx_desc_zone, tx_desc);
+}
+
+static struct mbuf *
+get_mbuf(void)
+{
+	struct mbuf *m_new;
+
+	if ((m_new = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR)) == NULL)
+		return NULL;
+	m_new->m_len = m_new->m_pkthdr.len = MCLBYTES;
+	return (m_new);
+}
+
+static void *
+get_buf(void)
+{
+	struct mbuf    *m_new;
+	vm_paddr_t 	temp1, temp2;
+	unsigned int 	*md;
+
+	m_new = get_mbuf();
+	if (m_new == NULL)
+		return m_new;
+
+	m_adj(m_new, XLR_CACHELINE_SIZE - ((unsigned int)m_new->m_data & 0x1f));
+	md = (unsigned int *)m_new->m_data;
+	md[0] = (unsigned int)m_new;	/* Back Ptr */
+	md[1] = 0xf00bad;
+	m_adj(m_new, XLR_CACHELINE_SIZE);
+
+	temp1 = vtophys((vm_offset_t) m_new->m_data);
+	temp2 = vtophys((vm_offset_t) m_new->m_data + 1536);
+	if ((temp1 + 1536) != temp2)
+		panic("ALLOCED BUFFER IS NOT CONTIGUOUS\n");
+
+	return ((void *)m_new->m_data);
+}
+
+static int
+nlge_gmac_config_speed(struct nlge_softc *sc, int quick)
+{
+	struct mii_data *md;
+	xlr_reg_t  *mmio;
+	int bmsr, n_tries, max_tries;
+	int core_ctl[]    = { 0x2, 0x1, 0x0, 0x1 };
+	int sgmii_speed[] = { SGMII_SPEED_10,
+			      SGMII_SPEED_100,
+			      SGMII_SPEED_1000,
+			      SGMII_SPEED_100 };    /* default to 100Mbps */
+	char *speed_str[] = { "10",
+			      "100",
+			      "1000",
+			      "unknown, defaulting to 100" };
+	int link_state = LINK_STATE_DOWN;
+
+	if (sc->port_type == XLR_XAUI || sc->port_type == XLR_XGMII)
+		return 0;
+
+	md = NULL;
+	mmio = sc->base;
+	if (sc->mii_base != NULL) {
+		max_tries = (quick == 1) ? 100 : 4000;
+		bmsr = 0;
+		for (n_tries = 0; n_tries < max_tries; n_tries++) {
+			bmsr = nlge_mii_read_internal(sc->mii_base,
+			    sc->phy_addr, MII_BMSR);
+			if ((bmsr & BMSR_ACOMP) && (bmsr & BMSR_LINK))
+				break; /* Auto-negotiation is complete
+					  and link is up */
+			DELAY(1000);
+		}
+		bmsr &= BMSR_LINK;
+		sc->link = (bmsr == 0) ? xlr_mac_link_down : xlr_mac_link_up;
+		sc->speed = nlge_mii_read_internal(sc->mii_base, sc->phy_addr, 28);
+		sc->speed = (sc->speed >> 3) & 0x03;
+		if (sc->link == xlr_mac_link_up) {
+			link_state = LINK_STATE_UP;
+			nlge_sgmii_init(sc);
+		}
+		if (sc->mii_bus)
+			md = (struct mii_data *)device_get_softc(sc->mii_bus);
+	}
+
+	if (sc->port_type != XLR_RGMII)
+		NLGE_WRITE(mmio, R_INTERFACE_CONTROL, sgmii_speed[sc->speed]);
+	if (sc->speed == xlr_mac_speed_10 || sc->speed == xlr_mac_speed_100 ||
+	    sc->speed == xlr_mac_speed_rsvd) {
+		NLGE_WRITE(mmio, R_MAC_CONFIG_2, 0x7117);
+	} else if (sc->speed == xlr_mac_speed_1000) {
+		NLGE_WRITE(mmio, R_MAC_CONFIG_2, 0x7217);
+		if (md != NULL) {
+			ifmedia_set(&md->mii_media, IFM_MAKEWORD(IFM_ETHER,
+			    IFM_1000_T, IFM_FDX, md->mii_instance));
+		}
+	}
+	NLGE_WRITE(mmio, R_CORECONTROL, core_ctl[sc->speed]);
+	if_link_state_change(sc->nlge_if, link_state);
+	printf("%s: [%sMbps]\n", device_get_nameunit(sc->nlge_dev),
+	    speed_str[sc->speed]);
+		
+	return (0);
+}
+
+/*
+ * This function is called for each port that was added to the device tree
+ * and it initializes the following port attributes:
+ * 	- type
+ *      - base (base address to access port-specific registers)
+ *      - mii_base
+ * 	- phy_addr
+ */
+static void
+nlge_set_port_attribs(struct nlge_softc *sc,
+    struct xlr_gmac_port *port_info)
+{
+	sc->instance = port_info->instance % 4;	/* TBD: will not work for SPI-4 */
+	sc->port_type = port_info->type;
+	sc->base = (xlr_reg_t *) (port_info->base_addr +
+	    (uint32_t)DEFAULT_XLR_IO_BASE);
+	sc->mii_base = (xlr_reg_t *) (port_info->mii_addr +
+	    (uint32_t)DEFAULT_XLR_IO_BASE);
+	if (port_info->pcs_addr != 0)
+		sc->pcs_addr = (xlr_reg_t *) (port_info->pcs_addr +
+		    (uint32_t)DEFAULT_XLR_IO_BASE);
+	if (port_info->serdes_addr != 0)
+		sc->serdes_addr = (xlr_reg_t *) (port_info->serdes_addr +
+		    (uint32_t)DEFAULT_XLR_IO_BASE);
+	sc->phy_addr = port_info->phy_addr;
+
+	PDEBUG("Port%d: base=%p, mii_base=%p, phy_addr=%d\n", sc->id, sc->base,
+	    sc->mii_base, sc->phy_addr);
+}
+
+/* ------------------------------------------------------------------------ */
+
+/* Debug dump functions */
+
+#ifdef DEBUG
+
+static void
+dump_reg(xlr_reg_t *base, uint32_t offset, char *name)
+{
+	int val;
+
+	val = NLGE_READ(base, offset);
+	printf("%-30s: 0x%8x 0x%8x\n", name, offset, val);
+}
+
+#define STRINGIFY(x) 		#x
+
+static void
+dump_na_registers(xlr_reg_t *base_addr, int port_id)
+{
+	PDEBUG("Register dump for NA (of port=%d)\n", port_id);
+	dump_reg(base_addr, R_PARSERCONFIGREG, STRINGIFY(R_PARSERCONFIGREG));
+	PDEBUG("Tx bucket sizes\n");
+	dump_reg(base_addr, R_GMAC_JFR0_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_JFR0_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_RFR0_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_RFR0_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_TX0_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_TX0_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_TX1_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_TX1_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_TX2_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_TX2_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_TX3_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_TX3_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_JFR1_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_JFR1_BUCKET_SIZE));
+	dump_reg(base_addr, R_GMAC_RFR1_BUCKET_SIZE,
+	    STRINGIFY(R_GMAC_RFR1_BUCKET_SIZE));
+	dump_reg(base_addr, R_TXDATAFIFO0, STRINGIFY(R_TXDATAFIFO0));
+	dump_reg(base_addr, R_TXDATAFIFO1, STRINGIFY(R_TXDATAFIFO1));
+}
+
+static void
+dump_gmac_registers(struct nlge_softc *sc)
+{
+	xlr_reg_t *base_addr = sc->base;
+	int port_id = sc->instance;
+
+	PDEBUG("Register dump for port=%d\n", port_id);
+	if (sc->port_type == XLR_RGMII || sc->port_type == XLR_SGMII) {
+		dump_reg(base_addr, R_MAC_CONFIG_1, STRINGIFY(R_MAC_CONFIG_1));
+		dump_reg(base_addr, R_MAC_CONFIG_2, STRINGIFY(R_MAC_CONFIG_2));
+		dump_reg(base_addr, R_IPG_IFG, STRINGIFY(R_IPG_IFG));
+		dump_reg(base_addr, R_HALF_DUPLEX, STRINGIFY(R_HALF_DUPLEX));
+		dump_reg(base_addr, R_MAXIMUM_FRAME_LENGTH,
+		    STRINGIFY(R_MAXIMUM_FRAME_LENGTH));
+		dump_reg(base_addr, R_TEST, STRINGIFY(R_TEST));
+		dump_reg(base_addr, R_MII_MGMT_CONFIG,
+		    STRINGIFY(R_MII_MGMT_CONFIG));
+		dump_reg(base_addr, R_MII_MGMT_COMMAND,
+		    STRINGIFY(R_MII_MGMT_COMMAND));
+		dump_reg(base_addr, R_MII_MGMT_ADDRESS,
+		    STRINGIFY(R_MII_MGMT_ADDRESS));
+		dump_reg(base_addr, R_MII_MGMT_WRITE_DATA,
+		    STRINGIFY(R_MII_MGMT_WRITE_DATA));
+		dump_reg(base_addr, R_MII_MGMT_STATUS,
+		    STRINGIFY(R_MII_MGMT_STATUS));
+		dump_reg(base_addr, R_MII_MGMT_INDICATORS,
+		    STRINGIFY(R_MII_MGMT_INDICATORS));
+		dump_reg(base_addr, R_INTERFACE_CONTROL,
+		    STRINGIFY(R_INTERFACE_CONTROL));
+		dump_reg(base_addr, R_INTERFACE_STATUS,
+		    STRINGIFY(R_INTERFACE_STATUS));
+	} else if (sc->port_type == XLR_XAUI || sc->port_type == XLR_XGMII) {
+		dump_reg(base_addr, R_XGMAC_CONFIG_0,
+		    STRINGIFY(R_XGMAC_CONFIG_0));
+		dump_reg(base_addr, R_XGMAC_CONFIG_1,
+		    STRINGIFY(R_XGMAC_CONFIG_1));
+		dump_reg(base_addr, R_XGMAC_CONFIG_2,
+		    STRINGIFY(R_XGMAC_CONFIG_2));
+		dump_reg(base_addr, R_XGMAC_CONFIG_3,
+		    STRINGIFY(R_XGMAC_CONFIG_3));
+		dump_reg(base_addr, R_XGMAC_STATION_ADDRESS_LS,
+		    STRINGIFY(R_XGMAC_STATION_ADDRESS_LS));
+		dump_reg(base_addr, R_XGMAC_STATION_ADDRESS_MS,
+		    STRINGIFY(R_XGMAC_STATION_ADDRESS_MS));
+		dump_reg(base_addr, R_XGMAC_MAX_FRAME_LEN,
+		    STRINGIFY(R_XGMAC_MAX_FRAME_LEN));
+		dump_reg(base_addr, R_XGMAC_REV_LEVEL,
+		    STRINGIFY(R_XGMAC_REV_LEVEL));
+		dump_reg(base_addr, R_XGMAC_MIIM_COMMAND,
+		    STRINGIFY(R_XGMAC_MIIM_COMMAND));
+		dump_reg(base_addr, R_XGMAC_MIIM_FILED,
+		    STRINGIFY(R_XGMAC_MIIM_FILED));
+		dump_reg(base_addr, R_XGMAC_MIIM_CONFIG,
+		    STRINGIFY(R_XGMAC_MIIM_CONFIG));
+		dump_reg(base_addr, R_XGMAC_MIIM_LINK_FAIL_VECTOR,
+		    STRINGIFY(R_XGMAC_MIIM_LINK_FAIL_VECTOR));
+		dump_reg(base_addr, R_XGMAC_MIIM_INDICATOR,
+		    STRINGIFY(R_XGMAC_MIIM_INDICATOR));
+	}
+
+	dump_reg(base_addr, R_MAC_ADDR0, STRINGIFY(R_MAC_ADDR0));
+	dump_reg(base_addr, R_MAC_ADDR0 + 1, STRINGIFY(R_MAC_ADDR0+1));
+	dump_reg(base_addr, R_MAC_ADDR1, STRINGIFY(R_MAC_ADDR1));
+	dump_reg(base_addr, R_MAC_ADDR2, STRINGIFY(R_MAC_ADDR2));
+	dump_reg(base_addr, R_MAC_ADDR3, STRINGIFY(R_MAC_ADDR3));
+	dump_reg(base_addr, R_MAC_ADDR_MASK2, STRINGIFY(R_MAC_ADDR_MASK2));
+	dump_reg(base_addr, R_MAC_ADDR_MASK3, STRINGIFY(R_MAC_ADDR_MASK3));
+	dump_reg(base_addr, R_MAC_FILTER_CONFIG, STRINGIFY(R_MAC_FILTER_CONFIG));
+	dump_reg(base_addr, R_TX_CONTROL, STRINGIFY(R_TX_CONTROL));
+	dump_reg(base_addr, R_RX_CONTROL, STRINGIFY(R_RX_CONTROL));
+	dump_reg(base_addr, R_DESC_PACK_CTRL, STRINGIFY(R_DESC_PACK_CTRL));
+	dump_reg(base_addr, R_STATCTRL, STRINGIFY(R_STATCTRL));
+	dump_reg(base_addr, R_L2ALLOCCTRL, STRINGIFY(R_L2ALLOCCTRL));
+	dump_reg(base_addr, R_INTMASK, STRINGIFY(R_INTMASK));
+	dump_reg(base_addr, R_INTREG, STRINGIFY(R_INTREG));
+	dump_reg(base_addr, R_TXRETRY, STRINGIFY(R_TXRETRY));
+	dump_reg(base_addr, R_CORECONTROL, STRINGIFY(R_CORECONTROL));
+	dump_reg(base_addr, R_BYTEOFFSET0, STRINGIFY(R_BYTEOFFSET0));
+	dump_reg(base_addr, R_BYTEOFFSET1, STRINGIFY(R_BYTEOFFSET1));
+	dump_reg(base_addr, R_L2TYPE_0, STRINGIFY(R_L2TYPE_0));
+	dump_na_registers(base_addr, port_id);
+}
+
+static void
+dump_fmn_cpu_credits_for_gmac(struct xlr_board_info *board, int gmac_id)
+{
+	struct stn_cc *cc;
+	int gmac_bucket_ids[] = { 97, 98, 99, 100, 101, 103 };
+	int j, k, r, c;
+	int n_gmac_buckets;
+
+	n_gmac_buckets = sizeof (gmac_bucket_ids) / sizeof (gmac_bucket_ids[0]);
+	for (j = 0; j < 8; j++) { 		// for each cpu
+		cc = board->credit_configs[j];
+		printf("Credits for Station CPU_%d ---> GMAC buckets (tx path)\n", j);
+		for (k = 0; k < n_gmac_buckets; k++) {
+			r = gmac_bucket_ids[k] / 8;
+			c = gmac_bucket_ids[k] % 8;
+			printf ("    --> gmac%d_bucket_%-3d: credits=%d\n", gmac_id,
+				gmac_bucket_ids[k], cc->counters[r][c]);
+		}
+	}
+}
+
+static void
+dump_fmn_gmac_credits(struct xlr_board_info *board, int gmac_id)
+{
+	struct stn_cc *cc;
+	int j, k;
+
+	cc = board->gmac_block[gmac_id].credit_config;
+	printf("Credits for Station: GMAC_%d ---> CPU buckets (rx path)\n", gmac_id);
+	for (j = 0; j < 8; j++) { 		// for each cpu
+		printf("    ---> cpu_%d\n", j);
+		for (k = 0; k < 8; k++) {	// for each bucket in cpu
+			printf("        ---> bucket_%d: credits=%d\n", j * 8 + k,
+			       cc->counters[j][k]);
+		}
+	}
+}
+
+static void
+dump_board_info(struct xlr_board_info *board)
+{
+	struct xlr_gmac_block_t *gm;
+	int i, k;
+
+	printf("cpu=%x ", xlr_revision());
+	printf("board_version: major=%llx, minor=%llx\n",
+	    xlr_boot1_info.board_major_version,
+	    xlr_boot1_info.board_minor_version);
+	printf("is_xls=%d, nr_cpus=%d, usb=%s, cfi=%s, ata=%s\npci_irq=%d,"
+	    "gmac_ports=%d\n", board->is_xls, board->nr_cpus,
+	    board->usb ? "Yes" : "No", board->cfi ? "Yes": "No",
+	    board->ata ? "Yes" : "No", board->pci_irq, board->gmacports);
+	printf("FMN: Core-station bucket sizes\n");
+	for (i = 0; i < 128; i++) {
+		if (i && ((i % 16) == 0))
+			printf("\n");
+		printf ("b[%d] = %d ", i, board->bucket_sizes->bucket[i]);
+	}
+	printf("\n");
+	for (i = 0; i < 3; i++) {
+		gm = &board->gmac_block[i];
+		printf("RNA_%d: type=%d, enabled=%s, mode=%d, station_id=%d,"
+		    "station_txbase=%d, station_rfr=%d ", i, gm->type,
+		    gm->enabled ? "Yes" : "No", gm->mode, gm->station_id,
+		    gm->station_txbase, gm->station_rfr);
+		printf("n_ports=%d, baseaddr=%p, baseirq=%d, baseinst=%d\n",
+		     gm->num_ports, (xlr_reg_t *)gm->baseaddr, gm->baseirq,
+		     gm->baseinst);
+	}
+	for (k = 0; k < 3; k++) { 	// for each NA
+		dump_fmn_cpu_credits_for_gmac(board, k);
+		dump_fmn_gmac_credits(board, k);
+	}
+}
+
+static void
+dump_mac_stats(struct nlge_softc *sc)
+{
+	xlr_reg_t *addr;
+	uint32_t pkts_tx, pkts_rx;
+
+	addr = sc->base;
+	pkts_rx = NLGE_READ(sc->base, R_RPKT);
+	pkts_tx = NLGE_READ(sc->base, R_TPKT);
+
+	printf("[nlge_%d mac stats]: pkts_tx=%u, pkts_rx=%u\n", sc->id, pkts_tx,
+	    pkts_rx);
+	if (pkts_rx > 0) {
+		uint32_t r;
+
+		/* dump all rx counters. we need this because pkts_rx includes
+		   bad packets. */
+		for (r = R_RFCS; r <= R_ROVR; r++)
+			printf("[nlge_%d mac stats]: [0x%x]=%u\n", sc->id, r,
+			    NLGE_READ(sc->base, r));
+	}
+	if (pkts_tx > 0) {
+		uint32_t r;
+
+		/* dump all tx counters. might be useful for debugging. */
+		for (r = R_TMCA; r <= R_TFRG; r++) {
+			if ((r == (R_TNCL + 1)) || (r == (R_TNCL + 2)))
+				continue;
+			printf("[nlge_%d mac stats]: [0x%x]=%u\n", sc->id, r,
+			    NLGE_READ(sc->base, r));
+		}
+	}
+		
+}
+
+static void
+dump_mii_regs(struct nlge_softc *sc)
+{
+	uint32_t mii_regs[] = {  0x0,  0x1,  0x2,  0x3,  0x4,  0x5,  0x6,  0x7,
+	                         0x8,  0x9,  0xa,  0xf, 0x10, 0x11, 0x12, 0x13,
+				0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
+				0x1c, 0x1d, 0x1e};
+	int i, n_regs;
+
+	if (sc->mii_base == NULL || sc->mii_bus == NULL)
+		return;
+
+	n_regs = sizeof (mii_regs) / sizeof (mii_regs[0]);
+	for (i = 0; i < n_regs; i++) {
+		printf("[mii_0x%x] = %x\n", mii_regs[i],
+		    nlge_mii_read_internal(sc->mii_base, sc->phy_addr,
+		        mii_regs[i]));
+	}
+}
+
+static void
+dump_ifmedia(struct ifmedia *ifm)
+{
+	printf("ifm_mask=%08x, ifm_media=%08x, cur=%p\n", ifm->ifm_mask,
+	    ifm->ifm_media, ifm->ifm_cur);
+	if (ifm->ifm_cur != NULL) {
+		printf("Cur attribs: ifmedia_entry.ifm_media=%08x,"
+		    " ifmedia_entry.ifm_data=%08x\n", ifm->ifm_cur->ifm_media,
+		    ifm->ifm_cur->ifm_data);
+	}
+}
+
+static void
+dump_mii_data(struct mii_data *mii)
+{
+	dump_ifmedia(&mii->mii_media);
+	printf("ifp=%p, mii_instance=%d, mii_media_status=%08x,"
+	    " mii_media_active=%08x\n", mii->mii_ifp, mii->mii_instance,
+	    mii->mii_media_status, mii->mii_media_active);
+}
+
+static void
+dump_pcs_regs(struct nlge_softc *sc, int phy)
+{
+	int i, val;
+
+	printf("PCS regs from %p for phy=%d\n", sc->pcs_addr, phy);
+	for (i = 0; i < 18; i++) {
+		if (i == 2 || i == 3 || (i >= 9 && i <= 14))
+			continue;
+		val = nlge_mii_read_internal(sc->pcs_addr, phy, i);
+		printf("PHY:%d pcs[0x%x] is 0x%x\n", phy, i, val);
+	}
+}
+#endif
diff --git a/sys/mips/rmi/dev/nlge/if_nlge.h b/sys/mips/rmi/dev/nlge/if_nlge.h
new file mode 100644
index 00000000000..0347071ca4c
--- /dev/null
+++ b/sys/mips/rmi/dev/nlge/if_nlge.h
@@ -0,0 +1,1180 @@
+/*-
+ * Copyright (c) 2003-2009 RMI Corporation
+ * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
+ * $FreeBSD$
+ *
+ * RMI_BSD 
+ */
+
+/* #define MAC_SPLIT_MODE */
+
+#define MAC_SPACING                 0x400
+#define XGMAC_SPACING               0x400
+
+/* PE-MCXMAC register and bit field definitions */
+#define R_MAC_CONFIG_1                                              0x00
+#define   O_MAC_CONFIG_1__srst                                      31
+#define   O_MAC_CONFIG_1__simr                                      30
+#define   O_MAC_CONFIG_1__hrrmc                                     18
+#define   W_MAC_CONFIG_1__hrtmc                                      2
+#define   O_MAC_CONFIG_1__hrrfn                                     16
+#define   W_MAC_CONFIG_1__hrtfn                                      2
+#define   O_MAC_CONFIG_1__intlb                                      8
+#define   O_MAC_CONFIG_1__rxfc                                       5
+#define   O_MAC_CONFIG_1__txfc                                       4
+#define   O_MAC_CONFIG_1__srxen                                      3
+#define   O_MAC_CONFIG_1__rxen                                       2
+#define   O_MAC_CONFIG_1__stxen                                      1
+#define   O_MAC_CONFIG_1__txen                                       0
+#define R_MAC_CONFIG_2                                              0x01
+#define   O_MAC_CONFIG_2__prlen                                     12
+#define   W_MAC_CONFIG_2__prlen                                      4
+#define   O_MAC_CONFIG_2__speed                                      8
+#define   W_MAC_CONFIG_2__speed                                      2
+#define   O_MAC_CONFIG_2__hugen                                      5
+#define   O_MAC_CONFIG_2__flchk                                      4
+#define   O_MAC_CONFIG_2__crce                                       1
+#define   O_MAC_CONFIG_2__fulld                                      0
+#define R_IPG_IFG                                                   0x02
+#define   O_IPG_IFG__ipgr1                                          24
+#define   W_IPG_IFG__ipgr1                                           7
+#define   O_IPG_IFG__ipgr2                                          16
+#define   W_IPG_IFG__ipgr2                                           7
+#define   O_IPG_IFG__mifg                                            8
+#define   W_IPG_IFG__mifg                                            8
+#define   O_IPG_IFG__ipgt                                            0
+#define   W_IPG_IFG__ipgt                                            7
+#define R_HALF_DUPLEX                                               0x03
+#define   O_HALF_DUPLEX__abebt                                      24
+#define   W_HALF_DUPLEX__abebt                                       4
+#define   O_HALF_DUPLEX__abebe                                      19
+#define   O_HALF_DUPLEX__bpnb                                       18
+#define   O_HALF_DUPLEX__nobo                                       17
+#define   O_HALF_DUPLEX__edxsdfr                                    16
+#define   O_HALF_DUPLEX__retry                                      12
+#define   W_HALF_DUPLEX__retry                                       4
+#define   O_HALF_DUPLEX__lcol                                        0
+#define   W_HALF_DUPLEX__lcol                                       10
+#define R_MAXIMUM_FRAME_LENGTH                                      0x04
+#define   O_MAXIMUM_FRAME_LENGTH__maxf                               0
+#define   W_MAXIMUM_FRAME_LENGTH__maxf                              16
+#define R_TEST                                                      0x07
+#define   O_TEST__mbof                                               3
+#define   O_TEST__rthdf                                              2
+#define   O_TEST__tpause                                             1
+#define   O_TEST__sstct                                              0
+#define R_MII_MGMT_CONFIG                                           0x08
+#define   O_MII_MGMT_CONFIG__scinc                                   5
+#define   O_MII_MGMT_CONFIG__spre                                    4
+#define   O_MII_MGMT_CONFIG__clks                                    3
+#define   W_MII_MGMT_CONFIG__clks                                    3
+#define R_MII_MGMT_COMMAND                                          0x09
+#define   O_MII_MGMT_COMMAND__scan                                   1
+#define   O_MII_MGMT_COMMAND__rstat                                  0
+#define R_MII_MGMT_ADDRESS                                          0x0A
+#define   O_MII_MGMT_ADDRESS__fiad                                   8
+#define   W_MII_MGMT_ADDRESS__fiad                                   5
+#define   O_MII_MGMT_ADDRESS__fgad                                   5
+#define   W_MII_MGMT_ADDRESS__fgad                                   0
+#define R_MII_MGMT_WRITE_DATA                                       0x0B
+#define   O_MII_MGMT_WRITE_DATA__ctld                                0
+#define   W_MII_MGMT_WRITE_DATA__ctld                               16
+#define R_MII_MGMT_STATUS                                           0x0C
+#define R_MII_MGMT_INDICATORS                                       0x0D
+#define   O_MII_MGMT_INDICATORS__nvalid                              2
+#define   O_MII_MGMT_INDICATORS__scan                                1
+#define   O_MII_MGMT_INDICATORS__busy                                0
+#define R_INTERFACE_CONTROL                                         0x0E
+#define   O_INTERFACE_CONTROL__hrstint                              31
+#define   O_INTERFACE_CONTROL__tbimode                              27
+#define   O_INTERFACE_CONTROL__ghdmode                              26
+#define   O_INTERFACE_CONTROL__lhdmode                              25
+#define   O_INTERFACE_CONTROL__phymod                               24
+#define   O_INTERFACE_CONTROL__hrrmi                                23
+#define   O_INTERFACE_CONTROL__rspd                                 16
+#define   O_INTERFACE_CONTROL__hr100                                15
+#define   O_INTERFACE_CONTROL__frcq                                 10
+#define   O_INTERFACE_CONTROL__nocfr                                 9
+#define   O_INTERFACE_CONTROL__dlfct                                 8
+#define   O_INTERFACE_CONTROL__enjab                                 0
+#define R_INTERFACE_STATUS                                         0x0F
+#define   O_INTERFACE_STATUS__xsdfr                                  9
+#define   O_INTERFACE_STATUS__ssrr                                   8
+#define   W_INTERFACE_STATUS__ssrr                                   5
+#define   O_INTERFACE_STATUS__miilf                                  3
+#define   O_INTERFACE_STATUS__locar                                  2
+#define   O_INTERFACE_STATUS__sqerr                                  1
+#define   O_INTERFACE_STATUS__jabber                                 0
+#define R_STATION_ADDRESS_LS                                       0x10
+#define R_STATION_ADDRESS_MS                                       0x11
+
+/* A-XGMAC register and bit field definitions */
+#define R_XGMAC_CONFIG_0    0x00
+#define   O_XGMAC_CONFIG_0__hstmacrst               31
+#define   O_XGMAC_CONFIG_0__hstrstrctl              23
+#define   O_XGMAC_CONFIG_0__hstrstrfn               22
+#define   O_XGMAC_CONFIG_0__hstrsttctl              18
+#define   O_XGMAC_CONFIG_0__hstrsttfn               17
+#define   O_XGMAC_CONFIG_0__hstrstmiim              16
+#define   O_XGMAC_CONFIG_0__hstloopback             8
+#define R_XGMAC_CONFIG_1    0x01
+#define   O_XGMAC_CONFIG_1__hsttctlen               31
+#define   O_XGMAC_CONFIG_1__hsttfen                 30
+#define   O_XGMAC_CONFIG_1__hstrctlen               29
+#define   O_XGMAC_CONFIG_1__hstrfen                 28
+#define   O_XGMAC_CONFIG_1__tfen                    26
+#define   O_XGMAC_CONFIG_1__rfen                    24
+#define   O_XGMAC_CONFIG_1__hstrctlshrtp            12
+#define   O_XGMAC_CONFIG_1__hstdlyfcstx             10
+#define   W_XGMAC_CONFIG_1__hstdlyfcstx              2
+#define   O_XGMAC_CONFIG_1__hstdlyfcsrx              8
+#define   W_XGMAC_CONFIG_1__hstdlyfcsrx              2
+#define   O_XGMAC_CONFIG_1__hstppen                  7
+#define   O_XGMAC_CONFIG_1__hstbytswp                6
+#define   O_XGMAC_CONFIG_1__hstdrplt64               5
+#define   O_XGMAC_CONFIG_1__hstprmscrx               4
+#define   O_XGMAC_CONFIG_1__hstlenchk                3
+#define   O_XGMAC_CONFIG_1__hstgenfcs                2
+#define   O_XGMAC_CONFIG_1__hstpadmode               0
+#define   W_XGMAC_CONFIG_1__hstpadmode               2
+#define R_XGMAC_CONFIG_2    0x02
+#define   O_XGMAC_CONFIG_2__hsttctlfrcp             31
+#define   O_XGMAC_CONFIG_2__hstmlnkflth             27
+#define   O_XGMAC_CONFIG_2__hstalnkflth             26
+#define   O_XGMAC_CONFIG_2__rflnkflt                24
+#define   W_XGMAC_CONFIG_2__rflnkflt                 2
+#define   O_XGMAC_CONFIG_2__hstipgextmod            16
+#define   W_XGMAC_CONFIG_2__hstipgextmod             5
+#define   O_XGMAC_CONFIG_2__hstrctlfrcp             15
+#define   O_XGMAC_CONFIG_2__hstipgexten              5
+#define   O_XGMAC_CONFIG_2__hstmipgext               0
+#define   W_XGMAC_CONFIG_2__hstmipgext               5
+#define R_XGMAC_CONFIG_3    0x03
+#define   O_XGMAC_CONFIG_3__hstfltrfrm              31
+#define   W_XGMAC_CONFIG_3__hstfltrfrm              16
+#define   O_XGMAC_CONFIG_3__hstfltrfrmdc            15
+#define   W_XGMAC_CONFIG_3__hstfltrfrmdc            16
+#define R_XGMAC_STATION_ADDRESS_LS      0x04
+#define   O_XGMAC_STATION_ADDRESS_LS__hstmacadr0    0
+#define   W_XGMAC_STATION_ADDRESS_LS__hstmacadr0    32
+#define R_XGMAC_STATION_ADDRESS_MS      0x05
+#define R_XGMAC_MAX_FRAME_LEN           0x08
+#define   O_XGMAC_MAX_FRAME_LEN__hstmxfrmwctx       16
+#define   W_XGMAC_MAX_FRAME_LEN__hstmxfrmwctx       14
+#define   O_XGMAC_MAX_FRAME_LEN__hstmxfrmbcrx        0
+#define   W_XGMAC_MAX_FRAME_LEN__hstmxfrmbcrx       16
+#define R_XGMAC_REV_LEVEL               0x0B
+#define   O_XGMAC_REV_LEVEL__revlvl                  0
+#define   W_XGMAC_REV_LEVEL__revlvl                 15
+#define R_XGMAC_MIIM_COMMAND            0x10
+#define   O_XGMAC_MIIM_COMMAND__hstldcmd             3
+#define   O_XGMAC_MIIM_COMMAND__hstmiimcmd           0
+#define   W_XGMAC_MIIM_COMMAND__hstmiimcmd           3
+#define R_XGMAC_MIIM_FILED              0x11
+#define   O_XGMAC_MIIM_FILED__hststfield            30
+#define   W_XGMAC_MIIM_FILED__hststfield             2
+#define   O_XGMAC_MIIM_FILED__hstopfield            28
+#define   W_XGMAC_MIIM_FILED__hstopfield             2
+#define   O_XGMAC_MIIM_FILED__hstphyadx             23
+#define   W_XGMAC_MIIM_FILED__hstphyadx              5
+#define   O_XGMAC_MIIM_FILED__hstregadx             18
+#define   W_XGMAC_MIIM_FILED__hstregadx              5
+#define   O_XGMAC_MIIM_FILED__hsttafield            16
+#define   W_XGMAC_MIIM_FILED__hsttafield             2
+#define   O_XGMAC_MIIM_FILED__miimrddat              0
+#define   W_XGMAC_MIIM_FILED__miimrddat             16
+#define R_XGMAC_MIIM_CONFIG             0x12
+#define   O_XGMAC_MIIM_CONFIG__hstnopram             7
+#define   O_XGMAC_MIIM_CONFIG__hstclkdiv             0
+#define   W_XGMAC_MIIM_CONFIG__hstclkdiv             7
+#define R_XGMAC_MIIM_LINK_FAIL_VECTOR   0x13
+#define   O_XGMAC_MIIM_LINK_FAIL_VECTOR__miimlfvec   0
+#define   W_XGMAC_MIIM_LINK_FAIL_VECTOR__miimlfvec  32
+#define R_XGMAC_MIIM_INDICATOR          0x14
+#define   O_XGMAC_MIIM_INDICATOR__miimphylf          4
+#define   O_XGMAC_MIIM_INDICATOR__miimmoncplt        3
+#define   O_XGMAC_MIIM_INDICATOR__miimmonvld         2
+#define   O_XGMAC_MIIM_INDICATOR__miimmon            1
+#define   O_XGMAC_MIIM_INDICATOR__miimbusy           0
+
+/* GMAC stats registers */
+#define R_RBYT							    0x27
+#define R_RPKT							    0x28
+#define R_RFCS							    0x29
+#define R_RMCA							    0x2A
+#define R_RBCA							    0x2B
+#define R_RXCF							    0x2C
+#define R_RXPF							    0x2D
+#define R_RXUO							    0x2E
+#define R_RALN							    0x2F
+#define R_RFLR							    0x30
+#define R_RCDE							    0x31
+#define R_RCSE							    0x32
+#define R_RUND							    0x33
+#define R_ROVR							    0x34
+#define R_TBYT							    0x38
+#define R_TPKT							    0x39
+#define R_TMCA							    0x3A
+#define R_TBCA							    0x3B
+#define R_TXPF							    0x3C
+#define R_TDFR							    0x3D
+#define R_TEDF							    0x3E
+#define R_TSCL							    0x3F
+#define R_TMCL							    0x40
+#define R_TLCL							    0x41
+#define R_TXCL							    0x42
+#define R_TNCL							    0x43
+#define R_TJBR							    0x46
+#define R_TFCS							    0x47
+#define R_TXCF							    0x48
+#define R_TOVR							    0x49
+#define R_TUND							    0x4A
+#define R_TFRG							    0x4B
+
+/* Glue logic register and bit field definitions */
+#define R_MAC_ADDR0                                                 0x50
+#define R_MAC_ADDR1                                                 0x52
+#define R_MAC_ADDR2                                                 0x54
+#define R_MAC_ADDR3                                                 0x56
+#define R_MAC_ADDR_MASK2                                            0x58
+#define R_MAC_ADDR_MASK3                                            0x5A
+#define R_MAC_FILTER_CONFIG                                         0x5C
+#define   O_MAC_FILTER_CONFIG__BROADCAST_EN                         10
+#define   O_MAC_FILTER_CONFIG__PAUSE_FRAME_EN                       9
+#define   O_MAC_FILTER_CONFIG__ALL_MCAST_EN                         8
+#define   O_MAC_FILTER_CONFIG__ALL_UCAST_EN                         7
+#define   O_MAC_FILTER_CONFIG__HASH_MCAST_EN                        6
+#define   O_MAC_FILTER_CONFIG__HASH_UCAST_EN                        5
+#define   O_MAC_FILTER_CONFIG__ADDR_MATCH_DISC                      4
+#define   O_MAC_FILTER_CONFIG__MAC_ADDR3_VALID                      3
+#define   O_MAC_FILTER_CONFIG__MAC_ADDR2_VALID                      2
+#define   O_MAC_FILTER_CONFIG__MAC_ADDR1_VALID                      1
+#define   O_MAC_FILTER_CONFIG__MAC_ADDR0_VALID                      0
+#define R_HASH_TABLE_VECTOR                                         0x30
+#define R_TX_CONTROL                                                 0x0A0
+#define   O_TX_CONTROL__Tx15Halt                                     31
+#define   O_TX_CONTROL__Tx14Halt                                     30
+#define   O_TX_CONTROL__Tx13Halt                                     29
+#define   O_TX_CONTROL__Tx12Halt                                     28
+#define   O_TX_CONTROL__Tx11Halt                                     27
+#define   O_TX_CONTROL__Tx10Halt                                     26
+#define   O_TX_CONTROL__Tx9Halt                                      25
+#define   O_TX_CONTROL__Tx8Halt                                      24
+#define   O_TX_CONTROL__Tx7Halt                                      23
+#define   O_TX_CONTROL__Tx6Halt                                      22
+#define   O_TX_CONTROL__Tx5Halt                                      21
+#define   O_TX_CONTROL__Tx4Halt                                      20
+#define   O_TX_CONTROL__Tx3Halt                                      19
+#define   O_TX_CONTROL__Tx2Halt                                      18
+#define   O_TX_CONTROL__Tx1Halt                                      17
+#define   O_TX_CONTROL__Tx0Halt                                      16
+#define   O_TX_CONTROL__TxIdle                                       15
+#define   O_TX_CONTROL__TxEnable                                     14
+#define   O_TX_CONTROL__TxThreshold                                  0
+#define   W_TX_CONTROL__TxThreshold                                  14
+#define R_RX_CONTROL                                                 0x0A1
+#define   O_RX_CONTROL__RGMII                                        10
+#define   O_RX_CONTROL__SoftReset			             2
+#define   O_RX_CONTROL__RxHalt                                       1
+#define   O_RX_CONTROL__RxEnable                                     0
+#define R_DESC_PACK_CTRL                                            0x0A2
+#define   O_DESC_PACK_CTRL__ByteOffset                              17
+#define   W_DESC_PACK_CTRL__ByteOffset                              3
+#define   O_DESC_PACK_CTRL__PrePadEnable                            16
+#define   O_DESC_PACK_CTRL__MaxEntry                                14
+#define   W_DESC_PACK_CTRL__MaxEntry                                2
+#define   O_DESC_PACK_CTRL__RegularSize                             0
+#define   W_DESC_PACK_CTRL__RegularSize                             14
+#define R_STATCTRL                                                  0x0A3
+#define   O_STATCTRL__OverFlowEn                                    4
+#define   O_STATCTRL__GIG                                           3
+#define   O_STATCTRL__Sten                                          2
+#define   O_STATCTRL__ClrCnt                                        1
+#define   O_STATCTRL__AutoZ                                         0
+#define R_L2ALLOCCTRL                                               0x0A4
+#define   O_L2ALLOCCTRL__TxL2Allocate                               9
+#define   W_L2ALLOCCTRL__TxL2Allocate                               9
+#define   O_L2ALLOCCTRL__RxL2Allocate                               0
+#define   W_L2ALLOCCTRL__RxL2Allocate                               9
+#define R_INTMASK                                                   0x0A5
+#define   O_INTMASK__Spi4TxError                                     28
+#define   O_INTMASK__Spi4RxError                                     27
+#define   O_INTMASK__RGMIIHalfDupCollision                           27
+#define   O_INTMASK__Abort                                           26
+#define   O_INTMASK__Underrun                                        25
+#define   O_INTMASK__DiscardPacket                                   24
+#define   O_INTMASK__AsyncFifoFull                                   23
+#define   O_INTMASK__TagFull                                         22
+#define   O_INTMASK__Class3Full                                      21
+#define   O_INTMASK__C3EarlyFull                                     20
+#define   O_INTMASK__Class2Full                                      19
+#define   O_INTMASK__C2EarlyFull                                     18
+#define   O_INTMASK__Class1Full                                      17
+#define   O_INTMASK__C1EarlyFull                                     16
+#define   O_INTMASK__Class0Full                                      15
+#define   O_INTMASK__C0EarlyFull                                     14
+#define   O_INTMASK__RxDataFull                                      13
+#define   O_INTMASK__RxEarlyFull                                     12
+#define   O_INTMASK__RFreeEmpty                                      9
+#define   O_INTMASK__RFEarlyEmpty                                    8
+#define   O_INTMASK__P2PSpillEcc                                     7
+#define   O_INTMASK__FreeDescFull                                    5
+#define   O_INTMASK__FreeEarlyFull                                   4
+#define   O_INTMASK__TxFetchError                                    3
+#define   O_INTMASK__StatCarry                                       2
+#define   O_INTMASK__MDInt                                           1
+#define   O_INTMASK__TxIllegal                                       0
+#define R_INTREG                                                    0x0A6
+#define   O_INTREG__Spi4TxError                                     28
+#define   O_INTREG__Spi4RxError                                     27
+#define   O_INTREG__RGMIIHalfDupCollision                           27
+#define   O_INTREG__Abort                                           26
+#define   O_INTREG__Underrun                                        25
+#define   O_INTREG__DiscardPacket                                   24
+#define   O_INTREG__AsyncFifoFull                                   23
+#define   O_INTREG__TagFull                                         22
+#define   O_INTREG__Class3Full                                      21
+#define   O_INTREG__C3EarlyFull                                     20
+#define   O_INTREG__Class2Full                                      19
+#define   O_INTREG__C2EarlyFull                                     18
+#define   O_INTREG__Class1Full                                      17
+#define   O_INTREG__C1EarlyFull                                     16
+#define   O_INTREG__Class0Full                                      15
+#define   O_INTREG__C0EarlyFull                                     14
+#define   O_INTREG__RxDataFull                                      13
+#define   O_INTREG__RxEarlyFull                                     12
+#define   O_INTREG__RFreeEmpty                                      9
+#define   O_INTREG__RFEarlyEmpty                                    8
+#define   O_INTREG__P2PSpillEcc                                     7
+#define   O_INTREG__FreeDescFull                                    5
+#define   O_INTREG__FreeEarlyFull                                   4
+#define   O_INTREG__TxFetchError                                    3
+#define   O_INTREG__StatCarry                                       2
+#define   O_INTREG__MDInt                                           1
+#define   O_INTREG__TxIllegal                                       0
+#define R_TXRETRY                                                   0x0A7
+#define   O_TXRETRY__CollisionRetry                                 6
+#define   O_TXRETRY__BusErrorRetry                                  5
+#define   O_TXRETRY__UnderRunRetry                                  4
+#define   O_TXRETRY__Retries                                        0
+#define   W_TXRETRY__Retries                                        4
+#define R_CORECONTROL                                               0x0A8
+#define   O_CORECONTROL__ErrorThread                                4
+#define   W_CORECONTROL__ErrorThread                                7
+#define   O_CORECONTROL__Shutdown                                   2
+#define   O_CORECONTROL__Speed                                      0
+#define   W_CORECONTROL__Speed                                      2
+#define R_BYTEOFFSET0                                               0x0A9
+#define R_BYTEOFFSET1                                               0x0AA
+#define R_L2TYPE_0                                                  0x0F0
+#define   O_L2TYPE__ExtraHdrProtoSize                               26
+#define   W_L2TYPE__ExtraHdrProtoSize                               5
+#define   O_L2TYPE__ExtraHdrProtoOffset                             20
+#define   W_L2TYPE__ExtraHdrProtoOffset                             6
+#define   O_L2TYPE__ExtraHeaderSize                                 14
+#define   W_L2TYPE__ExtraHeaderSize                                 6
+#define   O_L2TYPE__ProtoOffset                                     8
+#define   W_L2TYPE__ProtoOffset                                     6
+#define   O_L2TYPE__L2HdrOffset                                     2
+#define   W_L2TYPE__L2HdrOffset                                     6
+#define   O_L2TYPE__L2Proto                                         0
+#define   W_L2TYPE__L2Proto                                         2
+#define R_L2TYPE_1                                                  0xF0
+#define R_L2TYPE_2                                                  0xF0
+#define R_L2TYPE_3                                                  0xF0
+#define R_PARSERCONFIGREG                                           0x100
+#define   O_PARSERCONFIGREG__CRCHashPoly                            8
+#define   W_PARSERCONFIGREG__CRCHashPoly                            7
+#define   O_PARSERCONFIGREG__PrePadOffset                           4
+#define   W_PARSERCONFIGREG__PrePadOffset                           4
+#define   O_PARSERCONFIGREG__UseCAM                                 2
+#define   O_PARSERCONFIGREG__UseHASH                                1
+#define   O_PARSERCONFIGREG__UseProto                               0
+#define R_L3CTABLE                                                  0x140
+#define   O_L3CTABLE__Offset0                                       25
+#define   W_L3CTABLE__Offset0                                       7
+#define   O_L3CTABLE__Len0                                          21
+#define   W_L3CTABLE__Len0                                          4
+#define   O_L3CTABLE__Offset1                                       14
+#define   W_L3CTABLE__Offset1                                       7
+#define   O_L3CTABLE__Len1                                          10
+#define   W_L3CTABLE__Len1                                          4
+#define   O_L3CTABLE__Offset2                                       4
+#define   W_L3CTABLE__Offset2                                       6
+#define   O_L3CTABLE__Len2                                          0
+#define   W_L3CTABLE__Len2                                          4
+#define   O_L3CTABLE__L3HdrOffset                                   26
+#define   W_L3CTABLE__L3HdrOffset                                   6
+#define   O_L3CTABLE__L4ProtoOffset                                 20
+#define   W_L3CTABLE__L4ProtoOffset                                 6
+#define   O_L3CTABLE__IPChksumCompute                               19
+#define   O_L3CTABLE__L4Classify                                    18
+#define   O_L3CTABLE__L2Proto                                       16
+#define   W_L3CTABLE__L2Proto                                       2
+#define   O_L3CTABLE__L3ProtoKey                                    0
+#define   W_L3CTABLE__L3ProtoKey                                    16
+#define R_L4CTABLE                                                  0x160
+#define   O_L4CTABLE__Offset0                                       21
+#define   W_L4CTABLE__Offset0                                       6
+#define   O_L4CTABLE__Len0                                          17
+#define   W_L4CTABLE__Len0                                          4
+#define   O_L4CTABLE__Offset1                                       11
+#define   W_L4CTABLE__Offset1                                       6
+#define   O_L4CTABLE__Len1                                          7
+#define   W_L4CTABLE__Len1                                          4
+#define   O_L4CTABLE__TCPChksumEnable                               0
+#define R_CAM4X128TABLE                                             0x172
+#define   O_CAM4X128TABLE__ClassId                                  7
+#define   W_CAM4X128TABLE__ClassId                                  2
+#define   O_CAM4X128TABLE__BucketId                                 1
+#define   W_CAM4X128TABLE__BucketId                                 6
+#define   O_CAM4X128TABLE__UseBucket                                0
+#define R_CAM4X128KEY                                               0x180
+#define R_TRANSLATETABLE                                            0x1A0
+#define R_DMACR0                                                    0x200
+#define   O_DMACR0__Data0WrMaxCr                                    27
+#define   W_DMACR0__Data0WrMaxCr                                    3
+#define   O_DMACR0__Data0RdMaxCr                                    24
+#define   W_DMACR0__Data0RdMaxCr                                    3
+#define   O_DMACR0__Data1WrMaxCr                                    21
+#define   W_DMACR0__Data1WrMaxCr                                    3
+#define   O_DMACR0__Data1RdMaxCr                                    18
+#define   W_DMACR0__Data1RdMaxCr                                    3
+#define   O_DMACR0__Data2WrMaxCr                                    15
+#define   W_DMACR0__Data2WrMaxCr                                    3
+#define   O_DMACR0__Data2RdMaxCr                                    12
+#define   W_DMACR0__Data2RdMaxCr                                    3
+#define   O_DMACR0__Data3WrMaxCr                                    9
+#define   W_DMACR0__Data3WrMaxCr                                    3
+#define   O_DMACR0__Data3RdMaxCr                                    6
+#define   W_DMACR0__Data3RdMaxCr                                    3
+#define   O_DMACR0__Data4WrMaxCr                                    3
+#define   W_DMACR0__Data4WrMaxCr                                    3
+#define   O_DMACR0__Data4RdMaxCr                                    0
+#define   W_DMACR0__Data4RdMaxCr                                    3
+#define R_DMACR1                                                    0x201
+#define   O_DMACR1__Data5WrMaxCr                                    27
+#define   W_DMACR1__Data5WrMaxCr                                    3
+#define   O_DMACR1__Data5RdMaxCr                                    24
+#define   W_DMACR1__Data5RdMaxCr                                    3
+#define   O_DMACR1__Data6WrMaxCr                                    21
+#define   W_DMACR1__Data6WrMaxCr                                    3
+#define   O_DMACR1__Data6RdMaxCr                                    18
+#define   W_DMACR1__Data6RdMaxCr                                    3
+#define   O_DMACR1__Data7WrMaxCr                                    15
+#define   W_DMACR1__Data7WrMaxCr                                    3
+#define   O_DMACR1__Data7RdMaxCr                                    12
+#define   W_DMACR1__Data7RdMaxCr                                    3
+#define   O_DMACR1__Data8WrMaxCr                                    9
+#define   W_DMACR1__Data8WrMaxCr                                    3
+#define   O_DMACR1__Data8RdMaxCr                                    6
+#define   W_DMACR1__Data8RdMaxCr                                    3
+#define   O_DMACR1__Data9WrMaxCr                                    3
+#define   W_DMACR1__Data9WrMaxCr                                    3
+#define   O_DMACR1__Data9RdMaxCr                                    0
+#define   W_DMACR1__Data9RdMaxCr                                    3
+#define R_DMACR2                                                    0x202
+#define   O_DMACR2__Data10WrMaxCr                                   27
+#define   W_DMACR2__Data10WrMaxCr                                   3
+#define   O_DMACR2__Data10RdMaxCr                                   24
+#define   W_DMACR2__Data10RdMaxCr                                   3
+#define   O_DMACR2__Data11WrMaxCr                                   21
+#define   W_DMACR2__Data11WrMaxCr                                   3
+#define   O_DMACR2__Data11RdMaxCr                                   18
+#define   W_DMACR2__Data11RdMaxCr                                   3
+#define   O_DMACR2__Data12WrMaxCr                                   15
+#define   W_DMACR2__Data12WrMaxCr                                   3
+#define   O_DMACR2__Data12RdMaxCr                                   12
+#define   W_DMACR2__Data12RdMaxCr                                   3
+#define   O_DMACR2__Data13WrMaxCr                                   9
+#define   W_DMACR2__Data13WrMaxCr                                   3
+#define   O_DMACR2__Data13RdMaxCr                                   6
+#define   W_DMACR2__Data13RdMaxCr                                   3
+#define   O_DMACR2__Data14WrMaxCr                                   3
+#define   W_DMACR2__Data14WrMaxCr                                   3
+#define   O_DMACR2__Data14RdMaxCr                                   0
+#define   W_DMACR2__Data14RdMaxCr                                   3
+#define R_DMACR3                                                    0x203
+#define   O_DMACR3__Data15WrMaxCr                                   27
+#define   W_DMACR3__Data15WrMaxCr                                   3
+#define   O_DMACR3__Data15RdMaxCr                                   24
+#define   W_DMACR3__Data15RdMaxCr                                   3
+#define   O_DMACR3__SpClassWrMaxCr                                  21
+#define   W_DMACR3__SpClassWrMaxCr                                  3
+#define   O_DMACR3__SpClassRdMaxCr                                  18
+#define   W_DMACR3__SpClassRdMaxCr                                  3
+#define   O_DMACR3__JumFrInWrMaxCr                                  15
+#define   W_DMACR3__JumFrInWrMaxCr                                  3
+#define   O_DMACR3__JumFrInRdMaxCr                                  12
+#define   W_DMACR3__JumFrInRdMaxCr                                  3
+#define   O_DMACR3__RegFrInWrMaxCr                                  9
+#define   W_DMACR3__RegFrInWrMaxCr                                  3
+#define   O_DMACR3__RegFrInRdMaxCr                                  6
+#define   W_DMACR3__RegFrInRdMaxCr                                  3
+#define   O_DMACR3__FrOutWrMaxCr                                    3
+#define   W_DMACR3__FrOutWrMaxCr                                    3
+#define   O_DMACR3__FrOutRdMaxCr                                    0
+#define   W_DMACR3__FrOutRdMaxCr                                    3
+#define R_REG_FRIN_SPILL_MEM_START_0                                0x204
+#define   O_REG_FRIN_SPILL_MEM_START_0__RegFrInSpillMemStart0        0
+#define   W_REG_FRIN_SPILL_MEM_START_0__RegFrInSpillMemStart0       32
+#define R_REG_FRIN_SPILL_MEM_START_1                                0x205
+#define   O_REG_FRIN_SPILL_MEM_START_1__RegFrInSpillMemStart1        0
+#define   W_REG_FRIN_SPILL_MEM_START_1__RegFrInSpillMemStart1        3
+#define R_REG_FRIN_SPILL_MEM_SIZE                                   0x206
+#define   O_REG_FRIN_SPILL_MEM_SIZE__RegFrInSpillMemSize             0
+#define   W_REG_FRIN_SPILL_MEM_SIZE__RegFrInSpillMemSize            32
+#define R_FROUT_SPILL_MEM_START_0                                   0x207
+#define   O_FROUT_SPILL_MEM_START_0__FrOutSpillMemStart0             0
+#define   W_FROUT_SPILL_MEM_START_0__FrOutSpillMemStart0            32
+#define R_FROUT_SPILL_MEM_START_1                                   0x208
+#define   O_FROUT_SPILL_MEM_START_1__FrOutSpillMemStart1             0
+#define   W_FROUT_SPILL_MEM_START_1__FrOutSpillMemStart1             3
+#define R_FROUT_SPILL_MEM_SIZE                                      0x209
+#define   O_FROUT_SPILL_MEM_SIZE__FrOutSpillMemSize                  0
+#define   W_FROUT_SPILL_MEM_SIZE__FrOutSpillMemSize                 32
+#define R_CLASS0_SPILL_MEM_START_0                                  0x20A
+#define   O_CLASS0_SPILL_MEM_START_0__Class0SpillMemStart0           0
+#define   W_CLASS0_SPILL_MEM_START_0__Class0SpillMemStart0          32
+#define R_CLASS0_SPILL_MEM_START_1                                  0x20B
+#define   O_CLASS0_SPILL_MEM_START_1__Class0SpillMemStart1           0
+#define   W_CLASS0_SPILL_MEM_START_1__Class0SpillMemStart1           3
+#define R_CLASS0_SPILL_MEM_SIZE                                     0x20C
+#define   O_CLASS0_SPILL_MEM_SIZE__Class0SpillMemSize                0
+#define   W_CLASS0_SPILL_MEM_SIZE__Class0SpillMemSize               32
+#define R_JUMFRIN_SPILL_MEM_START_0                                 0x20D
+#define   O_JUMFRIN_SPILL_MEM_START_0__JumFrInSpillMemStar0          0
+#define   W_JUMFRIN_SPILL_MEM_START_0__JumFrInSpillMemStar0         32
+#define R_JUMFRIN_SPILL_MEM_START_1                                 0x20E
+#define   O_JUMFRIN_SPILL_MEM_START_1__JumFrInSpillMemStart1         0
+#define   W_JUMFRIN_SPILL_MEM_START_1__JumFrInSpillMemStart1         3
+#define R_JUMFRIN_SPILL_MEM_SIZE                                    0x20F
+#define   O_JUMFRIN_SPILL_MEM_SIZE__JumFrInSpillMemSize              0
+#define   W_JUMFRIN_SPILL_MEM_SIZE__JumFrInSpillMemSize             32
+#define R_CLASS1_SPILL_MEM_START_0                                  0x210
+#define   O_CLASS1_SPILL_MEM_START_0__Class1SpillMemStart0           0
+#define   W_CLASS1_SPILL_MEM_START_0__Class1SpillMemStart0          32
+#define R_CLASS1_SPILL_MEM_START_1                                  0x211
+#define   O_CLASS1_SPILL_MEM_START_1__Class1SpillMemStart1           0
+#define   W_CLASS1_SPILL_MEM_START_1__Class1SpillMemStart1           3
+#define R_CLASS1_SPILL_MEM_SIZE                                     0x212
+#define   O_CLASS1_SPILL_MEM_SIZE__Class1SpillMemSize                0
+#define   W_CLASS1_SPILL_MEM_SIZE__Class1SpillMemSize               32
+#define R_CLASS2_SPILL_MEM_START_0                                  0x213
+#define   O_CLASS2_SPILL_MEM_START_0__Class2SpillMemStart0           0
+#define   W_CLASS2_SPILL_MEM_START_0__Class2SpillMemStart0          32
+#define R_CLASS2_SPILL_MEM_START_1                                  0x214
+#define   O_CLASS2_SPILL_MEM_START_1__Class2SpillMemStart1           0
+#define   W_CLASS2_SPILL_MEM_START_1__Class2SpillMemStart1           3
+#define R_CLASS2_SPILL_MEM_SIZE                                     0x215
+#define   O_CLASS2_SPILL_MEM_SIZE__Class2SpillMemSize                0
+#define   W_CLASS2_SPILL_MEM_SIZE__Class2SpillMemSize               32
+#define R_CLASS3_SPILL_MEM_START_0                                  0x216
+#define   O_CLASS3_SPILL_MEM_START_0__Class3SpillMemStart0           0
+#define   W_CLASS3_SPILL_MEM_START_0__Class3SpillMemStart0          32
+#define R_CLASS3_SPILL_MEM_START_1                                  0x217
+#define   O_CLASS3_SPILL_MEM_START_1__Class3SpillMemStart1           0
+#define   W_CLASS3_SPILL_MEM_START_1__Class3SpillMemStart1           3
+#define R_CLASS3_SPILL_MEM_SIZE                                     0x218
+#define   O_CLASS3_SPILL_MEM_SIZE__Class3SpillMemSize                0
+#define   W_CLASS3_SPILL_MEM_SIZE__Class3SpillMemSize               32
+#define R_REG_FRIN1_SPILL_MEM_START_0                               0x219
+#define R_REG_FRIN1_SPILL_MEM_START_1                               0x21a
+#define R_REG_FRIN1_SPILL_MEM_SIZE                                  0x21b
+#define R_SPIHNGY0                                                  0x219
+#define   O_SPIHNGY0__EG_HNGY_THRESH_0                              24
+#define   W_SPIHNGY0__EG_HNGY_THRESH_0                              7
+#define   O_SPIHNGY0__EG_HNGY_THRESH_1                              16
+#define   W_SPIHNGY0__EG_HNGY_THRESH_1                              7
+#define   O_SPIHNGY0__EG_HNGY_THRESH_2                              8
+#define   W_SPIHNGY0__EG_HNGY_THRESH_2                              7
+#define   O_SPIHNGY0__EG_HNGY_THRESH_3                              0
+#define   W_SPIHNGY0__EG_HNGY_THRESH_3                              7
+#define R_SPIHNGY1                                                  0x21A
+#define   O_SPIHNGY1__EG_HNGY_THRESH_4                              24
+#define   W_SPIHNGY1__EG_HNGY_THRESH_4                              7
+#define   O_SPIHNGY1__EG_HNGY_THRESH_5                              16
+#define   W_SPIHNGY1__EG_HNGY_THRESH_5                              7
+#define   O_SPIHNGY1__EG_HNGY_THRESH_6                              8
+#define   W_SPIHNGY1__EG_HNGY_THRESH_6                              7
+#define   O_SPIHNGY1__EG_HNGY_THRESH_7                              0
+#define   W_SPIHNGY1__EG_HNGY_THRESH_7                              7
+#define R_SPIHNGY2                                                  0x21B
+#define   O_SPIHNGY2__EG_HNGY_THRESH_8                              24
+#define   W_SPIHNGY2__EG_HNGY_THRESH_8                              7
+#define   O_SPIHNGY2__EG_HNGY_THRESH_9                              16
+#define   W_SPIHNGY2__EG_HNGY_THRESH_9                              7
+#define   O_SPIHNGY2__EG_HNGY_THRESH_10                             8
+#define   W_SPIHNGY2__EG_HNGY_THRESH_10                             7
+#define   O_SPIHNGY2__EG_HNGY_THRESH_11                             0
+#define   W_SPIHNGY2__EG_HNGY_THRESH_11                             7
+#define R_SPIHNGY3                                                  0x21C
+#define   O_SPIHNGY3__EG_HNGY_THRESH_12                             24
+#define   W_SPIHNGY3__EG_HNGY_THRESH_12                             7
+#define   O_SPIHNGY3__EG_HNGY_THRESH_13                             16
+#define   W_SPIHNGY3__EG_HNGY_THRESH_13                             7
+#define   O_SPIHNGY3__EG_HNGY_THRESH_14                             8
+#define   W_SPIHNGY3__EG_HNGY_THRESH_14                             7
+#define   O_SPIHNGY3__EG_HNGY_THRESH_15                             0
+#define   W_SPIHNGY3__EG_HNGY_THRESH_15                             7
+#define R_SPISTRV0                                                  0x21D
+#define   O_SPISTRV0__EG_STRV_THRESH_0                              24
+#define   W_SPISTRV0__EG_STRV_THRESH_0                              7
+#define   O_SPISTRV0__EG_STRV_THRESH_1                              16
+#define   W_SPISTRV0__EG_STRV_THRESH_1                              7
+#define   O_SPISTRV0__EG_STRV_THRESH_2                              8
+#define   W_SPISTRV0__EG_STRV_THRESH_2                              7
+#define   O_SPISTRV0__EG_STRV_THRESH_3                              0
+#define   W_SPISTRV0__EG_STRV_THRESH_3                              7
+#define R_SPISTRV1                                                  0x21E
+#define   O_SPISTRV1__EG_STRV_THRESH_4                              24
+#define   W_SPISTRV1__EG_STRV_THRESH_4                              7
+#define   O_SPISTRV1__EG_STRV_THRESH_5                              16
+#define   W_SPISTRV1__EG_STRV_THRESH_5                              7
+#define   O_SPISTRV1__EG_STRV_THRESH_6                              8
+#define   W_SPISTRV1__EG_STRV_THRESH_6                              7
+#define   O_SPISTRV1__EG_STRV_THRESH_7                              0
+#define   W_SPISTRV1__EG_STRV_THRESH_7                              7
+#define R_SPISTRV2                                                  0x21F
+#define   O_SPISTRV2__EG_STRV_THRESH_8                              24
+#define   W_SPISTRV2__EG_STRV_THRESH_8                              7
+#define   O_SPISTRV2__EG_STRV_THRESH_9                              16
+#define   W_SPISTRV2__EG_STRV_THRESH_9                              7
+#define   O_SPISTRV2__EG_STRV_THRESH_10                             8
+#define   W_SPISTRV2__EG_STRV_THRESH_10                             7
+#define   O_SPISTRV2__EG_STRV_THRESH_11                             0
+#define   W_SPISTRV2__EG_STRV_THRESH_11                             7
+#define R_SPISTRV3                                                  0x220
+#define   O_SPISTRV3__EG_STRV_THRESH_12                             24
+#define   W_SPISTRV3__EG_STRV_THRESH_12                             7
+#define   O_SPISTRV3__EG_STRV_THRESH_13                             16
+#define   W_SPISTRV3__EG_STRV_THRESH_13                             7
+#define   O_SPISTRV3__EG_STRV_THRESH_14                             8
+#define   W_SPISTRV3__EG_STRV_THRESH_14                             7
+#define   O_SPISTRV3__EG_STRV_THRESH_15                             0
+#define   W_SPISTRV3__EG_STRV_THRESH_15                             7
+#define R_TXDATAFIFO0                                               0x221
+#define   O_TXDATAFIFO0__Tx0DataFifoStart                           24
+#define   W_TXDATAFIFO0__Tx0DataFifoStart                           7
+#define   O_TXDATAFIFO0__Tx0DataFifoSize                            16
+#define   W_TXDATAFIFO0__Tx0DataFifoSize                            7
+#define   O_TXDATAFIFO0__Tx1DataFifoStart                           8
+#define   W_TXDATAFIFO0__Tx1DataFifoStart                           7
+#define   O_TXDATAFIFO0__Tx1DataFifoSize                            0
+#define   W_TXDATAFIFO0__Tx1DataFifoSize                            7
+#define R_TXDATAFIFO1                                               0x222
+#define   O_TXDATAFIFO1__Tx2DataFifoStart                           24
+#define   W_TXDATAFIFO1__Tx2DataFifoStart                           7
+#define   O_TXDATAFIFO1__Tx2DataFifoSize                            16
+#define   W_TXDATAFIFO1__Tx2DataFifoSize                            7
+#define   O_TXDATAFIFO1__Tx3DataFifoStart                           8
+#define   W_TXDATAFIFO1__Tx3DataFifoStart                           7
+#define   O_TXDATAFIFO1__Tx3DataFifoSize                            0
+#define   W_TXDATAFIFO1__Tx3DataFifoSize                            7
+#define R_TXDATAFIFO2                                               0x223
+#define   O_TXDATAFIFO2__Tx4DataFifoStart                           24
+#define   W_TXDATAFIFO2__Tx4DataFifoStart                           7
+#define   O_TXDATAFIFO2__Tx4DataFifoSize                            16
+#define   W_TXDATAFIFO2__Tx4DataFifoSize                            7
+#define   O_TXDATAFIFO2__Tx5DataFifoStart                           8
+#define   W_TXDATAFIFO2__Tx5DataFifoStart                           7
+#define   O_TXDATAFIFO2__Tx5DataFifoSize                            0
+#define   W_TXDATAFIFO2__Tx5DataFifoSize                            7
+#define R_TXDATAFIFO3                                               0x224
+#define   O_TXDATAFIFO3__Tx6DataFifoStart                           24
+#define   W_TXDATAFIFO3__Tx6DataFifoStart                           7
+#define   O_TXDATAFIFO3__Tx6DataFifoSize                            16
+#define   W_TXDATAFIFO3__Tx6DataFifoSize                            7
+#define   O_TXDATAFIFO3__Tx7DataFifoStart                           8
+#define   W_TXDATAFIFO3__Tx7DataFifoStart                           7
+#define   O_TXDATAFIFO3__Tx7DataFifoSize                            0
+#define   W_TXDATAFIFO3__Tx7DataFifoSize                            7
+#define R_TXDATAFIFO4                                               0x225
+#define   O_TXDATAFIFO4__Tx8DataFifoStart                           24
+#define   W_TXDATAFIFO4__Tx8DataFifoStart                           7
+#define   O_TXDATAFIFO4__Tx8DataFifoSize                            16
+#define   W_TXDATAFIFO4__Tx8DataFifoSize                            7
+#define   O_TXDATAFIFO4__Tx9DataFifoStart                           8
+#define   W_TXDATAFIFO4__Tx9DataFifoStart                           7
+#define   O_TXDATAFIFO4__Tx9DataFifoSize                            0
+#define   W_TXDATAFIFO4__Tx9DataFifoSize                            7
+#define R_TXDATAFIFO5                                               0x226
+#define   O_TXDATAFIFO5__Tx10DataFifoStart                          24
+#define   W_TXDATAFIFO5__Tx10DataFifoStart                          7
+#define   O_TXDATAFIFO5__Tx10DataFifoSize                           16
+#define   W_TXDATAFIFO5__Tx10DataFifoSize                           7
+#define   O_TXDATAFIFO5__Tx11DataFifoStart                          8
+#define   W_TXDATAFIFO5__Tx11DataFifoStart                          7
+#define   O_TXDATAFIFO5__Tx11DataFifoSize                           0
+#define   W_TXDATAFIFO5__Tx11DataFifoSize                           7
+#define R_TXDATAFIFO6                                               0x227
+#define   O_TXDATAFIFO6__Tx12DataFifoStart                          24
+#define   W_TXDATAFIFO6__Tx12DataFifoStart                          7
+#define   O_TXDATAFIFO6__Tx12DataFifoSize                           16
+#define   W_TXDATAFIFO6__Tx12DataFifoSize                           7
+#define   O_TXDATAFIFO6__Tx13DataFifoStart                          8
+#define   W_TXDATAFIFO6__Tx13DataFifoStart                          7
+#define   O_TXDATAFIFO6__Tx13DataFifoSize                           0
+#define   W_TXDATAFIFO6__Tx13DataFifoSize                           7
+#define R_TXDATAFIFO7                                               0x228
+#define   O_TXDATAFIFO7__Tx14DataFifoStart                          24
+#define   W_TXDATAFIFO7__Tx14DataFifoStart                          7
+#define   O_TXDATAFIFO7__Tx14DataFifoSize                           16
+#define   W_TXDATAFIFO7__Tx14DataFifoSize                           7
+#define   O_TXDATAFIFO7__Tx15DataFifoStart                          8
+#define   W_TXDATAFIFO7__Tx15DataFifoStart                          7
+#define   O_TXDATAFIFO7__Tx15DataFifoSize                           0
+#define   W_TXDATAFIFO7__Tx15DataFifoSize                           7
+#define R_RXDATAFIFO0                                               0x229
+#define   O_RXDATAFIFO0__Rx0DataFifoStart                           24
+#define   W_RXDATAFIFO0__Rx0DataFifoStart                           7
+#define   O_RXDATAFIFO0__Rx0DataFifoSize                            16
+#define   W_RXDATAFIFO0__Rx0DataFifoSize                            7
+#define   O_RXDATAFIFO0__Rx1DataFifoStart                           8
+#define   W_RXDATAFIFO0__Rx1DataFifoStart                           7
+#define   O_RXDATAFIFO0__Rx1DataFifoSize                            0
+#define   W_RXDATAFIFO0__Rx1DataFifoSize                            7
+#define R_RXDATAFIFO1                                               0x22A
+#define   O_RXDATAFIFO1__Rx2DataFifoStart                           24
+#define   W_RXDATAFIFO1__Rx2DataFifoStart                           7
+#define   O_RXDATAFIFO1__Rx2DataFifoSize                            16
+#define   W_RXDATAFIFO1__Rx2DataFifoSize                            7
+#define   O_RXDATAFIFO1__Rx3DataFifoStart                           8
+#define   W_RXDATAFIFO1__Rx3DataFifoStart                           7
+#define   O_RXDATAFIFO1__Rx3DataFifoSize                            0
+#define   W_RXDATAFIFO1__Rx3DataFifoSize                            7
+#define R_RXDATAFIFO2                                               0x22B
+#define   O_RXDATAFIFO2__Rx4DataFifoStart                           24
+#define   W_RXDATAFIFO2__Rx4DataFifoStart                           7
+#define   O_RXDATAFIFO2__Rx4DataFifoSize                            16
+#define   W_RXDATAFIFO2__Rx4DataFifoSize                            7
+#define   O_RXDATAFIFO2__Rx5DataFifoStart                           8
+#define   W_RXDATAFIFO2__Rx5DataFifoStart                           7
+#define   O_RXDATAFIFO2__Rx5DataFifoSize                            0
+#define   W_RXDATAFIFO2__Rx5DataFifoSize                            7
+#define R_RXDATAFIFO3                                               0x22C
+#define   O_RXDATAFIFO3__Rx6DataFifoStart                           24
+#define   W_RXDATAFIFO3__Rx6DataFifoStart                           7
+#define   O_RXDATAFIFO3__Rx6DataFifoSize                            16
+#define   W_RXDATAFIFO3__Rx6DataFifoSize                            7
+#define   O_RXDATAFIFO3__Rx7DataFifoStart                           8
+#define   W_RXDATAFIFO3__Rx7DataFifoStart                           7
+#define   O_RXDATAFIFO3__Rx7DataFifoSize                            0
+#define   W_RXDATAFIFO3__Rx7DataFifoSize                            7
+#define R_RXDATAFIFO4                                               0x22D
+#define   O_RXDATAFIFO4__Rx8DataFifoStart                           24
+#define   W_RXDATAFIFO4__Rx8DataFifoStart                           7
+#define   O_RXDATAFIFO4__Rx8DataFifoSize                            16
+#define   W_RXDATAFIFO4__Rx8DataFifoSize                            7
+#define   O_RXDATAFIFO4__Rx9DataFifoStart                           8
+#define   W_RXDATAFIFO4__Rx9DataFifoStart                           7
+#define   O_RXDATAFIFO4__Rx9DataFifoSize                            0
+#define   W_RXDATAFIFO4__Rx9DataFifoSize                            7
+#define R_RXDATAFIFO5                                               0x22E
+#define   O_RXDATAFIFO5__Rx10DataFifoStart                          24
+#define   W_RXDATAFIFO5__Rx10DataFifoStart                          7
+#define   O_RXDATAFIFO5__Rx10DataFifoSize                           16
+#define   W_RXDATAFIFO5__Rx10DataFifoSize                           7
+#define   O_RXDATAFIFO5__Rx11DataFifoStart                          8
+#define   W_RXDATAFIFO5__Rx11DataFifoStart                          7
+#define   O_RXDATAFIFO5__Rx11DataFifoSize                           0
+#define   W_RXDATAFIFO5__Rx11DataFifoSize                           7
+#define R_RXDATAFIFO6                                               0x22F
+#define   O_RXDATAFIFO6__Rx12DataFifoStart                          24
+#define   W_RXDATAFIFO6__Rx12DataFifoStart                          7
+#define   O_RXDATAFIFO6__Rx12DataFifoSize                           16
+#define   W_RXDATAFIFO6__Rx12DataFifoSize                           7
+#define   O_RXDATAFIFO6__Rx13DataFifoStart                          8
+#define   W_RXDATAFIFO6__Rx13DataFifoStart                          7
+#define   O_RXDATAFIFO6__Rx13DataFifoSize                           0
+#define   W_RXDATAFIFO6__Rx13DataFifoSize                           7
+#define R_RXDATAFIFO7                                               0x230
+#define   O_RXDATAFIFO7__Rx14DataFifoStart                          24
+#define   W_RXDATAFIFO7__Rx14DataFifoStart                          7
+#define   O_RXDATAFIFO7__Rx14DataFifoSize                           16
+#define   W_RXDATAFIFO7__Rx14DataFifoSize                           7
+#define   O_RXDATAFIFO7__Rx15DataFifoStart                          8
+#define   W_RXDATAFIFO7__Rx15DataFifoStart                          7
+#define   O_RXDATAFIFO7__Rx15DataFifoSize                           0
+#define   W_RXDATAFIFO7__Rx15DataFifoSize                           7
+#define R_XGMACPADCALIBRATION                                       0x231
+#define R_FREEQCARVE                                                0x233
+#define R_SPI4STATICDELAY0                                          0x240
+#define   O_SPI4STATICDELAY0__DataLine7                             28
+#define   W_SPI4STATICDELAY0__DataLine7                             4
+#define   O_SPI4STATICDELAY0__DataLine6                             24
+#define   W_SPI4STATICDELAY0__DataLine6                             4
+#define   O_SPI4STATICDELAY0__DataLine5                             20
+#define   W_SPI4STATICDELAY0__DataLine5                             4
+#define   O_SPI4STATICDELAY0__DataLine4                             16
+#define   W_SPI4STATICDELAY0__DataLine4                             4
+#define   O_SPI4STATICDELAY0__DataLine3                             12
+#define   W_SPI4STATICDELAY0__DataLine3                             4
+#define   O_SPI4STATICDELAY0__DataLine2                             8
+#define   W_SPI4STATICDELAY0__DataLine2                             4
+#define   O_SPI4STATICDELAY0__DataLine1                             4
+#define   W_SPI4STATICDELAY0__DataLine1                             4
+#define   O_SPI4STATICDELAY0__DataLine0                             0
+#define   W_SPI4STATICDELAY0__DataLine0                             4
+#define R_SPI4STATICDELAY1                                          0x241
+#define   O_SPI4STATICDELAY1__DataLine15                            28
+#define   W_SPI4STATICDELAY1__DataLine15                            4
+#define   O_SPI4STATICDELAY1__DataLine14                            24
+#define   W_SPI4STATICDELAY1__DataLine14                            4
+#define   O_SPI4STATICDELAY1__DataLine13                            20
+#define   W_SPI4STATICDELAY1__DataLine13                            4
+#define   O_SPI4STATICDELAY1__DataLine12                            16
+#define   W_SPI4STATICDELAY1__DataLine12                            4
+#define   O_SPI4STATICDELAY1__DataLine11                            12
+#define   W_SPI4STATICDELAY1__DataLine11                            4
+#define   O_SPI4STATICDELAY1__DataLine10                            8
+#define   W_SPI4STATICDELAY1__DataLine10                            4
+#define   O_SPI4STATICDELAY1__DataLine9                             4
+#define   W_SPI4STATICDELAY1__DataLine9                             4
+#define   O_SPI4STATICDELAY1__DataLine8                             0
+#define   W_SPI4STATICDELAY1__DataLine8                             4
+#define R_SPI4STATICDELAY2                                          0x242
+#define   O_SPI4STATICDELAY0__TxStat1                               8
+#define   W_SPI4STATICDELAY0__TxStat1                               4
+#define   O_SPI4STATICDELAY0__TxStat0                               4
+#define   W_SPI4STATICDELAY0__TxStat0                               4
+#define   O_SPI4STATICDELAY0__RxControl                             0
+#define   W_SPI4STATICDELAY0__RxControl                             4
+#define R_SPI4CONTROL                                               0x243
+#define   O_SPI4CONTROL__StaticDelay                                2
+#define   O_SPI4CONTROL__LVDS_LVTTL                                 1
+#define   O_SPI4CONTROL__SPI4Enable                                 0
+#define R_CLASSWATERMARKS                                           0x244
+#define   O_CLASSWATERMARKS__Class0Watermark                        24
+#define   W_CLASSWATERMARKS__Class0Watermark                        5
+#define   O_CLASSWATERMARKS__Class1Watermark                        16
+#define   W_CLASSWATERMARKS__Class1Watermark                        5
+#define   O_CLASSWATERMARKS__Class3Watermark                        0
+#define   W_CLASSWATERMARKS__Class3Watermark                        5
+#define R_RXWATERMARKS1                                              0x245
+#define   O_RXWATERMARKS__Rx0DataWatermark                          24
+#define   W_RXWATERMARKS__Rx0DataWatermark                          7
+#define   O_RXWATERMARKS__Rx1DataWatermark                          16
+#define   W_RXWATERMARKS__Rx1DataWatermark                          7
+#define   O_RXWATERMARKS__Rx3DataWatermark                          0
+#define   W_RXWATERMARKS__Rx3DataWatermark                          7
+#define R_RXWATERMARKS2                                              0x246
+#define   O_RXWATERMARKS__Rx4DataWatermark                          24
+#define   W_RXWATERMARKS__Rx4DataWatermark                          7
+#define   O_RXWATERMARKS__Rx5DataWatermark                          16
+#define   W_RXWATERMARKS__Rx5DataWatermark                          7
+#define   O_RXWATERMARKS__Rx6DataWatermark                          8
+#define   W_RXWATERMARKS__Rx6DataWatermark                          7
+#define   O_RXWATERMARKS__Rx7DataWatermark                          0
+#define   W_RXWATERMARKS__Rx7DataWatermark                          7
+#define R_RXWATERMARKS3                                              0x247
+#define   O_RXWATERMARKS__Rx8DataWatermark                          24
+#define   W_RXWATERMARKS__Rx8DataWatermark                          7
+#define   O_RXWATERMARKS__Rx9DataWatermark                          16
+#define   W_RXWATERMARKS__Rx9DataWatermark                          7
+#define   O_RXWATERMARKS__Rx10DataWatermark                         8
+#define   W_RXWATERMARKS__Rx10DataWatermark                         7
+#define   O_RXWATERMARKS__Rx11DataWatermark                         0
+#define   W_RXWATERMARKS__Rx11DataWatermark                         7
+#define R_RXWATERMARKS4                                              0x248
+#define   O_RXWATERMARKS__Rx12DataWatermark                         24
+#define   W_RXWATERMARKS__Rx12DataWatermark                         7
+#define   O_RXWATERMARKS__Rx13DataWatermark                         16
+#define   W_RXWATERMARKS__Rx13DataWatermark                         7
+#define   O_RXWATERMARKS__Rx14DataWatermark                         8
+#define   W_RXWATERMARKS__Rx14DataWatermark                         7
+#define   O_RXWATERMARKS__Rx15DataWatermark                         0
+#define   W_RXWATERMARKS__Rx15DataWatermark                         7
+#define R_FREEWATERMARKS                                            0x249
+#define   O_FREEWATERMARKS__FreeOutWatermark                        16
+#define   W_FREEWATERMARKS__FreeOutWatermark                        16
+#define   O_FREEWATERMARKS__JumFrWatermark                          8
+#define   W_FREEWATERMARKS__JumFrWatermark                          7
+#define   O_FREEWATERMARKS__RegFrWatermark                          0
+#define   W_FREEWATERMARKS__RegFrWatermark                          7
+#define R_EGRESSFIFOCARVINGSLOTS                                    0x24a
+
+#define CTRL_RES0           0
+#define CTRL_RES1           1
+#define CTRL_REG_FREE       2
+#define CTRL_JUMBO_FREE     3
+#define CTRL_CONT           4
+#define CTRL_EOP            5
+#define CTRL_START          6
+#define CTRL_SNGL           7
+
+#define CTRL_B0_NOT_EOP     0
+#define CTRL_B0_EOP         1
+
+#define R_ROUND_ROBIN_TABLE                 0
+#define R_PDE_CLASS_0                       0x300
+#define R_PDE_CLASS_1                       0x302
+#define R_PDE_CLASS_2                       0x304
+#define R_PDE_CLASS_3                       0x306
+
+#define R_MSG_TX_THRESHOLD                  0x308
+
+#define R_GMAC_JFR0_BUCKET_SIZE              0x320
+#define R_GMAC_RFR0_BUCKET_SIZE              0x321
+#define R_GMAC_TX0_BUCKET_SIZE              0x322
+#define R_GMAC_TX1_BUCKET_SIZE              0x323
+#define R_GMAC_TX2_BUCKET_SIZE              0x324
+#define R_GMAC_TX3_BUCKET_SIZE              0x325
+#define R_GMAC_JFR1_BUCKET_SIZE              0x326
+#define R_GMAC_RFR1_BUCKET_SIZE              0x327
+
+#define R_XGS_TX0_BUCKET_SIZE               0x320
+#define R_XGS_TX1_BUCKET_SIZE               0x321
+#define R_XGS_TX2_BUCKET_SIZE               0x322
+#define R_XGS_TX3_BUCKET_SIZE               0x323
+#define R_XGS_TX4_BUCKET_SIZE               0x324
+#define R_XGS_TX5_BUCKET_SIZE               0x325
+#define R_XGS_TX6_BUCKET_SIZE               0x326
+#define R_XGS_TX7_BUCKET_SIZE               0x327
+#define R_XGS_TX8_BUCKET_SIZE               0x328
+#define R_XGS_TX9_BUCKET_SIZE               0x329
+#define R_XGS_TX10_BUCKET_SIZE              0x32A
+#define R_XGS_TX11_BUCKET_SIZE              0x32B
+#define R_XGS_TX12_BUCKET_SIZE              0x32C
+#define R_XGS_TX13_BUCKET_SIZE              0x32D
+#define R_XGS_TX14_BUCKET_SIZE              0x32E
+#define R_XGS_TX15_BUCKET_SIZE              0x32F
+#define R_XGS_JFR_BUCKET_SIZE               0x330
+#define R_XGS_RFR_BUCKET_SIZE               0x331
+
+#define R_CC_CPU0_0                         0x380
+#define R_CC_CPU1_0                         0x388
+#define R_CC_CPU2_0                         0x390
+#define R_CC_CPU3_0                         0x398
+#define R_CC_CPU4_0                         0x3a0
+#define R_CC_CPU5_0                         0x3a8
+#define R_CC_CPU6_0                         0x3b0
+#define R_CC_CPU7_0                         0x3b8
+
+#define XLR_GMAC_BLK_SZ		            (XLR_IO_GMAC_1_OFFSET - \
+    XLR_IO_GMAC_0_OFFSET)
+
+/* Constants used for configuring the devices */
+
+#define RGE_TX_THRESHOLD                1024
+#define RGE_TX_Q_SIZE                   1024
+
+#define MAC_B2B_IPG                     88
+
+/* frame sizes need to be cacheline aligned */
+#define MAX_FRAME_SIZE                  1536
+#define MAX_FRAME_SIZE_JUMBO            9216
+#define RGE_TX_THRESHOLD_BYTES		ETHER_MAX_LEN
+
+#define MAC_SKB_BACK_PTR_SIZE           SMP_CACHE_BYTES
+#define MAC_PREPAD                      0
+#define BYTE_OFFSET                     2
+#define XLR_RX_BUF_SIZE                 (MAX_FRAME_SIZE + BYTE_OFFSET + \
+    MAC_PREPAD + MAC_SKB_BACK_PTR_SIZE + SMP_CACHE_BYTES)
+#define MAC_CRC_LEN                     4
+#define MAX_NUM_MSGRNG_STN_CC           128
+#define MAX_MSG_SND_ATTEMPTS		100	/* 13 stns x 4 entry msg/stn +
+						   headroom */
+
+#define MAC_FRIN_TO_BE_SENT_THRESHOLD   16
+
+#define MAX_NUM_DESC_SPILL		1024
+#define MAX_FRIN_SPILL                  (MAX_NUM_DESC_SPILL << 2)
+#define MAX_FROUT_SPILL                 (MAX_NUM_DESC_SPILL << 2)
+#define MAX_CLASS_0_SPILL               (MAX_NUM_DESC_SPILL << 2)
+#define MAX_CLASS_1_SPILL               (MAX_NUM_DESC_SPILL << 2)
+#define MAX_CLASS_2_SPILL               (MAX_NUM_DESC_SPILL << 2)
+#define MAX_CLASS_3_SPILL               (MAX_NUM_DESC_SPILL << 2)
+
+#define XLR_MAX_CORE                    8
+
+#define XLR_MAX_NLNA			3
+#define XLR_MAX_MACS                    8
+#define XLR_MAX_TX_FRAGS                14
+#define MAX_P2D_DESC_PER_PORT           512 
+
+#define PHY_STATUS_RETRIES 		25000
+
+
+/* Structs representing hardware data structures */
+struct size_1_desc {
+	uint64_t	entry0;
+};
+
+struct size_2_desc {
+	uint64_t	entry0;
+	uint64_t	entry1;
+};
+
+struct size_3_desc {
+	uint64_t	entry0;
+	uint64_t	entry1;
+	uint64_t	entry2;
+};
+
+struct size_4_desc {
+	uint64_t	entry0;
+	uint64_t	entry1;
+	uint64_t	entry2;
+	uint64_t	entry3;
+};
+
+struct fr_desc {
+	struct size_1_desc d1;
+};
+
+union rx_tx_desc {
+	struct size_2_desc d2;
+	/* struct size_3_desc d3; */
+	/* struct size_4_desc d4; */
+};
+
+
+extern unsigned char xlr_base_mac_addr[];
+
+/* Driver data structures and enums */
+
+typedef enum {
+	xlr_mac_speed_10, xlr_mac_speed_100,
+	xlr_mac_speed_1000, xlr_mac_speed_rsvd
+}		xlr_mac_speed_t;
+
+typedef enum {
+	xlr_mac_duplex_auto, xlr_mac_duplex_half,
+	xlr_mac_duplex_full
+}		xlr_mac_duplex_t;
+
+typedef enum {
+	xlr_mac_link_down,
+	xlr_mac_link_up,
+}		xlr_mac_link_t;
+
+typedef enum {
+	xlr_mac_fc_auto, xlr_mac_fc_disabled, xlr_mac_fc_frame,
+	xlr_mac_fc_collision, xlr_mac_fc_carrier
+}		xlr_mac_fc_t;
+
+enum {
+        SGMII_SPEED_10   = 0x00000000,
+        SGMII_SPEED_100  = 0x02000000,
+        SGMII_SPEED_1000 = 0x04000000,
+};
+
+struct nlge_softc;
+
+/*
+ * A data-structure to hold a set of related ports. The "sense" in which they
+ * are related is defined by the user of this data-structure. 
+ *
+ * One example: a set of ports that are controlled thru a single MDIO line. 
+ */
+struct nlge_port_set {
+	struct nlge_softc **port_vec;
+	uint32_t	   vec_sz;
+};
+
+/*
+ * nlna_softc has Network Accelerator (NA) attributes that are necessary to 
+ * configure the h/w registers of this block. All the commmon configuration
+ * for a set of GMAC ports controlled by an NA is done from here.
+ */
+struct nlna_softc {
+        device_t	nlna_dev;
+
+        uint32_t	num_ports;
+        int		na_type;
+        int		mac_type;
+        xlr_reg_t	*base;
+
+	struct fr_desc *frin_spill;
+	struct fr_desc *frout_spill;
+	union rx_tx_desc *class_0_spill;
+	union rx_tx_desc *class_1_spill;
+	union rx_tx_desc *class_2_spill;
+	union rx_tx_desc *class_3_spill;
+	uint32_t	rfrbucket;
+	uint32_t	station_id;
+	
+	struct nlge_softc *child_sc[XLR_MAX_MACS];
+
+	/*
+	 * Set of ports controlled/configured by the MII line 
+	 * of this network accelerator.
+	 */
+	struct nlge_port_set mdio_set;
+	struct nlge_softc *mdio_sc[XLR_MAX_MACS];
+};
+
+struct nlge_softc {
+	struct ifnet 	*nlge_if;	/* should be first member - cf.
+					   mii.c:miibus_attach() */
+	struct mii_data nlge_mii;
+	struct nlge_port_set *mdio_pset;
+        device_t        nlge_dev;
+	device_t	mii_bus;
+        xlr_reg_t	*base;
+        xlr_reg_t	*mii_base;
+        xlr_reg_t	*pcs_addr;
+        xlr_reg_t	*serdes_addr;
+        int		port_type;
+	xlr_mac_speed_t	speed;
+	xlr_mac_duplex_t duplex;
+	xlr_mac_link_t	link;
+	xlr_mac_fc_t	flow_ctrl;
+        uint32_t	id;
+        uint32_t	instance;
+	uint32_t	phy_addr;
+	uint32_t	tx_bucket_id;
+	uint8_t		dev_addr[ETHER_ADDR_LEN];
+	struct mtx 	sc_lock;
+};
+
+
+struct nlge_tx_desc {
+	uint64_t	frag[XLR_MAX_TX_FRAGS + 2];
+};
+
+#define MAX_TX_RING_SIZE        (XLR_MAX_MACS * MAX_P2D_DESC_PER_PORT *\
+    sizeof(struct p2d_tx_desc))
+
+#define NLGE_WRITE(base, off, val)		xlr_write_reg(base, off, val)
+#define NLGE_READ(base, off)			xlr_read_reg(base, off)
+#define NLGE_UPDATE(base, off, val, mask)	\
+			do {						\
+				uint32_t	rd_val, wrt_val;	\
+				rd_val = NLGE_READ(base, off);		\
+				wrt_val = (rd_val & ~mask) | (val & mask);	\
+				NLGE_WRITE(base, off, wrt_val);		\
+			} while (0)
+
+#define NLGE_LOCK_INIT(_sc, _name) \
+	mtx_init(&(_sc)->sc_lock, _name, MTX_NETWORK_LOCK, MTX_DEF)
+#define NLGE_LOCK_DESTROY(_sc)	mtx_destroy(&(_sc)->sc_lock)
+#define NLGE_LOCK(_sc)		mtx_lock(&(_sc)->sc_lock)
+#define NLGE_UNLOCK(_sc)	mtx_unlock(&(_sc)->sc_lock)
+#define NLGE_LOCK_ASSERT(_sc)	mtx_assert(&(_sc)->sc_lock, MA_OWNED)
+
diff --git a/sys/mips/rmi/files.xlr b/sys/mips/rmi/files.xlr
index ace84421cb5..e96fc43789f 100644
--- a/sys/mips/rmi/files.xlr
+++ b/sys/mips/rmi/files.xlr
@@ -21,6 +21,7 @@ mips/rmi/bus_space_rmi_pci.c			standard
 mips/rmi/dev/sec/rmisec.c			optional rmisec
 mips/rmi/dev/sec/rmilib.c			optional rmisec
 mips/rmi/dev/xlr/rge.c				optional rge
+mips/rmi/dev/nlge/if_nlge.c			optional nlge
 dev/iicbus/xlr_rtc.c				optional xlr_rtc
 dev/iicbus/xlr_temperature.c			optional xlr_temperature
 dev/iicbus/xlr_eeprom.c				optional xlr_eeprom
diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index fc18732488b..be6856421ed 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -108,13 +108,14 @@ iodi_setup_intr(device_t dev, device_t child,
     struct resource *ires, int flags, driver_filter_t * filt,
     driver_intr_t *intr, void *arg, void **cookiep)
 {
+	const char *name = device_get_name(child);
 
-	if (strcmp(device_get_name(child), "uart") == 0) {
+	if (strcmp(name, "uart") == 0) {
 		/* FIXME uart 1? */
 		cpu_establish_hardintr("uart", filt, intr, arg,
 		    PIC_UART_0_IRQ, flags, cookiep);
 		pic_setup_intr(PIC_IRT_UART_0_INDEX, PIC_UART_0_IRQ, 0x1, 0);
-	} else if (strcmp(device_get_name(child), "rge") == 0) {
+	} else if (strcmp(name, "rge") == 0 || strcmp(name, "nlge") == 0) {
 		int irq;
 
 		/* This is a hack to pass in the irq */
@@ -122,16 +123,15 @@ iodi_setup_intr(device_t dev, device_t child,
 		cpu_establish_hardintr("rge", filt, intr, arg, irq, flags,
 		    cookiep);
 		pic_setup_intr(irq - PIC_IRQ_BASE, irq, 0x1, 0);
-	} else if (strcmp(device_get_name(child), "ehci") == 0) {
+	} else if (strcmp(name, "ehci") == 0) {
 		cpu_establish_hardintr("ehci", filt, intr, arg, PIC_USB_IRQ, flags,
 		    cookiep);
 		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1, 0);
-	} else if (strcmp(device_get_name(child), "ata") == 0) {
+	} else if (strcmp(name, "ata") == 0) {
 		xlr_establish_intr("ata", filt, intr, arg, PIC_PCMCIA_IRQ, flags,
 		    cookiep, bridge_pcmcia_ack);
 		pic_setup_intr(PIC_PCMCIA_IRQ - PIC_IRQ_BASE, PIC_PCMCIA_IRQ, 0x1, 0);
 	}
-
 	return (0);
 }
 
@@ -194,6 +194,7 @@ iodi_activate_resource(device_t bus, device_t child, int type, int rid,
 /* prototypes */
 static int iodi_probe(device_t);
 static int iodi_attach(device_t);
+static int iodi_detach(device_t);
 static void iodi_identify(driver_t *, device_t);
 
 int
@@ -213,6 +214,7 @@ int
 iodi_attach(device_t dev)
 {
 	device_t tmpd;
+	int i;
 
 	/*
 	 * Attach each devices
@@ -268,17 +270,47 @@ iodi_attach(device_t dev)
 			tmpd = device_add_child(dev, "rge", 5);
 			device_set_ivars(tmpd, &xlr_board_info.gmac_block[1]);
 #endif
-		} else
-			device_printf(dev, "Unknown type of gmac 1\n");
+		} else 
+			device_printf(dev, "Unknown type of gmac 1\n"); 
+	}
+
+	/* This is to add the new GMAC driver. The above adds the old driver,
+	   which has been retained for now as the new driver is stabilized.
+	   The new driver is enabled with "option nlge". Make sure that only
+	   one of rge or nlge is enabled in the conf file. */
+	for (i = 0; i < 3; i++) {
+		if (xlr_board_info.gmac_block[i].enabled == 0)
+			continue;
+		tmpd = device_add_child(dev, "nlna", i);
+		device_set_ivars(tmpd, &xlr_board_info.gmac_block[i]);
 	}
 	bus_generic_probe(dev);
 	bus_generic_attach(dev);
 	return 0;
 }
 
+int
+iodi_detach(device_t dev)
+{
+	device_t nlna_dev;
+	int error, i, ret;
+
+	error = 0;
+	ret = 0;
+	for (i = 0; i < 3; i++) {
+		nlna_dev = device_find_child(dev, "nlna", i);
+		if (nlna_dev != NULL)
+			error = bus_generic_detach(nlna_dev);
+		if (error)
+			ret = error;
+	}
+	return ret;
+}
+
 static device_method_t iodi_methods[] = {
 	DEVMETHOD(device_probe, iodi_probe),
 	DEVMETHOD(device_attach, iodi_attach),
+	DEVMETHOD(device_detach, iodi_detach),
 	DEVMETHOD(device_identify, iodi_identify),
 	DEVMETHOD(bus_alloc_resource, iodi_alloc_resource),
 	DEVMETHOD(bus_activate_resource, iodi_activate_resource),

From 3e9e888541f743b94652575b03bd06ca39a350c9 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sat, 28 Aug 2010 19:28:12 +0000
Subject: [PATCH 0328/1624] Move ZUT_OBJS in the same place that is used in
 vendor code.

Obtained from:	//depot/user/pjd/zfs/...
---
 sys/cddl/contrib/opensolaris/uts/common/Makefile.files | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/Makefile.files b/sys/cddl/contrib/opensolaris/uts/common/Makefile.files
index 3761d5ed31f..2aaf5bcdaff 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/Makefile.files
+++ b/sys/cddl/contrib/opensolaris/uts/common/Makefile.files
@@ -19,9 +19,6 @@
 # CDDL HEADER END
 #
 
-ZUT_OBJS +=			\
-	zut.o
-
 #
 # Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 # Use is subject to license terms.
@@ -109,3 +106,6 @@ ZFS_OBJS +=			\
 	zfs_vfsops.o		\
 	zfs_vnops.o		\
 	zvol.o
+
+ZUT_OBJS +=			\
+	zut.o

From b8a4becc2d57beb4e92baedeeee55b88222d008e Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sat, 28 Aug 2010 19:29:06 +0000
Subject: [PATCH 0329/1624] Return NULL pointer instead of B_FALSE as it is
 done in the vendor code.

Obtained from:	//depot/user/pjd/zfs/...
---
 sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c
index f09c984651e..4cef53f9513 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c
@@ -82,7 +82,7 @@ rrn_find(rrwlock_t *rrl)
 	rrw_node_t *rn;
 
 	if (refcount_count(&rrl->rr_linked_rcount) == 0)
-		return (B_FALSE);
+		return (NULL);
 
 	for (rn = tsd_get(rrw_tsd_key); rn != NULL; rn = rn->rn_next) {
 		if (rn->rn_rrl == rrl)

From 9bc38a3ba251eced4be304b0024f93b2947a3d26 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Sat, 28 Aug 2010 21:06:13 +0000
Subject: [PATCH 0330/1624] Now that we default to the proper endian, we don't
 need these for mips

---
 share/mk/bsd.cpu.mk | 7 -------
 1 file changed, 7 deletions(-)

diff --git a/share/mk/bsd.cpu.mk b/share/mk/bsd.cpu.mk
index a748c6959f3..e3ad18b98d4 100644
--- a/share/mk/bsd.cpu.mk
+++ b/share/mk/bsd.cpu.mk
@@ -203,13 +203,6 @@ LD += -EB
 .endif
 
 .if ${MACHINE_ARCH} == "mips" 
-. if defined(TARGET_BIG_ENDIAN)
-CFLAGS += -EB
-LD += -EB
-. else
-CFLAGS += -EL
-LD += -EL
-. endif
 CFLAGS += -G0
 .endif
 

From e24ea413e0d0d376bbae627ecf629ba9c0bbf9bb Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Sat, 28 Aug 2010 21:15:00 +0000
Subject: [PATCH 0331/1624] Bugfix: Do not send a packet drop report in
 response to a received         INIT-ACK with incorrect CRC.

---
 sys/netinet/sctp_output.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index aa771a65899..d322d07fd1d 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -11001,9 +11001,12 @@ sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
 		switch (ch->chunk_type) {
 		case SCTP_PACKET_DROPPED:
 		case SCTP_ABORT_ASSOCIATION:
-			/*-
-			 * we don't respond with an PKT-DROP to an ABORT
-			 * or PKT-DROP
+		case SCTP_INITIATION_ACK:
+			/**
+			 * We don't respond with an PKT-DROP to an ABORT
+			 * or PKT-DROP. We also do not respond to an
+			 * INIT-ACK, because we can't know if the initiation
+			 * tag is correct or not.
 			 */
 			sctp_free_a_chunk(stcb, chk);
 			return;

From 2ec3f925280b599ce2f87a66f35bfac27462c1d3 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Sat, 28 Aug 2010 21:41:18 +0000
Subject: [PATCH 0332/1624] The timer routine in the experimental NFS server
 did not acquire the correct mutex when checking nfsv4root_lock. Although this
 could be fixed by adding mutex lock/unlock calls, zack.kirsch at isilon.com
 suggested a better fix that uses a non-blocking acquisition of a reference
 count on nfsv4root_lock. This fix allows the weird NFSLOCKSTATE();
 NFSUNLOCKSTATE(); synchronization to be deleted. This patch applies this fix.

Tested by:	zack.kirsch at isilon.com
MFC after:	2 weeks
---
 sys/fs/nfs/nfs_commonsubs.c       | 15 ++++++++++++++
 sys/fs/nfs/nfs_var.h              |  1 +
 sys/fs/nfsserver/nfs_nfsdsocket.c |  2 --
 sys/fs/nfsserver/nfs_nfsdstate.c  | 33 +++++++++++--------------------
 4 files changed, 28 insertions(+), 23 deletions(-)

diff --git a/sys/fs/nfs/nfs_commonsubs.c b/sys/fs/nfs/nfs_commonsubs.c
index dc5b2dcc991..6585fced6d5 100644
--- a/sys/fs/nfs/nfs_commonsubs.c
+++ b/sys/fs/nfs/nfs_commonsubs.c
@@ -1823,6 +1823,21 @@ nfsv4_getref(struct nfsv4lock *lp, int *isleptp, void *mutex)
 	lp->nfslock_usecnt++;
 }
 
+/*
+ * Get a reference as above, but return failure instead of sleeping if
+ * an exclusive lock is held.
+ */
+APPLESTATIC int
+nfsv4_getref_nonblock(struct nfsv4lock *lp)
+{
+
+	if ((lp->nfslock_lock & NFSV4LOCK_LOCK) != 0)
+		return (0);
+
+	lp->nfslock_usecnt++;
+	return (1);
+}
+
 /*
  * Test for a lock. Return 1 if locked, 0 otherwise.
  */
diff --git a/sys/fs/nfs/nfs_var.h b/sys/fs/nfs/nfs_var.h
index d6ecda21731..d46983fa97e 100644
--- a/sys/fs/nfs/nfs_var.h
+++ b/sys/fs/nfs/nfs_var.h
@@ -251,6 +251,7 @@ int nfsv4_lock(struct nfsv4lock *, int, int *, void *);
 void nfsv4_unlock(struct nfsv4lock *, int);
 void nfsv4_relref(struct nfsv4lock *);
 void nfsv4_getref(struct nfsv4lock *, int *, void *);
+int nfsv4_getref_nonblock(struct nfsv4lock *);
 int nfsv4_testlock(struct nfsv4lock *);
 int nfsrv_mtostr(struct nfsrv_descript *, char *, int);
 int nfsrv_checkutf8(u_int8_t *, int);
diff --git a/sys/fs/nfsserver/nfs_nfsdsocket.c b/sys/fs/nfsserver/nfs_nfsdsocket.c
index c95fef22a46..af1a3fa7e95 100644
--- a/sys/fs/nfsserver/nfs_nfsdsocket.c
+++ b/sys/fs/nfsserver/nfs_nfsdsocket.c
@@ -533,8 +533,6 @@ nfsrvd_compound(struct nfsrv_descript *nd, int isdgram,
 		    NFSV4ROOTLOCKMUTEXPTR);
 	NFSUNLOCKV4ROOTMUTEX();
 	if (igotlock) {
-		NFSLOCKSTATE();	/* to avoid a race with */
-		NFSUNLOCKSTATE();	/* nfsrv_servertimer() */
 		/*
 		 * If I got the lock, I can update the stable storage file.
 		 * Done when the grace period is over or a client has long
diff --git a/sys/fs/nfsserver/nfs_nfsdstate.c b/sys/fs/nfsserver/nfs_nfsdstate.c
index 6c89e6b2d9b..c96907e8d3e 100644
--- a/sys/fs/nfsserver/nfs_nfsdstate.c
+++ b/sys/fs/nfsserver/nfs_nfsdstate.c
@@ -164,8 +164,6 @@ nfsrv_setclient(struct nfsrv_descript *nd, struct nfsclient **new_clpp,
 		    NFSV4ROOTLOCKMUTEXPTR);
 	} while (!igotlock);
 	NFSUNLOCKV4ROOTMUTEX();
-	NFSLOCKSTATE();	/* to avoid a race with */
-	NFSUNLOCKSTATE();	/* nfsrv_servertimer() */
 
 	/*
 	 * Search for a match in the client list.
@@ -416,8 +414,6 @@ nfsrv_getclient(nfsquad_t clientid, int opflags, struct nfsclient **clpp,
 			    NFSV4ROOTLOCKMUTEXPTR);
 		} while (!igotlock);
 		NFSUNLOCKV4ROOTMUTEX();
-		NFSLOCKSTATE();	/* to avoid a race with */
-		NFSUNLOCKSTATE();	/* nfsrv_servertimer() */
 	} else if (opflags != CLOPS_RENEW) {
 		NFSLOCKSTATE();
 	}
@@ -547,8 +543,6 @@ nfsrv_adminrevoke(struct nfsd_clid *revokep, NFSPROC_T *p)
 		    NFSV4ROOTLOCKMUTEXPTR);
 	} while (!igotlock);
 	NFSUNLOCKV4ROOTMUTEX();
-	NFSLOCKSTATE();	/* to avoid a race with */
-	NFSUNLOCKSTATE();	/* nfsrv_servertimer() */
 
 	/*
 	 * Search for a match in the client list.
@@ -824,11 +818,8 @@ nfsrv_dumplocks(vnode_t vp, struct nfsd_dumplocks *ldumpp, int maxcnt,
 
 /*
  * Server timer routine. It can scan any linked list, so long
- * as it holds the spin lock and there is no exclusive lock on
+ * as it holds the spin/mutex lock and there is no exclusive lock on
  * nfsv4rootfs_lock.
- * Must be called by a kernel thread and not a timer interrupt,
- * so that it only runs when the nfsd threads are sleeping on a
- * uniprocessor and uses the State spin lock for an SMP system.
  * (For OpenBSD, a kthread is ok. For FreeBSD, I think it is ok
  *  to do this from a callout, since the spin locks work. For
  *  Darwin, I'm not sure what will work correctly yet.)
@@ -839,7 +830,7 @@ nfsrv_servertimer(void)
 {
 	struct nfsclient *clp, *nclp;
 	struct nfsstate *stp, *nstp;
-	int i;
+	int got_ref, i;
 
 	/*
 	 * Make sure nfsboottime is set. This is used by V3 as well
@@ -867,13 +858,14 @@ nfsrv_servertimer(void)
 	}
 
 	/*
-	 * Return now if an nfsd thread has the exclusive lock on
-	 * nfsv4rootfs_lock. The dirty trick here is that we have
-	 * the spin lock already and the nfsd threads do a:
-	 * NFSLOCKSTATE, NFSUNLOCKSTATE after getting the exclusive
-	 * lock, so they won't race with code after this check.
+	 * Try and get a reference count on the nfsv4rootfs_lock so that
+	 * no nfsd thread can acquire an exclusive lock on it before this
+	 * call is done. If it is already exclusively locked, just return.
 	 */
-	if (nfsv4rootfs_lock.nfslock_lock & NFSV4LOCK_LOCK) {
+	NFSLOCKV4ROOTMUTEX();
+	got_ref = nfsv4_getref_nonblock(&nfsv4rootfs_lock);
+	NFSUNLOCKV4ROOTMUTEX();
+	if (got_ref == 0) {
 		NFSUNLOCKSTATE();
 		return;
 	}
@@ -945,6 +937,9 @@ nfsrv_servertimer(void)
 	    }
 	}
 	NFSUNLOCKSTATE();
+	NFSLOCKV4ROOTMUTEX();
+	nfsv4_relref(&nfsv4rootfs_lock);
+	NFSUNLOCKV4ROOTMUTEX();
 }
 
 /*
@@ -4224,8 +4219,6 @@ nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, __unused vnode_t vp,
 			    NFSV4ROOTLOCKMUTEXPTR);
 		} while (!gotlock);
 		NFSUNLOCKV4ROOTMUTEX();
-		NFSLOCKSTATE();	/* to avoid a race with */
-		NFSUNLOCKSTATE();	/* nfsrv_servertimer() */
 		*haslockp = 1;
 		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY, p);
 		return (1);
@@ -4390,8 +4383,6 @@ nfsrv_delegconflict(struct nfsstate *stp, int *haslockp, NFSPROC_T *p,
 			    NFSV4ROOTLOCKMUTEXPTR);
 		} while (!gotlock);
 		NFSUNLOCKV4ROOTMUTEX();
-		NFSLOCKSTATE();	/* to avoid a race with */
-		NFSUNLOCKSTATE();	/* nfsrv_servertimer() */
 		*haslockp = 1;
 		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY, p);
 		return (-1);

From b5cb66df259b869ec637decc25714ef6a67fe60d Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Sat, 28 Aug 2010 23:50:09 +0000
Subject: [PATCH 0333/1624] Add acquisition of a reference count on
 nfsv4root_lock to the nfsd_recalldelegation() function, since this function
 is called by nfsd threads when they are handling NFSv2 or NFSv3 RPCs, where
 no reference count would have been acquired.

MFC after:	2 weeks
---
 sys/fs/nfsserver/nfs_nfsdstate.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/sys/fs/nfsserver/nfs_nfsdstate.c b/sys/fs/nfsserver/nfs_nfsdstate.c
index c96907e8d3e..a53175154d0 100644
--- a/sys/fs/nfsserver/nfs_nfsdstate.c
+++ b/sys/fs/nfsserver/nfs_nfsdstate.c
@@ -4562,6 +4562,14 @@ nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
 	    nfsrv_issuedelegs == 0)
 		return;
 
+	/*
+	 * First, get a reference on the nfsv4rootfs_lock so that an
+	 * exclusive lock cannot be acquired by another thread.
+	 */
+	NFSLOCKV4ROOTMUTEX();
+	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR);
+	NFSUNLOCKV4ROOTMUTEX();
+
 	/*
 	 * Now, call nfsrv_checkremove() in a loop while it returns
 	 * NFSERR_DELAY. Return upon any other error or when timed out.
@@ -4576,11 +4584,14 @@ nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
 			    NFS_REMOVETIMEO &&
 			    ((u_int32_t)mytime.tv_sec - starttime) <
 			    100000)
-				return;
+				break;
 			/* Sleep for a short period of time */
 			(void) nfs_catnap(PZERO, 0, "nfsremove");
 		}
 	} while (error == NFSERR_DELAY);
+	NFSLOCKV4ROOTMUTEX();
+	nfsv4_relref(&nfsv4rootfs_lock);
+	NFSUNLOCKV4ROOTMUTEX();
 }
 
 APPLESTATIC void

From 9ebbcfd58bd6214a143355d0a3c1e6a03f1a8d3d Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Sun, 29 Aug 2010 05:39:21 +0000
Subject: [PATCH 0334/1624] Apply MIPS pmap clean up patch from alc@ (with
 minor change to KASSERT):

  PMAP_DIAGNOSTIC was eliminated from amd64/i386, and, in fact, the
  non-MIPS parts of the kernel, several years ago.  Any of the interesting
  checks were turned into KASSERT()s.  Basically, the motivation was that
  lots of people run with INVARIANTS but no one runs with DIAGNOSTIC.

  panic strings needn't and shouldn't have a terminating newline.

  Finally, there is one functional change.  The sched_pin() in
  pmap_remove_pages() is an artifact of the way we temporarily map page
  table pages on i386.  (The mappings are processor private.  We don't do
  a system-wide shootdown.)  It isn't needed by MIPS.

Tested by: jchandra

Submitted by:	alc
---
 sys/mips/include/pmap.h |  5 ---
 sys/mips/mips/pmap.c    | 76 ++++++++---------------------------------
 2 files changed, 14 insertions(+), 67 deletions(-)

diff --git a/sys/mips/include/pmap.h b/sys/mips/include/pmap.h
index 543251995fd..e6aada96705 100644
--- a/sys/mips/include/pmap.h
+++ b/sys/mips/include/pmap.h
@@ -126,11 +126,6 @@ typedef struct pv_entry {
 	vm_page_t pv_ptem;	/* VM page for pte */
 }       *pv_entry_t;
 
-
-#if defined(DIAGNOSTIC)
-#define	PMAP_DIAGNOSTIC
-#endif
-
 /*
  * physmem_desc[] is a superset of phys_avail[] and describes all the
  * memory present in the system.
diff --git a/sys/mips/mips/pmap.c b/sys/mips/mips/pmap.c
index 2ff6f1c3491..89332d3168c 100644
--- a/sys/mips/mips/pmap.c
+++ b/sys/mips/mips/pmap.c
@@ -105,17 +105,13 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 
-#if defined(DIAGNOSTIC)
-#define	PMAP_DIAGNOSTIC
-#endif
-
 #undef PMAP_DEBUG
 
 #ifndef PMAP_SHPGPERPROC
 #define	PMAP_SHPGPERPROC 200
 #endif
 
-#if !defined(PMAP_DIAGNOSTIC)
+#if !defined(DIAGNOSTIC)
 #define	PMAP_INLINE __inline
 #else
 #define	PMAP_INLINE
@@ -635,22 +631,6 @@ pmap_init(void)
  * Low level helper routines.....
  ***************************************************/
 
-#if defined(PMAP_DIAGNOSTIC)
-
-/*
- * This code checks for non-writeable/modified pages.
- * This should be an invalid condition.
- */
-static int
-pmap_nw_modified(pt_entry_t pte)
-{
-	if ((pte & (PTE_D | PTE_RO)) == (PTE_D | PTE_RO))
-		return (1);
-	else
-		return (0);
-}
-#endif
-
 static __inline void
 pmap_invalidate_all_local(pmap_t pmap)
 {
@@ -1598,13 +1578,9 @@ pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, vm_offset_t va)
 	if (page_is_managed(pa)) {
 		m = PHYS_TO_VM_PAGE(pa);
 		if (pte_test(&oldpte, PTE_D)) {
-#if defined(PMAP_DIAGNOSTIC)
-			if (pmap_nw_modified(oldpte)) {
-				printf(
-				    "pmap_remove: modified page not writable: va: 0x%x, pte: 0x%x\n",
-				    va, oldpte);
-			}
-#endif
+			KASSERT(!pte_test(&oldpte, PTE_RO),
+			    ("%s: modified page not writable: va: %p, pte: 0x%x",
+			    __func__, (void *)va, oldpte));
 			vm_page_dirty(m);
 		}
 		if (m->md.pv_flags & PV_TABLE_REF)
@@ -1761,13 +1737,9 @@ pmap_remove_all(vm_page_t m)
 		 * Update the vm_page_t clean and reference bits.
 		 */
 		if (pte_test(&tpte, PTE_D)) {
-#if defined(PMAP_DIAGNOSTIC)
-			if (pmap_nw_modified(tpte)) {
-				printf(
-				    "pmap_remove_all: modified page not writable: va: 0x%x, pte: 0x%x\n",
-				    pv->pv_va, tpte);
-			}
-#endif
+			KASSERT(!pte_test(&tpte, PTE_RO),
+			    ("%s: modified page not writable: va: %p, pte: 0x%x",
+			    __func__, (void *)pv->pv_va, tpte));
 			vm_page_dirty(m);
 		}
 		pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
@@ -1908,7 +1880,7 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_prot_t access, vm_page_t m,
 	 * Page Directory table entry not valid, we need a new PT page
 	 */
 	if (pte == NULL) {
-		panic("pmap_enter: invalid page directory, pdir=%p, va=%p\n",
+		panic("pmap_enter: invalid page directory, pdir=%p, va=%p",
 		    (void *)pmap->pm_segtab, (void *)va);
 	}
 	pa = VM_PAGE_TO_PHYS(m);
@@ -1931,13 +1903,9 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_prot_t access, vm_page_t m,
 		else if (!wired && pte_test(&origpte, PTE_W))
 			pmap->pm_stats.wired_count--;
 
-#if defined(PMAP_DIAGNOSTIC)
-		if (pmap_nw_modified(origpte)) {
-			printf(
-			    "pmap_enter: modified page not writable: va: 0x%x, pte: 0x%x\n",
-			    va, origpte);
-		}
-#endif
+		KASSERT(!pte_test(&origpte, PTE_D | PTE_RO),
+		    ("%s: modified page not writable: va: %p, pte: 0x%x",
+		    __func__, (void *)va, origpte));
 
 		/*
 		 * Remove extra pte reference
@@ -2529,13 +2497,11 @@ pmap_remove_pages(pmap_t pmap)
 	}
 	vm_page_lock_queues();
 	PMAP_LOCK(pmap);
-	sched_pin();
-	//XXX need to be TAILQ_FOREACH_SAFE ?
-	for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
+	for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv != NULL; pv = npv) {
 
 		pte = pmap_pte(pv->pv_pmap, pv->pv_va);
 		if (!pte_test(pte, PTE_V))
-			panic("pmap_remove_pages: page on pm_pvlist has no pte\n");
+			panic("pmap_remove_pages: page on pm_pvlist has no pte");
 		tpte = *pte;
 
 /*
@@ -2570,7 +2536,6 @@ pmap_remove_pages(pmap_t pmap)
 		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
 		free_pv_entry(pv);
 	}
-	sched_unpin();
 	pmap_invalidate_all(pmap);
 	PMAP_UNLOCK(pmap);
 	vm_page_unlock_queues();
@@ -2596,12 +2561,6 @@ pmap_testbit(vm_page_t m, int bit)
 
 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
-#if defined(PMAP_DIAGNOSTIC)
-		if (!pv->pv_pmap) {
-			printf("Null pmap (tb) at va: 0x%x\n", pv->pv_va);
-			continue;
-		}
-#endif
 		PMAP_LOCK(pv->pv_pmap);
 		pte = pmap_pte(pv->pv_pmap, pv->pv_va);
 		rv = pte_test(pte, bit);
@@ -2630,13 +2589,6 @@ pmap_changebit(vm_page_t m, int bit, boolean_t setem)
 	 * setting RO do we need to clear the VAC?
 	 */
 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
-#if defined(PMAP_DIAGNOSTIC)
-		if (!pv->pv_pmap) {
-			printf("Null pmap (cb) at va: 0x%x\n", pv->pv_va);
-			continue;
-		}
-#endif
-
 		PMAP_LOCK(pv->pv_pmap);
 		pte = pmap_pte(pv->pv_pmap, pv->pv_va);
 		if (setem) {
@@ -2723,7 +2675,7 @@ pmap_remove_write(vm_page_t m)
 		npv = TAILQ_NEXT(pv, pv_plist);
 		pte = pmap_pte(pv->pv_pmap, pv->pv_va);
 		if (pte == NULL || !pte_test(pte, PTE_V))
-			panic("page on pm_pvlist has no pte\n");
+			panic("page on pm_pvlist has no pte");
 
 		va = pv->pv_va;
 		pmap_protect(pv->pv_pmap, va, va + PAGE_SIZE,

From b2d89ed701b83a173b01f7b479adb7df4c1d7d53 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ulrich=20Sp=C3=B6rlein?= 
Date: Sun, 29 Aug 2010 11:32:41 +0000
Subject: [PATCH 0335/1624] gsched(8): fix example usage, mdoc nits

- ad0 was referred to as da0
- wrong parameter -s instead of -a in example
- use double quotes consistently

PR:            docs/150082
Submitted by:  N.J. Mann 
MFC after:     2 weeks
---
 sbin/geom/class/sched/gsched.8 | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/sbin/geom/class/sched/gsched.8 b/sbin/geom/class/sched/gsched.8
index caa8417db23..7e6b1134e89 100644
--- a/sbin/geom/class/sched/gsched.8
+++ b/sbin/geom/class/sched/gsched.8
@@ -25,7 +25,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd April 12, 2010
+.Dd August 29, 2010
 .Dt GSCHED 8
 .Os
 .Sh NAME
@@ -92,7 +92,7 @@ which in turn forwards requests to the existing geom.
 This operation allows one to start/stop a scheduling service
 on an already existing provider.
 .Pp
-A subsequent 'destroy' will remove the newly created geom and
+A subsequent "destroy" will remove the newly created geom and
 hook the provider back to the original geom.
 .It Cm configure
 Configure existing scheduling provider.  It supports the same options
@@ -135,16 +135,16 @@ maximum amount of debug information is printed.
 Exit status is 0 on success, and 1 if the command fails.
 .Sh EXAMPLES
 The following example shows how to create a scheduling provider for disk
-.Pa /dev/da0
-, and how to destroy it.
+.Pa /dev/ad0 ,
+and how to destroy it.
 .Bd -literal -offset indent
 # Load the geom_sched module:
 kldload geom_sched
 # Load some scheduler classes used by geom_sched:
 kldload gsched_rr gsched_as
-# Configure device ad0 to use scheduler 'rr':
-geom sched insert -s rr ad0
-# Now provider ad0 uses the 'rr' algorithm;
+# Configure device ad0 to use scheduler "rr":
+geom sched insert -a rr ad0
+# Now provider ad0 uses the "rr" algorithm;
 # the new geom is ad0.sched.
 # Remove the scheduler on the device:
 geom sched destroy -v ad0.sched.

From cd14b457565dfc1669c2e598ddc0b3e4bdd3f429 Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Sun, 29 Aug 2010 11:56:56 +0000
Subject: [PATCH 0336/1624] Correct an out-by-one error when earlying out ustar
 filenames that are too long.  Filenames escaping this test are caught later
 on, so the bug doesn't cause any breakage.

Document the correct ustar limitations in pax.  As I have no access
to the IEEE 1003.2 spec, I can only assume that the limitations
imposed are in fact correct.

Add regression tests for the filename limitations imposed by pax.

MFC after:	3 weeks
---
 bin/pax/pax.1                      |  4 +-
 bin/pax/tar.c                      |  2 +-
 tools/regression/bin/pax/Makefile  |  8 +++
 tools/regression/bin/pax/regress.t | 91 ++++++++++++++++++++++++++++++
 4 files changed, 103 insertions(+), 2 deletions(-)
 create mode 100644 tools/regression/bin/pax/Makefile
 create mode 100755 tools/regression/bin/pax/regress.t

diff --git a/bin/pax/pax.1 b/bin/pax/pax.1
index 373ec9baa9d..58fba132bab 100644
--- a/bin/pax/pax.1
+++ b/bin/pax/pax.1
@@ -748,7 +748,9 @@ The extended tar interchange format specified in the
 .St -p1003.2
 standard.
 The default blocksize for this format is 10240 bytes.
-Pathnames stored by this format must be 250 characters or less in length.
+Pathnames stored by this format must be 255 characters or less in length.
+The directory part may be at most 155 characters and each path component
+must be less than 100 characters.
 .El
 .Pp
 The
diff --git a/bin/pax/tar.c b/bin/pax/tar.c
index e274df47cf7..05e8be57ee5 100644
--- a/bin/pax/tar.c
+++ b/bin/pax/tar.c
@@ -1086,7 +1086,7 @@ name_split(char *name, int len)
 	 */
 	if (len <= TNMSZ)
 		return(name);
-	if (len > (TPFSZ + TNMSZ + 1))
+	if (len > TPFSZ + TNMSZ)
 		return(NULL);
 
 	/*
diff --git a/tools/regression/bin/pax/Makefile b/tools/regression/bin/pax/Makefile
new file mode 100644
index 00000000000..dc1a317928d
--- /dev/null
+++ b/tools/regression/bin/pax/Makefile
@@ -0,0 +1,8 @@
+# $FreeBSD$
+
+test:
+	prove -vmw regress.t
+
+clean:
+	rm -rf ustar-pathnames-[12]
+	rm -f ustar.ok ustar.fail*
diff --git a/tools/regression/bin/pax/regress.t b/tools/regression/bin/pax/regress.t
new file mode 100755
index 00000000000..7c392cbb765
--- /dev/null
+++ b/tools/regression/bin/pax/regress.t
@@ -0,0 +1,91 @@
+#! /usr/bin/perl
+#
+# $FreeBSD$
+
+use strict;
+use warnings;
+
+use Test::More tests => 6;
+use File::Path qw(rmtree mkpath);
+use Cwd;
+
+my $n = 0;
+sub create_file {
+    my $fn = shift;
+
+    $n++;
+    (my $dir = $fn) =~ s,/[^/]+$,,;
+    mkpath $dir;
+    open my $fd, ">", $fn or die "$fn: $!";
+    print $fd "file $n\n";
+}
+
+
+ustar_pathnames: { SKIP: {
+    # Prove that pax breaks up ustar pathnames properly
+
+    my $top = getcwd . "/ustar-pathnames-1";
+    skip "Current path is too long", 6 if length $top > 92;
+    rmtree $top;
+    my $subdir = "x" . "x" x (92 - length $top);
+    my $work94 = "$top/$subdir";
+    mkpath $work94;		# $work is 94 characters long
+
+    my $x49 = "x" x 49;
+    my $x50 = "x" x 50;
+    my $x60 = "x" x 60;
+    my $x95 = "x" x 95;
+
+    my @paths = (
+	"$work94/x099",		# 99 chars
+	"$work94/xx100",		# 100 chars
+	"$work94/xxx101",		# 101 chars
+	"$work94/$x49/${x50}x199",	# 199 chars
+	"$work94/$x49/${x50}xx200",	# 200 chars
+	"$work94/$x49/${x50}xxx201",	# 201 chars
+	"$work94/$x60/${x95}254",	# 254 chars
+	"$work94/$x60/${x95}x255",	# 255 chars
+    );
+
+    my @l = map { length } @paths;
+
+    my $n = 0;
+    create_file $_ for @paths;
+    system "pax -wf ustar.ok $work94";
+    ok($? == 0, "Wrote 'ustar.ok' containing files with lengths @l");
+
+    (my $orig = $top) =~ s,1$,2,;
+    rmtree $orig;
+    rename $top, $orig;
+
+    system "pax -rf ustar.ok";
+    ok($? == 0, "Restored 'ustar.ok' containing files with lengths @l");
+
+    system "diff -ru $orig $top";
+    ok($? == 0, "Restored files are identical");
+
+    rmtree $top;
+    rename $orig, $top;
+
+    # 256 chars (with components < 100 chars) should not work
+    push @paths, "$work94/x$x60/${x95}x256";	# 256 chars
+    push @l, length $paths[-1];
+    create_file $paths[-1];
+    system "pax -wf ustar.fail1 $work94";
+    ok($?, "Failed to write 'ustar.fail1' containing files with lengths @l");
+
+    # Components with 100 chars shouldn't work
+    unlink $paths[-1];
+    $paths[-1] = "$work94/${x95}xc100";		# 100 char filename
+    $l[-1] = length $paths[-1];
+    create_file $paths[-1];
+    system "pax -wf ustar.fail2 $work94";
+    ok($?, "Failed to write 'ustar.fail2' with a 100 char filename");
+
+    unlink $paths[-1];
+    $paths[-1] = "$work94/${x95}xc100/x";	# 100 char component
+    $l[-1] = length $paths[-1];
+    create_file $paths[-1];
+    system "pax -wf ustar.fail3 $work94";
+    ok($?, "Failed to write 'ustar.fail3' with a 100 char component");
+}}

From 25fdbebeb20973a26be543e464f09a8fc8d8bcbd Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Sun, 29 Aug 2010 12:14:53 +0000
Subject: [PATCH 0337/1624] Add a Makefile for tools/regression/bin and support
 'all' in pax/Makefile.

MFC after:	3 weeks
---
 tools/regression/bin/Makefile     | 5 +++++
 tools/regression/bin/pax/Makefile | 2 +-
 2 files changed, 6 insertions(+), 1 deletion(-)
 create mode 100644 tools/regression/bin/Makefile

diff --git a/tools/regression/bin/Makefile b/tools/regression/bin/Makefile
new file mode 100644
index 00000000000..e0e3ea3820b
--- /dev/null
+++ b/tools/regression/bin/Makefile
@@ -0,0 +1,5 @@
+# $FreeBSD$
+
+SUBDIR=	date mv pax sh
+
+.include 
diff --git a/tools/regression/bin/pax/Makefile b/tools/regression/bin/pax/Makefile
index dc1a317928d..6855bca9706 100644
--- a/tools/regression/bin/pax/Makefile
+++ b/tools/regression/bin/pax/Makefile
@@ -1,6 +1,6 @@
 # $FreeBSD$
 
-test:
+all test:
 	prove -vmw regress.t
 
 clean:

From 3b8199dbfc3bb4d563c30b822aece42fea153c80 Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Sun, 29 Aug 2010 12:17:16 +0000
Subject: [PATCH 0338/1624] Touch the man page date after updating the ustar
 limitations.

MFC after:	3 weeks
---
 bin/pax/pax.1 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/bin/pax/pax.1 b/bin/pax/pax.1
index 58fba132bab..33fedf6d233 100644
--- a/bin/pax/pax.1
+++ b/bin/pax/pax.1
@@ -33,7 +33,7 @@
 .\"	@(#)pax.1	8.4 (Berkeley) 4/18/94
 .\" $FreeBSD$
 .\"
-.Dd July 3, 2004
+.Dd August 29, 2010
 .Dt PAX 1
 .Os
 .Sh NAME

From da881cad0763c5931a6ffa4bc197bbd96f210b6d Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sun, 29 Aug 2010 16:38:08 +0000
Subject: [PATCH 0339/1624] Use NULL instead of 0 for pointer in example.

MFC after:	3 days
---
 lib/libc/sys/sigaltstack.2 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libc/sys/sigaltstack.2 b/lib/libc/sys/sigaltstack.2
index 6119c6a3abc..d9cb2736259 100644
--- a/lib/libc/sys/sigaltstack.2
+++ b/lib/libc/sys/sigaltstack.2
@@ -104,7 +104,7 @@ if ((sigstk.ss_sp = malloc(SIGSTKSZ)) == NULL)
 	/* error return */
 sigstk.ss_size = SIGSTKSZ;
 sigstk.ss_flags = 0;
-if (sigaltstack(&sigstk,0) < 0)
+if (sigaltstack(&sigstk, NULL) < 0)
 	perror("sigaltstack");
 .Ed
 An alternative approach is provided for programs with signal handlers

From 7eeda62ca92329b3b4eaedad61e03c782bc5e38a Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Sun, 29 Aug 2010 18:17:38 +0000
Subject: [PATCH 0340/1624] Avoid a race in the allocation of new segment IDs
 that could result in memory corruption on heavily loaded SMP systems.

MFC after:	2 weeks
---
 sys/powerpc/aim/mmu_oea64.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index 962e8ec528b..c1c2651c5c0 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -285,6 +285,7 @@ extern void bs_remap_earlyboot(void);
  * Lock for the pteg and pvo tables.
  */
 struct mtx	moea64_table_mutex;
+struct mtx	moea64_slb_mutex;
 
 /*
  * PTEG data.
@@ -1068,6 +1069,7 @@ moea64_bootstrap(mmu_t mmup, vm_offset_t kernelstart, vm_offset_t kernelend)
 	 */
 	mtx_init(&moea64_table_mutex, "pmap table", NULL, MTX_DEF |
 	    MTX_RECURSE);
+	mtx_init(&moea64_slb_mutex, "SLB table", NULL, MTX_DEF);
 
 	/*
 	 * Initialize the TLBIE lock. TLBIE can only be executed by one CPU.
@@ -2054,6 +2056,7 @@ moea64_get_unique_vsid(void) {
 	entropy = 0;
 	__asm __volatile("mftb %0" : "=r"(entropy));
 
+	mtx_lock(&moea64_slb_mutex);
 	for (i = 0; i < NVSIDS; i += VSID_NBPW) {
 		u_int	n;
 
@@ -2083,9 +2086,11 @@ moea64_get_unique_vsid(void) {
 			hash |= i;
 		}
 		moea64_vsid_bitmap[n] |= mask;
+		mtx_unlock(&moea64_slb_mutex);
 		return (hash);
 	}
 
+	mtx_unlock(&moea64_slb_mutex);
 	panic("%s: out of segments",__func__);
 }
 

From 9c7635e18b98078a74f35d3c14f7bd5418920f55 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Sun, 29 Aug 2010 18:50:30 +0000
Subject: [PATCH 0341/1624] Fix the the SCTP_WITH_NO_CSUM option when used in
 combination with interface supporting CRC offload. While at it, make use of
 the feature that the loopback interface provides CRC offloading.

MFC after: 4 weeks
---
 sys/netinet/sctp_crc32.c    |  12 +--
 sys/netinet/sctp_crc32.h    |   7 +-
 sys/netinet/sctp_input.c    |  20 ++---
 sys/netinet/sctp_os_bsd.h   |  17 ++--
 sys/netinet/sctp_output.c   | 160 ++++++++++++++++++++----------------
 sys/netinet/sctp_sysctl.c   |   6 ++
 sys/netinet/sctp_sysctl.h   |   2 +
 sys/netinet6/sctp6_usrreq.c |  10 ++-
 8 files changed, 132 insertions(+), 102 deletions(-)

diff --git a/sys/netinet/sctp_crc32.c b/sys/netinet/sctp_crc32.c
index d9ae238835f..0ab8039ac06 100644
--- a/sys/netinet/sctp_crc32.c
+++ b/sys/netinet/sctp_crc32.c
@@ -115,20 +115,15 @@ sctp_calculate_cksum(struct mbuf *m, uint32_t offset)
 	return (base);
 }
 
-#else
-
-uint32_t
-sctp_calculate_cksum(struct mbuf *m, uint32_t offset)
-{
-	return (0);
-}
-
 #endif				/* !defined(SCTP_WITH_NO_CSUM) */
 
 
 void
 sctp_delayed_cksum(struct mbuf *m, uint32_t offset)
 {
+#if defined(SCTP_WITH_NO_CSUM)
+	panic("sctp_delayed_cksum() called when using no SCTP CRC.");
+#else
 	struct ip *ip;
 	uint32_t checksum;
 
@@ -149,4 +144,5 @@ sctp_delayed_cksum(struct mbuf *m, uint32_t offset)
 		return;
 	}
 	*(uint32_t *) (m->m_data + offset) = checksum;
+#endif
 }
diff --git a/sys/netinet/sctp_crc32.h b/sys/netinet/sctp_crc32.h
index e66815ee517..eb7a1bc7a8e 100644
--- a/sys/netinet/sctp_crc32.h
+++ b/sys/netinet/sctp_crc32.h
@@ -36,11 +36,12 @@ __FBSDID("$FreeBSD$");
 #ifndef __crc32c_h__
 #define __crc32c_h__
 
-#if defined(_KERNEL) || defined(__Userspace__)
-
+#if defined(_KERNEL)
+#if !defined(SCTP_WITH_NO_CSUM)
 uint32_t sctp_calculate_cksum(struct mbuf *, uint32_t);
+
+#endif
 void sctp_delayed_cksum(struct mbuf *, uint32_t offset);
 
 #endif				/* _KERNEL */
-
 #endif				/* __crc32c_h__ */
diff --git a/sys/netinet/sctp_input.c b/sys/netinet/sctp_input.c
index 089c9b6834c..5da86ff564b 100644
--- a/sys/netinet/sctp_input.c
+++ b/sys/netinet/sctp_input.c
@@ -3068,7 +3068,7 @@ process_chunk_drop(struct sctp_tcb *stcb, struct sctp_chunk_desc *desc,
     struct sctp_nets *net, uint8_t flg)
 {
 	switch (desc->chunk_type) {
-		case SCTP_DATA:
+	case SCTP_DATA:
 		/* find the tsn to resend (possibly */
 		{
 			uint32_t tsn;
@@ -5717,14 +5717,17 @@ sctp_input_with_port(struct mbuf *i_pak, int off, uint16_t port)
 	struct ip *ip;
 	struct sctphdr *sh;
 	struct sctp_inpcb *inp = NULL;
-
-	uint32_t check, calc_check;
 	struct sctp_nets *net;
 	struct sctp_tcb *stcb = NULL;
 	struct sctp_chunkhdr *ch;
 	int refcount_up = 0;
 	int length, mlen, offset;
 
+#if !defined(SCTP_WITH_NO_CSUM)
+	uint32_t check, calc_check;
+
+#endif
+
 	if (SCTP_GET_PKT_VRFID(i_pak, vrf_id)) {
 		SCTP_RELEASE_PKT(i_pak);
 		return;
@@ -5799,18 +5802,14 @@ sctp_input_with_port(struct mbuf *i_pak, int off, uint16_t port)
 	    m->m_pkthdr.len,
 	    if_name(m->m_pkthdr.rcvif),
 	    m->m_pkthdr.csum_flags);
+#if defined(SCTP_WITH_NO_CSUM)
+	SCTP_STAT_INCR(sctps_recvnocrc);
+#else
 	if (m->m_pkthdr.csum_flags & CSUM_SCTP_VALID) {
 		SCTP_STAT_INCR(sctps_recvhwcrc);
 		goto sctp_skip_csum_4;
 	}
 	check = sh->checksum;	/* save incoming checksum */
-	if ((check == 0) && (SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback)) &&
-	    ((ip->ip_src.s_addr == ip->ip_dst.s_addr) ||
-	    (SCTP_IS_IT_LOOPBACK(m)))
-	    ) {
-		SCTP_STAT_INCR(sctps_recvnocrc);
-		goto sctp_skip_csum_4;
-	}
 	sh->checksum = 0;	/* prepare for calc */
 	calc_check = sctp_calculate_cksum(m, iphlen);
 	sh->checksum = check;
@@ -5840,6 +5839,7 @@ sctp_input_with_port(struct mbuf *i_pak, int off, uint16_t port)
 		goto bad;
 	}
 sctp_skip_csum_4:
+#endif
 	/* destination port of 0 is illegal, based on RFC2960. */
 	if (sh->dest_port == 0) {
 		SCTP_STAT_INCR(sctps_hdrops);
diff --git a/sys/netinet/sctp_os_bsd.h b/sys/netinet/sctp_os_bsd.h
index cec568d52c6..883d6dd8ac4 100644
--- a/sys/netinet/sctp_os_bsd.h
+++ b/sys/netinet/sctp_os_bsd.h
@@ -433,20 +433,21 @@ typedef struct rtentry sctp_rtentry_t;
  */
 #define SCTP_IP_OUTPUT(result, o_pak, ro, stcb, vrf_id) \
 { \
-	int o_flgs = 0; \
-	if (stcb && stcb->sctp_ep && stcb->sctp_ep->sctp_socket) { \
-		o_flgs = IP_RAWOUTPUT | (stcb->sctp_ep->sctp_socket->so_options & SO_DONTROUTE); \
-	} else { \
-		o_flgs = IP_RAWOUTPUT; \
-	} \
+	int o_flgs = IP_RAWOUTPUT; \
+	struct sctp_tcb *local_stcb = stcb; \
+	if (local_stcb && \
+	    local_stcb->sctp_ep && \
+	    local_stcb->sctp_ep->sctp_socket) \
+		o_flgs |= local_stcb->sctp_ep->sctp_socket->so_options & SO_DONTROUTE; \
 	result = ip_output(o_pak, NULL, ro, o_flgs, 0, NULL); \
 }
 
 #define SCTP_IP6_OUTPUT(result, o_pak, ro, ifp, stcb, vrf_id) \
 { \
- 	if (stcb && stcb->sctp_ep) \
+	struct sctp_tcb *local_stcb = stcb; \
+	if (local_stcb && local_stcb->sctp_ep) \
 		result = ip6_output(o_pak, \
-				    ((struct in6pcb *)(stcb->sctp_ep))->in6p_outputopts, \
+				    ((struct in6pcb *)(local_stcb->sctp_ep))->in6p_outputopts, \
 				    (ro), 0, 0, ifp, NULL); \
 	else \
 		result = ip6_output(o_pak, NULL, (ro), 0, 0, ifp, NULL); \
diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index d322d07fd1d..a9d00b8372a 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -3741,6 +3741,9 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
 		if (port) {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
 			    (stcb) &&
 			    (stcb->asoc.loopback_scope))) {
@@ -3749,17 +3752,16 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 			} else {
 				SCTP_STAT_INCR(sctps_sendnocrc);
 			}
+#endif
 			SCTP_ENABLE_UDP_CSUM(o_pak);
 		} else {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				m->m_pkthdr.csum_flags = CSUM_SCTP;
-				m->m_pkthdr.csum_data = 0;
-				SCTP_STAT_INCR(sctps_sendhwcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			m->m_pkthdr.csum_flags = CSUM_SCTP;
+			m->m_pkthdr.csum_data = 0;
+			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
 		/* send it out.  table id is taken from stcb */
 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
@@ -4051,6 +4053,9 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
 		if (port) {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
 			    (stcb) &&
 			    (stcb->asoc.loopback_scope))) {
@@ -4059,10 +4064,14 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 			} else {
 				SCTP_STAT_INCR(sctps_sendnocrc);
 			}
+#endif
 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), packet_length - sizeof(struct ip6_hdr))) == 0) {
 				udp->uh_sum = 0xffff;
 			}
 		} else {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
 			    (stcb) &&
 			    (stcb->asoc.loopback_scope))) {
@@ -4072,6 +4081,7 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 			} else {
 				SCTP_STAT_INCR(sctps_sendnocrc);
 			}
+#endif
 		}
 		/* send it out. table id is taken from stcb */
 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
@@ -10571,7 +10581,6 @@ sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
 	if (iph_out != NULL) {
 		sctp_route_t ro;
 		int ret;
-		struct sctp_tcb *stcb = NULL;
 
 		mlen = SCTP_BUF_LEN(mout);
 		bzero(&ro, sizeof ro);
@@ -10582,17 +10591,25 @@ sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
 			sctp_packet_log(mout, mlen);
 #endif
 		if (port) {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			comp_cp->sh.checksum = sctp_calculate_cksum(mout, offset_out);
 			SCTP_STAT_INCR(sctps_sendswcrc);
+#endif
 			SCTP_ENABLE_UDP_CSUM(mout);
 		} else {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			mout->m_pkthdr.csum_flags = CSUM_SCTP;
 			mout->m_pkthdr.csum_data = 0;
 			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
 		SCTP_ATTACH_CHAIN(o_pak, mout, mlen);
 		/* out it goes */
-		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
+		SCTP_IP_OUTPUT(ret, o_pak, &ro, NULL, vrf_id);
 
 		/* Free the route if we got one back */
 		if (ro.ro_rt)
@@ -10602,7 +10619,6 @@ sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
 	if (ip6_out != NULL) {
 		struct route_in6 ro;
 		int ret;
-		struct sctp_tcb *stcb = NULL;
 		struct ifnet *ifp = NULL;
 
 		bzero(&ro, sizeof(ro));
@@ -10613,29 +10629,25 @@ sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, mout, mlen);
 		if (port) {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				comp_cp->sh.checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
-				SCTP_STAT_INCR(sctps_sendswcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			comp_cp->sh.checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
+			SCTP_STAT_INCR(sctps_sendswcrc);
+#endif
 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), mlen - sizeof(struct ip6_hdr))) == 0) {
 				udp->uh_sum = 0xffff;
 			}
 		} else {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				mout->m_pkthdr.csum_flags = CSUM_SCTP;
-				mout->m_pkthdr.csum_data = 0;
-				SCTP_STAT_INCR(sctps_sendhwcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			mout->m_pkthdr.csum_flags = CSUM_SCTP;
+			mout->m_pkthdr.csum_data = 0;
+			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
-		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
+		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, NULL, vrf_id);
 
 		/* Free the route if we got one back */
 		if (ro.ro_rt)
@@ -11632,7 +11644,6 @@ sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
 	}
 	if (iph_out != NULL) {
 		sctp_route_t ro;
-		struct sctp_tcb *stcb = NULL;
 		int ret;
 
 		/* zap the stack pointer to the route */
@@ -11652,15 +11663,23 @@ sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
 		if (port) {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			abm->sh.checksum = sctp_calculate_cksum(mout, iphlen_out);
 			SCTP_STAT_INCR(sctps_sendswcrc);
+#endif
 			SCTP_ENABLE_UDP_CSUM(o_pak);
 		} else {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			mout->m_pkthdr.csum_flags = CSUM_SCTP;
 			mout->m_pkthdr.csum_data = 0;
 			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
-		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
+		SCTP_IP_OUTPUT(ret, o_pak, &ro, NULL, vrf_id);
 
 		/* Free the route if we got one back */
 		if (ro.ro_rt)
@@ -11670,7 +11689,6 @@ sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
 	if (ip6_out != NULL) {
 		struct route_in6 ro;
 		int ret;
-		struct sctp_tcb *stcb = NULL;
 		struct ifnet *ifp = NULL;
 
 		/* zap the stack pointer to the route */
@@ -11687,29 +11705,25 @@ sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
 		if (port) {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				abm->sh.checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
-				SCTP_STAT_INCR(sctps_sendswcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			abm->sh.checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
+			SCTP_STAT_INCR(sctps_sendswcrc);
+#endif
 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), len - sizeof(struct ip6_hdr))) == 0) {
 				udp->uh_sum = 0xffff;
 			}
 		} else {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				mout->m_pkthdr.csum_flags = CSUM_SCTP;
-				mout->m_pkthdr.csum_data = 0;
-				SCTP_STAT_INCR(sctps_sendhwcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			mout->m_pkthdr.csum_flags = CSUM_SCTP;
+			mout->m_pkthdr.csum_data = 0;
+			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
-		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
+		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, NULL, vrf_id);
 
 		/* Free the route if we got one back */
 		if (ro.ro_rt)
@@ -11872,7 +11886,6 @@ sctp_send_operr_to(struct mbuf *m, int iphlen, struct mbuf *scm, uint32_t vtag,
 	}
 	if (iph_out != NULL) {
 		sctp_route_t ro;
-		struct sctp_tcb *stcb = NULL;
 		int ret;
 
 		/* zap the stack pointer to the route */
@@ -11890,15 +11903,23 @@ sctp_send_operr_to(struct mbuf *m, int iphlen, struct mbuf *scm, uint32_t vtag,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
 		if (port) {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			sh_out->checksum = sctp_calculate_cksum(mout, iphlen_out);
 			SCTP_STAT_INCR(sctps_sendswcrc);
+#endif
 			SCTP_ENABLE_UDP_CSUM(o_pak);
 		} else {
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
 			mout->m_pkthdr.csum_flags = CSUM_SCTP;
 			mout->m_pkthdr.csum_data = 0;
 			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
-		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
+		SCTP_IP_OUTPUT(ret, o_pak, &ro, NULL, vrf_id);
 
 		/* Free the route if we got one back */
 		if (ro.ro_rt)
@@ -11908,7 +11929,6 @@ sctp_send_operr_to(struct mbuf *m, int iphlen, struct mbuf *scm, uint32_t vtag,
 	if (ip6_out != NULL) {
 		struct route_in6 ro;
 		int ret;
-		struct sctp_tcb *stcb = NULL;
 		struct ifnet *ifp = NULL;
 
 		/* zap the stack pointer to the route */
@@ -11923,29 +11943,25 @@ sctp_send_operr_to(struct mbuf *m, int iphlen, struct mbuf *scm, uint32_t vtag,
 #endif
 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
 		if (port) {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				sh_out->checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
-				SCTP_STAT_INCR(sctps_sendswcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			sh_out->checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
+			SCTP_STAT_INCR(sctps_sendswcrc);
+#endif
 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), len - sizeof(struct ip6_hdr))) == 0) {
 				udp->uh_sum = 0xffff;
 			}
 		} else {
-			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
-			    (stcb) &&
-			    (stcb->asoc.loopback_scope))) {
-				mout->m_pkthdr.csum_flags = CSUM_SCTP;
-				mout->m_pkthdr.csum_data = 0;
-				SCTP_STAT_INCR(sctps_sendhwcrc);
-			} else {
-				SCTP_STAT_INCR(sctps_sendnocrc);
-			}
+#if defined(SCTP_WITH_NO_CSUM)
+			SCTP_STAT_INCR(sctps_sendnocrc);
+#else
+			mout->m_pkthdr.csum_flags = CSUM_SCTP;
+			mout->m_pkthdr.csum_data = 0;
+			SCTP_STAT_INCR(sctps_sendhwcrc);
+#endif
 		}
-		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
+		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, NULL, vrf_id);
 
 		/* Free the route if we got one back */
 		if (ro.ro_rt)
diff --git a/sys/netinet/sctp_sysctl.c b/sys/netinet/sctp_sysctl.c
index 9ba7dd40be3..f4b9c772be1 100644
--- a/sys/netinet/sctp_sysctl.c
+++ b/sys/netinet/sctp_sysctl.c
@@ -54,7 +54,9 @@ sctp_init_sysctls()
 	SCTP_BASE_SYSCTL(sctp_ecn_enable) = SCTPCTL_ECN_ENABLE_DEFAULT;
 	SCTP_BASE_SYSCTL(sctp_ecn_nonce) = SCTPCTL_ECN_NONCE_DEFAULT;
 	SCTP_BASE_SYSCTL(sctp_strict_sacks) = SCTPCTL_STRICT_SACKS_DEFAULT;
+#if !defined(SCTP_WITH_NO_CSUM)
 	SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) = SCTPCTL_LOOPBACK_NOCSUM_DEFAULT;
+#endif
 	SCTP_BASE_SYSCTL(sctp_strict_init) = SCTPCTL_STRICT_INIT_DEFAULT;
 	SCTP_BASE_SYSCTL(sctp_peer_chunk_oh) = SCTPCTL_PEER_CHKOH_DEFAULT;
 	SCTP_BASE_SYSCTL(sctp_max_burst_default) = SCTPCTL_MAXBURST_DEFAULT;
@@ -568,7 +570,9 @@ sysctl_sctp_check(SYSCTL_HANDLER_ARGS)
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_ecn_enable), SCTPCTL_ECN_ENABLE_MIN, SCTPCTL_ECN_ENABLE_MAX);
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_ecn_nonce), SCTPCTL_ECN_NONCE_MIN, SCTPCTL_ECN_NONCE_MAX);
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_strict_sacks), SCTPCTL_STRICT_SACKS_MIN, SCTPCTL_STRICT_SACKS_MAX);
+#if !defined(SCTP_WITH_NO_CSUM)
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback), SCTPCTL_LOOPBACK_NOCSUM_MIN, SCTPCTL_LOOPBACK_NOCSUM_MAX);
+#endif
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_strict_init), SCTPCTL_STRICT_INIT_MIN, SCTPCTL_STRICT_INIT_MAX);
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_peer_chunk_oh), SCTPCTL_PEER_CHKOH_MIN, SCTPCTL_PEER_CHKOH_MAX);
 		RANGECHK(SCTP_BASE_SYSCTL(sctp_max_burst_default), SCTPCTL_MAXBURST_MIN, SCTPCTL_MAXBURST_MAX);
@@ -829,9 +833,11 @@ SYSCTL_PROC(_net_inet_sctp, OID_AUTO, strict_sacks, CTLTYPE_INT | CTLFLAG_RW,
     &SCTP_BASE_SYSCTL(sctp_strict_sacks), 0, sysctl_sctp_check, "IU",
     SCTPCTL_STRICT_SACKS_DESC);
 
+#if !defined(SCTP_WITH_NO_CSUM)
 SYSCTL_PROC(_net_inet_sctp, OID_AUTO, loopback_nocsum, CTLTYPE_INT | CTLFLAG_RW,
     &SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback), 0, sysctl_sctp_check, "IU",
     SCTPCTL_LOOPBACK_NOCSUM_DESC);
+#endif
 
 SYSCTL_PROC(_net_inet_sctp, OID_AUTO, strict_init, CTLTYPE_INT | CTLFLAG_RW,
     &SCTP_BASE_SYSCTL(sctp_strict_init), 0, sysctl_sctp_check, "IU",
diff --git a/sys/netinet/sctp_sysctl.h b/sys/netinet/sctp_sysctl.h
index 477ee36f759..1140b972526 100644
--- a/sys/netinet/sctp_sysctl.h
+++ b/sys/netinet/sctp_sysctl.h
@@ -45,7 +45,9 @@ struct sctp_sysctl {
 	uint32_t sctp_ecn_enable;
 	uint32_t sctp_ecn_nonce;
 	uint32_t sctp_strict_sacks;
+#if !defined(SCTP_WITH_NO_CSUM)
 	uint32_t sctp_no_csum_on_loopback;
+#endif
 	uint32_t sctp_strict_init;
 	uint32_t sctp_peer_chunk_oh;
 	uint32_t sctp_max_burst_default;
diff --git a/sys/netinet6/sctp6_usrreq.c b/sys/netinet6/sctp6_usrreq.c
index 1fce08e2eca..8c1405637d6 100644
--- a/sys/netinet6/sctp6_usrreq.c
+++ b/sys/netinet6/sctp6_usrreq.c
@@ -72,7 +72,6 @@ sctp6_input(struct mbuf **i_pak, int *offp, int proto)
 	struct sctp_inpcb *in6p = NULL;
 	struct sctp_nets *net;
 	int refcount_up = 0;
-	uint32_t check, calc_check;
 	uint32_t vrf_id = 0;
 	struct inpcb *in6p_ip;
 	struct sctp_chunkhdr *ch;
@@ -80,6 +79,11 @@ sctp6_input(struct mbuf **i_pak, int *offp, int proto)
 	uint8_t ecn_bits;
 	struct sctp_tcb *stcb = NULL;
 	int pkt_len = 0;
+
+#if !defined(SCTP_WITH_NO_CSUM)
+	uint32_t check, calc_check;
+
+#endif
 	int off = *offp;
 	uint16_t port = 0;
 
@@ -133,6 +137,9 @@ sctp6_input(struct mbuf **i_pak, int *offp, int proto)
 	    m->m_pkthdr.len,
 	    if_name(m->m_pkthdr.rcvif),
 	    m->m_pkthdr.csum_flags);
+#if defined(SCTP_WITH_NO_CSUM)
+	SCTP_STAT_INCR(sctps_recvnocrc);
+#else
 	if (m->m_pkthdr.csum_flags & CSUM_SCTP_VALID) {
 		SCTP_STAT_INCR(sctps_recvhwcrc);
 		goto sctp_skip_csum;
@@ -171,6 +178,7 @@ sctp6_input(struct mbuf **i_pak, int *offp, int proto)
 	sh->checksum = calc_check;
 
 sctp_skip_csum:
+#endif
 	net = NULL;
 	/*
 	 * Locate pcb and tcb for datagram sctp_findassociation_addr() wants

From 4f1f4356f3012928b463f9ef1710fb908e48b1e2 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 20:18:06 +0000
Subject: [PATCH 0342/1624] Fix 'zfs allow' (maybe not only) returning:

	cannot access dataset system/usr/home: Operation not supported

by including libzfs_impl.h. What libzfs_impl.h does is to redefine ioctl() to
be compatible with OpenSolaris. More specifically OpenSolaris returns ENOMEM
when buffer is too small and sets field zc_nvlist_dst_size to the size that
will be big enough for the data. In FreeBSD case ioctl() doesn't copy data
structure back in case of a failure. We work-around it in kernel and libzfs by
returning 0 from ioctl() and always checking if zc_nvlist_dst_size hasn't
changed. For this work-around to work in pyzfs we need this compatible ioctl()
which is implemented in libzfs_impl.h.

MFC after:	2 weeks
---
 cddl/contrib/opensolaris/lib/pyzfs/common/ioctl.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/cddl/contrib/opensolaris/lib/pyzfs/common/ioctl.c b/cddl/contrib/opensolaris/lib/pyzfs/common/ioctl.c
index c0de5c474c0..4571147a487 100644
--- a/cddl/contrib/opensolaris/lib/pyzfs/common/ioctl.c
+++ b/cddl/contrib/opensolaris/lib/pyzfs/common/ioctl.c
@@ -33,6 +33,7 @@
 #include 
 #include 
 #include 
+#include 
 #include "zfs_prop.h"
 
 static PyObject *ZFSError;

From 083b49f0dcb576f9f19f3b6ef338c548d06a87b2 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 20:21:10 +0000
Subject: [PATCH 0343/1624] Print errors on stderr.

MFC after:	2 weeks
---
 cddl/contrib/opensolaris/cmd/zfs/zfs_main.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c b/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
index 2241f9c42d5..32764311ff6 100644
--- a/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
+++ b/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
@@ -1733,7 +1733,7 @@ zfs_do_userspace(int argc, char **argv)
 	 */
 	(void) execv(pypath, argv-1);
 
-	(void) printf("internal error: %s not found\n"
+	(void) fprintf(stderr, "internal error: %s not found\n"
 	    "falling back on built-in implementation, "
 	    "some features will not work\n", pypath);
 
@@ -3797,7 +3797,7 @@ static int
 zfs_do_python(int argc, char **argv)
 {
 	(void) execv(pypath, argv-1);
-	(void) printf("internal error: %s not found\n", pypath);
+	(void) fprintf(stderr, "internal error: %s not found\n", pypath);
 	return (-1);
 }
 

From d448e183aa1b7e70f4e2b691f7c9583ab537cd9b Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 20:25:25 +0000
Subject: [PATCH 0344/1624] Give user a hint what to do when
 /usr/lib/zfs/pyzfs.py is missing.

MFC after:	2 weeks
---
 cddl/contrib/opensolaris/cmd/zfs/zfs_main.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c b/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
index 32764311ff6..c5e9b64a1f4 100644
--- a/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
+++ b/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
@@ -1736,6 +1736,7 @@ zfs_do_userspace(int argc, char **argv)
 	(void) fprintf(stderr, "internal error: %s not found\n"
 	    "falling back on built-in implementation, "
 	    "some features will not work\n", pypath);
+	(void) fprintf(stderr, "    install sysutils/py-zfs port to correct this\n");
 
 	if ((zhp = zfs_open(g_zfs, argv[argc-1], ZFS_TYPE_DATASET)) == NULL)
 		return (1);
@@ -3798,6 +3799,7 @@ zfs_do_python(int argc, char **argv)
 {
 	(void) execv(pypath, argv-1);
 	(void) fprintf(stderr, "internal error: %s not found\n", pypath);
+	(void) fprintf(stderr, "    install sysutils/py-zfs port to correct this\n");
 	return (-1);
 }
 

From 83866607fb6286714711d8e0bc0ab6a5ba985ce1 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 29 Aug 2010 20:53:24 +0000
Subject: [PATCH 0345/1624] sh: Weaken builtins/command4 test to only require a
 nonzero exit status.

This matches what is in POSIX; various other shells use different exit
statuses.

Note that it is still required that there be no output.
---
 tools/regression/bin/sh/builtins/command4.0   | 2 ++
 tools/regression/bin/sh/builtins/command4.127 | 2 --
 2 files changed, 2 insertions(+), 2 deletions(-)
 create mode 100644 tools/regression/bin/sh/builtins/command4.0
 delete mode 100644 tools/regression/bin/sh/builtins/command4.127

diff --git a/tools/regression/bin/sh/builtins/command4.0 b/tools/regression/bin/sh/builtins/command4.0
new file mode 100644
index 00000000000..3e496137ff5
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/command4.0
@@ -0,0 +1,2 @@
+# $FreeBSD$
+! command -v nonexisting
diff --git a/tools/regression/bin/sh/builtins/command4.127 b/tools/regression/bin/sh/builtins/command4.127
deleted file mode 100644
index c66f60fda25..00000000000
--- a/tools/regression/bin/sh/builtins/command4.127
+++ /dev/null
@@ -1,2 +0,0 @@
-# $FreeBSD$
-command -v nonexisting

From 572cdb22169b1481d23736b4f221af6cb8016413 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 21:37:21 +0000
Subject: [PATCH 0346/1624] Implement mtx_destroy() and rw_destroy().

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/synch.h | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/sbin/hastd/synch.h b/sbin/hastd/synch.h
index 006b0e74ee4..1dda49d7eb7 100644
--- a/sbin/hastd/synch.h
+++ b/sbin/hastd/synch.h
@@ -48,6 +48,14 @@ mtx_init(pthread_mutex_t *lock)
 	assert(error == 0);
 }
 static __inline void
+mtx_destroy(pthread_mutex_t *lock)
+{
+	int error;
+
+	error = pthread_mutex_destroy(lock);
+	assert(error == 0);
+}
+static __inline void
 mtx_lock(pthread_mutex_t *lock)
 {
 	int error;
@@ -88,6 +96,14 @@ rw_init(pthread_rwlock_t *lock)
 	assert(error == 0);
 }
 static __inline void
+rw_destroy(pthread_rwlock_t *lock)
+{
+	int error;
+
+	error = pthread_rwlock_destroy(lock);
+	assert(error == 0);
+}
+static __inline void
 rw_rlock(pthread_rwlock_t *lock)
 {
 	int error;

From 25ec2e3e2b919f6bf96604d9a592eeb5ef35930c Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 21:39:49 +0000
Subject: [PATCH 0347/1624] - Add hook_fini() which should be called after
 fork() from the main hastd   process, once it start to use hooks. - Add
 hook_check_one() in case the caller expects different child processes   and
 once it can recognize it, it will pass pid and status to hook_check_one().

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hooks.c | 80 +++++++++++++++++++++++++++++++++-------------
 sbin/hastd/hooks.h |  4 +++
 2 files changed, 62 insertions(+), 22 deletions(-)

diff --git a/sbin/hastd/hooks.c b/sbin/hastd/hooks.c
index 11ede20c78f..eff2f6f9531 100644
--- a/sbin/hastd/hooks.c
+++ b/sbin/hastd/hooks.c
@@ -82,6 +82,9 @@ struct hookproc {
 static TAILQ_HEAD(, hookproc) hookprocs;
 static pthread_mutex_t hookprocs_lock;
 
+static void hook_remove(struct hookproc *hp);
+static void hook_free(struct hookproc *hp);
+
 static void
 descriptors(void)
 {
@@ -147,11 +150,35 @@ void
 hook_init(void)
 {
 
+	assert(!hooks_initialized);
+
 	mtx_init(&hookprocs_lock);
 	TAILQ_INIT(&hookprocs);
 	hooks_initialized = true;
 }
 
+void
+hook_fini(void)
+{
+	struct hookproc *hp;
+
+	assert(hooks_initialized);
+
+	mtx_lock(&hookprocs_lock);
+	while ((hp = TAILQ_FIRST(&hookprocs)) != NULL) {
+		assert(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
+		assert(hp->hp_pid > 0);
+
+		hook_remove(hp);
+		hook_free(hp);
+	}
+	mtx_unlock(&hookprocs_lock);
+
+	mtx_destroy(&hookprocs_lock);
+	TAILQ_INIT(&hookprocs);
+	hooks_initialized = false;
+}
+
 static struct hookproc *
 hook_alloc(const char *path, char **args)
 {
@@ -237,6 +264,34 @@ hook_find(pid_t pid)
 	return (hp);
 }
 
+void
+hook_check_one(pid_t pid, int status)
+{
+	struct hookproc *hp;
+
+	mtx_lock(&hookprocs_lock);
+	hp = hook_find(pid);
+	if (hp == NULL) {
+		mtx_unlock(&hookprocs_lock);
+		pjdlog_debug(1, "Unknown process pid=%u", pid);
+		return;
+	}
+	hook_remove(hp);
+	mtx_unlock(&hookprocs_lock);
+	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
+		pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).",
+		    pid, hp->hp_comm);
+	} else if (WIFSIGNALED(status)) {
+		pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).",
+		    pid, WTERMSIG(status), hp->hp_comm);
+	} else {
+		pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).",
+		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1,
+		    hp->hp_comm);
+	}
+	hook_free(hp);
+}
+
 void
 hook_check(bool sigchld)
 {
@@ -250,28 +305,9 @@ hook_check(bool sigchld)
 	/*
 	 * If SIGCHLD was received, garbage collect finished processes.
 	 */
-	while (sigchld && (pid = wait3(&status, WNOHANG, NULL)) > 0) {
-		mtx_lock(&hookprocs_lock);
-		hp = hook_find(pid);
-		if (hp == NULL) {
-			mtx_unlock(&hookprocs_lock);
-			pjdlog_warning("Unknown process pid=%u", pid);
-			continue;
-		}
-		hook_remove(hp);
-		mtx_unlock(&hookprocs_lock);
-		if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
-			pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).",
-			    pid, hp->hp_comm);
-		} else if (WIFSIGNALED(status)) {
-			pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).",
-			    pid, WTERMSIG(status), hp->hp_comm);
-		} else {
-			pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).",
-			    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1,
-			    hp->hp_comm);
-		}
-		hook_free(hp);
+	if (sigchld) {
+		while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
+			hook_check_one(pid, status);
 	}
 
 	/*
diff --git a/sbin/hastd/hooks.h b/sbin/hastd/hooks.h
index d18ddc496a2..5cc57df5e2b 100644
--- a/sbin/hastd/hooks.h
+++ b/sbin/hastd/hooks.h
@@ -33,10 +33,14 @@
 #ifndef	_HOOKS_H_
 #define	_HOOKS_H_
 
+#include 
+
 #include 
 #include 
 
 void hook_init(void);
+void hook_fini(void);
+void hook_check_one(pid_t pid, int status);
 void hook_check(bool sigchld);
 void hook_exec(const char *path, ...);
 void hook_execv(const char *path, va_list ap);

From ecc99c890e2a30d5ac3d1f2f13550977229485fd Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 21:41:53 +0000
Subject: [PATCH 0348/1624] Allow to run hooks from the main hastd process.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hastd.c     | 20 +++++++++++++++++---
 sbin/hastd/primary.c   |  2 ++
 sbin/hastd/secondary.c |  3 +++
 3 files changed, 22 insertions(+), 3 deletions(-)

diff --git a/sbin/hastd/hastd.c b/sbin/hastd/hastd.c
index 785798ad768..ad80c8e9b42 100644
--- a/sbin/hastd/hastd.c
+++ b/sbin/hastd/hastd.c
@@ -55,6 +55,7 @@ __FBSDID("$FreeBSD$");
 #include "hast.h"
 #include "hast_proto.h"
 #include "hastd.h"
+#include "hooks.h"
 #include "subr.h"
 
 /* Path to configuration file. */
@@ -70,6 +71,9 @@ bool sigexit_received = false;
 /* PID file handle. */
 struct pidfh *pfh;
 
+/* How often check for hooks running for too long. */
+#define	REPORT_INTERVAL	10
+
 static void
 usage(void)
 {
@@ -144,8 +148,10 @@ child_exit(void)
 		if (res == NULL) {
 			/*
 			 * This can happen when new connection arrives and we
-			 * cancel child responsible for the old one.
+			 * cancel child responsible for the old one or if this
+			 * was hook which we executed.
 			 */
+			hook_check_one(pid, status);
 			continue;
 		}
 		pjdlog_prefix_set("[%s] (%s) ", res->hr_name,
@@ -620,6 +626,10 @@ main_loop(void)
 {
 	fd_set rfds, wfds;
 	int cfd, lfd, maxfd, ret;
+	struct timeval timeout;
+
+	timeout.tv_sec = REPORT_INTERVAL;
+	timeout.tv_usec = 0;
 
 	for (;;) {
 		if (sigexit_received) {
@@ -648,8 +658,10 @@ main_loop(void)
 		FD_SET(cfd, &wfds);
 		FD_SET(lfd, &wfds);
 
-		ret = select(maxfd + 1, &rfds, &wfds, NULL, NULL);
-		if (ret == -1) {
+		ret = select(maxfd + 1, &rfds, &wfds, NULL, &timeout);
+		if (ret == 0)
+			hook_check(false);
+		else if (ret == -1) {
 			if (errno == EINTR)
 				continue;
 			KEEP_ERRNO((void)pidfile_remove(pfh));
@@ -754,6 +766,8 @@ main(int argc, char *argv[])
 		}
 	}
 
+	hook_init();
+
 	main_loop();
 
 	exit(0);
diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index c495f1093bc..f0b84232d94 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -786,7 +786,9 @@ hastd_primary(struct hast_resource *res)
 		res->hr_workerpid = pid;
 		return;
 	}
+
 	(void)pidfile_close(pfh);
+	hook_fini();
 
 	setproctitle("%s (primary)", res->hr_name);
 
diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index b76f6804891..6051722ed39 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -57,6 +57,7 @@ __FBSDID("$FreeBSD$");
 #include "hast.h"
 #include "hast_proto.h"
 #include "hastd.h"
+#include "hooks.h"
 #include "metadata.h"
 #include "proto.h"
 #include "subr.h"
@@ -357,7 +358,9 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 		res->hr_workerpid = pid;
 		return;
 	}
+
 	(void)pidfile_close(pfh);
+	hook_fini();
 
 	setproctitle("%s (secondary)", res->hr_name);
 

From a870e771b9f07ea66cc1af3612fd57f0aef66cc2 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 21:42:45 +0000
Subject: [PATCH 0349/1624] - Call hook on role change. - Document new event.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/control.c   |  5 +++++
 sbin/hastd/hast.conf.5 | 22 +++++++++++++++++++++-
 2 files changed, 26 insertions(+), 1 deletion(-)

diff --git a/sbin/hastd/control.c b/sbin/hastd/control.c
index 5c48061a385..2f42826cfa5 100644
--- a/sbin/hastd/control.c
+++ b/sbin/hastd/control.c
@@ -43,6 +43,7 @@ __FBSDID("$FreeBSD$");
 #include "hast.h"
 #include "hastd.h"
 #include "hast_proto.h"
+#include "hooks.h"
 #include "nv.h"
 #include "pjdlog.h"
 #include "proto.h"
@@ -54,6 +55,7 @@ static void
 control_set_role_common(struct hastd_config *cfg, struct nv *nvout,
     uint8_t role, struct hast_resource *res, const char *name, unsigned int no)
 {
+	int oldrole;
 
 	/* Name is always needed. */
 	if (name != NULL)
@@ -85,6 +87,7 @@ control_set_role_common(struct hastd_config *cfg, struct nv *nvout,
 	pjdlog_info("Role changed to %s.", role2str(role));
 
 	/* Change role to the new one. */
+	oldrole = res->hr_role;
 	res->hr_role = role;
 	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
 
@@ -113,6 +116,8 @@ control_set_role_common(struct hastd_config *cfg, struct nv *nvout,
 	if (role == HAST_ROLE_PRIMARY)
 		hastd_primary(res);
 	pjdlog_prefix_set("%s", "");
+	hook_exec(res->hr_exec, "role", res->hr_name, role2str(oldrole),
+	    role2str(res->hr_role), NULL);
 }
 
 void
diff --git a/sbin/hastd/hast.conf.5 b/sbin/hastd/hast.conf.5
index f312648f9b9..0707115e722 100644
--- a/sbin/hastd/hast.conf.5
+++ b/sbin/hastd/hast.conf.5
@@ -28,7 +28,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd August 27, 2010
+.Dd August 29, 2010
 .Dt HAST.CONF 5
 .Os
 .Sh NAME
@@ -228,6 +228,10 @@ Executed on primary node when synchronization process of secondary node is
 interrupted, most likely due to secondary node outage or connection failure
 between the nodes.
 .Pp
+.It Ic " role   "
+.Pp
+Executed on both primary and secondary nodes when resource role is changed.
+.Pp
 .El
 The
 .Aq path
@@ -241,6 +245,22 @@ The
 .Aq resource
 argument is resource name from the configuration file.
 .Pp
+The
+.Aq oldrole
+argument is previous resource role (before the change).
+It can be one of:
+.Ar init ,
+.Ar secondary ,
+.Ar primary .
+.Pp
+The
+.Aq newrole
+argument is current resource role (after the change).
+It can be one of:
+.Ar init ,
+.Ar secondary ,
+.Ar primary .
+.Pp
 .It Ic name Aq name
 .Pp
 GEOM provider name that will appear as

From ee087cdf97f7cf15e9ae725e6164648d85f9ce3e Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 22:17:53 +0000
Subject: [PATCH 0350/1624] Disconnect after logging errors.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index f0b84232d94..e8d8185f79d 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1234,12 +1234,12 @@ remote_send_thread(void *arg)
 		    data != NULL ? length : 0) < 0) {
 			hio->hio_errors[ncomp] = errno;
 			rw_unlock(&hio_remote_lock[ncomp]);
-			remote_close(res, ncomp);
 			pjdlog_debug(2,
 			    "remote_send: (%p) Unable to send request.", hio);
 			reqlog(LOG_ERR, 0, ggio,
 			    "Unable to send request (%s): ",
 			    strerror(hio->hio_errors[ncomp]));
+			remote_close(res, ncomp);
 			/*
 			 * Take request back from the receive queue and move
 			 * it immediately to the done queue.

From 5a0884b3289f9aa16dcc41d5f2fbb0335a400569 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 29 Aug 2010 22:22:15 +0000
Subject: [PATCH 0351/1624] Correct value for _POSIX_AIO_LISTIO_MAX in
 .

All the "Minimum Values" (POSIX.1-2008 XBD 13 Headers ) are now
correct. These should all be exactly as they are in the specification; the
possibly higher values we support are announced differently.

PR:		standards/104743
Submitted by:	gcooper
MFC after:	2 weeks
---
 include/limits.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/include/limits.h b/include/limits.h
index 6a249136731..9828ab67b98 100644
--- a/include/limits.h
+++ b/include/limits.h
@@ -70,7 +70,7 @@
 #endif
 
 #if __POSIX_VISIBLE >= 199309
-#define	_POSIX_AIO_LISTIO_MAX	16
+#define	_POSIX_AIO_LISTIO_MAX	2
 #define	_POSIX_AIO_MAX		1
 #define	_POSIX_DELAYTIMER_MAX	32
 #define	_POSIX_MQ_OPEN_MAX	8

From ff6bb1f8b3c01188967a79404f0a468c4c9f9082 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Sun, 29 Aug 2010 22:55:21 +0000
Subject: [PATCH 0352/1624] - Move functionality responsible for checking one
 connection to separate   function to make code more readable. - Be sure not
 to reconnect too often in case of signal delivery, etc.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 127 +++++++++++++++++++++++++------------------
 1 file changed, 75 insertions(+), 52 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index e8d8185f79d..7eb62a42021 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -1903,6 +1903,67 @@ keepalive_send(struct hast_resource *res, unsigned int ncomp)
 	pjdlog_debug(2, "keepalive_send: Request sent.");
 }
 
+static void
+guard_one(struct hast_resource *res, unsigned int ncomp)
+{
+	struct proto_conn *in, *out;
+
+	if (!ISREMOTE(ncomp))
+		return;
+
+	rw_rlock(&hio_remote_lock[ncomp]);
+
+	if (!real_remote(res)) {
+		rw_unlock(&hio_remote_lock[ncomp]);
+		return;
+	}
+
+	if (ISCONNECTED(res, ncomp)) {
+		assert(res->hr_remotein != NULL);
+		assert(res->hr_remoteout != NULL);
+		keepalive_send(res, ncomp);
+	}
+
+	if (ISCONNECTED(res, ncomp)) {
+		assert(res->hr_remotein != NULL);
+		assert(res->hr_remoteout != NULL);
+		rw_unlock(&hio_remote_lock[ncomp]);
+		pjdlog_debug(2, "remote_guard: Connection to %s is ok.",
+		    res->hr_remoteaddr);
+		return;
+	}
+
+	assert(res->hr_remotein == NULL);
+	assert(res->hr_remoteout == NULL);
+	/*
+	 * Upgrade the lock. It doesn't have to be atomic as no other thread
+	 * can change connection status from disconnected to connected.
+	 */
+	rw_unlock(&hio_remote_lock[ncomp]);
+	pjdlog_debug(2, "remote_guard: Reconnecting to %s.",
+	    res->hr_remoteaddr);
+	in = out = NULL;
+	if (init_remote(res, &in, &out)) {
+		rw_wlock(&hio_remote_lock[ncomp]);
+		assert(res->hr_remotein == NULL);
+		assert(res->hr_remoteout == NULL);
+		assert(in != NULL && out != NULL);
+		res->hr_remotein = in;
+		res->hr_remoteout = out;
+		rw_unlock(&hio_remote_lock[ncomp]);
+		pjdlog_info("Successfully reconnected to %s.",
+		    res->hr_remoteaddr);
+		sync_start();
+	} else {
+		/* Both connections should be NULL. */
+		assert(res->hr_remotein == NULL);
+		assert(res->hr_remoteout == NULL);
+		assert(in == NULL && out == NULL);
+		pjdlog_debug(2, "remote_guard: Reconnect to %s failed.",
+		    res->hr_remoteaddr);
+	}
+}
+
 /*
  * Thread guards remote connections and reconnects when needed, handles
  * signals, etc.
@@ -1911,11 +1972,12 @@ static void *
 guard_thread(void *arg)
 {
 	struct hast_resource *res = arg;
-	struct proto_conn *in, *out;
 	unsigned int ii, ncomps;
+	time_t lastcheck, now;
 	int timeout;
 
 	ncomps = HAST_NCOMPONENTS;
+	lastcheck = time(NULL);
 
 	for (;;) {
 		if (sigexit_received) {
@@ -1930,63 +1992,24 @@ guard_thread(void *arg)
 		if (sigchld_received)
 			sigchld_received = false;
 
-		timeout = KEEPALIVE_SLEEP;
 		pjdlog_debug(2, "remote_guard: Checking connections.");
 		mtx_lock(&hio_guard_lock);
+		timeout = KEEPALIVE_SLEEP;
 		for (ii = 0; ii < ncomps; ii++) {
-			if (!ISREMOTE(ii))
-				continue;
-			rw_rlock(&hio_remote_lock[ii]);
-			if (ISCONNECTED(res, ii)) {
-				assert(res->hr_remotein != NULL);
-				assert(res->hr_remoteout != NULL);
-				keepalive_send(res, ii);
+			if (!ISCONNECTED(res, ii)) {
+				timeout = RECONNECT_SLEEP;
+				break;
 			}
-			if (ISCONNECTED(res, ii)) {
-				assert(res->hr_remotein != NULL);
-				assert(res->hr_remoteout != NULL);
-				rw_unlock(&hio_remote_lock[ii]);
-				pjdlog_debug(2,
-				    "remote_guard: Connection to %s is ok.",
-				    res->hr_remoteaddr);
-			} else if (real_remote(res)) {
-				assert(res->hr_remotein == NULL);
-				assert(res->hr_remoteout == NULL);
-				/*
-				 * Upgrade the lock. It doesn't have to be
-				 * atomic as no other thread can change
-				 * connection status from disconnected to
-				 * connected.
-				 */
-				rw_unlock(&hio_remote_lock[ii]);
-				pjdlog_debug(2,
-				    "remote_guard: Reconnecting to %s.",
-				    res->hr_remoteaddr);
-				in = out = NULL;
-				if (init_remote(res, &in, &out)) {
-					rw_wlock(&hio_remote_lock[ii]);
-					assert(res->hr_remotein == NULL);
-					assert(res->hr_remoteout == NULL);
-					assert(in != NULL && out != NULL);
-					res->hr_remotein = in;
-					res->hr_remoteout = out;
-					rw_unlock(&hio_remote_lock[ii]);
-					pjdlog_info("Successfully reconnected to %s.",
-					    res->hr_remoteaddr);
-					sync_start();
-				} else {
-					/* Both connections should be NULL. */
-					assert(res->hr_remotein == NULL);
-					assert(res->hr_remoteout == NULL);
-					assert(in == NULL && out == NULL);
-					pjdlog_debug(2,
-					    "remote_guard: Reconnect to %s failed.",
-					    res->hr_remoteaddr);
+		}
+		now = time(NULL);
+		if (lastcheck + timeout <= now) {
+			timeout = KEEPALIVE_SLEEP;
+			for (ii = 0; ii < ncomps; ii++) {
+				guard_one(res, ii);
+				if (!ISCONNECTED(res, ii))
 					timeout = RECONNECT_SLEEP;
-				}
-			} else {
-				rw_unlock(&hio_remote_lock[ii]);
 			}
+			lastcheck = now;
 		}
 		/* Sleep only if a signal wasn't delivered in the meantime. */
 		if (!sigexit_received && !sighup_received && !sigchld_received)

From 6d0c801ea956728a24ba14c5c48aff7b11eb4c27 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 00:06:05 +0000
Subject: [PATCH 0353/1624] Use sigtimedwait(2) for signals handling in primary
 process. This fixes various races and eliminates use of pthread* API in
 signal handler.

Pointed out by:	kib
With help from:	jilles
MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 121 ++++++++++++++-----------------------------
 1 file changed, 40 insertions(+), 81 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 7eb62a42021..088a272610b 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -46,6 +46,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -132,8 +133,6 @@ static pthread_cond_t sync_cond;
  * The lock below allows to synchornize access to remote connections.
  */
 static pthread_rwlock_t *hio_remote_lock;
-static pthread_mutex_t hio_guard_lock;
-static pthread_cond_t hio_guard_cond;
 
 /*
  * Lock to synchronize metadata updates. Also synchronize access to
@@ -152,13 +151,9 @@ static pthread_mutex_t metadata_lock;
  */
 #define	HAST_NCOMPONENTS	2
 /*
- * Number of seconds to sleep between keepalive packets.
+ * Number of seconds to sleep between reconnect retries or keepalive packets.
  */
-#define	KEEPALIVE_SLEEP		10
-/*
- * Number of seconds to sleep between reconnect retries.
- */
-#define	RECONNECT_SLEEP		5
+#define	RETRY_SLEEP		10
 
 #define	ISCONNECTED(res, no)	\
 	((res)->hr_remotein != NULL && (res)->hr_remoteout != NULL)
@@ -230,7 +225,11 @@ static void *ggate_send_thread(void *arg);
 static void *sync_thread(void *arg);
 static void *guard_thread(void *arg);
 
-static void sighandler(int sig);
+static void
+dummy_sighandler(int sig __unused)
+{
+	/* Nothing to do. */
+}
 
 static void
 cleanup(struct hast_resource *res)
@@ -319,6 +318,7 @@ init_environment(struct hast_resource *res __unused)
 {
 	struct hio *hio;
 	unsigned int ii, ncomps;
+	sigset_t mask;
 
 	/*
 	 * In the future it might be per-resource value.
@@ -389,8 +389,6 @@ init_environment(struct hast_resource *res __unused)
 	TAILQ_INIT(&hio_done_list);
 	mtx_init(&hio_done_list_lock);
 	cv_init(&hio_done_list_cond);
-	mtx_init(&hio_guard_lock);
-	cv_init(&hio_guard_cond);
 	mtx_init(&metadata_lock);
 
 	/*
@@ -431,10 +429,10 @@ init_environment(struct hast_resource *res __unused)
 	/*
 	 * Turn on signals handling.
 	 */
-	signal(SIGINT, sighandler);
-	signal(SIGTERM, sighandler);
-	signal(SIGHUP, sighandler);
-	signal(SIGCHLD, sighandler);
+	/* Because SIGCHLD is ignored by default, setup dummy handler for it. */
+	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
+	PJDLOG_VERIFY(sigfillset(&mask) == 0);
+	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
 }
 
 static void
@@ -893,16 +891,6 @@ remote_close(struct hast_resource *res, int ncomp)
 	 * Stop synchronization if in-progress.
 	 */
 	sync_stop();
-
-	/*
-	 * Wake up guard thread (if we are not called from within guard thread),
-	 * so it can immediately start reconnect.
-	 */
-	if (!mtx_owned(&hio_guard_lock)) {
-		mtx_lock(&hio_guard_lock);
-		cv_signal(&hio_guard_cond);
-		mtx_unlock(&hio_guard_lock);
-	}
 }
 
 /*
@@ -1733,35 +1721,6 @@ free_queue:
 	return (NULL);
 }
 
-static void
-sighandler(int sig)
-{
-	bool unlock;
-
-	switch (sig) {
-	case SIGINT:
-	case SIGTERM:
-		sigexit_received = true;
-		break;
-	case SIGHUP:
-		sighup_received = true;
-		break;
-	case SIGCHLD:
-		sigchld_received = true;
-		break;
-	default:
-		assert(!"invalid condition");
-	}
-	/*
-	 * Racy, but if we cannot obtain hio_guard_lock here, we don't
-	 * want to risk deadlock.
-	 */
-	unlock = mtx_trylock(&hio_guard_lock);
-	cv_signal(&hio_guard_cond);
-	if (unlock)
-		mtx_unlock(&hio_guard_lock);
-}
-
 static void
 config_reload(void)
 {
@@ -1973,48 +1932,48 @@ guard_thread(void *arg)
 {
 	struct hast_resource *res = arg;
 	unsigned int ii, ncomps;
+	struct timespec timeout;
 	time_t lastcheck, now;
-	int timeout;
+	sigset_t mask;
+	int signo;
 
 	ncomps = HAST_NCOMPONENTS;
 	lastcheck = time(NULL);
 
+	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
+
+	timeout.tv_nsec = 0;
+	signo = -1;
+
 	for (;;) {
-		if (sigexit_received) {
+		switch (signo) {
+		case SIGHUP:
+			config_reload();
+			break;
+		case SIGINT:
+		case SIGTERM:
+			sigexit_received = true;
 			primary_exitx(EX_OK,
 			    "Termination signal received, exiting.");
+			break;
+		default:
+			break;
 		}
-		if (sighup_received) {
-			sighup_received = false;
-			config_reload();
-		}
-		hook_check(sigchld_received);
-		if (sigchld_received)
-			sigchld_received = false;
+		hook_check(signo == SIGCHLD);
 
 		pjdlog_debug(2, "remote_guard: Checking connections.");
-		mtx_lock(&hio_guard_lock);
-		timeout = KEEPALIVE_SLEEP;
-		for (ii = 0; ii < ncomps; ii++) {
-			if (!ISCONNECTED(res, ii)) {
-				timeout = RECONNECT_SLEEP;
-				break;
-			}
-		}
 		now = time(NULL);
-		if (lastcheck + timeout <= now) {
-			timeout = KEEPALIVE_SLEEP;
-			for (ii = 0; ii < ncomps; ii++) {
+		if (lastcheck + RETRY_SLEEP <= now) {
+			for (ii = 0; ii < ncomps; ii++)
 				guard_one(res, ii);
-				if (!ISCONNECTED(res, ii))
-					timeout = RECONNECT_SLEEP;
-			}
 			lastcheck = now;
 		}
-		/* Sleep only if a signal wasn't delivered in the meantime. */
-		if (!sigexit_received && !sighup_received && !sigchld_received)
-			cv_timedwait(&hio_guard_cond, &hio_guard_lock, timeout);
-		mtx_unlock(&hio_guard_lock);
+		timeout.tv_sec = RETRY_SLEEP;
+		signo = sigtimedwait(&mask, NULL, &timeout);
 	}
 	/* NOTREACHED */
 	return (NULL);

From 2be8fd75ffb3de15c6c882462e7523bea7b8f528 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 00:12:10 +0000
Subject: [PATCH 0354/1624] Execute hook when split-brain is detected.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hast.conf.5 | 5 +++++
 sbin/hastd/primary.c   | 3 +++
 sbin/hastd/secondary.c | 2 ++
 3 files changed, 10 insertions(+)

diff --git a/sbin/hastd/hast.conf.5 b/sbin/hastd/hast.conf.5
index 0707115e722..f12768ed7cc 100644
--- a/sbin/hastd/hast.conf.5
+++ b/sbin/hastd/hast.conf.5
@@ -232,6 +232,11 @@ between the nodes.
 .Pp
 Executed on both primary and secondary nodes when resource role is changed.
 .Pp
+.It Ic " split-brain "
+.Pp
+Executed on both primary and secondary nodes when split-brain condition is
+detected.
+.Pp
 .El
 The
 .Aq path
diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 088a272610b..73155a180d8 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -498,6 +498,7 @@ init_remote(struct hast_resource *res, struct proto_conn **inp,
 	assert(real_remote(res));
 
 	in = out = NULL;
+	errmsg = NULL;
 
 	/* Prepare outgoing connection with remote node. */
 	if (proto_client(res->hr_remoteaddr, &out) < 0) {
@@ -673,6 +674,8 @@ init_remote(struct hast_resource *res, struct proto_conn **inp,
 	}
 	return (true);
 close:
+	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
+		hook_exec(res->hr_exec, "split-brain", res->hr_name, NULL);
 	proto_close(out);
 	if (in != NULL)
 		proto_close(in);
diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index 6051722ed39..d92030cfb19 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -323,6 +323,7 @@ init_remote(struct hast_resource *res, struct nv *nvin)
 	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
 	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
 		/* Exit on split-brain. */
+		hook_exec(res->hr_exec, "split-brain", res->hr_name, NULL);
 		exit(EX_CONFIG);
 	}
 }
@@ -373,6 +374,7 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
 
+	hook_init();
 	init_local(res);
 	init_remote(res, nvin);
 	init_environment();

From 5b41e6448619220247c35893228e54dbdbf0c196 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 00:31:30 +0000
Subject: [PATCH 0355/1624] Execute hook when connection between the nodes is
 established or lost.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hast.conf.5 | 20 +++++++++++++++-----
 sbin/hastd/primary.c   |  7 +++++--
 sbin/hastd/secondary.c | 24 +++++++++++++++++++++---
 3 files changed, 41 insertions(+), 10 deletions(-)

diff --git a/sbin/hastd/hast.conf.5 b/sbin/hastd/hast.conf.5
index f12768ed7cc..87a7e35f3b1 100644
--- a/sbin/hastd/hast.conf.5
+++ b/sbin/hastd/hast.conf.5
@@ -28,7 +28,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd August 29, 2010
+.Dd August 30, 2010
 .Dt HAST.CONF 5
 .Os
 .Sh NAME
@@ -212,6 +212,20 @@ Execute the given program on various HAST events.
 Below is the list of currently implemented events and arguments the given
 program is executed with:
 .Bl -tag -width ".Ic xxxx"
+.It Ic " role   "
+.Pp
+Executed on both primary and secondary nodes when resource role is changed.
+.Pp
+.It Ic " connect "
+.Pp
+Executed on both primary and secondary nodes when connection for the given
+resource between the nodes is established.
+.Pp
+.It Ic " disconnect "
+.Pp
+Executed on both primary and secondary nodes when connection for the given
+resource between the nodes is lost.
+.Pp
 .It Ic " syncstart "
 .Pp
 Executed on primary node when synchronization process of secondary node is
@@ -228,10 +242,6 @@ Executed on primary node when synchronization process of secondary node is
 interrupted, most likely due to secondary node outage or connection failure
 between the nodes.
 .Pp
-.It Ic " role   "
-.Pp
-Executed on both primary and secondary nodes when resource role is changed.
-.Pp
 .It Ic " split-brain "
 .Pp
 Executed on both primary and secondary nodes when split-brain condition is
diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 73155a180d8..86f274fda29 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -672,6 +672,7 @@ init_remote(struct hast_resource *res, struct proto_conn **inp,
 		res->hr_remotein = in;
 		res->hr_remoteout = out;
 	}
+	hook_exec(res->hr_exec, "connect", res->hr_name, NULL);
 	return (true);
 close:
 	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
@@ -765,8 +766,6 @@ hastd_primary(struct hast_resource *res)
 	pid_t pid;
 	int error;
 
-	gres = res;
-
 	/*
 	 * Create communication channel between parent and child.
 	 */
@@ -788,6 +787,8 @@ hastd_primary(struct hast_resource *res)
 		return;
 	}
 
+	gres = res;
+
 	(void)pidfile_close(pfh);
 	hook_fini();
 
@@ -894,6 +895,8 @@ remote_close(struct hast_resource *res, int ncomp)
 	 * Stop synchronization if in-progress.
 	 */
 	sync_stop();
+
+	hook_exec(res->hr_exec, "disconnect", res->hr_name, NULL);
 }
 
 /*
diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index d92030cfb19..d1575e8a5a7 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -74,6 +74,8 @@ struct hio {
 	TAILQ_ENTRY(hio) hio_next;
 };
 
+static struct hast_resource *gres;
+
 /*
  * Free list holds unused structures. When free list is empty, we have to wait
  * until some in-progress requests are freed.
@@ -360,6 +362,8 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 		return;
 	}
 
+	gres = res;
+
 	(void)pidfile_close(pfh);
 	hook_fini();
 
@@ -378,6 +382,7 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 	init_local(res);
 	init_remote(res, nvin);
 	init_environment();
+	hook_exec(res->hr_exec, "connect", res->hr_name, NULL);
 
 	error = pthread_create(&td, NULL, recv_thread, res);
 	assert(error == 0);
@@ -501,6 +506,19 @@ end:
 	return (hio->hio_error);
 }
 
+static void
+secondary_exit(int exitcode, const char *fmt, ...)
+{
+	va_list ap;
+
+	assert(exitcode != EX_OK);
+	va_start(ap, fmt);
+	pjdlogv_errno(LOG_ERR, fmt, ap);
+	va_end(ap);
+	hook_exec(gres->hr_exec, "disconnect", gres->hr_name, NULL);
+	exit(exitcode);
+}
+
 /*
  * Thread receives requests from the primary node.
  */
@@ -515,7 +533,7 @@ recv_thread(void *arg)
 		QUEUE_TAKE(free, hio);
 		pjdlog_debug(2, "recv: (%p) Got request.", hio);
 		if (hast_proto_recv_hdr(res->hr_remotein, &hio->hio_nv) < 0) {
-			pjdlog_exit(EX_TEMPFAIL,
+			secondary_exit(EX_TEMPFAIL,
 			    "Unable to receive request header");
 		}
 		if (requnpack(res, hio) != 0) {
@@ -537,7 +555,7 @@ recv_thread(void *arg)
 		} else if (hio->hio_cmd == HIO_WRITE) {
 			if (hast_proto_recv_data(res, res->hr_remotein,
 			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
-				pjdlog_exit(EX_TEMPFAIL,
+				secondary_exit(EX_TEMPFAIL,
 				    "Unable to receive reply data");
 			}
 		}
@@ -693,7 +711,7 @@ send_thread(void *arg)
 			nv_add_int16(nvout, hio->hio_error, "error");
 		if (hast_proto_send(res, res->hr_remoteout, nvout, data,
 		    length) < 0) {
-			pjdlog_exit(EX_TEMPFAIL, "Unable to send reply.");
+			secondary_exit(EX_TEMPFAIL, "Unable to send reply.");
 		}
 		nv_free(nvout);
 		pjdlog_debug(2, "send: (%p) Moving request to the free queue.",

From 1ece82b4877f94fd7c997a7f129bba3a62f7ea13 Mon Sep 17 00:00:00 2001
From: Maxim Konovalov 
Date: Mon, 30 Aug 2010 07:29:27 +0000
Subject: [PATCH 0356/1624] Make flags in usage() and SYNOPSYS more
 style(9)-ish.

Suggested by:	brian
MFC after:	3 days
---
 sbin/kldload/kldload.8 | 3 +--
 sbin/kldload/kldload.c | 2 +-
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/sbin/kldload/kldload.8 b/sbin/kldload/kldload.8
index 6491fedfa41..91b0c86c6d2 100644
--- a/sbin/kldload/kldload.8
+++ b/sbin/kldload/kldload.8
@@ -33,8 +33,7 @@
 .Nd load a file into the kernel
 .Sh SYNOPSIS
 .Nm
-.Op Fl v
-.Op Fl q
+.Op Fl qv
 .Ar
 .Sh DESCRIPTION
 The
diff --git a/sbin/kldload/kldload.c b/sbin/kldload/kldload.c
index 48d00e144b4..4d8d20a2184 100644
--- a/sbin/kldload/kldload.c
+++ b/sbin/kldload/kldload.c
@@ -129,7 +129,7 @@ path_check(const char *kldname, int quiet)
 static void
 usage(void)
 {
-	fprintf(stderr, "usage: kldload [-v] [-q] file ...\n");
+	fprintf(stderr, "usage: kldload [-qv] file ...\n");
 	exit(1);
 }
 

From f936972752a3a5c7d09e743d72b31f0b840c8b24 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 30 Aug 2010 08:23:22 +0000
Subject: [PATCH 0357/1624] Remove misleading comment in pte.h. MIPS PTE
 entries are software managed and does not need atomics.

Submitted by:	alc
---
 sys/mips/include/pte.h | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/sys/mips/include/pte.h b/sys/mips/include/pte.h
index 0765eb33a6f..a8926da8b5b 100644
--- a/sys/mips/include/pte.h
+++ b/sys/mips/include/pte.h
@@ -130,9 +130,6 @@ typedef	pt_entry_t *pd_entry_t;
 
 /*
  * PTE management functions for bits defined above.
- *
- * XXX Can make these atomics, but some users of them are using PTEs in local
- * registers and such and don't need the overhead.
  */
 #define	pte_clear(pte, bit)	(*(pte) &= ~(bit))
 #define	pte_set(pte, bit)	(*(pte) |= (bit))

From 5a47f206a1ec63f3d4ad4c9c92109422a35ab7eb Mon Sep 17 00:00:00 2001
From: Maxim Konovalov 
Date: Mon, 30 Aug 2010 09:29:51 +0000
Subject: [PATCH 0358/1624] o Some programs could send broadcast/multicast
 traffic to ipfw pseudo-interface.  This leads to a panic due to uninitialized
 if_broadcastaddr address.  Initialize it and implement ip_output() method to
 prevent mbuf leak later.

ipfw pseudo-interface should never send anything therefore call
panic(9) in if_start() method.

PR:		kern/149807
Submitted by:	Dmitrij Tejblum
MFC after:	2 weeks
---
 sys/netinet/ipfw/ip_fw_log.c | 23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)

diff --git a/sys/netinet/ipfw/ip_fw_log.c b/sys/netinet/ipfw/ip_fw_log.c
index 2995f2cc155..3560e137f1e 100644
--- a/sys/netinet/ipfw/ip_fw_log.c
+++ b/sys/netinet/ipfw/ip_fw_log.c
@@ -103,6 +103,24 @@ log_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
 	return EINVAL;
 }
 
+static int
+ipfw_log_output(struct ifnet *ifp, struct mbuf *m,
+	struct sockaddr *dst, struct route *ro)
+{
+	if (m != NULL)
+		m_freem(m);
+	return EINVAL;
+}
+
+static void
+ipfw_log_start(struct ifnet* ifp)
+{
+	panic("ipfw_log_start() must not be called");
+}
+
+static const u_char ipfwbroadcastaddr[6] =
+	{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
+
 void
 ipfw_log_bpf(int onoff)
 {
@@ -119,11 +137,12 @@ ipfw_log_bpf(int onoff)
 		ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
 		ifp->if_init = (void *)log_dummy;
 		ifp->if_ioctl = log_dummy;
-		ifp->if_start = (void *)log_dummy;
-		ifp->if_output = (void *)log_dummy;
+		ifp->if_start = ipfw_log_start;
+		ifp->if_output = ipfw_log_output;
 		ifp->if_addrlen = 6;
 		ifp->if_hdrlen = 14;
 		if_attach(ifp);
+		ifp->if_broadcastaddr = ipfwbroadcastaddr;
 		ifp->if_baudrate = IF_Mbps(10);
 		bpfattach(ifp, DLT_EN10MB, 14);
 		log_if = ifp;

From 61b993a34f8389409e2ce35b4d5cbb99cf0b607d Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 30 Aug 2010 13:05:21 +0000
Subject: [PATCH 0359/1624] Clean up header files in RMI platform code
 (sys/mips/rmi), and remove unused files.

- remove clock.c and clock.h, these are not used after the new timer
  code was added.
- remove duplicated include files, fix header file ordering, remove
  some unneeded includes.
- rename mips/rmi/shared_structs.h which contains the RMI boot loader
  interface to mips/rmi/rmi_boot_info.h. Remove unused files
  mips/rmi/shared_structs_func.h and sys/mips/rmi/shared_structs_offsets.h
- merge mips/rmi/xlrconfig.h and mips/rmi/rmi_mips_exts.h, and remove
  duplicated functions.
- nlge - minor change to remove unneeded argument.
- Add FreeBSD svn keyword for headers
---
 sys/mips/rmi/board.c                          |   2 +-
 sys/mips/rmi/board.h                          |   6 +-
 sys/mips/rmi/clock.c                          | 356 -----------------
 sys/mips/rmi/clock.h                          |  41 --
 sys/mips/rmi/debug.h                          |   4 +-
 sys/mips/rmi/dev/nlge/if_nlge.c               |  34 +-
 sys/mips/rmi/dev/xlr/rge.c                    |  26 +-
 sys/mips/rmi/interrupt.h                      |   6 +-
 sys/mips/rmi/intr_machdep.c                   |   4 +-
 sys/mips/rmi/iodi.c                           |  20 +-
 sys/mips/rmi/iomap.h                          |   4 +-
 sys/mips/rmi/msgring.h                        |  11 +-
 sys/mips/rmi/pic.h                            |   5 +-
 .../rmi/{shared_structs.h => rmi_boot_info.h} |   7 +-
 sys/mips/rmi/rmi_mips_exts.h                  | 343 ++++++++++++++++-
 sys/mips/rmi/shared_structs_func.h            |  54 ---
 sys/mips/rmi/shared_structs_offsets.h         |  76 ----
 sys/mips/rmi/xlr_machdep.c                    |   5 +-
 sys/mips/rmi/xlr_pci.c                        |  17 +-
 sys/mips/rmi/xlrconfig.h                      | 360 ------------------
 20 files changed, 393 insertions(+), 988 deletions(-)
 delete mode 100644 sys/mips/rmi/clock.c
 delete mode 100644 sys/mips/rmi/clock.h
 rename sys/mips/rmi/{shared_structs.h => rmi_boot_info.h} (96%)
 delete mode 100644 sys/mips/rmi/shared_structs_func.h
 delete mode 100644 sys/mips/rmi/shared_structs_offsets.h
 delete mode 100644 sys/mips/rmi/xlrconfig.h

diff --git a/sys/mips/rmi/board.c b/sys/mips/rmi/board.c
index ac36755a1d8..ea5f3c9c4f2 100644
--- a/sys/mips/rmi/board.c
+++ b/sys/mips/rmi/board.c
@@ -38,9 +38,9 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #include 
+#include 
 #include 
 #include 
-#include 
 
 static int xlr_rxstn_to_txstn_map[128] = {
 	[0 ... 7] = TX_STN_CPU_0,
diff --git a/sys/mips/rmi/board.h b/sys/mips/rmi/board.h
index ed2c04533f9..814eba1f74b 100644
--- a/sys/mips/rmi/board.h
+++ b/sys/mips/rmi/board.h
@@ -104,10 +104,10 @@ xlr_processor_id(void)
  * These should come up in PCI device mode (not yet)
  */
 static __inline__ int
-xlr_board_pci(void)
+xlr_board_pci(int board_major)
 {
-	return ((xlr_boot1_info.board_major_version == RMI_XLR_BOARD_ARIZONA_III) ||
-		(xlr_boot1_info.board_major_version == RMI_XLR_BOARD_ARIZONA_V));
+	return ((board_major == RMI_XLR_BOARD_ARIZONA_III) ||
+		(board_major == RMI_XLR_BOARD_ARIZONA_V));
 }
 
 static __inline__ int
diff --git a/sys/mips/rmi/clock.c b/sys/mips/rmi/clock.c
deleted file mode 100644
index c123edf589e..00000000000
--- a/sys/mips/rmi/clock.c
+++ /dev/null
@@ -1,356 +0,0 @@
-/*-
- * Copyright (c) 2003-2009 RMI Corporation
- * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
- *
- * RMI_BSD 
- */
-
-#include 		/* RCS ID & Copyright macro defns */
-__FBSDID("$FreeBSD$");
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#ifdef XLR_PERFMON
-#include 
-#endif
-
-uint64_t counter_freq;
-uint64_t cycles_per_tick;
-uint64_t cycles_per_usec;
-uint64_t cycles_per_sec;
-uint64_t cycles_per_hz;
-
-u_int32_t counter_upper = 0;
-u_int32_t counter_lower_last = 0;
-
-#define STAT_PROF_CLOCK_SCALE_FACTOR 8
-
-static int scale_factor;
-static int count_scale_factor[32];
-
-uint64_t
-platform_get_frequency()
-{
-	return XLR_PIC_HZ;
-}
-
-void
-mips_timer_early_init(uint64_t clock_hz)
-{
-	/* Initialize clock early so that we can use DELAY sooner */
-	counter_freq = clock_hz;
-	cycles_per_usec = (clock_hz / (1000 * 1000));
-
-}
-
-/*
-* count_compare_clockhandler:
-*
-* Handle the clock interrupt when count becomes equal to
-* compare.
-*/
-int
-count_compare_clockhandler(struct trapframe *tf)
-{
-	int cpu = PCPU_GET(cpuid);
-	uint32_t cycles;
-
-	critical_enter();
-
-	if (cpu == 0) {
-		mips_wr_compare(0);
-	} else {
-		count_scale_factor[cpu]++;
-		cycles = mips_rd_count();
-		cycles += XLR_CPU_HZ / hz;
-		mips_wr_compare(cycles);
-
-		hardclock_cpu(TRAPF_USERMODE(tf));
-		if (count_scale_factor[cpu] == STAT_PROF_CLOCK_SCALE_FACTOR) {
-			statclock(TRAPF_USERMODE(tf));
-			if (profprocs != 0) {
-				profclock(TRAPF_USERMODE(tf), tf->pc);
-			}
-			count_scale_factor[cpu] = 0;
-		}
-		/* If needed , handle count compare tick skew here */
-	}
-
-	critical_exit();
-	return (FILTER_HANDLED);
-}
-
-unsigned long clock_tick_foo=0;
-
-int
-pic_hardclockhandler(struct trapframe *tf)
-{
-	int cpu = PCPU_GET(cpuid);
-
-	critical_enter();
-
-	if (cpu == 0) {
-		scale_factor++;
-		clock_tick_foo++;
-/*
-		if ((clock_tick_foo % 10000) == 0) {
-			printf("Clock tick foo at %ld\n", clock_tick_foo);
-		}
-*/
-		hardclock(TRAPF_USERMODE(tf), tf->pc);
-		if (scale_factor == STAT_PROF_CLOCK_SCALE_FACTOR) {
-			statclock(TRAPF_USERMODE(tf));
-			if (profprocs != 0) {
-				profclock(TRAPF_USERMODE(tf), tf->pc);
-			}
-			scale_factor = 0;
-		}
-#ifdef XLR_PERFMON
-		if (xlr_perfmon_started)
-			xlr_perfmon_clockhandler();
-#endif
-
-	} else {
-		/* If needed , handle count compare tick skew here */
-	}
-	critical_exit();
-	return (FILTER_HANDLED);
-}
-
-int
-pic_timecounthandler(struct trapframe *tf)
-{
-	return (FILTER_HANDLED);
-}
-
-void
-rmi_early_counter_init()
-{
-	int cpu = PCPU_GET(cpuid);
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-
-	/*
-	 * We do this to get the PIC time counter running right after system
-	 * start. Otherwise the DELAY() function will not be able to work
-	 * since it won't have a TC to read.
-	 */
-	xlr_write_reg(mmio, PIC_TIMER_6_MAXVAL_0, (0xffffffff & 0xffffffff));
-	xlr_write_reg(mmio, PIC_TIMER_6_MAXVAL_1, (0xffffffff & 0xffffffff));
-	xlr_write_reg(mmio, PIC_IRT_0_TIMER_6, (1 << cpu));
-	xlr_write_reg(mmio, PIC_IRT_1_TIMER_6, (1 << 31) | (0 << 30) | (1 << 6) | (PIC_TIMER_6_IRQ));
-	pic_update_control(1 << (8 + 6), 0);
-}
-
-void tick_init(void);
-
-void
-platform_initclocks(void)
-{
-	int cpu = PCPU_GET(cpuid);
-	void *cookie;
-
-	/*
-	 * Note: Passing #3 as NULL ensures that clockhandler gets called
-	 * with trapframe
-	 */
-	/* profiling/process accounting timer interrupt for non-zero cpus */
-	cpu_establish_hardintr("compare",
-	    (driver_filter_t *) count_compare_clockhandler,
-	    NULL,
-	    NULL,
-	    IRQ_TIMER,
-	    INTR_TYPE_CLK | INTR_FAST, &cookie);
-
-	/* timekeeping timer interrupt for cpu 0 */
-	cpu_establish_hardintr("hardclk",
-	    (driver_filter_t *) pic_hardclockhandler,
-	    NULL,
-	    NULL,
-	    PIC_TIMER_7_IRQ,
-	    INTR_TYPE_CLK | INTR_FAST,
-	    &cookie);
-
-	/* this is used by timecounter */
-	cpu_establish_hardintr("timecount",
-	    (driver_filter_t *) pic_timecounthandler, NULL,
-	    NULL, PIC_TIMER_6_IRQ, INTR_TYPE_CLK | INTR_FAST,
-	    &cookie);
-
-	if (cpu == 0) {
-		__uint64_t maxval = XLR_PIC_HZ / hz;
-		xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-
-		stathz = hz / STAT_PROF_CLOCK_SCALE_FACTOR;
-		profhz = stathz;
-
-		/* Setup PIC Interrupt */
-
-		if (rmi_spin_mutex_safe)
-			mtx_lock_spin(&xlr_pic_lock);
-		xlr_write_reg(mmio, PIC_TIMER_7_MAXVAL_0, (maxval & 0xffffffff));	/* 0x100 + 7 */
-		xlr_write_reg(mmio, PIC_TIMER_7_MAXVAL_1, (maxval >> 32) & 0xffffffff);	/* 0x110 + 7 */
-		/* 0x40 + 8 */
-		/* reg 40 is lower bits 31-0  and holds CPU mask */
-		xlr_write_reg(mmio, PIC_IRT_0_TIMER_7, (1 << cpu));
-		/* 0x80 + 8 */
-		/* Reg 80 is upper bits 63-32 and holds                              */
-		/* Valid   Edge    Local    IRQ */
-		xlr_write_reg(mmio, PIC_IRT_1_TIMER_7, (1 << 31) | (0 << 30) | (1 << 6) | (PIC_TIMER_7_IRQ));
-
-		pic_update_control(1 << (8 + 7), 1);
-		xlr_write_reg(mmio, PIC_TIMER_6_MAXVAL_0, (0xffffffff & 0xffffffff));
-		xlr_write_reg(mmio, PIC_TIMER_6_MAXVAL_1, (0xffffffff & 0xffffffff));
-		xlr_write_reg(mmio, PIC_IRT_0_TIMER_6, (1 << cpu));
-		xlr_write_reg(mmio, PIC_IRT_1_TIMER_6, (1 << 31) | (0 << 30) | (1 << 6) | (PIC_TIMER_6_IRQ));
-		pic_update_control(1 << (8 + 6), 1);
-		if (rmi_spin_mutex_safe)
-			mtx_unlock_spin(&xlr_pic_lock);
-	} else {
-		/* Setup count-compare interrupt for vcpu[1-31] */
-		mips_wr_compare((xlr_boot1_info.cpu_frequency) / hz);
-	}
-	tick_init();
-}
-
-unsigned
-__attribute__((no_instrument_function))
-platform_get_timecount(struct timecounter *tc __unused)
-{
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-
-	return 0xffffffffU - xlr_read_reg(mmio, PIC_TIMER_6_COUNTER_0);
-}
-
-void
-DELAY(int n)
-{
-	uint32_t cur, last, delta, usecs;
-
-	/*
-	 * This works by polling the timer and counting the number of
-	 * microseconds that go by.
-	 */
-	last = platform_get_timecount(NULL);
-	delta = usecs = 0;
-
-	while (n > usecs) {
-		cur = platform_get_timecount(NULL);
-
-		/* Check to see if the timer has wrapped around. */
-		if (cur < last)
-			delta += (cur + (cycles_per_hz - last));
-		else
-			delta += (cur - last);
-
-		last = cur;
-
-		if (delta >= cycles_per_usec) {
-			usecs += delta / cycles_per_usec;
-			delta %= cycles_per_usec;
-		}
-	}
-}
-
-static
-uint64_t
-read_pic_counter(void)
-{
-	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	uint32_t lower, upper;
-	uint64_t tc;
-
-	/*
-	 * Pull the value of the 64 bit counter which is stored in PIC
-	 * register 120+N and 130+N
-	 */
-	upper = 0xffffffffU - xlr_read_reg(mmio, PIC_TIMER_6_COUNTER_1);
-	lower = 0xffffffffU - xlr_read_reg(mmio, PIC_TIMER_6_COUNTER_0);
-	tc = (((uint64_t) upper << 32) | (uint64_t) lower);
-	return (tc);
-}
-
-extern struct timecounter counter_timecounter;
-
-void
-mips_timer_init_params(uint64_t platform_counter_freq, int double_count)
-{
-
-	/*
-	 * XXX: Do not use printf here: uart code 8250 may use DELAY so this
-	 * function should  be called before cninit.
-	 */
-	counter_freq = platform_counter_freq;
-	/*
-	 * XXX: Some MIPS32 cores update the Count register only every two
-	 * pipeline cycles.
-	 */
-	if (double_count != 0)
-		counter_freq /= 2;
-
-	cycles_per_tick = counter_freq / 1000;
-	cycles_per_hz = counter_freq / hz;
-	cycles_per_usec = counter_freq / (1 * 1000 * 1000);
-	cycles_per_sec = counter_freq;
-
-	counter_timecounter.tc_frequency = counter_freq;
-	printf("hz=%d cyl_per_hz:%jd cyl_per_usec:%jd freq:%jd cyl_per_hz:%jd cyl_per_sec:%jd\n",
-	    hz,
-	    cycles_per_tick,
-	    cycles_per_usec,
-	    counter_freq,
-	    cycles_per_hz,
-	    cycles_per_sec
-	    );
-	set_cputicker(read_pic_counter, counter_freq, 1);
-}
diff --git a/sys/mips/rmi/clock.h b/sys/mips/rmi/clock.h
deleted file mode 100644
index c0675810fc8..00000000000
--- a/sys/mips/rmi/clock.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * Copyright (c) 2003-2009 RMI Corporation
- * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
- *
- * RMI_BSD */
-#ifndef _RMI_CLOCK_H_
-#define _RMI_CLOCK_H_
-
-#define XLR_PIC_HZ 66000000U
-#define XLR_CPU_HZ (xlr_boot1_info.cpu_frequency)
-
-int count_compare_clockhandler(struct trapframe *);
-int pic_hardclockhandler(struct trapframe *);
-int pic_timecounthandler(struct trapframe *);
-void rmi_early_counter_init(void);
-
-#endif				/* _RMI_CLOCK_H_ */
diff --git a/sys/mips/rmi/debug.h b/sys/mips/rmi/debug.h
index b5ec144cc2c..53f1cb21dc0 100644
--- a/sys/mips/rmi/debug.h
+++ b/sys/mips/rmi/debug.h
@@ -26,7 +26,9 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * RMI_BSD */
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef _RMI_DEBUG_H_
 #define _RMI_DEBUG_H_
 
diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
index ec476ad7fbe..cdf5ffccbf7 100644
--- a/sys/mips/rmi/dev/nlge/if_nlge.c
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -104,10 +104,9 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
-#include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -209,7 +208,7 @@ static int	prepare_fmn_message(struct nlge_softc *sc,
     uint64_t fr_stid, struct nlge_tx_desc **tx_desc);
 
 static void	release_mbuf(uint64_t phy_addr);
-static void 	release_tx_desc(struct msgrng_msg *msg, int rel_buf);
+static void 	release_tx_desc(struct msgrng_msg *msg);
 static int	send_fmn_msg_tx(struct nlge_softc *, struct msgrng_msg *,
     uint32_t n_entries);
 
@@ -679,7 +678,7 @@ nlge_msgring_handler(int bucket, int size, int code, int stid,
 
 	if (ctrl == CTRL_REG_FREE || ctrl == CTRL_JUMBO_FREE) {
 		if (is_p2p)
-			release_tx_desc(msg, 1);
+			release_tx_desc(msg);
 		else {
 			release_mbuf(msg->msg0 & 0xffffffffffULL);
 		}
@@ -725,7 +724,7 @@ nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc)
 
 	cpu = xlr_core_id();	
 	tid = xlr_thr_id();
-	fr_stid = (cpu << 3) + tid + 4;	/* Each CPU has 8 buckets. */
+	fr_stid = cpu * 8 + tid + 4;
 
 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
 		return;
@@ -1909,9 +1908,9 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg,
 
 		while (len) {
 			if (msg_sz == (FMN_SZ - 1)) {
-				p2p = uma_zalloc(nl_tx_desc_zone, M_NOWAIT);
-			if (p2p == NULL)
-				return 2;
+				p2p = uma_zalloc(nl_tx_desc_zone, M_WAITOK);
+				if (p2p == NULL)
+					return 2;
 				/*
 				 * As we currently use xlr_paddr_lw on a 32-bit
 				 * OS, both the pointers are laid out in one
@@ -1929,7 +1928,7 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg,
 				return 1;
 			}
 			paddr = vtophys(buf);
-			frag_sz = PAGE_SIZE - (buf & PAGE_MASK) ;
+			frag_sz = PAGE_SIZE - (buf & PAGE_MASK);
 			if (len < frag_sz)
 				frag_sz = len;
 			*cur_p2d++ = (127ULL << 54) | ((uint64_t)frag_sz << 40)
@@ -1993,7 +1992,7 @@ release_mbuf(uint64_t phy_addr)
 }
 
 static void
-release_tx_desc(struct msgrng_msg *msg, int rel_buf)
+release_tx_desc(struct msgrng_msg *msg)
 {
 	vm_paddr_t	paddr;
 	uint64_t	temp;
@@ -2005,17 +2004,12 @@ release_tx_desc(struct msgrng_msg *msg, int rel_buf)
 	paddr += (XLR_MAX_TX_FRAGS * sizeof(uint64_t));
 	sr = xlr_enable_kx();
 	temp = xlr_paddr_lw(paddr);
-	mips_wr_status(sr);
 	tx_desc = (struct nlge_tx_desc*)((intptr_t) temp);
-
-	if (rel_buf) {
-		paddr += sizeof(void *);
-		sr = xlr_enable_kx();
-		temp = xlr_paddr_lw(paddr);
-		mips_wr_status(sr);
-		m = (struct mbuf *)((intptr_t) temp);
-		m_freem(m);
-	}
+	paddr += sizeof(void *);
+	temp = xlr_paddr_lw(paddr);
+	mips_wr_status(sr);
+	m = (struct mbuf *)((intptr_t) temp);
+	m_freem(m);
 
 	uma_zfree(nl_tx_desc_zone, tx_desc);
 }
diff --git a/sys/mips/rmi/dev/xlr/rge.c b/sys/mips/rmi/dev/xlr/rge.c
index 979543bd9b7..9e0bef7a9df 100644
--- a/sys/mips/rmi/dev/xlr/rge.c
+++ b/sys/mips/rmi/dev/xlr/rge.c
@@ -55,6 +55,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -63,7 +64,6 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include 
-
 #include 
 #include 
 
@@ -87,27 +87,23 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 	/* */
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
 
 #include 
 #include 
 #include 
 
-#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
 #include 
 
-/* #include "opt_rge.h" */
-
 #include "miibus_if.h"
 
 MODULE_DEPEND(rge, ether, 1, 1, 1);
diff --git a/sys/mips/rmi/interrupt.h b/sys/mips/rmi/interrupt.h
index 8573338e45d..76bbe5afa2e 100644
--- a/sys/mips/rmi/interrupt.h
+++ b/sys/mips/rmi/interrupt.h
@@ -25,8 +25,10 @@
  * 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.
- *__FBSDID("$FreeBSD$")
- * RMI_BSD */
+ *
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef _RMI_INTERRUPT_H_
 #define _RMI_INTERRUPT_H_
 
diff --git a/sys/mips/rmi/intr_machdep.c b/sys/mips/rmi/intr_machdep.c
index cf6df1ddbe3..04f6cde02eb 100644
--- a/sys/mips/rmi/intr_machdep.c
+++ b/sys/mips/rmi/intr_machdep.c
@@ -44,9 +44,9 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
+
+#include 
 #include 
-#include 
 #include 
 
 struct xlr_intrsrc {
diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index be6856421ed..d8cb081e24c 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -40,6 +40,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -48,28 +49,17 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-
 #include 
 #include 
 #include 	/* for DELAY */
-#include 
 #include 
+
+#include 
+#include 
 #include 
 #include 
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
+#include 
 
 #include 
 #include 
diff --git a/sys/mips/rmi/iomap.h b/sys/mips/rmi/iomap.h
index afc52bf712f..72756d25483 100644
--- a/sys/mips/rmi/iomap.h
+++ b/sys/mips/rmi/iomap.h
@@ -26,7 +26,9 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * RMI_BSD */
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef _RMI_IOMAP_H_
 #define _RMI_IOMAP_H_
 
diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h
index 33b23629074..6d9fd108a3d 100644
--- a/sys/mips/rmi/msgring.h
+++ b/sys/mips/rmi/msgring.h
@@ -25,13 +25,15 @@
  * 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.
- * $FreeBSD$
  *
- * RMI_BSD */
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef _RMI_MSGRING_H_
 #define _RMI_MSGRING_H_
 
-#include 
+#include 
+#include 
 
 #define MSGRNG_TX_BUF_REG 0
 #define MSGRNG_RX_BUF_REG 1
@@ -368,9 +370,6 @@ message_send(unsigned int size, unsigned int code,
 
 	dest = ((size - 1) << 16) | (code << 8) | (stid);
 
-	//dbg_msg("Sending msg<%Lx,%Lx,%Lx,%Lx> to dest = %x\n",
-	    //msg->msg0, msg->msg1, msg->msg2, msg->msg3, dest);
-
 	msgrng_send(dest);
 
 	for (i = 0; i < 16; i++) {
diff --git a/sys/mips/rmi/pic.h b/sys/mips/rmi/pic.h
index 3c777d8f5d7..8a3dd1f8b1d 100644
--- a/sys/mips/rmi/pic.h
+++ b/sys/mips/rmi/pic.h
@@ -25,9 +25,10 @@
  * 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.
- * __FBSDID("$FreeBSD$");
  *
- * RMI_BSD */
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef _RMI_PIC_H_
 #define	_RMI_PIC_H_
 
diff --git a/sys/mips/rmi/shared_structs.h b/sys/mips/rmi/rmi_boot_info.h
similarity index 96%
rename from sys/mips/rmi/shared_structs.h
rename to sys/mips/rmi/rmi_boot_info.h
index 6e5ecd43cea..38c81bd395d 100644
--- a/sys/mips/rmi/shared_structs.h
+++ b/sys/mips/rmi/rmi_boot_info.h
@@ -26,13 +26,12 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * RMI_BSD */
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef _SHARED_STRUCTS_H
 #define _SHARED_STRUCTS_H
 
-/* If you make any changes to the below structs, shared_structs_offsets.h
- * should be regenerated
- */
 #define BOOT1_INFO_VERSION 0x0001
 
 struct boot1_info {
diff --git a/sys/mips/rmi/rmi_mips_exts.h b/sys/mips/rmi/rmi_mips_exts.h
index 824381ac906..75e4a00047f 100644
--- a/sys/mips/rmi/rmi_mips_exts.h
+++ b/sys/mips/rmi/rmi_mips_exts.h
@@ -26,27 +26,12 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * RMI_BSD */
+ * RMI_BSD
+ * $FreeBSD$
+ */
 #ifndef __MIPS_EXTS_H__
 #define __MIPS_EXTS_H__
 
-#define enable_KX(flags)   __asm__ __volatile__ (          \
-		".set push\n"              \
-		".set noat\n"               \
-		".set noreorder\n"     \
-		"mfc0 %0, $12\n\t"             \
-		"ori $1, %0, 0x81\n\t"   \
-		"xori $1, 1\n\t"      \
-		"mtc0 $1, $12\n"       \
-		".set pop\n"          \
-		: "=r"(flags) )
-
-#define disable_KX(flags)   __asm__ __volatile__ (          \
-		".set push\n"              \
-		"mtc0 %0, $12\n"       \
-		".set pop\n"          \
-		: : "r"(flags) )
-
 #define CPU_BLOCKID_IFU      0
 #define CPU_BLOCKID_ICU      1
 #define CPU_BLOCKID_IEU      2
@@ -140,5 +125,327 @@ static __inline__ void write_64bit_phnx_ctrl_reg(int block, int reg,unsigned lon
 		);
 }
 
+#define read_c0_register32(reg, sel)                            \
+({ unsigned int __rv;                                           \
+        __asm__ __volatile__(                                   \
+        ".set\tpush\n\t"                                        \
+        ".set mips32\n\t"                                       \
+        "mfc0\t%0,$%1,%2\n\t"                                   \
+        ".set\tpop"                                             \
+        : "=r" (__rv) : "i" (reg), "i" (sel) );                 \
+        __rv;})
+
+#define write_c0_register32(reg,  sel, value)                   \
+        __asm__ __volatile__(                                   \
+        ".set\tpush\n\t"                                        \
+        ".set mips32\n\t"                                       \
+        "mtc0\t%0,$%1,%2\n\t"                                   \
+        ".set\tpop"                                             \
+        : : "r" (value), "i" (reg), "i" (sel) );
+
+#define read_c0_register64(reg, sel)                            \
+   ({ unsigned int __high, __low;                               \
+        __asm__ __volatile__(                                   \
+        ".set\tpush\n\t"                                        \
+        ".set mips64\n\t"                                       \
+        "dmfc0\t $8, $%2, %3\n\t"                               \
+        "dsrl32\t%0, $8, 0\n\t"                                 \
+        "dsll32\t$8, $8, 0\n\t"                                 \
+        "dsrl32\t%1, $8, 0\n\t"                                 \
+        ".set\tpop"                                             \
+        : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel): "$8" );\
+        (((unsigned long long)__high << 32) | __low);})
+
+#define write_c0_register64(reg, sel, value)                    \
+ do{                                                            \
+       unsigned int __high = val>>32;                           \
+       unsigned int __low = val & 0xffffffff;                   \
+        __asm__ __volatile__(                                   \
+        ".set\tpush\n\t"                                        \
+        ".set mips64\n\t"                                       \
+        "dsll32\t$8, %1, 0\n\t"                                 \
+        "dsll32\t$9, %0, 0\n\t"                                 \
+        "or\t    $8, $8, $9\n\t"                                \
+        "dmtc0\t $8, $%2, %3\n\t"                               \
+        ".set\tpop"                                             \
+        :: "r"(high), "r"(low),  "i"(reg), "i"(sel):"$8", "$9");\
+   } while(0)
+
+#define read_c2_register32(reg, sel)                            \
+({ unsigned int __rv;                                           \
+        __asm__ __volatile__(                                   \
+        ".set\tpush\n\t"                                        \
+        ".set mips32\n\t"                                       \
+        "mfc2\t%0,$%1,%2\n\t"                                   \
+        ".set\tpop"                                             \
+        : "=r" (__rv) : "i" (reg), "i" (sel) );                 \
+        __rv;})
+
+#define write_c2_register32(reg,  sel, value)                   \
+        __asm__ __volatile__(                                   \
+        ".set\tpush\n\t"                                        \
+        ".set mips32\n\t"                                       \
+        "mtc2\t%0,$%1,%2\n\t"                                   \
+        ".set\tpop"                                             \
+        : : "r" (value), "i" (reg), "i" (sel) );
+
+#define read_c2_register64(reg, sel)                            \
+   ({ unsigned int __high, __low;                               \
+        __asm__ __volatile__(                                   \
+        ".set mips64\n\t"                                       \
+        "dmfc2\t $8, $%2, %3\n\t"                               \
+        "dsrl32\t%0, $8, 0\n\t"                                 \
+        "dsll32\t$8, $8, 0\n\t"                                 \
+        "dsrl32\t%1, $8, 0\n\t"                                 \
+        ".set\tmips0"                                           \
+        : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel): "$8" );\
+        (((unsigned long long)__high << 32) | __low);})
+
+#define write_c2_register64(reg, sel, value)                    \
+ do{                                                            \
+       unsigned int __high = value>>32;                         \
+       unsigned int __low = value & 0xffffffff;                 \
+        __asm__ __volatile__(                                   \
+        ".set mips64\n\t"                                       \
+        "dsll32\t$8, %1, 0\n\t"                                 \
+        "dsll32\t$9, %0, 0\n\t"                                 \
+        "dsrl32\t$8, $8, 0\n\t"                                 \
+        "or\t    $8, $8, $9\n\t"                                \
+        "dmtc2\t $8, $%2, %3\n\t"                               \
+        ".set\tmips0"                                           \
+        :: "r"(__high), "r"(__low),                             \
+           "i"(reg), "i"(sel)                                   \
+        :"$8", "$9");                                           \
+   } while(0)
+
+#define xlr_cpu_id()                                            \
+({int __id;                                                     \
+ __asm__ __volatile__ (                                         \
+           ".set push\n"                                        \
+           ".set noreorder\n"                                   \
+           "mfc0 $8, $15, 1\n"                                  \
+           "andi %0, $8, 0x1f\n"                                \
+           ".set pop\n"                                         \
+           : "=r" (__id) : : "$8");                             \
+ __id;})
+
+#define xlr_core_id()                                           \
+({int __id;                                                     \
+ __asm__ __volatile__ (                                         \
+           ".set push\n"                                        \
+           ".set noreorder\n"                                   \
+           "mfc0 $8, $15, 1\n"                                  \
+           "andi %0, $8, 0x1f\n"                                \
+           ".set pop\n"                                         \
+           : "=r" (__id) : : "$8");                             \
+ __id/4;})
+
+#define xlr_thr_id()                                            \
+({int __id;                                                     \
+ __asm__ __volatile__ (                                         \
+           ".set push\n"                                        \
+           ".set noreorder\n"                                   \
+           "mfc0 $8, $15, 1\n"                                  \
+           "andi %0, $8, 0x3\n"                                 \
+           ".set pop\n"                                         \
+           : "=r" (__id) : : "$8");                             \
+ __id;})
+
+
+/* Additional registers on the XLR */
+#define MIPS_COP_0_OSSCRATCH   22
+
+#define XLR_CACHELINE_SIZE 32
+
+#define XLR_MAX_CORES 8
+
+/* functions to write to and read from the extended
+ * cp0 registers.
+ * EIRR : Extended Interrupt Request Register
+ *        cp0 register 9 sel 6
+ *        bits 0...7 are same as cause register 8...15
+ * EIMR : Extended Interrupt Mask Register
+ *        cp0 register 9 sel 7
+ *        bits 0...7 are same as status register 8...15
+ */
+
+static inline uint64_t 
+read_c0_eirr64(void)
+{
+	__uint32_t high, low;
+
+	__asm__ __volatile__(
+	            ".set push\n"
+	            ".set noreorder\n"
+	            ".set noat\n"
+	            ".set mips4\n"
+
+	            ".word 0x40214806  \n\t"
+	            "nop               \n\t"
+	            "dsra32 %0, $1, 0  \n\t"
+	            "sll    %1, $1, 0  \n\t"
+
+	            ".set pop\n"
+
+	    :       "=r"(high), "=r"(low)
+	);
+
+	return (((__uint64_t) high) << 32) | low;
+}
+
+static inline __uint64_t 
+read_c0_eimr64(void)
+{
+	__uint32_t high, low;
+
+	__asm__ __volatile__(
+	            ".set push\n"
+	            ".set noreorder\n"
+	            ".set noat\n"
+	            ".set mips4\n"
+
+	            ".word 0x40214807  \n\t"
+	            "nop               \n\t"
+	            "dsra32 %0, $1, 0  \n\t"
+	            "sll    %1, $1, 0  \n\t"
+
+	            ".set pop\n"
+
+	    :       "=r"(high), "=r"(low)
+	);
+
+	return (((__uint64_t) high) << 32) | low;
+}
+
+static inline void 
+write_c0_eirr64(__uint64_t value)
+{
+	__uint32_t low, high;
+
+	high = value >> 32;
+	low = value & 0xffffffff;
+
+	__asm__ __volatile__(
+	            ".set push\n"
+	            ".set noreorder\n"
+	            ".set noat\n"
+	            ".set mips4\n\t"
+
+	            "dsll32 $2, %1, 0  \n\t"
+	            "dsll32 $1, %0, 0  \n\t"
+	            "dsrl32 $2, $2, 0  \n\t"
+	            "or     $1, $1, $2 \n\t"
+	            ".word  0x40a14806 \n\t"
+	            "nop               \n\t"
+
+	            ".set pop\n"
+
+	    :
+	    :       "r"(high), "r"(low)
+	    :       "$1", "$2");
+}
+
+static inline void 
+write_c0_eimr64(__uint64_t value)
+{
+	__uint32_t low, high;
+
+	high = value >> 32;
+	low = value & 0xffffffff;
+
+	__asm__ __volatile__(
+	            ".set push\n"
+	            ".set noreorder\n"
+	            ".set noat\n"
+	            ".set mips4\n\t"
+
+	            "dsll32 $2, %1, 0  \n\t"
+	            "dsll32 $1, %0, 0  \n\t"
+	            "dsrl32 $2, $2, 0  \n\t"
+	            "or     $1, $1, $2 \n\t"
+	            ".word  0x40a14807 \n\t"
+	            "nop               \n\t"
+
+	            ".set pop\n"
+
+	    :
+	    :       "r"(high), "r"(low)
+	    :       "$1", "$2");
+}
+
+static __inline__ int 
+xlr_test_and_set(int *lock)
+{
+	int oldval = 0;
+
+	__asm__ __volatile__(".set push\n"
+	            ".set noreorder\n"
+	            "move $9, %2\n"
+	            "li $8, 1\n"
+	    //      "swapw $8, $9\n"
+	            ".word 0x71280014\n"
+	            "move %1, $8\n"
+	            ".set pop\n"
+	    :       "+m"(*lock), "=r"(oldval)
+	    :       "r"((unsigned long)lock)
+	    :       "$8", "$9"
+	);
+
+	return (oldval == 0 ? 1 /* success */ : 0 /* failure */ );
+}
+
+static __inline__ uint32_t 
+xlr_mfcr(uint32_t reg)
+{
+	uint32_t val;
+
+	__asm__ __volatile__(
+	            "move   $8, %1\n"
+	            ".word  0x71090018\n"
+	            "move   %0, $9\n"
+	    :       "=r"(val)
+	    :       "r"(reg):"$8", "$9");
+
+	return val;
+}
+
+static __inline__ void 
+xlr_mtcr(uint32_t reg, uint32_t val)
+{
+	__asm__ __volatile__(
+	            "move   $8, %1\n"
+	            "move   $9, %0\n"
+	            ".word  0x71090019\n"
+	    ::      "r"(val), "r"(reg)
+	    :       "$8", "$9");
+}
+
+static __inline__ uint32_t
+xlr_paddr_lw(uint64_t paddr)
+{
+        uint32_t high, low, tmp;
+
+        high = 0x98000000 | (paddr >> 32);
+        low = paddr & 0xffffffff;
+
+        __asm__ __volatile__(
+                    ".set push         \n\t"
+                    ".set mips64       \n\t"
+                    "dsll32 %1, %1, 0  \n\t"
+                    "dsll32 %2, %2, 0  \n\t"  /* get rid of the */
+                    "dsrl32 %2, %2, 0  \n\t"  /* sign extend */
+                    "or     %1, %1, %2 \n\t"
+                    "lw     %0, 0(%1)  \n\t"
+                    ".set pop           \n"
+            :       "=r"(tmp)
+            :       "r"(high), "r"(low));
+
+	return tmp;
+}
+
+/* for cpuid to hardware thread id mapping */
+extern uint32_t xlr_hw_thread_mask;
+extern int xlr_cpuid_to_hwtid[];
+extern int xlr_hwtid_to_cpuid[];
 
 #endif
diff --git a/sys/mips/rmi/shared_structs_func.h b/sys/mips/rmi/shared_structs_func.h
deleted file mode 100644
index be964140835..00000000000
--- a/sys/mips/rmi/shared_structs_func.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * Copyright (c) 2003-2009 RMI Corporation
- * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
- *
- * RMI_BSD */
-/* DO NOT EDIT THIS FILE
- * This file has been autogenerated by ./gen_struct_offsets
- */
-#ifndef _SHARED_STRUCTS_FUNC_H
-#define _SHARED_STRUCTS_FUNC_H
-
-/* struct boot1_info function prototypes */
-#define boot1_info_uart_print_func(info_ptr, ...) ((void (*)(const char *, ...))(unsigned long)(info_ptr->uart_print))( __VA_ARGS__ )
-#define boot1_info_led_output_func(info_ptr, ...) ((void (*)(int))(unsigned long)(info_ptr->led_output))( __VA_ARGS__ )
-#define boot1_info_init_func(info_ptr, ...) ((void (*)(void))(unsigned long)(info_ptr->init))( __VA_ARGS__ )
-#define boot1_info_exit_func(info_ptr, ...) ((void (*)(void))(unsigned long)(info_ptr->exit))( __VA_ARGS__ )
-#define boot1_info_warm_reset_func(info_ptr, ...) ((void (*)(void))(unsigned long)(info_ptr->warm_reset))( __VA_ARGS__ )
-#define boot1_info_wakeup_func(info_ptr, ...) ((int (*)(void *, void *, unsigned int))(unsigned long)(info_ptr->wakeup))( __VA_ARGS__ )
-#define boot1_info_master_reentry_fn_func(info_ptr, ...) ((void (*)(void *))(unsigned long)(info_ptr->master_reentry_fn))( __VA_ARGS__ )
-#define boot1_info_slave_reentry_fn_func(info_ptr, ...) ((void (*)(void *))(unsigned long)(info_ptr->slave_reentry_fn))( __VA_ARGS__ )
-#define boot1_info_uart_putchar_func(info_ptr, ...) ((void (*)(char))(unsigned long)(info_ptr->uart_putchar))( __VA_ARGS__ )
-#define boot1_info_uart_getchar_func(info_ptr, ...) ((char (*)(void))(unsigned long)(info_ptr->uart_getchar))( __VA_ARGS__ )
-#define boot1_info_malloc_func(info_ptr, ...) ((void *(*)(size_t))(unsigned long)(info_ptr->malloc))( __VA_ARGS__ )
-#define boot1_info_free_func(info_ptr, ...) ((void (*)(void *))(unsigned long)(info_ptr->free))( __VA_ARGS__ )
-#define boot1_info_alloc_pbuf_func(info_ptr, ...) ((struct packet *(*)(void))(unsigned long)(info_ptr->alloc_pbuf))( __VA_ARGS__ )
-#define boot1_info_free_pbuf_func(info_ptr, ...) ((void (*)(struct packet *))(unsigned long)(info_ptr->free_pbuf))( __VA_ARGS__ )
-#define boot1_info_wakeup_os_func(info_ptr, ...) ((int (*)(void *, void *, unsigned int))(unsigned long)(info_ptr->wakeup_os))( __VA_ARGS__ )
-
-
-#endif
diff --git a/sys/mips/rmi/shared_structs_offsets.h b/sys/mips/rmi/shared_structs_offsets.h
deleted file mode 100644
index 605c735356c..00000000000
--- a/sys/mips/rmi/shared_structs_offsets.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*-
- * Copyright (c) 2003-2009 RMI Corporation
- * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
- *
- * RMI_BSD */
-/* DO NOT EDIT THIS FILE
- * This file has been autogenerated by ./gen_struct_offsets
- */
-#ifndef _SHARED_STRUCTS_OFFSETS_H
-#define _SHARED_STRUCTS_OFFSETS_H
-
-/* struct boot1_info offsets */
-#define boot1_info_boot_level_off 0
-#define boot1_info_io_base_off 8
-#define boot1_info_output_device_off 16
-#define boot1_info_uart_print_off 24
-#define boot1_info_led_output_off 32
-#define boot1_info_init_off 40
-#define boot1_info_exit_off 48
-#define boot1_info_warm_reset_off 56
-#define boot1_info_wakeup_off 64
-#define boot1_info_cpu_online_map_off 72
-#define boot1_info_master_reentry_sp_off 80
-#define boot1_info_master_reentry_gp_off 88
-#define boot1_info_master_reentry_fn_off 96
-#define boot1_info_slave_reentry_fn_off 104
-#define boot1_info_magic_dword_off 112
-#define boot1_info_uart_putchar_off 120
-#define boot1_info_size_off 128
-#define boot1_info_uart_getchar_off 136
-#define boot1_info_nmi_handler_off 144
-#define boot1_info_psb_version_off 152
-#define boot1_info_mac_addr_off 160
-#define boot1_info_cpu_frequency_off 168
-#define boot1_info_board_version_off 176
-#define boot1_info_malloc_off 184
-#define boot1_info_free_off 192
-#define boot1_info_alloc_pbuf_off 200
-#define boot1_info_free_pbuf_off 208
-#define boot1_info_psb_os_cpu_map_off 216
-#define boot1_info_userapp_cpu_map_off 224
-#define boot1_info_wakeup_os_off 232
-#define boot1_info_psb_mem_map_off 240
-
-/* struct boot1_info size */
-#define boot1_info_size 248
-
-/* boot1_info version */
-#define boot1_info_version 1
-
-
-#endif
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index dec8bc6bbf4..fcbba2c9dd6 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -66,15 +66,14 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
 
 #include 
-#include 
 #include 
-#include 
 #include 
 #include 
 #include 
+#include 
+#include 
 
 void mpwait(void);
 unsigned long xlr_io_base = (unsigned long)(DEFAULT_XLR_IO_BASE);
diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c
index aa1458929a8..a7d3510eaaf 100644
--- a/sys/mips/rmi/xlr_pci.c
+++ b/sys/mips/rmi/xlr_pci.c
@@ -38,23 +38,24 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
+#include 
+
 #include 
 #include 
 #include 
 
-#include 
 #include 
 #include 
 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
 #include 
 #include 
-#include 
 #include 
 #include 
 
diff --git a/sys/mips/rmi/xlrconfig.h b/sys/mips/rmi/xlrconfig.h
deleted file mode 100644
index 1b22f7cc6db..00000000000
--- a/sys/mips/rmi/xlrconfig.h
+++ /dev/null
@@ -1,360 +0,0 @@
-/*-
- * Copyright (c) 2003-2009 RMI Corporation
- * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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.
-  __FBSDID("$FreeBSD$");
- *
- * RMI_BSD */
-#ifndef XLRCONFIG_H
-#define XLRCONFIG_H
-
-#include 
-#include 
-#include 
-
-#define read_c0_register32(reg, sel)                            \
-({ unsigned int __rv;                                           \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mfc0\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : "=r" (__rv) : "i" (reg), "i" (sel) );                 \
-        __rv;})
-
-#define write_c0_register32(reg,  sel, value)                   \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mtc0\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : : "r" (value), "i" (reg), "i" (sel) );
-
-#define read_c0_register64(reg, sel)                            \
-   ({ unsigned int __high, __low;                               \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips64\n\t"                                       \
-        "dmfc0\t $8, $%2, %3\n\t"                               \
-        "dsrl32\t%0, $8, 0\n\t"                                 \
-        "dsll32\t$8, $8, 0\n\t"                                 \
-        "dsrl32\t%1, $8, 0\n\t"                                 \
-        ".set\tpop"                                             \
-        : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel): "$8" );\
-        (((unsigned long long)__high << 32) | __low);})
-
-#define write_c0_register64(reg, sel, value)                    \
- do{                                                            \
-       unsigned int __high = val>>32;                           \
-       unsigned int __low = val & 0xffffffff;                   \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips64\n\t"                                       \
-        "dsll32\t$8, %1, 0\n\t"                                 \
-        "dsll32\t$9, %0, 0\n\t"                                 \
-        "or\t    $8, $8, $9\n\t"                                \
-        "dmtc0\t $8, $%2, %3\n\t"                               \
-        ".set\tpop"                                             \
-        :: "r"(high), "r"(low),  "i"(reg), "i"(sel):"$8", "$9");\
-   } while(0)
-
-#define read_c2_register32(reg, sel)                            \
-({ unsigned int __rv;                                           \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mfc2\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : "=r" (__rv) : "i" (reg), "i" (sel) );                 \
-        __rv;})
-
-#define write_c2_register32(reg,  sel, value)                   \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mtc2\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : : "r" (value), "i" (reg), "i" (sel) );
-
-#define read_c2_register64(reg, sel)                            \
-   ({ unsigned int __high, __low;                               \
-        __asm__ __volatile__(                                   \
-        ".set mips64\n\t"                                       \
-        "dmfc2\t $8, $%2, %3\n\t"                               \
-        "dsrl32\t%0, $8, 0\n\t"                                 \
-        "dsll32\t$8, $8, 0\n\t"                                 \
-        "dsrl32\t%1, $8, 0\n\t"                                 \
-        ".set\tmips0"                                           \
-        : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel): "$8" );\
-        (((unsigned long long)__high << 32) | __low);})
-
-#define write_c2_register64(reg, sel, value)                    \
- do{                                                            \
-       unsigned int __high = value>>32;                         \
-       unsigned int __low = value & 0xffffffff;                 \
-        __asm__ __volatile__(                                   \
-        ".set mips64\n\t"                                       \
-        "dsll32\t$8, %1, 0\n\t"                                 \
-        "dsll32\t$9, %0, 0\n\t"                                 \
-        "dsrl32\t$8, $8, 0\n\t"                                 \
-        "or\t    $8, $8, $9\n\t"                                \
-        "dmtc2\t $8, $%2, %3\n\t"                               \
-        ".set\tmips0"                                           \
-        :: "r"(__high), "r"(__low),                             \
-           "i"(reg), "i"(sel)                                   \
-        :"$8", "$9");                                           \
-   } while(0)
-
-#define xlr_cpu_id()                                            \
-({int __id;                                                     \
- __asm__ __volatile__ (                                         \
-           ".set push\n"                                        \
-           ".set noreorder\n"                                   \
-           "mfc0 $8, $15, 1\n"                                  \
-           "andi %0, $8, 0x1f\n"                                \
-           ".set pop\n"                                         \
-           : "=r" (__id) : : "$8");                             \
- __id;})
-
-#define xlr_core_id()                                           \
-({int __id;                                                     \
- __asm__ __volatile__ (                                         \
-           ".set push\n"                                        \
-           ".set noreorder\n"                                   \
-           "mfc0 $8, $15, 1\n"                                  \
-           "andi %0, $8, 0x1f\n"                                \
-           ".set pop\n"                                         \
-           : "=r" (__id) : : "$8");                             \
- __id/4;})
-
-#define xlr_thr_id()                                            \
-({int __id;                                                     \
- __asm__ __volatile__ (                                         \
-           ".set push\n"                                        \
-           ".set noreorder\n"                                   \
-           "mfc0 $8, $15, 1\n"                                  \
-           "andi %0, $8, 0x3\n"                                 \
-           ".set pop\n"                                         \
-           : "=r" (__id) : : "$8");                             \
- __id;})
-
-
-/* Additional registers on the XLR */
-#define MIPS_COP_0_OSSCRATCH   22
-
-#define XLR_CACHELINE_SIZE 32
-
-#define XLR_MAX_CORES 8
-
-/* functions to write to and read from the extended
- * cp0 registers.
- * EIRR : Extended Interrupt Request Register
- *        cp0 register 9 sel 6
- *        bits 0...7 are same as cause register 8...15
- * EIMR : Extended Interrupt Mask Register
- *        cp0 register 9 sel 7
- *        bits 0...7 are same as status register 8...15
- */
-
-static inline uint64_t 
-read_c0_eirr64(void)
-{
-	__uint32_t high, low;
-
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n"
-
-	            ".word 0x40214806  \n\t"
-	            "nop               \n\t"
-	            "dsra32 %0, $1, 0  \n\t"
-	            "sll    %1, $1, 0  \n\t"
-
-	            ".set pop\n"
-
-	    :       "=r"(high), "=r"(low)
-	);
-
-	return (((__uint64_t) high) << 32) | low;
-}
-
-static inline __uint64_t 
-read_c0_eimr64(void)
-{
-	__uint32_t high, low;
-
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n"
-
-	            ".word 0x40214807  \n\t"
-	            "nop               \n\t"
-	            "dsra32 %0, $1, 0  \n\t"
-	            "sll    %1, $1, 0  \n\t"
-
-	            ".set pop\n"
-
-	    :       "=r"(high), "=r"(low)
-	);
-
-	return (((__uint64_t) high) << 32) | low;
-}
-
-static inline void 
-write_c0_eirr64(__uint64_t value)
-{
-	__uint32_t low, high;
-
-	high = value >> 32;
-	low = value & 0xffffffff;
-
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n\t"
-
-	            "dsll32 $2, %1, 0  \n\t"
-	            "dsll32 $1, %0, 0  \n\t"
-	            "dsrl32 $2, $2, 0  \n\t"
-	            "or     $1, $1, $2 \n\t"
-	            ".word  0x40a14806 \n\t"
-	            "nop               \n\t"
-
-	            ".set pop\n"
-
-	    :
-	    :       "r"(high), "r"(low)
-	    :       "$1", "$2");
-}
-
-static inline void 
-write_c0_eimr64(__uint64_t value)
-{
-	__uint32_t low, high;
-
-	high = value >> 32;
-	low = value & 0xffffffff;
-
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n\t"
-
-	            "dsll32 $2, %1, 0  \n\t"
-	            "dsll32 $1, %0, 0  \n\t"
-	            "dsrl32 $2, $2, 0  \n\t"
-	            "or     $1, $1, $2 \n\t"
-	            ".word  0x40a14807 \n\t"
-	            "nop               \n\t"
-
-	            ".set pop\n"
-
-	    :
-	    :       "r"(high), "r"(low)
-	    :       "$1", "$2");
-}
-
-static __inline__ int 
-xlr_test_and_set(int *lock)
-{
-	int oldval = 0;
-
-	__asm__ __volatile__(".set push\n"
-	            ".set noreorder\n"
-	            "move $9, %2\n"
-	            "li $8, 1\n"
-	    //      "swapw $8, $9\n"
-	            ".word 0x71280014\n"
-	            "move %1, $8\n"
-	            ".set pop\n"
-	    :       "+m"(*lock), "=r"(oldval)
-	    :       "r"((unsigned long)lock)
-	    :       "$8", "$9"
-	);
-
-	return (oldval == 0 ? 1 /* success */ : 0 /* failure */ );
-}
-
-static __inline__ uint32_t 
-xlr_mfcr(uint32_t reg)
-{
-	uint32_t val;
-
-	__asm__ __volatile__(
-	            "move   $8, %1\n"
-	            ".word  0x71090018\n"
-	            "move   %0, $9\n"
-	    :       "=r"(val)
-	    :       "r"(reg):"$8", "$9");
-
-	return val;
-}
-
-static __inline__ void 
-xlr_mtcr(uint32_t reg, uint32_t val)
-{
-	__asm__ __volatile__(
-	            "move   $8, %1\n"
-	            "move   $9, %0\n"
-	            ".word  0x71090019\n"
-	    ::      "r"(val), "r"(reg)
-	    :       "$8", "$9");
-}
-
-static __inline__ uint32_t
-xlr_paddr_lw(uint64_t paddr)
-{
-        uint32_t high, low, tmp;
-
-        high = 0x98000000 | (paddr >> 32);
-        low = paddr & 0xffffffff;
-
-        __asm__ __volatile__(
-                    ".set push         \n\t"
-                    ".set mips64       \n\t"
-                    "dsll32 %1, %1, 0  \n\t"
-                    "dsll32 %2, %2, 0  \n\t"  /* get rid of the */
-                    "dsrl32 %2, %2, 0  \n\t"  /* sign extend */
-                    "or     %1, %1, %2 \n\t"
-                    "lw     %0, 0(%1)  \n\t"
-                    ".set pop           \n"
-            :       "=r"(tmp)
-            :       "r"(high), "r"(low));
-
-	return tmp;
-}
-
-/* for cpuid to hardware thread id mapping */
-extern uint32_t xlr_hw_thread_mask;
-extern int xlr_cpuid_to_hwtid[];
-extern int xlr_hwtid_to_cpuid[];
-#endif

From 79994806a18a0e2d773f61f9c670135abead530d Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 30 Aug 2010 13:26:07 +0000
Subject: [PATCH 0360/1624] Move debug.h to the the rge driver directory. rge.c
 is the only user of debug.h. Remove debug.h references from other files.

---
 sys/mips/rmi/dev/nlge/if_nlge.c    |  1 -
 sys/mips/rmi/{ => dev/xlr}/debug.h |  0
 sys/mips/rmi/dev/xlr/rge.c         |  3 ++-
 sys/mips/rmi/msgring.h             | 20 ++++----------------
 4 files changed, 6 insertions(+), 18 deletions(-)
 rename sys/mips/rmi/{ => dev/xlr}/debug.h (100%)

diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
index cdf5ffccbf7..746023020cf 100644
--- a/sys/mips/rmi/dev/nlge/if_nlge.c
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -102,7 +102,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
diff --git a/sys/mips/rmi/debug.h b/sys/mips/rmi/dev/xlr/debug.h
similarity index 100%
rename from sys/mips/rmi/debug.h
rename to sys/mips/rmi/dev/xlr/debug.h
diff --git a/sys/mips/rmi/dev/xlr/rge.c b/sys/mips/rmi/dev/xlr/rge.c
index 9e0bef7a9df..b021ceebcbc 100644
--- a/sys/mips/rmi/dev/xlr/rge.c
+++ b/sys/mips/rmi/dev/xlr/rge.c
@@ -95,11 +95,12 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
 #include 
+
+#include 
 #include 
 #include 
 #include 
diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h
index 6d9fd108a3d..6986739e0ad 100644
--- a/sys/mips/rmi/msgring.h
+++ b/sys/mips/rmi/msgring.h
@@ -374,18 +374,12 @@ message_send(unsigned int size, unsigned int code,
 
 	for (i = 0; i < 16; i++) {
 		status = msgrng_read_status();
-		//dbg_msg("status = %Lx\n", status);
 
 		if (status & 0x6) {
 			continue;
 		} else
 			break;
 	}
-	if (i == 16) {
-		if (dest == 0x61)
-			//dbg_msg("Processor %x: Unable to send msg to %llx\n", processor_id(), dest);
-		return status & 0x6;
-	}
 	return msgrng_read_status() & 0x06;
 }
 
@@ -417,16 +411,10 @@ static __inline__ int
 message_receive(int pri, int *size, int *code, int *src_id,
     struct msgrng_msg *msg)
 {
-	int res = message_receive_fast(pri, *size, *code, *src_id, msg->msg0, msg->msg1, msg->msg2, msg->msg3);
-
-#ifdef MSGRING_DUMP_MESSAGES
-	if (!res) {
-		dbg_msg("Received msg <%llx, %llx, %llx, %llx> <%d,%d,%d>\n",
-		    msg->msg0, msg->msg1, msg->msg2, msg->msg3,
-		    *size, *code, *src_id);
-	}
-#endif
-
+	int res;
+       
+	res = message_receive_fast(pri, *size, *code, *src_id,
+			msg->msg0, msg->msg1, msg->msg2, msg->msg3);
 	return res;
 }
 

From 8d19559bde75aab7e27125bc4c9387fe81488695 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 30 Aug 2010 14:24:44 +0000
Subject: [PATCH 0361/1624] Make the syscalls reserved for AFS usable by
 OpenAFS port.

Submitted by:	Benjamin Kaduk 
MFC after:	2 weeks
---
 sys/kern/syscalls.master | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/sys/kern/syscalls.master b/sys/kern/syscalls.master
index 75f775a62e0..ef6082847ca 100644
--- a/sys/kern/syscalls.master
+++ b/sys/kern/syscalls.master
@@ -594,7 +594,9 @@
 337	AUE_NULL	STD	{ int kldsym(int fileid, int cmd, \
 				    void *data); }
 338	AUE_JAIL	STD	{ int jail(struct jail *jail); }
-339	AUE_NULL	UNIMPL	pioctl
+339	AUE_NULL	NOSTD|NOTSTATIC	{ int nnpfs_syscall(int operation, \
+				    char *a_pathP, int a_opcode, \
+				    void *a_paramsP, int a_followSymlinks); }
 340	AUE_SIGPROCMASK	STD	{ int sigprocmask(int how, \
 				    const sigset_t *set, sigset_t *oset); }
 341	AUE_SIGSUSPEND	STD	{ int sigsuspend(const sigset_t *sigmask); }
@@ -670,7 +672,9 @@
 374	AUE_NULL	STD	{ int __setugid(int flag); }
 375	AUE_NULL	UNIMPL	nfsclnt
 376	AUE_EACCESS	STD	{ int eaccess(char *path, int flags); }
-377	AUE_NULL	UNIMPL	afs_syscall
+377	AUE_NULL	NOSTD|NOTSTATIC	{ int afs3_syscall(long syscall, \
+				    long parm1, long parm2, long parm3, \
+				    long parm4, long parm5, long parm6); }
 378	AUE_NMOUNT	STD	{ int nmount(struct iovec *iovp, \
 				    unsigned int iovcnt, int flags); }
 379	AUE_NULL	UNIMPL	kse_exit

From e7fb66340e060b9837c228fde0b7155592cb42b2 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 30 Aug 2010 14:26:02 +0000
Subject: [PATCH 0362/1624] Regen

---
 sys/kern/init_sysent.c   |  6 ++--
 sys/kern/syscalls.c      |  6 ++--
 sys/kern/systrace_args.c | 74 ++++++++++++++++++++++++++++++++++++++++
 sys/sys/syscall.h        |  4 ++-
 sys/sys/syscall.mk       |  4 ++-
 sys/sys/sysproto.h       | 22 +++++++++++-
 6 files changed, 107 insertions(+), 9 deletions(-)

diff --git a/sys/kern/init_sysent.c b/sys/kern/init_sysent.c
index ae10abeb474..706c966e3af 100644
--- a/sys/kern/init_sysent.c
+++ b/sys/kern/init_sysent.c
@@ -3,7 +3,7 @@
  *
  * DO NOT EDIT-- this file is automatically generated.
  * $FreeBSD$
- * created from FreeBSD: head/sys/kern/syscalls.master 209579 2010-06-28 18:06:46Z kib 
+ * created from FreeBSD: head/sys/kern/syscalls.master 211998 2010-08-30 14:24:44Z kib 
  */
 
 #include "opt_compat.h"
@@ -373,7 +373,7 @@ struct sysent sysent[] = {
 	{ compat4(AS(freebsd4_sendfile_args),sendfile), AUE_SENDFILE, NULL, 0, 0, 0, SY_THR_STATIC },	/* 336 = freebsd4 sendfile */
 	{ AS(kldsym_args), (sy_call_t *)kldsym, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 337 = kldsym */
 	{ AS(jail_args), (sy_call_t *)jail, AUE_JAIL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 338 = jail */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 339 = pioctl */
+	{ AS(nnpfs_syscall_args), (sy_call_t *)lkmressys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },	/* 339 = nnpfs_syscall */
 	{ AS(sigprocmask_args), (sy_call_t *)sigprocmask, AUE_SIGPROCMASK, NULL, 0, 0, 0, SY_THR_STATIC },	/* 340 = sigprocmask */
 	{ AS(sigsuspend_args), (sy_call_t *)sigsuspend, AUE_SIGSUSPEND, NULL, 0, 0, 0, SY_THR_STATIC },	/* 341 = sigsuspend */
 	{ compat4(AS(freebsd4_sigaction_args),sigaction), AUE_SIGACTION, NULL, 0, 0, 0, SY_THR_STATIC },	/* 342 = freebsd4 sigaction */
@@ -411,7 +411,7 @@ struct sysent sysent[] = {
 	{ AS(__setugid_args), (sy_call_t *)__setugid, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 374 = __setugid */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 375 = nfsclnt */
 	{ AS(eaccess_args), (sy_call_t *)eaccess, AUE_EACCESS, NULL, 0, 0, 0, SY_THR_STATIC },	/* 376 = eaccess */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 377 = afs_syscall */
+	{ AS(afs3_syscall_args), (sy_call_t *)lkmressys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },	/* 377 = afs3_syscall */
 	{ AS(nmount_args), (sy_call_t *)nmount, AUE_NMOUNT, NULL, 0, 0, 0, SY_THR_STATIC },	/* 378 = nmount */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 379 = kse_exit */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 380 = kse_wakeup */
diff --git a/sys/kern/syscalls.c b/sys/kern/syscalls.c
index e783799c192..77cc53f0a9a 100644
--- a/sys/kern/syscalls.c
+++ b/sys/kern/syscalls.c
@@ -3,7 +3,7 @@
  *
  * DO NOT EDIT-- this file is automatically generated.
  * $FreeBSD$
- * created from FreeBSD: head/sys/kern/syscalls.master 209579 2010-06-28 18:06:46Z kib 
+ * created from FreeBSD: head/sys/kern/syscalls.master 211998 2010-08-30 14:24:44Z kib 
  */
 
 const char *syscallnames[] = {
@@ -346,7 +346,7 @@ const char *syscallnames[] = {
 	"compat4.sendfile",		/* 336 = freebsd4 sendfile */
 	"kldsym",			/* 337 = kldsym */
 	"jail",			/* 338 = jail */
-	"#339",			/* 339 = pioctl */
+	"nnpfs_syscall",			/* 339 = nnpfs_syscall */
 	"sigprocmask",			/* 340 = sigprocmask */
 	"sigsuspend",			/* 341 = sigsuspend */
 	"compat4.sigaction",		/* 342 = freebsd4 sigaction */
@@ -384,7 +384,7 @@ const char *syscallnames[] = {
 	"__setugid",			/* 374 = __setugid */
 	"#375",			/* 375 = nfsclnt */
 	"eaccess",			/* 376 = eaccess */
-	"#377",			/* 377 = afs_syscall */
+	"afs3_syscall",			/* 377 = afs3_syscall */
 	"nmount",			/* 378 = nmount */
 	"#379",			/* 379 = kse_exit */
 	"#380",			/* 380 = kse_wakeup */
diff --git a/sys/kern/systrace_args.c b/sys/kern/systrace_args.c
index 743ad033dd9..4b95f010ea7 100644
--- a/sys/kern/systrace_args.c
+++ b/sys/kern/systrace_args.c
@@ -1770,6 +1770,17 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
 		*n_args = 1;
 		break;
 	}
+	/* nnpfs_syscall */
+	case 339: {
+		struct nnpfs_syscall_args *p = params;
+		iarg[0] = p->operation; /* int */
+		uarg[1] = (intptr_t) p->a_pathP; /* char * */
+		iarg[2] = p->a_opcode; /* int */
+		uarg[3] = (intptr_t) p->a_paramsP; /* void * */
+		iarg[4] = p->a_followSymlinks; /* int */
+		*n_args = 5;
+		break;
+	}
 	/* sigprocmask */
 	case 340: {
 		struct sigprocmask_args *p = params;
@@ -2011,6 +2022,19 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
 		*n_args = 2;
 		break;
 	}
+	/* afs3_syscall */
+	case 377: {
+		struct afs3_syscall_args *p = params;
+		iarg[0] = p->syscall; /* long */
+		iarg[1] = p->parm1; /* long */
+		iarg[2] = p->parm2; /* long */
+		iarg[3] = p->parm3; /* long */
+		iarg[4] = p->parm4; /* long */
+		iarg[5] = p->parm5; /* long */
+		iarg[6] = p->parm6; /* long */
+		*n_args = 7;
+		break;
+	}
 	/* nmount */
 	case 378: {
 		struct nmount_args *p = params;
@@ -5900,6 +5924,28 @@ systrace_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
 			break;
 		};
 		break;
+	/* nnpfs_syscall */
+	case 339:
+		switch(ndx) {
+		case 0:
+			p = "int";
+			break;
+		case 1:
+			p = "char *";
+			break;
+		case 2:
+			p = "int";
+			break;
+		case 3:
+			p = "void *";
+			break;
+		case 4:
+			p = "int";
+			break;
+		default:
+			break;
+		};
+		break;
 	/* sigprocmask */
 	case 340:
 		switch(ndx) {
@@ -6325,6 +6371,34 @@ systrace_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
 			break;
 		};
 		break;
+	/* afs3_syscall */
+	case 377:
+		switch(ndx) {
+		case 0:
+			p = "long";
+			break;
+		case 1:
+			p = "long";
+			break;
+		case 2:
+			p = "long";
+			break;
+		case 3:
+			p = "long";
+			break;
+		case 4:
+			p = "long";
+			break;
+		case 5:
+			p = "long";
+			break;
+		case 6:
+			p = "long";
+			break;
+		default:
+			break;
+		};
+		break;
 	/* nmount */
 	case 378:
 		switch(ndx) {
diff --git a/sys/sys/syscall.h b/sys/sys/syscall.h
index e7371f247a4..64e36064521 100644
--- a/sys/sys/syscall.h
+++ b/sys/sys/syscall.h
@@ -3,7 +3,7 @@
  *
  * DO NOT EDIT-- this file is automatically generated.
  * $FreeBSD$
- * created from FreeBSD: head/sys/kern/syscalls.master 209579 2010-06-28 18:06:46Z kib 
+ * created from FreeBSD: head/sys/kern/syscalls.master 211998 2010-08-30 14:24:44Z kib 
  */
 
 #define	SYS_syscall	0
@@ -277,6 +277,7 @@
 #define	SYS_freebsd4_sendfile	336
 #define	SYS_kldsym	337
 #define	SYS_jail	338
+#define	SYS_nnpfs_syscall	339
 #define	SYS_sigprocmask	340
 #define	SYS_sigsuspend	341
 #define	SYS_freebsd4_sigaction	342
@@ -306,6 +307,7 @@
 #define	SYS_extattr_delete_fd	373
 #define	SYS___setugid	374
 #define	SYS_eaccess	376
+#define	SYS_afs3_syscall	377
 #define	SYS_nmount	378
 #define	SYS___mac_get_proc	384
 #define	SYS___mac_set_proc	385
diff --git a/sys/sys/syscall.mk b/sys/sys/syscall.mk
index 8c8d1351bee..645b113cc27 100644
--- a/sys/sys/syscall.mk
+++ b/sys/sys/syscall.mk
@@ -1,7 +1,7 @@
 # FreeBSD system call names.
 # DO NOT EDIT-- this file is automatically generated.
 # $FreeBSD$
-# created from FreeBSD: head/sys/kern/syscalls.master 209579 2010-06-28 18:06:46Z kib 
+# created from FreeBSD: head/sys/kern/syscalls.master 211998 2010-08-30 14:24:44Z kib 
 MIASM =  \
 	syscall.o \
 	exit.o \
@@ -226,6 +226,7 @@ MIASM =  \
 	freebsd4_sendfile.o \
 	kldsym.o \
 	jail.o \
+	nnpfs_syscall.o \
 	sigprocmask.o \
 	sigsuspend.o \
 	freebsd4_sigaction.o \
@@ -255,6 +256,7 @@ MIASM =  \
 	extattr_delete_fd.o \
 	__setugid.o \
 	eaccess.o \
+	afs3_syscall.o \
 	nmount.o \
 	__mac_get_proc.o \
 	__mac_set_proc.o \
diff --git a/sys/sys/sysproto.h b/sys/sys/sysproto.h
index 5f86f3d8314..e1b35fe1ded 100644
--- a/sys/sys/sysproto.h
+++ b/sys/sys/sysproto.h
@@ -3,7 +3,7 @@
  *
  * DO NOT EDIT-- this file is automatically generated.
  * $FreeBSD$
- * created from FreeBSD: head/sys/kern/syscalls.master 209579 2010-06-28 18:06:46Z kib 
+ * created from FreeBSD: head/sys/kern/syscalls.master 211998 2010-08-30 14:24:44Z kib 
  */
 
 #ifndef _SYS_SYSPROTO_H_
@@ -933,6 +933,13 @@ struct kldsym_args {
 struct jail_args {
 	char jail_l_[PADL_(struct jail *)]; struct jail * jail; char jail_r_[PADR_(struct jail *)];
 };
+struct nnpfs_syscall_args {
+	char operation_l_[PADL_(int)]; int operation; char operation_r_[PADR_(int)];
+	char a_pathP_l_[PADL_(char *)]; char * a_pathP; char a_pathP_r_[PADR_(char *)];
+	char a_opcode_l_[PADL_(int)]; int a_opcode; char a_opcode_r_[PADR_(int)];
+	char a_paramsP_l_[PADL_(void *)]; void * a_paramsP; char a_paramsP_r_[PADR_(void *)];
+	char a_followSymlinks_l_[PADL_(int)]; int a_followSymlinks; char a_followSymlinks_r_[PADR_(int)];
+};
 struct sigprocmask_args {
 	char how_l_[PADL_(int)]; int how; char how_r_[PADR_(int)];
 	char set_l_[PADL_(const sigset_t *)]; const sigset_t * set; char set_r_[PADR_(const sigset_t *)];
@@ -1068,6 +1075,15 @@ struct eaccess_args {
 	char path_l_[PADL_(char *)]; char * path; char path_r_[PADR_(char *)];
 	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
 };
+struct afs3_syscall_args {
+	char syscall_l_[PADL_(long)]; long syscall; char syscall_r_[PADR_(long)];
+	char parm1_l_[PADL_(long)]; long parm1; char parm1_r_[PADR_(long)];
+	char parm2_l_[PADL_(long)]; long parm2; char parm2_r_[PADR_(long)];
+	char parm3_l_[PADL_(long)]; long parm3; char parm3_r_[PADR_(long)];
+	char parm4_l_[PADL_(long)]; long parm4; char parm4_r_[PADR_(long)];
+	char parm5_l_[PADL_(long)]; long parm5; char parm5_r_[PADR_(long)];
+	char parm6_l_[PADL_(long)]; long parm6; char parm6_r_[PADR_(long)];
+};
 struct nmount_args {
 	char iovp_l_[PADL_(struct iovec *)]; struct iovec * iovp; char iovp_r_[PADR_(struct iovec *)];
 	char iovcnt_l_[PADL_(unsigned int)]; unsigned int iovcnt; char iovcnt_r_[PADR_(unsigned int)];
@@ -1858,6 +1874,7 @@ int	sched_rr_get_interval(struct thread *, struct sched_rr_get_interval_args *);
 int	utrace(struct thread *, struct utrace_args *);
 int	kldsym(struct thread *, struct kldsym_args *);
 int	jail(struct thread *, struct jail_args *);
+int	nnpfs_syscall(struct thread *, struct nnpfs_syscall_args *);
 int	sigprocmask(struct thread *, struct sigprocmask_args *);
 int	sigsuspend(struct thread *, struct sigsuspend_args *);
 int	sigpending(struct thread *, struct sigpending_args *);
@@ -1885,6 +1902,7 @@ int	extattr_get_fd(struct thread *, struct extattr_get_fd_args *);
 int	extattr_delete_fd(struct thread *, struct extattr_delete_fd_args *);
 int	__setugid(struct thread *, struct __setugid_args *);
 int	eaccess(struct thread *, struct eaccess_args *);
+int	afs3_syscall(struct thread *, struct afs3_syscall_args *);
 int	nmount(struct thread *, struct nmount_args *);
 int	__mac_get_proc(struct thread *, struct __mac_get_proc_args *);
 int	__mac_set_proc(struct thread *, struct __mac_set_proc_args *);
@@ -2529,6 +2547,7 @@ int	freebsd7_shmctl(struct thread *, struct freebsd7_shmctl_args *);
 #define	SYS_AUE_freebsd4_sendfile	AUE_SENDFILE
 #define	SYS_AUE_kldsym	AUE_NULL
 #define	SYS_AUE_jail	AUE_JAIL
+#define	SYS_AUE_nnpfs_syscall	AUE_NULL
 #define	SYS_AUE_sigprocmask	AUE_SIGPROCMASK
 #define	SYS_AUE_sigsuspend	AUE_SIGSUSPEND
 #define	SYS_AUE_freebsd4_sigaction	AUE_SIGACTION
@@ -2558,6 +2577,7 @@ int	freebsd7_shmctl(struct thread *, struct freebsd7_shmctl_args *);
 #define	SYS_AUE_extattr_delete_fd	AUE_EXTATTR_DELETE_FD
 #define	SYS_AUE___setugid	AUE_NULL
 #define	SYS_AUE_eaccess	AUE_EACCESS
+#define	SYS_AUE_afs3_syscall	AUE_NULL
 #define	SYS_AUE_nmount	AUE_NMOUNT
 #define	SYS_AUE___mac_get_proc	AUE_NULL
 #define	SYS_AUE___mac_set_proc	AUE_NULL

From de478dd4b427a1f2c667af80784c58e5d73892e3 Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Mon, 30 Aug 2010 16:30:18 +0000
Subject: [PATCH 0363/1624] execve(2) has a special check for file permissions:
 a file must have at least one execute bit set, otherwise execve(2) will
 return EACCES even for an user with PRIV_VFS_EXEC privilege.

Add the check also to vaccess(9), vaccess_acl_nfs4(9) and
vaccess_acl_posix1e(9). This makes access(2) to better agree with
execve(2). Because ZFS doesn't use vaccess(9) for VEXEC, add the check
to zfs_freebsd_access() too. There may be other file systems which are
not using vaccess*() functions and need to be handled separately.

PR:		kern/125009
Reviewed by:	bde, trasz
Approved by:	pjd (ZFS part)
---
 .../opensolaris/uts/common/fs/zfs/zfs_vnops.c | 15 +++++++++----
 sys/kern/kern_exec.c                          | 16 +++++++-------
 sys/kern/subr_acl_nfs4.c                      | 22 +++++++++++++++++--
 sys/kern/subr_acl_posix1e.c                   | 10 +++++++--
 sys/kern/vfs_subr.c                           |  6 +++++
 5 files changed, 53 insertions(+), 16 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 1eeac3839de..180ac4fc4ef 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -4247,6 +4247,9 @@ zfs_freebsd_access(ap)
 		struct thread *a_td;
 	} */ *ap;
 {
+	vnode_t *vp = ap->a_vp;
+	znode_t *zp = VTOZ(vp);
+	znode_phys_t *zphys = zp->z_phys;
 	accmode_t accmode;
 	int error = 0;
 
@@ -4263,16 +4266,20 @@ zfs_freebsd_access(ap)
 	if (error == 0) {
 		accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
 		if (accmode != 0) {
-			vnode_t *vp = ap->a_vp;
-			znode_t *zp = VTOZ(vp);
-			znode_phys_t *zphys = zp->z_phys;
-
 			error = vaccess(vp->v_type, zphys->zp_mode,
 			    zphys->zp_uid, zphys->zp_gid, accmode, ap->a_cred,
 			    NULL);
 		}
 	}
 
+	/*
+	 * For VEXEC, ensure that at least one execute bit is set for
+	 * non-directories.
+	 */
+	if (error == 0 && (ap->a_accmode & VEXEC) != 0 && vp->v_type != VDIR &&
+	    (zphys->zp_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)
+		error = EACCES;
+
 	return (error);
 }
 
diff --git a/sys/kern/kern_exec.c b/sys/kern/kern_exec.c
index 2e7e08a56f5..3c05530160a 100644
--- a/sys/kern/kern_exec.c
+++ b/sys/kern/kern_exec.c
@@ -1363,17 +1363,17 @@ exec_check_permissions(imgp)
 	if (error)
 		return (error);
 #endif
-	
+
 	/*
-	 * 1) Check if file execution is disabled for the filesystem that this
-	 *	file resides on.
-	 * 2) Insure that at least one execute bit is on - otherwise root
-	 *	will always succeed, and we don't want to happen unless the
-	 *	file really is executable.
-	 * 3) Insure that the file is a regular file.
+	 * 1) Check if file execution is disabled for the filesystem that
+	 *    this file resides on.
+	 * 2) Ensure that at least one execute bit is on. Otherwise, a
+	 *    privileged user will always succeed, and we don't want this
+	 *    to happen unless the file really is executable.
+	 * 3) Ensure that the file is a regular file.
 	 */
 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
-	    ((attr->va_mode & 0111) == 0) ||
+	    (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
 	    (attr->va_type != VREG))
 		return (EACCES);
 
diff --git a/sys/kern/subr_acl_nfs4.c b/sys/kern/subr_acl_nfs4.c
index ec7ead930bb..5b2b0862201 100644
--- a/sys/kern/subr_acl_nfs4.c
+++ b/sys/kern/subr_acl_nfs4.c
@@ -162,6 +162,7 @@ vaccess_acl_nfs4(enum vtype type, uid_t file_uid, gid_t file_gid,
 	accmode_t priv_granted = 0;
 	int denied, explicitly_denied, access_mask, is_directory,
 	    must_be_owner = 0;
+	mode_t file_mode;
 
 	KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND |
 	    VEXPLICIT_DENY | VREAD_NAMED_ATTRS | VWRITE_NAMED_ATTRS |
@@ -216,6 +217,17 @@ vaccess_acl_nfs4(enum vtype type, uid_t file_uid, gid_t file_gid,
 			denied = EPERM;
 	}
 
+	/*
+	 * For VEXEC, ensure that at least one execute bit is set for
+	 * non-directories. We have to check the mode here to stay
+	 * consistent with execve(2). See the test in
+	 * exec_check_permissions().
+	 */
+	acl_nfs4_sync_mode_from_acl(&file_mode, aclp);
+	if (!denied && !is_directory && (accmode & VEXEC) &&
+	    (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0)
+		denied = EACCES;
+
 	if (!denied)
 		return (0);
 
@@ -236,8 +248,14 @@ vaccess_acl_nfs4(enum vtype type, uid_t file_uid, gid_t file_gid,
 		    PRIV_VFS_LOOKUP, 0))
 			priv_granted |= VEXEC;
 	} else {
-		if ((accmode & VEXEC) && !priv_check_cred(cred,
-		    PRIV_VFS_EXEC, 0))
+		/*
+		 * Ensure that at least one execute bit is on. Otherwise,
+		 * a privileged user will always succeed, and we don't want
+		 * this to happen unless the file really is executable.
+		 */
+		if ((accmode & VEXEC) && (file_mode &
+		    (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
+		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
 			priv_granted |= VEXEC;
 	}
 
diff --git a/sys/kern/subr_acl_posix1e.c b/sys/kern/subr_acl_posix1e.c
index f6fc6b2f990..311b214ff37 100644
--- a/sys/kern/subr_acl_posix1e.c
+++ b/sys/kern/subr_acl_posix1e.c
@@ -90,8 +90,14 @@ vaccess_acl_posix1e(enum vtype type, uid_t file_uid, gid_t file_gid,
 		     PRIV_VFS_LOOKUP, 0))
 			priv_granted |= VEXEC;
 	} else {
-		if ((accmode & VEXEC) && !priv_check_cred(cred,
-		    PRIV_VFS_EXEC, 0))
+		/*
+		 * Ensure that at least one execute bit is on. Otherwise,
+		 * a privileged user will always succeed, and we don't want
+		 * this to happen unless the file really is executable.
+		 */
+		if ((accmode & VEXEC) && (acl_posix1e_acl_to_mode(acl) &
+		    (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
+		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
 			priv_granted |= VEXEC;
 	}
 
diff --git a/sys/kern/vfs_subr.c b/sys/kern/vfs_subr.c
index 9bb365fcaae..783cbee1901 100644
--- a/sys/kern/vfs_subr.c
+++ b/sys/kern/vfs_subr.c
@@ -3619,7 +3619,13 @@ privcheck:
 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
 			priv_granted |= VEXEC;
 	} else {
+		/*
+		 * Ensure that at least one execute bit is on. Otherwise,
+		 * a privileged user will always succeed, and we don't want
+		 * this to happen unless the file really is executable.
+		 */
 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
+		    (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
 		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
 			priv_granted |= VEXEC;
 	}

From 400dda66463aec4bce4a9c788c7e04cf525c667e Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Mon, 30 Aug 2010 18:12:21 +0000
Subject: [PATCH 0364/1624] When DTrace is enabled, make sure we don't
 overwrite the IDT_DTRACE_RET entry with an IRQ for some hardware component.

Reviewed by:	jhb
Sponsored by:	The FreeBSD Foundation
---
 sys/x86/x86/local_apic.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/sys/x86/x86/local_apic.c b/sys/x86/x86/local_apic.c
index a05abe4c4a5..f479bbee769 100644
--- a/sys/x86/x86/local_apic.c
+++ b/sys/x86/x86/local_apic.c
@@ -89,6 +89,7 @@ CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
 /* Magic IRQ values for the timer and syscalls. */
 #define	IRQ_TIMER	(NUM_IO_INTS + 1)
 #define	IRQ_SYSCALL	(NUM_IO_INTS + 2)
+#define	IRQ_DTRACE_RET	(NUM_IO_INTS + 3)
 
 /*
  * Support for local APICs.  Local APICs manage interrupts on each
@@ -307,6 +308,10 @@ lapic_create(u_int apic_id, int boot_cpu)
 	lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
 	lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
 	    IRQ_TIMER;
+#ifdef KDTRACE_HOOKS
+	lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] = IRQ_DTRACE_RET;
+#endif
+
 
 #ifdef SMP
 	cpu_add(apic_id, boot_cpu);
@@ -1028,6 +1033,10 @@ apic_enable_vector(u_int apic_id, u_int vector)
 	KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
 	KASSERT(ioint_handlers[vector / 32] != NULL,
 	    ("No ISR handler for vector %u", vector));
+#ifdef KDTRACE_HOOKS
+	KASSERT(vector != IDT_DTRACE_RET,
+	    ("Attempt to overwrite DTrace entry"));
+#endif
 	setidt(vector, ioint_handlers[vector / 32], SDT_APIC, SEL_KPL,
 	    GSEL_APIC);
 }
@@ -1037,6 +1046,10 @@ apic_disable_vector(u_int apic_id, u_int vector)
 {
 
 	KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
+#ifdef KDTRACE_HOOKS
+	KASSERT(vector != IDT_DTRACE_RET,
+	    ("Attempt to overwrite DTrace entry"));
+#endif
 	KASSERT(ioint_handlers[vector / 32] != NULL,
 	    ("No ISR handler for vector %u", vector));
 #ifdef notyet
@@ -1060,6 +1073,10 @@ apic_free_vector(u_int apic_id, u_int vector, u_int irq)
 	KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
 	KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
 	    irq, ("IRQ mismatch"));
+#ifdef KDTRACE_HOOKS
+	KASSERT(vector != IDT_DTRACE_RET,
+	    ("Attempt to overwrite DTrace entry"));
+#endif
 
 	/*
 	 * Bind us to the cpu that owned the vector before freeing it so
@@ -1092,6 +1109,10 @@ apic_idt_to_irq(u_int apic_id, u_int vector)
 	KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
 	    vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
 	    ("Vector %u does not map to an IRQ line", vector));
+#ifdef KDTRACE_HOOKS
+	KASSERT(vector != IDT_DTRACE_RET,
+	    ("Attempt to overwrite DTrace entry"));
+#endif
 	irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
 	if (irq < 0)
 		irq = 0;
@@ -1123,6 +1144,10 @@ DB_SHOW_COMMAND(apic, db_show_apic)
 			irq = lapics[apic_id].la_ioint_irqs[i];
 			if (irq == -1 || irq == IRQ_SYSCALL)
 				continue;
+#ifdef KDTRACE_HOOKS
+			if (irq == IRQ_DTRACE_RET)
+				continue;
+#endif
 			db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
 			if (irq == IRQ_TIMER)
 				db_printf("lapic timer\n");

From a806ad402119299a9ea31a4252ee8197351cf632 Mon Sep 17 00:00:00 2001
From: Xin LI 
Date: Mon, 30 Aug 2010 19:15:04 +0000
Subject: [PATCH 0365/1624] Vendor update to version 3.80.06.003 to fix a panic
 with ZFS when under heavy I/O load.

Many thanks to LSI for continuing to support FreeBSD.

PR:		kern/149968
Submitted by:	LSI (Tom Couch)
Reported by:	Kai Kockro 
Tested by:	Kai Kockro, jpaetzel
MFC after:	7 days
---
 sys/dev/twa/tw_cl.h          |   4 +-
 sys/dev/twa/tw_cl_externs.h  |   2 +
 sys/dev/twa/tw_cl_fwif.h     |   2 +-
 sys/dev/twa/tw_cl_init.c     |   6 +-
 sys/dev/twa/tw_cl_intr.c     |  13 ++-
 sys/dev/twa/tw_cl_io.c       | 208 ++++++++++++++++++-----------------
 sys/dev/twa/tw_cl_misc.c     | 101 ++++++++---------
 sys/dev/twa/tw_cl_share.h    |  16 ++-
 sys/dev/twa/tw_osl.h         |   5 +
 sys/dev/twa/tw_osl_cam.c     | 108 +++++++++---------
 sys/dev/twa/tw_osl_freebsd.c | 179 +++++++++++++++++++++++-------
 sys/dev/twa/tw_osl_share.h   |   2 +-
 12 files changed, 386 insertions(+), 260 deletions(-)

diff --git a/sys/dev/twa/tw_cl.h b/sys/dev/twa/tw_cl.h
index f15260a5ac7..ab1936d7302 100644
--- a/sys/dev/twa/tw_cl.h
+++ b/sys/dev/twa/tw_cl.h
@@ -88,7 +88,8 @@ struct tw_cli_q_stats {
 #define TW_CLI_BUSY_Q		1	/* q of reqs submitted to fw */
 #define TW_CLI_PENDING_Q	2	/* q of reqs deferred due to 'q full' */
 #define TW_CLI_COMPLETE_Q	3	/* q of reqs completed by fw */
-#define TW_CLI_Q_COUNT		4	/* total number of queues */
+#define TW_CLI_RESET_Q		4	/* q of reqs reset by timeout */
+#define TW_CLI_Q_COUNT		5	/* total number of queues */
 
 
 /* CL's internal request context. */
@@ -133,6 +134,7 @@ struct tw_cli_ctlr_context {
 	TW_UINT8 		interrupts_enabled;	  /* Interrupts on controller enabled. */
 	TW_UINT8 		internal_req_busy;	  /* Data buffer for internal requests in use. */
 	TW_UINT8 		get_more_aens;		  /* More AEN's need to be retrieved. */
+	TW_UINT8 		reset_needed;		  /* Controller needs a soft reset. */
 	TW_UINT8 		reset_in_progress;	  /* Controller is being reset. */
 	TW_UINT8 		reset_phase1_in_progress; /* In 'phase 1' of reset. */
 	TW_UINT32		flags;		/* controller settings */
diff --git a/sys/dev/twa/tw_cl_externs.h b/sys/dev/twa/tw_cl_externs.h
index 1dd24255e5f..9fd2a3280b9 100644
--- a/sys/dev/twa/tw_cl_externs.h
+++ b/sys/dev/twa/tw_cl_externs.h
@@ -86,6 +86,8 @@ extern TW_INT32	tw_cli_submit_and_poll_request(struct tw_cli_req_context *req,
 
 /* Soft reset the controller. */
 extern TW_INT32	tw_cli_soft_reset(struct tw_cli_ctlr_context *ctlr);
+extern int twa_setup_intr(struct twa_softc *sc);
+extern int twa_teardown_intr(struct twa_softc *sc);
 
 /* Send down a SCSI command to the firmware (usually, an internal Req Sense. */
 extern TW_INT32	tw_cli_send_scsi_cmd(struct tw_cli_req_context *req,
diff --git a/sys/dev/twa/tw_cl_fwif.h b/sys/dev/twa/tw_cl_fwif.h
index f9c7678380e..52f76bfeab1 100644
--- a/sys/dev/twa/tw_cl_fwif.h
+++ b/sys/dev/twa/tw_cl_fwif.h
@@ -89,7 +89,7 @@
 #define TWA_STATUS_MINOR_VERSION_MASK		0x0F000000
 #define TWA_STATUS_MAJOR_VERSION_MASK		0xF0000000
 
-#define TWA_STATUS_UNEXPECTED_BITS		0x00F00000
+#define TWA_STATUS_UNEXPECTED_BITS		0x00D00000
 
 
 /* PCI related defines. */
diff --git a/sys/dev/twa/tw_cl_init.c b/sys/dev/twa/tw_cl_init.c
index 0b7daa521f8..a39da75b7ff 100644
--- a/sys/dev/twa/tw_cl_init.c
+++ b/sys/dev/twa/tw_cl_init.c
@@ -315,6 +315,7 @@ tw_cl_init_ctlr(struct tw_cl_ctlr_handle *ctlr_handle, TW_UINT32 flags,
 	tw_cli_req_q_init(ctlr, TW_CLI_BUSY_Q);
 	tw_cli_req_q_init(ctlr, TW_CLI_PENDING_Q);
 	tw_cli_req_q_init(ctlr, TW_CLI_COMPLETE_Q);
+	tw_cli_req_q_init(ctlr, TW_CLI_RESET_Q);
 
 	/* Initialize all locks used by CL. */
 	ctlr->gen_lock = &(ctlr->gen_lock_handle);
@@ -675,15 +676,14 @@ tw_cli_init_connection(struct tw_cli_ctlr_context *ctlr,
 	/* Submit the command, and wait for it to complete. */
 	error = tw_cli_submit_and_poll_request(req,
 		TW_CLI_REQUEST_TIMEOUT_PERIOD);
-	if (error == TW_OSL_ETIMEDOUT)
-		/* Clean-up done by tw_cli_submit_and_poll_request. */
-		return(error);
 	if (error)
 		goto out;
 	if ((error = init_connect->status)) {
+#if       0
 		tw_cli_create_ctlr_event(ctlr,
 			TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 			&(req->cmd_pkt->cmd_hdr));
+#endif // 0
 		goto out;
 	}
 	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
diff --git a/sys/dev/twa/tw_cl_intr.c b/sys/dev/twa/tw_cl_intr.c
index 08d63f9f0b8..a7c90d39555 100644
--- a/sys/dev/twa/tw_cl_intr.c
+++ b/sys/dev/twa/tw_cl_intr.c
@@ -248,8 +248,7 @@ tw_cli_process_resp_intr(struct tw_cli_ctlr_context *ctlr)
 #ifdef TW_OSL_DEBUG
 			tw_cl_print_ctlr_stats(ctlr->ctlr_handle);
 #endif /* TW_OSL_DEBUG */
-			tw_cl_reset_ctlr(ctlr->ctlr_handle);
-			return(TW_OSL_EIO);
+			continue;
 		}
 
 		/*
@@ -402,9 +401,7 @@ tw_cli_complete_io(struct tw_cli_req_context *req)
 #ifdef TW_OSL_DEBUG
 		tw_cl_print_ctlr_stats(ctlr->ctlr_handle);
 #endif /* TW_OSL_DEBUG */
-		tw_cl_reset_ctlr(ctlr->ctlr_handle);
-		req_pkt->status = TW_CL_ERR_REQ_BUS_RESET;
-		goto out;
+		return;
 	}
 
 	if (req->flags & TW_CLI_REQ_FLAGS_PASSTHRU) {
@@ -483,6 +480,7 @@ tw_cli_scsi_complete(struct tw_cli_req_context *req)
 			cdb[8], cdb[9], cdb[10], cdb[11],
 			cdb[12], cdb[13], cdb[14], cdb[15]);
 
+#if       0
 		/* 
 		 * Print the error. Firmware doesn't yet support
 		 * the 'Mode Sense' cmd.  Don't print if the cmd
@@ -493,6 +491,7 @@ tw_cli_scsi_complete(struct tw_cli_req_context *req)
 			tw_cli_create_ctlr_event(req->ctlr,
 				TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 				cmd_hdr);
+#endif // 0
 	}
 
 	if (scsi_req->sense_data) {
@@ -530,9 +529,11 @@ tw_cli_param_callback(struct tw_cli_req_context *req)
 	 */
 	if (! req->error_code)
 		if (cmd->param.status) {
+#if       0
 			tw_cli_create_ctlr_event(ctlr,
 				TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 				&(req->cmd_pkt->cmd_hdr));
+#endif // 0
 			tw_cl_create_event(ctlr->ctlr_handle, TW_CL_FALSE,
 				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_ERROR,
 				0x1204, 0x1, TW_CL_SEVERITY_ERROR_STRING,
@@ -590,9 +591,11 @@ tw_cli_aen_callback(struct tw_cli_req_context *req)
 		if ((error = cmd->status)) {
 			cmd_hdr = (struct tw_cl_command_header *)
 				(&(req->cmd_pkt->cmd_hdr));
+#if       0
 			tw_cli_create_ctlr_event(ctlr,
 				TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 				cmd_hdr);
+#endif // 0
 			tw_cl_create_event(ctlr->ctlr_handle, TW_CL_FALSE,
 				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_ERROR,
 				0x1206, 0x1, TW_CL_SEVERITY_ERROR_STRING,
diff --git a/sys/dev/twa/tw_cl_io.c b/sys/dev/twa/tw_cl_io.c
index 51ce08cdf43..1e1ca6cd676 100644
--- a/sys/dev/twa/tw_cl_io.c
+++ b/sys/dev/twa/tw_cl_io.c
@@ -74,18 +74,12 @@ tw_cl_start_io(struct tw_cl_ctlr_handle *ctlr_handle,
 	struct tw_cli_req_context		*req;
 	struct tw_cl_command_9k			*cmd;
 	struct tw_cl_scsi_req_packet		*scsi_req;
-	TW_INT32				error;
+	TW_INT32				error = TW_CL_ERR_REQ_SUCCESS;
 
 	tw_cli_dbg_printf(10, ctlr_handle, tw_osl_cur_func(), "entered");
 
 	ctlr = (struct tw_cli_ctlr_context *)(ctlr_handle->cl_ctlr_ctxt);
 
-	if (ctlr->reset_in_progress) {
-		tw_cli_dbg_printf(2, ctlr_handle, tw_osl_cur_func(),
-			"I/O during reset: returning busy.");
-		return(TW_OSL_EBUSY);
-	}
-
 	/*
 	 * If working with a firmware version that does not support multiple
 	 * luns, and this request is directed at a non-zero lun, error it
@@ -145,7 +139,12 @@ tw_cl_start_io(struct tw_cl_ctlr_handle *ctlr_handle,
 			cmd->sg_list, scsi_req->sgl_entries);
 	}
 
-	if ((error = tw_cli_submit_cmd(req))) {
+	if (((TW_CL_Q_FIRST_ITEM(&(ctlr->req_q_head[TW_CLI_PENDING_Q]))) != TW_CL_NULL) ||
+		(ctlr->reset_in_progress)) {
+		tw_cli_req_q_insert_tail(req, TW_CLI_PENDING_Q);
+		TW_CLI_WRITE_CONTROL_REGISTER(ctlr_handle,
+			TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
+	} else if ((error = tw_cli_submit_cmd(req))) {
 		tw_cli_dbg_printf(2, ctlr_handle, tw_osl_cur_func(),
 			"Could not start request. request = %p, error = %d",
 			req, error);
@@ -171,7 +170,7 @@ tw_cli_submit_cmd(struct tw_cli_req_context *req)
 	struct tw_cli_ctlr_context	*ctlr = req->ctlr;
 	struct tw_cl_ctlr_handle	*ctlr_handle = ctlr->ctlr_handle;
 	TW_UINT32			status_reg;
-	TW_INT32			error;
+	TW_INT32			error = 0;
 
 	tw_cli_dbg_printf(10, ctlr_handle, tw_osl_cur_func(), "entered");
 
@@ -185,11 +184,7 @@ tw_cli_submit_cmd(struct tw_cli_req_context *req)
 				 TWA_COMMAND_QUEUE_OFFSET_LOW,
 				 (TW_UINT32)(req->cmd_pkt_phys + sizeof(struct tw_cl_command_header)), 4);
 
-	/* Check to see if we can post a command. */
 	status_reg = TW_CLI_READ_STATUS_REGISTER(ctlr_handle);
-	if ((error = tw_cli_check_ctlr_state(ctlr, status_reg)))
-		goto out;
-
 	if (status_reg & TWA_STATUS_COMMAND_QUEUE_FULL) {
 		struct tw_cl_req_packet	*req_pkt =
 			(struct tw_cl_req_packet *)(req->orig_req);
@@ -207,14 +202,12 @@ tw_cli_submit_cmd(struct tw_cli_req_context *req)
 					"pending internal/ioctl request");
 				req->state = TW_CLI_REQ_STATE_PENDING;
 				tw_cli_req_q_insert_tail(req, TW_CLI_PENDING_Q);
-				error = 0;
 				/* Unmask command interrupt. */
 				TW_CLI_WRITE_CONTROL_REGISTER(ctlr_handle,
 					TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
 			} else
 				error = TW_OSL_EBUSY;
 		} else {
-			tw_osl_ctlr_busy(ctlr_handle, req->req_handle);
 			error = TW_OSL_EBUSY;
 		}
 	} else {
@@ -246,7 +239,7 @@ tw_cli_submit_cmd(struct tw_cli_req_context *req)
 						 (TW_UINT32)(req->cmd_pkt_phys + sizeof(struct tw_cl_command_header)), 4);
 		}
 	}
-out:
+
 	tw_osl_free_lock(ctlr_handle, ctlr->io_lock);
 
 	return(error);
@@ -277,18 +270,12 @@ tw_cl_fw_passthru(struct tw_cl_ctlr_handle *ctlr_handle,
 	TW_UINT8				opcode;
 	TW_UINT8				sgl_offset;
 	TW_VOID					*sgl = TW_CL_NULL;
-	TW_INT32				error;
+	TW_INT32				error = TW_CL_ERR_REQ_SUCCESS;
 
 	tw_cli_dbg_printf(5, ctlr_handle, tw_osl_cur_func(), "entered");
 
 	ctlr = (struct tw_cli_ctlr_context *)(ctlr_handle->cl_ctlr_ctxt);
 
-	if (ctlr->reset_in_progress) {
-		tw_cli_dbg_printf(2, ctlr_handle, tw_osl_cur_func(),
-			"Passthru request during reset: returning busy.");
-		return(TW_OSL_EBUSY);
-	}
-
 	if ((req = tw_cli_get_request(ctlr
 		)) == TW_CL_NULL) {
 		tw_cli_dbg_printf(2, ctlr_handle, tw_osl_cur_func(),
@@ -301,7 +288,7 @@ tw_cl_fw_passthru(struct tw_cl_ctlr_handle *ctlr_handle,
 	req->orig_req = req_pkt;
 	req->tw_cli_callback = tw_cli_complete_io;
 
-	req->flags |= (TW_CLI_REQ_FLAGS_EXTERNAL | TW_CLI_REQ_FLAGS_PASSTHRU);
+	req->flags |= TW_CLI_REQ_FLAGS_PASSTHRU;
 
 	pt_req = &(req_pkt->gen_req_pkt.pt_req);
 
@@ -348,7 +335,12 @@ tw_cl_fw_passthru(struct tw_cl_ctlr_handle *ctlr_handle,
 		tw_cli_fill_sg_list(ctlr, pt_req->sg_list,
 			sgl, pt_req->sgl_entries);
 
-	if ((error = tw_cli_submit_cmd(req))) {
+	if (((TW_CL_Q_FIRST_ITEM(&(ctlr->req_q_head[TW_CLI_PENDING_Q]))) != TW_CL_NULL) ||
+		(ctlr->reset_in_progress)) {
+		tw_cli_req_q_insert_tail(req, TW_CLI_PENDING_Q);
+		TW_CLI_WRITE_CONTROL_REGISTER(ctlr_handle,
+			TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
+	} else if ((error = tw_cli_submit_cmd(req))) {
 		tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_ERROR,
 			0x1100, 0x1, TW_CL_SEVERITY_ERROR_STRING,
@@ -760,8 +752,7 @@ tw_cli_get_param(struct tw_cli_ctlr_context *ctlr, TW_INT32 table_id,
 
 	cmd->param.sgl_off__opcode =
 		BUILD_SGL_OFF__OPCODE(2, TWA_FW_CMD_GET_PARAM);
-	cmd->param.request_id =
-		(TW_UINT8)(TW_CL_SWAP16(req->request_id));
+	cmd->param.request_id = (TW_UINT8)(TW_CL_SWAP16(req->request_id));
 	cmd->param.host_id__unit = BUILD_HOST_ID__UNIT(0, 0);
 	cmd->param.param_count = TW_CL_SWAP16(1);
 
@@ -789,15 +780,14 @@ tw_cli_get_param(struct tw_cli_ctlr_context *ctlr, TW_INT32 table_id,
 		/* There's no call back; wait till the command completes. */
 		error = tw_cli_submit_and_poll_request(req,
 				TW_CLI_REQUEST_TIMEOUT_PERIOD);
-		if (error == TW_OSL_ETIMEDOUT)
-			/* Clean-up done by tw_cli_submit_and_poll_request. */
-			return(error);
 		if (error)
 			goto out;
 		if ((error = cmd->param.status)) {
+#if       0
 			tw_cli_create_ctlr_event(ctlr,
 				TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 				&(req->cmd_pkt->cmd_hdr));
+#endif // 0
 			goto out;
 		}
 		tw_osl_memcpy(param_data, param->data, param_size);
@@ -905,18 +895,17 @@ tw_cli_set_param(struct tw_cli_ctlr_context *ctlr, TW_INT32 table_id,
 
 	/* Submit the command. */
 	if (callback == TW_CL_NULL) {
-		/* There's no call back;  wait till the command completes. */
+		/* There's no call back; wait till the command completes. */
 		error = tw_cli_submit_and_poll_request(req,
-			TW_CLI_REQUEST_TIMEOUT_PERIOD);
-		if (error == TW_OSL_ETIMEDOUT)
-			/* Clean-up done by tw_cli_submit_and_poll_request. */
-			return(error);
+				TW_CLI_REQUEST_TIMEOUT_PERIOD);
 		if (error)
 			goto out;
 		if ((error = cmd->param.status)) {
+#if       0
 			tw_cli_create_ctlr_event(ctlr,
 				TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 				&(req->cmd_pkt->cmd_hdr));
+#endif // 0
 			goto out;
 		}
 		ctlr->internal_req_busy = TW_CL_FALSE;
@@ -1022,9 +1011,7 @@ tw_cli_submit_and_poll_request(struct tw_cli_req_context *req,
 	 * tw_cli_submit_pending_queue.  There could be a race in that case.
 	 * Need to revisit.
 	 */
-	if (req->state != TW_CLI_REQ_STATE_PENDING)
-		tw_cl_reset_ctlr(ctlr->ctlr_handle);
-	else {
+	if (req->state == TW_CLI_REQ_STATE_PENDING) {
 		tw_cli_dbg_printf(3, ctlr->ctlr_handle, tw_osl_cur_func(),
 			"Removing request from pending queue");
 		/*
@@ -1053,6 +1040,7 @@ tw_cli_submit_and_poll_request(struct tw_cli_req_context *req,
  *			drains any incomplete requests.
  *
  * Input:		ctlr	-- ptr to per ctlr structure
+ * 			req_handle	-- ptr to request handle
  * Output:		None
  * Return value:	0	-- success
  *			non-zero-- failure
@@ -1063,15 +1051,15 @@ tw_cl_reset_ctlr(struct tw_cl_ctlr_handle *ctlr_handle)
 	struct tw_cli_ctlr_context	*ctlr =
 		(struct tw_cli_ctlr_context *)(ctlr_handle->cl_ctlr_ctxt);
 	struct twa_softc		*sc = ctlr_handle->osl_ctlr_ctxt;
+	struct tw_cli_req_context	*req;
 	TW_INT32			reset_attempt = 1;
-	TW_INT32			error;
+	TW_INT32			error = 0;
 
 	tw_cli_dbg_printf(2, ctlr_handle, tw_osl_cur_func(), "entered");
 
 	ctlr->reset_in_progress = TW_CL_TRUE;
-	xpt_freeze_simq(sc->sim, 1);
+	twa_teardown_intr(sc);
 
-	tw_cli_disable_interrupts(ctlr);
 
 	/*
 	 * Error back all requests in the complete, busy, and pending queues.
@@ -1080,8 +1068,6 @@ tw_cl_reset_ctlr(struct tw_cl_ctlr_handle *ctlr_handle)
 	 * will continue its course and get submitted to the controller after
 	 * the reset is done (and io_lock is released).
 	 */
-	tw_cli_dbg_printf(2, ctlr_handle, tw_osl_cur_func(),
-		"Draining all queues following reset");
 	tw_cli_drain_complete_queue(ctlr);
 	tw_cli_drain_busy_queue(ctlr);
 	tw_cli_drain_pending_queue(ctlr);
@@ -1089,53 +1075,88 @@ tw_cl_reset_ctlr(struct tw_cl_ctlr_handle *ctlr_handle)
 	ctlr->get_more_aens     = TW_CL_FALSE;
 
 	/* Soft reset the controller. */
-try_reset:
-	if ((error = tw_cli_soft_reset(ctlr))) {
-		tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+	while (reset_attempt <= TW_CLI_MAX_RESET_ATTEMPTS) {
+		if ((error = tw_cli_soft_reset(ctlr))) {
+			tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
+				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
+				0x1105, 0x1, TW_CL_SEVERITY_ERROR_STRING,
+				"Controller reset failed",
+				"error = %d; attempt %d", error, reset_attempt++);
+			reset_attempt++;
+			continue;
+		}
+
+		/* Re-establish logical connection with the controller. */
+		if ((error = tw_cli_init_connection(ctlr,
+				(TW_UINT16)(ctlr->max_simult_reqs),
+				0, 0, 0, 0, 0, TW_CL_NULL, TW_CL_NULL, TW_CL_NULL,
+				TW_CL_NULL, TW_CL_NULL))) {
+			tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
+				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
+				0x1106, 0x1, TW_CL_SEVERITY_ERROR_STRING,
+				"Can't initialize connection after reset",
+				"error = %d", error);
+			reset_attempt++;
+			continue;
+		}
+
+#ifdef    TW_OSL_DEBUG
+		tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
-			0x1105, 0x1, TW_CL_SEVERITY_ERROR_STRING,
-			"Controller reset failed",
-			"error = %d; attempt %d", error, reset_attempt++);
-		if (reset_attempt <= TW_CLI_MAX_RESET_ATTEMPTS)
-			goto try_reset;
-		else
-			goto out;
+			0x1107, 0x3, TW_CL_SEVERITY_INFO_STRING,
+			"Controller reset done!", " ");
+#endif /* TW_OSL_DEBUG */
+		break;
+	} /* End of while */
+
+	/* Move commands from the reset queue to the pending queue. */
+	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_RESET_Q)) != TW_CL_NULL) {
+		tw_osl_timeout(req->req_handle);
+		tw_cli_req_q_insert_tail(req, TW_CLI_PENDING_Q);
 	}
 
-	/* Re-establish logical connection with the controller. */
-	if ((error = tw_cli_init_connection(ctlr,
-			(TW_UINT16)(ctlr->max_simult_reqs),
-			0, 0, 0, 0, 0, TW_CL_NULL, TW_CL_NULL, TW_CL_NULL,
-			TW_CL_NULL, TW_CL_NULL))) {
-		tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
-			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
-			0x1106, 0x1, TW_CL_SEVERITY_ERROR_STRING,
-			"Can't initialize connection after reset",
-			"error = %d", error);
-		goto out;
-	}
-
-	tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
-		TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
-		0x1107, 0x3, TW_CL_SEVERITY_INFO_STRING,
-		"Controller reset done!",
-		" ");
-
-out:
-	ctlr->reset_in_progress = TW_CL_FALSE;
-	xpt_release_simq(sc->sim, 1);
-
-	/*
-	 * Enable interrupts, and also clear attention and response interrupts.
-	 */
+	twa_setup_intr(sc);
 	tw_cli_enable_interrupts(ctlr);
-	
+	if ((TW_CL_Q_FIRST_ITEM(&(ctlr->req_q_head[TW_CLI_PENDING_Q]))) != TW_CL_NULL)
+		TW_CLI_WRITE_CONTROL_REGISTER(ctlr_handle,
+			TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
+	ctlr->reset_in_progress = TW_CL_FALSE;
+	ctlr->reset_needed = TW_CL_FALSE;
+
 	/* Request for a bus re-scan. */
-	if (!error)
-		tw_osl_scan_bus(ctlr_handle);
+	tw_osl_scan_bus(ctlr_handle);
+
 	return(error);
 }
 
+TW_VOID
+tw_cl_set_reset_needed(struct tw_cl_ctlr_handle *ctlr_handle)
+{
+	struct tw_cli_ctlr_context	*ctlr =
+		(struct tw_cli_ctlr_context *)(ctlr_handle->cl_ctlr_ctxt);
+
+	ctlr->reset_needed = TW_CL_TRUE;
+}
+
+TW_INT32
+tw_cl_is_reset_needed(struct tw_cl_ctlr_handle *ctlr_handle)
+{
+	struct tw_cli_ctlr_context	*ctlr =
+		(struct tw_cli_ctlr_context *)(ctlr_handle->cl_ctlr_ctxt);
+
+	return(ctlr->reset_needed);
+}
+
+TW_INT32
+tw_cl_is_active(struct tw_cl_ctlr_handle *ctlr_handle)
+{
+	struct tw_cli_ctlr_context	*ctlr =
+		(struct tw_cli_ctlr_context *)
+		(ctlr_handle->cl_ctlr_ctxt);
+
+		return(ctlr->active);
+}
+
 
 
 /*
@@ -1151,14 +1172,13 @@ TW_INT32
 tw_cli_soft_reset(struct tw_cli_ctlr_context *ctlr)
 {
 	struct tw_cl_ctlr_handle	*ctlr_handle = ctlr->ctlr_handle;
-	TW_UINT32			status_reg;
 	int				found;
 	int				loop_count;
 	TW_UINT32			error;
 
 	tw_cli_dbg_printf(1, ctlr_handle, tw_osl_cur_func(), "entered");
 
-	tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+	tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 		TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 		0x1108, 0x3, TW_CL_SEVERITY_INFO_STRING,
 		"Resetting controller...",
@@ -1193,7 +1213,7 @@ tw_cli_soft_reset(struct tw_cli_ctlr_context *ctlr)
 		} while (!found && (loop_count < 6000000)); /* Loop for no more than 60 seconds */
 
 		if (!found) {
-			tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+			tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 				0x1109, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 				"Missed firmware handshake after soft-reset",
@@ -1210,7 +1230,7 @@ tw_cli_soft_reset(struct tw_cli_ctlr_context *ctlr)
 			TWA_STATUS_MICROCONTROLLER_READY |
 			TWA_STATUS_ATTENTION_INTERRUPT,
 			TW_CLI_RESET_TIMEOUT_PERIOD))) {
-		tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+		tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 			0x1109, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 			"Micro-ctlr not ready/No attn intr after reset",
@@ -1244,26 +1264,14 @@ tw_cli_soft_reset(struct tw_cli_ctlr_context *ctlr)
 	}
 	
 	if ((error = tw_cli_find_aen(ctlr, TWA_AEN_SOFT_RESET))) {
-		tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+		tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 			0x110C, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 			"Reset not reported by controller",
 			"error = %d", error);
 		return(error);
 	}
-	
-	status_reg = TW_CLI_READ_STATUS_REGISTER(ctlr_handle);
-	
-	if ((error = TW_CLI_STATUS_ERRORS(status_reg)) ||
-			(error = tw_cli_check_ctlr_state(ctlr, status_reg))) {
-		tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
-			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
-			0x110D, 0x1, TW_CL_SEVERITY_ERROR_STRING,
-			"Controller errors detected after reset",
-			"error = %d", error);
-		return(error);
-	}
-	
+
 	return(TW_OSL_ESUCCESS);
 }
 
diff --git a/sys/dev/twa/tw_cl_misc.c b/sys/dev/twa/tw_cl_misc.c
index f6c98455303..b6b53330f21 100644
--- a/sys/dev/twa/tw_cl_misc.c
+++ b/sys/dev/twa/tw_cl_misc.c
@@ -83,7 +83,8 @@ tw_cli_drain_complete_queue(struct tw_cli_ctlr_context *ctlr)
 	tw_cli_dbg_printf(3, ctlr->ctlr_handle, tw_osl_cur_func(), "entered");
 
 	/* Walk the busy queue. */
-	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_COMPLETE_Q))) {
+	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_COMPLETE_Q)) !=
+		TW_CL_NULL) {
 		if (req->flags & TW_CLI_REQ_FLAGS_INTERNAL) {
 			/*
 			 * It's an internal request.  Set the appropriate
@@ -97,20 +98,21 @@ tw_cli_drain_complete_queue(struct tw_cli_ctlr_context *ctlr)
 			req->error_code = TW_CL_ERR_REQ_BUS_RESET;
 			if (req->tw_cli_callback)
 				req->tw_cli_callback(req);
-		} else {
-			if ((req_pkt = req->orig_req)) {
-				/* It's a SCSI request.  Complete it. */
-				tw_cli_dbg_printf(2, ctlr->ctlr_handle,
-					tw_osl_cur_func(),
-					"Completing complete request %p "
-					"on reset",
-					req);
+		} else if (req->flags & TW_CLI_REQ_FLAGS_PASSTHRU) {
+			/* It's a passthru request.  Complete it. */
+			if ((req_pkt = req->orig_req) != TW_CL_NULL) {
 				req_pkt->status = TW_CL_ERR_REQ_BUS_RESET;
-				req_pkt->tw_osl_callback(req->req_handle);
+
+				if (req_pkt->tw_osl_callback)
+					req_pkt->tw_osl_callback(req->req_handle);
 			}
 			tw_cli_req_q_insert_tail(req, TW_CLI_FREE_Q);
+		} else {
+			/* It's an external (SCSI) request.  Add it to the reset queue. */
+			tw_osl_untimeout(req->req_handle);
+			tw_cli_req_q_insert_tail(req, TW_CLI_RESET_Q);
 		}
-	}
+	} /* End of while loop */
 }
 
 
@@ -135,7 +137,8 @@ tw_cli_drain_busy_queue(struct tw_cli_ctlr_context *ctlr)
 	tw_cli_dbg_printf(3, ctlr->ctlr_handle, tw_osl_cur_func(), "entered");
 
 	/* Walk the busy queue. */
-	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_BUSY_Q))) {
+	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_BUSY_Q)) !=
+		TW_CL_NULL) {
 		if (req->flags & TW_CLI_REQ_FLAGS_INTERNAL) {
 			/*
 			 * It's an internal request.  Set the appropriate
@@ -149,19 +152,21 @@ tw_cli_drain_busy_queue(struct tw_cli_ctlr_context *ctlr)
 			req->error_code = TW_CL_ERR_REQ_BUS_RESET;
 			if (req->tw_cli_callback)
 				req->tw_cli_callback(req);
-		} else {
-			if ((req_pkt = req->orig_req)) {
-				/* It's a SCSI request.  Complete it. */
-				tw_cli_dbg_printf(2, ctlr->ctlr_handle,
-					tw_osl_cur_func(),
-					"Completing busy request %p on reset",
-					req);
+		} else if (req->flags & TW_CLI_REQ_FLAGS_PASSTHRU) {
+			/* It's a passthru request.  Complete it. */
+			if ((req_pkt = req->orig_req) != TW_CL_NULL) {
 				req_pkt->status = TW_CL_ERR_REQ_BUS_RESET;
-				req_pkt->tw_osl_callback(req->req_handle);
+
+				if (req_pkt->tw_osl_callback)
+					req_pkt->tw_osl_callback(req->req_handle);
 			}
 			tw_cli_req_q_insert_tail(req, TW_CLI_FREE_Q);
+		} else {
+			/* It's an external (SCSI) request.  Add it to the reset queue. */
+			tw_osl_untimeout(req->req_handle);
+			tw_cli_req_q_insert_tail(req, TW_CLI_RESET_Q);
 		}
-	}
+	} /* End of while loop */
 }
 
 
@@ -188,7 +193,8 @@ tw_cli_drain_pending_queue(struct tw_cli_ctlr_context *ctlr)
 	/*
 	 * Pull requests off the pending queue, and complete them.
 	 */
-	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_PENDING_Q))) {
+	while ((req = tw_cli_req_q_remove_head(ctlr, TW_CLI_PENDING_Q)) !=
+		TW_CL_NULL) {
 		if (req->flags & TW_CLI_REQ_FLAGS_INTERNAL) {
 			/*
 			 * It's an internal request.  Set the appropriate
@@ -202,19 +208,21 @@ tw_cli_drain_pending_queue(struct tw_cli_ctlr_context *ctlr)
 			req->error_code = TW_CL_ERR_REQ_BUS_RESET;
 			if (req->tw_cli_callback)
 				req->tw_cli_callback(req);
-		} else {
-			if ((req_pkt = req->orig_req)) {
-				/* It's an external request.  Complete it. */
-				tw_cli_dbg_printf(2, ctlr->ctlr_handle,
-					tw_osl_cur_func(),
-					"Completing pending request %p "
-					"on reset", req);
+		} else if (req->flags & TW_CLI_REQ_FLAGS_PASSTHRU) {
+			/* It's a passthru request.  Complete it. */
+			if ((req_pkt = req->orig_req) != TW_CL_NULL) {
 				req_pkt->status = TW_CL_ERR_REQ_BUS_RESET;
-				req_pkt->tw_osl_callback(req->req_handle);
+
+				if (req_pkt->tw_osl_callback)
+					req_pkt->tw_osl_callback(req->req_handle);
 			}
 			tw_cli_req_q_insert_tail(req, TW_CLI_FREE_Q);
+		} else {
+			/* It's an external (SCSI) request.  Add it to the reset queue. */
+			tw_osl_untimeout(req->req_handle);
+			tw_cli_req_q_insert_tail(req, TW_CLI_RESET_Q);
 		}
-	}
+	} /* End of while loop */
 }
 
 
@@ -239,9 +247,6 @@ tw_cli_drain_response_queue(struct tw_cli_ctlr_context *ctlr)
 	for (;;) {
 		status_reg = TW_CLI_READ_STATUS_REGISTER(ctlr->ctlr_handle);
 
-		if (tw_cli_check_ctlr_state(ctlr, status_reg))
-			return(TW_OSL_EGENFAILURE);
-
 		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
 			return(TW_OSL_ESUCCESS); /* no more response queue entries */
 
@@ -273,9 +278,6 @@ tw_cli_find_response(struct tw_cli_ctlr_context *ctlr, TW_INT32 req_id)
 	for (;;) {
 		status_reg = TW_CLI_READ_STATUS_REGISTER(ctlr->ctlr_handle);
 
-		if (tw_cli_check_ctlr_state(ctlr, status_reg))
-			return(TW_OSL_EGENFAILURE);
-
 		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
 			return(TW_OSL_ENOTTY); /* no more response queue entries */
 
@@ -356,9 +358,11 @@ tw_cli_drain_aen_queue(struct tw_cli_ctlr_context *ctlr)
 
 		if ((error = req->cmd_pkt->command.cmd_pkt_9k.status)) {
 			cmd_hdr = &req->cmd_pkt->cmd_hdr;
+#if       0
 			tw_cli_create_ctlr_event(ctlr,
 				TW_CL_MESSAGE_SOURCE_CONTROLLER_ERROR,
 				cmd_hdr);
+#endif // 0
 			break;
 		}
 
@@ -714,7 +718,7 @@ tw_cli_check_ctlr_state(struct tw_cli_ctlr_context *ctlr, TW_UINT32 status_reg)
 
 		tw_osl_memzero(desc, 200);
 		if (!(ctlr->reset_phase1_in_progress)) {
-			tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+			tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 				0x1301, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 				"Missing expected status bit(s)",
@@ -738,7 +742,7 @@ tw_cli_check_ctlr_state(struct tw_cli_ctlr_context *ctlr, TW_UINT32 status_reg)
 		     (ctlr->device_id != TW_CL_DEVICE_ID_9K_SA)) ||
 		    (!(ctlr->reset_in_progress)) ||
 		    ((status_reg & TWA_STATUS_QUEUE_ERROR_INTERRUPT) == 0))
-		tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+		tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 			TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 			0x1302, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 			"Unexpected status bit(s)",
@@ -748,7 +752,7 @@ tw_cli_check_ctlr_state(struct tw_cli_ctlr_context *ctlr, TW_UINT32 status_reg)
 				TWA_STATUS_UNEXPECTED_BITS, desc));
 
 		if (status_reg & TWA_STATUS_PCI_PARITY_ERROR_INTERRUPT) {
-			tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+			tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 				0x1303, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 				"PCI parity error: clearing... "
@@ -768,7 +772,7 @@ tw_cli_check_ctlr_state(struct tw_cli_ctlr_context *ctlr, TW_UINT32 status_reg)
 		}
 
 		if (status_reg & TWA_STATUS_PCI_ABORT_INTERRUPT) {
-			tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+			tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 				0x1304, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 				"PCI abort: clearing... ",
@@ -791,7 +795,7 @@ tw_cli_check_ctlr_state(struct tw_cli_ctlr_context *ctlr, TW_UINT32 status_reg)
 			if (((ctlr->device_id != TW_CL_DEVICE_ID_9K_E) &&
 			     (ctlr->device_id != TW_CL_DEVICE_ID_9K_SA)) ||
 			    (!(ctlr->reset_in_progress)))
-				tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
+				tw_cl_create_event(ctlr_handle, TW_CL_FALSE,
 						   TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
 						   0x1305, 0x1, TW_CL_SEVERITY_ERROR_STRING,
 						   "Controller queue error: clearing... ",
@@ -801,17 +805,6 @@ tw_cli_check_ctlr_state(struct tw_cli_ctlr_context *ctlr, TW_UINT32 status_reg)
 			TW_CLI_WRITE_CONTROL_REGISTER(ctlr->ctlr_handle,
 				TWA_CONTROL_CLEAR_QUEUE_ERROR);
 		}
-
-		if (status_reg & TWA_STATUS_MICROCONTROLLER_ERROR) {
-			tw_cl_create_event(ctlr_handle, TW_CL_TRUE,
-				TW_CL_MESSAGE_SOURCE_COMMON_LAYER_EVENT,
-				0x1307, 0x1, TW_CL_SEVERITY_ERROR_STRING,
-				"Micro-controller error! ",
-				"status reg = 0x%x %s",
-				status_reg,
-				tw_cli_describe_bits(status_reg, desc));
-			error = TW_OSL_EGENFAILURE;
-		}
 	}
 	return(error);
 }	
@@ -850,8 +843,6 @@ tw_cli_describe_bits(TW_UINT32 reg, TW_INT8 *str)
 		tw_osl_strcpy(&str[tw_osl_strlen(str)], "HOST_INTR,");
 	if (reg & TWA_STATUS_PCI_ABORT_INTERRUPT)
 		tw_osl_strcpy(&str[tw_osl_strlen(str)], "PCI_ABRT,");
-	if (reg & TWA_STATUS_MICROCONTROLLER_ERROR)
-		tw_osl_strcpy(&str[tw_osl_strlen(str)], "MC_ERR,");
 	if (reg & TWA_STATUS_QUEUE_ERROR_INTERRUPT)
 		tw_osl_strcpy(&str[tw_osl_strlen(str)], "Q_ERR,");
 	if (reg & TWA_STATUS_PCI_PARITY_ERROR_INTERRUPT)
diff --git a/sys/dev/twa/tw_cl_share.h b/sys/dev/twa/tw_cl_share.h
index d9eb788b17a..727684984c5 100644
--- a/sys/dev/twa/tw_cl_share.h
+++ b/sys/dev/twa/tw_cl_share.h
@@ -349,10 +349,14 @@ extern TW_VOID	tw_osl_breakpoint(TW_VOID);
 #endif
 
 
-#ifndef tw_osl_ctlr_busy
-/* Called when CL is too busy to accept new requests. */
-extern TW_VOID	tw_osl_ctlr_busy(struct tw_cl_ctlr_handle *ctlr_handle,
-	struct tw_cl_req_handle *req_handle);
+#ifndef tw_osl_timeout
+/* Start OS timeout() routine after controller reset sequence */
+extern TW_VOID	tw_osl_timeout(struct tw_cl_req_handle *req_handle);
+#endif
+
+#ifndef tw_osl_untimeout
+/* Stop OS timeout() routine during controller reset sequence */
+extern TW_VOID	tw_osl_untimeout(struct tw_cl_req_handle *req_handle);
 #endif
 
 
@@ -552,6 +556,10 @@ extern TW_INT32	tw_cl_init_ctlr(struct tw_cl_ctlr_handle *ctlr_handle,
 	);
 
 
+extern TW_VOID  tw_cl_set_reset_needed(struct tw_cl_ctlr_handle *ctlr_handle);
+extern TW_INT32 tw_cl_is_reset_needed(struct tw_cl_ctlr_handle *ctlr_handle);
+extern TW_INT32 tw_cl_is_active(struct tw_cl_ctlr_handle *ctlr_handle);
+
 /* CL's interrupt handler. */
 extern TW_INT32	tw_cl_interrupt(struct tw_cl_ctlr_handle *ctlr_handle);
 
diff --git a/sys/dev/twa/tw_osl.h b/sys/dev/twa/tw_osl.h
index bce9958987b..1cc40fb1f03 100644
--- a/sys/dev/twa/tw_osl.h
+++ b/sys/dev/twa/tw_osl.h
@@ -77,6 +77,7 @@
 						EINPROGRESS */
 #define TW_OSLI_REQ_FLAGS_PASSTHRU	(1<<5)	/* pass through request */
 #define TW_OSLI_REQ_FLAGS_SLEEPING	(1<<6)	/* owner sleeping on this cmd */
+#define TW_OSLI_REQ_FLAGS_FAILED	(1<<7)	/* bus_dmamap_load() failed */
 
 
 #ifdef TW_OSL_DEBUG
@@ -100,6 +101,7 @@ struct tw_osli_req_context {
 	struct twa_softc	*ctlr;	/* ptr to OSL's controller context */
 	TW_VOID			*data;	/* ptr to data being passed to CL */
 	TW_UINT32		length;	/* length of buf being passed to CL */
+	TW_UINT64		deadline;/* request timeout (in absolute time) */
 
 	/*
 	 * ptr to, and length of data passed to us from above, in case a buffer
@@ -151,6 +153,9 @@ struct twa_softc {
 	struct mtx		sim_lock_handle;/* sim lock shared with cam */
 	struct mtx		*sim_lock;/* ptr to sim lock */
 
+	struct callout		watchdog_callout[2]; /* For command timout */
+	TW_UINT32		watchdog_index;
+
 #ifdef TW_OSL_DEBUG
 	struct tw_osli_q_stats	q_stats[TW_OSLI_Q_COUNT];/* queue statistics */
 #endif /* TW_OSL_DEBUG */
diff --git a/sys/dev/twa/tw_osl_cam.c b/sys/dev/twa/tw_osl_cam.c
index 5854fd6c727..8b81ccca4f0 100644
--- a/sys/dev/twa/tw_osl_cam.c
+++ b/sys/dev/twa/tw_osl_cam.c
@@ -55,7 +55,6 @@
 
 static TW_VOID	twa_action(struct cam_sim *sim, union ccb *ccb);
 static TW_VOID	twa_poll(struct cam_sim *sim);
-static TW_VOID	twa_timeout(TW_VOID *arg);
 
 static TW_INT32	tw_osli_execute_scsi(struct tw_osli_req_context *req,
 	union ccb *ccb);
@@ -81,7 +80,7 @@ tw_osli_cam_attach(struct twa_softc *sc)
 	/*
 	 * Create the device queue for our SIM.
 	 */
-	if ((devq = cam_simq_alloc(TW_OSLI_MAX_NUM_REQUESTS)) == NULL) {
+	if ((devq = cam_simq_alloc(TW_OSLI_MAX_NUM_IOS)) == NULL) {
 		tw_osli_printf(sc, "error = %d",
 			TW_CL_SEVERITY_ERROR_STRING,
 			TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
@@ -275,6 +274,7 @@ tw_osli_execute_scsi(struct tw_osli_req_context *req, union ccb *ccb)
 					"I/O size too big",
 					csio->dxfer_len);
 				ccb_h->status = CAM_REQ_TOO_BIG;
+				ccb_h->status &= ~CAM_SIM_QUEUED;
 				xpt_done(ccb);
 				return(1);
 			}
@@ -290,6 +290,7 @@ tw_osli_execute_scsi(struct tw_osli_req_context *req, union ccb *ccb)
 				0x2107,
 				"XPT_SCSI_IO: Got SGList");
 			ccb_h->status = CAM_REQ_INVALID;
+			ccb_h->status &= ~CAM_SIM_QUEUED;
 			xpt_done(ccb);
 			return(1);
 		}
@@ -306,13 +307,20 @@ tw_osli_execute_scsi(struct tw_osli_req_context *req, union ccb *ccb)
 		return(1);
 	}
 
-	ccb_h->timeout_ch = timeout(twa_timeout, req,
-		(ccb_h->timeout * hz) / 1000);
+	req->deadline = tw_osl_get_local_time() + (ccb_h->timeout / 1000);
+
+
 	/*
 	 * twa_map_load_data_callback will fill in the SGL,
 	 * and submit the I/O.
 	 */
 	error = tw_osli_map_request(req);
+	if ((error) && (req->flags & TW_OSLI_REQ_FLAGS_FAILED)) {
+		req->deadline = 0;
+		ccb_h->status = CAM_REQ_CMP_ERR;
+		ccb_h->status &= ~CAM_SIM_QUEUED;
+		xpt_done(ccb);
+	}
 	return(error);
 }
 
@@ -345,10 +353,20 @@ twa_action(struct cam_sim *sim, union ccb *ccb)
 			 * Freeze the simq to maintain ccb ordering.  The next
 			 * ccb that gets completed will unfreeze the simq.
 			 */
+			ccb_h->status &= ~CAM_SIM_QUEUED;
 			ccb_h->status |= CAM_REQUEUE_REQ;
 			xpt_done(ccb);
 			break;
 		}
+
+		if ((tw_cl_is_reset_needed(&(req->ctlr->ctlr_handle)))) {
+			ccb_h->status &= ~CAM_SIM_QUEUED;
+			ccb_h->status |= CAM_REQUEUE_REQ;
+			xpt_done(ccb);
+			tw_osli_req_q_insert_tail(req, TW_OSLI_FREE_Q);
+			break;
+		}
+
 		req->req_handle.osl_req_ctxt = req;
 		req->req_handle.is_io = TW_CL_TRUE;
 		req->orig_req = ccb;
@@ -364,25 +382,14 @@ twa_action(struct cam_sim *sim, union ccb *ccb)
 		break;
 
 	case XPT_RESET_BUS:
-		tw_cl_create_event(&(sc->ctlr_handle), TW_CL_TRUE,
+		tw_cl_create_event(&(sc->ctlr_handle), TW_CL_FALSE,
 			TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
 			0x2108, 0x3, TW_CL_SEVERITY_INFO_STRING,
 			"Received Reset Bus request from CAM",
 			" ");
 
-		mtx_unlock(sc->sim_lock);
-		if (tw_cl_reset_ctlr(&sc->ctlr_handle)) {
-			tw_cl_create_event(&(sc->ctlr_handle), TW_CL_TRUE,
-				TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
-				0x2109, 0x1, TW_CL_SEVERITY_ERROR_STRING,
-				"Failed to reset bus",
-				" ");
-			ccb_h->status = CAM_REQ_CMP_ERR;
-		}
-		else
-			ccb_h->status = CAM_REQ_CMP;
-
-		mtx_lock(sc->sim_lock);
+		tw_cl_set_reset_needed(&(sc->ctlr_handle));
+		ccb_h->status = CAM_REQ_CMP;
 		xpt_done(ccb);
 		break;
 
@@ -450,6 +457,7 @@ twa_action(struct cam_sim *sim, union ccb *ccb)
                 path_inq->transport_version = 2;
                 path_inq->protocol = PROTO_SCSI;
                 path_inq->protocol_version = SCSI_REV_2;
+                path_inq->maxio = TW_CL_MAX_IO_SIZE;
 		ccb_h->status = CAM_REQ_CMP;
 		xpt_done(ccb);
 		break;
@@ -486,31 +494,6 @@ twa_poll(struct cam_sim *sim)
 
 
 
-/*
- * Function name:	twa_timeout
- * Description:		Driver entry point for being alerted on a request
- *			timing out.
- *
- * Input:		arg	-- ptr to timed out request
- * Output:		None
- * Return value:	None
- */
-static TW_VOID
-twa_timeout(TW_VOID *arg)
-{
-	struct tw_osli_req_context	*req =
-		(struct tw_osli_req_context *)arg;
-
-	tw_cl_create_event(&(req->ctlr->ctlr_handle), TW_CL_TRUE,
-		TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
-		0x210B, 0x1, TW_CL_SEVERITY_ERROR_STRING,
-		"Request timed out!",
-		"request = %p", req);
-	tw_cl_reset_ctlr(&(req->ctlr->ctlr_handle));
-}
-
-
-
 /*
  * Function name:	tw_osli_request_bus_scan
  * Description:		Requests CAM for a scan of the bus.
@@ -574,20 +557,39 @@ tw_osli_disallow_new_requests(struct twa_softc *sc,
 
 
 /*
- * Function name:	tw_osl_ctlr_busy
- * Description:		CL calls this function on cmd queue full or otherwise,
- *			when it is too busy to accept new requests.
+ * Function name:	tw_osl_timeout
+ * Description:		Call to timeout().
  *
- * Input:		ctlr_handle	-- ptr to controller handle
- *			req_handle	-- ptr to request handle sent by OSL.
+ * Input:		req_handle -- ptr to request handle sent by OSL.
  * Output:		None
  * Return value:	None
  */
 TW_VOID
-tw_osl_ctlr_busy(struct tw_cl_ctlr_handle *ctlr_handle,
-	struct tw_cl_req_handle *req_handle)
+tw_osl_timeout(struct tw_cl_req_handle *req_handle)
 {
-	tw_osli_disallow_new_requests(ctlr_handle->osl_ctlr_ctxt, req_handle);
+	struct tw_osli_req_context	*req = req_handle->osl_req_ctxt;
+	union ccb			*ccb = (union ccb *)(req->orig_req);
+	struct ccb_hdr			*ccb_h = &(ccb->ccb_h);
+
+	req->deadline = tw_osl_get_local_time() + (ccb_h->timeout / 1000);
+}
+
+
+
+/*
+ * Function name:	tw_osl_untimeout
+ * Description:		Inverse of call to timeout().
+ *
+ * Input:		req_handle -- ptr to request handle sent by OSL.
+ * Output:		None
+ * Return value:	None
+ */
+TW_VOID
+tw_osl_untimeout(struct tw_cl_req_handle *req_handle)
+{
+	struct tw_osli_req_context	*req = req_handle->osl_req_ctxt;
+
+	req->deadline = 0;
 }
 
 
@@ -655,7 +657,7 @@ tw_osl_complete_io(struct tw_cl_req_handle *req_handle)
 
 	tw_osli_unmap_request(req);
 
-	untimeout(twa_timeout, req, ccb->ccb_h.timeout_ch);
+	req->deadline = 0;
 	if (req->error_code) {
 		/* This request never got submitted to the firmware. */
 		if (req->error_code == EBUSY) {
@@ -682,7 +684,7 @@ tw_osl_complete_io(struct tw_cl_req_handle *req_handle)
 			else if (req_pkt->status & TW_CL_ERR_REQ_SCSI_ERROR)
 				ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
 			else if (req_pkt->status & TW_CL_ERR_REQ_BUS_RESET)
-				ccb->ccb_h.status |= CAM_SCSI_BUS_RESET;
+				ccb->ccb_h.status |= (CAM_REQUEUE_REQ | CAM_SCSI_BUS_RESET);
 			/*
 			 * If none of the above errors occurred, simply
 			 * mark completion error.
diff --git a/sys/dev/twa/tw_osl_freebsd.c b/sys/dev/twa/tw_osl_freebsd.c
index 09bb55ee2db..5cb25bd9847 100644
--- a/sys/dev/twa/tw_osl_freebsd.c
+++ b/sys/dev/twa/tw_osl_freebsd.c
@@ -175,6 +175,9 @@ static TW_INT32	twa_detach(device_t dev);
 static TW_INT32	twa_shutdown(device_t dev);
 static TW_VOID	twa_busdma_lock(TW_VOID *lock_arg, bus_dma_lock_op_t op);
 static TW_VOID	twa_pci_intr(TW_VOID *arg);
+static TW_VOID	twa_watchdog(TW_VOID *arg);
+int twa_setup_intr(struct twa_softc *sc);
+int twa_teardown_intr(struct twa_softc *sc);
 
 static TW_INT32	tw_osli_alloc_mem(struct twa_softc *sc);
 static TW_VOID	tw_osli_free_resources(struct twa_softc *sc);
@@ -238,6 +241,32 @@ twa_probe(device_t dev)
 	return(ENXIO);
 }
 
+int twa_setup_intr(struct twa_softc *sc)
+{
+	int error = 0;
+
+	if (!(sc->intr_handle) && (sc->irq_res)) {
+		error = bus_setup_intr(sc->bus_dev, sc->irq_res,
+					INTR_TYPE_CAM | INTR_MPSAFE,
+					NULL, twa_pci_intr,
+					sc, &sc->intr_handle);
+	}
+	return( error );
+}
+
+
+int twa_teardown_intr(struct twa_softc *sc)
+{
+	int error = 0;
+
+	if ((sc->intr_handle) && (sc->irq_res)) {
+		error = bus_teardown_intr(sc->bus_dev,
+						sc->irq_res, sc->intr_handle);
+		sc->intr_handle = NULL;
+	}
+	return( error );
+}
+
 
 
 /*
@@ -354,10 +383,7 @@ twa_attach(device_t dev)
 		tw_osli_free_resources(sc);
 		return(ENXIO);
 	}
-	if ((error = bus_setup_intr(sc->bus_dev, sc->irq_res,
-			INTR_TYPE_CAM | INTR_MPSAFE,
-			NULL, twa_pci_intr,	    
-			sc, &sc->intr_handle))) {
+	if ((error = twa_setup_intr(sc))) {
 		tw_osli_printf(sc, "error = %d",
 			TW_CL_SEVERITY_ERROR_STRING,
 			TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
@@ -412,10 +438,77 @@ twa_attach(device_t dev)
 		return(error);
 	}
 
+	sc->watchdog_index = 0;
+	callout_init(&(sc->watchdog_callout[0]), CALLOUT_MPSAFE);
+	callout_init(&(sc->watchdog_callout[1]), CALLOUT_MPSAFE);
+	callout_reset(&(sc->watchdog_callout[0]), 5*hz, twa_watchdog, &sc->ctlr_handle);
+
 	return(0);
 }
 
 
+static TW_VOID
+twa_watchdog(TW_VOID *arg)
+{
+	struct tw_cl_ctlr_handle *ctlr_handle =
+		(struct tw_cl_ctlr_handle *)arg;
+	struct twa_softc		*sc = ctlr_handle->osl_ctlr_ctxt;
+	int				i;
+	int				i_need_a_reset = 0;
+	int				driver_is_active = 0;
+	int				my_watchdog_was_pending = 1234;
+	TW_UINT64			current_time;
+	struct tw_osli_req_context	*my_req;
+
+
+//==============================================================================
+	current_time = (TW_UINT64) (tw_osl_get_local_time());
+
+	for (i = 0; i < TW_OSLI_MAX_NUM_REQUESTS; i++) {
+		my_req = &(sc->req_ctx_buf[i]);
+
+		if ((my_req->state == TW_OSLI_REQ_STATE_BUSY) &&
+			(my_req->deadline) &&
+			(my_req->deadline < current_time)) {
+			tw_cl_set_reset_needed(ctlr_handle);
+#ifdef    TW_OSL_DEBUG
+			device_printf((sc)->bus_dev, "Request %d timed out! d = %p, c = %p\n", i, (void*)my_req->deadline, (void*)current_time);
+#else  /* TW_OSL_DEBUG */
+			device_printf((sc)->bus_dev, "Request %d timed out!\n", i);
+#endif /* TW_OSL_DEBUG */
+			break;
+		}
+	}
+//==============================================================================
+
+	i_need_a_reset = tw_cl_is_reset_needed(ctlr_handle);
+
+	i = (int) ((sc->watchdog_index++) & 1);
+
+	driver_is_active = tw_cl_is_active(ctlr_handle);
+
+	if (i_need_a_reset) {
+#ifdef    TW_OSL_DEBUG
+		device_printf((sc)->bus_dev, "Watchdog rescheduled in 70 seconds\n");
+#endif /* TW_OSL_DEBUG */
+		my_watchdog_was_pending =
+			callout_reset(&(sc->watchdog_callout[i]), 70*hz, twa_watchdog, &sc->ctlr_handle);
+		tw_cl_reset_ctlr(ctlr_handle);
+#ifdef    TW_OSL_DEBUG
+		device_printf((sc)->bus_dev, "Watchdog reset completed!\n");
+#endif /* TW_OSL_DEBUG */
+	} else if (driver_is_active) {
+		my_watchdog_was_pending =
+			callout_reset(&(sc->watchdog_callout[i]),  5*hz, twa_watchdog, &sc->ctlr_handle);
+	}
+#ifdef    TW_OSL_DEBUG
+	if (i_need_a_reset || my_watchdog_was_pending)
+		device_printf((sc)->bus_dev, "i_need_a_reset = %d, "
+		"driver_is_active = %d, my_watchdog_was_pending = %d\n",
+		i_need_a_reset, driver_is_active, my_watchdog_was_pending);
+#endif /* TW_OSL_DEBUG */
+}
+
 
 /*
  * Function name:	tw_osli_alloc_mem
@@ -715,9 +808,7 @@ tw_osli_free_resources(struct twa_softc *sc)
 
 
 	/* Disconnect the interrupt handler. */
-	if (sc->intr_handle)
-		if ((error = bus_teardown_intr(sc->bus_dev,
-				sc->irq_res, sc->intr_handle)))
+	if ((error = twa_teardown_intr(sc)))
 			tw_osli_dbg_dprintf(1, sc,
 				"teardown_intr returned %d", error);
 
@@ -809,6 +900,9 @@ twa_shutdown(device_t dev)
 
 	tw_osli_dbg_dprintf(3, sc, "entered");
 
+	/* Disconnect interrupts. */
+	error = twa_teardown_intr(sc);
+
 	/* Disconnect from the controller. */
 	if ((error = tw_cl_shutdown_ctlr(&(sc->ctlr_handle), 0))) {
 		tw_osli_printf(sc, "error = %d",
@@ -997,33 +1091,35 @@ tw_osli_fw_passthru(struct twa_softc *sc, TW_INT8 *buf)
 				error = 0; /* False error */
 				break;
 			}
-			tw_osli_printf(sc, "request = %p",
-				TW_CL_SEVERITY_ERROR_STRING,
-				TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
-				0x2018,
-				"Passthru request timed out!",
-				req);
-			/*
-			 * Should I check here if the timeout happened
-			 * because of yet another reset, and not do a
-			 * second reset?
-			 */
-			tw_cl_reset_ctlr(&sc->ctlr_handle);
+			if (!(tw_cl_is_reset_needed(&(req->ctlr->ctlr_handle)))) {
+#ifdef    TW_OSL_DEBUG
+				tw_osli_printf(sc, "request = %p",
+					TW_CL_SEVERITY_ERROR_STRING,
+					TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
+					0x2018,
+					"Passthru request timed out!",
+					req);
+#else  /* TW_OSL_DEBUG */
+			device_printf((sc)->bus_dev, "Passthru request timed out!\n");
+#endif /* TW_OSL_DEBUG */
+				tw_cl_reset_ctlr(&(req->ctlr->ctlr_handle));
+			}
+
+			error = 0;
+			end_time = tw_osl_get_local_time() + timeout;
+			continue;
 			/*
 			 * Don't touch req after a reset.  It (and any
-			 * associated data) will already have been
+			 * associated data) will be
 			 * unmapped by the callback.
 			 */
-			user_buf->driver_pkt.os_status = error;
-			error = ETIMEDOUT;
-			goto fw_passthru_err;
 		}
 		/* 
 		 * Either the request got completed, or we were woken up by a
 		 * signal.  Calculate the new timeout, in case it was the latter.
 		 */
 		timeout = (end_time - tw_osl_get_local_time());
-	}
+	} /* End of while loop */
 
 	/* If there was a payload, copy it back. */
 	if ((!error) && (req->length))
@@ -1037,19 +1133,9 @@ tw_osli_fw_passthru(struct twa_softc *sc, TW_INT8 *buf)
 				error);
 	
 fw_passthru_err:
-	/*
-	 * Print the failure message.  For some reason, on certain OS versions,
-	 * printing this error message during reset hangs the display (although
-	 * the rest of the system is running fine.  So, don't print it if the
-	 * failure was due to a reset.
-	 */
-	if ((error) && (error != TW_CL_ERR_REQ_BUS_RESET))
-		tw_osli_printf(sc, "error = %d",		
-			TW_CL_SEVERITY_ERROR_STRING,
-			TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
-			0x201A,
-			"Firmware passthru failed!",
-			error);
+
+	if (req_pkt->status == TW_CL_ERR_REQ_BUS_RESET)
+		error = EBUSY;
 
 	user_buf->driver_pkt.os_status = error;
 	/* Free resources. */
@@ -1073,6 +1159,8 @@ TW_VOID
 tw_osl_complete_passthru(struct tw_cl_req_handle *req_handle)
 {
 	struct tw_osli_req_context	*req = req_handle->osl_req_ctxt;
+	struct tw_cl_req_packet		*req_pkt =
+		(struct tw_cl_req_packet *)(&req->req_pkt);
 	struct twa_softc		*sc = req->ctlr;
 
 	tw_osli_dbg_dprintf(5, sc, "entered");
@@ -1120,6 +1208,9 @@ tw_osl_complete_passthru(struct tw_cl_req_handle *req_handle)
 			if (req->flags & TW_OSLI_REQ_FLAGS_MAPPED)
 				return;
 
+			if (req_pkt->status == TW_CL_ERR_REQ_BUS_RESET)
+				return;
+
 			tw_osli_printf(sc, "request = %p",
 				TW_CL_SEVERITY_ERROR_STRING,
 				TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
@@ -1166,6 +1257,7 @@ tw_osli_get_request(struct twa_softc *sc)
 		req->req_handle.is_io = 0;
 		req->data = NULL;
 		req->length = 0;
+		req->deadline = 0;
 		req->real_data = NULL;
 		req->real_length = 0;
 		req->state = TW_OSLI_REQ_STATE_INIT;/* req being initialized */
@@ -1207,6 +1299,11 @@ twa_map_load_data_callback(TW_VOID *arg, bus_dma_segment_t *segs,
 
 	tw_osli_dbg_dprintf(10, sc, "entered");
 
+	if (error == EINVAL) {
+		req->error_code = error;
+		return;
+	}
+
 	/* Mark the request as currently being processed. */
 	req->state = TW_OSLI_REQ_STATE_BUSY;
 	/* Move the request into the busy queue. */
@@ -1400,6 +1497,14 @@ tw_osli_map_request(struct tw_osli_req_context *req)
 				mtx_unlock_spin(sc->io_lock);
 				error = 0;
 			} else {
+				tw_osli_printf(sc, "error = %d",
+					TW_CL_SEVERITY_ERROR_STRING,
+					TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
+					0x9999,
+					"Failed to map DMA memory "
+					"for I/O request",
+					error);
+				req->flags |= TW_OSLI_REQ_FLAGS_FAILED;
 				/* Free alignment buffer if it was used. */
 				if (req->flags &
 					TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED) {
diff --git a/sys/dev/twa/tw_osl_share.h b/sys/dev/twa/tw_osl_share.h
index 4d10ed46c1b..c17d8cc28b5 100644
--- a/sys/dev/twa/tw_osl_share.h
+++ b/sys/dev/twa/tw_osl_share.h
@@ -75,7 +75,7 @@
 #define TW_OSL_ENCLOSURE_SUPPORT
 #endif
 
-#define TW_OSL_DRIVER_VERSION_STRING	"3.80.06.002"
+#define TW_OSL_DRIVER_VERSION_STRING	"3.80.06.003"
 
 #define	TW_OSL_CAN_SLEEP
 

From 67d640fc214bc61fd2d6d2a621ba32e2e053b214 Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Mon, 30 Aug 2010 21:18:59 +0000
Subject: [PATCH 0366/1624] Add myself to committers-src.dot.

Approved by:	rpaulo (mentor)
---
 share/misc/committers-src.dot | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/share/misc/committers-src.dot b/share/misc/committers-src.dot
index 1708a1fa59b..27e0050fb01 100644
--- a/share/misc/committers-src.dot
+++ b/share/misc/committers-src.dot
@@ -85,6 +85,7 @@ delphij [label="Xin Li\ndelphij@FreeBSD.org\n2004/09/14"]
 des [label="Dag-Erling Smorgrav\ndes@FreeBSD.org\n1998/04/03"]
 dg [label="David Greenman\ndg@FreeBSD.org\n1993/06/14"]
 dhartmei [label="Daniel Hartmeier\ndhartmei@FreeBSD.org\n2004/04/06"]
+dim [label="Dimitry Andric\ndim@FreeBSD.org\n2010/08/30"]
 dmlb [label="Duncan Barclay\ndmlb@FreeBSD.org\n2001/12/14"]
 dwmalone [label="David Malone\ndwmalone@FreeBSD.org\n2000/07/11"]
 ed [label="Ed Schouten\ned@FreeBSD.org\n2008/05/22"]
@@ -271,6 +272,7 @@ dwmalone -> fanf
 dwmalone -> peadar
 dwmalone -> snb
 
+ed -> dim
 ed -> gavin
 ed -> jilles
 ed -> rdivacky
@@ -430,6 +432,7 @@ rgrimes -> markm
 
 rpaulo -> avg
 rpaulo -> bschmidt
+rpaulo -> dim
 
 rrs -> brucec
 rrs -> jchandra

From 305c5c0acb8edd986d02d4d287785d5052a736dd Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Mon, 30 Aug 2010 21:19:42 +0000
Subject: [PATCH 0367/1624] Save MSR_FSBASE, MSR_GSBASE and MSR_KGSBASE
 directly to PCB as we do not use these values in the function.

---
 sys/amd64/amd64/cpu_switch.S | 15 ++++++---------
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/sys/amd64/amd64/cpu_switch.S b/sys/amd64/amd64/cpu_switch.S
index b2948646205..952a70b87ab 100644
--- a/sys/amd64/amd64/cpu_switch.S
+++ b/sys/amd64/amd64/cpu_switch.S
@@ -338,19 +338,16 @@ ENTRY(savectx)
 
 	movl	$MSR_FSBASE,%ecx
 	rdmsr
-	shlq	$32,%rdx
-	leaq	(%rax,%rdx),%rax
-	movq	%rax,PCB_FSBASE(%rdi)
+	movl	%eax,PCB_FSBASE(%rdi)
+	movl	%edx,PCB_FSBASE+4(%rdi)
 	movl	$MSR_GSBASE,%ecx
 	rdmsr
-	shlq	$32,%rdx
-	leaq	(%rax,%rdx),%rax
-	movq	%rax,PCB_GSBASE(%rdi)
+	movl	%eax,PCB_GSBASE(%rdi)
+	movl	%edx,PCB_GSBASE+4(%rdi)
 	movl	$MSR_KGSBASE,%ecx
 	rdmsr
-	shlq	$32,%rdx
-	leaq	(%rax,%rdx),%rax
-	movq	%rax,PCB_KGSBASE(%rdi)
+	movl	%eax,PCB_KGSBASE(%rdi)
+	movl	%edx,PCB_KGSBASE+4(%rdi)
 
 	sgdt	PCB_GDT(%rdi)
 	sidt	PCB_IDT(%rdi)

From a4703857ff47b53af55a43534cb76abd7235d760 Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Mon, 30 Aug 2010 21:20:24 +0000
Subject: [PATCH 0368/1624] Add myself to calendars.freebsd.

Approved by:	rpaulo (mentor)
---
 usr.bin/calendar/calendars/calendar.freebsd | 1 +
 1 file changed, 1 insertion(+)

diff --git a/usr.bin/calendar/calendars/calendar.freebsd b/usr.bin/calendar/calendars/calendar.freebsd
index 273be1645cc..d1992399f89 100644
--- a/usr.bin/calendar/calendars/calendar.freebsd
+++ b/usr.bin/calendar/calendars/calendar.freebsd
@@ -8,6 +8,7 @@
 #define _calendar_freebsd_
 
 01/01	Alexander Langer  born in Duesseldorf, Nordrhein-Westfalen, Germany, 1981
+01/01	Dimitry Andric  born in Utrecht, the Netherlands, 1969
 01/02	Ion-Mihai "IOnut" Tetcu  born in Bucharest, Romania, 1980
 01/02	Patrick Li  born in Beijing, People's Republic of China, 1985
 01/03	Tetsurou Okazaki  born in Mobara, Chiba, Japan, 1972

From 08390ba4c9709314bb37c26806e2520a96b790bb Mon Sep 17 00:00:00 2001
From: Xin LI 
Date: Mon, 30 Aug 2010 21:33:33 +0000
Subject: [PATCH 0369/1624] Drain watchdog callouts before detaching.  This
 prevents a panic while unloading the kernel module.

Submitted by:	Tom Cough
---
 sys/dev/twa/tw_osl_freebsd.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/sys/dev/twa/tw_osl_freebsd.c b/sys/dev/twa/tw_osl_freebsd.c
index 5cb25bd9847..3b7b426a628 100644
--- a/sys/dev/twa/tw_osl_freebsd.c
+++ b/sys/dev/twa/tw_osl_freebsd.c
@@ -903,6 +903,10 @@ twa_shutdown(device_t dev)
 	/* Disconnect interrupts. */
 	error = twa_teardown_intr(sc);
 
+	/* Stop watchdog task. */
+	callout_drain(&(sc->watchdog_callout[0]));
+	callout_drain(&(sc->watchdog_callout[1]));
+
 	/* Disconnect from the controller. */
 	if ((error = tw_cl_shutdown_ctlr(&(sc->ctlr_handle), 0))) {
 		tw_osli_printf(sc, "error = %d",

From 89513bce113664394f9bebd3f214d820972a5a28 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Mon, 30 Aug 2010 21:58:52 +0000
Subject: [PATCH 0370/1624] Use MACHINE_ARCH instead of MACHINE as the
 directory to fetch packages from. Packages are architecture dependent, not
 machine dependent.

---
 usr.sbin/pkg_install/add/main.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/usr.sbin/pkg_install/add/main.c b/usr.sbin/pkg_install/add/main.c
index 762b61a442e..c8339db0b14 100644
--- a/usr.sbin/pkg_install/add/main.c
+++ b/usr.sbin/pkg_install/add/main.c
@@ -22,7 +22,7 @@
 __FBSDID("$FreeBSD$");
 
 #include 
-#include 
+#include 
 #include 
 #include 
 
@@ -301,7 +301,9 @@ getpackagesite(void)
 {
     int reldate, i;
     static char sitepath[MAXPATHLEN];
-    struct utsname u;
+    int archmib[] = { CTL_HW, HW_MACHINE_ARCH };
+    char arch[64];
+    size_t archlen = sizeof(arch);
 
     if (getenv("PACKAGESITE")) {
 	if (strlcpy(sitepath, getenv("PACKAGESITE"), sizeof(sitepath))
@@ -324,8 +326,10 @@ getpackagesite(void)
 	>= sizeof(sitepath))
 	return NULL;
 
-    uname(&u);
-    if (strlcat(sitepath, u.machine, sizeof(sitepath)) >= sizeof(sitepath))
+    if (sysctl(archmib, 2, arch, &archlen, NULL, 0) == -1)
+	return NULL;
+    arch[archlen-1] = 0;
+    if (strlcat(sitepath, arch, sizeof(sitepath)) >= sizeof(sitepath))
 	return NULL;
 
     reldate = getosreldate();

From 746b67cdfab321e3f13565cb6e3e2b7931367e22 Mon Sep 17 00:00:00 2001
From: Edwin Groothuis 
Date: Mon, 30 Aug 2010 22:24:26 +0000
Subject: [PATCH 0371/1624] Use basename(3) to determine the name of the
 program.

Submitted by:	Alexander Best 
---
 usr.bin/ncal/ncal.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/usr.bin/ncal/ncal.c b/usr.bin/ncal/ncal.c
index 5ab9a21c0d8..44e31fec1db 100644
--- a/usr.bin/ncal/ncal.c
+++ b/usr.bin/ncal/ncal.c
@@ -33,6 +33,7 @@ static const char rcsid[] =
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -245,9 +246,7 @@ main(int argc, char *argv[])
 	 * Get the filename portion of argv[0] and set flag_backward if
 	 * this program is called "cal".
 	 */
-	cp = strrchr(argv[0], '/');
-	cp = (cp == NULL) ? argv[0] : cp + 1;
-	if (strcmp("cal", cp) == 0)
+	if (strncmp(basename(argv[0]), "cal", strlen("cal")) == 0)
 		flag_backward = 1;
 
 	/* Set the switch date to United Kingdom if backwards compatible */

From b938cdcc9bff515f661579c36db9552821e4562f Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 22:26:42 +0000
Subject: [PATCH 0372/1624] Constify arguments we can constify.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hast_proto.c | 30 ++++++++++++++++--------------
 sbin/hastd/hast_proto.h | 10 +++++-----
 sbin/hastd/proto.c      |  4 ++--
 sbin/hastd/proto.h      |  4 ++--
 4 files changed, 25 insertions(+), 23 deletions(-)

diff --git a/sbin/hastd/hast_proto.c b/sbin/hastd/hast_proto.c
index 4e898ca12e0..101a508cc86 100644
--- a/sbin/hastd/hast_proto.c
+++ b/sbin/hastd/hast_proto.c
@@ -56,8 +56,10 @@ struct hast_main_header {
 	uint32_t	size;
 } __packed;
 
-typedef int hps_send_t(struct hast_resource *, struct nv *nv, void **, size_t *, bool *);
-typedef int hps_recv_t(struct hast_resource *, struct nv *nv, void **, size_t *, bool *);
+typedef int hps_send_t(const struct hast_resource *, struct nv *nv, void **,
+    size_t *, bool *);
+typedef int hps_recv_t(const struct hast_resource *, struct nv *nv, void **,
+    size_t *, bool *);
 
 struct hast_pipe_stage {
 	const char	*hps_name;
@@ -65,14 +67,14 @@ struct hast_pipe_stage {
 	hps_recv_t	*hps_recv;
 };
 
-static int compression_send(struct hast_resource *res, struct nv *nv,
+static int compression_send(const struct hast_resource *res, struct nv *nv,
     void **datap, size_t *sizep, bool *freedatap);
-static int compression_recv(struct hast_resource *res, struct nv *nv,
+static int compression_recv(const struct hast_resource *res, struct nv *nv,
     void **datap, size_t *sizep, bool *freedatap);
 #ifdef HAVE_CRYPTO
-static int checksum_send(struct hast_resource *res, struct nv *nv,
+static int checksum_send(const struct hast_resource *res, struct nv *nv,
     void **datap, size_t *sizep, bool *freedatap);
-static int checksum_recv(struct hast_resource *res, struct nv *nv,
+static int checksum_recv(const struct hast_resource *res, struct nv *nv,
     void **datap, size_t *sizep, bool *freedatap);
 #endif
 
@@ -84,7 +86,7 @@ static struct hast_pipe_stage pipeline[] = {
 };
 
 static int
-compression_send(struct hast_resource *res, struct nv *nv, void **datap,
+compression_send(const struct hast_resource *res, struct nv *nv, void **datap,
     size_t *sizep, bool *freedatap)
 {
 	unsigned char *newbuf;
@@ -132,7 +134,7 @@ compression_send(struct hast_resource *res, struct nv *nv, void **datap,
 }
 
 static int
-compression_recv(struct hast_resource *res, struct nv *nv, void **datap,
+compression_recv(const struct hast_resource *res, struct nv *nv, void **datap,
     size_t *sizep, bool *freedatap)
 {
 	unsigned char *newbuf;
@@ -169,7 +171,7 @@ compression_recv(struct hast_resource *res, struct nv *nv, void **datap,
 
 #ifdef HAVE_CRYPTO
 static int
-checksum_send(struct hast_resource *res, struct nv *nv, void **datap,
+checksum_send(const struct hast_resource *res, struct nv *nv, void **datap,
     size_t *sizep, bool *freedatap __unused)
 {
 	unsigned char hash[SHA256_DIGEST_LENGTH];
@@ -188,7 +190,7 @@ checksum_send(struct hast_resource *res, struct nv *nv, void **datap,
 }
 
 static int
-checksum_recv(struct hast_resource *res, struct nv *nv, void **datap,
+checksum_recv(const struct hast_resource *res, struct nv *nv, void **datap,
     size_t *sizep, bool *freedatap __unused)
 {
 	unsigned char chash[SHA256_DIGEST_LENGTH];
@@ -236,7 +238,7 @@ checksum_recv(struct hast_resource *res, struct nv *nv, void **datap,
  * There can be no data at all (data is NULL then).
  */
 int
-hast_proto_send(struct hast_resource *res, struct proto_conn *conn,
+hast_proto_send(const struct hast_resource *res, struct proto_conn *conn,
     struct nv *nv, const void *data, size_t size)
 {
 	struct hast_main_header hdr;
@@ -293,7 +295,7 @@ end:
 }
 
 int
-hast_proto_recv_hdr(struct proto_conn *conn, struct nv **nvp)
+hast_proto_recv_hdr(const struct proto_conn *conn, struct nv **nvp)
 {
 	struct hast_main_header hdr;
 	struct nv *nv;
@@ -335,7 +337,7 @@ fail:
 }
 
 int
-hast_proto_recv_data(struct hast_resource *res, struct proto_conn *conn,
+hast_proto_recv_data(const struct hast_resource *res, struct proto_conn *conn,
     struct nv *nv, void *data, size_t size)
 {
 	unsigned int ii;
@@ -384,7 +386,7 @@ if (ret < 0) printf("%s:%u %s\n", __func__, __LINE__, strerror(errno));
 }
 
 int
-hast_proto_recv(struct hast_resource *res, struct proto_conn *conn,
+hast_proto_recv(const struct hast_resource *res, struct proto_conn *conn,
     struct nv **nvp, void *data, size_t size)
 {
 	struct nv *nv;
diff --git a/sbin/hastd/hast_proto.h b/sbin/hastd/hast_proto.h
index 3894e383808..b48c3ca1214 100644
--- a/sbin/hastd/hast_proto.h
+++ b/sbin/hastd/hast_proto.h
@@ -37,12 +37,12 @@
 #include 
 #include 
 
-int hast_proto_send(struct hast_resource *res, struct proto_conn *conn,
+int hast_proto_send(const struct hast_resource *res, struct proto_conn *conn,
     struct nv *nv, const void *data, size_t size);
-int hast_proto_recv(struct hast_resource *res, struct proto_conn *conn,
+int hast_proto_recv(const struct hast_resource *res, struct proto_conn *conn,
     struct nv **nvp, void *data, size_t size);
-int hast_proto_recv_hdr(struct proto_conn *conn, struct nv **nvp);
-int hast_proto_recv_data(struct hast_resource *res, struct proto_conn *conn,
-    struct nv *nv, void *data, size_t size);
+int hast_proto_recv_hdr(const struct proto_conn *conn, struct nv **nvp);
+int hast_proto_recv_data(const struct hast_resource *res,
+    struct proto_conn *conn, struct nv *nv, void *data, size_t size);
 
 #endif	/* !_HAST_PROTO_H_ */
diff --git a/sbin/hastd/proto.c b/sbin/hastd/proto.c
index 8f003de6fdd..db2a2ef4338 100644
--- a/sbin/hastd/proto.c
+++ b/sbin/hastd/proto.c
@@ -179,7 +179,7 @@ proto_accept(struct proto_conn *conn, struct proto_conn **newconnp)
 }
 
 int
-proto_send(struct proto_conn *conn, const void *data, size_t size)
+proto_send(const struct proto_conn *conn, const void *data, size_t size)
 {
 	int ret;
 
@@ -196,7 +196,7 @@ proto_send(struct proto_conn *conn, const void *data, size_t size)
 }
 
 int
-proto_recv(struct proto_conn *conn, void *data, size_t size)
+proto_recv(const struct proto_conn *conn, void *data, size_t size)
 {
 	int ret;
 
diff --git a/sbin/hastd/proto.h b/sbin/hastd/proto.h
index 13248bad649..8d1046caed5 100644
--- a/sbin/hastd/proto.h
+++ b/sbin/hastd/proto.h
@@ -41,8 +41,8 @@ int proto_client(const char *addr, struct proto_conn **connp);
 int proto_connect(struct proto_conn *conn);
 int proto_server(const char *addr, struct proto_conn **connp);
 int proto_accept(struct proto_conn *conn, struct proto_conn **newconnp);
-int proto_send(struct proto_conn *conn, const void *data, size_t size);
-int proto_recv(struct proto_conn *conn, void *data, size_t size);
+int proto_send(const struct proto_conn *conn, const void *data, size_t size);
+int proto_recv(const struct proto_conn *conn, void *data, size_t size);
 int proto_descriptor(const struct proto_conn *conn);
 bool proto_address_match(const struct proto_conn *conn, const char *addr);
 void proto_local_address(const struct proto_conn *conn, char *addr,

From 6be3a25c85fa84906d36a1e2760ec8508e3db680 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 22:28:04 +0000
Subject: [PATCH 0373/1624] Use pjdlog_exit() before fork().

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index 86f274fda29..e018e89a186 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -771,14 +771,14 @@ hastd_primary(struct hast_resource *res)
 	 */
 	if (proto_client("socketpair://", &res->hr_ctrl) < 0) {
 		KEEP_ERRNO((void)pidfile_remove(pfh));
-		primary_exit(EX_OSERR,
+		pjdlog_exit(EX_OSERR,
 		    "Unable to create control sockets between parent and child");
 	}
 
 	pid = fork();
 	if (pid < 0) {
 		KEEP_ERRNO((void)pidfile_remove(pfh));
-		primary_exit(EX_TEMPFAIL, "Unable to fork");
+		pjdlog_exit(EX_TEMPFAIL, "Unable to fork");
 	}
 
 	if (pid > 0) {

From c31776f0f8390b787612a7ff79688b82db828a54 Mon Sep 17 00:00:00 2001
From: Edwin Groothuis 
Date: Mon, 30 Aug 2010 22:45:32 +0000
Subject: [PATCH 0374/1624] For calendars which don't match the solar-based
 Gregorian calendar, be able to specify a year string in an entry.

---
 usr.bin/calendar/calendar.1                |   2 +
 usr.bin/calendar/calendar.h                |   1 +
 usr.bin/calendar/calendars/calendar.judaic | 472 ++++++++++++++++++++-
 usr.bin/calendar/parsedata.c               | 103 +++--
 4 files changed, 541 insertions(+), 37 deletions(-)

diff --git a/usr.bin/calendar/calendar.1 b/usr.bin/calendar/calendar.1
index 8f8fb5cbadc..1e5ac58d0c1 100644
--- a/usr.bin/calendar/calendar.1
+++ b/usr.bin/calendar/calendar.1
@@ -103,6 +103,7 @@ Print lines from today and the next
 days (forward, future).
 Ignore weekends when calculating the number of days.
 .El
+.Sh FILE FORMAT
 .Pp
 To handle calendars in your national code table you can specify
 .Dq LANG=
@@ -196,6 +197,7 @@ Jun. 15\fB\et\fRJune 15.
 Thursday\fB\et\fREvery Thursday.
 June\fB\et\fREvery June 1st.
 15 *\fB\et\fR15th of every month.
+2010/4/15\fB\et\fR15 April 2010
 
 May Sun+2\fB\et\fRsecond Sunday in May (Muttertag)
 04/SunLast\fB\et\fRlast Sunday in April,
diff --git a/usr.bin/calendar/calendar.h b/usr.bin/calendar/calendar.h
index 634c2782a56..8166baea45a 100644
--- a/usr.bin/calendar/calendar.h
+++ b/usr.bin/calendar/calendar.h
@@ -80,6 +80,7 @@ extern int EastLongitude;
 #define	F_SEPEQUINOX		0x08000
 #define	F_JUNSOLSTICE		0x10000
 #define	F_DECSOLSTICE		0x20000
+#define	F_YEAR			0x40000
 
 #define	STRING_EASTER		"Easter"
 #define	STRING_PASKHA		"Paskha"
diff --git a/usr.bin/calendar/calendars/calendar.judaic b/usr.bin/calendar/calendars/calendar.judaic
index 33e8033aa72..25d816efee6 100644
--- a/usr.bin/calendar/calendars/calendar.judaic
+++ b/usr.bin/calendar/calendars/calendar.judaic
@@ -13,10 +13,477 @@
 #define _calendar_judaic_
 
 /*
- * Jewish calendar for the CE year 2007
- * 11 Tevet 5767 - 22 tevet 5768
+ * The calendar below has gotten from the port deskutils/hebcal for
+ * the year of 2010 and for the city of New York.
+ * This should be updated every year!
  */
 
+2010/Jan/16*	Rosh Chodesh Sh'vat
+2010/Jan/30*	Tu B'Shvat
+2010/Feb/13*	Shabbat Shekalim
+2010/Feb/14*	Rosh Chodesh Adar
+2010/Feb/15*	Rosh Chodesh Adar
+2010/Feb/25*	Ta'anit Esther
+2010/Feb/27*	Shabbat Zachor
+2010/Feb/28*	Purim
+2010/Mar/1*	Shushan Purim
+2010/Mar/6*	Shabbat Parah
+2010/Mar/13*	Shabbat HaChodesh
+2010/Mar/16*	Rosh Chodesh Nisan
+2010/Mar/27*	Shabbat HaGadol
+2010/Mar/29*	Ta'anit Bechorot
+2010/Mar/29*	Erev Pesach
+2010/Mar/30*	Pesach I
+2010/Mar/31*	Pesach II
+2010/Apr/1*	Pesach III (CH''M)
+2010/Apr/2*	Pesach IV (CH''M)
+2010/Apr/3*	Pesach V (CH''M)
+2010/Apr/4*	Pesach VI (CH''M)
+2010/Apr/5*	Pesach VII
+2010/Apr/6*	Pesach VIII
+2010/Apr/11*	Yom HaShoah
+2010/Apr/14*	Rosh Chodesh Iyyar
+2010/Apr/15*	Rosh Chodesh Iyyar
+2010/Apr/19*	Yom HaZikaron
+2010/Apr/20*	Yom HaAtzma'ut
+2010/May/2*	Lag B'Omer
+2010/May/Dec*	Yom Yerushalayim
+2010/May/14*	Rosh Chodesh Sivan
+2010/May/18*	Erev Shavuot
+2010/May/19*	Shavuot I
+2010/May/20*	Shavuot II
+2010/Jun/Dec*	Rosh Chodesh Tamuz
+2010/Jun/13*	Rosh Chodesh Tamuz
+2010/Jun/29*	Tzom Tammuz
+2010/Jul/Dec*	Rosh Chodesh Av
+2010/Jul/17*	Shabbat Hazon
+2010/Jul/20*	Tish'a B'Av
+2010/Jul/24*	Shabbat Nachamu
+2010/Aug/Oct*	Rosh Chodesh Elul
+2010/Aug/11*	Rosh Chodesh Elul
+2010/Sep/8*	Erev Rosh Hashana
+2010/Sep/9*	Rosh Hashana 5771
+2010/Sep/Oct*	Rosh Hashana II
+2010/Sep/11*	Shabbat Shuva
+2010/Sep/Dec*	Tzom Gedaliah
+2010/Sep/17*	Erev Yom Kippur
+2010/Sep/18*	Yom Kippur
+2010/Sep/22*	Erev Sukkot
+2010/Sep/23*	Sukkot I
+2010/Sep/24*	Sukkot II
+2010/Sep/25*	Sukkot III (CH''M)
+2010/Sep/26*	Sukkot IV (CH''M)
+2010/Sep/27*	Sukkot V (CH''M)
+2010/Sep/28*	Sukkot VI (CH''M)
+2010/Sep/29*	Sukkot VII (Hoshana Raba)
+2010/Sep/30*	Shmini Atzeret
+2010/Oct/1*	Simchat Torah
+2010/Oct/8*	Rosh Chodesh Cheshvan
+2010/Oct/9*	Rosh Chodesh Cheshvan
+2010/Nov/7*	Rosh Chodesh Kislev
+2010/Nov/8*	Rosh Chodesh Kislev
+2010/Dec/1*	Chanukah: 1 Candle
+2010/Dec/2*	Chanukah: 2 Candles
+2010/Dec/3*	Chanukah: 3 Candles
+2010/Dec/4*	Chanukah: 4 Candles
+2010/Dec/5*	Chanukah: 5 Candles
+2010/Dec/6*	Chanukah: 6 Candles
+2010/Dec/7*	Rosh Chodesh Tevet
+2010/Dec/7*	Chanukah: 7 Candles
+2010/Dec/8*	Rosh Chodesh Tevet
+2010/Dec/8*	Chanukah: 8 Candles
+2010/Dec/9*	Chanukah: 8th Day
+2010/Dec/16*	Asara B'Tevet
+2011/1/6*	Rosh Chodesh Sh'vat
+2011/1/20*	Tu B'Shvat
+2011/2/4*	Rosh Chodesh Adar I
+2011/2/5*	Rosh Chodesh Adar I
+2011/2/18*	Purim Katan
+2011/3/5*	Shabbat Shekalim
+2011/3/6*	Rosh Chodesh Adar II
+2011/3/7*	Rosh Chodesh Adar II
+2011/3/17*	Ta'anit Esther
+2011/3/19*	Shabbat Zachor
+2011/3/20*	Purim
+2011/3/21*	Shushan Purim
+2011/3/26*	Shabbat Parah
+2011/4/2*	Shabbat HaChodesh
+2011/4/5*	Rosh Chodesh Nisan
+2011/4/16*	Shabbat HaGadol
+2011/4/18*	Ta'anit Bechorot
+2011/4/18*	Erev Pesach
+2011/4/19*	Pesach I
+2011/4/20*	Pesach II
+2011/4/21*	Pesach III (CH''M)
+2011/4/22*	Pesach IV (CH''M)
+2011/4/23*	Pesach V (CH''M)
+2011/4/24*	Pesach VI (CH''M)
+2011/4/25*	Pesach VII
+2011/4/26*	Pesach VIII
+2011/5/1*	Yom HaShoah
+2011/5/4*	Rosh Chodesh Iyyar
+2011/5/5*	Rosh Chodesh Iyyar
+2011/5/9*	Yom HaZikaron
+2011/5/10*	Yom HaAtzma'ut
+2011/5/22*	Lag B'Omer
+2011/6/1*	Yom Yerushalayim
+2011/6/3*	Rosh Chodesh Sivan
+2011/6/7*	Erev Shavuot
+2011/6/8*	Shavuot I
+2011/6/9*	Shavuot II
+2011/7/2*	Rosh Chodesh Tamuz
+2011/7/3*	Rosh Chodesh Tamuz
+2011/7/19*	Tzom Tammuz
+2011/8/1*	Rosh Chodesh Av
+2011/8/6*	Shabbat Hazon
+2011/8/9*	Tish'a B'Av
+2011/8/13*	Shabbat Nachamu
+2011/8/30*	Rosh Chodesh Elul
+2011/8/31*	Rosh Chodesh Elul
+2011/9/28*	Erev Rosh Hashana
+2011/9/29*	Rosh Hashana 5772
+2011/9/30*	Rosh Hashana II
+2011/10/1*	Shabbat Shuva
+2011/10/2*	Tzom Gedaliah
+2011/10/7*	Erev Yom Kippur
+2011/10/8*	Yom Kippur
+2011/10/12*	Erev Sukkot
+2011/10/13*	Sukkot I
+2011/10/14*	Sukkot II
+2011/10/15*	Sukkot III (CH''M)
+2011/10/16*	Sukkot IV (CH''M)
+2011/10/17*	Sukkot V (CH''M)
+2011/10/18*	Sukkot VI (CH''M)
+2011/10/19*	Sukkot VII (Hoshana Raba)
+2011/10/20*	Shmini Atzeret
+2011/10/21*	Simchat Torah
+2011/10/28*	Rosh Chodesh Cheshvan
+2011/10/29*	Rosh Chodesh Cheshvan
+2011/11/27*	Rosh Chodesh Kislev
+2011/12/20*	Chanukah: 1 Candle
+2011/12/21*	Chanukah: 2 Candles
+2011/12/22*	Chanukah: 3 Candles
+2011/12/23*	Chanukah: 4 Candles
+2011/12/24*	Chanukah: 5 Candles
+2011/12/25*	Chanukah: 6 Candles
+2011/12/26*	Rosh Chodesh Tevet
+2011/12/26*	Chanukah: 7 Candles
+2011/12/27*	Rosh Chodesh Tevet
+2011/12/27*	Chanukah: 8 Candles
+2011/12/28*	Chanukah: 8th Day
+2012/1/5*	Asara B'Tevet
+2012/1/25*	Rosh Chodesh Sh'vat
+2012/2/8*	Tu B'Shvat
+2012/2/18*	Shabbat Shekalim
+2012/2/23*	Rosh Chodesh Adar
+2012/2/24*	Rosh Chodesh Adar
+2012/3/3*	Shabbat Zachor
+2012/3/7*	Ta'anit Esther
+2012/3/8*	Purim
+2012/3/9*	Shushan Purim
+2012/3/17*	Shabbat Parah
+2012/3/24*	Rosh Chodesh Nisan
+2012/3/24*	Shabbat HaChodesh
+2012/3/31*	Shabbat HaGadol
+2012/4/5*	Ta'anit Bechorot
+2012/4/6*	Erev Pesach
+2012/4/7*	Pesach I
+2012/4/8*	Pesach II
+2012/4/9*	Pesach III (CH''M)
+2012/4/10*	Pesach IV (CH''M)
+2012/4/11*	Pesach V (CH''M)
+2012/4/12*	Pesach VI (CH''M)
+2012/4/13*	Pesach VII
+2012/4/14*	Pesach VIII
+2012/4/19*	Yom HaShoah
+2012/4/22*	Rosh Chodesh Iyyar
+2012/4/23*	Rosh Chodesh Iyyar
+2012/4/25*	Yom HaZikaron
+2012/4/26*	Yom HaAtzma'ut
+2012/5/10*	Lag B'Omer
+2012/5/20*	Yom Yerushalayim
+2012/5/22*	Rosh Chodesh Sivan
+2012/5/26*	Erev Shavuot
+2012/5/27*	Shavuot I
+2012/5/28*	Shavuot II
+2012/6/20*	Rosh Chodesh Tamuz
+2012/6/21*	Rosh Chodesh Tamuz
+2012/7/8*	Tzom Tammuz
+2012/7/20*	Rosh Chodesh Av
+2012/7/28*	Shabbat Hazon
+2012/7/29*	Tish'a B'Av
+2012/8/4*	Shabbat Nachamu
+2012/8/18*	Rosh Chodesh Elul
+2012/8/19*	Rosh Chodesh Elul
+2012/9/16*	Erev Rosh Hashana
+2012/9/17*	Rosh Hashana 5773
+2012/9/18*	Rosh Hashana II
+2012/9/19*	Tzom Gedaliah
+2012/9/22*	Shabbat Shuva
+2012/9/25*	Erev Yom Kippur
+2012/9/26*	Yom Kippur
+2012/9/30*	Erev Sukkot
+2012/10/1*	Sukkot I
+2012/10/2*	Sukkot II
+2012/10/3*	Sukkot III (CH''M)
+2012/10/4*	Sukkot IV (CH''M)
+2012/10/5*	Sukkot V (CH''M)
+2012/10/6*	Sukkot VI (CH''M)
+2012/10/7*	Sukkot VII (Hoshana Raba)
+2012/10/8*	Shmini Atzeret
+2012/10/9*	Simchat Torah
+2012/10/16*	Rosh Chodesh Cheshvan
+2012/10/17*	Rosh Chodesh Cheshvan
+2012/11/15*	Rosh Chodesh Kislev
+2012/12/8*	Chanukah: 1 Candle
+2012/12/9*	Chanukah: 2 Candles
+2012/12/10*	Chanukah: 3 Candles
+2012/12/11*	Chanukah: 4 Candles
+2012/12/12*	Chanukah: 5 Candles
+2012/12/13*	Chanukah: 6 Candles
+2012/12/14*	Rosh Chodesh Tevet
+2012/12/14*	Chanukah: 7 Candles
+2012/12/15*	Chanukah: 8 Candles
+2012/12/16*	Chanukah: 8th Day
+2012/12/23*	Asara B'Tevet
+2013/1/12*	Rosh Chodesh Sh'vat
+2013/1/26*	Tu B'Shvat
+2013/2/9*	Shabbat Shekalim
+2013/2/10*	Rosh Chodesh Adar
+2013/2/11*	Rosh Chodesh Adar
+2013/2/21*	Ta'anit Esther
+2013/2/23*	Shabbat Zachor
+2013/2/24*	Purim
+2013/2/25*	Shushan Purim
+2013/3/2*	Shabbat Parah
+2013/3/9*	Shabbat HaChodesh
+2013/3/12*	Rosh Chodesh Nisan
+2013/3/23*	Shabbat HaGadol
+2013/3/25*	Ta'anit Bechorot
+2013/3/25*	Erev Pesach
+2013/3/26*	Pesach I
+2013/3/27*	Pesach II
+2013/3/28*	Pesach III (CH''M)
+2013/3/29*	Pesach IV (CH''M)
+2013/3/30*	Pesach V (CH''M)
+2013/3/31*	Pesach VI (CH''M)
+2013/4/1*	Pesach VII
+2013/4/2*	Pesach VIII
+2013/4/7*	Yom HaShoah
+2013/4/10*	Rosh Chodesh Iyyar
+2013/4/11*	Rosh Chodesh Iyyar
+2013/4/15*	Yom HaZikaron
+2013/4/16*	Yom HaAtzma'ut
+2013/4/28*	Lag B'Omer
+2013/5/8*	Yom Yerushalayim
+2013/5/10*	Rosh Chodesh Sivan
+2013/5/14*	Erev Shavuot
+2013/5/15*	Shavuot I
+2013/5/16*	Shavuot II
+2013/6/8*	Rosh Chodesh Tamuz
+2013/6/9*	Rosh Chodesh Tamuz
+2013/6/25*	Tzom Tammuz
+2013/7/8*	Rosh Chodesh Av
+2013/7/13*	Shabbat Hazon
+2013/7/16*	Tish'a B'Av
+2013/7/20*	Shabbat Nachamu
+2013/8/6*	Rosh Chodesh Elul
+2013/8/7*	Rosh Chodesh Elul
+2013/9/4*	Erev Rosh Hashana
+2013/9/5*	Rosh Hashana 5774
+2013/9/6*	Rosh Hashana II
+2013/9/7*	Shabbat Shuva
+2013/9/8*	Tzom Gedaliah
+2013/9/13*	Erev Yom Kippur
+2013/9/14*	Yom Kippur
+2013/9/18*	Erev Sukkot
+2013/9/19*	Sukkot I
+2013/9/20*	Sukkot II
+2013/9/21*	Sukkot III (CH''M)
+2013/9/22*	Sukkot IV (CH''M)
+2013/9/23*	Sukkot V (CH''M)
+2013/9/24*	Sukkot VI (CH''M)
+2013/9/25*	Sukkot VII (Hoshana Raba)
+2013/9/26*	Shmini Atzeret
+2013/9/27*	Simchat Torah
+2013/10/4*	Rosh Chodesh Cheshvan
+2013/10/5*	Rosh Chodesh Cheshvan
+2013/11/3*	Rosh Chodesh Kislev
+2013/11/4*	Rosh Chodesh Kislev
+2013/11/27*	Chanukah: 1 Candle
+2013/11/28*	Chanukah: 2 Candles
+2013/11/29*	Chanukah: 3 Candles
+2013/11/30*	Chanukah: 4 Candles
+2013/12/1*	Chanukah: 5 Candles
+2013/12/2*	Chanukah: 6 Candles
+2013/12/3*	Rosh Chodesh Tevet
+2013/12/3*	Chanukah: 7 Candles
+2013/12/4*	Rosh Chodesh Tevet
+2013/12/4*	Chanukah: 8 Candles
+2013/12/5*	Chanukah: 8th Day
+2013/12/12*	Asara B'Tevet
+2014/1/2*	Rosh Chodesh Sh'vat
+2014/1/16*	Tu B'Shvat
+2014/1/31*	Rosh Chodesh Adar I
+2014/2/1*	Rosh Chodesh Adar I
+2014/2/14*	Purim Katan
+2014/3/1*	Shabbat Shekalim
+2014/3/2*	Rosh Chodesh Adar II
+2014/3/3*	Rosh Chodesh Adar II
+2014/3/13*	Ta'anit Esther
+2014/3/15*	Shabbat Zachor
+2014/3/16*	Purim
+2014/3/17*	Shushan Purim
+2014/3/22*	Shabbat Parah
+2014/3/29*	Shabbat HaChodesh
+2014/4/1*	Rosh Chodesh Nisan
+2014/4/12*	Shabbat HaGadol
+2014/4/14*	Ta'anit Bechorot
+2014/4/14*	Erev Pesach
+2014/4/15*	Pesach I
+2014/4/16*	Pesach II
+2014/4/17*	Pesach III (CH''M)
+2014/4/18*	Pesach IV (CH''M)
+2014/4/19*	Pesach V (CH''M)
+2014/4/20*	Pesach VI (CH''M)
+2014/4/21*	Pesach VII
+2014/4/22*	Pesach VIII
+2014/4/27*	Yom HaShoah
+2014/4/30*	Rosh Chodesh Iyyar
+2014/5/1*	Rosh Chodesh Iyyar
+2014/5/5*	Yom HaZikaron
+2014/5/6*	Yom HaAtzma'ut
+2014/5/18*	Lag B'Omer
+2014/5/28*	Yom Yerushalayim
+2014/5/30*	Rosh Chodesh Sivan
+2014/6/3*	Erev Shavuot
+2014/6/4*	Shavuot I
+2014/6/5*	Shavuot II
+2014/6/28*	Rosh Chodesh Tamuz
+2014/6/29*	Rosh Chodesh Tamuz
+2014/7/15*	Tzom Tammuz
+2014/7/28*	Rosh Chodesh Av
+2014/8/2*	Shabbat Hazon
+2014/8/5*	Tish'a B'Av
+2014/8/9*	Shabbat Nachamu
+2014/8/26*	Rosh Chodesh Elul
+2014/8/27*	Rosh Chodesh Elul
+2014/9/24*	Erev Rosh Hashana
+2014/9/25*	Rosh Hashana 5775
+2014/9/26*	Rosh Hashana II
+2014/9/27*	Shabbat Shuva
+2014/9/28*	Tzom Gedaliah
+2014/10/3*	Erev Yom Kippur
+2014/10/4*	Yom Kippur
+2014/10/8*	Erev Sukkot
+2014/10/9*	Sukkot I
+2014/10/10*	Sukkot II
+2014/10/11*	Sukkot III (CH''M)
+2014/10/12*	Sukkot IV (CH''M)
+2014/10/13*	Sukkot V (CH''M)
+2014/10/14*	Sukkot VI (CH''M)
+2014/10/15*	Sukkot VII (Hoshana Raba)
+2014/10/16*	Shmini Atzeret
+2014/10/17*	Simchat Torah
+2014/10/24*	Rosh Chodesh Cheshvan
+2014/10/25*	Rosh Chodesh Cheshvan
+2014/11/23*	Rosh Chodesh Kislev
+2014/12/16*	Chanukah: 1 Candle
+2014/12/17*	Chanukah: 2 Candles
+2014/12/18*	Chanukah: 3 Candles
+2014/12/19*	Chanukah: 4 Candles
+2014/12/20*	Chanukah: 5 Candles
+2014/12/21*	Chanukah: 6 Candles
+2014/12/22*	Rosh Chodesh Tevet
+2014/12/22*	Chanukah: 7 Candles
+2014/12/23*	Rosh Chodesh Tevet
+2014/12/23*	Chanukah: 8 Candles
+2014/12/24*	Chanukah: 8th Day
+2015/1/1*	Asara B'Tevet
+2015/1/21*	Rosh Chodesh Sh'vat
+2015/2/4*	Tu B'Shvat
+2015/2/14*	Shabbat Shekalim
+2015/2/19*	Rosh Chodesh Adar
+2015/2/20*	Rosh Chodesh Adar
+2015/2/28*	Shabbat Zachor
+2015/3/4*	Ta'anit Esther
+2015/3/5*	Purim
+2015/3/6*	Shushan Purim
+2015/3/14*	Shabbat Parah
+2015/3/21*	Rosh Chodesh Nisan
+2015/3/21*	Shabbat HaChodesh
+2015/3/28*	Shabbat HaGadol
+2015/4/2*	Ta'anit Bechorot
+2015/4/3*	Erev Pesach
+2015/4/4*	Pesach I
+2015/4/5*	Pesach II
+2015/4/6*	Pesach III (CH''M)
+2015/4/7*	Pesach IV (CH''M)
+2015/4/8*	Pesach V (CH''M)
+2015/4/9*	Pesach VI (CH''M)
+2015/4/10*	Pesach VII
+2015/4/11*	Pesach VIII
+2015/4/16*	Yom HaShoah
+2015/4/19*	Rosh Chodesh Iyyar
+2015/4/20*	Rosh Chodesh Iyyar
+2015/4/22*	Yom HaZikaron
+2015/4/23*	Yom HaAtzma'ut
+2015/5/7*	Lag B'Omer
+2015/5/17*	Yom Yerushalayim
+2015/5/19*	Rosh Chodesh Sivan
+2015/5/23*	Erev Shavuot
+2015/5/24*	Shavuot I
+2015/5/25*	Shavuot II
+2015/6/17*	Rosh Chodesh Tamuz
+2015/6/18*	Rosh Chodesh Tamuz
+2015/7/5*	Tzom Tammuz
+2015/7/17*	Rosh Chodesh Av
+2015/7/25*	Shabbat Hazon
+2015/7/26*	Tish'a B'Av
+2015/8/1*	Shabbat Nachamu
+2015/8/15*	Rosh Chodesh Elul
+2015/8/16*	Rosh Chodesh Elul
+2015/9/13*	Erev Rosh Hashana
+2015/9/14*	Rosh Hashana 5776
+2015/9/15*	Rosh Hashana II
+2015/9/16*	Tzom Gedaliah
+2015/9/19*	Shabbat Shuva
+2015/9/22*	Erev Yom Kippur
+2015/9/23*	Yom Kippur
+2015/9/27*	Erev Sukkot
+2015/9/28*	Sukkot I
+2015/9/29*	Sukkot II
+2015/9/30*	Sukkot III (CH''M)
+2015/10/1*	Sukkot IV (CH''M)
+2015/10/2*	Sukkot V (CH''M)
+2015/10/3*	Sukkot VI (CH''M)
+2015/10/4*	Sukkot VII (Hoshana Raba)
+2015/10/5*	Shmini Atzeret
+2015/10/6*	Simchat Torah
+2015/10/13*	Rosh Chodesh Cheshvan
+2015/10/14*	Rosh Chodesh Cheshvan
+2015/11/12*	Rosh Chodesh Kislev
+2015/11/13*	Rosh Chodesh Kislev
+2015/12/6*	Chanukah: 1 Candle
+2015/12/7*	Chanukah: 2 Candles
+2015/12/8*	Chanukah: 3 Candles
+2015/12/9*	Chanukah: 4 Candles
+2015/12/10*	Chanukah: 5 Candles
+2015/12/11*	Chanukah: 6 Candles
+2015/12/12*	Rosh Chodesh Tevet
+2015/12/12*	Chanukah: 7 Candles
+2015/12/13*	Rosh Chodesh Tevet
+2015/12/13*	Chanukah: 8 Candles
+2015/12/14*	Chanukah: 8th Day
+2015/12/22*	Asara B'Tevet
+
+/*
+ * The calendar data below was for 2007, so it is commented out.
+ */
+
+/*
+ * Jewish calendar for the CE year 2007
+ * 11 Tevet 5767 - 22 tevet 5768
 
 01/06*	Parshas Vayechi
 01/13*	Parshas Shemos
@@ -223,5 +690,6 @@
 12/22*	Parshas Vayechi
 12/29*	Parshas Shemos
 
+*/
 
 #endif /* !_calendar_judaic_ */
diff --git a/usr.bin/calendar/parsedata.c b/usr.bin/calendar/parsedata.c
index 6482fd3e081..51834390d5a 100644
--- a/usr.bin/calendar/parsedata.c
+++ b/usr.bin/calendar/parsedata.c
@@ -87,9 +87,9 @@ static int
 determinestyle(char *date, int *flags,
     char *month, int *imonth, char *dayofmonth, int *idayofmonth,
     char *dayofweek, int *idayofweek, char *modifieroffset,
-    char *modifierindex, char *specialday)
+    char *modifierindex, char *specialday, char *year, int *iyear)
 {
-	char *p, *p1, *p2;
+	char *p, *p1, *p2, *py;
 	const char *dow, *pmonth;
 	char pold;
 	size_t len, offset;
@@ -97,6 +97,8 @@ determinestyle(char *date, int *flags,
 	*flags = F_NONE;
 	*month = '\0';
 	*imonth = 0;
+	*year = '\0';
+	*iyear = 0;
 	*dayofmonth = '\0';
 	*idayofmonth = 0;
 	*dayofweek = '\0';
@@ -191,6 +193,22 @@ determinestyle(char *date, int *flags,
 	p2 = p + 1;
 	/* Now p2 points to the next field and p1 to the first field */
 
+	if ((py = strchr(p2, '/')) != NULL) {
+		/* We have a year in the string. Now this is getting tricky */
+		strcpy(year, p1);
+		*iyear = (int)strtol(year, NULL, 10);
+		p1 = p2;
+		p2 = py + 1;
+		*py = 0;
+		*flags |= F_YEAR;
+	}
+
+	/*
+	printf("p1: %s\n", p1);
+	printf("p2: %s\n", p2);
+	printf("year: %s\n", year);
+	*/
+
 	/* Check if there is a month-string in the date */
 	if ((checkmonth(p1, &len, &offset, &pmonth) != 0)
 	 || (checkmonth(p2, &len, &offset, &pmonth) != 0 && (p2 = p1))) {
@@ -323,7 +341,8 @@ remember(int *rememberindex, int *y, int *m, int *d, char **ed, int yy, int mm,
 static void
 debug_determinestyle(int dateonly, char *date, int flags, char *month,
     int imonth, char *dayofmonth, int idayofmonth, char *dayofweek,
-    int idayofweek, char *modifieroffset, char *modifierindex, char *specialday)
+    int idayofweek, char *modifieroffset, char *modifierindex, char *specialday,
+    char *year, int iyear)
 {
 
 	if (dateonly != 0) {
@@ -336,6 +355,8 @@ debug_determinestyle(int dateonly, char *date, int flags, char *month,
 		printf("modifieroffset: |%s|\n", modifieroffset);
 	if (modifierindex[0] != '\0')
 		printf("modifierindex: |%s|\n", modifierindex);
+	if (year[0] != '\0')
+		printf("year: |%s| (%d)\n", year, iyear);
 	if (month[0] != '\0')
 		printf("month: |%s| (%d)\n", month, imonth);
 	if (dayofmonth[0] != '\0')
@@ -371,8 +392,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
     char **edp)
 {
 	char month[100], dayofmonth[100], dayofweek[100], modifieroffset[100];
+	char syear[100];
 	char modifierindex[100], specialday[100];
-	int idayofweek = -1, imonth = -1, idayofmonth = -1, year, remindex;
+	int idayofweek = -1, imonth = -1, idayofmonth = -1, iyear = -1;
+	int year, remindex;
 	int d, m, dow, rm, rd, offset;
 	char *ed;
 	int retvalsign = 1;
@@ -394,10 +417,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 	if (debug)
 		debug_determinestyle(1, date, *flags, month, imonth,
 		    dayofmonth, idayofmonth, dayofweek, idayofweek,
-		    modifieroffset, modifierindex, specialday);
+		    modifieroffset, modifierindex, specialday, syear, iyear);
 	if (determinestyle(date, flags, month, &imonth, dayofmonth,
 	    &idayofmonth, dayofweek, &idayofweek, modifieroffset,
-	    modifierindex, specialday) == 0) {
+	    modifierindex, specialday, syear, &iyear) == 0) {
 		if (debug)
 			printf("Failed!\n");
 		return (0);
@@ -406,10 +429,18 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 	if (debug)
 		debug_determinestyle(0, date, *flags, month, imonth,
 		    dayofmonth, idayofmonth, dayofweek, idayofweek,
-		    modifieroffset, modifierindex, specialday);
+		    modifieroffset, modifierindex, specialday, syear, iyear);
 
 	remindex = 0;
 	for (year = year1; year <= year2; year++) {
+
+		int lflags = *flags;
+		/* If the year is specified, only do it if it is this year! */
+		if ((lflags & F_YEAR) != 0)
+			if (iyear != year)
+				continue;
+		lflags &= ~F_YEAR;
+
 		/* Get important dates for this year */
 		yearinfo = years;
 		while (yearinfo != NULL) {
@@ -452,7 +483,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Same day every year */
-		if (*flags == (F_MONTH | F_DAYOFMONTH)) {
+		if (lflags == (F_MONTH | F_DAYOFMONTH)) {
 			if (!remember_ymd(year, imonth, idayofmonth))
 				continue;
 			remember(&remindex, yearp, monthp, dayp, edp,
@@ -461,7 +492,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* XXX Same day every year, but variable */
-		if (*flags == (F_MONTH | F_DAYOFMONTH | F_VARIABLE)) {
+		if (lflags == (F_MONTH | F_DAYOFMONTH | F_VARIABLE)) {
 			if (!remember_ymd(year, imonth, idayofmonth))
 				continue;
 			remember(&remindex, yearp, monthp, dayp, edp,
@@ -470,7 +501,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Same day every month */
-		if (*flags == (F_ALLMONTH | F_DAYOFMONTH)) {
+		if (lflags == (F_ALLMONTH | F_DAYOFMONTH)) {
 			for (m = 1; m <= 12; m++) {
 				if (!remember_ymd(year, m, idayofmonth))
 					continue;
@@ -481,7 +512,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Every day of a month */
-		if (*flags == (F_ALLDAY | F_MONTH)) {
+		if (lflags == (F_ALLDAY | F_MONTH)) {
 			for (d = 1; d <= yearinfo->mondays[imonth]; d++) {
 				if (!remember_ymd(year, imonth, d))
 					continue;
@@ -492,7 +523,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* One day of every month */
-		if (*flags == (F_ALLMONTH | F_DAYOFWEEK)) {
+		if (lflags == (F_ALLMONTH | F_DAYOFWEEK)) {
 			for (m = 1; m <= 12; m++) {
 				if (!remember_ymd(year, m, idayofmonth))
 					continue;
@@ -503,7 +534,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Every dayofweek of the year */
-		if (*flags == (F_DAYOFWEEK | F_VARIABLE)) {
+		if (lflags == (F_DAYOFWEEK | F_VARIABLE)) {
 			dow = first_dayofweek_of_year(year);
 			d = (idayofweek - dow + 8) % 7;
 			while (d <= 366) {
@@ -517,7 +548,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* A certain dayofweek of a month */
-		if (*flags ==
+		if (lflags ==
 		    (F_MONTH | F_DAYOFWEEK | F_MODIFIERINDEX | F_VARIABLE)) {
 			offset = indextooffset(modifierindex);
 			dow = first_dayofweek_of_month(year, imonth);
@@ -553,7 +584,7 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Every dayofweek of the month */
-		if (*flags == (F_DAYOFWEEK | F_MONTH | F_VARIABLE)) {
+		if (lflags == (F_DAYOFWEEK | F_MONTH | F_VARIABLE)) {
 			dow = first_dayofweek_of_month(year, imonth);
 			d = (idayofweek - dow + 8) % 7;
 			while (d <= yearinfo->mondays[imonth]) {
@@ -567,10 +598,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Easter */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_EASTER)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year, yearinfo->ieaster + offset,
 			    &rm, &rd))
@@ -580,10 +611,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Paskha */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_PASKHA)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year, yearinfo->ipaskha + offset,
 			    &rm, &rd))
@@ -593,10 +624,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* Chinese New Year */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_CNY)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year, yearinfo->firstcnyday + offset,
 			    &rm, &rd))
@@ -606,12 +637,12 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* FullMoon */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_FULLMOON)) {
 			int i;
 
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			for (i = 0; yearinfo->ffullmoon[i] > 0; i++) {
 				if (remember_yd(year,
@@ -628,12 +659,12 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* NewMoon */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_NEWMOON)) {
 			int i;
 
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			for (i = 0; yearinfo->ffullmoon[i] > 0; i++) {
 				if (remember_yd(year,
@@ -649,10 +680,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* (Mar|Sep)Equinox */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_MAREQUINOX)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year, yearinfo->equinoxdays[0] + offset,
 			    &rm, &rd)) {
@@ -662,10 +693,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 			}
 			continue;
 		}
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_SEPEQUINOX)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year, yearinfo->equinoxdays[1] + offset,
 			    &rm, &rd)) {
@@ -677,10 +708,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		/* (Jun|Dec)Solstice */
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_JUNSOLSTICE)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year,
 			    yearinfo->solsticedays[0] + offset, &rm, &rd)) {
@@ -690,10 +721,10 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 			}
 			continue;
 		}
-		if ((*flags & ~F_MODIFIEROFFSET) ==
+		if ((lflags & ~F_MODIFIEROFFSET) ==
 		    (F_SPECIALDAY | F_VARIABLE | F_DECSOLSTICE)) {
 			offset = 0;
-			if ((*flags & F_MODIFIEROFFSET) != 0)
+			if ((lflags & F_MODIFIEROFFSET) != 0)
 				offset = parseoffset(modifieroffset);
 			if (remember_yd(year,
 			    yearinfo->solsticedays[1] + offset, &rm, &rd)) {
@@ -705,9 +736,9 @@ parsedaymonth(char *date, int *yearp, int *monthp, int *dayp, int *flags,
 		}
 
 		printf("Unprocessed:\n");
-		debug_determinestyle(2, date, *flags, month, imonth,
+		debug_determinestyle(2, date, lflags, month, imonth,
 		    dayofmonth, idayofmonth, dayofweek, idayofweek,
-		    modifieroffset, modifierindex, specialday);
+		    modifieroffset, modifierindex, specialday, syear, iyear);
 		retvalsign = -1;
 	}
 
@@ -723,6 +754,8 @@ showflags(int flags)
 	static char s[1000];
 	s[0] = '\0';
 
+	if ((flags & F_YEAR) != 0)
+		strcat(s, "year ");
 	if ((flags & F_MONTH) != 0)
 		strcat(s, "month ");
 	if ((flags & F_DAYOFWEEK) != 0)

From eea2deaad04644b7f677033f3f8e3cbb0cc9c22f Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 23:16:45 +0000
Subject: [PATCH 0375/1624] When someone gives NULL as data, assume this is
 because he want to declare connection side only.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/proto_socketpair.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/sbin/hastd/proto_socketpair.c b/sbin/hastd/proto_socketpair.c
index 0d040f39454..c0b41a46da3 100644
--- a/sbin/hastd/proto_socketpair.c
+++ b/sbin/hastd/proto_socketpair.c
@@ -140,6 +140,10 @@ sp_send(void *ctx, const unsigned char *data, size_t size)
 		abort();
 	}
 
+	/* Someone is just trying to decide about side. */
+	if (data == NULL)
+		return (0);
+
 	return (proto_common_send(fd, data, size));
 }
 
@@ -174,6 +178,10 @@ sp_recv(void *ctx, unsigned char *data, size_t size)
 		abort();
 	}
 
+	/* Someone is just trying to decide about side. */
+	if (data == NULL)
+		return (0);
+
 	return (proto_common_recv(fd, data, size));
 }
 

From 6b276294afee31ba53c10bc5adbfeb62bb012e02 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 23:19:21 +0000
Subject: [PATCH 0376/1624] We only want to know if descriptors are ready for
 reading.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/hastd.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)

diff --git a/sbin/hastd/hastd.c b/sbin/hastd/hastd.c
index ad80c8e9b42..ccc25cfe0f4 100644
--- a/sbin/hastd/hastd.c
+++ b/sbin/hastd/hastd.c
@@ -624,7 +624,7 @@ close:
 static void
 main_loop(void)
 {
-	fd_set rfds, wfds;
+	fd_set rfds;
 	int cfd, lfd, maxfd, ret;
 	struct timeval timeout;
 
@@ -654,11 +654,8 @@ main_loop(void)
 		FD_ZERO(&rfds);
 		FD_SET(cfd, &rfds);
 		FD_SET(lfd, &rfds);
-		FD_ZERO(&wfds);
-		FD_SET(cfd, &wfds);
-		FD_SET(lfd, &wfds);
 
-		ret = select(maxfd + 1, &rfds, &wfds, NULL, &timeout);
+		ret = select(maxfd + 1, &rfds, NULL, NULL, &timeout);
 		if (ret == 0)
 			hook_check(false);
 		else if (ret == -1) {
@@ -668,9 +665,9 @@ main_loop(void)
 			pjdlog_exit(EX_OSERR, "select() failed");
 		}
 
-		if (FD_ISSET(cfd, &rfds) || FD_ISSET(cfd, &wfds))
+		if (FD_ISSET(cfd, &rfds))
 			control_handle(cfg);
-		if (FD_ISSET(lfd, &rfds) || FD_ISSET(lfd, &wfds))
+		if (FD_ISSET(lfd, &rfds))
 			listen_accept();
 	}
 }

From 5bdff860e71f864e1f472010b0284ff6ae222b5d Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 30 Aug 2010 23:26:10 +0000
Subject: [PATCH 0377/1624] Because it is very hard to make fork(2) from
 threaded process safe (we are limited to async-signal safe functions in the
 child process), move all hooks execution to the main (non-threaded) process.

Do it by maintaining connection (socketpair) between child and parent
and sending events from the child to parent, so it can execute the hook.

This is step in right direction for others reasons too. For example there is
one less problem to drop privs in worker processes.

MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/Makefile    |  2 +-
 sbin/hastd/hast.h      |  2 ++
 sbin/hastd/hastd.c     | 44 ++++++++++++++++++++++++++++++++----------
 sbin/hastd/primary.c   | 39 +++++++++++++++++++------------------
 sbin/hastd/secondary.c | 21 ++++++++++++++++----
 5 files changed, 74 insertions(+), 34 deletions(-)

diff --git a/sbin/hastd/Makefile b/sbin/hastd/Makefile
index bfb62f4f11f..6e3147dcd31 100644
--- a/sbin/hastd/Makefile
+++ b/sbin/hastd/Makefile
@@ -5,7 +5,7 @@
 PROG=	hastd
 SRCS=	activemap.c
 SRCS+=	control.c
-SRCS+=	ebuf.c
+SRCS+=	ebuf.c event.c
 SRCS+=	hast_proto.c hastd.c hooks.c
 SRCS+=	metadata.c
 SRCS+=	nv.c
diff --git a/sbin/hastd/hast.h b/sbin/hastd/hast.h
index 71379178e76..a42865f0d06 100644
--- a/sbin/hastd/hast.h
+++ b/sbin/hastd/hast.h
@@ -181,6 +181,8 @@ struct hast_resource {
 	pid_t	hr_workerpid;
 	/* Control connection between parent and child. */
 	struct proto_conn *hr_ctrl;
+	/* Events from child to parent. */
+	struct proto_conn *hr_event;
 
 	/* Activemap structure. */
 	struct activemap *hr_amp;
diff --git a/sbin/hastd/hastd.c b/sbin/hastd/hastd.c
index ccc25cfe0f4..6ddcbd2f831 100644
--- a/sbin/hastd/hastd.c
+++ b/sbin/hastd/hastd.c
@@ -52,6 +52,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include "control.h"
+#include "event.h"
 #include "hast.h"
 #include "hast_proto.h"
 #include "hastd.h"
@@ -158,6 +159,11 @@ child_exit(void)
 		    role2str(res->hr_role));
 		child_exit_log(pid, status);
 		proto_close(res->hr_ctrl);
+		res->hr_ctrl = NULL;
+		if (res->hr_event != NULL) {
+			proto_close(res->hr_event);
+			res->hr_event = NULL;
+		}
 		res->hr_workerpid = 0;
 		if (res->hr_role == HAST_ROLE_PRIMARY) {
 			/*
@@ -624,9 +630,10 @@ close:
 static void
 main_loop(void)
 {
-	fd_set rfds;
-	int cfd, lfd, maxfd, ret;
+	struct hast_resource *res;
 	struct timeval timeout;
+	int fd, maxfd, ret;
+	fd_set rfds;
 
 	timeout.tv_sec = REPORT_INTERVAL;
 	timeout.tv_usec = 0;
@@ -646,14 +653,20 @@ main_loop(void)
 			hastd_reload();
 		}
 
-		cfd = proto_descriptor(cfg->hc_controlconn);
-		lfd = proto_descriptor(cfg->hc_listenconn);
-		maxfd = cfd > lfd ? cfd : lfd;
-
 		/* Setup descriptors for select(2). */
 		FD_ZERO(&rfds);
-		FD_SET(cfd, &rfds);
-		FD_SET(lfd, &rfds);
+		maxfd = fd = proto_descriptor(cfg->hc_controlconn);
+		FD_SET(fd, &rfds);
+		fd = proto_descriptor(cfg->hc_listenconn);
+		FD_SET(fd, &rfds);
+		maxfd = fd > maxfd ? fd : maxfd;
+		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
+			if (res->hr_event == NULL)
+				continue;
+			fd = proto_descriptor(res->hr_event);
+			FD_SET(fd, &rfds);
+			maxfd = fd > maxfd ? fd : maxfd;
+		}
 
 		ret = select(maxfd + 1, &rfds, NULL, NULL, &timeout);
 		if (ret == 0)
@@ -665,10 +678,21 @@ main_loop(void)
 			pjdlog_exit(EX_OSERR, "select() failed");
 		}
 
-		if (FD_ISSET(cfd, &rfds))
+		if (FD_ISSET(proto_descriptor(cfg->hc_controlconn), &rfds))
 			control_handle(cfg);
-		if (FD_ISSET(lfd, &rfds))
+		if (FD_ISSET(proto_descriptor(cfg->hc_listenconn), &rfds))
 			listen_accept();
+		TAILQ_FOREACH(res, &cfg->hc_resources, hr_next) {
+			if (res->hr_event == NULL)
+				continue;
+			if (FD_ISSET(proto_descriptor(res->hr_event), &rfds)) {
+				if (event_recv(res) == 0)
+					continue;
+				/* The worker process exited? */
+				proto_close(res->hr_event);
+				res->hr_event = NULL;
+			}
+		}
 	}
 }
 
diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index e018e89a186..a8a2d41f87a 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -58,6 +58,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include "control.h"
+#include "event.h"
 #include "hast.h"
 #include "hast_proto.h"
 #include "hastd.h"
@@ -225,12 +226,6 @@ static void *ggate_send_thread(void *arg);
 static void *sync_thread(void *arg);
 static void *guard_thread(void *arg);
 
-static void
-dummy_sighandler(int sig __unused)
-{
-	/* Nothing to do. */
-}
-
 static void
 cleanup(struct hast_resource *res)
 {
@@ -429,8 +424,6 @@ init_environment(struct hast_resource *res __unused)
 	/*
 	 * Turn on signals handling.
 	 */
-	/* Because SIGCHLD is ignored by default, setup dummy handler for it. */
-	PJDLOG_VERIFY(signal(SIGCHLD, dummy_sighandler) != SIG_ERR);
 	PJDLOG_VERIFY(sigfillset(&mask) == 0);
 	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
 }
@@ -672,11 +665,11 @@ init_remote(struct hast_resource *res, struct proto_conn **inp,
 		res->hr_remotein = in;
 		res->hr_remoteout = out;
 	}
-	hook_exec(res->hr_exec, "connect", res->hr_name, NULL);
+	event_send(res, EVENT_CONNECT);
 	return (true);
 close:
 	if (errmsg != NULL && strcmp(errmsg, "Split-brain condition!") == 0)
-		hook_exec(res->hr_exec, "split-brain", res->hr_name, NULL);
+		event_send(res, EVENT_SPLITBRAIN);
 	proto_close(out);
 	if (in != NULL)
 		proto_close(in);
@@ -774,6 +767,14 @@ hastd_primary(struct hast_resource *res)
 		pjdlog_exit(EX_OSERR,
 		    "Unable to create control sockets between parent and child");
 	}
+	/*
+	 * Create communication channel between child and parent.
+	 */
+	if (proto_client("socketpair://", &res->hr_event) < 0) {
+		KEEP_ERRNO((void)pidfile_remove(pfh));
+		pjdlog_exit(EX_OSERR,
+		    "Unable to create event sockets between child and parent");
+	}
 
 	pid = fork();
 	if (pid < 0) {
@@ -783,6 +784,8 @@ hastd_primary(struct hast_resource *res)
 
 	if (pid > 0) {
 		/* This is parent. */
+		/* Declare that we are receiver. */
+		proto_recv(res->hr_event, NULL, 0);
 		res->hr_workerpid = pid;
 		return;
 	}
@@ -797,7 +800,9 @@ hastd_primary(struct hast_resource *res)
 	signal(SIGHUP, SIG_DFL);
 	signal(SIGCHLD, SIG_DFL);
 
-	hook_init();
+	/* Declare that we are sender. */
+	proto_send(res->hr_event, NULL, 0);
+
 	init_local(res);
 	if (real_remote(res) && init_remote(res, NULL, NULL))
 		sync_start();
@@ -896,7 +901,7 @@ remote_close(struct hast_resource *res, int ncomp)
 	 */
 	sync_stop();
 
-	hook_exec(res->hr_exec, "disconnect", res->hr_name, NULL);
+	event_send(res, EVENT_DISCONNECT);
 }
 
 /*
@@ -1512,7 +1517,7 @@ sync_thread(void *arg __unused)
 			pjdlog_info("Synchronization interrupted. "
 			    "%jd bytes synchronized so far.",
 			    (intmax_t)synced);
-			hook_exec(res->hr_exec, "syncintr", res->hr_name, NULL);
+			event_send(res, EVENT_SYNCINTR);
 		}
 		while (!sync_inprogress) {
 			dorewind = true;
@@ -1545,8 +1550,7 @@ sync_thread(void *arg __unused)
 				pjdlog_info("Synchronization started. %ju bytes to go.",
 				    (uintmax_t)(res->hr_extentsize *
 				    activemap_ndirty(res->hr_amp)));
-				hook_exec(res->hr_exec, "syncstart",
-				    res->hr_name, NULL);
+				event_send(res, EVENT_SYNCSTART);
 			}
 		}
 		if (offset < 0) {
@@ -1563,8 +1567,7 @@ sync_thread(void *arg __unused)
 					pjdlog_info("Synchronization complete. "
 					    "%jd bytes synchronized.",
 					    (intmax_t)synced);
-					hook_exec(res->hr_exec, "syncdone",
-					    res->hr_name, NULL);
+					event_send(res, EVENT_SYNCDONE);
 				}
 				mtx_lock(&metadata_lock);
 				res->hr_syncsrc = HAST_SYNCSRC_UNDEF;
@@ -1950,7 +1953,6 @@ guard_thread(void *arg)
 	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
 	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
 	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
-	PJDLOG_VERIFY(sigaddset(&mask, SIGCHLD) == 0);
 
 	timeout.tv_nsec = 0;
 	signo = -1;
@@ -1969,7 +1971,6 @@ guard_thread(void *arg)
 		default:
 			break;
 		}
-		hook_check(signo == SIGCHLD);
 
 		pjdlog_debug(2, "remote_guard: Checking connections.");
 		now = time(NULL);
diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index d1575e8a5a7..14016f703db 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -54,6 +54,7 @@ __FBSDID("$FreeBSD$");
 #include 
 
 #include "control.h"
+#include "event.h"
 #include "hast.h"
 #include "hast_proto.h"
 #include "hastd.h"
@@ -325,7 +326,7 @@ init_remote(struct hast_resource *res, struct nv *nvin)
 	if (res->hr_secondary_localcnt > res->hr_primary_remotecnt &&
 	     res->hr_primary_localcnt > res->hr_secondary_remotecnt) {
 		/* Exit on split-brain. */
-		hook_exec(res->hr_exec, "split-brain", res->hr_name, NULL);
+		event_send(res, EVENT_SPLITBRAIN);
 		exit(EX_CONFIG);
 	}
 }
@@ -345,6 +346,14 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 		pjdlog_exit(EX_OSERR,
 		    "Unable to create control sockets between parent and child");
 	}
+	/*
+	 * Create communication channel between child and parent.
+	 */
+	if (proto_client("socketpair://", &res->hr_event) < 0) {
+		KEEP_ERRNO((void)pidfile_remove(pfh));
+		pjdlog_exit(EX_OSERR,
+		    "Unable to create event sockets between child and parent");
+	}
 
 	pid = fork();
 	if (pid < 0) {
@@ -358,6 +367,8 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 		res->hr_remotein = NULL;
 		proto_close(res->hr_remoteout);
 		res->hr_remoteout = NULL;
+		/* Declare that we are receiver. */
+		proto_recv(res->hr_event, NULL, 0);
 		res->hr_workerpid = pid;
 		return;
 	}
@@ -372,17 +383,19 @@ hastd_secondary(struct hast_resource *res, struct nv *nvin)
 	signal(SIGHUP, SIG_DFL);
 	signal(SIGCHLD, SIG_DFL);
 
+	/* Declare that we are sender. */
+	proto_send(res->hr_event, NULL, 0);
+
 	/* Error in setting timeout is not critical, but why should it fail? */
 	if (proto_timeout(res->hr_remotein, 0) < 0)
 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
 	if (proto_timeout(res->hr_remoteout, res->hr_timeout) < 0)
 		pjdlog_errno(LOG_WARNING, "Unable to set connection timeout");
 
-	hook_init();
 	init_local(res);
 	init_remote(res, nvin);
 	init_environment();
-	hook_exec(res->hr_exec, "connect", res->hr_name, NULL);
+	event_send(res, EVENT_CONNECT);
 
 	error = pthread_create(&td, NULL, recv_thread, res);
 	assert(error == 0);
@@ -515,7 +528,7 @@ secondary_exit(int exitcode, const char *fmt, ...)
 	va_start(ap, fmt);
 	pjdlogv_errno(LOG_ERR, fmt, ap);
 	va_end(ap);
-	hook_exec(gres->hr_exec, "disconnect", gres->hr_name, NULL);
+	event_send(gres, EVENT_DISCONNECT);
 	exit(exitcode);
 }
 

From 2d0c83b139646fe95441531071a719b67e2d05d7 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Tue, 31 Aug 2010 01:16:45 +0000
Subject: [PATCH 0378/1624] Add a null_remove() function to nullfs, so that the
 v_usecount of the lower level vnode is incremented to greater than 1 when the
 upper level vnode's v_usecount is greater than one. This is necessary for the
 NFS clients, so that they will do a silly rename of the file instead of
 actually removing it when the file is still in use. It is "racy", since the
 v_usecount is incremented in many places in the kernel with minimal
 synchronization, but an extraneous silly rename is preferred to not doing a
 silly rename when it is required. The only other file systems that currently
 check the value of v_usecount in their VOP_REMOVE() functions are nwfs and
 smbfs. These file systems choose to fail a remove when the v_usecount is
 greater than 1 and I believe will function more correctly with this patch, as
 well.

Tested by:	to.my.trociny at gmail.com
Submitted by:	to.my.trociny at gmail.com (earlier version)
Reviewed by:	kib
MFC after:	2 weeks
---
 sys/fs/nullfs/null_vnops.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/sys/fs/nullfs/null_vnops.c b/sys/fs/nullfs/null_vnops.c
index af49e3e18c1..b86ba83cb30 100644
--- a/sys/fs/nullfs/null_vnops.c
+++ b/sys/fs/nullfs/null_vnops.c
@@ -498,6 +498,32 @@ null_accessx(struct vop_accessx_args *ap)
 	return (null_bypass((struct vop_generic_args *)ap));
 }
 
+/*
+ * Increasing refcount of lower vnode is needed at least for the case
+ * when lower FS is NFS to do sillyrename if the file is in use.
+ * Unfortunately v_usecount is incremented in many places in
+ * the kernel and, as such, there may be races that result in
+ * the NFS client doing an extraneous silly rename, but that seems
+ * preferable to not doing a silly rename when it is needed.
+ */
+static int
+null_remove(struct vop_remove_args *ap)
+{
+	int retval, vreleit;
+	struct vnode *lvp;
+
+	if (vrefcnt(ap->a_vp) > 1) {
+		lvp = NULLVPTOLOWERVP(ap->a_vp);
+		VREF(lvp);
+		vreleit = 1;
+	} else
+		vreleit = 0;
+	retval = null_bypass(&ap->a_gen);
+	if (vreleit != 0)
+		vrele(lvp);
+	return (retval);
+}
+
 /*
  * We handle this to eliminate null FS to lower FS
  * file moving. Don't know why we don't allow this,
@@ -809,6 +835,7 @@ struct vop_vector null_vnodeops = {
 	.vop_open =		null_open,
 	.vop_print =		null_print,
 	.vop_reclaim =		null_reclaim,
+	.vop_remove =		null_remove,
 	.vop_rename =		null_rename,
 	.vop_setattr =		null_setattr,
 	.vop_strategy =		VOP_EOPNOTSUPP,

From 1264a5f4c51bfb723c47b2b9419f8c89d0e80ebf Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Tue, 31 Aug 2010 02:07:13 +0000
Subject: [PATCH 0379/1624] Missed one place the SLB lock should be held in
 r211967.

---
 sys/powerpc/aim/mmu_oea64.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index c1c2651c5c0..cc7f3878e92 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -2232,12 +2232,14 @@ moea64_qremove(mmu_t mmu, vm_offset_t va, int count)
 void
 moea64_release_vsid(uint64_t vsid)
 {
-        int idx, mask;
+	int idx, mask;
 
-        idx = vsid & (NVSIDS-1);
-        mask = 1 << (idx % VSID_NBPW);
-        idx /= VSID_NBPW;
-        moea64_vsid_bitmap[idx] &= ~mask;
+	mtx_lock(&moea64_slb_mutex);
+	idx = vsid & (NVSIDS-1);
+	mask = 1 << (idx % VSID_NBPW);
+	idx /= VSID_NBPW;
+	moea64_vsid_bitmap[idx] &= ~mask;
+	mtx_unlock(&moea64_slb_mutex);
 }
 	
 
@@ -2253,7 +2255,7 @@ moea64_release(mmu_t mmu, pmap_t pmap)
 	slb_free_user_cache(pmap->pm_slb);
     #else
         if (pmap->pm_sr[0] == 0)
-                panic("moea64_release");
+                panic("moea64_release: pm_sr[0] = 0");
 
 	moea64_release_vsid(pmap->pm_sr[0]);
     #endif

From 55d308bc948d6a475c3b7c689099add504567a35 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Tue, 31 Aug 2010 04:18:47 +0000
Subject: [PATCH 0380/1624] Add the workaround for 4xx lite boards after it was
 lost in the last board.c update.

---
 sys/mips/rmi/board.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/sys/mips/rmi/board.c b/sys/mips/rmi/board.c
index ea5f3c9c4f2..26658a5cc0d 100644
--- a/sys/mips/rmi/board.c
+++ b/sys/mips/rmi/board.c
@@ -188,6 +188,23 @@ xls_board_specific_overrides(struct xlr_board_info* board)
 		blk1->gmac_port[1].mdint_id = 0;
 		blk1->gmac_port[2].mdint_id = 0;
 		blk1->gmac_port[3].mdint_id = 0;
+
+		/* If we have a 4xx lite chip, don't enable the 
+		 * GMACs which are disabled in hardware */
+		if (xlr_is_xls4xx_lite()) {
+			xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_GPIO_OFFSET);
+			uint32_t tmp;
+
+			/* Port 6 & 7 are not enabled on the condor 4xx, figure
+			 * this out from the GPIO fuse bank */
+			tmp = xlr_read_reg(mmio, 35);
+			if ((tmp & (3 << 28)) != 0) {
+				blk1->enabled = 0x3;
+				blk1->gmac_port[2].valid = 0;
+				blk1->gmac_port[3].valid = 0;
+				blk1->num_ports = 2;
+			}
+		}
 		break;
 
 	case RMI_XLR_BOARD_ARIZONA_VIII:

From 852ac373cb1334c843dcb658dfb3a616fe2c8d95 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 31 Aug 2010 06:22:03 +0000
Subject: [PATCH 0381/1624] Mask only those signals that we want to handle.

Suggested by:	jilles
MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/primary.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/sbin/hastd/primary.c b/sbin/hastd/primary.c
index a8a2d41f87a..6f0995bb741 100644
--- a/sbin/hastd/primary.c
+++ b/sbin/hastd/primary.c
@@ -424,7 +424,10 @@ init_environment(struct hast_resource *res __unused)
 	/*
 	 * Turn on signals handling.
 	 */
-	PJDLOG_VERIFY(sigfillset(&mask) == 0);
+	PJDLOG_VERIFY(sigemptyset(&mask) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGHUP) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGINT) == 0);
+	PJDLOG_VERIFY(sigaddset(&mask, SIGTERM) == 0);
 	PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
 }
 

From 83b718eb07be2da422633a97298fb549aed1d711 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Tue, 31 Aug 2010 07:15:50 +0000
Subject: [PATCH 0382/1624] If a process is being debugged, skips job control
 caused by SIGSTOP/SIGCONT signals, because it is managed by debugger, however
 a normal signal sent to a interruptibly sleeping thread wakes up the thread
 so it will handle the signal when the process leaves the stopped state.

PR:	150138
MFC after:	1 week
---
 sys/kern/kern_sig.c | 19 ++++++-------------
 1 file changed, 6 insertions(+), 13 deletions(-)

diff --git a/sys/kern/kern_sig.c b/sys/kern/kern_sig.c
index c620bdc21bd..9cbbe8d6c97 100644
--- a/sys/kern/kern_sig.c
+++ b/sys/kern/kern_sig.c
@@ -2139,20 +2139,9 @@ tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
 	 * We try do the per-process part here.
 	 */
 	if (P_SHOULDSTOP(p)) {
-		/*
-		 * The process is in stopped mode. All the threads should be
-		 * either winding down or already on the suspended queue.
-		 */
-		if (p->p_flag & P_TRACED) {
-			/*
-			 * The traced process is already stopped,
-			 * so no further action is necessary.
-			 * No signal can restart us.
-			 */
-			goto out;
-		}
-
 		if (sig == SIGKILL) {
+			if (p->p_flag & P_TRACED)
+				goto out;
 			/*
 			 * SIGKILL sets process running.
 			 * It will die elsewhere.
@@ -2163,6 +2152,8 @@ tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
 		}
 
 		if (prop & SA_CONT) {
+			if (p->p_flag & P_TRACED)
+				goto out;
 			/*
 			 * If SIGCONT is default (or ignored), we continue the
 			 * process but don't leave the signal in sigqueue as
@@ -2207,6 +2198,8 @@ tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
 		}
 
 		if (prop & SA_STOP) {
+			if (p->p_flag & P_TRACED)
+				goto out;
 			/*
 			 * Already stopped, don't need to stop again
 			 * (If we did the shell could get confused).

From 34759932a8c5b0de7a43f59aeb02de70ecb8aeea Mon Sep 17 00:00:00 2001
From: Kevin Lo 
Date: Tue, 31 Aug 2010 07:19:10 +0000
Subject: [PATCH 0383/1624] For consistency, cast result of getpid() to long

---
 usr.bin/usbhidaction/usbhidaction.c | 3 ++-
 usr.sbin/apmd/apmd.c                | 2 +-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/usr.bin/usbhidaction/usbhidaction.c b/usr.bin/usbhidaction/usbhidaction.c
index fc78d4e31cb..142e3cc8a3a 100644
--- a/usr.bin/usbhidaction/usbhidaction.c
+++ b/usr.bin/usbhidaction/usbhidaction.c
@@ -165,7 +165,8 @@ main(int argc, char **argv)
 	if (demon) {
 		fp = open(pidfile, O_WRONLY|O_CREAT, S_IRUSR|S_IRGRP|S_IROTH);
 		if (fp >= 0) {
-			sz1 = snprintf(buf, sizeof buf, "%d\n", getpid());
+			sz1 = snprintf(buf, sizeof buf, "%ld\n", 
+			    (long)getpid());
 			if (sz1 > sizeof buf)
 				sz1 = sizeof buf;
 			write(fp, buf, sz1);
diff --git a/usr.sbin/apmd/apmd.c b/usr.sbin/apmd/apmd.c
index f6654d58f12..585383c7221 100644
--- a/usr.sbin/apmd/apmd.c
+++ b/usr.sbin/apmd/apmd.c
@@ -435,7 +435,7 @@ write_pid(void)
 	FILE *fp = fopen(apmd_pidfile, "w");
 
 	if (fp) {
-		fprintf(fp, "%d\n", getpid());
+		fprintf(fp, "%ld\n", (long)getpid());
 		fclose(fp);
 	}
 }

From 71c895eb1fb680a5d9783e99da84dd0bcbeb830c Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 31 Aug 2010 09:38:43 +0000
Subject: [PATCH 0384/1624] Forgot to add event.c and event.h in r212038.

Pointed out by:	pluknet 
MFC after:	2 weeks
Obtained from:	Wheel Systems Sp. z o.o. http://www.wheelsystems.com
---
 sbin/hastd/event.c | 162 +++++++++++++++++++++++++++++++++++++++++++++
 sbin/hastd/event.h |  46 +++++++++++++
 2 files changed, 208 insertions(+)
 create mode 100644 sbin/hastd/event.c
 create mode 100644 sbin/hastd/event.h

diff --git a/sbin/hastd/event.c b/sbin/hastd/event.c
new file mode 100644
index 00000000000..d772f692ba2
--- /dev/null
+++ b/sbin/hastd/event.c
@@ -0,0 +1,162 @@
+/*-
+ * Copyright (c) 2010 Pawel Jakub Dawidek 
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+
+#include "hast.h"
+#include "hast_proto.h"
+#include "hooks.h"
+#include "nv.h"
+#include "pjdlog.h"
+#include "proto.h"
+#include "subr.h"
+
+#include "event.h"
+
+void
+event_send(const struct hast_resource *res, int event)
+{
+	struct nv *nvin, *nvout;
+	int error;
+
+	assert(res != NULL);
+	assert(event >= EVENT_MIN && event <= EVENT_MAX);
+
+	nvin = nvout = NULL;
+
+	/*
+	 * Prepare and send event to parent process.
+	 */
+	nvout = nv_alloc();
+	nv_add_uint8(nvout, (uint8_t)event, "event");
+	error = nv_error(nvout);
+	if (error != 0) {
+		pjdlog_common(LOG_ERR, 0, error,
+		    "Unable to prepare event header");
+		goto done;
+	}
+	if (hast_proto_send(res, res->hr_event, nvout, NULL, 0) < 0) {
+		pjdlog_errno(LOG_ERR, "Unable to send event header");
+		goto done;
+	}
+	if (hast_proto_recv_hdr(res->hr_event, &nvin) < 0) {
+		pjdlog_errno(LOG_ERR, "Unable to receive event header");
+		goto done;
+	}
+	/*
+	 * Do nothing with the answer. We only wait for it to be sure not
+	 * to exit too quickly after sending an event and exiting immediately.
+	 */
+done:
+	if (nvin != NULL)
+		nv_free(nvin);
+	if (nvout != NULL)
+		nv_free(nvout);
+}
+
+int
+event_recv(const struct hast_resource *res)
+{
+	struct nv *nvin, *nvout;
+	const char *evstr;
+	uint8_t event;
+	int error;
+
+	assert(res != NULL);
+
+	nvin = nvout = NULL;
+
+	if (hast_proto_recv_hdr(res->hr_event, &nvin) < 0) {
+		/*
+		 * First error log as debug. This is because worker process
+		 * most likely exited.
+		 */
+		pjdlog_common(LOG_DEBUG, 1, errno,
+		    "Unable to receive event header");
+		goto fail;
+	}
+
+	event = nv_get_uint8(nvin, "event");
+	if (event == EVENT_NONE) {
+		pjdlog_error("Event header is missing 'event' field.");
+		goto fail;
+	}
+
+	switch (event) {
+	case EVENT_CONNECT:
+		evstr = "connect";
+		break;
+	case EVENT_DISCONNECT:
+		evstr = "disconnect";
+		break;
+	case EVENT_SYNCSTART:
+		evstr = "syncstart";
+		break;
+	case EVENT_SYNCDONE:
+		evstr = "syncdone";
+		break;
+	case EVENT_SYNCINTR:
+		evstr = "syncintr";
+		break;
+	case EVENT_SPLITBRAIN:
+		evstr = "split-brain";
+		break;
+	default:
+		pjdlog_error("Event header contain invalid event number (%hhu).",
+		    event);
+		goto fail;
+	}
+
+	pjdlog_prefix_set("[%s] (%s) ", res->hr_name, role2str(res->hr_role));
+	hook_exec(res->hr_exec, evstr, res->hr_name, NULL);
+	pjdlog_prefix_set("%s", "");
+
+	nvout = nv_alloc();
+	nv_add_int16(nvout, 0, "error");
+	error = nv_error(nvout);
+	if (error != 0) {
+		pjdlog_common(LOG_ERR, 0, error,
+		    "Unable to prepare event header");
+		goto fail;
+	}
+	if (hast_proto_send(res, res->hr_event, nvout, NULL, 0) < 0) {
+		pjdlog_errno(LOG_ERR, "Unable to send event header");
+		goto fail;
+	}
+	nv_free(nvin);
+	nv_free(nvout);
+	return (0);
+fail:
+	if (nvin != NULL)
+		nv_free(nvin);
+	if (nvout != NULL)
+		nv_free(nvout);
+	return (-1);
+}
diff --git a/sbin/hastd/event.h b/sbin/hastd/event.h
new file mode 100644
index 00000000000..1614bf19916
--- /dev/null
+++ b/sbin/hastd/event.h
@@ -0,0 +1,46 @@
+/*-
+ * Copyright (c) 2010 Pawel Jakub Dawidek 
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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.
+ *
+ * $FreeBSD$
+ */
+
+#ifndef	_EVENT_H_
+#define	_EVENT_H_
+
+#define	EVENT_NONE		0
+#define	EVENT_CONNECT		1
+#define	EVENT_DISCONNECT	2
+#define	EVENT_SYNCSTART		3
+#define	EVENT_SYNCDONE		4
+#define	EVENT_SYNCINTR		5
+#define	EVENT_SPLITBRAIN	6
+
+#define	EVENT_MIN		EVENT_CONNECT
+#define	EVENT_MAX		EVENT_SPLITBRAIN
+
+void event_send(const struct hast_resource *res, int event);
+int event_recv(const struct hast_resource *res);
+
+#endif	/* !_EVENT_H_ */

From 0b887306623afaf9c038c5ce8990131767343dec Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 31 Aug 2010 10:41:53 +0000
Subject: [PATCH 0385/1624] When upgrading a pool which contain root file
 system, give user a hint that he should update boot code.

MFC after:	2 weeks
---
 .../opensolaris/cmd/zpool/zpool_main.c        | 47 +++++++++++++++++++
 1 file changed, 47 insertions(+)

diff --git a/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c b/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
index abfd062d790..2d9891674a7 100644
--- a/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
+++ b/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
@@ -3333,11 +3333,38 @@ typedef struct upgrade_cbdata {
 	int	cb_all;
 	int	cb_first;
 	int	cb_newer;
+	char	cb_poolname[ZPOOL_MAXNAMELEN];
 	int	cb_argc;
 	uint64_t cb_version;
 	char	**cb_argv;
 } upgrade_cbdata_t;
 
+static int
+is_root_pool(zpool_handle_t *zhp)
+{
+	static struct statfs sfs;
+	static char *poolname = NULL;
+	static boolean_t stated = B_FALSE;
+	char *slash;
+
+	while (!stated) {
+		stated = B_TRUE;
+		if (statfs("/", &sfs) == -1) {
+			(void) fprintf(stderr,
+			    "Unable to stat root file system: %s.\n",
+			    strerror(errno));
+			break;
+		}
+		if (strcmp(sfs.f_fstypename, "zfs") != 0)
+			break;
+		poolname = sfs.f_mntfromname;
+		if ((slash = strchr(poolname, '/')) != NULL)
+			*slash = '\0';
+		break;
+	}
+	return (poolname != NULL && strcmp(poolname, zpool_get_name(zhp)) == 0);
+}
+
 static int
 upgrade_cb(zpool_handle_t *zhp, void *arg)
 {
@@ -3371,6 +3398,12 @@ upgrade_cb(zpool_handle_t *zhp, void *arg)
 			if (!ret) {
 				(void) printf(gettext("Successfully upgraded "
 				    "'%s'\n\n"), zpool_get_name(zhp));
+				if (cbp->cb_poolname[0] == '\0' &&
+				    is_root_pool(zhp)) {
+					(void) strlcpy(cbp->cb_poolname,
+					    zpool_get_name(zhp),
+					    sizeof(cbp->cb_poolname));
+				}
 			}
 		}
 	} else if (cbp->cb_newer && version > SPA_VERSION) {
@@ -3428,6 +3461,10 @@ upgrade_one(zpool_handle_t *zhp, void *data)
 		    "from version %llu to version %llu\n\n"),
 		    zpool_get_name(zhp), (u_longlong_t)cur_version,
 		    (u_longlong_t)cbp->cb_version);
+		if (cbp->cb_poolname[0] == '\0' && is_root_pool(zhp)) {
+			(void) strlcpy(cbp->cb_poolname, zpool_get_name(zhp),
+			    sizeof(cbp->cb_poolname));
+		}
 	}
 
 	return (ret != 0);
@@ -3569,6 +3606,16 @@ zpool_do_upgrade(int argc, char **argv)
 		    upgrade_one, &cb);
 	}
 
+	if (cb.cb_poolname[0] != '\0') {
+		(void) printf(
+		    "If you boot from pool '%s', don't forget to update boot code.\n"
+		    "Assuming you use GPT partitioning and da0 is your boot disk\n"
+		    "the following command will do it:\n"
+		    "\n"
+		    "\tgpart bootcode -b /boot/pmbr -p /boot/gptzfsboot -i 1 da0\n\n",
+		    cb.cb_poolname);
+	}
+
 	return (ret);
 }
 

From 8ecdeae9d92001eb5684ac8853692dcc325d9e56 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 31 Aug 2010 12:03:29 +0000
Subject: [PATCH 0386/1624] Correct error message.

Submitted by:	Mikolaj Golub 
MFC after:	2 weeks
---
 sbin/hastd/secondary.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sbin/hastd/secondary.c b/sbin/hastd/secondary.c
index 14016f703db..fa898ecd0f5 100644
--- a/sbin/hastd/secondary.c
+++ b/sbin/hastd/secondary.c
@@ -569,7 +569,7 @@ recv_thread(void *arg)
 			if (hast_proto_recv_data(res, res->hr_remotein,
 			    hio->hio_nv, hio->hio_data, MAXPHYS) < 0) {
 				secondary_exit(EX_TEMPFAIL,
-				    "Unable to receive reply data");
+				    "Unable to receive request data");
 			}
 		}
 		pjdlog_debug(2, "recv: (%p) Moving request to the disk queue.",

From 6d19256b15d4d8eccf68ae15d439b6dd8816417f Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 31 Aug 2010 12:05:13 +0000
Subject: [PATCH 0387/1624] Include process PID in log messages.

Submitted by:	Mikolaj Golub 
MFC after:	2 weeks
---
 sbin/hastd/pjdlog.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/sbin/hastd/pjdlog.c b/sbin/hastd/pjdlog.c
index ef3026f7745..89121058629 100644
--- a/sbin/hastd/pjdlog.c
+++ b/sbin/hastd/pjdlog.c
@@ -57,6 +57,9 @@ pjdlog_mode_set(int mode)
 	assert(mode == PJDLOG_MODE_STD || mode == PJDLOG_MODE_SYSLOG);
 
 	pjdlog_mode = mode;
+
+	if (mode == PJDLOG_MODE_SYSLOG)
+		openlog(NULL, LOG_PID, LOG_DAEMON);
 }
 
 /*

From 68181d0091629a04de47868fed0c079acb4cf165 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Tue, 31 Aug 2010 15:22:09 +0000
Subject: [PATCH 0388/1624] Remove some code made obsolete by the powerpc64
 import.

---
 sys/powerpc/aim/trap_subr.S | 677 ------------------------------------
 1 file changed, 677 deletions(-)
 delete mode 100644 sys/powerpc/aim/trap_subr.S

diff --git a/sys/powerpc/aim/trap_subr.S b/sys/powerpc/aim/trap_subr.S
deleted file mode 100644
index 5d9596b5184..00000000000
--- a/sys/powerpc/aim/trap_subr.S
+++ /dev/null
@@ -1,677 +0,0 @@
-/* $FreeBSD$ */
-/* $NetBSD: trap_subr.S,v 1.20 2002/04/22 23:20:08 kleink Exp $	*/
-
-/*-
- * Copyright (C) 1995, 1996 Wolfgang Solfrank.
- * Copyright (C) 1995, 1996 TooLs GmbH.
- * 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 TooLs GmbH.
- * 4. The name of TooLs GmbH may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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.
- */
-
-/*
- * NOTICE: This is not a standalone file.  to use it, #include it in
- * your port's locore.S, like so:
- *
- *	#include 
- */
-
-/*
- * Save/restore segment registers
- */
-#define RESTORE_SRS(pmap,sr)	mtsr    0,sr; \
-	lwz	sr,1*4(pmap);	mtsr	1,sr; \
-	lwz	sr,2*4(pmap);	mtsr	2,sr; \
-	lwz	sr,3*4(pmap);	mtsr	3,sr; \
-	lwz	sr,4*4(pmap);	mtsr	4,sr; \
-	lwz	sr,5*4(pmap);	mtsr	5,sr; \
-	lwz	sr,6*4(pmap);	mtsr	6,sr; \
-	lwz	sr,7*4(pmap);	mtsr	7,sr; \
-	lwz	sr,8*4(pmap);	mtsr	8,sr; \
-	lwz	sr,9*4(pmap);	mtsr	9,sr; \
-	lwz	sr,10*4(pmap);	mtsr	10,sr; \
-	lwz	sr,11*4(pmap);	mtsr	11,sr; \
-	lwz	sr,12*4(pmap);	mtsr	12,sr; \
-	lwz	sr,13*4(pmap);	mtsr	13,sr; \
-	lwz	sr,14*4(pmap);	mtsr	14,sr; \
-	lwz	sr,15*4(pmap);	mtsr	15,sr; isync;
-
-/*
- * User SRs are loaded through a pointer to the current pmap.
- */
-#define RESTORE_USER_SRS(pmap,sr) \
-	GET_CPUINFO(pmap); \
-	lwz	pmap,PC_CURPMAP(pmap); \
-	lwzu	sr,PM_SR(pmap); \
-	RESTORE_SRS(pmap,sr)
-
-/*
- * Kernel SRs are loaded directly from kernel_pmap_
- */
-#define RESTORE_KERN_SRS(pmap,sr) \
-	lis	pmap,CNAME(kernel_pmap_store)@ha; \
-	lwzu	sr,CNAME(kernel_pmap_store)+PM_SR@l(pmap); \
-	RESTORE_SRS(pmap,sr)
-
-/*
- * FRAME_SETUP assumes:
- *	SPRG1		SP (1)
- * 	SPRG3		trap type
- *	savearea	r28-r31,DAR,DSISR   (DAR & DSISR only for DSI traps)
- *	r28		LR
- *	r29		CR
- *	r30		scratch
- *	r31		scratch
- *	r1		kernel stack
- *	SRR0/1		as at start of trap
- */
-#define	FRAME_SETUP(savearea)						\
-/* Have to enable translation to allow access of kernel stack: */	\
-	GET_CPUINFO(%r31);						\
-	mfsrr0	%r30;							\
-	stw	%r30,(savearea+CPUSAVE_SRR0)(%r31);	/* save SRR0 */	\
-	mfsrr1	%r30;							\
-	stw	%r30,(savearea+CPUSAVE_SRR1)(%r31);	/* save SRR1 */	\
-	mfmsr	%r30;							\
-	ori	%r30,%r30,(PSL_DR|PSL_IR|PSL_RI)@l; /* relocation on */	\
-	mtmsr	%r30;			/* stack can now be accessed */	\
-	isync;								\
-	mfsprg1	%r31;			/* get saved SP */		\
-	stwu	%r31,-FRAMELEN(%r1);	/* save it in the callframe */	\
-	stw	%r0, FRAME_0+8(%r1);	/* save r0 in the trapframe */	\
-	stw	%r31,FRAME_1+8(%r1);	/* save SP   "      "       */	\
-	stw	%r2, FRAME_2+8(%r1);	/* save r2   "      "       */	\
-	stw	%r28,FRAME_LR+8(%r1);	/* save LR   "      "       */	\
-	stw	%r29,FRAME_CR+8(%r1);	/* save CR   "      "       */	\
-	GET_CPUINFO(%r2);						\
-	lwz	%r28,(savearea+CPUSAVE_R28)(%r2); /* get saved r28 */	\
-	lwz	%r29,(savearea+CPUSAVE_R29)(%r2); /* get saved r29 */	\
-	lwz	%r30,(savearea+CPUSAVE_R30)(%r2); /* get saved r30 */	\
-	lwz	%r31,(savearea+CPUSAVE_R31)(%r2); /* get saved r31 */	\
-	stw	%r3,  FRAME_3+8(%r1);	/* save r3-r31 */		\
-	stw	%r4,  FRAME_4+8(%r1);					\
-	stw	%r5,  FRAME_5+8(%r1);					\
-	stw	%r6,  FRAME_6+8(%r1);					\
-	stw	%r7,  FRAME_7+8(%r1);					\
-	stw	%r8,  FRAME_8+8(%r1);					\
-	stw	%r9,  FRAME_9+8(%r1);					\
-	stw	%r10, FRAME_10+8(%r1);					\
-	stw	%r11, FRAME_11+8(%r1);					\
-	stw	%r12, FRAME_12+8(%r1);					\
-	stw	%r13, FRAME_13+8(%r1);					\
-	stw	%r14, FRAME_14+8(%r1);					\
-	stw	%r15, FRAME_15+8(%r1);					\
-	stw	%r16, FRAME_16+8(%r1);					\
-	stw	%r17, FRAME_17+8(%r1);					\
-	stw	%r18, FRAME_18+8(%r1);					\
-	stw	%r19, FRAME_19+8(%r1);					\
-	stw	%r20, FRAME_20+8(%r1);					\
-	stw	%r21, FRAME_21+8(%r1);					\
-	stw	%r22, FRAME_22+8(%r1);					\
-	stw	%r23, FRAME_23+8(%r1);					\
-	stw	%r24, FRAME_24+8(%r1);					\
-	stw	%r25, FRAME_25+8(%r1);					\
-	stw	%r26, FRAME_26+8(%r1);					\
-	stw	%r27, FRAME_27+8(%r1);					\
-	stw	%r28, FRAME_28+8(%r1);					\
-	stw	%r29, FRAME_29+8(%r1);					\
-	stw	%r30, FRAME_30+8(%r1);					\
-	stw	%r31, FRAME_31+8(%r1);					\
-	lwz	%r28,(savearea+CPUSAVE_AIM_DAR)(%r2);  /* saved DAR */	\
-	lwz	%r29,(savearea+CPUSAVE_AIM_DSISR)(%r2);/* saved DSISR */\
-	lwz	%r30,(savearea+CPUSAVE_SRR0)(%r2); /* saved SRR0 */	\
-	lwz	%r31,(savearea+CPUSAVE_SRR1)(%r2); /* saved SRR1 */	\
-	mfxer	%r3;							\
-	mfctr	%r4;							\
-	mfsprg3	%r5;							\
-	stw	%r3, FRAME_XER+8(1);	/* save xer/ctr/exc */		\
-	stw	%r4, FRAME_CTR+8(1);					\
-	stw	%r5, FRAME_EXC+8(1);					\
-	stw	%r28,FRAME_AIM_DAR+8(1);				\
-	stw	%r29,FRAME_AIM_DSISR+8(1); /* save dsisr/srr0/srr1 */	\
-	stw	%r30,FRAME_SRR0+8(1);					\
-	stw	%r31,FRAME_SRR1+8(1)
-
-#define	FRAME_LEAVE(savearea)						\
-/* Now restore regs: */							\
-	lwz	%r2,FRAME_SRR0+8(%r1);					\
-	lwz	%r3,FRAME_SRR1+8(%r1);					\
-	lwz	%r4,FRAME_CTR+8(%r1);					\
-	lwz	%r5,FRAME_XER+8(%r1);					\
-	lwz	%r6,FRAME_LR+8(%r1);					\
-	GET_CPUINFO(%r7);						\
-	stw	%r2,(savearea+CPUSAVE_SRR0)(%r7); /* save SRR0 */	\
-	stw	%r3,(savearea+CPUSAVE_SRR1)(%r7); /* save SRR1 */	\
-	lwz	%r7,FRAME_CR+8(%r1);					\
-	mtctr	%r4;							\
-	mtxer	%r5;							\
-	mtlr	%r6;							\
-	mtsprg1	%r7;			/* save cr */			\
-	lwz	%r31,FRAME_31+8(%r1);   /* restore r0-31 */		\
-	lwz	%r30,FRAME_30+8(%r1);					\
-	lwz	%r29,FRAME_29+8(%r1);					\
-	lwz	%r28,FRAME_28+8(%r1);					\
-	lwz	%r27,FRAME_27+8(%r1);					\
-	lwz	%r26,FRAME_26+8(%r1);					\
-	lwz	%r25,FRAME_25+8(%r1);					\
-	lwz	%r24,FRAME_24+8(%r1);					\
-	lwz	%r23,FRAME_23+8(%r1);					\
-	lwz	%r22,FRAME_22+8(%r1);					\
-	lwz	%r21,FRAME_21+8(%r1);					\
-	lwz	%r20,FRAME_20+8(%r1);					\
-	lwz	%r19,FRAME_19+8(%r1);					\
-	lwz	%r18,FRAME_18+8(%r1);					\
-	lwz	%r17,FRAME_17+8(%r1);					\
-	lwz	%r16,FRAME_16+8(%r1);					\
-	lwz	%r15,FRAME_15+8(%r1);					\
-	lwz	%r14,FRAME_14+8(%r1);					\
-	lwz	%r13,FRAME_13+8(%r1);					\
-	lwz	%r12,FRAME_12+8(%r1);					\
-	lwz	%r11,FRAME_11+8(%r1);					\
-	lwz	%r10,FRAME_10+8(%r1);					\
-	lwz	%r9, FRAME_9+8(%r1);					\
-	lwz	%r8, FRAME_8+8(%r1);					\
-	lwz	%r7, FRAME_7+8(%r1);					\
-	lwz	%r6, FRAME_6+8(%r1);					\
-	lwz	%r5, FRAME_5+8(%r1);					\
-	lwz	%r4, FRAME_4+8(%r1);					\
-	lwz	%r3, FRAME_3+8(%r1);					\
-	lwz	%r2, FRAME_2+8(%r1);					\
-	lwz	%r0, FRAME_0+8(%r1);					\
-	lwz	%r1, FRAME_1+8(%r1);					\
-/* Can't touch %r1 from here on */					\
-	mtsprg2	%r2;			/* save r2 & r3 */		\
-	mtsprg3	%r3;							\
-/* Disable translation, machine check and recoverability: */		\
-	mfmsr	%r2;							\
-	andi.	%r2,%r2,~(PSL_DR|PSL_IR|PSL_EE|PSL_ME|PSL_RI)@l;	\
-	mtmsr	%r2;							\
-	isync;								\
-/* Decide whether we return to user mode: */				\
-	GET_CPUINFO(%r2);						\
-	lwz	%r3,(savearea+CPUSAVE_SRR1)(%r2);			\
-	mtcr	%r3;							\
-	bf	17,1f;			/* branch if PSL_PR is false */	\
-/* Restore user SRs */							\
-	RESTORE_USER_SRS(%r2,%r3);					\
-1:	mfsprg1	%r2;			/* restore cr */		\
-	mtcr	%r2;							\
-	GET_CPUINFO(%r2);						\
-	lwz	%r3,(savearea+CPUSAVE_SRR0)(%r2); /* restore srr0 */	\
-	mtsrr0	%r3;							\
-	lwz	%r3,(savearea+CPUSAVE_SRR1)(%r2); /* restore srr1 */	\
-									\
-	/* Make sure HV bit of MSR propagated to SRR1 */		\
-	mfmsr	%r2;							\
-	or	%r3,%r2,%r3;						\
-									\
-	mtsrr1	%r3;							\
-	mfsprg2	%r2;			/* restore r2 & r3 */		\
-	mfsprg3	%r3
-
-/*
- * The next two routines are 64-bit glue code. The first is used to test if
- * we are on a 64-bit system. By copying it to the illegal instruction
- * handler, we can test for 64-bit mode by trying to execute a 64-bit
- * instruction and seeing what happens. The second gets copied in front
- * of all the other handlers to restore 32-bit bridge mode when traps
- * are taken.
- */
-
-/* 64-bit test code. Sets SPRG2 to 0 if an illegal instruction is executed */
-
-	.globl	CNAME(testppc64),CNAME(testppc64size)
-CNAME(testppc64):
-	mtsprg1 %r31
-	mfsrr0  %r31
-	addi	%r31, %r31, 4
-	mtsrr0  %r31
-
-	li	%r31, 0
-	mtsprg2 %r31
-	mfsprg1 %r31
-
-	rfi
-CNAME(testppc64size) = .-CNAME(testppc64)
-
-
-/* 64-bit bridge mode restore snippet. Gets copied in front of everything else
- * on 64-bit systems. */
-
-	.globl	CNAME(restorebridge),CNAME(restorebridgesize)
-CNAME(restorebridge):
-	mtsprg1	%r31
-	mfmsr	%r31
-	clrldi	%r31,%r31,1
-	mtmsrd	%r31
-	mfsprg1	%r31
-	isync
-CNAME(restorebridgesize) = .-CNAME(restorebridge)
-
-#ifdef SMP
-/*
- * Processor reset exception handler. These are typically
- * the first instructions the processor executes after a
- * software reset. We do this in two bits so that we are
- * not still hanging around in the trap handling region
- * once the MMU is turned on.
- */
-	.globl	CNAME(rstcode), CNAME(rstsize)
-CNAME(rstcode):
-	ba	cpu_reset
-CNAME(rstsize) = . - CNAME(rstcode)
-
-cpu_reset:
-	bl	1f
-
-	.space	124
-
-1:
-	mflr	%r1
-	addi	%r1,%r1,(124-16)@l
-
-	lis	%r3,1@l
-	bla	CNAME(pmap_cpu_bootstrap)
-	bla	CNAME(cpudep_ap_bootstrap)
-	mr	%r1,%r3
-	bla	CNAME(machdep_ap_bootstrap)
-
-	/* Should not be reached */
-9:
-	b	9b
-#endif
-
-/*
- * This code gets copied to all the trap vectors
- * (except ISI/DSI, ALI, and the interrupts)
- */
-
-	.globl	CNAME(trapcode),CNAME(trapsize)
-CNAME(trapcode):
-	mtsprg1	%r1			/* save SP */
-	mflr	%r1			/* Save the old LR in r1 */
-	mtsprg2 %r1			/* And then in SPRG2 */
-	li	%r1, 0x20		/* How to get the vector from LR */
-	bla	generictrap		/* LR & SPRG3 is exception # */
-CNAME(trapsize) = .-CNAME(trapcode)
-
-/*
- * 64-bit version of trapcode. Identical, except it calls generictrap64.
- */
-	.globl	CNAME(trapcode64)
-CNAME(trapcode64):
-	mtsprg1	%r1			/* save SP */
-	mflr	%r1			/* Save the old LR in r1 */
-	mtsprg2 %r1			/* And then in SPRG2 */
-	li	%r1, 0x20		/* How to get the vector from LR */
-	bla	generictrap64		/* LR & SPRG3 is exception # */
-
-/*
- * For ALI: has to save DSISR and DAR
- */
-	.globl	CNAME(alitrap),CNAME(alisize)
-CNAME(alitrap):
-	mtsprg1	%r1			/* save SP */
-	GET_CPUINFO(%r1)
-	stw	%r28,(PC_TEMPSAVE+CPUSAVE_R28)(%r1)	/* free r28-r31 */
-	stw	%r29,(PC_TEMPSAVE+CPUSAVE_R29)(%r1)
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_R30)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_R31)(%r1)
-	mfdar	%r30
-	mfdsisr	%r31
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_AIM_DAR)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_AIM_DSISR)(%r1)
-	mfsprg1	%r1			/* restore SP, in case of branch */
-	mflr	%r28			/* save LR */
-	mfcr	%r29			/* save CR */
-
-	/* Put our exception vector in SPRG3 */
-	li	%r31, EXC_ALI
-	mtsprg3	%r31
-
-	/* Test whether we already had PR set */
-	mfsrr1	%r31
-	mtcr	%r31
-	bla	s_trap
-CNAME(alisize) = .-CNAME(alitrap)
-
-/*
- * Similar to the above for DSI
- * Has to handle BAT spills
- * and standard pagetable spills
- */
-	.globl	CNAME(dsitrap),CNAME(dsisize)
-CNAME(dsitrap):
-	mtsprg1	%r1			/* save SP */
-	GET_CPUINFO(%r1)
-	stw	%r28,(PC_DISISAVE+CPUSAVE_R28)(%r1)	/* free r28-r31 */
-	stw	%r29,(PC_DISISAVE+CPUSAVE_R29)(%r1)
-	stw	%r30,(PC_DISISAVE+CPUSAVE_R30)(%r1)
-	stw	%r31,(PC_DISISAVE+CPUSAVE_R31)(%r1)
-	mfsprg1	%r1			/* restore SP */
-	mfcr	%r29			/* save CR */
-	mfxer	%r30			/* save XER */
-	mtsprg2	%r30			/* in SPRG2 */
-	mfsrr1	%r31			/* test kernel mode */
-	mtcr	%r31
-	bt	17,1f			/* branch if PSL_PR is set */
-	mfdar	%r31			/* get fault address */
-	rlwinm	%r31,%r31,7,25,28	/* get segment * 8 */
-
-	/* get batu */
-	addis	%r31,%r31,CNAME(battable)@ha
-	lwz	%r30,CNAME(battable)@l(31)
-	mtcr	%r30
-	bf	30,1f			/* branch if supervisor valid is
-					   false */
-	/* get batl */
-	lwz	%r31,CNAME(battable)+4@l(31)
-/* We randomly use the highest two bat registers here */
-	mftb	%r28
-	andi.	%r28,%r28,1
-	bne	2f
-	mtdbatu	2,%r30
-	mtdbatl	2,%r31
-	b	3f
-2:
-	mtdbatu	3,%r30
-	mtdbatl	3,%r31
-3:
-	mfsprg2	%r30			/* restore XER */
-	mtxer	%r30
-	mtcr	%r29			/* restore CR */
-	mtsprg1	%r1
-	GET_CPUINFO(%r1)
-	lwz	%r28,(PC_DISISAVE+CPUSAVE_R28)(%r1)	/* restore r28-r31 */
-	lwz	%r29,(PC_DISISAVE+CPUSAVE_R29)(%r1)
-	lwz	%r30,(PC_DISISAVE+CPUSAVE_R30)(%r1)
-	lwz	%r31,(PC_DISISAVE+CPUSAVE_R31)(%r1)
-	mfsprg1	%r1
-	rfi				/* return to trapped code */
-1:
-	mflr	%r28			/* save LR (SP already saved) */
-	bla	disitrap
-CNAME(dsisize) = .-CNAME(dsitrap)
-
-/*
- * Preamble code for DSI/ISI traps
- */
-disitrap:
-	/* Write the trap vector to SPRG3 by computing LR & 0xff00 */
-	mflr	%r1
-	andi.	%r1,%r1,0xff00
-	mtsprg3	%r1
-	
-	GET_CPUINFO(%r1)
-	lwz	%r30,(PC_DISISAVE+CPUSAVE_R28)(%r1)
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_R28)(%r1)
-	lwz	%r31,(PC_DISISAVE+CPUSAVE_R29)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_R29)(%r1)
-	lwz	%r30,(PC_DISISAVE+CPUSAVE_R30)(%r1)
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_R30)(%r1)
-	lwz	%r31,(PC_DISISAVE+CPUSAVE_R31)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_R31)(%r1)
-	mfdar	%r30
-	mfdsisr	%r31
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_AIM_DAR)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_AIM_DSISR)(%r1)
-
-#ifdef KDB
-	/* Try and detect a kernel stack overflow */
-	mfsrr1	%r31
-	mtcr	%r31
-	bt	17,realtrap		/* branch is user mode */
-	mfsprg1	%r31			/* get old SP */
-	sub.	%r30,%r31,%r30		/* SP - DAR */
-	bge	1f
-	neg	%r30,%r30		/* modulo value */
-1:	cmplwi	%cr0,%r30,4096		/* is DAR within a page of SP? */
-	bge	%cr0,realtrap		/* no, too far away. */
-
-	/* Now convert this DSI into a DDB trap.  */
-	GET_CPUINFO(%r1)
-	lwz	%r30,(PC_TEMPSAVE+CPUSAVE_AIM_DAR)(%r1) /* get DAR */
-	stw	%r30,(PC_DBSAVE  +CPUSAVE_AIM_DAR)(%r1) /* save DAR */
-	lwz	%r30,(PC_TEMPSAVE+CPUSAVE_AIM_DSISR)(%r1) /* get DSISR */
-	stw	%r30,(PC_DBSAVE  +CPUSAVE_AIM_DSISR)(%r1) /* save DSISR */
-	lwz	%r30,(PC_DISISAVE+CPUSAVE_R28)(%r1) /* get  r28 */
-	stw	%r30,(PC_DBSAVE  +CPUSAVE_R28)(%r1) /* save r28 */
-	lwz	%r31,(PC_DISISAVE+CPUSAVE_R29)(%r1) /* get  r29 */
-	stw	%r31,(PC_DBSAVE  +CPUSAVE_R29)(%r1) /* save r29 */
-	lwz	%r30,(PC_DISISAVE+CPUSAVE_R30)(%r1) /* get  r30 */
-	stw	%r30,(PC_DBSAVE  +CPUSAVE_R30)(%r1) /* save r30 */
-	lwz	%r31,(PC_DISISAVE+CPUSAVE_R31)(%r1) /* get  r31 */
-	stw	%r31,(PC_DBSAVE  +CPUSAVE_R31)(%r1) /* save r31 */
-	b	dbtrap
-#endif
-
-	/* XXX need stack probe here */
-realtrap:
-/* Test whether we already had PR set */
-	mfsrr1	%r1
-	mtcr	%r1
-	mfsprg1	%r1			/* restore SP (might have been
-					   overwritten) */
-	bf	17,k_trap		/* branch if PSL_PR is false */
-	GET_CPUINFO(%r1)
-	lwz	%r1,PC_CURPCB(%r1)
-	RESTORE_KERN_SRS(%r30,%r31)	/* enable kernel mapping */
-	ba s_trap
-
-/*
- * generictrap does some standard setup for trap handling to minimize
- * the code that need be installed in the actual vectors. It expects
- * the following conditions.
- * 
- * R1 - Trap vector = LR & (0xff00 | R1)
- * SPRG1 - Original R1 contents
- * SPRG2 - Original LR
- */
-
-generictrap64:
-	mtsprg3	%r31
-	mfmsr	%r31
-	clrldi	%r31,%r31,1
-	mtmsrd	%r31
-	mfsprg3	%r31
-	isync
-
-generictrap:
-	/* Save R1 for computing the exception vector */
-	mtsprg3 %r1
-
-	/* Save interesting registers */
-	GET_CPUINFO(%r1)
-	stw	%r28,(PC_TEMPSAVE+CPUSAVE_R28)(%r1)	/* free r28-r31 */
-	stw	%r29,(PC_TEMPSAVE+CPUSAVE_R29)(%r1)
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_R30)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_R31)(%r1)
-	mfsprg1	%r1			/* restore SP, in case of branch */
-	mfsprg2	%r28			/* save LR */
-	mfcr	%r29			/* save CR */
-
-	/* Compute the exception vector from the link register */
-	mfsprg3 %r31
-	ori	%r31,%r31,0xff00
-	mflr	%r30
-	and	%r30,%r30,%r31
-	mtsprg3	%r30
-
-	/* Test whether we already had PR set */
-	mfsrr1	%r31
-	mtcr	%r31
-
-s_trap:
-	bf	17,k_trap		/* branch if PSL_PR is false */
-	GET_CPUINFO(%r1)
-u_trap:
-	lwz	%r1,PC_CURPCB(%r1)
-	RESTORE_KERN_SRS(%r30,%r31)	/* enable kernel mapping */
-
-/*
- * Now the common trap catching code.
- */
-k_trap:
-	FRAME_SETUP(PC_TEMPSAVE)
-/* Call C interrupt dispatcher: */
-trapagain:
-	addi	%r3,%r1,8
-	bl	CNAME(powerpc_interrupt)
-	.globl	CNAME(trapexit)		/* backtrace code sentinel */
-CNAME(trapexit):
-
-/* Disable interrupts: */
-	mfmsr	%r3
-	andi.	%r3,%r3,~PSL_EE@l
-	mtmsr	%r3
-/* Test AST pending: */
-	lwz	%r5,FRAME_SRR1+8(%r1)
-	mtcr	%r5
-	bf	17,1f			/* branch if PSL_PR is false */
-
-	GET_CPUINFO(%r3)		/* get per-CPU pointer */
-	lwz	%r4, PC_CURTHREAD(%r3)	/* deref to get curthread */
-	lwz	%r4, TD_FLAGS(%r4)	/* get thread flags value */
-	lis	%r5, (TDF_ASTPENDING|TDF_NEEDRESCHED)@h
-	ori	%r5,%r5, (TDF_ASTPENDING|TDF_NEEDRESCHED)@l
-	and.	%r4,%r4,%r5
-	beq	1f
-	mfmsr	%r3			/* re-enable interrupts */
-	ori	%r3,%r3,PSL_EE@l
-	mtmsr	%r3
-	isync
-	addi	%r3,%r1,8
-	bl	CNAME(ast)
-	.globl	CNAME(asttrapexit)	/* backtrace code sentinel #2 */
-CNAME(asttrapexit):
-	b	trapexit		/* test ast ret value ? */
-1:
-	FRAME_LEAVE(PC_TEMPSAVE)
-
-	.globl	CNAME(rfi_patch1)	/* replace rfi with rfid on ppc64 */
-CNAME(rfi_patch1):
-	rfi
-
-	.globl	CNAME(rfid_patch)
-CNAME(rfid_patch):
-	rfid
-
-#if defined(KDB)
-/*
- * Deliberate entry to dbtrap
- */
-	.globl	CNAME(breakpoint)
-CNAME(breakpoint):
-	mtsprg1	%r1
-	mfmsr	%r3
-	mtsrr1	%r3
-	andi.	%r3,%r3,~(PSL_EE|PSL_ME)@l
-	mtmsr	%r3			/* disable interrupts */
-	isync
-	GET_CPUINFO(%r3)
-	stw	%r28,(PC_DBSAVE+CPUSAVE_R28)(%r3)
-	stw	%r29,(PC_DBSAVE+CPUSAVE_R29)(%r3)
-	stw	%r30,(PC_DBSAVE+CPUSAVE_R30)(%r3)
-	stw	%r31,(PC_DBSAVE+CPUSAVE_R31)(%r3)
-	mflr	%r28
-	li	%r29,EXC_BPT
-	mtlr	%r29
-	mfcr	%r29
-	mtsrr0	%r28
-
-/*
- * Now the kdb trap catching code.
- */
-dbtrap:
-	/* Write the trap vector to SPRG3 by computing LR & 0xff00 */
-	mflr	%r1
-	andi.	%r1,%r1,0xff00
-	mtsprg3	%r1
-
-	lis	%r1,(tmpstk+TMPSTKSZ-16)@ha	/* get new SP */
-	addi	%r1,%r1,(tmpstk+TMPSTKSZ-16)@l
-
-	FRAME_SETUP(PC_DBSAVE)
-/* Call C trap code: */
-	addi	%r3,%r1,8
-	bl	CNAME(db_trap_glue)
-	or.	%r3,%r3,%r3
-	bne	dbleave
-/* This wasn't for KDB, so switch to real trap: */
-	lwz	%r3,FRAME_EXC+8(%r1)	/* save exception */
-	GET_CPUINFO(%r4)
-	stw	%r3,(PC_DBSAVE+CPUSAVE_R31)(%r4)
-	FRAME_LEAVE(PC_DBSAVE)
-	mtsprg1	%r1			/* prepare for entrance to realtrap */
-	GET_CPUINFO(%r1)
-	stw	%r28,(PC_TEMPSAVE+CPUSAVE_R28)(%r1)
-	stw	%r29,(PC_TEMPSAVE+CPUSAVE_R29)(%r1)
-	stw	%r30,(PC_TEMPSAVE+CPUSAVE_R30)(%r1)
-	stw	%r31,(PC_TEMPSAVE+CPUSAVE_R31)(%r1)
-	mflr	%r28
-	mfcr	%r29
-	lwz	%r31,(PC_DBSAVE+CPUSAVE_R31)(%r1)
-	mtsprg3	%r31			/* SPRG3 was clobbered by FRAME_LEAVE */
-	mfsprg1	%r1
-	b	realtrap
-dbleave:
-	FRAME_LEAVE(PC_DBSAVE)
-	.globl	CNAME(rfi_patch2)	/* replace rfi with rfid on ppc64 */
-CNAME(rfi_patch2):
-	rfi
-
-/*
- * In case of KDB we want a separate trap catcher for it
- */
-	.globl	CNAME(dblow),CNAME(dbsize)
-CNAME(dblow):
-	mtsprg1	%r1			/* save SP */
-	mtsprg2	%r29			/* save r29 */
-	mfcr	%r29			/* save CR in r29 */
-	mfsrr1	%r1
-	mtcr	%r1
-	bf	17,1f			/* branch if privileged */
-
-	/* Unprivileged case */
-	mtcr	%r29			/* put the condition register back */
-        mfsprg2	%r29			/* ... and r29 */
-        mflr	%r1			/* save LR */
-	mtsprg2 %r1			/* And then in SPRG2 */
-	li	%r1, 0	 		/* How to get the vector from LR */
-
-        bla     generictrap		/* and we look like a generic trap */
-1:
-	/* Privileged, so drop to KDB */
-	GET_CPUINFO(%r1)
-	stw	%r28,(PC_DBSAVE+CPUSAVE_R28)(%r1)	/* free r28 */
-        mfsprg2	%r28				/* r29 holds cr...  */
-        stw	%r28,(PC_DBSAVE+CPUSAVE_R29)(%r1)	/* free r29 */
-        stw	%r30,(PC_DBSAVE+CPUSAVE_R30)(%r1)	/* free r30 */
-        stw	%r31,(PC_DBSAVE+CPUSAVE_R31)(%r1)	/* free r31 */
-        mflr	%r28					/* save LR */
-	bla	dbtrap
-CNAME(dbsize) = .-CNAME(dblow)
-#endif /* KDB */

From b2a237be5c4031f91743bde57571075ff388e497 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Tue, 31 Aug 2010 15:27:46 +0000
Subject: [PATCH 0389/1624] Restructure how reset and poweroff are handled on
 PowerPC systems, since the existing code was very platform specific, and
 broken for SMP systems trying to reboot from KDB.

- Add a new PLATFORM_RESET() method to the platform KOBJ interface, and
  migrate existing reset functions into platform modules.
- Modify the OF_reboot() routine to submit the request by hand to avoid
  the IPIs involved in the regular openfirmware() routine. This fixes
  reboot from KDB on SMP machines.
- Move non-KDB reset and poweroff functions on the Powermac platform
  into the relevant power control drivers (cuda, pmu, smu), instead of
  using them through the Open Firmware backdoor.
- Rename platform_chrp to platform_powermac since it has become
  increasingly Powermac specific. When we gain support for IBM systems,
  we will grow a new platform_chrp.
---
 sys/conf/files.powerpc                        |  2 +-
 sys/powerpc/aim/machdep.c                     | 12 ----
 sys/powerpc/aim/ofw_machdep.c                 | 23 ++++---
 sys/powerpc/aim/vm_machdep.c                  |  9 ---
 sys/powerpc/booke/platform_bare.c             | 31 +++++++++
 sys/powerpc/include/ofw_machdep.h             |  1 -
 sys/powerpc/mpc85xx/mpc85xx.c                 | 25 -------
 sys/powerpc/powermac/cuda.c                   | 18 +++++
 .../platform_powermac.c}                      | 69 +++++++++++--------
 sys/powerpc/powermac/pmu.c                    | 26 +++++++
 sys/powerpc/powermac/smu.c                    | 26 +++++++
 sys/powerpc/powerpc/platform.c                | 10 +++
 sys/powerpc/powerpc/platform_if.m             |  7 ++
 13 files changed, 170 insertions(+), 89 deletions(-)
 rename sys/powerpc/{aim/platform_chrp.c => powermac/platform_powermac.c} (72%)

diff --git a/sys/conf/files.powerpc b/sys/conf/files.powerpc
index 70ca1087132..409554f0e04 100644
--- a/sys/conf/files.powerpc
+++ b/sys/conf/files.powerpc
@@ -82,7 +82,6 @@ powerpc/aim/mp_cpudep.c		optional	aim smp
 powerpc/aim/nexus.c		optional	aim
 powerpc/aim/ofw_machdep.c	optional	aim
 powerpc/aim/ofwmagic.S		optional	aim
-powerpc/aim/platform_chrp.c	optional	aim
 powerpc/aim/slb.c		optional	aim powerpc64
 powerpc/aim/swtch32.S		optional	aim powerpc
 powerpc/aim/swtch64.S		optional	aim powerpc64
@@ -143,6 +142,7 @@ powerpc/powermac/kiic.c		optional	powermac kiic
 powerpc/powermac/macgpio.c	optional	powermac pci 
 powerpc/powermac/macio.c	optional	powermac pci
 powerpc/powermac/openpic_macio.c optional	powermac pci
+powerpc/powermac/platform_powermac.c optional	powermac
 powerpc/powermac/pswitch.c	optional	powermac pswitch
 powerpc/powermac/pmu.c		optional	powermac pmu 
 powerpc/powermac/smu.c		optional	powermac smu 
diff --git a/sys/powerpc/aim/machdep.c b/sys/powerpc/aim/machdep.c
index a2f13efd6ca..fe3939d1f37 100644
--- a/sys/powerpc/aim/machdep.c
+++ b/sys/powerpc/aim/machdep.c
@@ -167,15 +167,6 @@ struct bat	battable[16];
 
 struct kva_md_info kmi;
 
-static void
-powerpc_ofw_shutdown(void *junk, int howto)
-{
-	if (howto & RB_HALT) {
-		OF_halt();
-	}
-	OF_reboot();
-}
-
 static void
 cpu_startup(void *dummy)
 {
@@ -233,9 +224,6 @@ cpu_startup(void *dummy)
 	 */
 	bufinit();
 	vm_pager_bufferinit();
-
-	EVENTHANDLER_REGISTER(shutdown_final, powerpc_ofw_shutdown, 0,
-	    SHUTDOWN_PRI_LAST);
 }
 
 extern char	kernel_text[], _end[];
diff --git a/sys/powerpc/aim/ofw_machdep.c b/sys/powerpc/aim/ofw_machdep.c
index 21b88477807..e0bf5057521 100644
--- a/sys/powerpc/aim/ofw_machdep.c
+++ b/sys/powerpc/aim/ofw_machdep.c
@@ -526,21 +526,22 @@ openfirmware(void *args)
 	return (result);
 }
 
-void
-OF_halt()
-{
-	int retval;	/* dummy, this may not be needed */
-
-	OF_interpret("shut-down", 1, &retval);
-	for (;;);	/* just in case */
-}
-
 void
 OF_reboot()
 {
-	int retval;	/* dummy, this may not be needed */
+	struct {
+		cell_t name;
+		cell_t nargs;
+		cell_t nreturns;
+		cell_t arg;
+	} args;
+
+	args.name = (cell_t)(uintptr_t)"interpret";
+	args.nargs = 1;
+	args.nreturns = 0;
+	args.arg = (cell_t)(uintptr_t)"reset-all";
+	openfirmware_core(&args); /* Don't do rendezvous! */
 
-	OF_interpret("reset-all", 1, &retval);
 	for (;;);	/* just in case */
 }
 
diff --git a/sys/powerpc/aim/vm_machdep.c b/sys/powerpc/aim/vm_machdep.c
index 6ee03fbb8c0..d1d569fc0f8 100644
--- a/sys/powerpc/aim/vm_machdep.c
+++ b/sys/powerpc/aim/vm_machdep.c
@@ -237,15 +237,6 @@ cpu_exit(td)
 {
 }
 
-/*
- * Reset back to firmware.
- */
-void
-cpu_reset()
-{
-	OF_reboot();
-}
-
 /*
  * Allocate a pool of sf_bufs (sendfile(2) or "super-fast" if you prefer. :-))
  */
diff --git a/sys/powerpc/booke/platform_bare.c b/sys/powerpc/booke/platform_bare.c
index 627470d6cce..bdfcbfc41b0 100644
--- a/sys/powerpc/booke/platform_bare.c
+++ b/sys/powerpc/booke/platform_bare.c
@@ -70,6 +70,8 @@ static int bare_smp_next_cpu(platform_t, struct cpuref *cpuref);
 static int bare_smp_get_bsp(platform_t, struct cpuref *cpuref);
 static int bare_smp_start_cpu(platform_t, struct pcpu *cpu);
 
+static void e500_reset(platform_t);
+
 static platform_method_t bare_methods[] = {
 	PLATFORMMETHOD(platform_probe, 		bare_probe),
 	PLATFORMMETHOD(platform_mem_regions,	bare_mem_regions),
@@ -80,6 +82,8 @@ static platform_method_t bare_methods[] = {
 	PLATFORMMETHOD(platform_smp_get_bsp,	bare_smp_get_bsp),
 	PLATFORMMETHOD(platform_smp_start_cpu,	bare_smp_start_cpu),
 
+	PLATFORMMETHOD(platform_reset,		e500_reset);
+
 	{ 0, 0 }
 };
 
@@ -260,3 +264,30 @@ bare_smp_start_cpu(platform_t plat, struct pcpu *pc)
 	return (ENXIO);
 #endif
 }
+
+static void
+e500_reset(platform_t plat)
+{
+	uint32_t ver = SVR_VER(mfspr(SPR_SVR));
+
+	if (ver == SVR_MPC8572E || ver == SVR_MPC8572 ||
+	    ver == SVR_MPC8548E || ver == SVR_MPC8548)
+		/* Systems with dedicated reset register */
+		ccsr_write4(OCP85XX_RSTCR, 2);
+	else {
+		/* Clear DBCR0, disables debug interrupts and events. */
+		mtspr(SPR_DBCR0, 0);
+		__asm __volatile("isync");
+
+		/* Enable Debug Interrupts in MSR. */
+		mtmsr(mfmsr() | PSL_DE);
+
+		/* Enable debug interrupts and issue reset. */
+		mtspr(SPR_DBCR0, mfspr(SPR_DBCR0) | DBCR0_IDM |
+		    DBCR0_RST_SYSTEM);
+	}
+
+	printf("Reset failed...\n");
+	while (1);
+}
+
diff --git a/sys/powerpc/include/ofw_machdep.h b/sys/powerpc/include/ofw_machdep.h
index bf79224795c..612b45b4bc1 100644
--- a/sys/powerpc/include/ofw_machdep.h
+++ b/sys/powerpc/include/ofw_machdep.h
@@ -43,7 +43,6 @@ void OF_getetheraddr(device_t dev, u_char *addr);
 void OF_initial_setup(void *fdt_ptr, void *junk, int (*openfirm)(void *));
 boolean_t OF_bootstrap(void);
 
-void OF_halt(void);
 void OF_reboot(void);
 
 void ofw_mem_regions(struct mem_region **, int *, struct mem_region **, int *);
diff --git a/sys/powerpc/mpc85xx/mpc85xx.c b/sys/powerpc/mpc85xx/mpc85xx.c
index 75304496d2f..564bf84b877 100644
--- a/sys/powerpc/mpc85xx/mpc85xx.c
+++ b/sys/powerpc/mpc85xx/mpc85xx.c
@@ -164,28 +164,3 @@ law_pci_target(struct resource *res, int *trgt_mem, int *trgt_io)
 	return (rv);
 }
 
-void
-cpu_reset(void)
-{
-	uint32_t ver = SVR_VER(mfspr(SPR_SVR));
-
-	if (ver == SVR_MPC8572E || ver == SVR_MPC8572 ||
-	    ver == SVR_MPC8548E || ver == SVR_MPC8548)
-		/* Systems with dedicated reset register */
-		ccsr_write4(OCP85XX_RSTCR, 2);
-	else {
-		/* Clear DBCR0, disables debug interrupts and events. */
-		mtspr(SPR_DBCR0, 0);
-		__asm __volatile("isync");
-
-		/* Enable Debug Interrupts in MSR. */
-		mtmsr(mfmsr() | PSL_DE);
-
-		/* Enable debug interrupts and issue reset. */
-		mtspr(SPR_DBCR0, mfspr(SPR_DBCR0) | DBCR0_IDM |
-		    DBCR0_RST_SYSTEM);
-	}
-
-	printf("Reset failed...\n");
-	while (1);
-}
diff --git a/sys/powerpc/powermac/cuda.c b/sys/powerpc/powermac/cuda.c
index 0499352adec..99a0ea9c461 100644
--- a/sys/powerpc/powermac/cuda.c
+++ b/sys/powerpc/powermac/cuda.c
@@ -38,6 +38,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -72,6 +73,7 @@ static u_int	cuda_adb_autopoll(device_t dev, uint16_t mask);
 static u_int	cuda_poll(device_t dev);
 static void	cuda_send_inbound(struct cuda_softc *sc);
 static void	cuda_send_outbound(struct cuda_softc *sc);
+static void	cuda_shutdown(void *xsc, int howto);
 
 /*
  * Clock interface
@@ -249,6 +251,8 @@ cuda_attach(device_t dev)
 	}
 
 	clock_register(dev, 1000);
+	EVENTHANDLER_REGISTER(shutdown_final, cuda_shutdown, sc,
+	    SHUTDOWN_PRI_LAST);
 
 	return (bus_generic_attach(dev));
 }
@@ -739,6 +743,20 @@ cuda_adb_autopoll(device_t dev, uint16_t mask) {
 	return (0);
 }
 
+static void
+cuda_shutdown(void *xsc, int howto)
+{
+	struct cuda_softc *sc = xsc;
+	uint8_t cmd[] = {CUDA_PSEUDO, 0};
+
+	cmd[1] = (howto & RB_HALT) ? CMD_POWEROFF : CMD_RESET;
+	cuda_poll(sc->sc_dev);
+	cuda_send(sc, 1, 2, cmd);
+
+	while (1)
+		cuda_poll(sc->sc_dev);
+}
+
 #define DIFF19041970	2082844800
 
 static int
diff --git a/sys/powerpc/aim/platform_chrp.c b/sys/powerpc/powermac/platform_powermac.c
similarity index 72%
rename from sys/powerpc/aim/platform_chrp.c
rename to sys/powerpc/powermac/platform_powermac.c
index a49b520eb6d..d495065b1b4 100644
--- a/sys/powerpc/aim/platform_chrp.c
+++ b/sys/powerpc/powermac/platform_powermac.c
@@ -55,38 +55,41 @@ __FBSDID("$FreeBSD$");
 extern void *ap_pcpu;
 #endif
 
-static int chrp_probe(platform_t);
-void chrp_mem_regions(platform_t, struct mem_region **phys, int *physsz,
+static int powermac_probe(platform_t);
+void powermac_mem_regions(platform_t, struct mem_region **phys, int *physsz,
     struct mem_region **avail, int *availsz);
-static u_long chrp_timebase_freq(platform_t, struct cpuref *cpuref);
-static int chrp_smp_first_cpu(platform_t, struct cpuref *cpuref);
-static int chrp_smp_next_cpu(platform_t, struct cpuref *cpuref);
-static int chrp_smp_get_bsp(platform_t, struct cpuref *cpuref);
-static int chrp_smp_start_cpu(platform_t, struct pcpu *cpu);
+static u_long powermac_timebase_freq(platform_t, struct cpuref *cpuref);
+static int powermac_smp_first_cpu(platform_t, struct cpuref *cpuref);
+static int powermac_smp_next_cpu(platform_t, struct cpuref *cpuref);
+static int powermac_smp_get_bsp(platform_t, struct cpuref *cpuref);
+static int powermac_smp_start_cpu(platform_t, struct pcpu *cpu);
+static void powermac_reset(platform_t);
 
-static platform_method_t chrp_methods[] = {
-	PLATFORMMETHOD(platform_probe, 		chrp_probe),
-	PLATFORMMETHOD(platform_mem_regions,	chrp_mem_regions),
-	PLATFORMMETHOD(platform_timebase_freq,	chrp_timebase_freq),
+static platform_method_t powermac_methods[] = {
+	PLATFORMMETHOD(platform_probe, 		powermac_probe),
+	PLATFORMMETHOD(platform_mem_regions,	powermac_mem_regions),
+	PLATFORMMETHOD(platform_timebase_freq,	powermac_timebase_freq),
 	
-	PLATFORMMETHOD(platform_smp_first_cpu,	chrp_smp_first_cpu),
-	PLATFORMMETHOD(platform_smp_next_cpu,	chrp_smp_next_cpu),
-	PLATFORMMETHOD(platform_smp_get_bsp,	chrp_smp_get_bsp),
-	PLATFORMMETHOD(platform_smp_start_cpu,	chrp_smp_start_cpu),
+	PLATFORMMETHOD(platform_smp_first_cpu,	powermac_smp_first_cpu),
+	PLATFORMMETHOD(platform_smp_next_cpu,	powermac_smp_next_cpu),
+	PLATFORMMETHOD(platform_smp_get_bsp,	powermac_smp_get_bsp),
+	PLATFORMMETHOD(platform_smp_start_cpu,	powermac_smp_start_cpu),
+
+	PLATFORMMETHOD(platform_reset,		powermac_reset),
 
 	{ 0, 0 }
 };
 
-static platform_def_t chrp_platform = {
-	"chrp",
-	chrp_methods,
+static platform_def_t powermac_platform = {
+	"powermac",
+	powermac_methods,
 	0
 };
 
-PLATFORM_DEF(chrp_platform);
+PLATFORM_DEF(powermac_platform);
 
 static int
-chrp_probe(platform_t plat)
+powermac_probe(platform_t plat)
 {
 	if (OF_finddevice("/memory") != -1 || OF_finddevice("/memory@0") != -1)
 		return (BUS_PROBE_GENERIC);
@@ -95,14 +98,14 @@ chrp_probe(platform_t plat)
 }
 
 void
-chrp_mem_regions(platform_t plat, struct mem_region **phys, int *physsz,
+powermac_mem_regions(platform_t plat, struct mem_region **phys, int *physsz,
     struct mem_region **avail, int *availsz)
 {
 	ofw_mem_regions(phys,physsz,avail,availsz);
 }
 
 static u_long
-chrp_timebase_freq(platform_t plat, struct cpuref *cpuref)
+powermac_timebase_freq(platform_t plat, struct cpuref *cpuref)
 {
 	phandle_t phandle;
 	int32_t ticks = -1;
@@ -119,7 +122,7 @@ chrp_timebase_freq(platform_t plat, struct cpuref *cpuref)
 
 
 static int
-chrp_smp_fill_cpuref(struct cpuref *cpuref, phandle_t cpu)
+powermac_smp_fill_cpuref(struct cpuref *cpuref, phandle_t cpu)
 {
 	cell_t cpuid, res;
 
@@ -139,7 +142,7 @@ chrp_smp_fill_cpuref(struct cpuref *cpuref, phandle_t cpu)
 }
 
 static int
-chrp_smp_first_cpu(platform_t plat, struct cpuref *cpuref)
+powermac_smp_first_cpu(platform_t plat, struct cpuref *cpuref)
 {
 	char buf[8];
 	phandle_t cpu, dev, root;
@@ -175,11 +178,11 @@ chrp_smp_first_cpu(platform_t plat, struct cpuref *cpuref)
 	if (cpu == 0)
 		return (ENOENT);
 
-	return (chrp_smp_fill_cpuref(cpuref, cpu));
+	return (powermac_smp_fill_cpuref(cpuref, cpu));
 }
 
 static int
-chrp_smp_next_cpu(platform_t plat, struct cpuref *cpuref)
+powermac_smp_next_cpu(platform_t plat, struct cpuref *cpuref)
 {
 	char buf[8];
 	phandle_t cpu;
@@ -195,11 +198,11 @@ chrp_smp_next_cpu(platform_t plat, struct cpuref *cpuref)
 	if (cpu == 0)
 		return (ENOENT);
 
-	return (chrp_smp_fill_cpuref(cpuref, cpu));
+	return (powermac_smp_fill_cpuref(cpuref, cpu));
 }
 
 static int
-chrp_smp_get_bsp(platform_t plat, struct cpuref *cpuref)
+powermac_smp_get_bsp(platform_t plat, struct cpuref *cpuref)
 {
 	ihandle_t inst;
 	phandle_t bsp, chosen;
@@ -214,11 +217,11 @@ chrp_smp_get_bsp(platform_t plat, struct cpuref *cpuref)
 		return (ENXIO);
 
 	bsp = OF_instance_to_package(inst);
-	return (chrp_smp_fill_cpuref(cpuref, bsp));
+	return (powermac_smp_fill_cpuref(cpuref, bsp));
 }
 
 static int
-chrp_smp_start_cpu(platform_t plat, struct pcpu *pc)
+powermac_smp_start_cpu(platform_t plat, struct pcpu *pc)
 {
 #ifdef SMP
 	phandle_t cpu;
@@ -277,3 +280,9 @@ chrp_smp_start_cpu(platform_t plat, struct pcpu *pc)
 #endif
 }
 
+static void
+powermac_reset(platform_t platform)
+{
+	OF_reboot();
+}
+
diff --git a/sys/powerpc/powermac/pmu.c b/sys/powerpc/powermac/pmu.c
index 1fa101d9b4f..d641c9c74f5 100644
--- a/sys/powerpc/powermac/pmu.c
+++ b/sys/powerpc/powermac/pmu.c
@@ -36,6 +36,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 
 #include 
@@ -81,6 +82,11 @@ static u_int	pmu_adb_send(device_t dev, u_char command_byte, int len,
 static u_int	pmu_adb_autopoll(device_t dev, uint16_t mask);
 static u_int	pmu_poll(device_t dev);
 
+/*
+ * Power interface
+ */
+
+static void	pmu_shutdown(void *xsc, int howto);
 static void	pmu_set_sleepled(void *xsc, int onoff);
 static int	pmu_server_mode(SYSCTL_HANDLER_ARGS);
 static int	pmu_acline_state(SYSCTL_HANDLER_ARGS);
@@ -474,6 +480,12 @@ pmu_attach(device_t dev)
 
 	clock_register(dev, 1000);
 
+	/*
+	 * Register power control handler
+	 */
+	EVENTHANDLER_REGISTER(shutdown_final, pmu_shutdown, sc,
+	    SHUTDOWN_PRI_LAST);
+
 	return (bus_generic_attach(dev));
 }
 
@@ -750,6 +762,20 @@ pmu_adb_autopoll(device_t dev, uint16_t mask)
 	return 0;
 }
 
+static void
+pmu_shutdown(void *xsc, int howto)
+{
+	struct pmu_softc *sc = xsc;
+	uint8_t cmd[] = {'M', 'A', 'T', 'T'};
+	
+	if (howto & RB_HALT)
+		pmu_send(sc, PMU_POWER_OFF, 4, cmd, 0, NULL);
+	else
+		pmu_send(sc, PMU_RESET_CPU, 0, NULL, 0, NULL);
+
+	for (;;);
+}
+
 static void
 pmu_set_sleepled(void *xsc, int onoff)
 {
diff --git a/sys/powerpc/powermac/smu.c b/sys/powerpc/powermac/smu.c
index 7a4fac836b1..28949043bf2 100644
--- a/sys/powerpc/powermac/smu.c
+++ b/sys/powerpc/powermac/smu.c
@@ -165,6 +165,7 @@ static void	smu_manage_fans(device_t smu);
 static void	smu_set_sleepled(void *xdev, int onoff);
 static int	smu_server_mode(SYSCTL_HANDLER_ARGS);
 static void	smu_doorbell_intr(void *xdev);
+static void	smu_shutdown(void *xdev, int howto);
 
 /* where to find the doorbell GPIO */
 
@@ -391,6 +392,12 @@ smu_attach(device_t dev)
 	 */
 	clock_register(dev, 1000);
 
+	/*
+	 * Learn about shutdown events
+	 */
+	EVENTHANDLER_REGISTER(shutdown_final, smu_shutdown, dev,
+	    SHUTDOWN_PRI_LAST);
+
 	return (bus_generic_attach(dev));
 }
 
@@ -1115,6 +1122,25 @@ smu_server_mode(SYSCTL_HANDLER_ARGS)
 	return (smu_run_cmd(smu, &cmd, 1));
 }
 
+static void
+smu_shutdown(void *xdev, int howto)
+{
+	device_t smu = xdev;
+	struct smu_cmd cmd;
+
+	cmd.cmd = SMU_POWER;
+	if (howto & RB_HALT)
+		strcpy(cmd.data, "SHUTDOWN");
+	else
+		strcpy(cmd.data, "RESTART");
+
+	cmd.len = strlen(cmd.data);
+
+	smu_run_cmd(smu, &cmd, 1);
+
+	for (;;);
+}
+
 static int
 smu_gettime(device_t dev, struct timespec *ts)
 {
diff --git a/sys/powerpc/powerpc/platform.c b/sys/powerpc/powerpc/platform.c
index 400856375db..2b5c60792db 100644
--- a/sys/powerpc/powerpc/platform.c
+++ b/sys/powerpc/powerpc/platform.c
@@ -46,6 +46,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 
+#include 
 #include 
 #include 
 #include 
@@ -104,6 +105,15 @@ platform_smp_start_cpu(struct pcpu *cpu)
 	return (PLATFORM_SMP_START_CPU(plat_obj, cpu));
 }
 
+/*
+ * Reset back to firmware.
+ */
+void
+cpu_reset()
+{
+        PLATFORM_RESET(plat_obj);
+}
+
 /*
  * Platform install routines. Highest priority wins, using the same
  * algorithm as bus attachment.
diff --git a/sys/powerpc/powerpc/platform_if.m b/sys/powerpc/powerpc/platform_if.m
index 600d14656a5..07e49bc884c 100644
--- a/sys/powerpc/powerpc/platform_if.m
+++ b/sys/powerpc/powerpc/platform_if.m
@@ -161,3 +161,10 @@ METHOD int smp_start_cpu {
 	struct pcpu	*_cpu;
 };
 
+/**
+ * @brief Reset system
+ */
+METHOD void reset {
+	platform_t	_plat;
+};
+

From 6d3ed393d65a21a4ebd8aefbeb6d657d0a1f7815 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Tue, 31 Aug 2010 16:57:58 +0000
Subject: [PATCH 0390/1624] The realloc case for memguard(9) will copy too many
 bytes when reallocating to a smaller-sized allocation.  Fix this issue.

Noticed by:     alc
Reviewed by:    alc
Approved by:    zml (mentor)
MFC after:      3 weeks
---
 sys/kern/kern_malloc.c | 11 ++---------
 sys/vm/memguard.c      | 25 +++++++++++++++++++++++++
 sys/vm/memguard.h      |  2 ++
 3 files changed, 29 insertions(+), 9 deletions(-)

diff --git a/sys/kern/kern_malloc.c b/sys/kern/kern_malloc.c
index 00df9dd3ee4..1e97b55dc03 100644
--- a/sys/kern/kern_malloc.c
+++ b/sys/kern/kern_malloc.c
@@ -566,11 +566,8 @@ realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
 	 */
 
 #ifdef DEBUG_MEMGUARD
-	if (is_memguard_addr(addr)) {
-		slab = NULL;
-		alloc = size;
-		goto remalloc;
-	}
+	if (is_memguard_addr(addr))
+		return (memguard_realloc(addr, size, mtp, flags));
 #endif
 
 #ifdef DEBUG_REDZONE
@@ -595,10 +592,6 @@ realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
 		return (addr);
 #endif /* !DEBUG_REDZONE */
 
-#ifdef DEBUG_MEMGUARD
-remalloc:
-#endif
-
 	/* Allocate a new, bigger (or smaller) block */
 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
 		return (NULL);
diff --git a/sys/vm/memguard.c b/sys/vm/memguard.c
index c3d93e06200..85893ab3807 100644
--- a/sys/vm/memguard.c
+++ b/sys/vm/memguard.c
@@ -399,6 +399,31 @@ memguard_free(void *ptr)
 	vm_map_unlock(memguard_map);
 }
 
+/*
+ * Re-allocate an allocation that was originally guarded.
+ */
+void *
+memguard_realloc(void *addr, unsigned long size, struct malloc_type *mtp,
+    int flags)
+{
+	void *newaddr;
+	u_long old_size;
+
+	/*
+	 * Allocate the new block.  Force the allocation to be guarded
+	 * as the original may have been guarded through random
+	 * chance, and that should be preserved.
+	 */
+	if ((newaddr = memguard_alloc(size, flags)) == NULL)
+		return (NULL);
+
+	/* Copy over original contents. */
+	old_size = *v2sizep(trunc_page((uintptr_t)addr));
+	bcopy(addr, newaddr, min(size, old_size));
+	memguard_free(addr);
+	return (newaddr);
+}
+
 int
 memguard_cmp(struct malloc_type *mtp, unsigned long size)
 {
diff --git a/sys/vm/memguard.h b/sys/vm/memguard.h
index ba7c2f1b427..25238b420d2 100644
--- a/sys/vm/memguard.h
+++ b/sys/vm/memguard.h
@@ -38,6 +38,7 @@ struct vm_map;
 unsigned long	memguard_fudge(unsigned long, unsigned long);
 void	memguard_init(struct vm_map *);
 void 	*memguard_alloc(unsigned long, int);
+void	*memguard_realloc(void *, unsigned long, struct malloc_type *, int);
 void	memguard_free(void *);
 int	memguard_cmp(struct malloc_type *, unsigned long);
 int	is_memguard_addr(void *);
@@ -45,6 +46,7 @@ int	is_memguard_addr(void *);
 #define	memguard_fudge(size, xxx)	(size)
 #define	memguard_init(map)		do { } while (0)
 #define	memguard_alloc(size, flags)	NULL
+#define	memguard_realloc(a, s, mtp, f)	NULL
 #define	memguard_free(addr)		do { } while (0)
 #define	memguard_cmp(mtp, size)		0
 #define	is_memguard_addr(addr)		0

From c05f0da034bab79c7a07c200bdd56e0b4b3b9de7 Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Tue, 31 Aug 2010 17:33:29 +0000
Subject: [PATCH 0391/1624] Use a more robust way to substitute gcc for clang,
 when compiling gnu/lib/libobjc and sys/boot/i386/boot2, so it also works when
 using absolute paths and/or options, as in CC="/absolute/path/clang -foo".

Approved by:	rpaulo (mentor)
---
 gnu/lib/libobjc/Makefile     | 4 +++-
 sys/boot/i386/boot2/Makefile | 4 +++-
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/gnu/lib/libobjc/Makefile b/gnu/lib/libobjc/Makefile
index 3dc49d842a6..3513103f2d7 100644
--- a/gnu/lib/libobjc/Makefile
+++ b/gnu/lib/libobjc/Makefile
@@ -16,7 +16,9 @@ SRCS=	archive.c class.c encoding.c gc.c hash.c init.c linking.m misc.c \
 	selector.c sendmsg.c thr.c thr-objc.c exception.c
 
 # XXX: clang cannot compile libobjc yet
-CC:=${CC:C/^cc|^clang/gcc/}
+.if ${CC:T:Mclang} == "clang"
+CC=gcc
+.endif
 
 INCS=	encoding.h hash.h objc-api.h objc-decls.h objc-list.h objc.h runtime.h \
 	sarray.h thr.h typedstream.h NXConstStr.h Object.h Protocol.h
diff --git a/sys/boot/i386/boot2/Makefile b/sys/boot/i386/boot2/Makefile
index bff4647668a..74aab82de43 100644
--- a/sys/boot/i386/boot2/Makefile
+++ b/sys/boot/i386/boot2/Makefile
@@ -3,7 +3,9 @@
 .include 
 
 # XXX: clang can compile the boot code just fine, but boot2 gets too big
-CC:=${CC:C/^cc|^clang/gcc/}
+.if ${CC:T:Mclang} == "clang"
+CC=gcc
+.endif
 
 FILES=		boot boot1 boot2
 

From 5b610048ecfd93f9fe08485a13a7a9545a1788b0 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 31 Aug 2010 17:33:48 +0000
Subject: [PATCH 0392/1624] Split common parent DMA tag into ring DMA tag and
 TX/RX mbuf DMA tag. All controllers that are not BCM5755 or higher have 4GB
 boundary DMA bug. Previously bge(4) used 32bit DMA address to workaround the
 bug(r199670). However this caused the use of bounce buffers such that it
 resulted in poor performance for systems which have more than 4GB memory.
 Because bus_dma(9) honors boundary restriction requirement of DMA tag for
 dynamic buffers, having a separate TX/RX mbuf DMA tag will greatly reduce the
 possibility of using bounce buffers. For DMA buffers allocated with
 bus_dmamem_alloc(9), now bge(4) explicitly checks whether the requested
 memory region crossed the boundary or not. With this change, only the DMA
 buffer that crossed the boundary will use 32bit DMA address. Other DMA
 buffers are not affected as separate DMA tag is created for each DMA buffer.
 Even if 32bit DMA address space is used for a buffer, the chance to use
 bounce buffer is still very low as the size of buffer is small. This change
 should eliminate most usage of bounce buffers on systems that have more than
 4GB memory.

More correct fix would be teaching bus_dma(9) to honor boundary
restriction for buffers created with bus_dmamem_alloc(9) but it
seems that is not easy.

While I'm here cleanup bge_dma_map_addr() and remove unnecessary
member variables in bge_dmamap_arg structure.

Tested by:	marcel
---
 sys/dev/bge/if_bge.c    | 383 +++++++++++++++-------------------------
 sys/dev/bge/if_bgereg.h |  12 +-
 2 files changed, 152 insertions(+), 243 deletions(-)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index c90319406ae..48f1d452f37 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -355,8 +355,10 @@ static int bge_suspend(device_t);
 static int bge_resume(device_t);
 static void bge_release_resources(struct bge_softc *);
 static void bge_dma_map_addr(void *, bus_dma_segment_t *, int, int);
-static int bge_dma_alloc(device_t);
+static int bge_dma_alloc(struct bge_softc *);
 static void bge_dma_free(struct bge_softc *);
+static int bge_dma_ring_alloc(struct bge_softc *, bus_size_t, bus_size_t,
+    bus_dma_tag_t *, uint8_t **, bus_dmamap_t *, bus_addr_t *, const char *);
 
 static int bge_get_eaddr_fw(struct bge_softc *sc, uint8_t ether_addr[]);
 static int bge_get_eaddr_mem(struct bge_softc *, uint8_t[]);
@@ -614,13 +616,9 @@ bge_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
 	if (error)
 		return;
 
+	KASSERT(nseg == 1, ("%s: %d segments returned!", __func__, nseg));
+
 	ctx = arg;
-
-	if (nseg > ctx->bge_maxsegs) {
-		ctx->bge_maxsegs = 0;
-		return;
-	}
-
 	ctx->bge_busaddr = segs->ds_addr;
 }
 
@@ -2122,27 +2120,84 @@ bge_dma_free(struct bge_softc *sc)
 	if (sc->bge_cdata.bge_stats_tag)
 		bus_dma_tag_destroy(sc->bge_cdata.bge_stats_tag);
 
+	if (sc->bge_cdata.bge_buffer_tag)
+		bus_dma_tag_destroy(sc->bge_cdata.bge_buffer_tag);
+
 	/* Destroy the parent tag. */
 	if (sc->bge_cdata.bge_parent_tag)
 		bus_dma_tag_destroy(sc->bge_cdata.bge_parent_tag);
 }
 
 static int
-bge_dma_alloc(device_t dev)
+bge_dma_ring_alloc(struct bge_softc *sc, bus_size_t alignment,
+    bus_size_t maxsize, bus_dma_tag_t *tag, uint8_t **ring, bus_dmamap_t *map,
+    bus_addr_t *paddr, const char *msg)
 {
 	struct bge_dmamap_arg ctx;
-	struct bge_softc *sc;
 	bus_addr_t lowaddr;
-	bus_size_t sbsz, txsegsz, txmaxsegsz;
-	int i, error;
+	bus_size_t ring_end;
+	int error;
 
-	sc = device_get_softc(dev);
+	lowaddr = BUS_SPACE_MAXADDR;
+again:
+	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
+	    alignment, 0, lowaddr, BUS_SPACE_MAXADDR, NULL,
+	    NULL, maxsize, 1, maxsize, 0, NULL, NULL, tag);
+	if (error != 0) {
+		device_printf(sc->bge_dev,
+		    "could not create %s dma tag\n", msg);
+		return (ENOMEM);
+	}
+	/* Allocate DMA'able memory for ring. */
+	error = bus_dmamem_alloc(*tag, (void **)ring,
+	    BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, map);
+	if (error != 0) {
+		device_printf(sc->bge_dev,
+		    "could not allocate DMA'able memory for %s\n", msg);
+		return (ENOMEM);
+	}
+	/* Load the address of the ring. */
+	ctx.bge_busaddr = 0;
+	error = bus_dmamap_load(*tag, *map, *ring, maxsize, bge_dma_map_addr,
+	    &ctx, BUS_DMA_NOWAIT);
+	if (error != 0) {
+		device_printf(sc->bge_dev,
+		    "could not load DMA'able memory for %s\n", msg);
+		return (ENOMEM);
+	}
+	*paddr = ctx.bge_busaddr;
+	ring_end = *paddr + maxsize;
+	if ((sc->bge_flags & BGE_FLAG_4G_BNDRY_BUG) != 0 &&
+	    BGE_ADDR_HI(*paddr) != BGE_ADDR_HI(ring_end)) {
+		/*
+		 * 4GB boundary crossed.  Limit maximum allowable DMA
+		 * address space to 32bit and try again.
+		 */
+		bus_dmamap_unload(*tag, *map);
+		bus_dmamem_free(*tag, *ring, *map);
+		bus_dma_tag_destroy(*tag);
+		if (bootverbose)
+			device_printf(sc->bge_dev, "4GB boundary crossed, "
+			    "limit DMA address space to 32bit for %s\n", msg);
+		*ring = NULL;
+		*tag = NULL;
+		*map = NULL;
+		lowaddr = BUS_SPACE_MAXADDR_32BIT;
+		goto again;
+	}
+	return (0);
+}
+
+static int
+bge_dma_alloc(struct bge_softc *sc)
+{
+	bus_addr_t lowaddr;
+	bus_size_t boundary, sbsz, txsegsz, txmaxsegsz;
+	int i, error;
 
 	lowaddr = BUS_SPACE_MAXADDR;
 	if ((sc->bge_flags & BGE_FLAG_40BIT_BUG) != 0)
 		lowaddr = BGE_DMA_MAXADDR;
-	if ((sc->bge_flags & BGE_FLAG_4G_BNDRY_BUG) != 0)
-		lowaddr = BUS_SPACE_MAXADDR_32BIT;
 	/*
 	 * Allocate the parent bus DMA tag appropriate for PCI.
 	 */
@@ -2150,16 +2205,84 @@ bge_dma_alloc(device_t dev)
 	    1, 0, lowaddr, BUS_SPACE_MAXADDR, NULL,
 	    NULL, BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
 	    0, NULL, NULL, &sc->bge_cdata.bge_parent_tag);
-
 	if (error != 0) {
 		device_printf(sc->bge_dev,
 		    "could not allocate parent dma tag\n");
 		return (ENOMEM);
 	}
 
+	/* Create tag for standard RX ring. */
+	error = bge_dma_ring_alloc(sc, PAGE_SIZE, BGE_STD_RX_RING_SZ,
+	    &sc->bge_cdata.bge_rx_std_ring_tag,
+	    (uint8_t **)&sc->bge_ldata.bge_rx_std_ring,
+	    &sc->bge_cdata.bge_rx_std_ring_map,
+	    &sc->bge_ldata.bge_rx_std_ring_paddr, "RX ring");
+	if (error)
+		return (error);
+
+	/* Create tag for RX return ring. */
+	error = bge_dma_ring_alloc(sc, PAGE_SIZE, BGE_RX_RTN_RING_SZ(sc),
+	    &sc->bge_cdata.bge_rx_return_ring_tag,
+	    (uint8_t **)&sc->bge_ldata.bge_rx_return_ring,
+	    &sc->bge_cdata.bge_rx_return_ring_map,
+	    &sc->bge_ldata.bge_rx_return_ring_paddr, "RX return ring");
+	if (error)
+		return (error);
+
+	/* Create tag for TX ring. */
+	error = bge_dma_ring_alloc(sc, PAGE_SIZE, BGE_TX_RING_SZ,
+	    &sc->bge_cdata.bge_tx_ring_tag,
+	    (uint8_t **)&sc->bge_ldata.bge_tx_ring,
+	    &sc->bge_cdata.bge_tx_ring_map,
+	    &sc->bge_ldata.bge_tx_ring_paddr, "TX ring");
+	if (error)
+		return (error);
+
 	/*
-	 * Create tag for Tx mbufs.
+	 * Create tag for status block.
+	 * Because we only use single Tx/Rx/Rx return ring, use
+	 * minimum status block size except BCM5700 AX/BX which
+	 * seems to want to see full status block size regardless
+	 * of configured number of ring.
 	 */
+	if (sc->bge_asicrev == BGE_ASICREV_BCM5700 &&
+	    sc->bge_chipid != BGE_CHIPID_BCM5700_C0)
+		sbsz = BGE_STATUS_BLK_SZ;
+	else
+		sbsz = 32;
+	error = bge_dma_ring_alloc(sc, PAGE_SIZE, sbsz,
+	    &sc->bge_cdata.bge_status_tag,
+	    (uint8_t **)&sc->bge_ldata.bge_status_block,
+	    &sc->bge_cdata.bge_status_map,
+	    &sc->bge_ldata.bge_status_block_paddr, "status block");
+	if (error)
+		return (error);
+
+	/* Create tag for jumbo RX ring. */
+	if (BGE_IS_JUMBO_CAPABLE(sc)) {
+		error = bge_dma_ring_alloc(sc, PAGE_SIZE, BGE_JUMBO_RX_RING_SZ,
+		    &sc->bge_cdata.bge_rx_jumbo_ring_tag,
+		    (uint8_t **)&sc->bge_ldata.bge_rx_jumbo_ring,
+		    &sc->bge_cdata.bge_rx_jumbo_ring_map,
+		    &sc->bge_ldata.bge_rx_jumbo_ring_paddr, "jumbo RX ring");
+		if (error)
+			return (error);
+	}
+
+	/* Create parent tag for buffers. */
+	boundary = 0;
+	if ((sc->bge_flags & BGE_FLAG_4G_BNDRY_BUG) != 0)
+		boundary = BGE_DMA_4G_BNDRY;
+	error = bus_dma_tag_create(bus_get_dma_tag(sc->bge_dev),
+	    1, boundary, lowaddr, BUS_SPACE_MAXADDR, NULL,
+	    NULL, BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
+	    0, NULL, NULL, &sc->bge_cdata.bge_buffer_tag);
+	if (error != 0) {
+		device_printf(sc->bge_dev,
+		    "could not allocate buffer dma tag\n");
+		return (ENOMEM);
+	}
+	/* Create tag for Tx mbufs. */
 	if (sc->bge_flags & BGE_FLAG_TSO) {
 		txsegsz = BGE_TSOSEG_SZ;
 		txmaxsegsz = 65535 + sizeof(struct ether_vlan_header);
@@ -2167,7 +2290,7 @@ bge_dma_alloc(device_t dev)
 		txsegsz = MCLBYTES;
 		txmaxsegsz = MCLBYTES * BGE_NSEG_NEW;
 	}
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag, 1,
+	error = bus_dma_tag_create(sc->bge_cdata.bge_buffer_tag, 1,
 	    0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
 	    txmaxsegsz, BGE_NSEG_NEW, txsegsz, 0, NULL, NULL,
 	    &sc->bge_cdata.bge_tx_mtag);
@@ -2177,10 +2300,8 @@ bge_dma_alloc(device_t dev)
 		return (ENOMEM);
 	}
 
-	/*
-	 * Create tag for Rx mbufs.
-	 */
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag, 1, 0,
+	/* Create tag for Rx mbufs. */
+	error = bus_dma_tag_create(sc->bge_cdata.bge_buffer_tag, 1, 0,
 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1,
 	    MCLBYTES, 0, NULL, NULL, &sc->bge_cdata.bge_rx_mtag);
 
@@ -2218,42 +2339,9 @@ bge_dma_alloc(device_t dev)
 		}
 	}
 
-	/* Create tag for standard RX ring. */
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
-	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
-	    NULL, BGE_STD_RX_RING_SZ, 1, BGE_STD_RX_RING_SZ, 0,
-	    NULL, NULL, &sc->bge_cdata.bge_rx_std_ring_tag);
-
-	if (error) {
-		device_printf(sc->bge_dev, "could not allocate dma tag\n");
-		return (ENOMEM);
-	}
-
-	/* Allocate DMA'able memory for standard RX ring. */
-	error = bus_dmamem_alloc(sc->bge_cdata.bge_rx_std_ring_tag,
-	    (void **)&sc->bge_ldata.bge_rx_std_ring, BUS_DMA_NOWAIT,
-	    &sc->bge_cdata.bge_rx_std_ring_map);
-	if (error)
-		return (ENOMEM);
-
-	bzero((char *)sc->bge_ldata.bge_rx_std_ring, BGE_STD_RX_RING_SZ);
-
-	/* Load the address of the standard RX ring. */
-	ctx.bge_maxsegs = 1;
-	ctx.sc = sc;
-
-	error = bus_dmamap_load(sc->bge_cdata.bge_rx_std_ring_tag,
-	    sc->bge_cdata.bge_rx_std_ring_map, sc->bge_ldata.bge_rx_std_ring,
-	    BGE_STD_RX_RING_SZ, bge_dma_map_addr, &ctx, BUS_DMA_NOWAIT);
-
-	if (error)
-		return (ENOMEM);
-
-	sc->bge_ldata.bge_rx_std_ring_paddr = ctx.bge_busaddr;
-
-	/* Create tags for jumbo mbufs. */
+	/* Create tags for jumbo RX buffers. */
 	if (BGE_IS_JUMBO_CAPABLE(sc)) {
-		error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
+		error = bus_dma_tag_create(sc->bge_cdata.bge_buffer_tag,
 		    1, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
 		    NULL, MJUM9BYTES, BGE_NSEG_JUMBO, PAGE_SIZE,
 		    0, NULL, NULL, &sc->bge_cdata.bge_mtag_jumbo);
@@ -2262,41 +2350,6 @@ bge_dma_alloc(device_t dev)
 			    "could not allocate jumbo dma tag\n");
 			return (ENOMEM);
 		}
-
-		/* Create tag for jumbo RX ring. */
-		error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
-		    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
-		    NULL, BGE_JUMBO_RX_RING_SZ, 1, BGE_JUMBO_RX_RING_SZ, 0,
-		    NULL, NULL, &sc->bge_cdata.bge_rx_jumbo_ring_tag);
-
-		if (error) {
-			device_printf(sc->bge_dev,
-			    "could not allocate jumbo ring dma tag\n");
-			return (ENOMEM);
-		}
-
-		/* Allocate DMA'able memory for jumbo RX ring. */
-		error = bus_dmamem_alloc(sc->bge_cdata.bge_rx_jumbo_ring_tag,
-		    (void **)&sc->bge_ldata.bge_rx_jumbo_ring,
-		    BUS_DMA_NOWAIT | BUS_DMA_ZERO,
-		    &sc->bge_cdata.bge_rx_jumbo_ring_map);
-		if (error)
-			return (ENOMEM);
-
-		/* Load the address of the jumbo RX ring. */
-		ctx.bge_maxsegs = 1;
-		ctx.sc = sc;
-
-		error = bus_dmamap_load(sc->bge_cdata.bge_rx_jumbo_ring_tag,
-		    sc->bge_cdata.bge_rx_jumbo_ring_map,
-		    sc->bge_ldata.bge_rx_jumbo_ring, BGE_JUMBO_RX_RING_SZ,
-		    bge_dma_map_addr, &ctx, BUS_DMA_NOWAIT);
-
-		if (error)
-			return (ENOMEM);
-
-		sc->bge_ldata.bge_rx_jumbo_ring_paddr = ctx.bge_busaddr;
-
 		/* Create DMA maps for jumbo RX buffers. */
 		error = bus_dmamap_create(sc->bge_cdata.bge_mtag_jumbo,
 		    0, &sc->bge_cdata.bge_rx_jumbo_sparemap);
@@ -2314,154 +2367,8 @@ bge_dma_alloc(device_t dev)
 				return (ENOMEM);
 			}
 		}
-
 	}
 
-	/* Create tag for RX return ring. */
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
-	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
-	    NULL, BGE_RX_RTN_RING_SZ(sc), 1, BGE_RX_RTN_RING_SZ(sc), 0,
-	    NULL, NULL, &sc->bge_cdata.bge_rx_return_ring_tag);
-
-	if (error) {
-		device_printf(sc->bge_dev, "could not allocate dma tag\n");
-		return (ENOMEM);
-	}
-
-	/* Allocate DMA'able memory for RX return ring. */
-	error = bus_dmamem_alloc(sc->bge_cdata.bge_rx_return_ring_tag,
-	    (void **)&sc->bge_ldata.bge_rx_return_ring, BUS_DMA_NOWAIT,
-	    &sc->bge_cdata.bge_rx_return_ring_map);
-	if (error)
-		return (ENOMEM);
-
-	bzero((char *)sc->bge_ldata.bge_rx_return_ring,
-	    BGE_RX_RTN_RING_SZ(sc));
-
-	/* Load the address of the RX return ring. */
-	ctx.bge_maxsegs = 1;
-	ctx.sc = sc;
-
-	error = bus_dmamap_load(sc->bge_cdata.bge_rx_return_ring_tag,
-	    sc->bge_cdata.bge_rx_return_ring_map,
-	    sc->bge_ldata.bge_rx_return_ring, BGE_RX_RTN_RING_SZ(sc),
-	    bge_dma_map_addr, &ctx, BUS_DMA_NOWAIT);
-
-	if (error)
-		return (ENOMEM);
-
-	sc->bge_ldata.bge_rx_return_ring_paddr = ctx.bge_busaddr;
-
-	/* Create tag for TX ring. */
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
-	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
-	    NULL, BGE_TX_RING_SZ, 1, BGE_TX_RING_SZ, 0, NULL, NULL,
-	    &sc->bge_cdata.bge_tx_ring_tag);
-
-	if (error) {
-		device_printf(sc->bge_dev, "could not allocate dma tag\n");
-		return (ENOMEM);
-	}
-
-	/* Allocate DMA'able memory for TX ring. */
-	error = bus_dmamem_alloc(sc->bge_cdata.bge_tx_ring_tag,
-	    (void **)&sc->bge_ldata.bge_tx_ring, BUS_DMA_NOWAIT,
-	    &sc->bge_cdata.bge_tx_ring_map);
-	if (error)
-		return (ENOMEM);
-
-	bzero((char *)sc->bge_ldata.bge_tx_ring, BGE_TX_RING_SZ);
-
-	/* Load the address of the TX ring. */
-	ctx.bge_maxsegs = 1;
-	ctx.sc = sc;
-
-	error = bus_dmamap_load(sc->bge_cdata.bge_tx_ring_tag,
-	    sc->bge_cdata.bge_tx_ring_map, sc->bge_ldata.bge_tx_ring,
-	    BGE_TX_RING_SZ, bge_dma_map_addr, &ctx, BUS_DMA_NOWAIT);
-
-	if (error)
-		return (ENOMEM);
-
-	sc->bge_ldata.bge_tx_ring_paddr = ctx.bge_busaddr;
-
-	/*
-	 * Create tag for status block.
-	 * Because we only use single Tx/Rx/Rx return ring, use
-	 * minimum status block size except BCM5700 AX/BX which
-	 * seems to want to see full status block size regardless
-	 * of configured number of ring.
-	 */
-	if (sc->bge_asicrev == BGE_ASICREV_BCM5700 &&
-	    sc->bge_chipid != BGE_CHIPID_BCM5700_C0)
-		sbsz = BGE_STATUS_BLK_SZ;
-	else
-		sbsz = 32;
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
-	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
-	    NULL, sbsz, 1, sbsz, 0, NULL, NULL, &sc->bge_cdata.bge_status_tag);
-
-	if (error) {
-		device_printf(sc->bge_dev,
-		    "could not allocate status dma tag\n");
-		return (ENOMEM);
-	}
-
-	/* Allocate DMA'able memory for status block. */
-	error = bus_dmamem_alloc(sc->bge_cdata.bge_status_tag,
-	    (void **)&sc->bge_ldata.bge_status_block, BUS_DMA_NOWAIT,
-	    &sc->bge_cdata.bge_status_map);
-	if (error)
-		return (ENOMEM);
-
-	bzero((char *)sc->bge_ldata.bge_status_block, sbsz);
-
-	/* Load the address of the status block. */
-	ctx.sc = sc;
-	ctx.bge_maxsegs = 1;
-
-	error = bus_dmamap_load(sc->bge_cdata.bge_status_tag,
-	    sc->bge_cdata.bge_status_map, sc->bge_ldata.bge_status_block,
-	    sbsz, bge_dma_map_addr, &ctx, BUS_DMA_NOWAIT);
-
-	if (error)
-		return (ENOMEM);
-
-	sc->bge_ldata.bge_status_block_paddr = ctx.bge_busaddr;
-
-	/* Create tag for statistics block. */
-	error = bus_dma_tag_create(sc->bge_cdata.bge_parent_tag,
-	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL,
-	    NULL, BGE_STATS_SZ, 1, BGE_STATS_SZ, 0, NULL, NULL,
-	    &sc->bge_cdata.bge_stats_tag);
-
-	if (error) {
-		device_printf(sc->bge_dev, "could not allocate dma tag\n");
-		return (ENOMEM);
-	}
-
-	/* Allocate DMA'able memory for statistics block. */
-	error = bus_dmamem_alloc(sc->bge_cdata.bge_stats_tag,
-	    (void **)&sc->bge_ldata.bge_stats, BUS_DMA_NOWAIT,
-	    &sc->bge_cdata.bge_stats_map);
-	if (error)
-		return (ENOMEM);
-
-	bzero((char *)sc->bge_ldata.bge_stats, BGE_STATS_SZ);
-
-	/* Load the address of the statstics block. */
-	ctx.sc = sc;
-	ctx.bge_maxsegs = 1;
-
-	error = bus_dmamap_load(sc->bge_cdata.bge_stats_tag,
-	    sc->bge_cdata.bge_stats_map, sc->bge_ldata.bge_stats,
-	    BGE_STATS_SZ, bge_dma_map_addr, &ctx, BUS_DMA_NOWAIT);
-
-	if (error)
-		return (ENOMEM);
-
-	sc->bge_ldata.bge_stats_paddr = ctx.bge_busaddr;
-
 	return (0);
 }
 
@@ -2788,7 +2695,7 @@ bge_attach(device_t dev)
 	else
 		sc->bge_return_ring_cnt = BGE_RETURN_RING_CNT;
 
-	if (bge_dma_alloc(dev)) {
+	if (bge_dma_alloc(sc)) {
 		device_printf(sc->bge_dev,
 		    "failed to allocate DMA resources\n");
 		error = ENXIO;
diff --git a/sys/dev/bge/if_bgereg.h b/sys/dev/bge/if_bgereg.h
index 6970a3d60da..01e4a6b2df7 100644
--- a/sys/dev/bge/if_bgereg.h
+++ b/sys/dev/bge/if_bgereg.h
@@ -2487,6 +2487,12 @@ struct bge_gib {
 #define	BGE_DMA_MAXADDR		0xFFFFFFFFFF
 #endif
 
+#if (BUS_SPACE_MAXADDR > 0xFFFFFFFF)
+#define	BGE_DMA_4G_BNDRY	0x100000000
+#else
+#define	BGE_DMA_4G_BNDRY	0
+#endif
+
 /*
  * Ring structures. Most of these reside in host memory and we tell
  * the NIC where they are via the ring control blocks. The exceptions
@@ -2530,6 +2536,7 @@ struct bge_ring_data {
  */
 struct bge_chain_data {
 	bus_dma_tag_t		bge_parent_tag;
+	bus_dma_tag_t		bge_buffer_tag;
 	bus_dma_tag_t		bge_rx_std_ring_tag;
 	bus_dma_tag_t		bge_rx_jumbo_ring_tag;
 	bus_dma_tag_t		bge_rx_return_ring_tag;
@@ -2558,12 +2565,7 @@ struct bge_chain_data {
 };
 
 struct bge_dmamap_arg {
-	struct bge_softc	*sc;
 	bus_addr_t		bge_busaddr;
-	uint16_t		bge_flags;
-	int			bge_idx;
-	int			bge_maxsegs;
-	struct bge_tx_bd	*bge_ring;
 };
 
 #define	BGE_HWREV_TIGON		0x01

From 52e2247273baf52aa772948a9a0ea28690e2da2d Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Tue, 31 Aug 2010 17:38:20 +0000
Subject: [PATCH 0393/1624] Always compile pc98 boot2 with gcc instead of
 clang, just as with i386 boot2.  Unfortunately both still are too big when
 compiled with clang.

Reviewed by:	nyan
Approved by:	rpaulo (mentor)
---
 sys/boot/pc98/boot2/Makefile | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/sys/boot/pc98/boot2/Makefile b/sys/boot/pc98/boot2/Makefile
index 63f364c2261..5f7355fd783 100644
--- a/sys/boot/pc98/boot2/Makefile
+++ b/sys/boot/pc98/boot2/Makefile
@@ -1,5 +1,12 @@
 # $FreeBSD$
 
+.include 
+
+# XXX: clang can compile the boot code just fine, but boot2 gets too big
+.if ${CC:T:Mclang} == "clang"
+CC=gcc
+.endif
+
 FILES=		boot boot1 boot2
 
 NM?=		nm

From a2a200a24d6137b42a72f41c8815e6c58f098d02 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Tue, 31 Aug 2010 17:43:47 +0000
Subject: [PATCH 0394/1624] Have memguard(9) crash with an easier-to-debug
 message on double-free.

Reviewed by:    zml
MFC after:      3 weeks
---
 sys/vm/memguard.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/sys/vm/memguard.c b/sys/vm/memguard.c
index 85893ab3807..3cf935c27eb 100644
--- a/sys/vm/memguard.c
+++ b/sys/vm/memguard.c
@@ -247,9 +247,13 @@ SYSINIT(memguard, SI_SUB_KLD, SI_ORDER_ANY, memguard_sysinit, NULL);
 static u_long *
 v2sizep(vm_offset_t va)
 {
+	vm_paddr_t pa;
 	struct vm_page *p;
 
-	p = PHYS_TO_VM_PAGE(pmap_kextract(va));
+	pa = pmap_kextract(va);
+	if (pa == 0)
+		panic("MemGuard detected double-free of %p", (void *)va);
+	p = PHYS_TO_VM_PAGE(pa);
 	KASSERT(p->wire_count != 0 && p->queue == PQ_NONE,
 	    ("MEMGUARD: Expected wired page %p in vtomgfifo!", p));
 	return ((u_long *)&p->pageq.tqe_next);

From 227209559d23063978bb7ce3165394a84201e362 Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Tue, 31 Aug 2010 18:11:50 +0000
Subject: [PATCH 0395/1624] Avoid directly manipulating a NULL pointer (which
 could result in undefined behaviour) in sys/boot/pc98/boot2/boot2.c.

Reviewed by:	nyan
Approved by:	rpaulo (mentor)
---
 sys/boot/pc98/boot2/boot2.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/boot/pc98/boot2/boot2.c b/sys/boot/pc98/boot2/boot2.c
index 8c833ba02d8..e35b42536c2 100644
--- a/sys/boot/pc98/boot2/boot2.c
+++ b/sys/boot/pc98/boot2/boot2.c
@@ -187,9 +187,9 @@ xfsread(ino_t inode, void *buf, size_t nbyte)
 static inline uint32_t
 memsize(void)
 {
-    u_char *p = (u_char *)PTOV(0);
+    u_char *p = (u_char *)PTOV(0x401);
 
-    return *(p + 0x401) * 128 * 1024 + *(u_int16_t *)(p + 0x594) * 1024 * 1024;
+    return *p * 128 * 1024 + *(u_int16_t *)(p + (0x594 - 0x401)) * 1024 * 1024;
 }
 
 static inline void

From 38cc61518b22afb1e0f5b34e7993a0115f4f8d71 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 31 Aug 2010 18:48:09 +0000
Subject: [PATCH 0396/1624] Handle PAE case correctly. You cannot effectively
 specify a 4GB boundary in PAE case so use a 2GB boundary for PAE as suggested
 by jhb.

Pointed out by:	jhb
Reviewed by:	jhb
---
 sys/dev/bge/if_bge.c    |  2 +-
 sys/dev/bge/if_bgereg.h | 10 +++++++---
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index 48f1d452f37..042bd1e44fd 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -2272,7 +2272,7 @@ bge_dma_alloc(struct bge_softc *sc)
 	/* Create parent tag for buffers. */
 	boundary = 0;
 	if ((sc->bge_flags & BGE_FLAG_4G_BNDRY_BUG) != 0)
-		boundary = BGE_DMA_4G_BNDRY;
+		boundary = BGE_DMA_BNDRY;
 	error = bus_dma_tag_create(bus_get_dma_tag(sc->bge_dev),
 	    1, boundary, lowaddr, BUS_SPACE_MAXADDR, NULL,
 	    NULL, BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
diff --git a/sys/dev/bge/if_bgereg.h b/sys/dev/bge/if_bgereg.h
index 01e4a6b2df7..d17d56d4903 100644
--- a/sys/dev/bge/if_bgereg.h
+++ b/sys/dev/bge/if_bgereg.h
@@ -2487,10 +2487,14 @@ struct bge_gib {
 #define	BGE_DMA_MAXADDR		0xFFFFFFFFFF
 #endif
 
-#if (BUS_SPACE_MAXADDR > 0xFFFFFFFF)
-#define	BGE_DMA_4G_BNDRY	0x100000000
+#ifdef PAE
+#define	BGE_DMA_BNDRY		0x80000000
 #else
-#define	BGE_DMA_4G_BNDRY	0
+#if (BUS_SPACE_MAXADDR > 0xFFFFFFFF)
+#define	BGE_DMA_BNDRY		0x100000000
+#else
+#define	BGE_DMA_BNDRY		0
+#endif
 #endif
 
 /*

From cff47502332de59b864b682851f99d954d8fcc45 Mon Sep 17 00:00:00 2001
From: Xin LI 
Date: Tue, 31 Aug 2010 19:01:12 +0000
Subject: [PATCH 0397/1624] For consistency, change all 'i386' and MACHINE_ARCH
 to x86.

Reviewed by:	jhb
MFC after:	1 week
---
 sys/boot/i386/efi/Makefile       | 2 +-
 sys/boot/i386/loader/Makefile    | 2 +-
 sys/boot/i386/zfsloader/Makefile | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/sys/boot/i386/efi/Makefile b/sys/boot/i386/efi/Makefile
index 2d1104611f5..943de119081 100644
--- a/sys/boot/i386/efi/Makefile
+++ b/sys/boot/i386/efi/Makefile
@@ -42,7 +42,7 @@ ${PROG}:	${LDSCRIPT}
 
 CLEANFILES=	vers.c loader.efi
 
-NEWVERSWHAT=	"EFI loader" ${MACHINE_ARCH}
+NEWVERSWHAT=	"EFI loader" x86
 
 vers.c:	${.CURDIR}/../../common/newvers.sh ${.CURDIR}/version
 	sh ${.CURDIR}/../../common/newvers.sh ${.CURDIR}/version ${NEWVERSWHAT}
diff --git a/sys/boot/i386/loader/Makefile b/sys/boot/i386/loader/Makefile
index a6f0d97919a..b834ea064f3 100644
--- a/sys/boot/i386/loader/Makefile
+++ b/sys/boot/i386/loader/Makefile
@@ -6,7 +6,7 @@ MK_SSP=		no
 LOADER?=	loader
 PROG=		${LOADER}.sym
 INTERNALPROG=
-NEWVERSWHAT?=	"bootstrap loader" i386
+NEWVERSWHAT?=	"bootstrap loader" x86
 
 # architecture-specific loader code
 SRCS=		main.c conf.c vers.c
diff --git a/sys/boot/i386/zfsloader/Makefile b/sys/boot/i386/zfsloader/Makefile
index 51338e17f82..926d69d0548 100644
--- a/sys/boot/i386/zfsloader/Makefile
+++ b/sys/boot/i386/zfsloader/Makefile
@@ -3,7 +3,7 @@
 .PATH:	${.CURDIR}/../loader
 
 LOADER=		zfsloader
-NEWVERSWHAT=	"ZFS enabled bootstrap loader" i386
+NEWVERSWHAT=	"ZFS enabled bootstrap loader" x86
 LOADER_ZFS_SUPPORT=yes
 LOADER_ONLY=	yes
 NO_MAN=		yes

From 81bbc7f7494264682705579f7313ec4a24c7b586 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 31 Aug 2010 19:01:46 +0000
Subject: [PATCH 0398/1624] Eliminate confusing while () loop. In the first
 version of the code it was there to avoid gotos, but in the current version
 it serves no purpose.

MFC after:	2 weeks
---
 cddl/contrib/opensolaris/cmd/zpool/zpool_main.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c b/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
index 2d9891674a7..08d8afeb0b4 100644
--- a/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
+++ b/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
@@ -3347,20 +3347,19 @@ is_root_pool(zpool_handle_t *zhp)
 	static boolean_t stated = B_FALSE;
 	char *slash;
 
-	while (!stated) {
+	if (!stated) {
 		stated = B_TRUE;
 		if (statfs("/", &sfs) == -1) {
 			(void) fprintf(stderr,
 			    "Unable to stat root file system: %s.\n",
 			    strerror(errno));
-			break;
+			return (0);
 		}
 		if (strcmp(sfs.f_fstypename, "zfs") != 0)
-			break;
+			return (0);
 		poolname = sfs.f_mntfromname;
 		if ((slash = strchr(poolname, '/')) != NULL)
 			*slash = '\0';
-		break;
 	}
 	return (poolname != NULL && strcmp(poolname, zpool_get_name(zhp)) == 0);
 }

From 95a0a340f4da999669db57b4fdea5afede9b0bd1 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 31 Aug 2010 19:59:18 +0000
Subject: [PATCH 0399/1624] bge_txeof() already checks whether it has to free
 transmitted mbufs or not by comparing reported TX consumer index with saved
 index. So remove unnecessary check done after freeing transmitted mbufs.
 While I'm here nuke unnecessary variable initializations.

---
 sys/dev/bge/if_bge.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index 042bd1e44fd..585e1f6d7f1 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -3394,7 +3394,7 @@ bge_rxeof(struct bge_softc *sc, uint16_t rx_prod, int holdlck)
 static void
 bge_txeof(struct bge_softc *sc, uint16_t tx_cons)
 {
-	struct bge_tx_bd *cur_tx = NULL;
+	struct bge_tx_bd *cur_tx;
 	struct ifnet *ifp;
 
 	BGE_LOCK_ASSERT(sc);
@@ -3412,7 +3412,7 @@ bge_txeof(struct bge_softc *sc, uint16_t tx_cons)
 	 * frames that have been sent.
 	 */
 	while (sc->bge_tx_saved_considx != tx_cons) {
-		uint32_t		idx = 0;
+		uint32_t		idx;
 
 		idx = sc->bge_tx_saved_considx;
 		cur_tx = &sc->bge_ldata.bge_tx_ring[idx];
@@ -3431,8 +3431,7 @@ bge_txeof(struct bge_softc *sc, uint16_t tx_cons)
 		BGE_INC(sc->bge_tx_saved_considx, BGE_TX_RING_CNT);
 	}
 
-	if (cur_tx != NULL)
-		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
+	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
 	if (sc->bge_txcnt == 0)
 		sc->bge_timer = 0;
 }

From c74dea9cc1dbc0350c6321ce3efe07b6e3bdeb01 Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Tue, 31 Aug 2010 20:21:52 +0000
Subject: [PATCH 0400/1624] Make sure the interrupt entry point is within the
 video ROM range.  We must not change interrupt vector if it is not pointing
 the ROM itself.  Actually, we just fail shadowing altogether if that is the
 case because the shadowed copy will be useless for sure and POST may not be
 relocatable or useful. While I'm here, fix a debugging message under
 bootverbose, really.  r211829 fixed one case but broke another.  Mea Culpa.

---
 sys/dev/fb/vesa.c | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/sys/dev/fb/vesa.c b/sys/dev/fb/vesa.c
index 5fa4eb42ef2..68f184b5c8e 100644
--- a/sys/dev/fb/vesa.c
+++ b/sys/dev/fb/vesa.c
@@ -799,19 +799,25 @@ vesa_bios_init(void)
 	/*
 	 * Shadow video ROM.
 	 */
-	offs = BIOS_SADDRTOLADDR(vesa_bios_int10);
+	offs = vesa_bios_int10;
 	if (vesa_shadow_rom) {
 		vbios = x86bios_get_orm(vesa_bios_offs);
 		if (vbios != NULL) {
 			vesa_bios_size = vbios[2] * 512;
-			vesa_bios = x86bios_alloc(&vesa_bios_offs,
-			    vesa_bios_size, M_WAITOK);
-			memcpy(vesa_bios, vbios, vesa_bios_size);
-			offs = offs - VESA_BIOS_OFFSET + vesa_bios_offs;
-			offs = (X86BIOS_PHYSTOSEG(offs) << 16) +
-			    X86BIOS_PHYSTOOFF(offs);
-			x86bios_set_intr(0x10, offs);
-		} else
+			offs = BIOS_SADDRTOLADDR(vesa_bios_int10);
+			if (offs > vesa_bios_offs &&
+			    offs < vesa_bios_offs + vesa_bios_size) {
+				vesa_bios = x86bios_alloc(&vesa_bios_offs,
+				    vesa_bios_size, M_WAITOK);
+				memcpy(vesa_bios, vbios, vesa_bios_size);
+				offs = offs - VESA_BIOS_OFFSET + vesa_bios_offs;
+				offs = (X86BIOS_PHYSTOSEG(offs) << 16) +
+				    X86BIOS_PHYSTOOFF(offs);
+				x86bios_set_intr(0x10, offs);
+			} else
+				offs = vesa_bios_int10;
+		}
+		if (vesa_bios == NULL)
 			printf("VESA: failed to shadow video ROM\n");
 	}
 	if (bootverbose)

From 175f87424f39f89d61e802cd9b7546a5dc9b0af1 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 31 Aug 2010 20:56:18 +0000
Subject: [PATCH 0401/1624] Remove unnecessary atomic operation in bge_poll.
 bge(4) always holds a driver lock in the function entry and memory
 synchronization is handled by bus_dmamap_sync(9).

---
 sys/dev/bge/if_bge.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index 585e1f6d7f1..30ccf22c43d 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -3457,8 +3457,8 @@ bge_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
 	rx_prod = sc->bge_ldata.bge_status_block->bge_idx[0].bge_rx_prod_idx;
 	tx_cons = sc->bge_ldata.bge_status_block->bge_idx[0].bge_tx_cons_idx;
 
-	statusword = atomic_readandclear_32(
-	    &sc->bge_ldata.bge_status_block->bge_status);
+	statusword = sc->bge_ldata.bge_status_block->bge_status;
+	sc->bge_ldata.bge_status_block->bge_status = 0;
 
 	bus_dmamap_sync(sc->bge_cdata.bge_status_tag,
 	    sc->bge_cdata.bge_status_map,

From fa04d5d393f1fe9733cb8dc9c7f66700a28985dc Mon Sep 17 00:00:00 2001
From: Jamie Gritton 
Date: Tue, 31 Aug 2010 21:48:45 +0000
Subject: [PATCH 0402/1624] Make it clear in the example that
 jailparam_export's return value should be freed.

MFC after:	3 days
---
 lib/libjail/jail.3 | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/libjail/jail.3 b/lib/libjail/jail.3
index 4207b0253a7..ee80e014d18 100644
--- a/lib/libjail/jail.3
+++ b/lib/libjail/jail.3
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd June 24, 2009
+.Dd August 31, 2010
 .Dt JAIL 3
 .Os
 .Sh NAME
@@ -248,6 +248,8 @@ jailparam_init(¶ms[1], "host.hostname");
 jailparam_get(params, 2, 0);
 hostname = jailparam_export(¶ms[1]);
 jailparam_free(params, 2);
+...
+free(hostname);
 .Ed
 .Sh ERRORS
 The

From 4d02a3e762285e35921bc27466178623006acacc Mon Sep 17 00:00:00 2001
From: Jamie Gritton 
Date: Tue, 31 Aug 2010 21:50:09 +0000
Subject: [PATCH 0403/1624] Don't over-allocate array values in
 jailparam_export. Fix a little comment typo.

MFC after:	3 days
---
 lib/libjail/jail.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/lib/libjail/jail.c b/lib/libjail/jail.c
index a3745634dcf..46da6b49e3f 100644
--- a/lib/libjail/jail.c
+++ b/lib/libjail/jail.c
@@ -719,6 +719,7 @@ jailparam_get(struct jailparam *jp, unsigned njp, int flags)
 char *
 jailparam_export(struct jailparam *jp)
 {
+	size_t *valuelens;
 	char *value, *tvalue, **values;
 	size_t valuelen;
 	int i, nval, ival;
@@ -740,6 +741,7 @@ jailparam_export(struct jailparam *jp)
 		return (value);
 	}
 	values = alloca(nval * sizeof(char *));
+	valuelens = alloca(nval * sizeof(size_t));
 	valuelen = 0;
 	for (i = 0; i < nval; i++) {
 		switch (jp->jp_ctltype & CTLTYPE) {
@@ -809,11 +811,12 @@ jailparam_export(struct jailparam *jp)
 			errno = ENOENT;
 			return (NULL);
 		}
-		valuelen += strlen(valbuf) + 1;
-		values[i] = alloca(valuelen);
+		valuelens[i] = strlen(valbuf) + 1;
+		valuelen += valuelens[i];
+		values[i] = alloca(valuelens[i]);
 		strcpy(values[i], valbuf);
 	}
-	value = malloc(valuelen + 1);
+	value = malloc(valuelen);
 	if (value == NULL)
 		strerror_r(errno, jail_errmsg, JAIL_ERRMSGLEN);
 	else {
@@ -821,8 +824,8 @@ jailparam_export(struct jailparam *jp)
 		for (i = 0; i < nval; i++) {
 			strcpy(tvalue, values[i]);
 			if (i < nval - 1) {
-				tvalue += strlen(values[i]);
-				*tvalue++ = ',';
+				tvalue += valuelens[i];
+				tvalue[-1] = ',';
 			}
 		}
 	}
@@ -830,7 +833,7 @@ jailparam_export(struct jailparam *jp)
 }
 
 /*
- * Free the contents of a jail parameter list (but not thst list itself).
+ * Free the contents of a jail parameter list (but not the list itself).
  */
 void
 jailparam_free(struct jailparam *jp, unsigned njp)

From 881f6af44be20eca52a691d34776557f1d0b0433 Mon Sep 17 00:00:00 2001
From: Jamie Gritton 
Date: Tue, 31 Aug 2010 23:14:03 +0000
Subject: [PATCH 0404/1624] Whitespace and comment fixes.

MFC after:	3 days
---
 lib/libjail/jail.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/lib/libjail/jail.c b/lib/libjail/jail.c
index 46da6b49e3f..1be8358d85b 100644
--- a/lib/libjail/jail.c
+++ b/lib/libjail/jail.c
@@ -786,7 +786,6 @@ jailparam_export(struct jailparam *jp)
 				    valbuf, sizeof(valbuf)) == NULL) {
 					strerror_r(errno, jail_errmsg,
 					    JAIL_ERRMSGLEN);
-
 					return (NULL);
 				}
 				break;
@@ -796,7 +795,6 @@ jailparam_export(struct jailparam *jp)
 				    valbuf, sizeof(valbuf)) == NULL) {
 					strerror_r(errno, jail_errmsg,
 					    JAIL_ERRMSGLEN);
-
 					return (NULL);
 				}
 				break;
@@ -894,7 +892,7 @@ jailparam_type(struct jailparam *jp)
 				mib[1] = 4;
 				desclen = sizeof(desc);
 				if (sysctl(mib, (miblen / sizeof(int)) + 2,
-					   &desc, &desclen, NULL, 0) < 0) {
+				    &desc, &desclen, NULL, 0) < 0) {
 					snprintf(jail_errmsg,
 					    JAIL_ERRMSGLEN,
 					    "sysctl(0.4.%s): %s", desc.s,
@@ -934,7 +932,7 @@ jailparam_type(struct jailparam *jp)
 		isarray = 1;
 		p[-2] = 0;
 	}
-	/* Look for types we understand */
+	/* Look for types we understand. */
 	jp->jp_ctltype = desc.i;
 	switch (desc.i & CTLTYPE) {
 	case CTLTYPE_INT:

From 137cf33d5e6d78f173f70f818abca937b43f8c85 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 1 Sep 2010 01:26:07 +0000
Subject: [PATCH 0405/1624] rescure comments from RELENG_4.

---
 sys/kern/kern_sig.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/sys/kern/kern_sig.c b/sys/kern/kern_sig.c
index 9cbbe8d6c97..f54d59e59f2 100644
--- a/sys/kern/kern_sig.c
+++ b/sys/kern/kern_sig.c
@@ -2140,6 +2140,10 @@ tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
 	 */
 	if (P_SHOULDSTOP(p)) {
 		if (sig == SIGKILL) {
+			/*
+			 * If traced process is already stopped,
+			 * then no further action is necessary.
+			 */
 			if (p->p_flag & P_TRACED)
 				goto out;
 			/*
@@ -2152,6 +2156,10 @@ tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
 		}
 
 		if (prop & SA_CONT) {
+			/*
+			 * If traced process is already stopped,
+			 * then no further action is necessary.
+			 */
 			if (p->p_flag & P_TRACED)
 				goto out;
 			/*
@@ -2198,6 +2206,10 @@ tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
 		}
 
 		if (prop & SA_STOP) {
+			/*
+			 * If traced process is already stopped,
+			 * then no further action is necessary.
+			 */
 			if (p->p_flag & P_TRACED)
 				goto out;
 			/*

From 02c3c85869f7ceee39a6e721b02df49714b49867 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 1 Sep 2010 02:18:33 +0000
Subject: [PATCH 0406/1624] Add signal handler wrapper, the reason to add it
 becauses there are some cases we want to improve:   1) if a thread signal got
 a signal while in cancellation point,      it is possible the TDP_WAKEUP may
 be eaten by signal handler      if the handler called some interruptibly
 system calls.   2) In signal handler, we want to disable cancellation.   3)
 When thread holding some low level locks, it is better to      disable
 signal, those code need not to worry reentrancy,      sigprocmask system call
 is avoided because it is a bit expensive. The signal handler wrapper works in
 this way:   1) libthr installs its signal handler if user code invokes
 sigaction      to install its handler, the user handler is recorded in
 internal      array.   2) when a signal is delivered, libthr's signal handler
 is invoke,      libthr checks if thread holds some low level lock or is in
 critical      region, if it is true, the signal is buffered, and all signals
 are      masked, once the thread leaves critical region, correct signal     
 mask is restored and buffered signal is processed.   3) before user signal
 handler is invoked, cancellation is temporarily      disabled, after user
 signal handler is returned, cancellation state      is restored, and pending
 cancellation is rescheduled.

---
 lib/libthr/thread/thr_cancel.c   |  41 +--
 lib/libthr/thread/thr_cond.c     |   4 +-
 lib/libthr/thread/thr_create.c   |  13 -
 lib/libthr/thread/thr_exit.c     |  19 ++
 lib/libthr/thread/thr_fork.c     |   6 +
 lib/libthr/thread/thr_init.c     |   8 +-
 lib/libthr/thread/thr_join.c     |   4 +-
 lib/libthr/thread/thr_kern.c     |  32 --
 lib/libthr/thread/thr_private.h  |  33 +-
 lib/libthr/thread/thr_rtld.c     |  13 +-
 lib/libthr/thread/thr_sig.c      | 526 +++++++++++++++++++++++++------
 lib/libthr/thread/thr_syscalls.c | 129 ++++----
 lib/libthr/thread/thr_umtx.c     |  39 +++
 lib/libthr/thread/thr_umtx.h     |   5 +
 14 files changed, 595 insertions(+), 277 deletions(-)

diff --git a/lib/libthr/thread/thr_cancel.c b/lib/libthr/thread/thr_cancel.c
index 943d53c39e9..e408e03dbcd 100644
--- a/lib/libthr/thread/thr_cancel.c
+++ b/lib/libthr/thread/thr_cancel.c
@@ -85,14 +85,11 @@ _pthread_setcancelstate(int state, int *oldstate)
 	oldval = curthread->cancel_enable;
 	switch (state) {
 	case PTHREAD_CANCEL_DISABLE:
-		THR_LOCK(curthread);
 		curthread->cancel_enable = 0;
-		THR_UNLOCK(curthread);
 		break;
 	case PTHREAD_CANCEL_ENABLE:
-		THR_LOCK(curthread);
 		curthread->cancel_enable = 1;
-		THR_UNLOCK(curthread);
+		testcancel(curthread);
 		break;
 	default:
 		return (EINVAL);
@@ -136,23 +133,22 @@ _pthread_testcancel(void)
 {
 	struct pthread *curthread = _get_curthread();
 
-	_thr_cancel_enter(curthread);
-	_thr_cancel_leave(curthread);
+	curthread->cancel_point = 1;
+	testcancel(curthread);
+	curthread->cancel_point = 0;
 }
 
 void
 _thr_cancel_enter(struct pthread *curthread)
 {
-	curthread->cancel_point++;
-	if (curthread->cancel_enable)
-		testcancel(curthread);
+	curthread->cancel_point = 1;
+	testcancel(curthread);
 }
 
 void
-_thr_cancel_enter_defer(struct pthread *curthread, int maycancel)
+_thr_cancel_enter2(struct pthread *curthread, int maycancel)
 {
-	curthread->cancel_defer++;
-	curthread->cancel_point++;
+	curthread->cancel_point = 1;
 	if (__predict_false(SHOULD_CANCEL(curthread) &&
 	    !THR_IN_CRITICAL(curthread))) {
 		if (!maycancel)
@@ -163,24 +159,9 @@ _thr_cancel_enter_defer(struct pthread *curthread, int maycancel)
 }
 
 void
-_thr_cancel_leave(struct pthread *curthread)
+_thr_cancel_leave(struct pthread *curthread, int maycancel)
 {
-	curthread->cancel_point--;
-}
-
-void
-_thr_cancel_leave2(struct pthread *curthread, int maycancel)
-{
-	if (curthread->cancel_enable && maycancel)
+	if (maycancel)
 		testcancel(curthread);
-	curthread->cancel_point--;
-}
-
-void
-_thr_cancel_leave_defer(struct pthread *curthread, int maycancel)
-{
-	if (curthread->cancel_enable && maycancel)
-		testcancel(curthread);
-	curthread->cancel_point--;
-	curthread->cancel_defer--;
+	curthread->cancel_point = 0;
 }
diff --git a/lib/libthr/thread/thr_cond.c b/lib/libthr/thread/thr_cond.c
index 95970d9d0fc..07f1b8b952c 100644
--- a/lib/libthr/thread/thr_cond.c
+++ b/lib/libthr/thread/thr_cond.c
@@ -210,10 +210,10 @@ cond_wait_common(pthread_cond_t *cond, pthread_mutex_t *mutex,
 
 	if (cancel) {
 		THR_CLEANUP_PUSH(curthread, cond_cancel_handler, &info);
-		_thr_cancel_enter_defer(curthread, 0);
+		_thr_cancel_enter2(curthread, 0);
 		ret = _thr_ucond_wait(&cv->c_kerncv, &cv->c_lock, tsp, 1);
 		info.cond = NULL;
-		_thr_cancel_leave_defer(curthread, (ret != 0));
+		_thr_cancel_leave(curthread, (ret != 0));
 		THR_CLEANUP_POP(curthread, 0);
 	} else {
 		ret = _thr_ucond_wait(&cv->c_kerncv, &cv->c_lock, tsp, 0);
diff --git a/lib/libthr/thread/thr_create.c b/lib/libthr/thread/thr_create.c
index f73a6c9231b..2677571b424 100644
--- a/lib/libthr/thread/thr_create.c
+++ b/lib/libthr/thread/thr_create.c
@@ -127,11 +127,6 @@ _pthread_create(pthread_t * thread, const pthread_attr_t * attr,
 	if (new_thread->attr.flags & PTHREAD_CREATE_DETACHED)
 		new_thread->tlflags |= TLFLAGS_DETACHED;
 
-	if (curthread->in_sigcancel_handler)
-		new_thread->unblock_sigcancel = 1;
-	else
-		new_thread->unblock_sigcancel = 0;
-
 	/* Add the new thread. */
 	new_thread->refcount = 1;
 	_thr_link(curthread, new_thread);
@@ -263,14 +258,6 @@ thread_start(struct pthread *curthread)
 	if (curthread->force_exit)
 		_pthread_exit(PTHREAD_CANCELED);
 
-	if (curthread->unblock_sigcancel) {
-		sigset_t set1;
-
-		SIGEMPTYSET(set1);
-		SIGADDSET(set1, SIGCANCEL);
-		__sys_sigprocmask(SIG_UNBLOCK, &set1, NULL);
-	}
-
 	if (curthread->attr.suspend == THR_CREATE_SUSPENDED) {
 #if 0
 		/* Done in THR_UNLOCK() */
diff --git a/lib/libthr/thread/thr_exit.c b/lib/libthr/thread/thr_exit.c
index e6facd9d85b..10581ab2395 100644
--- a/lib/libthr/thread/thr_exit.c
+++ b/lib/libthr/thread/thr_exit.c
@@ -34,6 +34,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 #include "un-namespace.h"
 
 #include "libc_private.h"
@@ -57,6 +59,12 @@ _thread_exit(const char *fname, int lineno, const char *msg)
 
 void
 _pthread_exit(void *status)
+{
+	_pthread_exit_mask(status, NULL);
+}
+
+void
+_pthread_exit_mask(void *status, sigset_t *mask)
 {
 	struct pthread *curthread = _get_curthread();
 
@@ -73,6 +81,17 @@ _pthread_exit(void *status)
 	curthread->cancelling = 1;
 	curthread->cancel_enable = 0;
 	curthread->cancel_async = 0;
+	curthread->cancel_point = 0;
+	if (mask != NULL)
+		__sys_sigprocmask(SIG_SETMASK, mask, NULL);
+	if (curthread->unblock_sigcancel) {
+		sigset_t set;
+
+		curthread->unblock_sigcancel = 0;
+		SIGEMPTYSET(set);
+		SIGADDSET(set, SIGCANCEL);
+		__sys_sigprocmask(SIG_UNBLOCK, mask, NULL);
+	}
 	
 	/* Save the return value: */
 	curthread->ret = status;
diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index f20942d42be..8e1ea6a5e72 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -115,6 +115,7 @@ __pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
 	}
 	THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
 	_thr_tsd_unload(phdr_info);
+	_thr_sigact_unload(phdr_info);
 }
 
 __weak_reference(_fork, fork);
@@ -161,6 +162,7 @@ _fork(void)
 	 * Block all signals until we reach a safe point.
 	 */
 	_thr_signal_block(curthread);
+	_thr_signal_prefork();
 
 	/* Fork a new process: */
 	if ((ret = __sys_fork()) == 0) {
@@ -182,6 +184,8 @@ _fork(void)
 		_thr_umutex_init(&curthread->lock);
 		_thr_umutex_init(&_thr_atfork_lock);
 
+		_thr_signal_postfork_child();
+
 		if (was_threaded)
 			_rtld_atfork_post(rtld_locks);
 		_thr_setthreaded(0);
@@ -211,6 +215,8 @@ _fork(void)
 		/* Parent process */
 		errsave = errno;
 
+		_thr_signal_postfork();
+
 		/* Ready to continue, unblock signals. */ 
 		_thr_signal_unblock(curthread);
 
diff --git a/lib/libthr/thread/thr_init.c b/lib/libthr/thread/thr_init.c
index 1bfdd287c20..ea567ee9958 100644
--- a/lib/libthr/thread/thr_init.c
+++ b/lib/libthr/thread/thr_init.c
@@ -289,7 +289,6 @@ void
 _libpthread_init(struct pthread *curthread)
 {
 	int fd, first = 0;
-	sigset_t sigset, oldset;
 
 	/* Check if this function has already been called: */
 	if ((_thr_initial != NULL) && (curthread == NULL))
@@ -347,13 +346,8 @@ _libpthread_init(struct pthread *curthread)
 	_tcb_set(curthread->tcb);
 
 	if (first) {
-		SIGFILLSET(sigset);
-		SIGDELSET(sigset, SIGTRAP);
-		__sys_sigprocmask(SIG_SETMASK, &sigset, &oldset);
-		_thr_signal_init();
 		_thr_initial = curthread;
-		SIGDELSET(oldset, SIGCANCEL);
-		__sys_sigprocmask(SIG_SETMASK, &oldset, NULL);
+		_thr_signal_init();
 		if (_thread_event_mask & TD_CREATE)
 			_thr_report_creation(curthread, curthread);
 	}
diff --git a/lib/libthr/thread/thr_join.c b/lib/libthr/thread/thr_join.c
index 8201abafeae..d3c8367dc13 100644
--- a/lib/libthr/thread/thr_join.c
+++ b/lib/libthr/thread/thr_join.c
@@ -107,7 +107,7 @@ join_common(pthread_t pthread, void **thread_return,
 	THREAD_LIST_UNLOCK(curthread);
 
 	THR_CLEANUP_PUSH(curthread, backout_join, pthread);
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 
 	tid = pthread->tid;
 	while (pthread->tid != TID_TERMINATED) {
@@ -127,7 +127,7 @@ join_common(pthread_t pthread, void **thread_return,
 			break;
 	}
 
-	_thr_cancel_leave_defer(curthread, 0);
+	_thr_cancel_leave(curthread, 0);
 	THR_CLEANUP_POP(curthread, 0);
 
 	if (ret == ETIMEDOUT) {
diff --git a/lib/libthr/thread/thr_kern.c b/lib/libthr/thread/thr_kern.c
index 649a973aabd..3ad33ad995a 100644
--- a/lib/libthr/thread/thr_kern.c
+++ b/lib/libthr/thread/thr_kern.c
@@ -60,38 +60,6 @@ _thr_setthreaded(int threaded)
 	return (0);
 }
 
-void
-_thr_signal_block(struct pthread *curthread)
-{
-	sigset_t set;
-	
-	if (curthread->sigblock > 0) {
-		curthread->sigblock++;
-		return;
-	}
-	SIGFILLSET(set);
-	SIGDELSET(set, SIGBUS);
-	SIGDELSET(set, SIGILL);
-	SIGDELSET(set, SIGFPE);
-	SIGDELSET(set, SIGSEGV);
-	SIGDELSET(set, SIGTRAP);
-	__sys_sigprocmask(SIG_BLOCK, &set, &curthread->sigmask);
-	curthread->sigblock++;
-}
-
-void
-_thr_signal_unblock(struct pthread *curthread)
-{
-	if (--curthread->sigblock == 0)
-		__sys_sigprocmask(SIG_SETMASK, &curthread->sigmask, NULL);
-}
-
-int
-_thr_send_sig(struct pthread *thread, int sig)
-{
-	return thr_kill(thread->tid, sig);
-}
-
 void
 _thr_assert_lock_level()
 {
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index f261810e7e9..492d58d2063 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -376,12 +376,21 @@ struct pthread {
 	/* Thread temporary signal mask. */
 	sigset_t		sigmask;
 
-	/* Thread is in SIGCANCEL handler. */
-	int			in_sigcancel_handler;
-
-	/* New thread should unblock SIGCANCEL. */
+	/* Thread should unblock SIGCANCEL. */
 	int			unblock_sigcancel;
 
+	/* In sigsuspend state */
+	int			in_sigsuspend;
+
+	/* deferred signal info	*/
+	siginfo_t		deferred_siginfo;
+
+	/* signal mask to restore. */
+	sigset_t		deferred_sigmask;
+
+	/* the sigaction should be used for deferred signal. */
+	struct sigaction	deferred_sigact;
+
 	/* Force new thread to exit. */
 	int			force_exit;
 
@@ -629,6 +638,7 @@ void	_thr_ref_delete_unlocked(struct pthread *, struct pthread *) __hidden;
 int	_thr_find_thread(struct pthread *, struct pthread *, int) __hidden;
 void	_thr_rtld_init(void) __hidden;
 void	_thr_rtld_fini(void) __hidden;
+void	_thr_rtld_postfork_child(void) __hidden;
 int	_thr_stack_alloc(struct pthread_attr *) __hidden;
 void	_thr_stack_free(struct pthread_attr *) __hidden;
 void	_thr_free(struct pthread *, struct pthread *) __hidden;
@@ -637,10 +647,8 @@ void    _thread_cleanupspecific(void) __hidden;
 void	_thread_printf(int, const char *, ...) __hidden;
 void	_thr_spinlock_init(void) __hidden;
 void	_thr_cancel_enter(struct pthread *) __hidden;
-void	_thr_cancel_leave(struct pthread *) __hidden;
-void	_thr_cancel_leave2(struct pthread *, int) __hidden;
-void	_thr_cancel_enter_defer(struct pthread *, int) __hidden;
-void	_thr_cancel_leave_defer(struct pthread *, int) __hidden;
+void	_thr_cancel_enter2(struct pthread *, int) __hidden;
+void	_thr_cancel_leave(struct pthread *, int) __hidden;
 void	_thr_testcancel(struct pthread *) __hidden;
 void	_thr_signal_block(struct pthread *) __hidden;
 void	_thr_signal_unblock(struct pthread *) __hidden;
@@ -653,7 +661,6 @@ void	_thr_hash_remove(struct pthread *) __hidden;
 struct pthread *_thr_hash_find(struct pthread *) __hidden;
 void	_thr_link(struct pthread *, struct pthread *) __hidden;
 void	_thr_unlink(struct pthread *, struct pthread *) __hidden;
-void	_thr_suspend_check(struct pthread *) __hidden;
 void	_thr_assert_lock_level(void) __hidden __dead2;
 void	_thr_ast(struct pthread *) __hidden;
 void	_thr_once_init(void) __hidden;
@@ -662,6 +669,9 @@ void	_thr_report_creation(struct pthread *curthread,
 void	_thr_report_death(struct pthread *curthread) __hidden;
 int	_thr_getscheduler(lwpid_t, int *, struct sched_param *) __hidden;
 int	_thr_setscheduler(lwpid_t, int, const struct sched_param *) __hidden;
+void	_thr_signal_prefork(void) __hidden;
+void	_thr_signal_postfork(void) __hidden;
+void	_thr_signal_postfork_child(void) __hidden;
 int	_rtp_to_schedparam(const struct rtprio *rtp, int *policy,
 		struct sched_param *param) __hidden;
 int	_schedparam_to_rtp(int policy, const struct sched_param *param,
@@ -672,6 +682,8 @@ int	_sched_yield(void);
 
 void	_pthread_cleanup_push(void (*)(void *), void *);
 void	_pthread_cleanup_pop(int);
+void	_pthread_exit_mask(void *status, sigset_t *mask) __dead2 __hidden;
+
 
 /* #include  */
 #ifdef  _SYS_FCNTL_H_
@@ -687,7 +699,7 @@ int     __sys_sigaction(int, const struct sigaction *, struct sigaction *);
 int     __sys_sigpending(sigset_t *);
 int     __sys_sigprocmask(int, const sigset_t *, sigset_t *);
 int     __sys_sigsuspend(const sigset_t *);
-int     __sys_sigreturn(ucontext_t *);
+int     __sys_sigreturn(const ucontext_t *);
 int     __sys_sigaltstack(const struct sigaltstack *, struct sigaltstack *);
 int	__sys_sigwait(const sigset_t *, int *);
 int	__sys_sigtimedwait(const sigset_t *, siginfo_t *,
@@ -740,6 +752,7 @@ _thr_check_init(void)
 struct dl_phdr_info;
 void __pthread_cxa_finalize(struct dl_phdr_info *phdr_info);
 void _thr_tsd_unload(struct dl_phdr_info *phdr_info) __hidden;
+void _thr_sigact_unload(struct dl_phdr_info *phdr_info) __hidden;
 
 __END_DECLS
 
diff --git a/lib/libthr/thread/thr_rtld.c b/lib/libthr/thread/thr_rtld.c
index d9041adcfb9..e6af7029c76 100644
--- a/lib/libthr/thread/thr_rtld.c
+++ b/lib/libthr/thread/thr_rtld.c
@@ -32,6 +32,7 @@
   */
 #include 
 #include 
+#include 
 
 #include "rtld_lock.h"
 #include "thr_private.h"
@@ -132,7 +133,7 @@ _thr_rtld_wlock_acquire(void *lock)
 	SAVE_ERRNO();
 	l = (struct rtld_lock *)lock;
 
-	_thr_signal_block(curthread);
+	THR_CRITICAL_ENTER(curthread);
 	while (_thr_rwlock_wrlock(&l->lock, NULL) != 0)
 		;
 	RESTORE_ERRNO();
@@ -152,12 +153,9 @@ _thr_rtld_lock_release(void *lock)
 	
 	state = l->lock.rw_state;
 	if (_thr_rwlock_unlock(&l->lock) == 0) {
-		if ((state & URWLOCK_WRITE_OWNER) == 0) {
+		if ((state & URWLOCK_WRITE_OWNER) == 0)
 			curthread->rdlock_count--;
-			THR_CRITICAL_LEAVE(curthread);
-		} else {
-			_thr_signal_unblock(curthread);
-		}
+		THR_CRITICAL_LEAVE(curthread);
 	}
 	RESTORE_ERRNO();
 }
@@ -193,6 +191,9 @@ _thr_rtld_init(void)
 	/* force to resolve errno() PLT */
 	__error();
 
+	/* force to resolve memcpy PLT */
+	memcpy(&dummy, &dummy, sizeof(dummy));
+
 	li.lock_create  = _thr_rtld_lock_create;
 	li.lock_destroy = _thr_rtld_lock_destroy;
 	li.rlock_acquire = _thr_rtld_rlock_acquire;
diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index 312c15f4a3b..382ff4fbbab 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -32,11 +32,10 @@
 #include 
 #include 
 #include 
-#include 
-#include 
 #include 
 #include 
 #include "un-namespace.h"
+#include "libc_private.h"
 
 #include "thr_private.h"
 
@@ -47,7 +46,19 @@
 #define DBG_MSG(x...)
 #endif
 
-extern int	__pause(void);
+struct usigaction {
+	struct sigaction sigact;
+	struct urwlock   lock;
+};
+
+static struct usigaction _thr_sigact[_SIG_MAXSIG];
+
+static void thr_sighandler(int, siginfo_t *, void *);
+static void handle_signal(struct sigaction *, int, siginfo_t *, ucontext_t *);
+static void check_deferred_signal(struct pthread *);
+static void check_suspend(struct pthread *);
+static void check_cancel(struct pthread *curthread, ucontext_t *ucp);
+
 int	___pause(void);
 int	_raise(int);
 int	__sigtimedwait(const sigset_t *set, siginfo_t *info,
@@ -59,10 +70,49 @@ int	_sigwaitinfo(const sigset_t *set, siginfo_t *info);
 int	__sigwait(const sigset_t *set, int *sig);
 int	_sigwait(const sigset_t *set, int *sig);
 int	__sigsuspend(const sigset_t *sigmask);
+int	_sigaction(int, const struct sigaction *, struct sigaction *);
 int	_setcontext(const ucontext_t *);
 int	_swapcontext(ucontext_t *, const ucontext_t *);
 
-static void
+static const sigset_t _thr_deferset={{
+	0xffffffff & ~(_SIG_BIT(SIGBUS)|_SIG_BIT(SIGILL)|_SIG_BIT(SIGFPE)|
+	_SIG_BIT(SIGSEGV)|_SIG_BIT(SIGTRAP)|_SIG_BIT(SIGSYS)),
+	0xffffffff,
+	0xffffffff,
+	0xffffffff}};
+
+static const sigset_t _thr_maskset={{
+	0xffffffff,
+	0xffffffff,
+	0xffffffff,
+	0xffffffff}};
+
+void
+_thr_signal_block(struct pthread *curthread)
+{
+	
+	if (curthread->sigblock > 0) {
+		curthread->sigblock++;
+		return;
+	}
+	__sys_sigprocmask(SIG_BLOCK, &_thr_maskset, &curthread->sigmask);
+	curthread->sigblock++;
+}
+
+void
+_thr_signal_unblock(struct pthread *curthread)
+{
+	if (--curthread->sigblock == 0)
+		__sys_sigprocmask(SIG_SETMASK, &curthread->sigmask, NULL);
+}
+
+int
+_thr_send_sig(struct pthread *thread, int sig)
+{
+	return thr_kill(thread->tid, sig);
+}
+
+static inline void
 remove_thr_signals(sigset_t *set)
 {
 	if (SIGISMEMBER(*set, SIGCANCEL))
@@ -72,87 +122,244 @@ remove_thr_signals(sigset_t *set)
 static const sigset_t *
 thr_remove_thr_signals(const sigset_t *set, sigset_t *newset)
 {
-	const sigset_t *pset;
-
-	if (SIGISMEMBER(*set, SIGCANCEL)) {
-		*newset = *set;
-		SIGDELSET(*newset, SIGCANCEL);
-		pset = newset;
-	} else
-		pset = set;
-	return (pset);
+	*newset = *set;
+	remove_thr_signals(newset);
+	return (newset);
 }
 
 static void
 sigcancel_handler(int sig __unused,
-	siginfo_t *info __unused, ucontext_t *ucp __unused)
+	siginfo_t *info __unused, ucontext_t *ucp)
 {
 	struct pthread *curthread = _get_curthread();
+	int err;
 
-	curthread->in_sigcancel_handler++;
-	_thr_ast(curthread);
-	curthread->in_sigcancel_handler--;
+	if (THR_IN_CRITICAL(curthread))
+		return;
+	err = errno;
+	check_suspend(curthread);
+	check_cancel(curthread, ucp);
+	errno = err;
+}
+
+typedef void (*ohandler)(int sig, int code,
+	struct sigcontext *scp, char *addr, __sighandler_t *catcher);
+
+/*
+ * The signal handler wrapper is entered with all signal masked.
+ */
+static void
+thr_sighandler(int sig, siginfo_t *info, void *_ucp)
+{
+	struct pthread *curthread = _get_curthread();
+	ucontext_t *ucp = _ucp;
+	struct sigaction act;
+	int err;
+
+	err = errno;
+	_thr_rwl_rdlock(&_thr_sigact[sig-1].lock);
+	act = _thr_sigact[sig-1].sigact;
+	_thr_rwl_unlock(&_thr_sigact[sig-1].lock);
+	errno = err;
+
+	/*
+	 * if a thread is in critical region, for example it holds low level locks,
+	 * try to defer the signal processing, however if the signal is synchronous
+	 * signal, it means a bad thing has happened, this is a programming error,
+	 * resuming fault point can not help anything (normally causes deadloop),
+	 * so here we let user code handle it immediately.
+	 */
+	if (THR_IN_CRITICAL(curthread) && SIGISMEMBER(_thr_deferset, sig)) {
+		memcpy(&curthread->deferred_sigact, &act, sizeof(struct sigaction));
+		memcpy(&curthread->deferred_siginfo, info, sizeof(siginfo_t));
+		curthread->deferred_sigmask = ucp->uc_sigmask;
+		/* mask all signals, we will restore it later. */
+		ucp->uc_sigmask = _thr_deferset;
+		return;
+	}
+
+	handle_signal(&act, sig, info, ucp);
+}
+
+static void
+handle_signal(struct sigaction *actp, int sig, siginfo_t *info, ucontext_t *ucp)
+{
+	struct pthread *curthread = _get_curthread();
+	ucontext_t uc2;
+	__siginfohandler_t *sigfunc;
+	int cancel_defer;
+	int cancel_point;
+	int cancel_async;
+	int cancel_enable;
+	int in_sigsuspend;
+	int err;
+
+	/* add previous level mask */
+	SIGSETOR(actp->sa_mask, ucp->uc_sigmask);
+
+	/* add this signal's mask */
+	if (!(actp->sa_flags & SA_NODEFER))
+		SIGADDSET(actp->sa_mask, sig);
+
+	in_sigsuspend = curthread->in_sigsuspend;
+	curthread->in_sigsuspend = 0;
+
+	/*
+	 * if thread is in deferred cancellation mode, disable cancellation
+	 * in signal handler.
+	 * if user signal handler calls a cancellation point function, e.g,
+	 * it calls write() to write data to file, because write() is a
+	 * cancellation point, the thread is immediately cancelled if 
+	 * cancellation is pending, to avoid this problem while thread is in
+	 * deferring mode, cancellation is temporarily disabled.
+	 */
+	cancel_defer = curthread->cancel_defer;
+	cancel_point = curthread->cancel_point;
+	cancel_async = curthread->cancel_async;
+	cancel_enable = curthread->cancel_enable;
+	curthread->cancel_point = 0;
+	curthread->cancel_defer = 0;
+	if (!cancel_async)
+		curthread->cancel_enable = 0;
+
+	/* restore correct mask before calling user handler */
+	__sys_sigprocmask(SIG_SETMASK, &actp->sa_mask, NULL);
+
+	sigfunc = actp->sa_sigaction;
+
+	/*
+	 * We have already reset cancellation point flags, so if user's code
+	 * longjmp()s out of its signal handler, wish its jmpbuf was set
+	 * outside of a cancellation point, in most cases, this would be
+	 * true. however, ther is no way to save cancel_enable in jmpbuf,
+	 * so after setjmps() returns once more, the user code may need to
+	 * re-set cancel_enable flag by calling pthread_setcancelstate().
+	 */
+	if ((actp->sa_flags & SA_SIGINFO) != 0)
+		(*(sigfunc))(sig, info, ucp);
+	else {
+		((ohandler)(*sigfunc))(
+			sig, info->si_code, (struct sigcontext *)ucp,
+			info->si_addr, (__sighandler_t *)sigfunc);
+	}
+	err = errno;
+
+	curthread->in_sigsuspend = in_sigsuspend;
+	curthread->cancel_defer = cancel_defer;
+	curthread->cancel_point = cancel_point;
+	curthread->cancel_enable = cancel_enable;
+
+	memcpy(&uc2, ucp, sizeof(uc2));
+	SIGDELSET(uc2.uc_sigmask, SIGCANCEL);
+
+	/* reschedule cancellation */
+	check_cancel(curthread, &uc2);
+	errno = err;
+	__sys_sigreturn(&uc2);
 }
 
 void
 _thr_ast(struct pthread *curthread)
 {
 
-	if (THR_IN_CRITICAL(curthread))
-		return;
-
-	if (curthread->cancel_pending && curthread->cancel_enable
-		&& !curthread->cancelling) {
-		if (curthread->cancel_async) {
-			/*
-		 	 * asynchronous cancellation mode, act upon
-			 * immediately.
-		 	 */
-			_pthread_exit(PTHREAD_CANCELED);
-		} else {
-			/*
-		 	 * Otherwise, we are in defer mode, and we are at
-			 * cancel point, tell kernel to not block the current
-			 * thread on next cancelable system call.
-			 * 
-			 * There are two cases we should call thr_wake() to 
-			 * turn on TDP_WAKEUP in kernel:
-			 * 1) we are going to call a cancelable system call,
-			 *    non-zero cancel_point means we are already in
-			 *    cancelable state, next system call is cancelable.
-			 * 2) because _thr_ast() may be called by
-			 *    THR_CRITICAL_LEAVE() which is used by rtld rwlock
-			 *    and any libthr internal locks, when rtld rwlock
-			 *    is used, it is mostly caused my an unresolved PLT.
-			 *    those routines may clear the TDP_WAKEUP flag by
-			 *    invoking some system calls, in those cases, we
-			 *    also should reenable the flag.
-		 	 */
-			if (curthread->cancel_point) {
-				if (curthread->cancel_defer)
-					thr_wake(curthread->tid);
-				else
-					_pthread_exit(PTHREAD_CANCELED);
-			}
-		}
+	if (!THR_IN_CRITICAL(curthread)) {
+		check_deferred_signal(curthread);
+		check_suspend(curthread);
+		check_cancel(curthread, NULL);
 	}
-
-	if (__predict_false((curthread->flags &
-	    (THR_FLAGS_NEED_SUSPEND | THR_FLAGS_SUSPENDED))
-		== THR_FLAGS_NEED_SUSPEND))
-		_thr_suspend_check(curthread);
 }
 
-void
-_thr_suspend_check(struct pthread *curthread)
+/* reschedule cancellation */
+static void
+check_cancel(struct pthread *curthread, ucontext_t *ucp)
+{
+
+	if (__predict_true(!curthread->cancel_pending || !curthread->cancel_enable ||
+	    curthread->cancelling))
+		return;
+
+	if (curthread->cancel_async) {
+		/*
+	 	 * asynchronous cancellation mode, act upon
+		 * immediately.
+	 	 */
+		_pthread_exit_mask(PTHREAD_CANCELED,
+		    ucp? &ucp->uc_sigmask : NULL);
+	} else {
+		/*
+	 	 * Otherwise, we are in defer mode, and we are at
+		 * cancel point, tell kernel to not block the current
+		 * thread on next cancelable system call.
+		 * 
+		 * There are three cases we should call thr_wake() to
+		 * turn on TDP_WAKEUP or send SIGCANCEL in kernel:
+		 * 1) we are going to call a cancelable system call,
+		 *    non-zero cancel_point means we are already in
+		 *    cancelable state, next system call is cancelable.
+		 * 2) because _thr_ast() may be called by
+		 *    THR_CRITICAL_LEAVE() which is used by rtld rwlock
+		 *    and any libthr internal locks, when rtld rwlock
+		 *    is used, it is mostly caused my an unresolved PLT.
+		 *    those routines may clear the TDP_WAKEUP flag by
+		 *    invoking some system calls, in those cases, we
+		 *    also should reenable the flag.
+		 * 3) thread is in sigsuspend(), and the syscall insists
+		 *    on getting a signal before it agrees to return.
+	 	 */
+		if (curthread->cancel_point) {
+			if (curthread->in_sigsuspend && ucp) {
+				SIGADDSET(ucp->uc_sigmask, SIGCANCEL);
+				curthread->unblock_sigcancel = 1;
+				_thr_send_sig(curthread, SIGCANCEL);
+			} else
+				thr_wake(curthread->tid);
+		}
+	}
+}
+
+static void
+check_deferred_signal(struct pthread *curthread)
+{
+	ucontext_t uc;
+	struct sigaction act;
+	siginfo_t info;
+	volatile int first;
+
+	if (__predict_true(curthread->deferred_siginfo.si_signo == 0))
+		return;
+	first = 1;
+	getcontext(&uc);
+	if (first) {
+		first = 0;
+		act = curthread->deferred_sigact;
+		uc.uc_sigmask = curthread->deferred_sigmask;
+		memcpy(&info, &curthread->deferred_siginfo, sizeof(siginfo_t));
+		/* remove signal */
+		curthread->deferred_siginfo.si_signo = 0;
+		if (act.sa_flags & SA_RESETHAND) {
+			struct sigaction tact;
+
+			tact = act;
+			tact.sa_handler = SIG_DFL;
+			_sigaction(info.si_signo, &tact, NULL);
+		}
+		handle_signal(&act, info.si_signo, &info, &uc);
+	}
+}
+
+static void
+check_suspend(struct pthread *curthread)
 {
 	uint32_t cycle;
-	int err;
+
+	if (__predict_true((curthread->flags &
+		(THR_FLAGS_NEED_SUSPEND | THR_FLAGS_SUSPENDED))
+		!= THR_FLAGS_NEED_SUSPEND))
+		return;
 
 	if (curthread->force_exit)
 		return;
 
-	err = errno;
 	/* 
 	 * Blocks SIGCANCEL which other threads must send.
 	 */
@@ -188,15 +395,7 @@ _thr_suspend_check(struct pthread *curthread)
 	THR_UMUTEX_UNLOCK(curthread, &(curthread)->lock);
 	curthread->critical_count--;
 
-	/* 
-	 * Unblocks SIGCANCEL, it is possible a new SIGCANCEL is ready and
-	 * a new signal frame will nest us, this seems a problem because 
-	 * stack will grow and overflow, but because kernel will automatically
-	 * mask the SIGCANCEL when delivering the signal, so we at most only
-	 * have one nesting signal frame, this should be fine.
-	 */
 	_thr_signal_unblock(curthread);
-	errno = err;
 }
 
 void
@@ -204,11 +403,80 @@ _thr_signal_init(void)
 {
 	struct sigaction act;
 
-	/* Install cancel handler. */
-	SIGEMPTYSET(act.sa_mask);
-	act.sa_flags = SA_SIGINFO | SA_RESTART;
+	/* Install SIGCANCEL handler. */
+	SIGFILLSET(act.sa_mask);
+	act.sa_flags = SA_SIGINFO;
 	act.sa_sigaction = (__siginfohandler_t *)&sigcancel_handler;
 	__sys_sigaction(SIGCANCEL, &act, NULL);
+
+	/* Unblock SIGCANCEL */
+	SIGEMPTYSET(act.sa_mask);
+	SIGADDSET(act.sa_mask, SIGCANCEL);
+	__sys_sigprocmask(SIG_UNBLOCK, &act.sa_mask, NULL);
+}
+
+/*
+ * called from rtld with rtld_lock locked, because rtld_lock is
+ * a critical region, so all signals have already beeen masked.
+ */
+void
+_thr_sigact_unload(struct dl_phdr_info *phdr_info)
+{
+	struct urwlock *rwlp;
+	struct sigaction *actp;
+	struct sigaction kact;
+	void (*handler)(int);
+	int sig;
+ 
+	for (sig = 1; sig < _SIG_MAXSIG; sig++) {
+		actp = &_thr_sigact[sig].sigact;
+retry:
+		handler = actp->sa_handler;
+		if (handler != SIG_DFL && handler != SIG_IGN &&
+		    __elf_phdr_match_addr(phdr_info, handler)) {
+			rwlp = &_thr_sigact[sig].lock;
+			_thr_rwl_wrlock(rwlp);
+			if (handler != actp->sa_handler) {
+				_thr_rwl_unlock(rwlp);
+				goto retry;
+			}
+			actp->sa_handler = SIG_DFL;
+			actp->sa_flags = SA_SIGINFO;
+			SIGEMPTYSET(actp->sa_mask);
+			if (__sys_sigaction(sig, NULL, &kact) == 0 &&
+				kact.sa_handler != SIG_DFL &&
+				kact.sa_handler != SIG_IGN)
+				__sys_sigaction(sig, actp, NULL);
+				_thr_rwl_unlock(rwlp);
+		}
+	}
+}
+
+void
+_thr_signal_prefork(void)
+{
+	int i;
+
+	for (i = 1; i < _SIG_MAXSIG; ++i)
+		_thr_rwl_rdlock(&_thr_sigact[i-1].lock);
+}
+
+void
+_thr_signal_postfork(void)
+{
+	int i;
+
+	for (i = 1; i < _SIG_MAXSIG; ++i)
+		_thr_rwl_unlock(&_thr_sigact[i-1].lock);
+}
+
+void
+_thr_signal_postfork_child(void)
+{
+	int i;
+
+	for (i = 1; i < _SIG_MAXSIG; ++i)
+		bzero(&_thr_sigact[i-1].lock, sizeof(struct urwlock));
 }
 
 void
@@ -221,14 +489,11 @@ __weak_reference(___pause, pause);
 int
 ___pause(void)
 {
-	struct pthread *curthread = _get_curthread();
-	int	ret;
+	sigset_t oset;
 
-	_thr_cancel_enter(curthread);
-	ret = __pause();
-	_thr_cancel_leave(curthread);
-	
-	return ret;
+	if (_sigprocmask(SIG_BLOCK, NULL, &oset) == -1)
+		return (-1);
+	return (__sigsuspend(&oset));
 }
 
 __weak_reference(_raise, raise);
@@ -236,13 +501,7 @@ __weak_reference(_raise, raise);
 int
 _raise(int sig)
 {
-	int ret;
-
-	if (!_thr_isthreaded())
-		ret = kill(getpid(), sig);
-	else
-		ret = _thr_send_sig(_get_curthread(), sig);
-	return (ret);
+	return _thr_send_sig(_get_curthread(), sig);
 }
 
 __weak_reference(_sigaction, sigaction);
@@ -250,14 +509,65 @@ __weak_reference(_sigaction, sigaction);
 int
 _sigaction(int sig, const struct sigaction * act, struct sigaction * oact)
 {
-	/* Check if the signal number is out of range: */
+	struct sigaction newact, oldact, oldact2;
+	sigset_t oldset;
+	int ret = 0, err = 0;
+
 	if (!_SIG_VALID(sig) || sig == SIGCANCEL) {
-		/* Return an invalid argument: */
 		errno = EINVAL;
 		return (-1);
 	}
 
-	return __sys_sigaction(sig, act, oact);
+	if (act)
+		newact = *act;
+
+	__sys_sigprocmask(SIG_SETMASK, &_thr_maskset, &oldset);
+	_thr_rwl_wrlock(&_thr_sigact[sig-1].lock);
+ 
+	if (act != NULL) {
+		oldact2 = _thr_sigact[sig-1].sigact;
+
+ 		/*
+		 * if a new sig handler is SIG_DFL or SIG_IGN,
+		 * don't remove old handler from _thr_sigact[],
+		 * so deferred signals still can use the handlers,
+		 * multiple threads invoking sigaction itself is
+		 * a race condition, so it is not a problem.
+		 */
+		if (newact.sa_handler != SIG_DFL &&
+		    newact.sa_handler != SIG_IGN) {
+			_thr_sigact[sig-1].sigact = newact;
+			remove_thr_signals(
+				&_thr_sigact[sig-1].sigact.sa_mask);
+			newact.sa_flags &= ~SA_NODEFER;
+			newact.sa_flags |= SA_SIGINFO;
+			newact.sa_sigaction = thr_sighandler;
+			newact.sa_mask = _thr_maskset; /* mask all signals */
+		}
+		if ((ret = __sys_sigaction(sig, &newact, &oldact))) {
+			err = errno;
+			_thr_sigact[sig-1].sigact = oldact2;
+		}
+	} else if (oact != NULL) {
+		ret = __sys_sigaction(sig, NULL, &oldact);
+		err = errno;
+	}
+
+	if (oldact.sa_handler != SIG_DFL &&
+	    oldact.sa_handler != SIG_IGN) {
+		oldact = _thr_sigact[sig-1].sigact;
+	}
+
+	_thr_rwl_unlock(&_thr_sigact[sig-1].lock);
+	__sys_sigprocmask(SIG_SETMASK, &oldset, NULL);
+
+	if (ret == 0) {
+		if (oact != NULL)
+			*oact = oldact;
+	} else {
+		errno = err;
+	}
+	return (ret);
 }
 
 __weak_reference(_sigprocmask, sigprocmask);
@@ -301,13 +611,24 @@ _sigsuspend(const sigset_t * set)
 int
 __sigsuspend(const sigset_t * set)
 {
-	struct pthread *curthread = _get_curthread();
+	struct pthread *curthread;
 	sigset_t newset;
-	int ret;
+	int ret, old;
 
+	curthread = _get_curthread();
+
+	old = curthread->in_sigsuspend;
+	curthread->in_sigsuspend = 1;
 	_thr_cancel_enter(curthread);
 	ret = __sys_sigsuspend(thr_remove_thr_signals(set, &newset));
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave(curthread, 1);
+	curthread->in_sigsuspend = old;
+	if (curthread->unblock_sigcancel) {
+		curthread->unblock_sigcancel = 0;
+		SIGEMPTYSET(newset);
+		SIGADDSET(newset, SIGCANCEL);
+		__sys_sigprocmask(SIG_UNBLOCK, &newset, NULL);
+	}
 
 	return (ret);
 }
@@ -339,10 +660,10 @@ __sigtimedwait(const sigset_t *set, siginfo_t *info,
 	sigset_t newset;
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_sigtimedwait(thr_remove_thr_signals(set, &newset), info,
 	    timeout);
-	_thr_cancel_leave_defer(curthread, (ret == -1));
+	_thr_cancel_leave(curthread, (ret == -1));
 	return (ret);
 }
 
@@ -366,9 +687,9 @@ __sigwaitinfo(const sigset_t *set, siginfo_t *info)
 	sigset_t newset;
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_sigwaitinfo(thr_remove_thr_signals(set, &newset), info);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	return (ret);
 }
 
@@ -392,9 +713,9 @@ __sigwait(const sigset_t *set, int *sig)
 	sigset_t newset;
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_sigwait(thr_remove_thr_signals(set, &newset), sig);
-	_thr_cancel_leave_defer(curthread, (ret != 0));
+	_thr_cancel_leave(curthread, (ret != 0));
 	return (ret);
 }
 
@@ -404,9 +725,8 @@ _setcontext(const ucontext_t *ucp)
 {
 	ucontext_t uc;
 
-	(void) memcpy(&uc, ucp, sizeof (uc));
+	(void) memcpy(&uc, ucp, sizeof(uc));
 	remove_thr_signals(&uc.uc_sigmask);
-
 	return __sys_setcontext(&uc);
 }
 
@@ -416,7 +736,7 @@ _swapcontext(ucontext_t *oucp, const ucontext_t *ucp)
 {
 	ucontext_t uc;
 
-	(void) memcpy(&uc, ucp, sizeof (uc));
+	(void) memcpy(&uc, ucp, sizeof(uc));
 	remove_thr_signals(&uc.uc_sigmask);
 	return __sys_swapcontext(oucp, &uc);
 }
diff --git a/lib/libthr/thread/thr_syscalls.c b/lib/libthr/thread/thr_syscalls.c
index 73fa56fcc8f..2327d7484e6 100644
--- a/lib/libthr/thread/thr_syscalls.c
+++ b/lib/libthr/thread/thr_syscalls.c
@@ -169,9 +169,9 @@ __accept(int s, struct sockaddr *addr, socklen_t *addrlen)
 	int ret;
 
 	curthread = _get_curthread();
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_accept(s, addr, addrlen);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
  	return (ret);
 }
@@ -187,7 +187,7 @@ __aio_suspend(const struct aiocb * const iocbs[], int niocb, const struct
 
 	_thr_cancel_enter(curthread);
 	ret = __sys_aio_suspend(iocbs, niocb, timeout);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave(curthread, 1);
 
 	return (ret);
 }
@@ -207,9 +207,9 @@ __close(int fd)
 	struct pthread	*curthread = _get_curthread();
 	int	ret;
 
-	_thr_cancel_enter_defer(curthread, 0);
+	_thr_cancel_enter2(curthread, 0);
 	ret = __sys_close(fd);
-	_thr_cancel_leave_defer(curthread, 1);
+	_thr_cancel_leave(curthread, 1);
 	
 	return (ret);
 }
@@ -226,9 +226,9 @@ __connect(int fd, const struct sockaddr *name, socklen_t namelen)
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 0);
+	_thr_cancel_enter(curthread);
 	ret = __sys_connect(fd, name, namelen);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
  	return (ret);
 }
@@ -245,9 +245,9 @@ ___creat(const char *path, mode_t mode)
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __creat(path, mode);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	
 	return ret;
 }
@@ -269,30 +269,15 @@ __fcntl(int fd, int cmd,...)
 	va_list	ap;
 
 	va_start(ap, cmd);
-	switch (cmd) {
-	case F_DUPFD:
-	case F_DUP2FD:
-		ret = __sys_fcntl(fd, cmd, va_arg(ap, int));
-		break;
-	case F_SETFD:
-	case F_SETFL:
-		ret = __sys_fcntl(fd, cmd, va_arg(ap, int));
-		break;
-	case F_GETFD:
-	case F_GETFL:
-		ret = __sys_fcntl(fd, cmd);
-		break;
-	case F_OSETLKW:
-	case F_SETLKW:
-		_thr_cancel_enter_defer(curthread, 1);
+	if (cmd == F_OSETLKW || cmd == F_SETLKW) {
+		_thr_cancel_enter(curthread);
 #ifdef SYSCALL_COMPAT
 		ret = __fcntl_compat(fd, cmd, va_arg(ap, void *));
 #else
 		ret = __sys_fcntl(fd, cmd, va_arg(ap, void *));
 #endif
-		_thr_cancel_leave_defer(curthread, ret == -1);
-		break;
-	default:
+		_thr_cancel_leave(curthread, ret == -1);
+	} else {
 #ifdef SYSCALL_COMPAT
 		ret = __fcntl_compat(fd, cmd, va_arg(ap, void *));
 #else
@@ -316,9 +301,9 @@ __fsync(int fd)
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 
-	_thr_cancel_enter_defer(curthread, 0);
+	_thr_cancel_enter2(curthread, 0);
 	ret = __sys_fsync(fd);
-	_thr_cancel_leave_defer(curthread, 1);
+	_thr_cancel_leave(curthread, 1);
 
 	return (ret);
 }
@@ -335,9 +320,9 @@ __msync(void *addr, size_t len, int flags)
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 
-	_thr_cancel_enter_defer(curthread, 0);
+	_thr_cancel_enter2(curthread, 0);
 	ret = __sys_msync(addr, len, flags);
-	_thr_cancel_leave_defer(curthread, 1);
+	_thr_cancel_leave(curthread, 1);
 
 	return ret;
 }
@@ -353,7 +338,7 @@ __nanosleep(const struct timespec *time_to_sleep,
 
 	_thr_cancel_enter(curthread);
 	ret = __sys_nanosleep(time_to_sleep, time_remaining);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave(curthread, 1);
 
 	return (ret);
 }
@@ -380,9 +365,9 @@ __open(const char *path, int flags,...)
 		va_end(ap);
 	}
 	
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_open(path, flags, mode);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
 	return ret;
 }
@@ -410,9 +395,9 @@ __openat(int fd, const char *path, int flags, ...)
 		va_end(ap);
 	}
 	
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_openat(fd, path, flags, mode);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
 	return ret;
 }
@@ -430,9 +415,9 @@ __poll(struct pollfd *fds, unsigned int nfds, int timeout)
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_poll(fds, nfds, timeout);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
 	return ret;
 }
@@ -451,9 +436,9 @@ ___pselect(int count, fd_set *rfds, fd_set *wfds, fd_set *efds,
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_pselect(count, rfds, wfds, efds, timo, mask);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
 	return (ret);
 }
@@ -471,9 +456,9 @@ __read(int fd, void *buf, size_t nbytes)
 	struct pthread *curthread = _get_curthread();
 	ssize_t	ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_read(fd, buf, nbytes);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 
 	return ret;
 }
@@ -491,9 +476,9 @@ __readv(int fd, const struct iovec *iov, int iovcnt)
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_readv(fd, iov, iovcnt);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	return ret;
 }
 
@@ -511,9 +496,9 @@ __recvfrom(int s, void *b, size_t l, int f, struct sockaddr *from,
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_recvfrom(s, b, l, f, from, fl);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	return (ret);
 }
 
@@ -530,9 +515,9 @@ __recvmsg(int s, struct msghdr *m, int f)
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_recvmsg(s, m, f);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	return (ret);
 }
 
@@ -550,9 +535,9 @@ __select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
 	struct pthread *curthread = _get_curthread();
 	int ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_select(numfds, readfds, writefds, exceptfds, timeout);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	return ret;
 }
 
@@ -569,9 +554,9 @@ __sendmsg(int s, const struct msghdr *m, int f)
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_sendmsg(s, m, f);
-	_thr_cancel_leave_defer(curthread, ret <= 0);
+	_thr_cancel_leave(curthread, ret <= 0);
 	return (ret);
 }
 
@@ -589,9 +574,9 @@ __sendto(int s, const void *m, size_t l, int f, const struct sockaddr *t,
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_sendto(s, m, l, f, t, tl);
-	_thr_cancel_leave_defer(curthread, ret <= 0);
+	_thr_cancel_leave(curthread, ret <= 0);
 	return (ret);
 }
 
@@ -605,7 +590,7 @@ ___sleep(unsigned int seconds)
 
 	_thr_cancel_enter(curthread);
 	ret = __sleep(seconds);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave(curthread, 1);
 	
 	return (ret);
 }
@@ -620,7 +605,7 @@ ___system(const char *string)
 
 	_thr_cancel_enter(curthread);
 	ret = __system(string);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave(curthread, 1);
 	
 	return ret;
 }
@@ -638,9 +623,9 @@ ___tcdrain(int fd)
 	struct pthread *curthread = _get_curthread();
 	int	ret;
 	
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __tcdrain(fd);
-	_thr_cancel_leave_defer(curthread, ret == -1);
+	_thr_cancel_leave(curthread, ret == -1);
 	return (ret);
 }
 
@@ -654,7 +639,7 @@ ___usleep(useconds_t useconds)
 
 	_thr_cancel_enter(curthread);
 	ret = __usleep(useconds);
-	_thr_cancel_leave(curthread);
+	_thr_cancel_leave(curthread, 1);
 	
 	return (ret);
 }
@@ -672,9 +657,9 @@ ___wait(int *istat)
 	struct pthread *curthread = _get_curthread();
 	pid_t	ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __wait(istat);
-	_thr_cancel_leave_defer(curthread, ret <= 0);
+	_thr_cancel_leave(curthread, ret <= 0);
 
 	return ret;
 }
@@ -692,9 +677,9 @@ __wait3(int *status, int options, struct rusage *rusage)
 	struct pthread *curthread = _get_curthread();
 	pid_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = _wait4(WAIT_ANY, status, options, rusage);
-	_thr_cancel_leave_defer(curthread, ret <= 0);
+	_thr_cancel_leave(curthread, ret <= 0);
 
 	return (ret);
 }
@@ -712,9 +697,9 @@ __wait4(pid_t pid, int *status, int options, struct rusage *rusage)
 	struct pthread *curthread = _get_curthread();
 	pid_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_wait4(pid, status, options, rusage);
-	_thr_cancel_leave_defer(curthread, ret <= 0);
+	_thr_cancel_leave(curthread, ret <= 0);
 
 	return ret;
 }
@@ -732,9 +717,9 @@ ___waitpid(pid_t wpid, int *status, int options)
 	struct pthread *curthread = _get_curthread();
 	pid_t	ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __waitpid(wpid, status, options);
-	_thr_cancel_leave_defer(curthread, ret <= 0);
+	_thr_cancel_leave(curthread, ret <= 0);
 	
 	return ret;
 }
@@ -752,9 +737,9 @@ __write(int fd, const void *buf, size_t nbytes)
 	struct pthread *curthread = _get_curthread();
 	ssize_t	ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_write(fd, buf, nbytes);
-	_thr_cancel_leave_defer(curthread, (ret <= 0));
+	_thr_cancel_leave(curthread, (ret <= 0));
 	return ret;
 }
 
@@ -771,8 +756,8 @@ __writev(int fd, const struct iovec *iov, int iovcnt)
 	struct pthread *curthread = _get_curthread();
 	ssize_t ret;
 
-	_thr_cancel_enter_defer(curthread, 1);
+	_thr_cancel_enter(curthread);
 	ret = __sys_writev(fd, iov, iovcnt);
-	_thr_cancel_leave_defer(curthread, (ret <= 0));
+	_thr_cancel_leave(curthread, (ret <= 0));
 	return ret;
 }
diff --git a/lib/libthr/thread/thr_umtx.c b/lib/libthr/thread/thr_umtx.c
index 5af923dce4f..b712b7af880 100644
--- a/lib/libthr/thread/thr_umtx.c
+++ b/lib/libthr/thread/thr_umtx.c
@@ -217,3 +217,42 @@ __thr_rwlock_unlock(struct urwlock *rwlock)
 {
 	return _umtx_op_err(rwlock, UMTX_OP_RW_UNLOCK, 0, NULL, NULL);
 }
+
+void
+_thr_rwl_rdlock(struct urwlock *rwlock)
+{
+	int ret;
+
+	for (;;) {
+		if (_thr_rwlock_tryrdlock(rwlock, URWLOCK_PREFER_READER) == 0)
+			return;
+		ret = __thr_rwlock_rdlock(rwlock, URWLOCK_PREFER_READER, NULL);
+		if (ret == 0)
+			return;
+		if (ret != EINTR)
+			PANIC("rdlock error");
+	}
+}
+
+void
+_thr_rwl_wrlock(struct urwlock *rwlock)
+{
+	int ret;
+
+	for (;;) {
+		if (_thr_rwlock_trywrlock(rwlock) == 0)
+			return;
+		ret = __thr_rwlock_wrlock(rwlock, NULL);
+		if (ret == 0)
+			return;
+		if (ret != EINTR)
+			PANIC("wrlock error");
+	}
+}
+
+void
+_thr_rwl_unlock(struct urwlock *rwlock)
+{
+	if (_thr_rwlock_unlock(rwlock))
+		PANIC("unlock error");
+}
diff --git a/lib/libthr/thread/thr_umtx.h b/lib/libthr/thread/thr_umtx.h
index a6e462e29ca..20489849f53 100644
--- a/lib/libthr/thread/thr_umtx.h
+++ b/lib/libthr/thread/thr_umtx.h
@@ -58,6 +58,11 @@ int __thr_rwlock_rdlock(struct urwlock *rwlock, int flags, struct timespec *tsp)
 int __thr_rwlock_wrlock(struct urwlock *rwlock, struct timespec *tsp) __hidden;
 int __thr_rwlock_unlock(struct urwlock *rwlock) __hidden;
 
+/* Internal used only */
+void _thr_rwl_rdlock(struct urwlock *rwlock) __hidden;
+void _thr_rwl_wrlock(struct urwlock *rwlock) __hidden;
+void _thr_rwl_unlock(struct urwlock *rwlock) __hidden;
+
 static inline int
 _thr_umutex_trylock(struct umutex *mtx, uint32_t id)
 {

From ada33a6e3629051aabc54ba3d1fa13d0ae82262b Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 1 Sep 2010 03:11:21 +0000
Subject: [PATCH 0407/1624] Change atfork lock from mutex to rwlock, also make
 mutexes used by malloc() module private type, when private type mutex is
 locked/unlocked, thread critical region is entered or leaved. These changes
 makes fork() async-signal safe which required by POSIX. Note that user's
 atfork handler still needs to be async-signal safe, but it is not problem of
 libthr, it is user's responsiblity.

---
 lib/libthr/thread/thr_fork.c    | 41 ++++++++++++++++++---------------
 lib/libthr/thread/thr_init.c    |  4 ++--
 lib/libthr/thread/thr_mutex.c   | 28 ++++++++++++++++++----
 lib/libthr/thread/thr_private.h |  3 ++-
 lib/libthr/thread/thr_umtx.c    |  7 ++++++
 lib/libthr/thread/thr_umtx.h    |  5 +++-
 6 files changed, 60 insertions(+), 28 deletions(-)

diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index 8e1ea6a5e72..1ce7c6eb4ae 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -89,9 +89,9 @@ _pthread_atfork(void (*prepare)(void), void (*parent)(void),
 	af->prepare = prepare;
 	af->parent = parent;
 	af->child = child;
-	THR_UMUTEX_LOCK(curthread, &_thr_atfork_lock);
+	_thr_rwl_rdlock(&_thr_atfork_lock);
 	TAILQ_INSERT_TAIL(&_thr_atfork_list, af, qe);
-	THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
+	_thr_rwl_unlock(&_thr_atfork_lock);
 	return (0);
 }
 
@@ -104,7 +104,7 @@ __pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
 	_thr_check_init();
 
 	curthread = _get_curthread();
-	THR_UMUTEX_LOCK(curthread, &_thr_atfork_lock);
+	_thr_rwl_wrlock(&_thr_atfork_lock);
 	TAILQ_FOREACH_SAFE(af, &_thr_atfork_list, qe, af1) {
 		if (__elf_phdr_match_addr(phdr_info, af->prepare) ||
 		    __elf_phdr_match_addr(phdr_info, af->parent) ||
@@ -113,7 +113,7 @@ __pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
 			free(af);
 		}
 	}
-	THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
+	_thr_rwl_unlock(&_thr_atfork_lock);
 	_thr_tsd_unload(phdr_info);
 	_thr_sigact_unload(phdr_info);
 }
@@ -137,7 +137,7 @@ _fork(void)
 
 	curthread = _get_curthread();
 
-	THR_UMUTEX_LOCK(curthread, &_thr_atfork_lock);
+	_thr_rwl_rdlock(&_thr_atfork_lock);
 
 	/* Run down atfork prepare handlers. */
 	TAILQ_FOREACH_REVERSE(af, &_thr_atfork_list, atfork_head, qe) {
@@ -145,6 +145,12 @@ _fork(void)
 			af->prepare();
 	}
 
+	/*
+	 * Block all signals until we reach a safe point.
+	 */
+	_thr_signal_block(curthread);
+	_thr_signal_prefork();
+
 	/*
 	 * All bets are off as to what should happen soon if the parent
 	 * process was not so kindly as to set up pthread fork hooks to
@@ -158,12 +164,6 @@ _fork(void)
 		was_threaded = 0;
 	}
 
-	/*
-	 * Block all signals until we reach a safe point.
-	 */
-	_thr_signal_block(curthread);
-	_thr_signal_prefork();
-
 	/* Fork a new process: */
 	if ((ret = __sys_fork()) == 0) {
 		/* Child process */
@@ -182,7 +182,7 @@ _fork(void)
 
 		/* clear other threads locked us. */
 		_thr_umutex_init(&curthread->lock);
-		_thr_umutex_init(&_thr_atfork_lock);
+		_mutex_fork(curthread);
 
 		_thr_signal_postfork_child();
 
@@ -192,13 +192,12 @@ _fork(void)
 
 		/* reinitialize libc spinlocks. */
 		_thr_spinlock_init();
-		_mutex_fork(curthread);
 
 		/* reinitalize library. */
 		_libpthread_init(curthread);
 
-		/* Ready to continue, unblock signals. */ 
-		_thr_signal_unblock(curthread);
+		/* atfork is reinitializeded by _libpthread_init()! */
+		_thr_rwl_rdlock(&_thr_atfork_lock);
 
 		if (was_threaded) {
 			__isthreaded = 1;
@@ -206,32 +205,36 @@ _fork(void)
 			__isthreaded = 0;
 		}
 
+		/* Ready to continue, unblock signals. */ 
+		_thr_signal_unblock(curthread);
+
 		/* Run down atfork child handlers. */
 		TAILQ_FOREACH(af, &_thr_atfork_list, qe) {
 			if (af->child != NULL)
 				af->child();
 		}
+		_thr_rwlock_unlock(&_thr_atfork_lock);
 	} else {
 		/* Parent process */
 		errsave = errno;
 
 		_thr_signal_postfork();
 
-		/* Ready to continue, unblock signals. */ 
-		_thr_signal_unblock(curthread);
-
 		if (was_threaded) {
 			_rtld_atfork_post(rtld_locks);
 			_malloc_postfork();
 		}
 
+		/* Ready to continue, unblock signals. */ 
+		_thr_signal_unblock(curthread);
+
 		/* Run down atfork parent handlers. */
 		TAILQ_FOREACH(af, &_thr_atfork_list, qe) {
 			if (af->parent != NULL)
 				af->parent();
 		}
 
-		THR_UMUTEX_UNLOCK(curthread, &_thr_atfork_lock);
+		_thr_rwlock_unlock(&_thr_atfork_lock);
 	}
 	errno = errsave;
 
diff --git a/lib/libthr/thread/thr_init.c b/lib/libthr/thread/thr_init.c
index ea567ee9958..e5dc2ce400d 100644
--- a/lib/libthr/thread/thr_init.c
+++ b/lib/libthr/thread/thr_init.c
@@ -65,7 +65,7 @@ pthreadlist	_thread_list = TAILQ_HEAD_INITIALIZER(_thread_list);
 pthreadlist 	_thread_gc_list = TAILQ_HEAD_INITIALIZER(_thread_gc_list);
 int		_thread_active_threads = 1;
 atfork_head	_thr_atfork_list = TAILQ_HEAD_INITIALIZER(_thr_atfork_list);
-struct umutex	_thr_atfork_lock = DEFAULT_UMUTEX;
+struct urwlock	_thr_atfork_lock = DEFAULT_URWLOCK;
 
 struct pthread_prio	_thr_priorities[3] = {
 	{RTP_PRIO_MIN,  RTP_PRIO_MAX, 0}, /* FIFO */
@@ -427,7 +427,7 @@ init_private(void)
 	_thr_umutex_init(&_cond_static_lock);
 	_thr_umutex_init(&_rwlock_static_lock);
 	_thr_umutex_init(&_keytable_lock);
-	_thr_umutex_init(&_thr_atfork_lock);
+	_thr_urwlock_init(&_thr_atfork_lock);
 	_thr_umutex_init(&_thr_event_lock);
 	_thr_once_init();
 	_thr_spinlock_init();
diff --git a/lib/libthr/thread/thr_mutex.c b/lib/libthr/thread/thr_mutex.c
index 5b69952fa86..fd8a342283e 100644
--- a/lib/libthr/thread/thr_mutex.c
+++ b/lib/libthr/thread/thr_mutex.c
@@ -224,8 +224,12 @@ _pthread_mutex_init_calloc_cb(pthread_mutex_t *mutex,
 		.m_ceiling = 0
 	};
 	static const struct pthread_mutex_attr *pattr = &attr;
+	int ret;
 
-	return mutex_init(mutex, (pthread_mutexattr_t *)&pattr, calloc_cb);
+	ret = mutex_init(mutex, (pthread_mutexattr_t *)&pattr, calloc_cb);
+	if (ret == 0)
+		(*mutex)->m_private = 1;
+	return (ret);
 }
 
 void
@@ -319,13 +323,16 @@ mutex_trylock_common(struct pthread *curthread, pthread_mutex_t *mutex)
 
 	id = TID(curthread);
 	m = *mutex;
+	if (m->m_private)
+		THR_CRITICAL_ENTER(curthread);
 	ret = _thr_umutex_trylock(&m->m_lock, id);
 	if (ret == 0) {
 		ENQUEUE_MUTEX(curthread, m);
 	} else if (m->m_owner == curthread) {
 		ret = mutex_self_trylock(m);
 	} /* else {} */
-
+	if (ret && m->m_private)
+		THR_CRITICAL_LEAVE(curthread);
 	return (ret);
 }
 
@@ -417,13 +424,19 @@ static inline int
 mutex_lock_common(struct pthread *curthread, struct pthread_mutex *m,
 	const struct timespec *abstime)
 {
+	int ret;
 
+	if (m->m_private)
+		THR_CRITICAL_ENTER(curthread);
 	if (_thr_umutex_trylock2(&m->m_lock, TID(curthread)) == 0) {
 		ENQUEUE_MUTEX(curthread, m);
-		return (0);
+		ret = 0;
+	} else {
+		ret = mutex_lock_sleep(curthread, m, abstime);
 	}
-	
-	return (mutex_lock_sleep(curthread, m, abstime));
+	if (ret && m->m_private)
+		THR_CRITICAL_LEAVE(curthread);
+	return (ret);
 }
 
 int
@@ -625,6 +638,8 @@ mutex_unlock_common(pthread_mutex_t *mutex)
 		MUTEX_INIT_LINK(m);
 		_thr_umutex_unlock(&m->m_lock, id);
 	}
+	if (m->m_private)
+		THR_CRITICAL_LEAVE(curthread);
 	return (0);
 }
 
@@ -660,6 +675,9 @@ _mutex_cv_unlock(pthread_mutex_t *mutex, int *count)
 	}
 	MUTEX_INIT_LINK(m);
 	_thr_umutex_unlock(&m->m_lock, TID(curthread));
+
+	if (m->m_private)
+		THR_CRITICAL_LEAVE(curthread);
 	return (0);
 }
 
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index 492d58d2063..a6bc205450f 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -132,6 +132,7 @@ struct pthread_mutex {
 	int				m_refcount;
 	int				m_spinloops;
 	int				m_yieldloops;
+	int				m_private;
 	/*
 	 * Link for all mutexes a thread currently owns.
 	 */
@@ -587,7 +588,7 @@ extern pthreadlist	_thread_gc_list __hidden;
 
 extern int		_thread_active_threads;
 extern atfork_head	_thr_atfork_list __hidden;
-extern struct umutex	_thr_atfork_lock __hidden;
+extern struct urwlock	_thr_atfork_lock __hidden;
 
 /* Default thread attributes: */
 extern struct pthread_attr _pthread_attr_default __hidden;
diff --git a/lib/libthr/thread/thr_umtx.c b/lib/libthr/thread/thr_umtx.c
index b712b7af880..dabfa359792 100644
--- a/lib/libthr/thread/thr_umtx.c
+++ b/lib/libthr/thread/thr_umtx.c
@@ -47,6 +47,13 @@ _thr_umutex_init(struct umutex *mtx)
 	*mtx = default_mtx;
 }
 
+void
+_thr_urwlock_init(struct urwlock *rwl)
+{
+	static struct urwlock default_rwl = DEFAULT_URWLOCK;
+	*rwl = default_rwl;
+}
+
 int
 __thr_umutex_lock(struct umutex *mtx, uint32_t id)
 {
diff --git a/lib/libthr/thread/thr_umtx.h b/lib/libthr/thread/thr_umtx.h
index 20489849f53..3f53fafcf7d 100644
--- a/lib/libthr/thread/thr_umtx.h
+++ b/lib/libthr/thread/thr_umtx.h
@@ -32,7 +32,8 @@
 #include 
 #include 
 
-#define DEFAULT_UMUTEX	{0,0, {0,0},{0,0,0,0}}
+#define DEFAULT_UMUTEX	{0,0,{0,0},{0,0,0,0}}
+#define DEFAULT_URWLOCK {0,0,0,0,{0,0,0,0}}
 
 int __thr_umutex_lock(struct umutex *mtx, uint32_t id) __hidden;
 int __thr_umutex_timedlock(struct umutex *mtx, uint32_t id,
@@ -43,6 +44,8 @@ int __thr_umutex_set_ceiling(struct umutex *mtx, uint32_t ceiling,
 	uint32_t *oldceiling) __hidden;
 
 void _thr_umutex_init(struct umutex *mtx) __hidden;
+void _thr_urwlock_init(struct urwlock *rwl) __hidden;
+
 int _thr_umtx_wait(volatile long *mtx, long exp,
 	const struct timespec *timeout) __hidden;
 int _thr_umtx_wait_uint(volatile u_int *mtx, u_int exp,

From a523216bc6c82fe915d2d1188029d01784db0d5d Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 1 Sep 2010 03:55:10 +0000
Subject: [PATCH 0408/1624] pthread_atfork should acquire writer lock and
 protect the code with critical region.

---
 lib/libthr/thread/thr_fork.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index 1ce7c6eb4ae..c70096ea642 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -89,9 +89,11 @@ _pthread_atfork(void (*prepare)(void), void (*parent)(void),
 	af->prepare = prepare;
 	af->parent = parent;
 	af->child = child;
-	_thr_rwl_rdlock(&_thr_atfork_lock);
+	THR_CRITICAL_ENTER(curthread);
+	_thr_rwl_wrlock(&_thr_atfork_lock);
 	TAILQ_INSERT_TAIL(&_thr_atfork_list, af, qe);
 	_thr_rwl_unlock(&_thr_atfork_lock);
+	THR_CRITICAL_LEAVE(curthread);
 	return (0);
 }
 

From 0cc17ce608ddb2cf9dad37e711b7bbb41ae4bb64 Mon Sep 17 00:00:00 2001
From: Ulf Lilleengen 
Date: Wed, 1 Sep 2010 05:34:17 +0000
Subject: [PATCH 0409/1624] - Remove duplicate comment.

PR:		kern/148820
Submitted by:	pluknet 
---
 sys/fs/ext2fs/ext2_alloc.c | 14 --------------
 1 file changed, 14 deletions(-)

diff --git a/sys/fs/ext2fs/ext2_alloc.c b/sys/fs/ext2fs/ext2_alloc.c
index 1095100aa9b..6f244957b45 100644
--- a/sys/fs/ext2fs/ext2_alloc.c
+++ b/sys/fs/ext2fs/ext2_alloc.c
@@ -75,20 +75,6 @@ static daddr_t  ext2_mapsearch(struct m_ext2fs *, char *, daddr_t);
  *        inode for the file.
  *   2) quadradically rehash into other cylinder groups, until an
  *        available block is located.
- *
- * A preference may be optionally specified. If a preference is given
- * the following hierarchy is used to allocate a block:
- *   1) allocate the requested block.
- *   2) allocate a rotationally optimal block in the same cylinder.
- *   3) allocate a block in the same cylinder group.
- *   4) quadradically rehash into other cylinder groups, until an
- *        available block is located.
- * If no block preference is given the following hierarchy is used
- * to allocate a block:
- *   1) allocate a block in the cylinder group that contains the
- *        inode for the file.
- *   2) quadradically rehash into other cylinder groups, until an
- *        available block is located.
  */
 
 int

From 901c71c7044d47f4ac6cc656e5d35aae7c8f2760 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 1 Sep 2010 06:43:41 +0000
Subject: [PATCH 0410/1624] Increase device reset timeout from 10 to 15
 seconds, same as in ahci(4). Some devices found need about 10-12 seconds to
 spinup.

---
 sys/dev/ata/chipsets/ata-ahci.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/ata/chipsets/ata-ahci.c b/sys/dev/ata/chipsets/ata-ahci.c
index 6811c795c85..ec1e8e3b870 100644
--- a/sys/dev/ata/chipsets/ata-ahci.c
+++ b/sys/dev/ata/chipsets/ata-ahci.c
@@ -815,7 +815,7 @@ ata_ahci_hardreset(device_t dev, int port, uint32_t *signature)
     if (!ata_sata_phy_reset(dev, port, 0))
 	return (ENOENT);
     /* Wait for clearing busy status. */
-    if (ata_ahci_wait_ready(dev, 10000)) {
+    if (ata_ahci_wait_ready(dev, 15000)) {
 	device_printf(dev, "hardware reset timeout\n");
 	return (EBUSY);
     }

From 12c61c22cee3fc4205ab945e038c9f1d6d0b0027 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 1 Sep 2010 07:09:46 +0000
Subject: [PATCH 0411/1624] In function __pthread_cxa_finalize(), also make
 code for removing atfork handler be async-signal safe.

---
 lib/libthr/thread/thr_fork.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index c70096ea642..c15e8f9a32a 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -100,22 +100,29 @@ _pthread_atfork(void (*prepare)(void), void (*parent)(void),
 void
 __pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
 {
+	atfork_head    temp_list = TAILQ_HEAD_INITIALIZER(temp_list);
 	struct pthread *curthread;
 	struct pthread_atfork *af, *af1;
 
 	_thr_check_init();
 
 	curthread = _get_curthread();
+	THR_CRITICAL_ENTER(curthread);
 	_thr_rwl_wrlock(&_thr_atfork_lock);
 	TAILQ_FOREACH_SAFE(af, &_thr_atfork_list, qe, af1) {
 		if (__elf_phdr_match_addr(phdr_info, af->prepare) ||
 		    __elf_phdr_match_addr(phdr_info, af->parent) ||
 		    __elf_phdr_match_addr(phdr_info, af->child)) {
 			TAILQ_REMOVE(&_thr_atfork_list, af, qe);
-			free(af);
+			TAILQ_INSERT_TAIL(&temp_list, af, qe);
 		}
 	}
 	_thr_rwl_unlock(&_thr_atfork_lock);
+	THR_CRITICAL_LEAVE(curthread);
+	while ((af = TAILQ_FIRST(&temp_list)) != NULL) {
+		TAILQ_REMOVE(&temp_list, af, qe);
+		free(af);
+	}
 	_thr_tsd_unload(phdr_info);
 	_thr_sigact_unload(phdr_info);
 }

From 28887567014fdc5f9d6a73940d3656d0f7191f02 Mon Sep 17 00:00:00 2001
From: Maxim Konovalov 
Date: Wed, 1 Sep 2010 08:32:40 +0000
Subject: [PATCH 0412/1624] o List MOUNTVER and SCHED classes.  X-ref
 gsched(8).  Bump Dd.

PR:		docs/149925
Submitted by:	arundel
---
 sbin/geom/core/geom.8 | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/sbin/geom/core/geom.8 b/sbin/geom/core/geom.8
index e745a3f0a96..5bc55bb2992 100644
--- a/sbin/geom/core/geom.8
+++ b/sbin/geom/core/geom.8
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd March 5, 2008
+.Dd September 1, 2010
 .Dt GEOM 8
 .Os
 .Sh NAME
@@ -120,6 +120,8 @@ LABEL
 .It
 MIRROR
 .It
+MOUNTVER
+.It
 MULTIPATH
 .It
 NOP
@@ -128,6 +130,8 @@ PART
 .It
 RAID3
 .It
+SCHED
+.It
 SHSEC
 .It
 STRIPE
@@ -177,6 +181,7 @@ geom md unload
 .Xr gnop 8 ,
 .Xr gpart 8 ,
 .Xr graid3 8 ,
+.Xr gsched 8 ,
 .Xr gshsec 8 ,
 .Xr gstripe 8 ,
 .Xr gvirstor 8

From 2400afc155562630eb9d9f4c376510514b488749 Mon Sep 17 00:00:00 2001
From: Ed Schouten 
Date: Wed, 1 Sep 2010 09:53:24 +0000
Subject: [PATCH 0413/1624] Remove reference to device minor numbers in psm(4)
 man page.

The number returned by stat(2) is generated automatically, so it is not
possible to deduce whether the device is blocking or not.

MFC after:	1 week
---
 share/man/man4/psm.4 | 19 +------------------
 1 file changed, 1 insertion(+), 18 deletions(-)

diff --git a/share/man/man4/psm.4 b/share/man/man4/psm.4
index ed911bdd914..ef23612ad88 100644
--- a/share/man/man4/psm.4
+++ b/share/man/man4/psm.4
@@ -179,22 +179,6 @@ The driver has an internal variable which governs the effect of
 the acceleration.
 Its value can be modified via the driver flag
 or via an ioctl call.
-.Ss Device Number
-The minor device number of the
-.Nm
-is made up of:
-.Bd -literal -offset indent
-minor = (`unit' << 1) | `non-blocking'
-.Ed
-.Pp
-where `unit' is the device number (usually 0) and the `non-blocking' bit
-is set to indicate ``do not block waiting for mouse input,
-return immediately''.
-The `non-blocking' bit should be set for \fIXFree86\fP,
-therefore the minor device number usually used for \fIXFree86\fP is 1.
-See
-.Sx FILES
-for device node names.
 .Sh DRIVER CONFIGURATION
 .Ss Kernel Configuration Options
 There are following kernel configuration options to control the
@@ -682,8 +666,7 @@ movement counts as described in
 .It Pa /dev/psm0
 `non-blocking' device node
 .It Pa /dev/bpsm0
-`blocking' device node under
-.Em devfs .
+`blocking' device node
 .El
 .Sh EXAMPLES
 In order to install the

From 8f7264f0e372ea41afc1c05fe3ddf083b7de0c47 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Wed, 1 Sep 2010 11:27:09 +0000
Subject: [PATCH 0414/1624] Include  on a generated header.

Sponsored by:	The FreeBSD Foundation
---
 cddl/contrib/opensolaris/lib/libdtrace/common/dt_program.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_program.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_program.c
index 73cf83eceb7..b110df39671 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_program.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_program.c
@@ -557,6 +557,10 @@ dt_header_provider(dtrace_hdl_t *dtp, dt_provider_t *pvp, FILE *out)
 	info.dthi_pfname = alloca(strlen(pvp->pv_desc.dtvd_name) + 1 + i);
 	dt_header_fmt_func(info.dthi_pfname, pvp->pv_desc.dtvd_name);
 
+#ifdef __FreeBSD__
+	if (fprintf(out, "#include \n\n") < 0)
+		return (dt_set_errno(dtp, errno));
+#endif
 	if (fprintf(out, "#if _DTRACE_VERSION\n\n") < 0)
 		return (dt_set_errno(dtp, errno));
 

From ea950d20f6d98c5e87300eb02f45f61a1e7ff7d1 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Wed, 1 Sep 2010 12:08:32 +0000
Subject: [PATCH 0415/1624] Make the /dev/dtrace/helper node have the mode
 0660. This allows programs that refuse to run as root (pgsql) to install
 probes when their user is part of the wheel group.

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/dev/dtrace/dtrace_load.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/cddl/dev/dtrace/dtrace_load.c b/sys/cddl/dev/dtrace/dtrace_load.c
index 912fe976b68..59267259c35 100644
--- a/sys/cddl/dev/dtrace/dtrace_load.c
+++ b/sys/cddl/dev/dtrace/dtrace_load.c
@@ -163,7 +163,7 @@ dtrace_load(void *dummy)
 #else
 	dtrace_dev = make_dev(&dtrace_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
 	    "dtrace/dtrace");
-	helper_dev = make_dev(&helper_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
+	helper_dev = make_dev(&helper_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660,
 	    "dtrace/helper");
 #endif
 

From 0090656231ba6849fc5b037d2b043bd6584083b3 Mon Sep 17 00:00:00 2001
From: Maxim Konovalov 
Date: Wed, 1 Sep 2010 12:08:54 +0000
Subject: [PATCH 0416/1624] o Sync the man page with the reality: nfs/ includes
 are under include/ and include/fs/.

PR:		docs/139153
Submitted by:	gjb
MFC after:	1 week
---
 share/man/man7/hier.7 | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/share/man/man7/hier.7 b/share/man/man7/hier.7
index 25d29eca2e7..b7aa57eb30f 100644
--- a/share/man/man7/hier.7
+++ b/share/man/man7/hier.7
@@ -250,6 +250,8 @@ per-process file descriptors file system
 FIFOs file system
 .It Pa msdosfs/
 MS-DOS file system
+.It Pa nfs/
+C include files for NFS (Network File System) version 2, 3 and 4
 .It Pa ntfs/
 NTFS file system
 .It Pa nullfs/
@@ -334,7 +336,7 @@ include files for the UNI signalling protocol
 .It Pa netsmb/
 SMB/CIFS requester
 .It Pa nfs/
-C include files for NFS (Network File System)
+C include files for NFS (Network File System) version 2 and 3 (legacy)
 .It Pa objc/
 Objective C include files
 .It Pa openssl/

From 21a9296f63047ef93ee3932bbfdb8c18a161123d Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 1 Sep 2010 13:22:55 +0000
Subject: [PATCH 0417/1624] Remove incorrect comments, also make sure signal is
 disabled when unregistering sigaction.

---
 lib/libthr/thread/thr_sig.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index 382ff4fbbab..b6755f91be0 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -415,19 +415,17 @@ _thr_signal_init(void)
 	__sys_sigprocmask(SIG_UNBLOCK, &act.sa_mask, NULL);
 }
 
-/*
- * called from rtld with rtld_lock locked, because rtld_lock is
- * a critical region, so all signals have already beeen masked.
- */
 void
 _thr_sigact_unload(struct dl_phdr_info *phdr_info)
 {
+	struct pthread *curthread = _get_curthread();
 	struct urwlock *rwlp;
 	struct sigaction *actp;
 	struct sigaction kact;
 	void (*handler)(int);
 	int sig;
  
+	_thr_signal_block(curthread);
 	for (sig = 1; sig < _SIG_MAXSIG; sig++) {
 		actp = &_thr_sigact[sig].sigact;
 retry:
@@ -447,9 +445,10 @@ retry:
 				kact.sa_handler != SIG_DFL &&
 				kact.sa_handler != SIG_IGN)
 				__sys_sigaction(sig, actp, NULL);
-				_thr_rwl_unlock(rwlp);
+			_thr_rwl_unlock(rwlp);
 		}
 	}
+	_thr_signal_unblock(curthread);
 }
 
 void

From e5ddf1158184fa58de4a89fb6c75ec9fe79510b1 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Wed, 1 Sep 2010 13:47:11 +0000
Subject: [PATCH 0418/1624] As long as we are going to panic anyway, there's no
 need to hide additional information behind DIAGNOSTIC.

---
 sys/kern/vfs_subr.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/kern/vfs_subr.c b/sys/kern/vfs_subr.c
index 783cbee1901..d770b988ef1 100644
--- a/sys/kern/vfs_subr.c
+++ b/sys/kern/vfs_subr.c
@@ -2203,9 +2203,7 @@ vputx(struct vnode *vp, int func)
 	}
 
 	if (vp->v_usecount != 1) {
-#ifdef DIAGNOSTIC
 		vprint("vputx: negative ref count", vp);
-#endif
 		panic("vputx: negative ref cnt");
 	}
 	CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);

From cd70197aa97908f96b0a5c517dec2c3f820ecb97 Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Wed, 1 Sep 2010 15:24:47 +0000
Subject: [PATCH 0419/1624] Use a cleaner expression to retrieve the memory
 size in pc98's boot2.c, which also avoids NULL pointer arithmetic, as
 suggested by jhb.  The available space goes from 11 bytes to 7.

Reviewed by:	nyan
Approved by:	rpaulo (mentor)
---
 sys/boot/pc98/boot2/boot2.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/sys/boot/pc98/boot2/boot2.c b/sys/boot/pc98/boot2/boot2.c
index e35b42536c2..54082ad207f 100644
--- a/sys/boot/pc98/boot2/boot2.c
+++ b/sys/boot/pc98/boot2/boot2.c
@@ -187,9 +187,8 @@ xfsread(ino_t inode, void *buf, size_t nbyte)
 static inline uint32_t
 memsize(void)
 {
-    u_char *p = (u_char *)PTOV(0x401);
-
-    return *p * 128 * 1024 + *(u_int16_t *)(p + (0x594 - 0x401)) * 1024 * 1024;
+    return (*(u_char *)PTOV(0x401) * 128 * 1024 +
+	*(uint16_t *)PTOV(0x594) * 1024 * 1024);
 }
 
 static inline void

From fc0487080a48e19775c1456ae120dff2a04d187e Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 1 Sep 2010 16:11:26 +0000
Subject: [PATCH 0420/1624] Fix a bug which results in peer IPv4 addresses
 a.b.c.d with 224<=d<=239 incorrectly being detected as multicast addresses on
 little endian systems.

MFC after: 2 weeks
---
 sys/netinet/sctp_pcb.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/netinet/sctp_pcb.c b/sys/netinet/sctp_pcb.c
index 846f55d8024..dd469cb90b3 100644
--- a/sys/netinet/sctp_pcb.c
+++ b/sys/netinet/sctp_pcb.c
@@ -5988,7 +5988,7 @@ sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
 				}
 				p4 = (struct sctp_ipv4addr_param *)phdr;
 				sin.sin_addr.s_addr = p4->addr;
-				if (IN_MULTICAST(sin.sin_addr.s_addr)) {
+				if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
 					/* Skip multi-cast addresses */
 					goto next_param;
 				}

From be4572c896a9bbd131ae025032ad3a5a0732af6f Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Wed, 1 Sep 2010 16:53:38 +0000
Subject: [PATCH 0421/1624] Add a sysctl knob to accept input packets on any
 link in a failover lagg.

---
 sys/net/if_lagg.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/sys/net/if_lagg.c b/sys/net/if_lagg.c
index cb146015fa7..8911cee1426 100644
--- a/sys/net/if_lagg.c
+++ b/sys/net/if_lagg.c
@@ -162,6 +162,14 @@ static const struct {
 	{ LAGG_PROTO_NONE,		NULL }
 };
 
+SYSCTL_DECL(_net_link);
+SYSCTL_NODE(_net_link, OID_AUTO, lagg, CTLFLAG_RW, 0, "Link Aggregation");
+
+static int lagg_failover_rx_all = 0; /* Allow input on any failover links */
+SYSCTL_INT(_net_link_lagg, OID_AUTO, failover_rx_all, CTLFLAG_RW,
+    &lagg_failover_rx_all, 0,
+    "Accept input from any interface in a failover lagg");
+
 static int
 lagg_modevent(module_t mod, int type, void *data)
 {
@@ -1560,7 +1568,7 @@ lagg_fail_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
 	struct ifnet *ifp = sc->sc_ifp;
 	struct lagg_port *tmp_tp;
 
-	if (lp == sc->sc_primary) {
+	if (lp == sc->sc_primary || lagg_failover_rx_all) {
 		m->m_pkthdr.rcvif = ifp;
 		return (m);
 	}

From 833182b77e6bb9b6e7d89a6b3a2bbefb1df93338 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 1 Sep 2010 17:35:31 +0000
Subject: [PATCH 0422/1624] Updates for the RMI MIPS platform code - set
 cache_coherent_dma flag in cpuinfo for XLR, this will make sure that  
 BUS_DMA_COHERENT flag is handled correctly in busdma_machdep.c - iodi.c, call
 device_get_name() just once - clear RMI specific EIRR while intializing CPUs
 - remove debug print in intr_machdep.c

---
 sys/mips/rmi/intr_machdep.c |  7 +++----
 sys/mips/rmi/iodi.c         | 11 ++++++-----
 sys/mips/rmi/pic.h          |  2 +-
 sys/mips/rmi/xlr_machdep.c  |  3 +++
 4 files changed, 13 insertions(+), 10 deletions(-)

diff --git a/sys/mips/rmi/intr_machdep.c b/sys/mips/rmi/intr_machdep.c
index 04f6cde02eb..c606548c19e 100644
--- a/sys/mips/rmi/intr_machdep.c
+++ b/sys/mips/rmi/intr_machdep.c
@@ -62,8 +62,10 @@ static int intrcnt_index;
 void
 xlr_enable_irq(int irq)
 {
+	uint64_t eimr;
 
-	write_c0_eimr64(read_c0_eimr64() | (1ULL << irq));
+	eimr = read_c0_eimr64();
+	write_c0_eimr64(eimr | (1ULL << irq));
 }
 
 void
@@ -128,9 +130,6 @@ xlr_establish_intr(const char *name, driver_filter_t filt,
 	 * FIXME locking - not needed now, because we do this only on
 	 * startup from CPU0
 	 */
-	printf("[%s] Setup intr %d called on cpu %d (%d)\n", name, irq,
-	    xlr_cpu_id(), PCPU_GET(cpuid));
-
 	src = &xlr_interrupts[irq];
 	ie = src->ie;
 	if (ie == NULL) {
diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index d8cb081e24c..47965673f56 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -95,7 +95,7 @@ bridge_pcmcia_ack(int irq)
 
 static int
 iodi_setup_intr(device_t dev, device_t child,
-    struct resource *ires, int flags, driver_filter_t * filt,
+    struct resource *ires, int flags, driver_filter_t *filt,
     driver_intr_t *intr, void *arg, void **cookiep)
 {
 	const char *name = device_get_name(child);
@@ -130,6 +130,7 @@ iodi_alloc_resource(device_t bus, device_t child, int type, int *rid,
     u_long start, u_long end, u_long count, u_int flags)
 {
 	struct resource *res = malloc(sizeof(*res), M_DEVBUF, M_WAITOK);
+	const char *name = device_get_name(child);
 	int unit;
 
 #ifdef DEBUG
@@ -151,7 +152,7 @@ iodi_alloc_resource(device_t bus, device_t child, int type, int *rid,
 	}
 #endif
 
-	if (strcmp(device_get_name(child), "uart") == 0) {
+	if (strcmp(name, "uart") == 0) {
 		if ((unit = device_get_unit(child)) == 0) {	/* uart 0 */
 			res->r_bushandle = (xlr_io_base + XLR_IO_UART_0_OFFSET);
 		} else if (unit == 1) {
@@ -160,13 +161,13 @@ iodi_alloc_resource(device_t bus, device_t child, int type, int *rid,
 			printf("%s: Unknown uart unit\n", __FUNCTION__);
 
 		res->r_bustag = uart_bus_space_mem;
-	} else if (strcmp(device_get_name(child), "ehci") == 0) {
+	} else if (strcmp(name, "ehci") == 0) {
 		res->r_bushandle = MIPS_PHYS_TO_KSEG1(0x1ef24000);
 		res->r_bustag = rmi_pci_bus_space;
-	} else if (strcmp(device_get_name(child), "cfi") == 0) {
+	} else if (strcmp(name, "cfi") == 0) {
 		res->r_bushandle = MIPS_PHYS_TO_KSEG1(0x1c000000);
 		res->r_bustag = 0;
-	} else if (strcmp(device_get_name(child), "ata") == 0) {
+	} else if (strcmp(name, "ata") == 0) {
 		res->r_bushandle = MIPS_PHYS_TO_KSEG1(0x1d000000);
 		res->r_bustag = rmi_pci_bus_space;  /* byte swapping (not really PCI) */
 	}
diff --git a/sys/mips/rmi/pic.h b/sys/mips/rmi/pic.h
index 8a3dd1f8b1d..55182dff008 100644
--- a/sys/mips/rmi/pic.h
+++ b/sys/mips/rmi/pic.h
@@ -189,7 +189,7 @@ pic_ack(int picintr)
 {
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 
-	xlr_write_reg(mmio, PIC_INT_ACK, 1 << picintr);
+	xlr_write_reg(mmio, PIC_INT_ACK, 1U << picintr);
 }
 
 static __inline
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index fcbba2c9dd6..7d050c7676f 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -266,6 +266,7 @@ mips_init(void)
 	init_param2(physmem);
 
 	mips_cpu_init();
+	cpuinfo.cache_coherent_dma = TRUE;
 	pmap_bootstrap();
 #ifdef DDB
 	kdb_init();
@@ -298,6 +299,7 @@ xlr_pic_init(void)
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
 	int i, level, irq;
 
+	write_c0_eimr64(0ULL);
 	mtx_init(&xlr_pic_lock, "pic", NULL, MTX_SPIN);
 	xlr_write_reg(mmio, PIC_CTRL, 0);
 
@@ -574,6 +576,7 @@ platform_init_ap(int cpuid)
 	stat |= MIPS_SR_COP_2_BIT | MIPS_SR_COP_0_BIT;
 	mips_wr_status(stat);
 
+	write_c0_eimr64(0ULL);
 	xlr_enable_irq(IRQ_IPI);
 	xlr_enable_irq(IRQ_TIMER);
 	if (xlr_thr_id() == 0) {

From 8eca70be71a3f8ca3cb6de3bd7f25c80e4ca442c Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 18:28:08 +0000
Subject: [PATCH 0423/1624] Remove leading and trailing white spaces. No
 functional changes.

---
 sys/dev/sis/if_sis.c    | 70 ++++++++++++++++++++---------------------
 sys/dev/sis/if_sisreg.h |  2 +-
 2 files changed, 36 insertions(+), 36 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 19833423c82..0416878f7c1 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -406,7 +406,7 @@ sis_read_mac(struct sis_softc *sc, device_t dev, caddr_t dest)
 
 	CSR_WRITE_4(sc, SIS_CSR, SIS_CSR_RELOAD | filtsave);
 	CSR_WRITE_4(sc, SIS_CSR, 0);
-		
+
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, filtsave & ~SIS_RXFILTCTL_ENABLE);
 
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR0);
@@ -429,9 +429,9 @@ static void
 sis_mii_sync(struct sis_softc *sc)
 {
 	int		i;
- 
+
  	SIO_SET(SIS_MII_DIR|SIS_MII_DATA);
- 
+
  	for (i = 0; i < 32; i++) {
  		SIO_SET(SIS_MII_CLK);
  		DELAY(1);
@@ -439,7 +439,7 @@ sis_mii_sync(struct sis_softc *sc)
  		DELAY(1);
  	}
 }
- 
+
 /*
  * Clock a series of bits through the MII.
  */
@@ -447,9 +447,9 @@ static void
 sis_mii_send(struct sis_softc *sc, uint32_t bits, int cnt)
 {
 	int			i;
- 
+
 	SIO_CLR(SIS_MII_CLK);
- 
+
 	for (i = (0x1 << (cnt - 1)); i; i >>= 1) {
 		if (bits & i) {
 			SIO_SET(SIS_MII_DATA);
@@ -462,7 +462,7 @@ sis_mii_send(struct sis_softc *sc, uint32_t bits, int cnt)
 		SIO_SET(SIS_MII_CLK);
 	}
 }
- 
+
 /*
  * Read an PHY register through the MII.
  */
@@ -470,7 +470,7 @@ static int
 sis_mii_readreg(struct sis_softc *sc, struct sis_mii_frame *frame)
 {
 	int			i, ack;
- 
+
 	/*
 	 * Set up frame for RX.
 	 */
@@ -478,14 +478,14 @@ sis_mii_readreg(struct sis_softc *sc, struct sis_mii_frame *frame)
 	frame->mii_opcode = SIS_MII_READOP;
 	frame->mii_turnaround = 0;
 	frame->mii_data = 0;
- 	
+
 	/*
  	 * Turn on data xmit.
 	 */
 	SIO_SET(SIS_MII_DIR);
 
 	sis_mii_sync(sc);
- 
+
 	/*
 	 * Send command/address info.
 	 */
@@ -493,23 +493,23 @@ sis_mii_readreg(struct sis_softc *sc, struct sis_mii_frame *frame)
 	sis_mii_send(sc, frame->mii_opcode, 2);
 	sis_mii_send(sc, frame->mii_phyaddr, 5);
 	sis_mii_send(sc, frame->mii_regaddr, 5);
- 
+
 	/* Idle bit */
 	SIO_CLR((SIS_MII_CLK|SIS_MII_DATA));
 	DELAY(1);
 	SIO_SET(SIS_MII_CLK);
 	DELAY(1);
- 
+
 	/* Turn off xmit. */
 	SIO_CLR(SIS_MII_DIR);
- 
+
 	/* Check for ack */
 	SIO_CLR(SIS_MII_CLK);
 	DELAY(1);
 	ack = CSR_READ_4(sc, SIS_EECTL) & SIS_MII_DATA;
 	SIO_SET(SIS_MII_CLK);
 	DELAY(1);
- 
+
 	/*
 	 * Now try reading data bits. If the ack failed, we still
 	 * need to clock through 16 cycles to keep the PHY(s) in sync.
@@ -523,7 +523,7 @@ sis_mii_readreg(struct sis_softc *sc, struct sis_mii_frame *frame)
 		}
 		goto fail;
 	}
- 
+
 	for (i = 0x8000; i; i >>= 1) {
 		SIO_CLR(SIS_MII_CLK);
 		DELAY(1);
@@ -547,47 +547,47 @@ fail:
 		return(1);
 	return(0);
 }
- 
+
 /*
  * Write to a PHY register through the MII.
  */
 static int
 sis_mii_writereg(struct sis_softc *sc, struct sis_mii_frame *frame)
 {
- 
+
  	/*
  	 * Set up frame for TX.
  	 */
- 
+
  	frame->mii_stdelim = SIS_MII_STARTDELIM;
  	frame->mii_opcode = SIS_MII_WRITEOP;
  	frame->mii_turnaround = SIS_MII_TURNAROUND;
- 	
+
  	/*
   	 * Turn on data output.
  	 */
  	SIO_SET(SIS_MII_DIR);
- 
+
  	sis_mii_sync(sc);
- 
+
  	sis_mii_send(sc, frame->mii_stdelim, 2);
  	sis_mii_send(sc, frame->mii_opcode, 2);
  	sis_mii_send(sc, frame->mii_phyaddr, 5);
  	sis_mii_send(sc, frame->mii_regaddr, 5);
  	sis_mii_send(sc, frame->mii_turnaround, 2);
  	sis_mii_send(sc, frame->mii_data, 16);
- 
+
  	/* Idle bit. */
  	SIO_SET(SIS_MII_CLK);
  	DELAY(1);
  	SIO_CLR(SIS_MII_CLK);
  	DELAY(1);
- 
+
  	/*
  	 * Turn off xmit.
  	 */
  	SIO_CLR(SIS_MII_DIR);
- 
+
  	return(0);
 }
 
@@ -877,7 +877,7 @@ sis_reset(struct sis_softc *sc)
 		CSR_WRITE_4(sc, NS_CLKRUN, 0);
 	}
 
-        return;
+	return;
 }
 
 /*
@@ -947,8 +947,8 @@ sis_attach(device_t dev)
 	sis_reset(sc);
 
 	if (sc->sis_type == SIS_TYPE_900 &&
-            (sc->sis_rev == SIS_REV_635 ||
-            sc->sis_rev == SIS_REV_900B)) {
+	    (sc->sis_rev == SIS_REV_635 ||
+	    sc->sis_rev == SIS_REV_900B)) {
 		SIO_SET(SIS_CFG_RND_CNT);
 		SIO_SET(SIS_CFG_PERR_DETECT);
 	}
@@ -1065,13 +1065,13 @@ sis_attach(device_t dev)
 	 * Allocate the parent bus DMA tag appropriate for PCI.
 	 */
 #define SIS_NSEG_NEW 32
-	 error = bus_dma_tag_create(NULL,	/* parent */ 
+	 error = bus_dma_tag_create(NULL,	/* parent */
 			1, 0,			/* alignment, boundary */
 			BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
 			BUS_SPACE_MAXADDR,	/* highaddr */
 			NULL, NULL,		/* filter, filterarg */
 			MAXBSIZE, SIS_NSEG_NEW,	/* maxsize, nsegments */
-			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */ 
+			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
 			BUS_DMA_ALLOCNOW,	/* flags */
 			NULL, NULL,		/* lockfunc, lockarg */
 			&sc->sis_parent_tag);
@@ -1213,7 +1213,7 @@ sis_attach(device_t dev)
 	 * Call MI attach routine.
 	 */
 	ether_ifattach(ifp, eaddr);
-	
+
 	/*
 	 * Tell the upper layer(s) we support long frames.
 	 */
@@ -1444,7 +1444,7 @@ sis_rxeof(struct sis_softc *sc)
 			continue;
 		}
 
-		/* No errors; receive the packet. */	
+		/* No errors; receive the packet. */
 #ifdef __NO_STRICT_ALIGNMENT
 		/*
 		 * On architectures without alignment problems we try to
@@ -1655,7 +1655,7 @@ sis_intr(void *arg)
 
 		if (status &
 		    (SIS_ISR_TX_DESC_OK | SIS_ISR_TX_ERR |
-		     SIS_ISR_TX_OK | SIS_ISR_TX_IDLE) )
+		    SIS_ISR_TX_OK | SIS_ISR_TX_IDLE) )
 			sis_txeof(sc);
 
 		if (status & (SIS_ISR_RX_DESC_OK | SIS_ISR_RX_OK |
@@ -1717,7 +1717,7 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head, uint32_t *txidx)
 			return (ENOBUFS);
 		*m_head = m;
 	}
-	
+
 	/*
  	 * Start packing the mbufs in this chain into
 	 * the fragment pointers. Stop when we run out
@@ -2003,7 +2003,7 @@ sis_initl(struct sis_softc *sc)
 		uint32_t reg;
 
 		/*
-		 * Short Cable Receive Errors (MP21.E) 
+		 * Short Cable Receive Errors (MP21.E)
 		 */
 		CSR_WRITE_4(sc, NS_PHY_PAGE, 0x0001);
 		reg = CSR_READ_4(sc, NS_PHY_DSPCFG) & 0xfff;
@@ -2141,7 +2141,7 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 			ifp->if_capenable |= IFCAP_POLLING;
 			SIS_UNLOCK(sc);
 			return (error);
-			
+
 		}
 		if (!(ifr->ifr_reqcap & IFCAP_POLLING) &&
 		    ifp->if_capenable & IFCAP_POLLING) {
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 927bd58f760..455c5987cea 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -252,7 +252,7 @@
 	 SIS_TXCFG_FILL(64)|SIS_TXCFG_DRAIN(1536))
 
 #define SIS_RXCFG_DRAIN_THRESH	0x0000003E /* 8-byte units */
-#define SIS_TXCFG_MPII03D	0x00040000 /* "Must be 1" */ 
+#define SIS_TXCFG_MPII03D	0x00040000 /* "Must be 1" */
 #define SIS_RXCFG_DMABURST	0x00700000
 #define SIS_RXCFG_RX_JABBER	0x08000000
 #define SIS_RXCFG_RX_TXPKTS	0x10000000

From cc26c0fd68455ba63dc57264ef72e244a7359510 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 18:39:35 +0000
Subject: [PATCH 0424/1624] style(9) - space after keywords.

---
 sys/dev/sis/if_sis.c | 70 ++++++++++++++++++++++----------------------
 1 file changed, 35 insertions(+), 35 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 0416878f7c1..3624e80b366 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -203,7 +203,7 @@ sis_reverse(uint16_t n)
 	n = ((n >>  4) & 0x0f0f) | ((n <<  4) & 0xf0f0);
 	n = ((n >>  8) & 0x00ff) | ((n <<  8) & 0xff00);
 
-	return(n);
+	return (n);
 }
 
 static void
@@ -342,7 +342,7 @@ sis_find_bridge(device_t dev)
 	int			i, j;
 
 	if ((pci_devclass = devclass_find("pci")) == NULL)
-		return(NULL);
+		return (NULL);
 
 	devclass_get_devices(pci_devclass, &pci_devices, &pci_count);
 
@@ -363,7 +363,7 @@ sis_find_bridge(device_t dev)
 
 done:
 	free(pci_devices, M_TEMP);
-	return(child);
+	return (child);
 }
 
 static void
@@ -515,7 +515,7 @@ sis_mii_readreg(struct sis_softc *sc, struct sis_mii_frame *frame)
 	 * need to clock through 16 cycles to keep the PHY(s) in sync.
 	 */
 	if (ack) {
-		for(i = 0; i < 16; i++) {
+		for (i = 0; i < 16; i++) {
 			SIO_CLR(SIS_MII_CLK);
 			DELAY(1);
 			SIO_SET(SIS_MII_CLK);
@@ -544,8 +544,8 @@ fail:
 	DELAY(1);
 
 	if (ack)
-		return(1);
-	return(0);
+		return (1);
+	return (0);
 }
 
 /*
@@ -588,7 +588,7 @@ sis_mii_writereg(struct sis_softc *sc, struct sis_mii_frame *frame)
  	 */
  	SIO_CLR(SIS_MII_DIR);
 
- 	return(0);
+ 	return (0);
 }
 
 static int
@@ -601,7 +601,7 @@ sis_miibus_readreg(device_t dev, int phy, int reg)
 
 	if (sc->sis_type == SIS_TYPE_83815) {
 		if (phy != 0)
-			return(0);
+			return (0);
 		/*
 		 * The NatSemi chip can take a while after
 		 * a reset to come ready, during which the BMSR
@@ -627,7 +627,7 @@ sis_miibus_readreg(device_t dev, int phy, int reg)
 		int i, val = 0;
 
 		if (phy != 0)
-			return(0);
+			return (0);
 
 		CSR_WRITE_4(sc, SIS_PHYCTL,
 		    (phy << 11) | (reg << 6) | SIS_PHYOP_READ);
@@ -640,15 +640,15 @@ sis_miibus_readreg(device_t dev, int phy, int reg)
 
 		if (i == SIS_TIMEOUT) {
 			device_printf(sc->sis_dev, "PHY failed to come ready\n");
-			return(0);
+			return (0);
 		}
 
 		val = (CSR_READ_4(sc, SIS_PHYCTL) >> 16) & 0xFFFF;
 
 		if (val == 0xFFFF)
-			return(0);
+			return (0);
 
-		return(val);
+		return (val);
 	} else {
 		bzero((char *)&frame, sizeof(frame));
 
@@ -656,7 +656,7 @@ sis_miibus_readreg(device_t dev, int phy, int reg)
 		frame.mii_regaddr = reg;
 		sis_mii_readreg(sc, &frame);
 
-		return(frame.mii_data);
+		return (frame.mii_data);
 	}
 }
 
@@ -670,9 +670,9 @@ sis_miibus_writereg(device_t dev, int phy, int reg, int data)
 
 	if (sc->sis_type == SIS_TYPE_83815) {
 		if (phy != 0)
-			return(0);
+			return (0);
 		CSR_WRITE_4(sc, NS_BMCR + (reg * 4), data);
-		return(0);
+		return (0);
 	}
 
 	/*
@@ -685,7 +685,7 @@ sis_miibus_writereg(device_t dev, int phy, int reg, int data)
 		int i;
 
 		if (phy != 0)
-			return(0);
+			return (0);
 
 		CSR_WRITE_4(sc, SIS_PHYCTL, (data << 16) | (phy << 11) |
 		    (reg << 6) | SIS_PHYOP_WRITE);
@@ -706,7 +706,7 @@ sis_miibus_writereg(device_t dev, int phy, int reg, int data)
 		frame.mii_data = data;
 		sis_mii_writereg(sc, &frame);
 	}
-	return(0);
+	return (0);
 }
 
 static void
@@ -891,7 +891,7 @@ sis_probe(device_t dev)
 
 	t = sis_devs;
 
-	while(t->sis_name != NULL) {
+	while (t->sis_name != NULL) {
 		if ((pci_get_vendor(dev) == t->sis_vid) &&
 		    (pci_get_device(dev) == t->sis_did)) {
 			device_set_desc(dev, t->sis_name);
@@ -900,7 +900,7 @@ sis_probe(device_t dev)
 		t++;
 	}
 
-	return(ENXIO);
+	return (ENXIO);
 }
 
 /*
@@ -1238,7 +1238,7 @@ fail:
 	if (error)
 		sis_detach(dev);
 
-	return(error);
+	return (error);
 }
 
 /*
@@ -1304,7 +1304,7 @@ sis_detach(device_t dev)
 
 	mtx_destroy(&sc->sis_mtx);
 
-	return(0);
+	return (0);
 }
 
 /*
@@ -1342,7 +1342,7 @@ sis_ring_init(struct sis_softc *sc)
 	for (i = 0; i < SIS_RX_LIST_CNT; i++, dp++) {
 		error = sis_newbuf(sc, dp, NULL);
 		if (error)
-			return(error);
+			return (error);
 		if (i == (SIS_RX_LIST_CNT - 1))
 			dp->sis_nextdesc = &sc->sis_rx_list[0];
 		else
@@ -1358,7 +1358,7 @@ sis_ring_init(struct sis_softc *sc)
 
 	sc->sis_rx_pdsc = &sc->sis_rx_list[0];
 
-	return(0);
+	return (0);
 }
 
 /*
@@ -1369,12 +1369,12 @@ sis_newbuf(struct sis_softc *sc, struct sis_desc *c, struct mbuf *m)
 {
 
 	if (c == NULL)
-		return(EINVAL);
+		return (EINVAL);
 
 	if (m == NULL) {
 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
 		if (m == NULL)
-			return(ENOBUFS);
+			return (ENOBUFS);
 	} else
 		m->m_data = m->m_ext.ext_buf;
 
@@ -1387,7 +1387,7 @@ sis_newbuf(struct sis_softc *sc, struct sis_desc *c, struct mbuf *m)
 	    sis_dma_map_desc_ptr, c, 0);
 	bus_dmamap_sync(sc->sis_tag, c->sis_map, BUS_DMASYNC_PREREAD);
 
-	return(0);
+	return (0);
 }
 
 /*
@@ -1407,7 +1407,7 @@ sis_rxeof(struct sis_softc *sc)
 
 	ifp = sc->sis_ifp;
 
-	for(cur_rx = sc->sis_rx_pdsc; SIS_OWNDESC(cur_rx);
+	for (cur_rx = sc->sis_rx_pdsc; SIS_OWNDESC(cur_rx);
 	    cur_rx = cur_rx->sis_nextdesc) {
 
 #ifdef DEVICE_POLLING
@@ -1729,7 +1729,7 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head, uint32_t *txidx)
 		if (m->m_len != 0) {
 			if ((SIS_TX_LIST_CNT -
 			    (sc->sis_tx_cnt + cnt)) < 2)
-				return(ENOBUFS);
+				return (ENOBUFS);
 			f = &sc->sis_tx_list[frag];
 			f->sis_ctl = SIS_CMDSTS_MORE | m->m_len;
 			bus_dmamap_create(sc->sis_tag, 0, &f->sis_map);
@@ -1747,7 +1747,7 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head, uint32_t *txidx)
 	}
 
 	if (m != NULL)
-		return(ENOBUFS);
+		return (ENOBUFS);
 
 	sc->sis_tx_list[cur].sis_mbuf = *m_head;
 	sc->sis_tx_list[cur].sis_ctl &= ~SIS_CMDSTS_MORE;
@@ -1755,7 +1755,7 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head, uint32_t *txidx)
 	sc->sis_tx_cnt += cnt;
 	*txidx = frag;
 
-	return(0);
+	return (0);
 }
 
 /*
@@ -1795,7 +1795,7 @@ sis_startl(struct ifnet *ifp)
 	if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
 		return;
 
-	while(sc->sis_tx_list[idx].sis_mbuf == NULL) {
+	while (sc->sis_tx_list[idx].sis_mbuf == NULL) {
 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
 		if (m_head == NULL)
 			break;
@@ -2071,7 +2071,7 @@ sis_ifmedia_upd(struct ifnet *ifp)
 	mii_mediachg(mii);
 	SIS_UNLOCK(sc);
 
-	return(0);
+	return (0);
 }
 
 /*
@@ -2101,7 +2101,7 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 	struct mii_data		*mii;
 	int			error = 0;
 
-	switch(command) {
+	switch (command) {
 	case SIOCSIFFLAGS:
 		SIS_LOCK(sc);
 		if (ifp->if_flags & IFF_UP) {
@@ -2134,7 +2134,7 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 		    !(ifp->if_capenable & IFCAP_POLLING)) {
 			error = ether_poll_register(sis_poll, ifp);
 			if (error)
-				return(error);
+				return (error);
 			SIS_LOCK(sc);
 			/* Disable interrupts */
 			CSR_WRITE_4(sc, SIS_IER, 0);
@@ -2160,7 +2160,7 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 		break;
 	}
 
-	return(error);
+	return (error);
 }
 
 static void

From 1d885b48c157f747744916f3c6ce1c89b3914021 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 18:41:59 +0000
Subject: [PATCH 0425/1624] Nuke unnecessary return at the end of function.

---
 sys/dev/sis/if_sis.c | 8 --------
 1 file changed, 8 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 3624e80b366..96ec5a0a123 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -393,7 +393,6 @@ sis_read_cmos(struct sis_softc *sc, device_t dev, caddr_t dest, int off, int cnt
 	}
 
 	pci_write_config(bridge, 0x48, reg & ~0x40, 1);
-	return;
 }
 
 static void
@@ -418,7 +417,6 @@ sis_read_mac(struct sis_softc *sc, device_t dev, caddr_t dest)
 
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, filtsave);
 	CSR_WRITE_4(sc, SIS_CSR, csrsave);
-	return;
 }
 #endif
 
@@ -789,8 +787,6 @@ sis_setmulti_ns(struct sis_softc *sc)
 	if_maddr_runlock(ifp);
 
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, filtsave);
-
-	return;
 }
 
 static void
@@ -876,8 +872,6 @@ sis_reset(struct sis_softc *sc)
 		CSR_WRITE_4(sc, NS_CLKRUN, NS_CLKRUN_PMESTS);
 		CSR_WRITE_4(sc, NS_CLKRUN, 0);
 	}
-
-	return;
 }
 
 /*
@@ -1538,8 +1532,6 @@ sis_txeof(struct sis_softc *sc)
 	}
 
 	sc->sis_watchdog_timer = (sc->sis_tx_cnt == 0) ? 0 : 5;
-
-	return;
 }
 
 static void

From a629f2b183dfeb553108d90f39c86aae71542e7b Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 19:33:40 +0000
Subject: [PATCH 0426/1624] bus_dma(9) cleanup.  o Enforce TX/RX descriptor
 ring alignment. NS data sheet says the    controller needs 4 bytes alignment
 but use 16 to cover both SiS    and NS controllers. I don't have SiS data
 sheet so I'm not sure    what is alignment restriction of SiS controller but
 16 would be    enough because it's larger than the size of a TX/RX
 descriptor.    Previously sis(4) ignored the alignment restriction.  o
 Enforce RX buffer alignment, 4.    Previously sis(4) ignored RX buffer
 alignment restriction.  o Limit number of TX DMA segment to be used to 16. It
 seems    controller has no restriction on number of DMA segments but    using
 more than 16 looks resource waste.  o Collapse long mbuf chains with
 m_collapse(9) instead of calling    expensive m_defrag(9).  o TX/RX side
 bus_dmamap_load_mbuf_sg(9) support and remove    unnecessary callbacks.  o
 Initial endianness support.  o Prefer local alignment fixup code to
 m_devget(9).  o Pre-allocate TX/RX mbuf DMA maps instead of
 creating/destroying    these maps in fast TX/RX path. On non-x86
 architectures, this is    very expensive operation and there is no need to do
 that.  o Add missing bus_dmamap_sync(9) in TX/RX path.  o watchdog is now
 unarmed only when there are no pending frames    on controller. Previously
 sis(4) blindly unarmed watchdog    without checking the number of queued
 frames.  o For efficiency, loaded DMA map is reused for error frames.  o DMA
 map loading failure is now gracefully handled. Previously    sis(4) ignored
 any DMA map loading errors.  o Nuke unused macros which are not appropriate
 for endianness    operation.  o Stop embedding driver maintained structures
 into descriptor    rings. Because TX/RX descriptor structures are shared
 between    host and controller, frequent bus_dmamap_sync(9) operations are   
 required in fast path. Embedding driver structures will increase    the size
 of DMA map which in turn will slow down performance.

---
 sys/dev/sis/if_sis.c    | 860 +++++++++++++++++++++-------------------
 sys/dev/sis/if_sisreg.h |  63 +--
 2 files changed, 500 insertions(+), 423 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 96ec5a0a123..4ad3371c10e 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -64,12 +64,15 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #include 
-#include 
-#include 
-#include 
+#include 
+#include 
 #include 
+#include 
+#include 
+#include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -127,13 +130,23 @@ static struct sis_type sis_devs[] = {
 };
 
 static int sis_detach(device_t);
+static __inline void sis_discard_rxbuf(struct sis_rxdesc *);
+static int sis_dma_alloc(struct sis_softc *);
+static void sis_dma_free(struct sis_softc *);
+static int sis_dma_ring_alloc(struct sis_softc *, bus_size_t, bus_size_t,
+    bus_dma_tag_t *, uint8_t **, bus_dmamap_t *, bus_addr_t *, const char *);
+static void sis_dmamap_cb(void *, bus_dma_segment_t *, int, int);
+#ifndef __NO_STRICT_ALIGNMENT
+static __inline void sis_fixup_rx(struct mbuf *);
+#endif
 static void sis_ifmedia_sts(struct ifnet *, struct ifmediareq *);
 static int sis_ifmedia_upd(struct ifnet *);
 static void sis_init(void *);
 static void sis_initl(struct sis_softc *);
 static void sis_intr(void *);
 static int sis_ioctl(struct ifnet *, u_long, caddr_t);
-static int sis_newbuf(struct sis_softc *, struct sis_desc *, struct mbuf *);
+static int sis_newbuf(struct sis_softc *, struct sis_rxdesc *);
+static int sis_rxeof(struct sis_softc *);
 static void sis_start(struct ifnet *);
 static void sis_startl(struct ifnet *);
 static void sis_stop(struct sis_softc *);
@@ -164,33 +177,6 @@ static struct resource_spec sis_res_spec[] = {
 #define SIO_CLR(x)					\
 	CSR_WRITE_4(sc, SIS_EECTL, CSR_READ_4(sc, SIS_EECTL) & ~x)
 
-static void
-sis_dma_map_desc_next(void *arg, bus_dma_segment_t *segs, int nseg, int error)
-{
-	struct sis_desc	*r;
-
-	r = arg;
-	r->sis_next = segs->ds_addr;
-}
-
-static void
-sis_dma_map_desc_ptr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
-{
-	struct sis_desc	*r;
-
-	r = arg;
-	r->sis_ptr = segs->ds_addr;
-}
-
-static void
-sis_dma_map_ring(void *arg, bus_dma_segment_t *segs, int nseg, int error)
-{
-	u_int32_t *p;
-
-	p = arg;
-	*p = segs->ds_addr;
-}
-
 /*
  * Routine to reverse the bits in a word. Stolen almost
  * verbatim from /usr/games/fortune.
@@ -1055,127 +1041,10 @@ sis_attach(device_t dev)
 		break;
 	}
 
-	/*
-	 * Allocate the parent bus DMA tag appropriate for PCI.
-	 */
-#define SIS_NSEG_NEW 32
-	 error = bus_dma_tag_create(NULL,	/* parent */
-			1, 0,			/* alignment, boundary */
-			BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
-			BUS_SPACE_MAXADDR,	/* highaddr */
-			NULL, NULL,		/* filter, filterarg */
-			MAXBSIZE, SIS_NSEG_NEW,	/* maxsize, nsegments */
-			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
-			BUS_DMA_ALLOCNOW,	/* flags */
-			NULL, NULL,		/* lockfunc, lockarg */
-			&sc->sis_parent_tag);
-	if (error)
+	/* Allocate DMA'able memory. */
+	if ((error = sis_dma_alloc(sc)) != 0)
 		goto fail;
 
-	/*
-	 * Now allocate a tag for the DMA descriptor lists and a chunk
-	 * of DMA-able memory based on the tag.  Also obtain the physical
-	 * addresses of the RX and TX ring, which we'll need later.
-	 * All of our lists are allocated as a contiguous block
-	 * of memory.
-	 */
-	error = bus_dma_tag_create(sc->sis_parent_tag,	/* parent */
-			1, 0,			/* alignment, boundary */
-			BUS_SPACE_MAXADDR,	/* lowaddr */
-			BUS_SPACE_MAXADDR,	/* highaddr */
-			NULL, NULL,		/* filter, filterarg */
-			SIS_RX_LIST_SZ, 1,	/* maxsize,nsegments */
-			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
-			0,			/* flags */
-			busdma_lock_mutex,	/* lockfunc */
-			&Giant,			/* lockarg */
-			&sc->sis_rx_tag);
-	if (error)
-		goto fail;
-
-	error = bus_dmamem_alloc(sc->sis_rx_tag,
-	    (void **)&sc->sis_rx_list, BUS_DMA_NOWAIT | BUS_DMA_ZERO,
-	    &sc->sis_rx_dmamap);
-
-	if (error) {
-		device_printf(dev, "no memory for rx list buffers!\n");
-		bus_dma_tag_destroy(sc->sis_rx_tag);
-		sc->sis_rx_tag = NULL;
-		goto fail;
-	}
-
-	error = bus_dmamap_load(sc->sis_rx_tag,
-	    sc->sis_rx_dmamap, &(sc->sis_rx_list[0]),
-	    sizeof(struct sis_desc), sis_dma_map_ring,
-	    &sc->sis_rx_paddr, 0);
-
-	if (error) {
-		device_printf(dev, "cannot get address of the rx ring!\n");
-		bus_dmamem_free(sc->sis_rx_tag,
-		    sc->sis_rx_list, sc->sis_rx_dmamap);
-		bus_dma_tag_destroy(sc->sis_rx_tag);
-		sc->sis_rx_tag = NULL;
-		goto fail;
-	}
-
-	error = bus_dma_tag_create(sc->sis_parent_tag,	/* parent */
-			1, 0,			/* alignment, boundary */
-			BUS_SPACE_MAXADDR,	/* lowaddr */
-			BUS_SPACE_MAXADDR,	/* highaddr */
-			NULL, NULL,		/* filter, filterarg */
-			SIS_TX_LIST_SZ, 1,	/* maxsize,nsegments */
-			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
-			0,			/* flags */
-			busdma_lock_mutex,	/* lockfunc */
-			&Giant,			/* lockarg */
-			&sc->sis_tx_tag);
-	if (error)
-		goto fail;
-
-	error = bus_dmamem_alloc(sc->sis_tx_tag,
-	    (void **)&sc->sis_tx_list, BUS_DMA_NOWAIT | BUS_DMA_ZERO,
-	    &sc->sis_tx_dmamap);
-
-	if (error) {
-		device_printf(dev, "no memory for tx list buffers!\n");
-		bus_dma_tag_destroy(sc->sis_tx_tag);
-		sc->sis_tx_tag = NULL;
-		goto fail;
-	}
-
-	error = bus_dmamap_load(sc->sis_tx_tag,
-	    sc->sis_tx_dmamap, &(sc->sis_tx_list[0]),
-	    sizeof(struct sis_desc), sis_dma_map_ring,
-	    &sc->sis_tx_paddr, 0);
-
-	if (error) {
-		device_printf(dev, "cannot get address of the tx ring!\n");
-		bus_dmamem_free(sc->sis_tx_tag,
-		    sc->sis_tx_list, sc->sis_tx_dmamap);
-		bus_dma_tag_destroy(sc->sis_tx_tag);
-		sc->sis_tx_tag = NULL;
-		goto fail;
-	}
-
-	error = bus_dma_tag_create(sc->sis_parent_tag,	/* parent */
-			1, 0,			/* alignment, boundary */
-			BUS_SPACE_MAXADDR,	/* lowaddr */
-			BUS_SPACE_MAXADDR,	/* highaddr */
-			NULL, NULL,		/* filter, filterarg */
-			MCLBYTES, 1,		/* maxsize,nsegments */
-			BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
-			0,			/* flags */
-			busdma_lock_mutex,	/* lockfunc */
-			&Giant,			/* lockarg */
-			&sc->sis_tag);
-	if (error)
-		goto fail;
-
-	/*
-	 * Obtain the physical addresses of the RX and TX
-	 * rings which we'll need later in the init routine.
-	 */
-
 	ifp = sc->sis_ifp = if_alloc(IFT_ETHER);
 	if (ifp == NULL) {
 		device_printf(dev, "can not if_alloc()\n");
@@ -1277,30 +1146,206 @@ sis_detach(device_t dev)
 	if (ifp)
 		if_free(ifp);
 
-	if (sc->sis_rx_tag) {
-		bus_dmamap_unload(sc->sis_rx_tag,
-		    sc->sis_rx_dmamap);
-		bus_dmamem_free(sc->sis_rx_tag,
-		    sc->sis_rx_list, sc->sis_rx_dmamap);
-		bus_dma_tag_destroy(sc->sis_rx_tag);
-	}
-	if (sc->sis_tx_tag) {
-		bus_dmamap_unload(sc->sis_tx_tag,
-		    sc->sis_tx_dmamap);
-		bus_dmamem_free(sc->sis_tx_tag,
-		    sc->sis_tx_list, sc->sis_tx_dmamap);
-		bus_dma_tag_destroy(sc->sis_tx_tag);
-	}
-	if (sc->sis_parent_tag)
-		bus_dma_tag_destroy(sc->sis_parent_tag);
-	if (sc->sis_tag)
-		bus_dma_tag_destroy(sc->sis_tag);
+	sis_dma_free(sc);
 
 	mtx_destroy(&sc->sis_mtx);
 
 	return (0);
 }
 
+struct sis_dmamap_arg {
+	bus_addr_t	sis_busaddr;
+};
+
+static void
+sis_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
+{
+	struct sis_dmamap_arg	*ctx;
+
+	if (error != 0)
+		return;
+
+	KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs));
+
+	ctx = (struct sis_dmamap_arg *)arg;
+	ctx->sis_busaddr = segs[0].ds_addr;
+}
+
+static int
+sis_dma_ring_alloc(struct sis_softc *sc, bus_size_t alignment,
+    bus_size_t maxsize, bus_dma_tag_t *tag, uint8_t **ring, bus_dmamap_t *map,
+    bus_addr_t *paddr, const char *msg)
+{
+	struct sis_dmamap_arg	ctx;
+	int			error;
+
+	error = bus_dma_tag_create(sc->sis_parent_tag, alignment, 0,
+	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, maxsize, 1,
+	    maxsize, 0, NULL, NULL, tag);
+	if (error != 0) {
+		device_printf(sc->sis_dev,
+		    "could not create %s dma tag\n", msg);
+		return (ENOMEM);
+	}
+	/* Allocate DMA'able memory for ring. */
+	error = bus_dmamem_alloc(*tag, (void **)ring,
+	    BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, map);
+	if (error != 0) {
+		device_printf(sc->sis_dev,
+		    "could not allocate DMA'able memory for %s\n", msg);
+		return (ENOMEM);
+	}
+	/* Load the address of the ring. */
+	ctx.sis_busaddr = 0;
+	error = bus_dmamap_load(*tag, *map, *ring, maxsize, sis_dmamap_cb,
+	    &ctx, BUS_DMA_NOWAIT);
+	if (error != 0) {
+		device_printf(sc->sis_dev,
+		    "could not load DMA'able memory for %s\n", msg);
+		return (ENOMEM);
+	}
+	*paddr = ctx.sis_busaddr;
+	return (0);
+}
+
+static int
+sis_dma_alloc(struct sis_softc *sc)
+{
+	struct sis_rxdesc	*rxd;
+	struct sis_txdesc	*txd;
+	int			error, i;
+
+	/* Allocate the parent bus DMA tag appropriate for PCI. */
+	error = bus_dma_tag_create(bus_get_dma_tag(sc->sis_dev),
+	    1, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL,
+	    NULL, BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT,
+	    0, NULL, NULL, &sc->sis_parent_tag);
+	if (error != 0) {
+		device_printf(sc->sis_dev,
+		    "could not allocate parent dma tag\n");
+		return (ENOMEM);
+	}
+
+	/* Create RX ring. */
+	error = sis_dma_ring_alloc(sc, SIS_DESC_ALIGN, SIS_RX_LIST_SZ,
+	    &sc->sis_rx_list_tag, (uint8_t **)&sc->sis_rx_list,
+	    &sc->sis_rx_list_map, &sc->sis_rx_paddr, "RX ring");
+	if (error)
+		return (error);
+
+	/* Create TX ring. */
+	error = sis_dma_ring_alloc(sc, SIS_DESC_ALIGN, SIS_TX_LIST_SZ,
+	    &sc->sis_tx_list_tag, (uint8_t **)&sc->sis_tx_list,
+	    &sc->sis_tx_list_map, &sc->sis_tx_paddr, "TX ring");
+	if (error)
+		return (error);
+
+	/* Create tag for RX mbufs. */
+	error = bus_dma_tag_create(sc->sis_parent_tag, SIS_RX_BUF_ALIGN, 0,
+	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1,
+	    MCLBYTES, 0, NULL, NULL, &sc->sis_rx_tag);
+	if (error) {
+		device_printf(sc->sis_dev, "could not allocate RX dma tag\n");
+		return (error);
+	}
+
+	/* Create tag for TX mbufs. */
+	error = bus_dma_tag_create(sc->sis_parent_tag, 1, 0,
+	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
+	    MCLBYTES * SIS_MAXTXSEGS, SIS_MAXTXSEGS, MCLBYTES, 0, NULL, NULL,
+	    &sc->sis_tx_tag);
+	if (error) {
+		device_printf(sc->sis_dev, "could not allocate TX dma tag\n");
+		return (error);
+	}
+
+	/* Create DMA maps for RX buffers. */
+	error = bus_dmamap_create(sc->sis_rx_tag, 0, &sc->sis_rx_sparemap);
+	if (error) {
+		device_printf(sc->sis_dev,
+		    "can't create spare DMA map for RX\n");
+		return (error);
+	}
+	for (i = 0; i < SIS_RX_LIST_CNT; i++) {
+		rxd = &sc->sis_rxdesc[i];
+		rxd->rx_m = NULL;
+		error = bus_dmamap_create(sc->sis_rx_tag, 0, &rxd->rx_dmamap);
+		if (error) {
+			device_printf(sc->sis_dev,
+			    "can't create DMA map for RX\n");
+			return (error);
+		}
+	}
+
+	/* Create DMA maps for TX buffers. */
+	for (i = 0; i < SIS_TX_LIST_CNT; i++) {
+		txd = &sc->sis_txdesc[i];
+		txd->tx_m = NULL;
+		error = bus_dmamap_create(sc->sis_tx_tag, 0, &txd->tx_dmamap);
+		if (error) {
+			device_printf(sc->sis_dev,
+			    "can't create DMA map for TX\n");
+			return (error);
+		}
+	}
+
+	return (0);
+}
+
+static void
+sis_dma_free(struct sis_softc *sc)
+{
+	struct sis_rxdesc	*rxd;
+	struct sis_txdesc	*txd;
+	int			i;
+
+	/* Destroy DMA maps for RX buffers. */
+	for (i = 0; i < SIS_RX_LIST_CNT; i++) {
+		rxd = &sc->sis_rxdesc[i];
+		if (rxd->rx_dmamap)
+			bus_dmamap_destroy(sc->sis_rx_tag, rxd->rx_dmamap);
+	}
+	if (sc->sis_rx_sparemap)
+		bus_dmamap_destroy(sc->sis_rx_tag, sc->sis_rx_sparemap);
+
+	/* Destroy DMA maps for TX buffers. */
+	for (i = 0; i < SIS_TX_LIST_CNT; i++) {
+		txd = &sc->sis_txdesc[i];
+		if (txd->tx_dmamap)
+			bus_dmamap_destroy(sc->sis_tx_tag, txd->tx_dmamap);
+	}
+
+	if (sc->sis_rx_tag)
+		bus_dma_tag_destroy(sc->sis_rx_tag);
+	if (sc->sis_tx_tag)
+		bus_dma_tag_destroy(sc->sis_tx_tag);
+
+	/* Destroy RX ring. */
+	if (sc->sis_rx_list_map)
+		bus_dmamap_unload(sc->sis_rx_list_tag, sc->sis_rx_list_map);
+	if (sc->sis_rx_list_map && sc->sis_rx_list)
+		bus_dmamem_free(sc->sis_rx_list_tag, sc->sis_rx_list,
+		    sc->sis_rx_list_map);
+
+	if (sc->sis_rx_list_tag)
+		bus_dma_tag_destroy(sc->sis_rx_list_tag);
+
+	/* Destroy TX ring. */
+	if (sc->sis_tx_list_map)
+		bus_dmamap_unload(sc->sis_tx_list_tag, sc->sis_tx_list_map);
+
+	if (sc->sis_tx_list_map && sc->sis_tx_list)
+		bus_dmamem_free(sc->sis_tx_list_tag, sc->sis_tx_list,
+		    sc->sis_tx_list_map);
+
+	if (sc->sis_tx_list_tag)
+		bus_dma_tag_destroy(sc->sis_tx_list_tag);
+
+	/* Destroy the parent tag. */
+	if (sc->sis_parent_tag)
+		bus_dma_tag_destroy(sc->sis_parent_tag);
+}
+
 /*
  * Initialize the TX and RX descriptors and allocate mbufs for them. Note that
  * we arrange the descriptors in a closed ring, so that the last descriptor
@@ -1309,48 +1354,41 @@ sis_detach(device_t dev)
 static int
 sis_ring_init(struct sis_softc *sc)
 {
-	int i, error;
-	struct sis_desc *dp;
+	struct sis_rxdesc	*rxd;
+	struct sis_txdesc	*txd;
+	bus_addr_t		next;
+	int			error, i;
 
-	dp = &sc->sis_tx_list[0];
-	for (i = 0; i < SIS_TX_LIST_CNT; i++, dp++) {
-		if (i == (SIS_TX_LIST_CNT - 1))
-			dp->sis_nextdesc = &sc->sis_tx_list[0];
+	bzero(&sc->sis_tx_list[0], SIS_TX_LIST_SZ);
+	for (i = 0; i < SIS_TX_LIST_CNT; i++) {
+		txd = &sc->sis_txdesc[i];
+		txd->tx_m = NULL;
+		if (i == SIS_TX_LIST_CNT - 1)
+			next = SIS_TX_RING_ADDR(sc, 0);
 		else
-			dp->sis_nextdesc = dp + 1;
-		bus_dmamap_load(sc->sis_tx_tag,
-		    sc->sis_tx_dmamap,
-		    dp->sis_nextdesc, sizeof(struct sis_desc),
-		    sis_dma_map_desc_next, dp, 0);
-		dp->sis_mbuf = NULL;
-		dp->sis_ptr = 0;
-		dp->sis_ctl = 0;
+			next = SIS_TX_RING_ADDR(sc, i + 1);
+		sc->sis_tx_list[i].sis_next = htole32(SIS_ADDR_LO(next));
 	}
-
 	sc->sis_tx_prod = sc->sis_tx_cons = sc->sis_tx_cnt = 0;
+	bus_dmamap_sync(sc->sis_tx_list_tag, sc->sis_tx_list_map,
+	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 
-	bus_dmamap_sync(sc->sis_tx_tag,
-	    sc->sis_tx_dmamap, BUS_DMASYNC_PREWRITE);
-
-	dp = &sc->sis_rx_list[0];
-	for (i = 0; i < SIS_RX_LIST_CNT; i++, dp++) {
-		error = sis_newbuf(sc, dp, NULL);
+	sc->sis_rx_cons = 0;
+	bzero(&sc->sis_rx_list[0], SIS_RX_LIST_SZ);
+	for (i = 0; i < SIS_RX_LIST_CNT; i++) {
+		rxd = &sc->sis_rxdesc[i];
+		rxd->rx_desc = &sc->sis_rx_list[i];
+		if (i == SIS_RX_LIST_CNT - 1)
+			next = SIS_RX_RING_ADDR(sc, 0);
+		else
+			next = SIS_RX_RING_ADDR(sc, i + 1);
+		rxd->rx_desc->sis_next = htole32(SIS_ADDR_LO(next));
+		error = sis_newbuf(sc, rxd);
 		if (error)
 			return (error);
-		if (i == (SIS_RX_LIST_CNT - 1))
-			dp->sis_nextdesc = &sc->sis_rx_list[0];
-		else
-			dp->sis_nextdesc = dp + 1;
-		bus_dmamap_load(sc->sis_rx_tag,
-		    sc->sis_rx_dmamap,
-		    dp->sis_nextdesc, sizeof(struct sis_desc),
-		    sis_dma_map_desc_next, dp, 0);
-		}
-
-	bus_dmamap_sync(sc->sis_rx_tag,
-	    sc->sis_rx_dmamap, BUS_DMASYNC_PREWRITE);
-
-	sc->sis_rx_pdsc = &sc->sis_rx_list[0];
+	}
+	bus_dmamap_sync(sc->sis_rx_list_tag, sc->sis_rx_list_map,
+	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 
 	return (0);
 }
@@ -1359,31 +1397,67 @@ sis_ring_init(struct sis_softc *sc)
  * Initialize an RX descriptor and attach an MBUF cluster.
  */
 static int
-sis_newbuf(struct sis_softc *sc, struct sis_desc *c, struct mbuf *m)
+sis_newbuf(struct sis_softc *sc, struct sis_rxdesc *rxd)
 {
+	struct mbuf		*m;
+	bus_dma_segment_t	segs[1];
+	bus_dmamap_t		map;
+	int nsegs;
 
-	if (c == NULL)
-		return (EINVAL);
+	m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
+	if (m == NULL)
+		return (ENOBUFS);
+	m->m_len = m->m_pkthdr.len = SIS_RXLEN;
+#ifndef __NO_STRICT_ALIGNMENT
+	m_adj(m, SIS_RX_BUF_ALIGN);
+#endif
 
-	if (m == NULL) {
-		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
-		if (m == NULL)
-			return (ENOBUFS);
-	} else
-		m->m_data = m->m_ext.ext_buf;
-
-	c->sis_mbuf = m;
-	c->sis_ctl = SIS_RXLEN;
-
-	bus_dmamap_create(sc->sis_tag, 0, &c->sis_map);
-	bus_dmamap_load(sc->sis_tag, c->sis_map,
-	    mtod(m, void *), MCLBYTES,
-	    sis_dma_map_desc_ptr, c, 0);
-	bus_dmamap_sync(sc->sis_tag, c->sis_map, BUS_DMASYNC_PREREAD);
+	if (bus_dmamap_load_mbuf_sg(sc->sis_rx_tag, sc->sis_rx_sparemap, m,
+	    segs, &nsegs, 0) != 0) {
+		m_freem(m);
+		return (ENOBUFS);
+	}
+	KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs));
 
+	if (rxd->rx_m != NULL) {
+		bus_dmamap_sync(sc->sis_rx_tag, rxd->rx_dmamap,
+		    BUS_DMASYNC_POSTREAD);
+		bus_dmamap_unload(sc->sis_rx_tag, rxd->rx_dmamap);
+	}
+	map = rxd->rx_dmamap;
+	rxd->rx_dmamap = sc->sis_rx_sparemap;
+	sc->sis_rx_sparemap = map;
+	bus_dmamap_sync(sc->sis_rx_tag, rxd->rx_dmamap, BUS_DMASYNC_PREREAD);
+	rxd->rx_m = m;
+	rxd->rx_desc->sis_cmdsts = htole32(SIS_RXLEN);
+	rxd->rx_desc->sis_ptr = htole32(SIS_ADDR_LO(segs[0].ds_addr));
 	return (0);
 }
 
+static __inline void
+sis_discard_rxbuf(struct sis_rxdesc *rxd)
+{
+
+	rxd->rx_desc->sis_cmdsts = htole32(SIS_RXLEN);
+}
+
+#ifndef __NO_STRICT_ALIGNMENT
+static __inline void
+sis_fixup_rx(struct mbuf *m)
+{
+	uint16_t		*src, *dst;
+	int			i;
+
+	src = mtod(m, uint16_t *);
+	dst = src - (SIS_RX_BUF_ALIGN - ETHER_ALIGN) / sizeof(*src);
+
+	for (i = 0; i < (m->m_len / sizeof(uint16_t) + 1); i++)
+		*dst++ = *src++;
+
+	m->m_data -= SIS_RX_BUF_ALIGN - ETHER_ALIGN;
+}
+#endif
+
 /*
  * A frame has been uploaded: pass the resulting mbuf chain up to
  * the higher level protocols.
@@ -1391,19 +1465,23 @@ sis_newbuf(struct sis_softc *sc, struct sis_desc *c, struct mbuf *m)
 static int
 sis_rxeof(struct sis_softc *sc)
 {
-	struct mbuf		*m, *m0;
+	struct mbuf		*m;
 	struct ifnet		*ifp;
+	struct sis_rxdesc	*rxd;
 	struct sis_desc		*cur_rx;
-	int			total_len = 0, rx_npkts = 0;
-	u_int32_t		rxstat;
+	int			prog, rx_cons, rx_npkts = 0, total_len;
+	uint32_t		rxstat;
 
 	SIS_LOCK_ASSERT(sc);
 
+	bus_dmamap_sync(sc->sis_rx_list_tag, sc->sis_rx_list_map,
+	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
+
+	rx_cons = sc->sis_rx_cons;
 	ifp = sc->sis_ifp;
 
-	for (cur_rx = sc->sis_rx_pdsc; SIS_OWNDESC(cur_rx);
-	    cur_rx = cur_rx->sis_nextdesc) {
-
+	for (prog = 0; (ifp->if_drv_flags & IFF_DRV_RUNNING) != 0;
+	    SIS_INC(rx_cons, SIS_RX_LIST_CNT), prog++) {
 #ifdef DEVICE_POLLING
 		if (ifp->if_capenable & IFCAP_POLLING) {
 			if (sc->rxcycles <= 0)
@@ -1411,21 +1489,13 @@ sis_rxeof(struct sis_softc *sc)
 			sc->rxcycles--;
 		}
 #endif
-		rxstat = cur_rx->sis_rxstat;
-		bus_dmamap_sync(sc->sis_tag,
-		    cur_rx->sis_map, BUS_DMASYNC_POSTWRITE);
-		bus_dmamap_unload(sc->sis_tag, cur_rx->sis_map);
-		bus_dmamap_destroy(sc->sis_tag, cur_rx->sis_map);
-		m = cur_rx->sis_mbuf;
-		cur_rx->sis_mbuf = NULL;
-		total_len = SIS_RXBYTES(cur_rx);
+		cur_rx = &sc->sis_rx_list[rx_cons];
+		rxstat = le32toh(cur_rx->sis_cmdsts);
+		if ((rxstat & SIS_CMDSTS_OWN) == 0)
+			break;
+		rxd = &sc->sis_rxdesc[rx_cons];
 
-		/*
-		 * If an error occurs, update stats, clear the
-		 * status word and leave the mbuf cluster in place:
-		 * it should simply get re-used next time this descriptor
-	 	 * comes up in the ring.
-		 */
+		total_len = (rxstat & SIS_CMDSTS_BUFLEN) - ETHER_CRC_LEN;
 		if ((ifp->if_capenable & IFCAP_VLAN_MTU) != 0 &&
 		    total_len <= (ETHER_MAX_LEN + ETHER_VLAN_ENCAP_LEN -
 		    ETHER_CRC_LEN))
@@ -1434,36 +1504,29 @@ sis_rxeof(struct sis_softc *sc)
 			ifp->if_ierrors++;
 			if (rxstat & SIS_RXSTAT_COLL)
 				ifp->if_collisions++;
-			sis_newbuf(sc, cur_rx, m);
+			sis_discard_rxbuf(rxd);
+			continue;
+		}
+
+		/* Add a new receive buffer to the ring. */
+		m = rxd->rx_m;
+		if (sis_newbuf(sc, rxd) != 0) {
+			ifp->if_iqdrops++;
+			sis_discard_rxbuf(rxd);
 			continue;
 		}
 
 		/* No errors; receive the packet. */
-#ifdef __NO_STRICT_ALIGNMENT
+		m->m_pkthdr.len = m->m_len = total_len;
+#ifndef __NO_STRICT_ALIGNMENT
 		/*
 		 * On architectures without alignment problems we try to
 		 * allocate a new buffer for the receive ring, and pass up
 		 * the one where the packet is already, saving the expensive
-		 * copy done in m_devget().
-		 * If we are on an architecture with alignment problems, or
-		 * if the allocation fails, then use m_devget and leave the
-		 * existing buffer in the receive ring.
+		 * copy operation.
 		 */
-		if (sis_newbuf(sc, cur_rx, NULL) == 0)
-			m->m_pkthdr.len = m->m_len = total_len;
-		else
+		sis_fixup_rx(m);
 #endif
-		{
-			m0 = m_devget(mtod(m, char *), total_len,
-				ETHER_ALIGN, ifp, NULL);
-			sis_newbuf(sc, cur_rx, m);
-			if (m0 == NULL) {
-				ifp->if_ierrors++;
-				continue;
-			}
-			m = m0;
-		}
-
 		ifp->if_ipackets++;
 		m->m_pkthdr.rcvif = ifp;
 
@@ -1473,7 +1536,12 @@ sis_rxeof(struct sis_softc *sc)
 		rx_npkts++;
 	}
 
-	sc->sis_rx_pdsc = cur_rx;
+	if (prog > 0) {
+		sc->sis_rx_cons = rx_cons;
+		bus_dmamap_sync(sc->sis_rx_list_tag, sc->sis_rx_list_map,
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+	}
+
 	return (rx_npkts);
 }
 
@@ -1486,52 +1554,54 @@ static void
 sis_txeof(struct sis_softc *sc)
 {
 	struct ifnet		*ifp;
-	u_int32_t		idx;
+	struct sis_desc		*cur_tx;
+	struct sis_txdesc	*txd;
+	uint32_t		cons, txstat;
 
 	SIS_LOCK_ASSERT(sc);
+
+	cons = sc->sis_tx_cons;
+	if (cons == sc->sis_tx_prod)
+		return;
+
 	ifp = sc->sis_ifp;
+	bus_dmamap_sync(sc->sis_tx_list_tag, sc->sis_tx_list_map,
+	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 
 	/*
 	 * Go through our tx list and free mbufs for those
 	 * frames that have been transmitted.
 	 */
-	for (idx = sc->sis_tx_cons; sc->sis_tx_cnt > 0;
-	    sc->sis_tx_cnt--, SIS_INC(idx, SIS_TX_LIST_CNT) ) {
-		struct sis_desc *cur_tx = &sc->sis_tx_list[idx];
-
-		if (SIS_OWNDESC(cur_tx))
+	for (; cons != sc->sis_tx_prod; SIS_INC(cons, SIS_TX_LIST_CNT)) {
+		cur_tx = &sc->sis_tx_list[cons];
+		txstat = le32toh(cur_tx->sis_cmdsts);
+		if ((txstat & SIS_CMDSTS_OWN) != 0)
 			break;
-
-		if (cur_tx->sis_ctl & SIS_CMDSTS_MORE)
-			continue;
-
-		if (!(cur_tx->sis_ctl & SIS_CMDSTS_PKT_OK)) {
-			ifp->if_oerrors++;
-			if (cur_tx->sis_txstat & SIS_TXSTAT_EXCESSCOLLS)
-				ifp->if_collisions++;
-			if (cur_tx->sis_txstat & SIS_TXSTAT_OUTOFWINCOLL)
-				ifp->if_collisions++;
+		txd = &sc->sis_txdesc[cons];
+		if (txd->tx_m != NULL) {
+			bus_dmamap_sync(sc->sis_tx_tag, txd->tx_dmamap,
+			    BUS_DMASYNC_POSTWRITE);
+			bus_dmamap_unload(sc->sis_tx_tag, txd->tx_dmamap);
+			m_freem(txd->tx_m);
+			txd->tx_m = NULL;
+			if ((txstat & SIS_CMDSTS_PKT_OK) != 0) {
+				ifp->if_opackets++;
+				ifp->if_collisions +=
+				    (txstat & SIS_TXSTAT_COLLCNT) >> 16;
+			} else {
+				ifp->if_oerrors++;
+				if (txstat & SIS_TXSTAT_EXCESSCOLLS)
+					ifp->if_collisions++;
+				if (txstat & SIS_TXSTAT_OUTOFWINCOLL)
+					ifp->if_collisions++;
+			}
 		}
-
-		ifp->if_collisions +=
-		    (cur_tx->sis_txstat & SIS_TXSTAT_COLLCNT) >> 16;
-
-		ifp->if_opackets++;
-		if (cur_tx->sis_mbuf != NULL) {
-			m_freem(cur_tx->sis_mbuf);
-			cur_tx->sis_mbuf = NULL;
-			bus_dmamap_unload(sc->sis_tag, cur_tx->sis_map);
-			bus_dmamap_destroy(sc->sis_tag, cur_tx->sis_map);
-		}
-	}
-
-	if (idx != sc->sis_tx_cons) {
-		/* we freed up some buffers */
-		sc->sis_tx_cons = idx;
+		sc->sis_tx_cnt--;
 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
 	}
-
-	sc->sis_watchdog_timer = (sc->sis_tx_cnt == 0) ? 0 : 5;
+	sc->sis_tx_cons = cons;
+	if (sc->sis_tx_cnt == 0)
+		sc->sis_watchdog_timer = 0;
 }
 
 static void
@@ -1680,83 +1750,80 @@ sis_intr(void *arg)
  * pointers to the fragment pointers.
  */
 static int
-sis_encap(struct sis_softc *sc, struct mbuf **m_head, uint32_t *txidx)
+sis_encap(struct sis_softc *sc, struct mbuf **m_head)
 {
-	struct sis_desc		*f = NULL;
 	struct mbuf		*m;
-	int			frag, cur, cnt = 0, chainlen = 0;
+	struct sis_txdesc	*txd;
+	struct sis_desc		*f;
+	bus_dma_segment_t	segs[SIS_MAXTXSEGS];
+	bus_dmamap_t		map;
+	int			error, i, frag, nsegs, prod;
 
-	/*
-	 * If there's no way we can send any packets, return now.
-	 */
-	if (SIS_TX_LIST_CNT - sc->sis_tx_cnt < 2)
-		return (ENOBUFS);
-
-	/*
-	 * Count the number of frags in this chain to see if
-	 * we need to m_defrag.  Since the descriptor list is shared
-	 * by all packets, we'll m_defrag long chains so that they
-	 * do not use up the entire list, even if they would fit.
-	 */
-
-	for (m = *m_head; m != NULL; m = m->m_next)
-		chainlen++;
-
-	if ((chainlen > SIS_TX_LIST_CNT / 4) ||
-	    ((SIS_TX_LIST_CNT - (chainlen + sc->sis_tx_cnt)) < 2)) {
-		m = m_defrag(*m_head, M_DONTWAIT);
-		if (m == NULL)
+	prod = sc->sis_tx_prod;
+	txd = &sc->sis_txdesc[prod];
+	error = bus_dmamap_load_mbuf_sg(sc->sis_tx_tag, txd->tx_dmamap,
+	    *m_head, segs, &nsegs, 0);
+	if (error == EFBIG) {
+		m = m_collapse(*m_head, M_DONTWAIT, SIS_MAXTXSEGS);
+		if (m == NULL) {
+			m_freem(*m_head);
+			*m_head = NULL;
 			return (ENOBUFS);
-		*m_head = m;
-	}
-
-	/*
- 	 * Start packing the mbufs in this chain into
-	 * the fragment pointers. Stop when we run out
- 	 * of fragments or hit the end of the mbuf chain.
-	 */
-	cur = frag = *txidx;
-
-	for (m = *m_head; m != NULL; m = m->m_next) {
-		if (m->m_len != 0) {
-			if ((SIS_TX_LIST_CNT -
-			    (sc->sis_tx_cnt + cnt)) < 2)
-				return (ENOBUFS);
-			f = &sc->sis_tx_list[frag];
-			f->sis_ctl = SIS_CMDSTS_MORE | m->m_len;
-			bus_dmamap_create(sc->sis_tag, 0, &f->sis_map);
-			bus_dmamap_load(sc->sis_tag, f->sis_map,
-			    mtod(m, void *), m->m_len,
-			    sis_dma_map_desc_ptr, f, 0);
-			bus_dmamap_sync(sc->sis_tag,
-			    f->sis_map, BUS_DMASYNC_PREREAD);
-			if (cnt != 0)
-				f->sis_ctl |= SIS_CMDSTS_OWN;
-			cur = frag;
-			SIS_INC(frag, SIS_TX_LIST_CNT);
-			cnt++;
 		}
+		*m_head = m;
+		error = bus_dmamap_load_mbuf_sg(sc->sis_tx_tag, txd->tx_dmamap,
+		    *m_head, segs, &nsegs, 0);
+		if (error != 0) {
+			m_freem(*m_head);
+			*m_head = NULL;
+			return (error);
+		}
+	} else if (error != 0)
+		return (error);
+
+	/* Check for descriptor overruns. */
+	if (sc->sis_tx_cnt + nsegs > SIS_TX_LIST_CNT - 1) {
+		bus_dmamap_unload(sc->sis_tx_tag, txd->tx_dmamap);
+		return (ENOBUFS);
 	}
 
-	if (m != NULL)
-		return (ENOBUFS);
+	bus_dmamap_sync(sc->sis_tx_tag, txd->tx_dmamap, BUS_DMASYNC_PREWRITE);
 
-	sc->sis_tx_list[cur].sis_mbuf = *m_head;
-	sc->sis_tx_list[cur].sis_ctl &= ~SIS_CMDSTS_MORE;
-	sc->sis_tx_list[*txidx].sis_ctl |= SIS_CMDSTS_OWN;
-	sc->sis_tx_cnt += cnt;
-	*txidx = frag;
+	frag = prod;
+	for (i = 0; i < nsegs; i++) {
+		f = &sc->sis_tx_list[prod];
+		if (i == 0)
+			f->sis_cmdsts = htole32(segs[i].ds_len |
+			    SIS_CMDSTS_MORE);
+		else
+			f->sis_cmdsts = htole32(segs[i].ds_len |
+			    SIS_CMDSTS_OWN | SIS_CMDSTS_MORE);
+		f->sis_ptr = htole32(SIS_ADDR_LO(segs[i].ds_addr));
+		SIS_INC(prod, SIS_TX_LIST_CNT);
+		sc->sis_tx_cnt++;
+	}
+
+	/* Update producer index. */
+	sc->sis_tx_prod = prod;
+
+	/* Remove MORE flag on the last descriptor. */
+	prod = (prod - 1) & (SIS_TX_LIST_CNT - 1);
+	f = &sc->sis_tx_list[prod];
+	f->sis_cmdsts &= ~htole32(SIS_CMDSTS_MORE);
+
+	/* Lastly transfer ownership of packet to the controller. */
+	f = &sc->sis_tx_list[frag];
+	f->sis_cmdsts |= htole32(SIS_CMDSTS_OWN);
+
+	/* Swap the last and the first dmamaps. */
+	map = txd->tx_dmamap;
+	txd->tx_dmamap = sc->sis_txdesc[frag].tx_dmamap;
+	sc->sis_txdesc[frag].tx_dmamap = map;
+	txd->tx_m = *m_head;
 
 	return (0);
 }
 
-/*
- * Main transmit routine. To avoid having to do mbuf copies, we put pointers
- * to the mbuf data regions directly in the transmit lists. We also save a
- * copy of the pointers since the transmit list fragment pointers are
- * physical addresses.
- */
-
 static void
 sis_start(struct ifnet *ifp)
 {
@@ -1772,27 +1839,26 @@ static void
 sis_startl(struct ifnet *ifp)
 {
 	struct sis_softc	*sc;
-	struct mbuf		*m_head = NULL;
-	u_int32_t		idx, queued = 0;
+	struct mbuf		*m_head;
+	int			queued;
 
 	sc = ifp->if_softc;
 
 	SIS_LOCK_ASSERT(sc);
 
-	if (!sc->sis_link)
+	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
+	    IFF_DRV_RUNNING || sc->sis_link == 0)
 		return;
 
-	idx = sc->sis_tx_prod;
-
-	if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
-		return;
-
-	while (sc->sis_tx_list[idx].sis_mbuf == NULL) {
+	for (queued = 0; !IFQ_DRV_IS_EMPTY(&ifp->if_snd) &&
+	    sc->sis_tx_cnt < SIS_TX_LIST_CNT - 4;) {
 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
 		if (m_head == NULL)
 			break;
 
-		if (sis_encap(sc, &m_head, &idx)) {
+		if (sis_encap(sc, &m_head) != 0) {
+			if (m_head == NULL)
+				break;
 			IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
 			break;
@@ -1805,12 +1871,12 @@ sis_startl(struct ifnet *ifp)
 		 * to him.
 		 */
 		BPF_MTAP(ifp, m_head);
-
 	}
 
 	if (queued) {
 		/* Transmit */
-		sc->sis_tx_prod = idx;
+		bus_dmamap_sync(sc->sis_tx_list_tag, sc->sis_tx_list_map,
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 		SIS_SETBIT(sc, SIS_CSR, SIS_CSR_TX_ENABLE);
 
 		/*
@@ -1948,8 +2014,8 @@ sis_initl(struct sis_softc *sc)
 	/*
 	 * Load the address of the RX and TX lists.
 	 */
-	CSR_WRITE_4(sc, SIS_RX_LISTPTR, sc->sis_rx_paddr);
-	CSR_WRITE_4(sc, SIS_TX_LISTPTR, sc->sis_tx_paddr);
+	CSR_WRITE_4(sc, SIS_RX_LISTPTR, SIS_ADDR_LO(sc->sis_rx_paddr));
+	CSR_WRITE_4(sc, SIS_TX_LISTPTR, SIS_ADDR_LO(sc->sis_tx_paddr));
 
 	/* SIS_CFG_EDB_MASTER_EN indicates the EDB bus is used instead of
 	 * the PCI bus. When this bit is set, the Max DMA Burst Size
@@ -1991,7 +2057,7 @@ sis_initl(struct sis_softc *sc)
 	}
 
 	if (sc->sis_type == SIS_TYPE_83815 && sc->sis_srr < NS_SRR_16A &&
-	     IFM_SUBTYPE(mii->mii_media_active) == IFM_100_TX) {
+	    IFM_SUBTYPE(mii->mii_media_active) == IFM_100_TX) {
 		uint32_t reg;
 
 		/*
@@ -2186,9 +2252,10 @@ sis_watchdog(struct sis_softc *sc)
 static void
 sis_stop(struct sis_softc *sc)
 {
-	int i;
 	struct ifnet *ifp;
-	struct sis_desc *dp;
+	struct sis_rxdesc *rxd;
+	struct sis_txdesc *txd;
+	int i;
 
 	if (sc->sis_stopped)
 		return;
@@ -2212,32 +2279,31 @@ sis_stop(struct sis_softc *sc)
 	/*
 	 * Free data in the RX lists.
 	 */
-	dp = &sc->sis_rx_list[0];
-	for (i = 0; i < SIS_RX_LIST_CNT; i++, dp++) {
-		if (dp->sis_mbuf == NULL)
-			continue;
-		bus_dmamap_unload(sc->sis_tag, dp->sis_map);
-		bus_dmamap_destroy(sc->sis_tag, dp->sis_map);
-		m_freem(dp->sis_mbuf);
-		dp->sis_mbuf = NULL;
+	for (i = 0; i < SIS_RX_LIST_CNT; i++) {
+		rxd = &sc->sis_rxdesc[i];
+		if (rxd->rx_m != NULL) {
+			bus_dmamap_sync(sc->sis_rx_tag, rxd->rx_dmamap,
+			    BUS_DMASYNC_POSTREAD);
+			bus_dmamap_unload(sc->sis_rx_tag, rxd->rx_dmamap);
+			m_freem(rxd->rx_m);
+			rxd->rx_m = NULL;
+		}
 	}
-	bzero(sc->sis_rx_list, SIS_RX_LIST_SZ);
 
 	/*
 	 * Free the TX list buffers.
 	 */
-	dp = &sc->sis_tx_list[0];
-	for (i = 0; i < SIS_TX_LIST_CNT; i++, dp++) {
-		if (dp->sis_mbuf == NULL)
-			continue;
-		bus_dmamap_unload(sc->sis_tag, dp->sis_map);
-		bus_dmamap_destroy(sc->sis_tag, dp->sis_map);
-		m_freem(dp->sis_mbuf);
-		dp->sis_mbuf = NULL;
+	for (i = 0; i < SIS_TX_LIST_CNT; i++) {
+		txd = &sc->sis_txdesc[i];
+		if (txd->tx_m != NULL) {
+			bus_dmamap_sync(sc->sis_tx_tag, txd->tx_dmamap,
+			    BUS_DMASYNC_POSTWRITE);
+			bus_dmamap_unload(sc->sis_tx_tag, txd->tx_dmamap);
+			m_freem(txd->tx_m);
+			txd->tx_m = NULL;
+		}
 	}
 
-	bzero(sc->sis_tx_list, SIS_TX_LIST_SZ);
-
 	sc->sis_stopped = 1;
 }
 
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 455c5987cea..2f233044e16 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -304,25 +304,13 @@
 #define NS_FILTADDR_FMEM_HI	0x000003FE
 
 /*
- * DMA descriptor structures. The first part of the descriptor
- * is the hardware descriptor format, which is just three longwords.
- * After this, we include some additional structure members for
- * use by the driver. Note that for this structure will be a different
- * size on the alpha, but that's okay as long as it's a multiple of 4
- * bytes in size.
+ * TX/RX DMA descriptor structures.
  */
 struct sis_desc {
 	/* SiS hardware descriptor section */
 	u_int32_t		sis_next;
 	u_int32_t		sis_cmdsts;
-#define sis_rxstat		sis_cmdsts
-#define sis_txstat		sis_cmdsts
-#define sis_ctl			sis_cmdsts
 	u_int32_t		sis_ptr;
-	/* Driver software section */
-	struct mbuf		*sis_mbuf;
-	struct sis_desc		*sis_nextdesc;
-	bus_dmamap_t		sis_map;
 };
 
 #define SIS_CMDSTS_BUFLEN	0x00000FFF
@@ -332,11 +320,6 @@ struct sis_desc {
 #define SIS_CMDSTS_MORE		0x40000000
 #define SIS_CMDSTS_OWN		0x80000000
 
-#define SIS_LASTDESC(x)		(!((x)->sis_ctl & SIS_CMDSTS_MORE))
-#define SIS_OWNDESC(x)		((x)->sis_ctl & SIS_CMDSTS_OWN)
-#define SIS_INC(x, y)		(x) = ((x) == ((y)-1)) ? 0 : (x)+1
-#define SIS_RXBYTES(x)		(((x)->sis_ctl & SIS_CMDSTS_BUFLEN) - ETHER_CRC_LEN)
-
 #define SIS_RXSTAT_COLL		0x00010000
 #define SIS_RXSTAT_LOOPBK	0x00020000
 #define SIS_RXSTAT_ALIGNERR	0x00040000
@@ -367,12 +350,25 @@ struct sis_desc {
 #define SIS_TXSTAT_UNDERRUN	0x02000000
 #define SIS_TXSTAT_TX_ABORT	0x04000000
 
+#define	SIS_DESC_ALIGN		16
+#define	SIS_RX_BUF_ALIGN	4
+#define	SIS_MAXTXSEGS		16
 #define SIS_RX_LIST_CNT		64
 #define SIS_TX_LIST_CNT		128
 
 #define SIS_RX_LIST_SZ		SIS_RX_LIST_CNT * sizeof(struct sis_desc)
 #define SIS_TX_LIST_SZ		SIS_TX_LIST_CNT * sizeof(struct sis_desc)
 
+#define	SIS_ADDR_LO(x)		((uint64_t) (x) & 0xffffffff)
+#define	SIS_ADDR_HI(x)		((uint64_t) (x) >> 32)
+
+#define	SIS_RX_RING_ADDR(sc, i)	\
+	((sc)->sis_rx_paddr + sizeof(struct sis_desc) * (i))
+#define	SIS_TX_RING_ADDR(sc, i)	\
+	((sc)->sis_tx_paddr + sizeof(struct sis_desc) * (i))
+
+#define	SIS_INC(x, y)		(x) = (x + 1) % (y)
+
 /*
  * SiS PCI vendor ID.
  */
@@ -434,6 +430,17 @@ struct sis_mii_frame {
 #define SIS_TYPE_83815	3
 #define SIS_TYPE_83816	4
 
+struct sis_txdesc {
+	struct mbuf		*tx_m;
+	bus_dmamap_t		tx_dmamap;
+};
+
+struct sis_rxdesc {
+	struct mbuf		*rx_m;
+	bus_dmamap_t		rx_dmamap;
+	struct sis_desc		*rx_desc;
+};
+
 struct sis_softc {
 	struct ifnet		*sis_ifp;	/* interface info */
 	struct resource		*sis_res[2];
@@ -446,18 +453,22 @@ struct sis_softc {
 	u_int			sis_srr;
 	struct sis_desc		*sis_rx_list;
 	struct sis_desc		*sis_tx_list;
-	bus_dma_tag_t		sis_rx_tag;
-	bus_dmamap_t		sis_rx_dmamap;
-	bus_dma_tag_t		sis_tx_tag;
-	bus_dmamap_t		sis_tx_dmamap;
+	bus_dma_tag_t		sis_rx_list_tag;
+	bus_dmamap_t		sis_rx_list_map;
+	bus_dma_tag_t		sis_tx_list_tag;
+	bus_dmamap_t		sis_tx_list_map;
 	bus_dma_tag_t		sis_parent_tag;
-	bus_dma_tag_t		sis_tag;
-	struct sis_desc		*sis_rx_pdsc;
+	bus_dma_tag_t		sis_rx_tag;
+	bus_dmamap_t		sis_rx_sparemap;
+	bus_dma_tag_t		sis_tx_tag;
+	struct sis_rxdesc	sis_rxdesc[SIS_RX_LIST_CNT];
+	struct sis_txdesc	sis_txdesc[SIS_TX_LIST_CNT];
 	int			sis_tx_prod;
 	int			sis_tx_cons;
 	int			sis_tx_cnt;
-	u_int32_t		sis_rx_paddr;
-	u_int32_t		sis_tx_paddr;
+	int			sis_rx_cons;;
+	bus_addr_t		sis_rx_paddr;
+	bus_addr_t		sis_tx_paddr;
 	struct callout		sis_stat_ch;
 	int			sis_watchdog_timer;
 	int			sis_stopped;

From 36058c09e4c0709b2d29c5e31efe0aa48acae329 Mon Sep 17 00:00:00 2001
From: Max Laier 
Date: Wed, 1 Sep 2010 19:50:03 +0000
Subject: [PATCH 0427/1624] rmlock(9) two additions and one change/fix:  - add
 rm_try_rlock().  - add RM_SLEEPABLE to use sx(9) as the back-end lock in
 order to sleep while    holding the write lock.  - change rm_noreadtoken to a
 cpu bitmask to indicate which CPUs need to go    through the lock/unlock in
 order to synchronize.  As a side effect, this    also avoids IPI to CPUs
 without any readers during rm_wlock.

Discussed with:		ups@, rwatson@ on arch@
Sponsored by:		Isilon Systems, Inc.
---
 share/man/man9/Makefile  |   1 +
 share/man/man9/locking.9 |   9 ++-
 share/man/man9/rmlock.9  |  30 ++++++++-
 sys/kern/kern_rmlock.c   | 127 +++++++++++++++++++++++++++------------
 sys/sys/_rmlock.h        |  10 ++-
 sys/sys/rmlock.h         |  22 ++++---
 6 files changed, 148 insertions(+), 51 deletions(-)

diff --git a/share/man/man9/Makefile b/share/man/man9/Makefile
index b438b90b9b1..e6d8881efce 100644
--- a/share/man/man9/Makefile
+++ b/share/man/man9/Makefile
@@ -986,6 +986,7 @@ MLINKS+=rman.9 rman_activate_resource.9 \
 MLINKS+=rmlock.9 rm_destroy.9 \
 	rmlock.9 rm_init.9 \
 	rmlock.9 rm_rlock.9 \
+	rmlock.9 rm_try_rlock.9 \
 	rmlock.9 rm_runlock.9 \
 	rmlock.9 RM_SYSINIT.9 \
 	rmlock.9 rm_wlock.9 \
diff --git a/share/man/man9/locking.9 b/share/man/man9/locking.9
index bd8a2335cc4..f2ff906e98a 100644
--- a/share/man/man9/locking.9
+++ b/share/man/man9/locking.9
@@ -301,7 +301,7 @@ one of the synchronization primitives discussed:
 .It mutex     Ta \&ok Ta \&ok-1 Ta \&no Ta \&ok Ta \&ok Ta \&no-3
 .It sx        Ta \&ok Ta \&ok Ta \&ok-2 Ta \&ok Ta \&ok Ta \&ok-4
 .It rwlock    Ta \&ok Ta \&ok Ta \&no Ta \&ok-2 Ta \&ok Ta \&no-3
-.It rmlock    Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&ok-2 Ta \&no
+.It rmlock    Ta \&ok Ta \&ok Ta \&ok-5 Ta \&ok Ta \&ok-2 Ta \&ok-5
 .El
 .Pp
 .Em *1
@@ -326,6 +326,13 @@ Though one can sleep holding an sx lock, one can also use
 .Fn sx_sleep
 which will atomically release this primitive when going to sleep and
 reacquire it on wakeup.
+.Pp
+.Em *5
+.Em Read-mostly
+locks can be initialized to support sleeping while holding a write lock.
+See
+.Xr rmlock 9
+for details.
 .Ss Context mode table
 The next table shows what can be used in different contexts.
 At this time this is a rather easy to remember table.
diff --git a/share/man/man9/rmlock.9 b/share/man/man9/rmlock.9
index e99661d9f8b..2e68b070477 100644
--- a/share/man/man9/rmlock.9
+++ b/share/man/man9/rmlock.9
@@ -35,6 +35,7 @@
 .Nm rm_init_flags ,
 .Nm rm_destroy ,
 .Nm rm_rlock ,
+.Nm rm_try_rlock ,
 .Nm rm_wlock ,
 .Nm rm_runlock ,
 .Nm rm_wunlock ,
@@ -53,6 +54,8 @@
 .Fn rm_destroy "struct rmlock *rm"
 .Ft void
 .Fn rm_rlock "struct rmlock *rm"  "struct rm_priotracker* tracker"
+.Ft int
+.Fn rm_try_rlock "struct rmlock *rm"  "struct rm_priotracker* tracker"
 .Ft void
 .Fn rm_wlock "struct rmlock *rm"
 .Ft void
@@ -84,14 +87,16 @@ Although reader/writer locks look very similar to
 locks, their usage pattern is different.
 Reader/writer locks can be treated as mutexes (see
 .Xr mutex 9 )
-with shared/exclusive semantics.
+with shared/exclusive semantics unless initialized with
+.Dv RM_SLEEPABLE .
 Unlike
 .Xr sx 9 ,
 an
 .Nm
 can be locked while holding a non-spin mutex, and an
 .Nm
-cannot be held while sleeping.
+cannot be held while sleeping, again unless initialized with
+.Dv RM_SLEEPABLE .
 The
 .Nm
 locks have full priority propagation like mutexes.
@@ -135,6 +140,13 @@ to ignore this lock.
 .It Dv RM_RECURSE
 Allow threads to recursively acquire exclusive locks for
 .Fa rm .
+.It Dv RM_SLEEPABLE
+Allow writers to sleep while holding the lock.
+Readers must not sleep while holding the lock and can avoid to sleep on
+taking the lock by using
+.Fn rm_try_rlock
+instead of
+.Fn rm_rlock .
 .El
 .It Fn rm_rlock "struct rmlock *rm" "struct rm_priotracker* tracker"
 Lock
@@ -161,6 +173,16 @@ access on
 .Fa rm .
 This is called
 .Dq "recursing on a lock" .
+.It Fn rm_try_rlock "struct rmlock *rm" "struct rm_priotracker* tracker"
+Try to lock
+.Fa rm
+as a reader.
+.Fn rm_try_rlock
+will return 0 if the lock cannot be acquired immediately;
+otherwise the lock will be acquired and a non-zero value will be returned.
+Note that
+.Fn rm_try_rlock
+may fail even while the lock is not currently held by a writer.
 .It Fn rm_wlock "struct rmlock *rm"
 Lock
 .Fa rm
@@ -217,6 +239,10 @@ The
 .Nm
 implementation is currently not optimized for single processor systems.
 .Pp
+.Fn rm_try_rlock
+can fail transiently even when there is no writer, while another reader
+updates the state on the local CPU.
+.Pp
 The
 .Nm
 implementation uses a single per CPU list shared by all
diff --git a/sys/kern/kern_rmlock.c b/sys/kern/kern_rmlock.c
index a6a622e141f..0ab5d744a5f 100644
--- a/sys/kern/kern_rmlock.c
+++ b/sys/kern/kern_rmlock.c
@@ -187,6 +187,8 @@ rm_cleanIPI(void *arg)
 	}
 }
 
+CTASSERT((RM_SLEEPABLE & LO_CLASSFLAGS) == RM_SLEEPABLE);
+
 void
 rm_init_flags(struct rmlock *rm, const char *name, int opts)
 {
@@ -197,9 +199,13 @@ rm_init_flags(struct rmlock *rm, const char *name, int opts)
 		liflags |= LO_WITNESS;
 	if (opts & RM_RECURSE)
 		liflags |= LO_RECURSABLE;
-	rm->rm_noreadtoken = 1;
+	rm->rm_writecpus = all_cpus;
 	LIST_INIT(&rm->rm_activeReaders);
-	mtx_init(&rm->rm_lock, name, "rmlock_mtx", MTX_NOWITNESS);
+	if (opts & RM_SLEEPABLE) {
+		liflags |= RM_SLEEPABLE;
+		sx_init_flags(&rm->rm_lock_sx, "rmlock_sx", SX_RECURSE);
+	} else
+		mtx_init(&rm->rm_lock_mtx, name, "rmlock_mtx", MTX_NOWITNESS);
 	lock_init(&rm->lock_object, &lock_class_rm, name, NULL, liflags);
 }
 
@@ -214,7 +220,10 @@ void
 rm_destroy(struct rmlock *rm)
 {
 
-	mtx_destroy(&rm->rm_lock);
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		sx_destroy(&rm->rm_lock_sx);
+	else
+		mtx_destroy(&rm->rm_lock_mtx);
 	lock_destroy(&rm->lock_object);
 }
 
@@ -222,7 +231,10 @@ int
 rm_wowned(struct rmlock *rm)
 {
 
-	return (mtx_owned(&rm->rm_lock));
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		return (sx_xlocked(&rm->rm_lock_sx));
+	else
+		return (mtx_owned(&rm->rm_lock_mtx));
 }
 
 void
@@ -241,8 +253,8 @@ rm_sysinit_flags(void *arg)
 	rm_init_flags(args->ra_rm, args->ra_desc, args->ra_opts);
 }
 
-static void
-_rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker)
+static int
+_rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker, int trylock)
 {
 	struct pcpu *pc;
 	struct rm_queue *queue;
@@ -252,9 +264,9 @@ _rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker)
 	pc = pcpu_find(curcpu);
 
 	/* Check if we just need to do a proper critical_exit. */
-	if (0 == rm->rm_noreadtoken) {
+	if (!(pc->pc_cpumask & rm->rm_writecpus)) {
 		critical_exit();
-		return;
+		return (1);
 	}
 
 	/* Remove our tracker from the per-cpu list. */
@@ -265,7 +277,7 @@ _rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker)
 		/* Just add back tracker - we hold the lock. */
 		rm_tracker_add(pc, tracker);
 		critical_exit();
-		return;
+		return (1);
 	}
 
 	/*
@@ -289,7 +301,7 @@ _rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker)
 				mtx_unlock_spin(&rm_spinlock);
 				rm_tracker_add(pc, tracker);
 				critical_exit();
-				return;
+				return (1);
 			}
 		}
 	}
@@ -297,20 +309,38 @@ _rm_rlock_hard(struct rmlock *rm, struct rm_priotracker *tracker)
 	sched_unpin();
 	critical_exit();
 
-	mtx_lock(&rm->rm_lock);
-	rm->rm_noreadtoken = 0;
-	critical_enter();
+	if (trylock) {
+		if (rm->lock_object.lo_flags & RM_SLEEPABLE) {
+			if (!sx_try_xlock(&rm->rm_lock_sx))
+				return (0);
+		} else {
+			if (!mtx_trylock(&rm->rm_lock_mtx))
+				return (0);
+		}
+	} else {
+		if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+			sx_xlock(&rm->rm_lock_sx);
+		else
+			mtx_lock(&rm->rm_lock_mtx);
+	}
 
+	critical_enter();
 	pc = pcpu_find(curcpu);
+	rm->rm_writecpus &= ~pc->pc_cpumask;
 	rm_tracker_add(pc, tracker);
 	sched_pin();
 	critical_exit();
 
-	mtx_unlock(&rm->rm_lock);
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		sx_xunlock(&rm->rm_lock_sx);
+	else
+		mtx_unlock(&rm->rm_lock_mtx);
+
+	return (1);
 }
 
-void
-_rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker)
+int
+_rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker, int trylock)
 {
 	struct thread *td = curthread;
 	struct pcpu *pc;
@@ -337,11 +367,11 @@ _rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker)
 	 * Fast path to combine two common conditions into a single
 	 * conditional jump.
 	 */
-	if (0 == (td->td_owepreempt | rm->rm_noreadtoken))
-		return;
+	if (0 == (td->td_owepreempt | (rm->rm_writecpus & pc->pc_cpumask)))
+		return (1);
 
 	/* We do not have a read token and need to acquire one. */
-	_rm_rlock_hard(rm, tracker);
+	return _rm_rlock_hard(rm, tracker, trylock);
 }
 
 static void
@@ -400,20 +430,26 @@ _rm_wlock(struct rmlock *rm)
 {
 	struct rm_priotracker *prio;
 	struct turnstile *ts;
+	cpumask_t readcpus;
 
-	mtx_lock(&rm->rm_lock);
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		sx_xlock(&rm->rm_lock_sx);
+	else
+		mtx_lock(&rm->rm_lock_mtx);
 
-	if (rm->rm_noreadtoken == 0) {
+	if (rm->rm_writecpus != all_cpus) {
 		/* Get all read tokens back */
 
-		rm->rm_noreadtoken = 1;
+		readcpus = all_cpus & (all_cpus & ~rm->rm_writecpus);
+		rm->rm_writecpus = all_cpus;
 
 		/*
-		 * Assumes rm->rm_noreadtoken update is visible on other CPUs
+		 * Assumes rm->rm_writecpus update is visible on other CPUs
 		 * before rm_cleanIPI is called.
 		 */
 #ifdef SMP
-		smp_rendezvous(smp_no_rendevous_barrier,
+		smp_rendezvous_cpus(readcpus,
+		    smp_no_rendevous_barrier,
 		    rm_cleanIPI,
 		    smp_no_rendevous_barrier,
 		    rm);
@@ -439,7 +475,10 @@ void
 _rm_wunlock(struct rmlock *rm)
 {
 
-	mtx_unlock(&rm->rm_lock);
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		sx_xunlock(&rm->rm_lock_sx);
+	else
+		mtx_unlock(&rm->rm_lock_mtx);
 }
 
 #ifdef LOCK_DEBUG
@@ -454,7 +493,11 @@ void _rm_wlock_debug(struct rmlock *rm, const char *file, int line)
 
 	LOCK_LOG_LOCK("RMWLOCK", &rm->lock_object, 0, 0, file, line);
 
-	WITNESS_LOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		WITNESS_LOCK(&rm->rm_lock_sx.lock_object, LOP_EXCLUSIVE,
+		    file, line);	
+	else
+		WITNESS_LOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
 
 	curthread->td_locks++;
 
@@ -465,25 +508,35 @@ _rm_wunlock_debug(struct rmlock *rm, const char *file, int line)
 {
 
 	curthread->td_locks--;
-	WITNESS_UNLOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
+	if (rm->lock_object.lo_flags & RM_SLEEPABLE)
+		WITNESS_UNLOCK(&rm->rm_lock_sx.lock_object, LOP_EXCLUSIVE,
+		    file, line);
+	else
+		WITNESS_UNLOCK(&rm->lock_object, LOP_EXCLUSIVE, file, line);
 	LOCK_LOG_LOCK("RMWUNLOCK", &rm->lock_object, 0, 0, file, line);
 	_rm_wunlock(rm);
 }
 
-void
+int
 _rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
-    const char *file, int line)
+    int trylock, const char *file, int line)
 {
-
+	if (!trylock && (rm->lock_object.lo_flags & RM_SLEEPABLE))
+		WITNESS_CHECKORDER(&rm->rm_lock_sx.lock_object, LOP_NEWORDER,
+		    file, line, NULL);
 	WITNESS_CHECKORDER(&rm->lock_object, LOP_NEWORDER, file, line, NULL);
 
-	_rm_rlock(rm, tracker);
+	if (_rm_rlock(rm, tracker, trylock)) {
+		LOCK_LOG_LOCK("RMRLOCK", &rm->lock_object, 0, 0, file, line);
 
-	LOCK_LOG_LOCK("RMRLOCK", &rm->lock_object, 0, 0, file, line);
+		WITNESS_LOCK(&rm->lock_object, 0, file, line);
 
-	WITNESS_LOCK(&rm->lock_object, 0, file, line);
+		curthread->td_locks++;
 
-	curthread->td_locks++;
+		return (1);
+	}
+
+	return (0);
 }
 
 void
@@ -517,12 +570,12 @@ _rm_wunlock_debug(struct rmlock *rm, const char *file, int line)
 	_rm_wunlock(rm);
 }
 
-void
+int
 _rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
-    const char *file, int line)
+    int trylock, const char *file, int line)
 {
 
-	_rm_rlock(rm, tracker);
+	return _rm_rlock(rm, tracker, trylock);
 }
 
 void
diff --git a/sys/sys/_rmlock.h b/sys/sys/_rmlock.h
index e5c68d54732..75a159c1082 100644
--- a/sys/sys/_rmlock.h
+++ b/sys/sys/_rmlock.h
@@ -45,11 +45,15 @@ LIST_HEAD(rmpriolist,rm_priotracker);
 
 struct rmlock {
 	struct lock_object lock_object; 
-	volatile int 	rm_noreadtoken;
+	volatile cpumask_t rm_writecpus;
 	LIST_HEAD(,rm_priotracker) rm_activeReaders;
-	struct mtx	rm_lock;
-
+	union {
+		struct mtx _rm_lock_mtx;
+		struct sx _rm_lock_sx;
+	} _rm_lock;
 };
+#define	rm_lock_mtx	_rm_lock._rm_lock_mtx
+#define	rm_lock_sx	_rm_lock._rm_lock_sx
 
 struct rm_priotracker {
 	struct rm_queue rmp_cpuQueue; /* Must be first */
diff --git a/sys/sys/rmlock.h b/sys/sys/rmlock.h
index 9766f670d2a..ef5776bcec3 100644
--- a/sys/sys/rmlock.h
+++ b/sys/sys/rmlock.h
@@ -33,6 +33,7 @@
 #define _SYS_RMLOCK_H_
 
 #include 
+#include 
 #include 
 #include 
 
@@ -43,6 +44,7 @@
  */
 #define	RM_NOWITNESS	0x00000001
 #define	RM_RECURSE	0x00000002
+#define	RM_SLEEPABLE	0x00000004
 
 void	rm_init(struct rmlock *rm, const char *name);
 void	rm_init_flags(struct rmlock *rm, const char *name, int opts);
@@ -53,14 +55,15 @@ void	rm_sysinit_flags(void *arg);
 
 void	_rm_wlock_debug(struct rmlock *rm, const char *file, int line);
 void	_rm_wunlock_debug(struct rmlock *rm, const char *file, int line);
-void	_rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
-	    const char *file, int line);
+int	_rm_rlock_debug(struct rmlock *rm, struct rm_priotracker *tracker,
+	    int trylock, const char *file, int line);
 void	_rm_runlock_debug(struct rmlock *rm,  struct rm_priotracker *tracker,
 	    const char *file, int line);
 
 void	_rm_wlock(struct rmlock *rm);
 void	_rm_wunlock(struct rmlock *rm);
-void	_rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker);
+int	_rm_rlock(struct rmlock *rm, struct rm_priotracker *tracker,
+	    int trylock);
 void	_rm_runlock(struct rmlock *rm,  struct rm_priotracker *tracker);
 
 /*
@@ -74,14 +77,17 @@ void	_rm_runlock(struct rmlock *rm,  struct rm_priotracker *tracker);
 #define	rm_wlock(rm)	_rm_wlock_debug((rm), LOCK_FILE, LOCK_LINE)
 #define	rm_wunlock(rm)	_rm_wunlock_debug((rm), LOCK_FILE, LOCK_LINE)
 #define	rm_rlock(rm,tracker)  \
-    _rm_rlock_debug((rm),(tracker), LOCK_FILE, LOCK_LINE )
+    ((void)_rm_rlock_debug((rm),(tracker), 0, LOCK_FILE, LOCK_LINE ))
+#define	rm_try_rlock(rm,tracker)  \
+    _rm_rlock_debug((rm),(tracker), 1, LOCK_FILE, LOCK_LINE )
 #define	rm_runlock(rm,tracker)	\
     _rm_runlock_debug((rm), (tracker), LOCK_FILE, LOCK_LINE )
 #else
-#define	rm_wlock(rm)		_rm_wlock((rm))
-#define	rm_wunlock(rm)		_rm_wunlock((rm))
-#define	rm_rlock(rm,tracker)   	_rm_rlock((rm),(tracker))
-#define	rm_runlock(rm,tracker)	_rm_runlock((rm), (tracker))
+#define	rm_wlock(rm)			_rm_wlock((rm))
+#define	rm_wunlock(rm)			_rm_wunlock((rm))
+#define	rm_rlock(rm,tracker)		((void)_rm_rlock((rm),(tracker), 0))
+#define	rm_try_rlock(rm,tracker)	_rm_rlock((rm),(tracker), 1)
+#define	rm_runlock(rm,tracker)		_rm_runlock((rm), (tracker))
 #endif
 
 struct rm_args {

From 91c265b83db965e65c78ed9227b980e2ea4cf141 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 19:53:15 +0000
Subject: [PATCH 0428/1624] s/u_intXX_t/uintXX_t/g

---
 sys/dev/sis/if_sis.c    | 40 ++++++++++++++++++++--------------------
 sys/dev/sis/if_sisreg.h | 30 +++++++++++++++---------------
 2 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 4ad3371c10e..151a0f2748b 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -259,7 +259,7 @@ static void
 sis_eeprom_getword(struct sis_softc *sc, int addr, uint16_t *dest)
 {
 	int		i;
-	u_int16_t		word = 0;
+	uint16_t	word = 0;
 
 	/* Force EEPROM to idle state. */
 	sis_eeprom_idle(sc);
@@ -302,11 +302,11 @@ static void
 sis_read_eeprom(struct sis_softc *sc, caddr_t dest, int off, int cnt, int swap)
 {
 	int			i;
-	u_int16_t		word = 0, *ptr;
+	uint16_t		word = 0, *ptr;
 
 	for (i = 0; i < cnt; i++) {
 		sis_eeprom_getword(sc, off + i, &word);
-		ptr = (u_int16_t *)(dest + (i * 2));
+		ptr = (uint16_t *)(dest + (i * 2));
 		if (swap)
 			*ptr = ntohs(word);
 		else
@@ -356,7 +356,7 @@ static void
 sis_read_cmos(struct sis_softc *sc, device_t dev, caddr_t dest, int off, int cnt)
 {
 	device_t		bridge;
-	u_int8_t		reg;
+	uint8_t			reg;
 	int			i;
 	bus_space_tag_t		btag;
 
@@ -384,7 +384,7 @@ sis_read_cmos(struct sis_softc *sc, device_t dev, caddr_t dest, int off, int cnt
 static void
 sis_read_mac(struct sis_softc *sc, device_t dev, caddr_t dest)
 {
-	u_int32_t		filtsave, csrsave;
+	uint32_t		filtsave, csrsave;
 
 	filtsave = CSR_READ_4(sc, SIS_RXFILT_CTL);
 	csrsave = CSR_READ_4(sc, SIS_CSR);
@@ -395,11 +395,11 @@ sis_read_mac(struct sis_softc *sc, device_t dev, caddr_t dest)
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, filtsave & ~SIS_RXFILTCTL_ENABLE);
 
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR0);
-	((u_int16_t *)dest)[0] = CSR_READ_2(sc, SIS_RXFILT_DATA);
+	((uint16_t *)dest)[0] = CSR_READ_2(sc, SIS_RXFILT_DATA);
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL,SIS_FILTADDR_PAR1);
-	((u_int16_t *)dest)[1] = CSR_READ_2(sc, SIS_RXFILT_DATA);
+	((uint16_t *)dest)[1] = CSR_READ_2(sc, SIS_RXFILT_DATA);
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR2);
-	((u_int16_t *)dest)[2] = CSR_READ_2(sc, SIS_RXFILT_DATA);
+	((uint16_t *)dest)[2] = CSR_READ_2(sc, SIS_RXFILT_DATA);
 
 	CSR_WRITE_4(sc, SIS_RXFILT_CTL, filtsave);
 	CSR_WRITE_4(sc, SIS_CSR, csrsave);
@@ -731,7 +731,7 @@ sis_setmulti_ns(struct sis_softc *sc)
 {
 	struct ifnet		*ifp;
 	struct ifmultiaddr	*ifma;
-	u_int32_t		h = 0, i, filtsave;
+	uint32_t		h = 0, i, filtsave;
 	int			bit, index;
 
 	ifp = sc->sis_ifp;
@@ -780,8 +780,8 @@ sis_setmulti_sis(struct sis_softc *sc)
 {
 	struct ifnet		*ifp;
 	struct ifmultiaddr	*ifma;
-	u_int32_t		h, i, n, ctl;
-	u_int16_t		hashes[16];
+	uint32_t		h, i, n, ctl;
+	uint16_t		hashes[16];
 
 	ifp = sc->sis_ifp;
 
@@ -963,7 +963,7 @@ sis_attach(device_t dev)
 		 * Why? Who the hell knows.
 		 */
 		{
-			u_int16_t		tmp[4];
+			uint16_t		tmp[4];
 
 			sis_read_eeprom(sc, (caddr_t)&tmp,
 			    NS_EE_NODEADDR, 4, 0);
@@ -1661,7 +1661,7 @@ sis_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
 		sis_startl(ifp);
 
 	if (sc->rxcycles > 0 || cmd == POLL_AND_CHECK_STATUS) {
-		u_int32_t	status;
+		uint32_t	status;
 
 		/* Reading the ISR register clears all interrupts. */
 		status = CSR_READ_4(sc, SIS_ISR);
@@ -1688,7 +1688,7 @@ sis_intr(void *arg)
 {
 	struct sis_softc	*sc;
 	struct ifnet		*ifp;
-	u_int32_t		status;
+	uint32_t		status;
 
 	sc = arg;
 	ifp = sc->sis_ifp;
@@ -1926,23 +1926,23 @@ sis_initl(struct sis_softc *sc)
 	if (sc->sis_type == SIS_TYPE_83815) {
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, NS_FILTADDR_PAR0);
 		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((u_int16_t *)IF_LLADDR(sc->sis_ifp))[0]);
+		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[0]);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, NS_FILTADDR_PAR1);
 		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((u_int16_t *)IF_LLADDR(sc->sis_ifp))[1]);
+		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[1]);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, NS_FILTADDR_PAR2);
 		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((u_int16_t *)IF_LLADDR(sc->sis_ifp))[2]);
+		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[2]);
 	} else {
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR0);
 		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((u_int16_t *)IF_LLADDR(sc->sis_ifp))[0]);
+		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[0]);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR1);
 		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((u_int16_t *)IF_LLADDR(sc->sis_ifp))[1]);
+		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[1]);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR2);
 		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((u_int16_t *)IF_LLADDR(sc->sis_ifp))[2]);
+		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[2]);
 	}
 
 	/* Init circular TX/RX lists. */
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 2f233044e16..69830d79618 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -308,9 +308,9 @@
  */
 struct sis_desc {
 	/* SiS hardware descriptor section */
-	u_int32_t		sis_next;
-	u_int32_t		sis_cmdsts;
-	u_int32_t		sis_ptr;
+	uint32_t		sis_next;
+	uint32_t		sis_cmdsts;
+	uint32_t		sis_ptr;
 };
 
 #define SIS_CMDSTS_BUFLEN	0x00000FFF
@@ -403,18 +403,18 @@ struct sis_desc {
 #define NS_DEVICEID_DP83815	0x0020
 
 struct sis_type {
-	u_int16_t		sis_vid;
-	u_int16_t		sis_did;
+	uint16_t		sis_vid;
+	uint16_t		sis_did;
 	char			*sis_name;
 };
 
 struct sis_mii_frame {
-	u_int8_t		mii_stdelim;
-	u_int8_t		mii_opcode;
-	u_int8_t		mii_phyaddr;
-	u_int8_t		mii_regaddr;
-	u_int8_t		mii_turnaround;
-	u_int16_t		mii_data;
+	uint8_t			mii_stdelim;
+	uint8_t			mii_opcode;
+	uint8_t			mii_phyaddr;
+	uint8_t			mii_regaddr;
+	uint8_t			mii_turnaround;
+	uint16_t		mii_data;
 };
 
 /*
@@ -447,10 +447,10 @@ struct sis_softc {
 	void			*sis_intrhand;
 	device_t		sis_dev;
 	device_t		sis_miibus;
-	u_int8_t		sis_type;
-	u_int8_t		sis_rev;
-	u_int8_t		sis_link;
-	u_int			sis_srr;
+	uint8_t			sis_type;
+	uint8_t			sis_rev;
+	uint8_t			sis_link;
+	uint32_t		sis_srr;
 	struct sis_desc		*sis_rx_list;
 	struct sis_desc		*sis_tx_list;
 	bus_dma_tag_t		sis_rx_list_tag;

From 0f7a0ebd59563feb711e719288448cac130c6ed5 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Wed, 1 Sep 2010 20:32:47 +0000
Subject: [PATCH 0429/1624] Fix a bug with sched_affinity() where it checks
 td_pinned of another thread in a racy manner, which can lead to attempting to
 migrate a thread that is pinned to a CPU.  Instead, have sched_switch()
 determine which CPU a thread should run on if the current one is not allowed.

KASSERT in sched_bind() that the thread is not yet pinned to a CPU.

KASSERT in sched_switch() that only migratable threads or those moving
due to a sched_bind() are changing CPUs.

sched_affinity code came from jhb@.

MFC after:	2 weeks
---
 sys/kern/sched_ule.c | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)

diff --git a/sys/kern/sched_ule.c b/sys/kern/sched_ule.c
index 0a1f7b9f80b..8e4a7babc1c 100644
--- a/sys/kern/sched_ule.c
+++ b/sys/kern/sched_ule.c
@@ -1797,10 +1797,16 @@ sched_switch(struct thread *td, struct thread *newtd, int flags)
 		srqflag = (flags & SW_PREEMPT) ?
 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
 		    SRQ_OURSELF|SRQ_YIELDING;
+		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
+			ts->ts_cpu = sched_pickcpu(td, 0);
 		if (ts->ts_cpu == cpuid)
 			tdq_runq_add(tdq, td, srqflag);
-		else
+		else {
+			KASSERT(THREAD_CAN_MIGRATE(td) ||
+			    (ts->ts_flags & TSF_BOUND) != 0,
+			    ("Thread %p shouldn't migrate", td));
 			mtx = sched_switch_migrate(tdq, td, srqflag);
+		}
 	} else {
 		/* This thread must be going to sleep. */
 		TDQ_LOCK(tdq);
@@ -2383,7 +2389,6 @@ sched_affinity(struct thread *td)
 {
 #ifdef SMP
 	struct td_sched *ts;
-	int cpu;
 
 	THREAD_LOCK_ASSERT(td, MA_OWNED);
 	ts = td->td_sched;
@@ -2397,17 +2402,13 @@ sched_affinity(struct thread *td)
 	if (!TD_IS_RUNNING(td))
 		return;
 	td->td_flags |= TDF_NEEDRESCHED;
-	if (!THREAD_CAN_MIGRATE(td))
-		return;
 	/*
-	 * Assign the new cpu and force a switch before returning to
-	 * userspace.  If the target thread is not running locally send
-	 * an ipi to force the issue.
+	 * Force a switch before returning to userspace.  If the
+	 * target thread is not running locally send an ipi to force
+	 * the issue.
 	 */
-	cpu = ts->ts_cpu;
-	ts->ts_cpu = sched_pickcpu(td, 0);
-	if (cpu != PCPU_GET(cpuid))
-		ipi_cpu(cpu, IPI_PREEMPT);
+	if (td != curthread)
+		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
 #endif
 }
 
@@ -2424,6 +2425,7 @@ sched_bind(struct thread *td, int cpu)
 	ts = td->td_sched;
 	if (ts->ts_flags & TSF_BOUND)
 		sched_unbind(td);
+	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
 	ts->ts_flags |= TSF_BOUND;
 	sched_pin();
 	if (PCPU_GET(cpuid) == cpu)

From d7b57e79e59f8f1e869ab60a4a85585497c2bca0 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 21:42:19 +0000
Subject: [PATCH 0430/1624] Overhaul link state change handling. Previously
 sis(4) blindly configured TX/RX MACs before getting a valid link. After that,
 when link state change callback is called, it called device initialization
 again to reconfigure TX/RX MACs depending on resolved link state. This hack
 created several bad side effects and it required more hacks to not collide
 with sis_tick callback as well as disabling switching to currently selected
 media in device initialization. Also it seems sis(4) was used to be a
 template driver for long time so other drivers which was modeled after sis(4)
 also should be changed.

TX/RX MACs are now reconfigured after getting a valid link. Fix for
short cable error is also applied after getting a link because it's
only valid when the resolved speed is 100Mbps.

While I'm here slightly reorganize interrupt handler such that
sis(4) always read SIS_ISR register to see whether the interrupt is
ours or not. This change removes another hack and make it possible
to nuke sis_stopped variable in softc.
---
 sys/dev/sis/if_sis.c    | 186 +++++++++++++++++++++-------------------
 sys/dev/sis/if_sisreg.h |   2 -
 2 files changed, 100 insertions(+), 88 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 151a0f2748b..54c81166589 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -697,10 +697,86 @@ static void
 sis_miibus_statchg(device_t dev)
 {
 	struct sis_softc	*sc;
+	struct mii_data		*mii;
+	struct ifnet		*ifp;
+	uint32_t		reg;
 
 	sc = device_get_softc(dev);
 	SIS_LOCK_ASSERT(sc);
-	sis_initl(sc);
+
+	mii = device_get_softc(sc->sis_miibus);
+	ifp = sc->sis_ifp;
+	if (mii == NULL || ifp == NULL ||
+	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
+		return;
+
+	sc->sis_link = 0;
+	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
+	    (IFM_ACTIVE | IFM_AVALID)) {
+		switch (IFM_SUBTYPE(mii->mii_media_active)) {
+		case IFM_10_T:
+			sc->sis_link++;
+			CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_10);
+			break;
+		case IFM_100_TX:
+			sc->sis_link++;
+			CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_100);
+			break;
+		default:
+			break;
+		}
+	}
+
+	if (sc->sis_link == 0) {
+		/*
+		 * Stopping MACs seem to reset SIS_TX_LISTPTR and
+		 * SIS_RX_LISTPTR which in turn requires resetting
+		 * TX/RX buffers.  So just don't do anything for
+		 * lost link.
+		 */
+		return;
+	}
+
+	/* Set full/half duplex mode. */
+	if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) {
+		SIS_SETBIT(sc, SIS_TX_CFG,
+		    (SIS_TXCFG_IGN_HBEAT | SIS_TXCFG_IGN_CARR));
+		SIS_SETBIT(sc, SIS_RX_CFG, SIS_RXCFG_RX_TXPKTS);
+	} else {
+		SIS_CLRBIT(sc, SIS_TX_CFG,
+		    (SIS_TXCFG_IGN_HBEAT | SIS_TXCFG_IGN_CARR));
+		SIS_CLRBIT(sc, SIS_RX_CFG, SIS_RXCFG_RX_TXPKTS);
+	}
+
+	if (sc->sis_type == SIS_TYPE_83816) {
+		/*
+		 * MPII03.D: Half Duplex Excessive Collisions.
+		 * Also page 49 in 83816 manual
+		 */
+		SIS_SETBIT(sc, SIS_TX_CFG, SIS_TXCFG_MPII03D);
+	}
+
+	if (sc->sis_type == SIS_TYPE_83815 && sc->sis_srr < NS_SRR_16A &&
+	    IFM_SUBTYPE(mii->mii_media_active) == IFM_100_TX) {
+		/*
+		 * Short Cable Receive Errors (MP21.E)
+		 */
+		CSR_WRITE_4(sc, NS_PHY_PAGE, 0x0001);
+		reg = CSR_READ_4(sc, NS_PHY_DSPCFG) & 0xfff;
+		CSR_WRITE_4(sc, NS_PHY_DSPCFG, reg | 0x1000);
+		DELAY(100);
+		reg = CSR_READ_4(sc, NS_PHY_TDATA) & 0xff;
+		if ((reg & 0x0080) == 0 || (reg > 0xd8 && reg <= 0xff)) {
+			device_printf(sc->sis_dev,
+			    "Applying short cable fix (reg=%x)\n", reg);
+			CSR_WRITE_4(sc, NS_PHY_TDATA, 0x00e8);
+			SIS_SETBIT(sc, NS_PHY_DSPCFG, 0x20);
+		}
+		CSR_WRITE_4(sc, NS_PHY_PAGE, 0);
+	}
+	/* Enable TX/RX MACs. */
+	SIS_CLRBIT(sc, SIS_CSR, SIS_CSR_TX_DISABLE | SIS_CSR_RX_DISABLE);
+	SIS_SETBIT(sc, SIS_CSR, SIS_CSR_TX_ENABLE | SIS_CSR_RX_ENABLE);
 }
 
 static uint32_t
@@ -1613,23 +1689,14 @@ sis_tick(void *xsc)
 
 	sc = xsc;
 	SIS_LOCK_ASSERT(sc);
-	sc->in_tick = 1;
 	ifp = sc->sis_ifp;
 
 	mii = device_get_softc(sc->sis_miibus);
 	mii_tick(mii);
-
 	sis_watchdog(sc);
-
-	if (!sc->sis_link && mii->mii_media_status & IFM_ACTIVE &&
-	    IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) {
-		sc->sis_link++;
-		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
-			sis_startl(ifp);
-	}
-
+	if (sc->sis_link == 0)
+		sis_miibus_statchg(sc->sis_dev);
 	callout_reset(&sc->sis_stat_ch, hz,  sis_tick, sc);
-	sc->in_tick = 0;
 }
 
 #ifdef DEVICE_POLLING
@@ -1693,9 +1760,6 @@ sis_intr(void *arg)
 	sc = arg;
 	ifp = sc->sis_ifp;
 
-	if (sc->sis_stopped)	/* Most likely shared interrupt */
-		return;
-
 	SIS_LOCK(sc);
 #ifdef DEVICE_POLLING
 	if (ifp->if_capenable & IFCAP_POLLING) {
@@ -1704,17 +1768,17 @@ sis_intr(void *arg)
 	}
 #endif
 
+	/* Reading the ISR register clears all interrupts. */
+	status = CSR_READ_4(sc, SIS_ISR);
+	if ((status & SIS_INTRS) == 0) {
+		/* Not ours. */
+		SIS_UNLOCK(sc);
+	}
+
 	/* Disable interrupts. */
 	CSR_WRITE_4(sc, SIS_IER, 0);
 
-	for (;;) {
-		SIS_LOCK_ASSERT(sc);
-		/* Reading the ISR register clears all interrupts. */
-		status = CSR_READ_4(sc, SIS_ISR);
-
-		if ((status & SIS_INTRS) == 0)
-			break;
-
+	for (;(status & SIS_INTRS) != 0;) {
 		if (status &
 		    (SIS_ISR_TX_DESC_OK | SIS_ISR_TX_ERR |
 		    SIS_ISR_TX_OK | SIS_ISR_TX_IDLE) )
@@ -1733,7 +1797,10 @@ sis_intr(void *arg)
 		if (status & SIS_ISR_SYSERR) {
 			sis_reset(sc);
 			sis_initl(sc);
+			SIS_UNLOCK(sc);
+			return;
 		}
+		status = CSR_READ_4(sc, SIS_ISR);
 	}
 
 	/* Re-enable interrupts. */
@@ -1908,7 +1975,6 @@ sis_initl(struct sis_softc *sc)
 	 * Cancel pending I/O and free all RX/TX buffers.
 	 */
 	sis_stop(sc);
-	sc->sis_stopped = 0;
 
 #ifdef notyet
 	if (sc->sis_type == SIS_TYPE_83815 && sc->sis_srr >= NS_SRR_16A) {
@@ -1972,7 +2038,6 @@ sis_initl(struct sis_softc *sc)
 		CSR_WRITE_4(sc, NS_PHY_PAGE, 0);
 	}
 
-
 	/*
 	 * For the NatSemi chip, we have to explicitly enable the
 	 * reception of ARP frames, as well as turn on the 'perfect
@@ -2030,52 +2095,11 @@ sis_initl(struct sis_softc *sc)
 	/* Accept Long Packets for VLAN support */
 	SIS_SETBIT(sc, SIS_RX_CFG, SIS_RXCFG_RX_JABBER);
 
-	/* Set TX configuration */
-	if (IFM_SUBTYPE(mii->mii_media_active) == IFM_10_T) {
-		CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_10);
-	} else {
-		CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_100);
-	}
-
-	/* Set full/half duplex mode. */
-	if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) {
-		SIS_SETBIT(sc, SIS_TX_CFG,
-		    (SIS_TXCFG_IGN_HBEAT|SIS_TXCFG_IGN_CARR));
-		SIS_SETBIT(sc, SIS_RX_CFG, SIS_RXCFG_RX_TXPKTS);
-	} else {
-		SIS_CLRBIT(sc, SIS_TX_CFG,
-		    (SIS_TXCFG_IGN_HBEAT|SIS_TXCFG_IGN_CARR));
-		SIS_CLRBIT(sc, SIS_RX_CFG, SIS_RXCFG_RX_TXPKTS);
-	}
-
-	if (sc->sis_type == SIS_TYPE_83816) {
-		/*
-		 * MPII03.D: Half Duplex Excessive Collisions.
-		 * Also page 49 in 83816 manual
-		 */
-		SIS_SETBIT(sc, SIS_TX_CFG, SIS_TXCFG_MPII03D);
-	}
-
-	if (sc->sis_type == SIS_TYPE_83815 && sc->sis_srr < NS_SRR_16A &&
-	    IFM_SUBTYPE(mii->mii_media_active) == IFM_100_TX) {
-		uint32_t reg;
-
-		/*
-		 * Short Cable Receive Errors (MP21.E)
-		 */
-		CSR_WRITE_4(sc, NS_PHY_PAGE, 0x0001);
-		reg = CSR_READ_4(sc, NS_PHY_DSPCFG) & 0xfff;
-		CSR_WRITE_4(sc, NS_PHY_DSPCFG, reg | 0x1000);
-		DELAY(100);
-		reg = CSR_READ_4(sc, NS_PHY_TDATA) & 0xff;
-		if ((reg & 0x0080) == 0 || (reg > 0xd8 && reg <= 0xff)) {
-			device_printf(sc->sis_dev,
-			    "Applying short cable fix (reg=%x)\n", reg);
-			CSR_WRITE_4(sc, NS_PHY_TDATA, 0x00e8);
-			SIS_SETBIT(sc, NS_PHY_DSPCFG, 0x20);
-		}
-		CSR_WRITE_4(sc, NS_PHY_PAGE, 0);
-	}
+	/*
+	 * Assume 100Mbps link, actual MAC configuration is done
+	 * after getting a valid link.
+	 */
+	CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_100);
 
 	/*
 	 * Enable interrupts.
@@ -2092,19 +2116,16 @@ sis_initl(struct sis_softc *sc)
 #endif
 	CSR_WRITE_4(sc, SIS_IER, 1);
 
-	/* Enable receiver and transmitter. */
-	SIS_CLRBIT(sc, SIS_CSR, SIS_CSR_TX_DISABLE|SIS_CSR_RX_DISABLE);
-	SIS_SETBIT(sc, SIS_CSR, SIS_CSR_RX_ENABLE);
+	/* Clear MAC disable. */
+	SIS_CLRBIT(sc, SIS_CSR, SIS_CSR_TX_DISABLE | SIS_CSR_RX_DISABLE);
 
-#ifdef notdef
+	sc->sis_link = 0;
 	mii_mediachg(mii);
-#endif
 
 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
 
-	if (!sc->in_tick)
-		callout_reset(&sc->sis_stat_ch, hz,  sis_tick, sc);
+	callout_reset(&sc->sis_stat_ch, hz,  sis_tick, sc);
 }
 
 /*
@@ -2226,10 +2247,6 @@ sis_watchdog(struct sis_softc *sc)
 {
 
 	SIS_LOCK_ASSERT(sc);
-	if (sc->sis_stopped) {
-		SIS_UNLOCK(sc);
-		return;
-	}
 
 	if (sc->sis_watchdog_timer == 0 || --sc->sis_watchdog_timer >0)
 		return;
@@ -2257,9 +2274,8 @@ sis_stop(struct sis_softc *sc)
 	struct sis_txdesc *txd;
 	int i;
 
-	if (sc->sis_stopped)
-		return;
 	SIS_LOCK_ASSERT(sc);
+
 	ifp = sc->sis_ifp;
 	sc->sis_watchdog_timer = 0;
 
@@ -2303,8 +2319,6 @@ sis_stop(struct sis_softc *sc)
 			txd->tx_m = NULL;
 		}
 	}
-
-	sc->sis_stopped = 1;
 }
 
 /*
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 69830d79618..9e08a1b8f92 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -471,11 +471,9 @@ struct sis_softc {
 	bus_addr_t		sis_tx_paddr;
 	struct callout		sis_stat_ch;
 	int			sis_watchdog_timer;
-	int			sis_stopped;
 #ifdef DEVICE_POLLING
 	int			rxcycles;
 #endif
-	int			in_tick;
 	struct mtx		sis_mtx;
 };
 

From fc58ee15ff7aba740ba7546cb74cc867919752cf Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 21:44:36 +0000
Subject: [PATCH 0431/1624] Report result of link state change to caller.
 Previously it always returned success.

---
 sys/dev/sis/if_sis.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 54c81166589..3a8b352001a 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -2136,6 +2136,7 @@ sis_ifmedia_upd(struct ifnet *ifp)
 {
 	struct sis_softc	*sc;
 	struct mii_data		*mii;
+	int			error;
 
 	sc = ifp->if_softc;
 
@@ -2147,10 +2148,10 @@ sis_ifmedia_upd(struct ifnet *ifp)
 		LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
 			mii_phy_reset(miisc);
 	}
-	mii_mediachg(mii);
+	error = mii_mediachg(mii);
 	SIS_UNLOCK(sc);
 
-	return (0);
+	return (error);
 }
 
 /*

From ae9e8d4935b6193d752d083057791ba856d04ed2 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 22:08:23 +0000
Subject: [PATCH 0432/1624] Do not reinitialize controller whenever promiscuous
 mode or allmulti is toggled. Controller does not require reinitialization.
 This removes unnecessary controller reinitialization whenever tcpdump is
 used. While I'm here remove unnecessary variable reinitialization.

---
 sys/dev/sis/if_sis.c    | 12 ++++++++++--
 sys/dev/sis/if_sisreg.h |  1 +
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 3a8b352001a..cecffe2f32f 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -2185,10 +2185,19 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 	case SIOCSIFFLAGS:
 		SIS_LOCK(sc);
 		if (ifp->if_flags & IFF_UP) {
-			sis_initl(sc);
+			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0 &&
+			    ((ifp->if_flags ^ sc->sis_if_flags) &
+			    (IFF_PROMISC | IFF_ALLMULTI)) != 0) {
+				if (sc->sis_type == SIS_TYPE_83815)
+					sis_setmulti_ns(sc);
+				else
+					sis_setmulti_sis(sc);
+			} else
+				sis_initl(sc);
 		} else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
 			sis_stop(sc);
 		}
+		sc->sis_if_flags = ifp->if_flags;
 		SIS_UNLOCK(sc);
 		error = 0;
 		break;
@@ -2200,7 +2209,6 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 		else
 			sis_setmulti_sis(sc);
 		SIS_UNLOCK(sc);
-		error = 0;
 		break;
 	case SIOCGIFMEDIA:
 	case SIOCSIFMEDIA:
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 9e08a1b8f92..5bcdcae03e0 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -471,6 +471,7 @@ struct sis_softc {
 	bus_addr_t		sis_tx_paddr;
 	struct callout		sis_stat_ch;
 	int			sis_watchdog_timer;
+	int			sis_if_flags;
 #ifdef DEVICE_POLLING
 	int			rxcycles;
 #endif

From d199ef7e0d935d1ee6e6b3a23f4157e47021d714 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 22:16:25 +0000
Subject: [PATCH 0433/1624] Avoid controller reinitialization which could be
 triggered by dhclient(8) or alias addresses are added.

PR:	kern/87506
---
 sys/dev/sis/if_sis.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index cecffe2f32f..6e9b8dbcc20 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -1741,6 +1741,7 @@ sis_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
 
 		if (status & SIS_ISR_SYSERR) {
 			sis_reset(sc);
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			sis_initl(sc);
 		}
 	}
@@ -1796,6 +1797,7 @@ sis_intr(void *arg)
 
 		if (status & SIS_ISR_SYSERR) {
 			sis_reset(sc);
+			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			sis_initl(sc);
 			SIS_UNLOCK(sc);
 			return;
@@ -1971,6 +1973,9 @@ sis_initl(struct sis_softc *sc)
 
 	SIS_LOCK_ASSERT(sc);
 
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+		return;
+
 	/*
 	 * Cancel pending I/O and free all RX/TX buffers.
 	 */

From 7723fa2e04d8403a075a1764300cb2e5a694799b Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 1 Sep 2010 22:50:11 +0000
Subject: [PATCH 0434/1624] Move sis_reset() to sis_initl(). This ensures
 driver starts with known good state of controller.

---
 sys/dev/sis/if_sis.c | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 6e9b8dbcc20..8886617eb66 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -1205,7 +1205,6 @@ sis_detach(device_t dev)
 	/* These should only be active if attach succeeded. */
 	if (device_is_attached(dev)) {
 		SIS_LOCK(sc);
-		sis_reset(sc);
 		sis_stop(sc);
 		SIS_UNLOCK(sc);
 		callout_drain(&sc->sis_stat_ch);
@@ -1740,7 +1739,6 @@ sis_poll(struct ifnet *ifp, enum poll_cmd cmd, int count)
 			SIS_SETBIT(sc, SIS_CSR, SIS_CSR_RX_ENABLE);
 
 		if (status & SIS_ISR_SYSERR) {
-			sis_reset(sc);
 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			sis_initl(sc);
 		}
@@ -1796,7 +1794,6 @@ sis_intr(void *arg)
 			SIS_SETBIT(sc, SIS_CSR, SIS_CSR_RX_ENABLE);
 
 		if (status & SIS_ISR_SYSERR) {
-			sis_reset(sc);
 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 			sis_initl(sc);
 			SIS_UNLOCK(sc);
@@ -1980,7 +1977,10 @@ sis_initl(struct sis_softc *sc)
 	 * Cancel pending I/O and free all RX/TX buffers.
 	 */
 	sis_stop(sc);
-
+	/*
+	 * Reset the chip to a known state.
+	 */
+	sis_reset(sc);
 #ifdef notyet
 	if (sc->sis_type == SIS_TYPE_83815 && sc->sis_srr >= NS_SRR_16A) {
 		/*
@@ -2268,8 +2268,7 @@ sis_watchdog(struct sis_softc *sc)
 	device_printf(sc->sis_dev, "watchdog timeout\n");
 	sc->sis_ifp->if_oerrors++;
 
-	sis_stop(sc);
-	sis_reset(sc);
+	sc->sis_ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 	sis_initl(sc);
 
 	if (!IFQ_DRV_IS_EMPTY(&sc->sis_ifp->if_snd))
@@ -2346,7 +2345,6 @@ sis_shutdown(device_t dev)
 
 	sc = device_get_softc(dev);
 	SIS_LOCK(sc);
-	sis_reset(sc);
 	sis_stop(sc);
 	SIS_UNLOCK(sc);
 	return (0);

From 910cb8feb94f25e1ad5446f771445c2a3f97a845 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Wed, 1 Sep 2010 23:47:53 +0000
Subject: [PATCH 0435/1624] Add missing MODULE_VERSION() definitions, this
 resolves problems around duplicate module loads.

PR:		usb/125736
Submitted by:	danger, mm
Reviewed by:	hselasky
---
 sys/dev/if_ndis/if_ndis_usb.c  | 1 +
 sys/dev/usb/input/atp.c        | 1 +
 sys/dev/usb/input/uep.c        | 1 +
 sys/dev/usb/input/uhid.c       | 1 +
 sys/dev/usb/input/ukbd.c       | 1 +
 sys/dev/usb/input/ums.c        | 1 +
 sys/dev/usb/misc/udbp.c        | 1 +
 sys/dev/usb/misc/ufm.c         | 1 +
 sys/dev/usb/net/if_aue.c       | 1 +
 sys/dev/usb/net/if_axe.c       | 1 +
 sys/dev/usb/net/if_cue.c       | 1 +
 sys/dev/usb/net/if_kue.c       | 1 +
 sys/dev/usb/net/if_rue.c       | 1 +
 sys/dev/usb/net/if_udav.c      | 1 +
 sys/dev/usb/serial/u3g.c       | 1 +
 sys/dev/usb/serial/uark.c      | 1 +
 sys/dev/usb/serial/ubsa.c      | 1 +
 sys/dev/usb/serial/ubser.c     | 1 +
 sys/dev/usb/serial/uchcom.c    | 1 +
 sys/dev/usb/serial/ucycom.c    | 1 +
 sys/dev/usb/serial/ufoma.c     | 1 +
 sys/dev/usb/serial/uftdi.c     | 1 +
 sys/dev/usb/serial/ugensa.c    | 1 +
 sys/dev/usb/serial/uipaq.c     | 1 +
 sys/dev/usb/serial/ulpt.c      | 1 +
 sys/dev/usb/serial/umct.c      | 1 +
 sys/dev/usb/serial/umoscom.c   | 1 +
 sys/dev/usb/serial/uvisor.c    | 1 +
 sys/dev/usb/storage/umass.c    | 1 +
 sys/dev/usb/storage/urio.c     | 1 +
 sys/dev/usb/usb_compat_linux.c | 1 +
 sys/dev/usb/usb_hub.c          | 1 +
 sys/dev/usb/wlan/if_rum.c      | 6 +++---
 sys/dev/usb/wlan/if_run.c      | 8 ++++----
 sys/dev/usb/wlan/if_uath.c     | 1 +
 sys/dev/usb/wlan/if_ural.c     | 1 +
 sys/dev/usb/wlan/if_urtw.c     | 1 +
 sys/dev/usb/wlan/if_zyd.c      | 1 +
 38 files changed, 43 insertions(+), 7 deletions(-)

diff --git a/sys/dev/if_ndis/if_ndis_usb.c b/sys/dev/if_ndis/if_ndis_usb.c
index b872f9ac52a..9aa717089f1 100644
--- a/sys/dev/if_ndis/if_ndis_usb.c
+++ b/sys/dev/if_ndis/if_ndis_usb.c
@@ -107,6 +107,7 @@ static driver_t ndis_driver = {
 static devclass_t ndis_devclass;
 
 DRIVER_MODULE(ndis, uhub, ndis_driver, ndis_devclass, ndisdrv_modevent, 0);
+MODULE_VERSION(ndis, 1);
 
 static int
 ndisusb_devcompare(interface_type bustype, struct ndis_usb_type *t, device_t dev)
diff --git a/sys/dev/usb/input/atp.c b/sys/dev/usb/input/atp.c
index c0fe6d4b386..1ec6f27b377 100644
--- a/sys/dev/usb/input/atp.c
+++ b/sys/dev/usb/input/atp.c
@@ -2222,3 +2222,4 @@ static devclass_t atp_devclass;
 
 DRIVER_MODULE(atp, uhub, atp_driver, atp_devclass, NULL, 0);
 MODULE_DEPEND(atp, usb, 1, 1, 1);
+MODULE_VERSION(atp, 1);
diff --git a/sys/dev/usb/input/uep.c b/sys/dev/usb/input/uep.c
index 27dec1ff271..048452d84b1 100644
--- a/sys/dev/usb/input/uep.c
+++ b/sys/dev/usb/input/uep.c
@@ -439,3 +439,4 @@ static driver_t uep_driver = {
 
 DRIVER_MODULE(uep, uhub, uep_driver, uep_devclass, NULL, NULL);
 MODULE_DEPEND(uep, usb, 1, 1, 1);
+MODULE_VERSION(uep, 1);
diff --git a/sys/dev/usb/input/uhid.c b/sys/dev/usb/input/uhid.c
index d36ecf36240..5575bdf6b07 100644
--- a/sys/dev/usb/input/uhid.c
+++ b/sys/dev/usb/input/uhid.c
@@ -801,3 +801,4 @@ static driver_t uhid_driver = {
 
 DRIVER_MODULE(uhid, uhub, uhid_driver, uhid_devclass, NULL, 0);
 MODULE_DEPEND(uhid, usb, 1, 1, 1);
+MODULE_VERSION(uhid, 1);
diff --git a/sys/dev/usb/input/ukbd.c b/sys/dev/usb/input/ukbd.c
index 034a781b2fe..5101a351292 100644
--- a/sys/dev/usb/input/ukbd.c
+++ b/sys/dev/usb/input/ukbd.c
@@ -1887,3 +1887,4 @@ static driver_t ukbd_driver = {
 
 DRIVER_MODULE(ukbd, uhub, ukbd_driver, ukbd_devclass, ukbd_driver_load, 0);
 MODULE_DEPEND(ukbd, usb, 1, 1, 1);
+MODULE_VERSION(ukbd, 1);
diff --git a/sys/dev/usb/input/ums.c b/sys/dev/usb/input/ums.c
index a41ddaaaf52..7a2d053763b 100644
--- a/sys/dev/usb/input/ums.c
+++ b/sys/dev/usb/input/ums.c
@@ -1010,3 +1010,4 @@ static driver_t ums_driver = {
 
 DRIVER_MODULE(ums, uhub, ums_driver, ums_devclass, NULL, 0);
 MODULE_DEPEND(ums, usb, 1, 1, 1);
+MODULE_VERSION(ums, 1);
diff --git a/sys/dev/usb/misc/udbp.c b/sys/dev/usb/misc/udbp.c
index 5eef3103c31..7e3a4b1c8eb 100644
--- a/sys/dev/usb/misc/udbp.c
+++ b/sys/dev/usb/misc/udbp.c
@@ -261,6 +261,7 @@ static driver_t udbp_driver = {
 DRIVER_MODULE(udbp, uhub, udbp_driver, udbp_devclass, udbp_modload, 0);
 MODULE_DEPEND(udbp, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
 MODULE_DEPEND(udbp, usb, 1, 1, 1);
+MODULE_VERSION(udbp, 1);
 
 static int
 udbp_modload(module_t mod, int event, void *data)
diff --git a/sys/dev/usb/misc/ufm.c b/sys/dev/usb/misc/ufm.c
index 136182a1c3e..5889dafe959 100644
--- a/sys/dev/usb/misc/ufm.c
+++ b/sys/dev/usb/misc/ufm.c
@@ -117,6 +117,7 @@ static driver_t ufm_driver = {
 
 DRIVER_MODULE(ufm, uhub, ufm_driver, ufm_devclass, NULL, 0);
 MODULE_DEPEND(ufm, usb, 1, 1, 1);
+MODULE_VERSION(ufm, 1);
 
 static int
 ufm_probe(device_t dev)
diff --git a/sys/dev/usb/net/if_aue.c b/sys/dev/usb/net/if_aue.c
index a8c0a548b51..7783b2aeb2a 100644
--- a/sys/dev/usb/net/if_aue.c
+++ b/sys/dev/usb/net/if_aue.c
@@ -281,6 +281,7 @@ MODULE_DEPEND(aue, uether, 1, 1, 1);
 MODULE_DEPEND(aue, usb, 1, 1, 1);
 MODULE_DEPEND(aue, ether, 1, 1, 1);
 MODULE_DEPEND(aue, miibus, 1, 1, 1);
+MODULE_VERSION(aue, 1);
 
 static const struct usb_ether_methods aue_ue_methods = {
 	.ue_attach_post = aue_attach_post,
diff --git a/sys/dev/usb/net/if_axe.c b/sys/dev/usb/net/if_axe.c
index e255c855c94..09f6561e21b 100644
--- a/sys/dev/usb/net/if_axe.c
+++ b/sys/dev/usb/net/if_axe.c
@@ -256,6 +256,7 @@ MODULE_DEPEND(axe, uether, 1, 1, 1);
 MODULE_DEPEND(axe, usb, 1, 1, 1);
 MODULE_DEPEND(axe, ether, 1, 1, 1);
 MODULE_DEPEND(axe, miibus, 1, 1, 1);
+MODULE_VERSION(axe, 1);
 
 static const struct usb_ether_methods axe_ue_methods = {
 	.ue_attach_post = axe_attach_post,
diff --git a/sys/dev/usb/net/if_cue.c b/sys/dev/usb/net/if_cue.c
index e26b29f6fd2..46ccc08f848 100644
--- a/sys/dev/usb/net/if_cue.c
+++ b/sys/dev/usb/net/if_cue.c
@@ -173,6 +173,7 @@ DRIVER_MODULE(cue, uhub, cue_driver, cue_devclass, NULL, 0);
 MODULE_DEPEND(cue, uether, 1, 1, 1);
 MODULE_DEPEND(cue, usb, 1, 1, 1);
 MODULE_DEPEND(cue, ether, 1, 1, 1);
+MODULE_VERSION(cue, 1);
 
 static const struct usb_ether_methods cue_ue_methods = {
 	.ue_attach_post = cue_attach_post,
diff --git a/sys/dev/usb/net/if_kue.c b/sys/dev/usb/net/if_kue.c
index 4eee0945d9f..7c8bf8bb357 100644
--- a/sys/dev/usb/net/if_kue.c
+++ b/sys/dev/usb/net/if_kue.c
@@ -215,6 +215,7 @@ DRIVER_MODULE(kue, uhub, kue_driver, kue_devclass, NULL, 0);
 MODULE_DEPEND(kue, uether, 1, 1, 1);
 MODULE_DEPEND(kue, usb, 1, 1, 1);
 MODULE_DEPEND(kue, ether, 1, 1, 1);
+MODULE_VERSION(kue, 1);
 
 static const struct usb_ether_methods kue_ue_methods = {
 	.ue_attach_post = kue_attach_post,
diff --git a/sys/dev/usb/net/if_rue.c b/sys/dev/usb/net/if_rue.c
index 7741b8d0ecb..75343c8f86e 100644
--- a/sys/dev/usb/net/if_rue.c
+++ b/sys/dev/usb/net/if_rue.c
@@ -213,6 +213,7 @@ MODULE_DEPEND(rue, uether, 1, 1, 1);
 MODULE_DEPEND(rue, usb, 1, 1, 1);
 MODULE_DEPEND(rue, ether, 1, 1, 1);
 MODULE_DEPEND(rue, miibus, 1, 1, 1);
+MODULE_VERSION(rue, 1);
 
 static const struct usb_ether_methods rue_ue_methods = {
 	.ue_attach_post = rue_attach_post,
diff --git a/sys/dev/usb/net/if_udav.c b/sys/dev/usb/net/if_udav.c
index f56e9b03829..bc687b612b3 100644
--- a/sys/dev/usb/net/if_udav.c
+++ b/sys/dev/usb/net/if_udav.c
@@ -172,6 +172,7 @@ MODULE_DEPEND(udav, uether, 1, 1, 1);
 MODULE_DEPEND(udav, usb, 1, 1, 1);
 MODULE_DEPEND(udav, ether, 1, 1, 1);
 MODULE_DEPEND(udav, miibus, 1, 1, 1);
+MODULE_VERSION(udav, 1);
 
 static const struct usb_ether_methods udav_ue_methods = {
 	.ue_attach_post = udav_attach_post,
diff --git a/sys/dev/usb/serial/u3g.c b/sys/dev/usb/serial/u3g.c
index 1b1a13e8a8d..5509a8c5ef9 100644
--- a/sys/dev/usb/serial/u3g.c
+++ b/sys/dev/usb/serial/u3g.c
@@ -178,6 +178,7 @@ static driver_t u3g_driver = {
 DRIVER_MODULE(u3g, uhub, u3g_driver, u3g_devclass, u3g_driver_loaded, 0);
 MODULE_DEPEND(u3g, ucom, 1, 1, 1);
 MODULE_DEPEND(u3g, usb, 1, 1, 1);
+MODULE_VERSION(u3g, 1);
 
 static const struct usb_device_id u3g_devs[] = {
 #define	U3G_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) }
diff --git a/sys/dev/usb/serial/uark.c b/sys/dev/usb/serial/uark.c
index 7dfb0f83f6e..10476c2133e 100644
--- a/sys/dev/usb/serial/uark.c
+++ b/sys/dev/usb/serial/uark.c
@@ -169,6 +169,7 @@ static driver_t uark_driver = {
 DRIVER_MODULE(uark, uhub, uark_driver, uark_devclass, NULL, 0);
 MODULE_DEPEND(uark, ucom, 1, 1, 1);
 MODULE_DEPEND(uark, usb, 1, 1, 1);
+MODULE_VERSION(uark, 1);
 
 static const struct usb_device_id uark_devs[] = {
 	{USB_VPI(USB_VENDOR_ARKMICRO, USB_PRODUCT_ARKMICRO_ARK3116, 0)},
diff --git a/sys/dev/usb/serial/ubsa.c b/sys/dev/usb/serial/ubsa.c
index 58175094922..83ae1c97e1c 100644
--- a/sys/dev/usb/serial/ubsa.c
+++ b/sys/dev/usb/serial/ubsa.c
@@ -277,6 +277,7 @@ static driver_t ubsa_driver = {
 DRIVER_MODULE(ubsa, uhub, ubsa_driver, ubsa_devclass, NULL, 0);
 MODULE_DEPEND(ubsa, ucom, 1, 1, 1);
 MODULE_DEPEND(ubsa, usb, 1, 1, 1);
+MODULE_VERSION(ubsa, 1);
 
 static int
 ubsa_probe(device_t dev)
diff --git a/sys/dev/usb/serial/ubser.c b/sys/dev/usb/serial/ubser.c
index 3f2dc2d30c7..be332c3df5f 100644
--- a/sys/dev/usb/serial/ubser.c
+++ b/sys/dev/usb/serial/ubser.c
@@ -215,6 +215,7 @@ static driver_t ubser_driver = {
 DRIVER_MODULE(ubser, uhub, ubser_driver, ubser_devclass, NULL, 0);
 MODULE_DEPEND(ubser, ucom, 1, 1, 1);
 MODULE_DEPEND(ubser, usb, 1, 1, 1);
+MODULE_VERSION(ubser, 1);
 
 static int
 ubser_probe(device_t dev)
diff --git a/sys/dev/usb/serial/uchcom.c b/sys/dev/usb/serial/uchcom.c
index 92f3a922345..3bcb49f8428 100644
--- a/sys/dev/usb/serial/uchcom.c
+++ b/sys/dev/usb/serial/uchcom.c
@@ -855,3 +855,4 @@ static devclass_t uchcom_devclass;
 DRIVER_MODULE(uchcom, uhub, uchcom_driver, uchcom_devclass, NULL, 0);
 MODULE_DEPEND(uchcom, ucom, 1, 1, 1);
 MODULE_DEPEND(uchcom, usb, 1, 1, 1);
+MODULE_VERSION(uchcom, 1);
diff --git a/sys/dev/usb/serial/ucycom.c b/sys/dev/usb/serial/ucycom.c
index 1cce28eb580..decd03ceabd 100644
--- a/sys/dev/usb/serial/ucycom.c
+++ b/sys/dev/usb/serial/ucycom.c
@@ -176,6 +176,7 @@ static driver_t ucycom_driver = {
 DRIVER_MODULE(ucycom, uhub, ucycom_driver, ucycom_devclass, NULL, 0);
 MODULE_DEPEND(ucycom, ucom, 1, 1, 1);
 MODULE_DEPEND(ucycom, usb, 1, 1, 1);
+MODULE_VERSION(ucycom, 1);
 
 /*
  * Supported devices
diff --git a/sys/dev/usb/serial/ufoma.c b/sys/dev/usb/serial/ufoma.c
index b1a73494945..e7d5a9d5a74 100644
--- a/sys/dev/usb/serial/ufoma.c
+++ b/sys/dev/usb/serial/ufoma.c
@@ -326,6 +326,7 @@ static driver_t ufoma_driver = {
 DRIVER_MODULE(ufoma, uhub, ufoma_driver, ufoma_devclass, NULL, 0);
 MODULE_DEPEND(ufoma, ucom, 1, 1, 1);
 MODULE_DEPEND(ufoma, usb, 1, 1, 1);
+MODULE_VERSION(ufoma, 1);
 
 static int
 ufoma_probe(device_t dev)
diff --git a/sys/dev/usb/serial/uftdi.c b/sys/dev/usb/serial/uftdi.c
index 9b84bcecec8..8cf5a329f36 100644
--- a/sys/dev/usb/serial/uftdi.c
+++ b/sys/dev/usb/serial/uftdi.c
@@ -205,6 +205,7 @@ static driver_t uftdi_driver = {
 DRIVER_MODULE(uftdi, uhub, uftdi_driver, uftdi_devclass, NULL, 0);
 MODULE_DEPEND(uftdi, ucom, 1, 1, 1);
 MODULE_DEPEND(uftdi, usb, 1, 1, 1);
+MODULE_VERSION(uftdi, 1);
 
 static struct usb_device_id uftdi_devs[] = {
 #define	UFTDI_DEV(v,p,t) \
diff --git a/sys/dev/usb/serial/ugensa.c b/sys/dev/usb/serial/ugensa.c
index e80660744a3..dd699863a5b 100644
--- a/sys/dev/usb/serial/ugensa.c
+++ b/sys/dev/usb/serial/ugensa.c
@@ -153,6 +153,7 @@ static driver_t ugensa_driver = {
 DRIVER_MODULE(ugensa, uhub, ugensa_driver, ugensa_devclass, NULL, 0);
 MODULE_DEPEND(ugensa, ucom, 1, 1, 1);
 MODULE_DEPEND(ugensa, usb, 1, 1, 1);
+MODULE_VERSION(ugensa, 1);
 
 static const struct usb_device_id ugensa_devs[] = {
 	{USB_VPI(USB_VENDOR_AIRPRIME, USB_PRODUCT_AIRPRIME_PC5220, 0)},
diff --git a/sys/dev/usb/serial/uipaq.c b/sys/dev/usb/serial/uipaq.c
index 687130910f8..3bc915f985f 100644
--- a/sys/dev/usb/serial/uipaq.c
+++ b/sys/dev/usb/serial/uipaq.c
@@ -1085,6 +1085,7 @@ static driver_t uipaq_driver = {
 DRIVER_MODULE(uipaq, uhub, uipaq_driver, uipaq_devclass, NULL, 0);
 MODULE_DEPEND(uipaq, ucom, 1, 1, 1);
 MODULE_DEPEND(uipaq, usb, 1, 1, 1);
+MODULE_VERSION(uipaq, 1);
 
 static int
 uipaq_probe(device_t dev)
diff --git a/sys/dev/usb/serial/ulpt.c b/sys/dev/usb/serial/ulpt.c
index 58dc367237b..a75eb16b13c 100644
--- a/sys/dev/usb/serial/ulpt.c
+++ b/sys/dev/usb/serial/ulpt.c
@@ -745,3 +745,4 @@ static driver_t ulpt_driver = {
 DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, NULL, 0);
 MODULE_DEPEND(ulpt, usb, 1, 1, 1);
 MODULE_DEPEND(ulpt, ucom, 1, 1, 1);
+MODULE_VERSION(ulpt, 1);
diff --git a/sys/dev/usb/serial/umct.c b/sys/dev/usb/serial/umct.c
index 524f8c4f4c0..d05a9f90154 100644
--- a/sys/dev/usb/serial/umct.c
+++ b/sys/dev/usb/serial/umct.c
@@ -219,6 +219,7 @@ static driver_t umct_driver = {
 DRIVER_MODULE(umct, uhub, umct_driver, umct_devclass, NULL, 0);
 MODULE_DEPEND(umct, ucom, 1, 1, 1);
 MODULE_DEPEND(umct, usb, 1, 1, 1);
+MODULE_VERSION(umct, 1);
 
 static int
 umct_probe(device_t dev)
diff --git a/sys/dev/usb/serial/umoscom.c b/sys/dev/usb/serial/umoscom.c
index 3a36a44f71c..b79290b6879 100644
--- a/sys/dev/usb/serial/umoscom.c
+++ b/sys/dev/usb/serial/umoscom.c
@@ -279,6 +279,7 @@ static driver_t umoscom_driver = {
 DRIVER_MODULE(umoscom, uhub, umoscom_driver, umoscom_devclass, NULL, 0);
 MODULE_DEPEND(umoscom, ucom, 1, 1, 1);
 MODULE_DEPEND(umoscom, usb, 1, 1, 1);
+MODULE_VERSION(umoscom, 1);
 
 static const struct usb_device_id umoscom_devs[] = {
 	{USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7703, 0)}
diff --git a/sys/dev/usb/serial/uvisor.c b/sys/dev/usb/serial/uvisor.c
index 77ff31f5bd2..96a33894080 100644
--- a/sys/dev/usb/serial/uvisor.c
+++ b/sys/dev/usb/serial/uvisor.c
@@ -252,6 +252,7 @@ static driver_t uvisor_driver = {
 DRIVER_MODULE(uvisor, uhub, uvisor_driver, uvisor_devclass, NULL, 0);
 MODULE_DEPEND(uvisor, ucom, 1, 1, 1);
 MODULE_DEPEND(uvisor, usb, 1, 1, 1);
+MODULE_VERSION(uvisor, 1);
 
 static const struct usb_device_id uvisor_devs[] = {
 #define	UVISOR_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) }
diff --git a/sys/dev/usb/storage/umass.c b/sys/dev/usb/storage/umass.c
index a66357b5db5..567584a5b92 100644
--- a/sys/dev/usb/storage/umass.c
+++ b/sys/dev/usb/storage/umass.c
@@ -715,6 +715,7 @@ static driver_t umass_driver = {
 DRIVER_MODULE(umass, uhub, umass_driver, umass_devclass, NULL, 0);
 MODULE_DEPEND(umass, usb, 1, 1, 1);
 MODULE_DEPEND(umass, cam, 1, 1, 1);
+MODULE_VERSION(umass, 1);
 
 /*
  * USB device probe/attach/detach
diff --git a/sys/dev/usb/storage/urio.c b/sys/dev/usb/storage/urio.c
index 1aef8469f43..bf2d3147f7a 100644
--- a/sys/dev/usb/storage/urio.c
+++ b/sys/dev/usb/storage/urio.c
@@ -197,6 +197,7 @@ static driver_t urio_driver = {
 
 DRIVER_MODULE(urio, uhub, urio_driver, urio_devclass, NULL, 0);
 MODULE_DEPEND(urio, usb, 1, 1, 1);
+MODULE_VERSION(urio, 1);
 
 static int
 urio_probe(device_t dev)
diff --git a/sys/dev/usb/usb_compat_linux.c b/sys/dev/usb/usb_compat_linux.c
index 89aaa8f7aac..7d44456b70f 100644
--- a/sys/dev/usb/usb_compat_linux.c
+++ b/sys/dev/usb/usb_compat_linux.c
@@ -122,6 +122,7 @@ static driver_t usb_linux_driver = {
 static devclass_t usb_linux_devclass;
 
 DRIVER_MODULE(usb_linux, uhub, usb_linux_driver, usb_linux_devclass, NULL, 0);
+MODULE_VERSION(usb_linux, 1);
 
 /*------------------------------------------------------------------------*
  *	usb_linux_lookup_id
diff --git a/sys/dev/usb/usb_hub.c b/sys/dev/usb/usb_hub.c
index 95e9b294b96..ee0e1dbd017 100644
--- a/sys/dev/usb/usb_hub.c
+++ b/sys/dev/usb/usb_hub.c
@@ -170,6 +170,7 @@ static driver_t uhub_driver = {
 
 DRIVER_MODULE(uhub, usbus, uhub_driver, uhub_devclass, 0, 0);
 DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, NULL, 0);
+MODULE_VERSION(uhub, 1);
 
 static void
 uhub_intr_callback(struct usb_xfer *xfer, usb_error_t error)
diff --git a/sys/dev/usb/wlan/if_rum.c b/sys/dev/usb/wlan/if_rum.c
index d8378f846f4..26993cd5de4 100644
--- a/sys/dev/usb/wlan/if_rum.c
+++ b/sys/dev/usb/wlan/if_rum.c
@@ -139,9 +139,6 @@ static const struct usb_device_id rum_devs[] = {
 #undef RUM_DEV
 };
 
-MODULE_DEPEND(rum, wlan, 1, 1, 1);
-MODULE_DEPEND(rum, usb, 1, 1, 1);
-
 static device_probe_t rum_match;
 static device_attach_t rum_attach;
 static device_detach_t rum_detach;
@@ -2360,3 +2357,6 @@ static driver_t rum_driver = {
 static devclass_t rum_devclass;
 
 DRIVER_MODULE(rum, uhub, rum_driver, rum_devclass, NULL, 0);
+MODULE_DEPEND(rum, wlan, 1, 1, 1);
+MODULE_DEPEND(rum, usb, 1, 1, 1);
+MODULE_VERSION(rum, 1);
diff --git a/sys/dev/usb/wlan/if_run.c b/sys/dev/usb/wlan/if_run.c
index c594f2148fd..6c9afb980e7 100644
--- a/sys/dev/usb/wlan/if_run.c
+++ b/sys/dev/usb/wlan/if_run.c
@@ -294,10 +294,6 @@ static const struct usb_device_id run_devs[] = {
 #undef RUN_DEV
 };
 
-MODULE_DEPEND(run, wlan, 1, 1, 1);
-MODULE_DEPEND(run, usb, 1, 1, 1);
-MODULE_DEPEND(run, firmware, 1, 1, 1);
-
 static device_probe_t	run_match;
 static device_attach_t	run_attach;
 static device_detach_t	run_detach;
@@ -4871,3 +4867,7 @@ static driver_t run_driver = {
 static devclass_t run_devclass;
 
 DRIVER_MODULE(run, uhub, run_driver, run_devclass, NULL, 0);
+MODULE_DEPEND(run, wlan, 1, 1, 1);
+MODULE_DEPEND(run, usb, 1, 1, 1);
+MODULE_DEPEND(run, firmware, 1, 1, 1);
+MODULE_VERSION(run, 1);
diff --git a/sys/dev/usb/wlan/if_uath.c b/sys/dev/usb/wlan/if_uath.c
index 40b7c83da10..a2fba421dfb 100644
--- a/sys/dev/usb/wlan/if_uath.c
+++ b/sys/dev/usb/wlan/if_uath.c
@@ -2892,3 +2892,4 @@ static devclass_t uath_devclass;
 DRIVER_MODULE(uath, uhub, uath_driver, uath_devclass, NULL, 0);
 MODULE_DEPEND(uath, wlan, 1, 1, 1);
 MODULE_DEPEND(uath, usb, 1, 1, 1);
+MODULE_VERSION(uath, 1);
diff --git a/sys/dev/usb/wlan/if_ural.c b/sys/dev/usb/wlan/if_ural.c
index c3e60cd59fb..94b560dc740 100644
--- a/sys/dev/usb/wlan/if_ural.c
+++ b/sys/dev/usb/wlan/if_ural.c
@@ -400,6 +400,7 @@ static devclass_t ural_devclass;
 DRIVER_MODULE(ural, uhub, ural_driver, ural_devclass, NULL, 0);
 MODULE_DEPEND(ural, usb, 1, 1, 1);
 MODULE_DEPEND(ural, wlan, 1, 1, 1);
+MODULE_VERSION(ural, 1);
 
 static int
 ural_match(device_t self)
diff --git a/sys/dev/usb/wlan/if_urtw.c b/sys/dev/usb/wlan/if_urtw.c
index 9ff16f3b137..39f184738c1 100644
--- a/sys/dev/usb/wlan/if_urtw.c
+++ b/sys/dev/usb/wlan/if_urtw.c
@@ -4441,3 +4441,4 @@ static devclass_t urtw_devclass;
 DRIVER_MODULE(urtw, uhub, urtw_driver, urtw_devclass, NULL, 0);
 MODULE_DEPEND(urtw, wlan, 1, 1, 1);
 MODULE_DEPEND(urtw, usb, 1, 1, 1);
+MODULE_VERSION(urtw, 1);
diff --git a/sys/dev/usb/wlan/if_zyd.c b/sys/dev/usb/wlan/if_zyd.c
index 94ad559a50d..6415cd4b227 100644
--- a/sys/dev/usb/wlan/if_zyd.c
+++ b/sys/dev/usb/wlan/if_zyd.c
@@ -2948,3 +2948,4 @@ static devclass_t zyd_devclass;
 DRIVER_MODULE(zyd, uhub, zyd_driver, zyd_devclass, NULL, 0);
 MODULE_DEPEND(zyd, usb, 1, 1, 1);
 MODULE_DEPEND(zyd, wlan, 1, 1, 1);
+MODULE_VERSION(zyd, 1);

From 090c02f8bd37fd278f8c4e26fc87b15578c80b7e Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Wed, 1 Sep 2010 23:51:07 +0000
Subject: [PATCH 0436/1624] Modify nfs_diskless.c to recognize the environment
 variable boot.nfsroot.nfshandlelen and set the diskless root fs to use NFSv3
 and this file handle length when it is set. If this environment variable is
 not set, the diskless root fs will use NFSv2 and the same defaults as before.
 This fixes the problem where the diskless nfs root fs had to be on a FreeBSD
 server for NFSv3 to work, because it did not know the correct file handle
 length and assumed the size used by FreeBSD. Until pxeboot and loader are
 replaced by ones built from commits coming soon, boot.nfsroot.nfshandlelen
 will not be set by them and the diskless root fs will use NFSv2 unless the
 /etc/fstab entry has the "nfsv3" option specified.

Tested by:	danny at cs.huji.ac.il
MFC after:	2 weeks
---
 sys/nfsclient/nfs_diskless.c | 165 +++++++++++++++++++++++++----------
 1 file changed, 120 insertions(+), 45 deletions(-)

diff --git a/sys/nfsclient/nfs_diskless.c b/sys/nfsclient/nfs_diskless.c
index 2f91b9d1799..aacecfff961 100644
--- a/sys/nfsclient/nfs_diskless.c
+++ b/sys/nfsclient/nfs_diskless.c
@@ -58,7 +58,7 @@ __FBSDID("$FreeBSD$");
 
 static int inaddr_to_sockaddr(char *ev, struct sockaddr_in *sa);
 static int hwaddr_to_sockaddr(char *ev, struct sockaddr_dl *sa);
-static int decode_nfshandle(char *ev, u_char *fh);
+static int decode_nfshandle(char *ev, u_char *fh, int maxfh);
 
 /*
  * Validate/sanity check a rsize/wsize parameter.
@@ -143,20 +143,37 @@ nfs_parse_options(const char *envopts, struct nfs_args *nd)
  * boot.nfsroot.server		IP address of root filesystem server
  * boot.nfsroot.path		path of the root filesystem on server
  * boot.nfsroot.nfshandle	NFS handle for root filesystem on server
+ * boot.nfsroot.nfshandlelen	and length of this handle (for NFSv3 only)
  * boot.nfsroot.options		NFS options for the root filesystem
  */
 void
 nfs_setup_diskless(void)
 {
 	struct nfs_diskless *nd = &nfs_diskless;
+	struct nfsv3_diskless *nd3 = &nfsv3_diskless;
 	struct ifnet *ifp;
 	struct ifaddr *ifa;
 	struct sockaddr_dl *sdl, ourdl;
 	struct sockaddr_in myaddr, netmask;
 	char *cp;
+	int cnt, fhlen, is_nfsv3;
+	uint32_t len;
 
-	if (nfs_diskless_valid)
+	if (nfs_diskless_valid != 0)
 		return;
+
+	/* get handle size. If this succeeds, it's an NFSv3 setup. */
+	if ((cp = getenv("boot.nfsroot.nfshandlelen")) != NULL) {
+		cnt = sscanf(cp, "%d", &len);
+		freeenv(cp);
+		if (cnt != 1 || len == 0 || len > NFSX_V3FHMAX) {
+			printf("nfs_diskless: bad NFS handle len\n");
+			return;
+		}
+		nd3->root_fhsize = len;
+		is_nfsv3 = 1;
+	} else
+		is_nfsv3 = 0;
 	/* set up interface */
 	if (inaddr_to_sockaddr("boot.netif.ip", &myaddr))
 		return;
@@ -164,11 +181,21 @@ nfs_setup_diskless(void)
 		printf("nfs_diskless: no netmask\n");
 		return;
 	}
-	bcopy(&myaddr, &nd->myif.ifra_addr, sizeof(myaddr));
-	bcopy(&myaddr, &nd->myif.ifra_broadaddr, sizeof(myaddr));
-	((struct sockaddr_in *) &nd->myif.ifra_broadaddr)->sin_addr.s_addr =
-		myaddr.sin_addr.s_addr | ~ netmask.sin_addr.s_addr;
-	bcopy(&netmask, &nd->myif.ifra_mask, sizeof(netmask));
+	if (is_nfsv3 != 0) {
+		bcopy(&myaddr, &nd3->myif.ifra_addr, sizeof(myaddr));
+		bcopy(&myaddr, &nd3->myif.ifra_broadaddr, sizeof(myaddr));
+		((struct sockaddr_in *) 
+		   &nd3->myif.ifra_broadaddr)->sin_addr.s_addr =
+		    myaddr.sin_addr.s_addr | ~ netmask.sin_addr.s_addr;
+		bcopy(&netmask, &nd3->myif.ifra_mask, sizeof(netmask));
+	} else {
+		bcopy(&myaddr, &nd->myif.ifra_addr, sizeof(myaddr));
+		bcopy(&myaddr, &nd->myif.ifra_broadaddr, sizeof(myaddr));
+		((struct sockaddr_in *) 
+		   &nd->myif.ifra_broadaddr)->sin_addr.s_addr =
+		    myaddr.sin_addr.s_addr | ~ netmask.sin_addr.s_addr;
+		bcopy(&netmask, &nd->myif.ifra_mask, sizeof(netmask));
+	}
 
 	if (hwaddr_to_sockaddr("boot.netif.hwaddr", &ourdl)) {
 		printf("nfs_diskless: no hardware address\n");
@@ -196,46 +223,94 @@ nfs_setup_diskless(void)
 	return;	/* no matching interface */
 match_done:
 	setenv("boot.netif.name", ifp->if_xname);
-	strlcpy(nd->myif.ifra_name, ifp->if_xname, sizeof(nd->myif.ifra_name));
+	if (is_nfsv3 != 0) {
+		strlcpy(nd3->myif.ifra_name, ifp->if_xname,
+		    sizeof(nd3->myif.ifra_name));
 	
-	/* set up gateway */
-	inaddr_to_sockaddr("boot.netif.gateway", &nd->mygateway);
+		/* set up gateway */
+		inaddr_to_sockaddr("boot.netif.gateway", &nd3->mygateway);
 
-	/* set up root mount */
-	nd->root_args.rsize = 8192;		/* XXX tunable? */
-	nd->root_args.wsize = 8192;
-	nd->root_args.sotype = SOCK_STREAM;
-	nd->root_args.flags = (NFSMNT_NFSV3 | NFSMNT_WSIZE | NFSMNT_RSIZE | NFSMNT_RESVPORT);
-	if (inaddr_to_sockaddr("boot.nfsroot.server", &nd->root_saddr)) {
-		printf("nfs_diskless: no server\n");
-		return;
-	}
-	nd->root_saddr.sin_port = htons(NFS_PORT);
-	if (decode_nfshandle("boot.nfsroot.nfshandle", &nd->root_fh[0]) == 0) {
-		printf("nfs_diskless: no NFS handle\n");
-		return;
-	}
-	if ((cp = getenv("boot.nfsroot.path")) != NULL) {
-		strncpy(nd->root_hostnam, cp, MNAMELEN - 1);
-		freeenv(cp);
-	}
-	if ((cp = getenv("boot.nfsroot.options")) != NULL) {
-		struct nfs_args args;
+		/* set up root mount */
+		nd3->root_args.rsize = 32768;		/* XXX tunable? */
+		nd3->root_args.wsize = 32768;
+		nd3->root_args.sotype = SOCK_STREAM;
+		nd3->root_args.flags = (NFSMNT_NFSV3 | NFSMNT_WSIZE |
+		    NFSMNT_RSIZE | NFSMNT_RESVPORT);
+		if (inaddr_to_sockaddr("boot.nfsroot.server",
+		    &nd3->root_saddr)) {
+			printf("nfs_diskless: no server\n");
+			return;
+		}
+		nd3->root_saddr.sin_port = htons(NFS_PORT);
+		fhlen = decode_nfshandle("boot.nfsroot.nfshandle",
+		    &nd3->root_fh[0], NFSX_V3FHMAX);
+		if (fhlen == 0) {
+			printf("nfs_diskless: no NFS handle\n");
+			return;
+		}
+		if (fhlen != nd3->root_fhsize) {
+			printf("nfs_diskless: bad NFS handle len=%d\n", fhlen);
+			return;
+		}
+		if ((cp = getenv("boot.nfsroot.path")) != NULL) {
+			strncpy(nd3->root_hostnam, cp, MNAMELEN - 1);
+			freeenv(cp);
+		}
+		if ((cp = getenv("boot.nfsroot.options")) != NULL) {
+			nfs_parse_options(cp, &nd3->root_args);
+			freeenv(cp);
+		}
+	
+		nfs_diskless_valid = 3;
+	} else {
+		strlcpy(nd->myif.ifra_name, ifp->if_xname,
+		    sizeof(nd->myif.ifra_name));
+	
+		/* set up gateway */
+		inaddr_to_sockaddr("boot.netif.gateway", &nd->mygateway);
 
-		/* XXX yech, convert between old and current arg format */
-		args.flags = nd->root_args.flags;
-		args.sotype = nd->root_args.sotype;
-		args.rsize = nd->root_args.rsize;
-		args.wsize = nd->root_args.wsize;
-		nfs_parse_options(cp, &args);
-		nd->root_args.flags = args.flags;
-		nd->root_args.sotype = args.sotype;
-		nd->root_args.rsize = args.rsize;
-		nd->root_args.wsize = args.wsize;
-		freeenv(cp);
+		/* set up root mount */
+		nd->root_args.rsize = 8192;		/* XXX tunable? */
+		nd->root_args.wsize = 8192;
+		nd->root_args.sotype = SOCK_STREAM;
+		nd->root_args.flags = (NFSMNT_WSIZE |
+		    NFSMNT_RSIZE | NFSMNT_RESVPORT);
+		if (inaddr_to_sockaddr("boot.nfsroot.server",
+		    &nd->root_saddr)) {
+			printf("nfs_diskless: no server\n");
+			return;
+		}
+		nd->root_saddr.sin_port = htons(NFS_PORT);
+		if (decode_nfshandle("boot.nfsroot.nfshandle",
+		    &nd->root_fh[0], NFSX_V2FH) == 0) {
+			printf("nfs_diskless: no NFS handle\n");
+			return;
+		}
+		if ((cp = getenv("boot.nfsroot.path")) != NULL) {
+			strncpy(nd->root_hostnam, cp, MNAMELEN - 1);
+			freeenv(cp);
+		}
+		if ((cp = getenv("boot.nfsroot.options")) != NULL) {
+			struct nfs_args args;
+	
+			/*
+			 * XXX yech, convert between old and current
+			 * arg format
+			 */
+			args.flags = nd->root_args.flags;
+			args.sotype = nd->root_args.sotype;
+			args.rsize = nd->root_args.rsize;
+			args.wsize = nd->root_args.wsize;
+			nfs_parse_options(cp, &args);
+			nd->root_args.flags = args.flags;
+			nd->root_args.sotype = args.sotype;
+			nd->root_args.rsize = args.rsize;
+			nd->root_args.wsize = args.wsize;
+			freeenv(cp);
+		}
+	
+		nfs_diskless_valid = 1;
 	}
-
-	nfs_diskless_valid = 1;
 }
 
 static int
@@ -289,7 +364,7 @@ hwaddr_to_sockaddr(char *ev, struct sockaddr_dl *sa)
 }
 
 static int
-decode_nfshandle(char *ev, u_char *fh) 
+decode_nfshandle(char *ev, u_char *fh, int maxfh) 
 {
 	u_char *cp, *ep;
 	int len, val;
@@ -315,7 +390,7 @@ decode_nfshandle(char *ev, u_char *fh)
 		*(fh++) = val;
 		len++;
 		cp += 2;
-		if (len > NFSX_V2FH) {
+		if (len > maxfh) {
 		    freeenv(ep);
 		    return (0);
 		}

From 8c6cd8631f9e1c1e23808d5bf52ce16c9eb367ab Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 00:44:05 +0000
Subject: [PATCH 0437/1624] Fix stupid error in r212109 which didn't swap DMA
 maps. This caused IOMMU panic on sparc64 under high TX load.

---
 sys/dev/sis/if_sis.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 8886617eb66..46d7b1f83c1 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -1883,8 +1883,8 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head)
 
 	/* Swap the last and the first dmamaps. */
 	map = txd->tx_dmamap;
-	txd->tx_dmamap = sc->sis_txdesc[frag].tx_dmamap;
-	sc->sis_txdesc[frag].tx_dmamap = map;
+	txd->tx_dmamap = sc->sis_txdesc[prod].tx_dmamap;
+	sc->sis_txdesc[prod].tx_dmamap = map;
 	txd->tx_m = *m_head;
 
 	return (0);

From de5f64707080e9c70ec67aee5b7b7af7e1b47a54 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Thu, 2 Sep 2010 01:00:13 +0000
Subject: [PATCH 0438/1624] Modify lib/libstand/nfs.c to use NFSv3 instead of
 NFSv2. This allows the nfs_getrootfh() function to return the correct file
 handle size to pxe.c for pxeboot. It also results in NFSv2 no longer being
 used by default anywhere in FreeBSD. If built with OLD_NFSV2 defined, the old
 code that predated this patch will be built and NFSv2 will be used.

Tested by:	danny at cs.huji.ac.il
MFC after:	2 weeks
---
 lib/libstand/nfs.c | 744 ++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 742 insertions(+), 2 deletions(-)

diff --git a/lib/libstand/nfs.c b/lib/libstand/nfs.c
index 485944922b1..e49999de957 100644
--- a/lib/libstand/nfs.c
+++ b/lib/libstand/nfs.c
@@ -50,7 +50,10 @@ __FBSDID("$FreeBSD$");
 
 #define NFS_DEBUGxx
 
+#define NFSREAD_SIZE 1024
+
 /* Define our own NFS attributes without NQNFS stuff. */
+#ifdef OLD_NFSV2
 struct nfsv2_fattrs {
 	n_long	fa_type;
 	n_long	fa_mode;
@@ -68,7 +71,6 @@ struct nfsv2_fattrs {
 	struct nfsv2_time fa_ctime;
 };
 
-
 struct nfs_read_args {
 	u_char	fh[NFS_FHSIZE];
 	n_long	off;
@@ -77,7 +79,6 @@ struct nfs_read_args {
 };
 
 /* Data part of nfs rpc reply (also the largest thing we receive) */
-#define NFSREAD_SIZE 1024
 struct nfs_read_repl {
 	n_long	errno;
 	struct	nfsv2_fattrs fa;
@@ -116,6 +117,72 @@ struct nfs_iodesc {
 	u_char	fh[NFS_FHSIZE];
 	struct nfsv2_fattrs fa;	/* all in network order */
 };
+#else	/* !OLD_NFSV2 */
+
+/* NFSv3 definitions */
+#define	NFS_V3MAXFHSIZE		64
+#define	NFS_VER3		3
+#define	RPCMNT_VER3		3
+#define	NFSPROCV3_LOOKUP	3
+#define	NFSPROCV3_READLINK	5
+#define	NFSPROCV3_READ		6
+#define	NFSPROCV3_READDIR	16
+
+typedef struct {
+	uint32_t val[2];
+} n_quad;
+
+struct nfsv3_time {
+	uint32_t nfs_sec;
+	uint32_t nfs_nsec;
+};
+
+struct nfsv3_fattrs {
+	uint32_t fa_type;
+	uint32_t fa_mode;
+	uint32_t fa_nlink;
+	uint32_t fa_uid;
+	uint32_t fa_gid;
+	n_quad fa_size;
+	n_quad fa_used;
+	n_quad fa_rdev;
+	n_quad fa_fsid;
+	n_quad fa_fileid;
+	struct nfsv3_time fa_atime;
+	struct nfsv3_time fa_mtime;
+	struct nfsv3_time fa_ctime;
+};
+
+/*
+ * For NFSv3, the file handle is variable in size, so most fixed sized
+ * structures for arguments won't work. For most cases, a structure
+ * that starts with any fixed size section is followed by an array
+ * that covers the maximum size required.
+ */
+struct nfsv3_readdir_repl {
+	uint32_t errno;
+	uint32_t ok;
+	struct nfsv3_fattrs fa;
+	uint32_t cookiev0;
+	uint32_t cookiev1;
+};
+
+struct nfsv3_readdir_entry {
+	uint32_t follows;
+	uint32_t fid0;
+	uint32_t fid1;
+	uint32_t len;
+	uint32_t nameplus[0];
+};
+
+struct nfs_iodesc {
+	struct iodesc *iodesc;
+	off_t off;
+	uint32_t fhsize;
+	u_char fh[NFS_V3MAXFHSIZE];
+	struct nfsv3_fattrs fa;	/* all in network order */
+};
+#endif	/* OLD_NFSV2 */
 
 /*
  * XXX interactions with tftp? See nfswrapper.c for a confusing
@@ -142,6 +209,7 @@ struct fs_ops nfs_fsops = {
 	nfs_readdir
 };
 
+#ifdef	OLD_NFSV2
 /*
  * Fetch the root file handle (call mount daemon)
  * Return zero or error number.
@@ -745,3 +813,675 @@ nfs_readdir(struct open_file *f, struct dirent *d)
 	cookie = ntohl(roff->cookie);
 	return 0;
 }
+#else	/* !OLD_NFSV2 */
+/*
+ * Fetch the root file handle (call mount daemon)
+ * Return zero or error number.
+ */
+int
+nfs_getrootfh(struct iodesc *d, char *path, uint32_t *fhlenp, u_char *fhp)
+{
+	int len;
+	struct args {
+		uint32_t len;
+		char path[FNAME_SIZE];
+	} *args;
+	struct repl {
+		uint32_t errno;
+		uint32_t fhsize;
+		u_char fh[NFS_V3MAXFHSIZE];
+		uint32_t authcnt;
+		uint32_t auth[7];
+	} *repl;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct args d;
+	} sdata;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct repl d;
+	} rdata;
+	size_t cc;
+
+#ifdef NFS_DEBUG
+	if (debug)
+		printf("nfs_getrootfh: %s\n", path);
+#endif
+
+	args = &sdata.d;
+	repl = &rdata.d;
+
+	bzero(args, sizeof(*args));
+	len = strlen(path);
+	if (len > sizeof(args->path))
+		len = sizeof(args->path);
+	args->len = htonl(len);
+	bcopy(path, args->path, len);
+	len = sizeof(uint32_t) + roundup(len, sizeof(uint32_t));
+
+	cc = rpc_call(d, RPCPROG_MNT, RPCMNT_VER3, RPCMNT_MOUNT,
+	    args, len, repl, sizeof(*repl));
+	if (cc == -1)
+		/* errno was set by rpc_call */
+		return (errno);
+	if (cc < 2 * sizeof (uint32_t))
+		return (EBADRPC);
+	if (repl->errno != 0)
+		return (ntohl(repl->errno));
+	*fhlenp = ntohl(repl->fhsize);
+	bcopy(repl->fh, fhp, *fhlenp);
+	return (0);
+}
+
+/*
+ * Lookup a file.  Store handle and attributes.
+ * Return zero or error number.
+ */
+int
+nfs_lookupfh(struct nfs_iodesc *d, const char *name, struct nfs_iodesc *newfd)
+{
+	int len, rlen, pos;
+	struct args {
+		uint32_t fhsize;
+		uint32_t fhplusname[1 +
+		    (NFS_V3MAXFHSIZE + FNAME_SIZE) / sizeof(uint32_t)];
+	} *args;
+	struct repl {
+		uint32_t errno;
+		uint32_t fhsize;
+		uint32_t fhplusattr[(NFS_V3MAXFHSIZE +
+		    2 * (sizeof(uint32_t) +
+		    sizeof(struct nfsv3_fattrs))) / sizeof(uint32_t)];
+	} *repl;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct args d;
+	} sdata;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct repl d;
+	} rdata;
+	ssize_t cc;
+
+#ifdef NFS_DEBUG
+	if (debug)
+		printf("lookupfh: called\n");
+#endif
+
+	args = &sdata.d;
+	repl = &rdata.d;
+
+	bzero(args, sizeof(*args));
+	args->fhsize = htonl(d->fhsize);
+	bcopy(d->fh, args->fhplusname, d->fhsize);
+	len = strlen(name);
+	if (len > FNAME_SIZE)
+		len = FNAME_SIZE;
+	pos = roundup(d->fhsize, sizeof(uint32_t)) / sizeof(uint32_t);
+	args->fhplusname[pos++] = htonl(len);
+	bcopy(name, &args->fhplusname[pos], len);
+	len = sizeof(uint32_t) + pos * sizeof(uint32_t) +
+	    roundup(len, sizeof(uint32_t));
+
+	rlen = sizeof(*repl);
+
+	cc = rpc_call(d->iodesc, NFS_PROG, NFS_VER3, NFSPROCV3_LOOKUP,
+	    args, len, repl, rlen);
+	if (cc == -1)
+		return (errno);		/* XXX - from rpc_call */
+	if (cc < 2 * sizeof(uint32_t))
+		return (EIO);
+	if (repl->errno != 0)
+		/* saerrno.h now matches NFS error numbers. */
+		return (ntohl(repl->errno));
+	newfd->fhsize = ntohl(repl->fhsize);
+	bcopy(repl->fhplusattr, &newfd->fh, newfd->fhsize);
+	pos = roundup(newfd->fhsize, sizeof(uint32_t)) / sizeof(uint32_t);
+	if (repl->fhplusattr[pos++] == 0)
+		return (EIO);
+	bcopy(&repl->fhplusattr[pos], &newfd->fa, sizeof(newfd->fa));
+	return (0);
+}
+
+#ifndef NFS_NOSYMLINK
+/*
+ * Get the destination of a symbolic link.
+ */
+int
+nfs_readlink(struct nfs_iodesc *d, char *buf)
+{
+	struct args {
+		uint32_t fhsize;
+		u_char fh[NFS_V3MAXFHSIZE];
+	} *args;
+	struct repl {
+		uint32_t errno;
+		uint32_t ok;
+		struct nfsv3_fattrs fa;
+		uint32_t len;
+		u_char path[NFS_MAXPATHLEN];
+	} *repl;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct args d;
+	} sdata;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct repl d;
+	} rdata;
+	ssize_t cc;
+
+#ifdef NFS_DEBUG
+	if (debug)
+		printf("readlink: called\n");
+#endif
+
+	args = &sdata.d;
+	repl = &rdata.d;
+
+	bzero(args, sizeof(*args));
+	args->fhsize = htonl(d->fhsize);
+	bcopy(d->fh, args->fh, d->fhsize);
+	cc = rpc_call(d->iodesc, NFS_PROG, NFS_VER3, NFSPROCV3_READLINK,
+	    args, sizeof(uint32_t) + roundup(d->fhsize, sizeof(uint32_t)),
+	    repl, sizeof(*repl));
+	if (cc == -1)
+		return (errno);
+
+	if (cc < 2 * sizeof(uint32_t))
+		return (EIO);
+
+	if (repl->errno != 0)
+		return (ntohl(repl->errno));
+
+	if (repl->ok == 0)
+		return (EIO);
+
+	repl->len = ntohl(repl->len);
+	if (repl->len > NFS_MAXPATHLEN)
+		return (ENAMETOOLONG);
+
+	bcopy(repl->path, buf, repl->len);
+	buf[repl->len] = 0;
+	return (0);
+}
+#endif
+
+/*
+ * Read data from a file.
+ * Return transfer count or -1 (and set errno)
+ */
+ssize_t
+nfs_readdata(struct nfs_iodesc *d, off_t off, void *addr, size_t len)
+{
+	struct args {
+		uint32_t fhsize;
+		uint32_t fhoffcnt[NFS_V3MAXFHSIZE / sizeof(uint32_t) + 3];
+	} *args;
+	struct repl {
+		uint32_t errno;
+		uint32_t ok;
+		struct nfsv3_fattrs fa;
+		uint32_t count;
+		uint32_t eof;
+		uint32_t len;
+		u_char data[NFSREAD_SIZE];
+	} *repl;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct args d;
+	} sdata;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct repl d;
+	} rdata;
+	size_t cc;
+	long x;
+	int hlen, rlen, pos;
+
+	args = &sdata.d;
+	repl = &rdata.d;
+
+	bzero(args, sizeof(*args));
+	args->fhsize = htonl(d->fhsize);
+	bcopy(d->fh, args->fhoffcnt, d->fhsize);
+	pos = roundup(d->fhsize, sizeof(uint32_t)) / sizeof(uint32_t);
+	args->fhoffcnt[pos++] = 0;
+	args->fhoffcnt[pos++] = htonl((uint32_t)off);
+	if (len > NFSREAD_SIZE)
+		len = NFSREAD_SIZE;
+	args->fhoffcnt[pos] = htonl((uint32_t)len);
+	hlen = sizeof(*repl) - NFSREAD_SIZE;
+
+	cc = rpc_call(d->iodesc, NFS_PROG, NFS_VER3, NFSPROCV3_READ,
+	    args, 4 * sizeof(uint32_t) + roundup(d->fhsize, sizeof(uint32_t)),
+	    repl, sizeof(*repl));
+	if (cc == -1)
+		/* errno was already set by rpc_call */
+		return (-1);
+	if (cc < hlen) {
+		errno = EBADRPC;
+		return (-1);
+	}
+	if (repl->errno != 0) {
+		errno = ntohl(repl->errno);
+		return (-1);
+	}
+	rlen = cc - hlen;
+	x = ntohl(repl->count);
+	if (rlen < x) {
+		printf("nfsread: short packet, %d < %ld\n", rlen, x);
+		errno = EBADRPC;
+		return (-1);
+	}
+	bcopy(repl->data, addr, x);
+	return (x);
+}
+
+/*
+ * Open a file.
+ * return zero or error number
+ */
+int
+nfs_open(const char *upath, struct open_file *f)
+{
+	struct iodesc *desc;
+	struct nfs_iodesc *currfd;
+	char buf[2 * NFS_V3MAXFHSIZE + 3];
+	u_char *fh;
+	char *cp;
+	int i;
+#ifndef NFS_NOSYMLINK
+	struct nfs_iodesc *newfd;
+	struct nfsv3_fattrs *fa;
+	char *ncp;
+	int c;
+	char namebuf[NFS_MAXPATHLEN + 1];
+	char linkbuf[NFS_MAXPATHLEN + 1];
+	int nlinks = 0;
+#endif
+	int error;
+	char *path;
+
+#ifdef NFS_DEBUG
+ 	if (debug)
+ 	    printf("nfs_open: %s (rootpath=%s)\n", upath, rootpath);
+#endif
+	if (!rootpath[0]) {
+		printf("no rootpath, no nfs\n");
+		return (ENXIO);
+	}
+
+	/*
+	 * This is silly - we should look at dv_type but that value is
+	 * arch dependant and we can't use it here.
+	 */
+#ifndef __i386__
+	if (strcmp(f->f_dev->dv_name, "net") != 0)
+		return (EINVAL);
+#else
+	if (strcmp(f->f_dev->dv_name, "pxe") != 0)
+		return (EINVAL);
+#endif
+
+	if (!(desc = socktodesc(*(int *)(f->f_devdata))))
+		return (EINVAL);
+
+	/* Bind to a reserved port. */
+	desc->myport = htons(--rpc_port);
+	desc->destip = rootip;
+	if ((error = nfs_getrootfh(desc, rootpath, &nfs_root_node.fhsize,
+	    nfs_root_node.fh)))
+		return (error);
+	nfs_root_node.iodesc = desc;
+
+	fh = &nfs_root_node.fh[0];
+	buf[0] = 'X';
+	cp = &buf[1];
+	for (i = 0; i < nfs_root_node.fhsize; i++, cp += 2)
+		sprintf(cp, "%02x", fh[i]);
+	sprintf(cp, "X");
+	setenv("boot.nfsroot.server", inet_ntoa(rootip), 1);
+	setenv("boot.nfsroot.path", rootpath, 1);
+	setenv("boot.nfsroot.nfshandle", buf, 1);
+	sprintf(buf, "%d", nfs_root_node.fhsize);
+	setenv("boot.nfsroot.nfshandlelen", buf, 1);
+
+#ifndef NFS_NOSYMLINK
+	/* Fake up attributes for the root dir. */
+	fa = &nfs_root_node.fa;
+	fa->fa_type  = htonl(NFDIR);
+	fa->fa_mode  = htonl(0755);
+	fa->fa_nlink = htonl(2);
+
+	currfd = &nfs_root_node;
+	newfd = 0;
+
+	cp = path = strdup(upath);
+	if (path == NULL) {
+		error = ENOMEM;
+		goto out;
+	}
+	while (*cp) {
+		/*
+		 * Remove extra separators
+		 */
+		while (*cp == '/')
+			cp++;
+
+		if (*cp == '\0')
+			break;
+		/*
+		 * Check that current node is a directory.
+		 */
+		if (currfd->fa.fa_type != htonl(NFDIR)) {
+			error = ENOTDIR;
+			goto out;
+		}
+
+		/* allocate file system specific data structure */
+		newfd = malloc(sizeof(*newfd));
+		if (newfd == NULL) {
+			error = ENOMEM;
+			goto out;
+		}
+		newfd->iodesc = currfd->iodesc;
+		newfd->off = 0;
+
+		/*
+		 * Get next component of path name.
+		 */
+		{
+			int len = 0;
+
+			ncp = cp;
+			while ((c = *cp) != '\0' && c != '/') {
+				if (++len > NFS_MAXNAMLEN) {
+					error = ENOENT;
+					goto out;
+				}
+				cp++;
+			}
+			*cp = '\0';
+		}
+
+		/* lookup a file handle */
+		error = nfs_lookupfh(currfd, ncp, newfd);
+		*cp = c;
+		if (error)
+			goto out;
+
+		/*
+		 * Check for symbolic link
+		 */
+		if (newfd->fa.fa_type == htonl(NFLNK)) {
+			int link_len, len;
+
+			error = nfs_readlink(newfd, linkbuf);
+			if (error)
+				goto out;
+
+			link_len = strlen(linkbuf);
+			len = strlen(cp);
+
+			if (link_len + len > MAXPATHLEN
+			    || ++nlinks > MAXSYMLINKS) {
+				error = ENOENT;
+				goto out;
+			}
+
+			bcopy(cp, &namebuf[link_len], len + 1);
+			bcopy(linkbuf, namebuf, link_len);
+
+			/*
+			 * If absolute pathname, restart at root.
+			 * If relative pathname, restart at parent directory.
+			 */
+			cp = namebuf;
+			if (*cp == '/') {
+				if (currfd != &nfs_root_node)
+					free(currfd);
+				currfd = &nfs_root_node;
+			}
+
+			free(newfd);
+			newfd = 0;
+
+			continue;
+		}
+
+		if (currfd != &nfs_root_node)
+			free(currfd);
+		currfd = newfd;
+		newfd = 0;
+	}
+
+	error = 0;
+
+out:
+	free(newfd);
+	free(path);
+#else
+	/* allocate file system specific data structure */
+	currfd = malloc(sizeof(*currfd));
+	if (currfd != NULL) {
+		currfd->iodesc = desc;
+		currfd->off = 0;
+
+		error = nfs_lookupfh(&nfs_root_node, upath, currfd);
+	} else
+		error = ENOMEM;
+#endif
+	if (!error) {
+		f->f_fsdata = (void *)currfd;
+		return (0);
+	}
+
+#ifdef NFS_DEBUG
+	if (debug)
+		printf("nfs_open: %s lookupfh failed: %s\n",
+		    path, strerror(error));
+#endif
+#ifndef NFS_NOSYMLINK
+	if (currfd != &nfs_root_node)
+#endif
+		free(currfd);
+
+	return (error);
+}
+
+int
+nfs_close(struct open_file *f)
+{
+	struct nfs_iodesc *fp = (struct nfs_iodesc *)f->f_fsdata;
+
+#ifdef NFS_DEBUG
+	if (debug)
+		printf("nfs_close: fp=0x%lx\n", (u_long)fp);
+#endif
+
+	if (fp != &nfs_root_node && fp)
+		free(fp);
+	f->f_fsdata = (void *)0;
+
+	return (0);
+}
+
+/*
+ * read a portion of a file
+ */
+int
+nfs_read(struct open_file *f, void *buf, size_t size, size_t *resid)
+{
+	struct nfs_iodesc *fp = (struct nfs_iodesc *)f->f_fsdata;
+	ssize_t cc;
+	char *addr = buf;
+
+#ifdef NFS_DEBUG
+	if (debug)
+		printf("nfs_read: size=%lu off=%d\n", (u_long)size,
+		       (int)fp->off);
+#endif
+	while ((int)size > 0) {
+		twiddle();
+		cc = nfs_readdata(fp, fp->off, (void *)addr, size);
+		/* XXX maybe should retry on certain errors */
+		if (cc == -1) {
+#ifdef NFS_DEBUG
+			if (debug)
+				printf("nfs_read: read: %s", strerror(errno));
+#endif
+			return (errno);	/* XXX - from nfs_readdata */
+		}
+		if (cc == 0) {
+#ifdef NFS_DEBUG
+			if (debug)
+				printf("nfs_read: hit EOF unexpectantly");
+#endif
+			goto ret;
+		}
+		fp->off += cc;
+		addr += cc;
+		size -= cc;
+	}
+ret:
+	if (resid)
+		*resid = size;
+
+	return (0);
+}
+
+/*
+ * Not implemented.
+ */
+int
+nfs_write(struct open_file *f, void *buf, size_t size, size_t *resid)
+{
+	return (EROFS);
+}
+
+off_t
+nfs_seek(struct open_file *f, off_t offset, int where)
+{
+	struct nfs_iodesc *d = (struct nfs_iodesc *)f->f_fsdata;
+	uint32_t size = ntohl(d->fa.fa_size.val[1]);
+
+	switch (where) {
+	case SEEK_SET:
+		d->off = offset;
+		break;
+	case SEEK_CUR:
+		d->off += offset;
+		break;
+	case SEEK_END:
+		d->off = size - offset;
+		break;
+	default:
+		errno = EINVAL;
+		return (-1);
+	}
+
+	return (d->off);
+}
+
+/* NFNON=0, NFREG=1, NFDIR=2, NFBLK=3, NFCHR=4, NFLNK=5, NFSOCK=6, NFFIFO=7 */
+int nfs_stat_types[9] = {
+	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK, S_IFSOCK, S_IFIFO, 0 };
+
+int
+nfs_stat(struct open_file *f, struct stat *sb)
+{
+	struct nfs_iodesc *fp = (struct nfs_iodesc *)f->f_fsdata;
+	uint32_t ftype, mode;
+
+	ftype = ntohl(fp->fa.fa_type);
+	mode  = ntohl(fp->fa.fa_mode);
+	mode |= nfs_stat_types[ftype & 7];
+
+	sb->st_mode  = mode;
+	sb->st_nlink = ntohl(fp->fa.fa_nlink);
+	sb->st_uid   = ntohl(fp->fa.fa_uid);
+	sb->st_gid   = ntohl(fp->fa.fa_gid);
+	sb->st_size  = ntohl(fp->fa.fa_size.val[1]);
+
+	return (0);
+}
+
+static int
+nfs_readdir(struct open_file *f, struct dirent *d)
+{
+	struct nfs_iodesc *fp = (struct nfs_iodesc *)f->f_fsdata;
+	struct nfsv3_readdir_repl *repl;
+	struct nfsv3_readdir_entry *rent;
+	static char *buf;
+	static uint32_t cookie0 = 0;
+	static uint32_t cookie1 = 0;
+	size_t cc;
+	static uint32_t cookieverf0 = 0;
+	static uint32_t cookieverf1 = 0;
+	int pos;
+
+	struct args {
+		uint32_t fhsize;
+		uint32_t fhpluscookie[5 + NFS_V3MAXFHSIZE];
+	} *args;
+	struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		struct args d;
+	} sdata;
+	static struct {
+		uint32_t h[RPC_HEADER_WORDS];
+		u_char d[NFS_READDIRSIZE];
+	} rdata;
+
+	if (cookie0 == 0 && cookie1 == 0) {
+	refill:
+		args = &sdata.d;
+		bzero(args, sizeof(*args));
+
+		args->fhsize = htonl(fp->fhsize);
+		bcopy(fp->fh, args->fhpluscookie, fp->fhsize);
+		pos = roundup(fp->fhsize, sizeof(uint32_t)) / sizeof(uint32_t);
+		args->fhpluscookie[pos++] = cookie0;
+		args->fhpluscookie[pos++] = cookie1;
+		args->fhpluscookie[pos++] = cookieverf0;
+		args->fhpluscookie[pos++] = cookieverf1;
+		args->fhpluscookie[pos] = htonl(NFS_READDIRSIZE);
+
+		cc = rpc_call(fp->iodesc, NFS_PROG, NFS_VER3, NFSPROCV3_READDIR,
+		    args, 6 * sizeof(uint32_t) +
+		    roundup(fp->fhsize, sizeof(uint32_t)),
+		    rdata.d, sizeof(rdata.d));
+		buf  = rdata.d;
+		repl = (struct nfsv3_readdir_repl *)buf;
+		if (repl->errno != 0)
+			return (ntohl(repl->errno));
+		cookieverf0 = repl->cookiev0;
+		cookieverf1 = repl->cookiev1;
+		buf += sizeof (struct nfsv3_readdir_repl);
+	}
+	rent = (struct nfsv3_readdir_entry *)buf;
+
+	if (rent->follows == 0) {
+		/* fid0 is actually eof */
+		if (rent->fid0 != 0) {
+			cookie0 = 0;
+			cookie1 = 0;
+			cookieverf0 = 0;
+			cookieverf1 = 0;
+			return (ENOENT);
+		}
+		goto refill;
+	}
+
+	d->d_namlen = ntohl(rent->len);
+	bcopy(rent->nameplus, d->d_name, d->d_namlen);
+	d->d_name[d->d_namlen] = '\0';
+
+	pos = roundup(d->d_namlen, sizeof(uint32_t)) / sizeof(uint32_t);
+	cookie0 = rent->nameplus[pos++];
+	cookie1 = rent->nameplus[pos++];
+	buf = (u_char *)&rent->nameplus[pos];
+	return (0);
+}
+#endif	/* OLD_NFSV2 */

From 4176401397bc6ac21687c3a500fb868cc85afa7c Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Thu, 2 Sep 2010 01:05:10 +0000
Subject: [PATCH 0439/1624] Modify pxe.c to use the version of nfs_getrootfh()
 that returns the file handle's size and was recently committed to
 lib/libstand/nfs.c. This allows pxeboot to use NFSv3 and work correcty for
 non-FreeBSD as well as FreeBSD NFS servers. If built with OLD_NFSV2 defined,
 the old code that predated this patch will be used.

Tested by:	danny at cs.huji.ac.il
---
 sys/boot/i386/libi386/pxe.c | 59 +++++++++++++++++++++++++++++++++++++
 1 file changed, 59 insertions(+)

diff --git a/sys/boot/i386/libi386/pxe.c b/sys/boot/i386/libi386/pxe.c
index 5629d90e2cb..0caee6abe42 100644
--- a/sys/boot/i386/libi386/pxe.c
+++ b/sys/boot/i386/libi386/pxe.c
@@ -409,6 +409,7 @@ pxe_perror(int err)
  * Reach inside the libstand NFS code and dig out an NFS handle
  * for the root filesystem.
  */
+#ifdef OLD_NFSV2
 struct nfs_iodesc {
 	struct	iodesc	*iodesc;
 	off_t	off;
@@ -456,6 +457,64 @@ pxe_setnfshandle(char *rootpath)
 	sprintf(cp, "X");
 	setenv("boot.nfsroot.nfshandle", buf, 1);
 }
+#else	/* !OLD_NFSV2 */
+
+#define	NFS_V3MAXFHSIZE		64
+
+struct nfs_iodesc {
+	struct iodesc *iodesc;
+	off_t off;
+	uint32_t fhsize;
+	u_char fh[NFS_V3MAXFHSIZE];
+	/* structure truncated */
+};
+extern struct nfs_iodesc nfs_root_node;
+extern int rpc_port;
+
+static void
+pxe_rpcmountcall()
+{
+	struct iodesc *d;
+	int error;
+
+	if (!(d = socktodesc(pxe_sock)))
+		return;
+        d->myport = htons(--rpc_port);
+        d->destip = rootip;
+	if ((error = nfs_getrootfh(d, rootpath, &nfs_root_node.fhsize,
+	    nfs_root_node.fh)) != 0) {
+		printf("NFS MOUNT RPC error: %d\n", error);
+		nfs_root_node.fhsize = 0;
+	}
+	nfs_root_node.iodesc = d;
+}
+
+static void
+pxe_setnfshandle(char *rootpath)
+{
+	int i;
+	u_char *fh;
+	char buf[2 * NFS_V3MAXFHSIZE + 3], *cp;
+
+	/*
+	 * If NFS files were never opened, we need to do mount call
+	 * ourselves. Use nfs_root_node.iodesc as flag indicating
+	 * previous NFS usage.
+	 */
+	if (nfs_root_node.iodesc == NULL)
+		pxe_rpcmountcall();
+
+	fh = &nfs_root_node.fh[0];
+	buf[0] = 'X';
+	cp = &buf[1];
+	for (i = 0; i < nfs_root_node.fhsize; i++, cp += 2)
+		sprintf(cp, "%02x", fh[i]);
+	sprintf(cp, "X");
+	setenv("boot.nfsroot.nfshandle", buf, 1);
+	sprintf(buf, "%d", nfs_root_node.fhsize);
+	setenv("boot.nfsroot.nfshandlelen", buf, 1);
+}
+#endif	/* OLD_NFSV2 */
 
 void
 pxenv_call(int func)

From 8d8bdb018dd70dfae557c91b21c28b14766471b2 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:28:03 +0000
Subject: [PATCH 0440/1624] We need to grab a node reference count to
 vap->iv_bss before using it as it is possible for the node to be replaced and
 freed at any time by ieee80211_sta_join1().

---
 sys/dev/usb/wlan/if_rum.c  |  7 +++++--
 sys/dev/usb/wlan/if_run.c  | 13 ++++++++++---
 sys/dev/usb/wlan/if_uath.c | 12 +++++++++---
 sys/dev/usb/wlan/if_upgt.c |  5 ++++-
 sys/dev/usb/wlan/if_ural.c | 10 +++++++---
 sys/dev/usb/wlan/if_urtw.c |  5 ++++-
 sys/dev/usb/wlan/if_zyd.c  |  4 +---
 7 files changed, 40 insertions(+), 16 deletions(-)

diff --git a/sys/dev/usb/wlan/if_rum.c b/sys/dev/usb/wlan/if_rum.c
index 26993cd5de4..d3cb78864a1 100644
--- a/sys/dev/usb/wlan/if_rum.c
+++ b/sys/dev/usb/wlan/if_rum.c
@@ -719,7 +719,7 @@ rum_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		break;
 
 	case IEEE80211_S_RUN:
-		ni = vap->iv_bss;
+		ni = ieee80211_ref_node(vap->iv_bss);
 
 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
 			rum_update_slot(ic->ic_ifp);
@@ -743,6 +743,7 @@ rum_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
 		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
 			rum_ratectl_start(sc, ni);
+		ieee80211_free_node(ni);
 		break;
 	default:
 		break;
@@ -2223,7 +2224,7 @@ rum_ratectl_task(void *arg, int pending)
 	struct ieee80211com *ic = vap->iv_ic;
 	struct ifnet *ifp = ic->ic_ifp;
 	struct rum_softc *sc = ifp->if_softc;
-	struct ieee80211_node *ni = vap->iv_bss;
+	struct ieee80211_node *ni;
 	int ok, fail;
 	int sum, retrycnt;
 
@@ -2237,8 +2238,10 @@ rum_ratectl_task(void *arg, int pending)
 	sum = ok+fail;
 	retrycnt = (le32toh(sc->sta[5]) & 0xffff) + fail;
 
+	ni = ieee80211_ref_node(vap->iv_bss);
 	ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt);
 	(void) ieee80211_ratectl_rate(ni, NULL, 0);
+	ieee80211_free_node(ni);
 
 	ifp->if_oerrors += fail;	/* count TX retry-fail as Tx errors */
 
diff --git a/sys/dev/usb/wlan/if_run.c b/sys/dev/usb/wlan/if_run.c
index 6c9afb980e7..d6cbf3ac609 100644
--- a/sys/dev/usb/wlan/if_run.c
+++ b/sys/dev/usb/wlan/if_run.c
@@ -1693,7 +1693,6 @@ run_media_change(struct ifnet *ifp)
 	struct ieee80211com *ic = vap->iv_ic;
 	const struct ieee80211_txparam *tp;
 	struct run_softc *sc = ic->ic_ifp->if_softc;
-	struct run_node	*rn = (void *)vap->iv_bss;
 	uint8_t rate, ridx;
 	int error;
 
@@ -1707,13 +1706,19 @@ run_media_change(struct ifnet *ifp)
 
 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
 	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
+		struct ieee80211_node *ni;
+		struct run_node	*rn;
+
 		rate = ic->ic_sup_rates[ic->ic_curmode].
 		    rs_rates[tp->ucastrate] & IEEE80211_RATE_VAL;
 		for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
 			if (rt2860_rates[ridx].rate == rate)
 				break;
+		ni = ieee80211_ref_node(vap->iv_bss);
+		rn = (struct run_node *)ni;
 		rn->fix_ridx = ridx;
 		DPRINTF("rate=%d, fix_ridx=%d\n", rate, rn->fix_ridx);
+		ieee80211_free_node(ni);
 	}
 
 #if 0
@@ -1736,7 +1741,6 @@ run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	struct run_softc *sc = ic->ic_ifp->if_softc;
 	struct run_vap *rvp = RUN_VAP(vap);
 	enum ieee80211_state ostate;
-	struct ieee80211_node *ni;
 	uint32_t sta[3];
 	uint32_t tmp;
 	uint8_t ratectl;
@@ -1781,7 +1785,6 @@ run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 
 
 	case IEEE80211_S_RUN:
-		ni = vap->iv_bss;
 		if (!(sc->runbmap & bid)) {
 			if(sc->running++)
 				restart_ratectl = 1;
@@ -1817,12 +1820,16 @@ run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		}
 
 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
+			struct ieee80211_node *ni;
+
 			run_updateslot(ic->ic_ifp);
 			run_enable_mrr(sc);
 			run_set_txpreamble(sc);
 			run_set_basicrates(sc);
+			ni = ieee80211_ref_node(vap->iv_bss);
 			IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
 			run_set_bssid(sc, ni->ni_bssid);
+			ieee80211_free_node(ni);
 			run_enable_tsf_sync(sc);
 
 			/* enable automatic rate adaptation */
diff --git a/sys/dev/usb/wlan/if_uath.c b/sys/dev/usb/wlan/if_uath.c
index a2fba421dfb..35202a9b50f 100644
--- a/sys/dev/usb/wlan/if_uath.c
+++ b/sys/dev/usb/wlan/if_uath.c
@@ -1968,9 +1968,10 @@ uath_create_connection(struct uath_softc *sc, uint32_t connid)
 	const struct ieee80211_rateset *rs;
 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
-	struct ieee80211_node *ni = vap->iv_bss;
+	struct ieee80211_node *ni;
 	struct uath_cmd_create_connection create;
 
+	ni = ieee80211_ref_node(vap->iv_bss);
 	bzero(&create, sizeof create);
 	create.connid = htobe32(connid);
 	create.bssid = htobe32(0);
@@ -1989,6 +1990,7 @@ uath_create_connection(struct uath_softc *sc, uint32_t connid)
 		create.connattr.wlanmode = htobe32(WLAN_MODE_11g);
 	else
 		create.connattr.wlanmode = htobe32(WLAN_MODE_11b);
+	ieee80211_free_node(ni);
 
 	return uath_cmd_write(sc, WDCMSG_CREATE_CONNECTION, &create,
 	    sizeof create, 0);
@@ -2017,14 +2019,16 @@ uath_write_associd(struct uath_softc *sc)
 {
 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
-	struct ieee80211_node *ni = vap->iv_bss;
+	struct ieee80211_node *ni;
 	struct uath_cmd_set_associd associd;
 
+	ni = ieee80211_ref_node(vap->iv_bss);
 	bzero(&associd, sizeof associd);
 	associd.defaultrateix = htobe32(1);	/* XXX */
 	associd.associd = htobe32(ni->ni_associd);
 	associd.timoffset = htobe32(0x3b);	/* XXX */
 	IEEE80211_ADDR_COPY(associd.bssid, ni->ni_bssid);
+	ieee80211_free_node(ni);
 	return uath_cmd_write(sc, WDCMSG_WRITE_ASSOCID, &associd,
 	    sizeof associd, 0);
 }
@@ -2065,7 +2069,7 @@ uath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 {
 	enum ieee80211_state ostate = vap->iv_state;
 	int error;
-	struct ieee80211_node *ni = vap->iv_bss;
+	struct ieee80211_node *ni;
 	struct ieee80211com *ic = vap->iv_ic;
 	struct uath_softc *sc = ic->ic_ifp->if_softc;
 	struct uath_vap *uvp = UATH_VAP(vap);
@@ -2078,6 +2082,7 @@ uath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	UATH_LOCK(sc);
 	callout_stop(&sc->stat_ch);
 	callout_stop(&sc->watchdog_ch);
+	ni = ieee80211_ref_node(vap->iv_bss);
 
 	switch (nstate) {
 	case IEEE80211_S_INIT:
@@ -2150,6 +2155,7 @@ uath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	default:
 		break;
 	}
+	ieee80211_free_node(ni);
 	UATH_UNLOCK(sc);
 	IEEE80211_LOCK(ic);
 	return (uvp->newstate(vap, nstate, arg));
diff --git a/sys/dev/usb/wlan/if_upgt.c b/sys/dev/usb/wlan/if_upgt.c
index 58d716201fc..73f7e1ee5c0 100644
--- a/sys/dev/usb/wlan/if_upgt.c
+++ b/sys/dev/usb/wlan/if_upgt.c
@@ -652,7 +652,6 @@ upgt_set_macfilter(struct upgt_softc *sc, uint8_t state)
 	struct ifnet *ifp = sc->sc_ifp;
 	struct ieee80211com *ic = ifp->if_l2com;
 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
-	struct ieee80211_node *ni = vap->iv_bss;
 	struct upgt_data *data_cmd;
 	struct upgt_lmac_mem *mem;
 	struct upgt_lmac_filter *filter;
@@ -707,6 +706,9 @@ upgt_set_macfilter(struct upgt_softc *sc, uint8_t state)
 		filter->unknown3 = htole16(UPGT_FILTER_UNKNOWN3);
 		break;
 	case IEEE80211_S_RUN:
+		struct ieee80211_node *ni;
+
+		ni = ieee80211_ref_node(vap->iv_bss);
 		/* XXX monitor mode isn't tested yet.  */
 		if (vap->iv_opmode == IEEE80211_M_MONITOR) {
 			filter->type = htole16(UPGT_FILTER_TYPE_MONITOR);
@@ -730,6 +732,7 @@ upgt_set_macfilter(struct upgt_softc *sc, uint8_t state)
 			filter->rxhw = htole32(sc->sc_eeprom_hwrx);
 			filter->unknown3 = htole16(UPGT_FILTER_UNKNOWN3);
 		}
+		ieee80211_free_node(ni);
 		break;
 	default:
 		device_printf(sc->sc_dev,
diff --git a/sys/dev/usb/wlan/if_ural.c b/sys/dev/usb/wlan/if_ural.c
index 94b560dc740..aa2dcbd5769 100644
--- a/sys/dev/usb/wlan/if_ural.c
+++ b/sys/dev/usb/wlan/if_ural.c
@@ -711,7 +711,7 @@ ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		break;
 
 	case IEEE80211_S_RUN:
-		ni = vap->iv_bss;
+		ni = ieee80211_ref_node(vap->iv_bss);
 
 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
 			ural_update_slot(ic->ic_ifp);
@@ -729,6 +729,7 @@ ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 				    "could not allocate beacon\n");
 				RAL_UNLOCK(sc);
 				IEEE80211_LOCK(ic);
+				ieee80211_free_node(ni);
 				return (-1);
 			}
 			ieee80211_ref_node(ni);
@@ -737,6 +738,7 @@ ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 				    "could not send beacon\n");
 				RAL_UNLOCK(sc);
 				IEEE80211_LOCK(ic);
+				ieee80211_free_node(ni);
 				return (-1);
 			}
 		}
@@ -754,7 +756,7 @@ ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
 		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
 			ural_ratectl_start(sc, ni);
-
+		ieee80211_free_node(ni);
 		break;
 
 	default:
@@ -2237,10 +2239,11 @@ ural_ratectl_task(void *arg, int pending)
 	struct ieee80211com *ic = vap->iv_ic;
 	struct ifnet *ifp = ic->ic_ifp;
 	struct ural_softc *sc = ifp->if_softc;
-	struct ieee80211_node *ni = vap->iv_bss;
+	struct ieee80211_node *ni;
 	int ok, fail;
 	int sum, retrycnt;
 
+	ni = ieee80211_ref_node(vap->iv_bss);
 	RAL_LOCK(sc);
 	/* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
@@ -2258,6 +2261,7 @@ ural_ratectl_task(void *arg, int pending)
 
 	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
 	RAL_UNLOCK(sc);
+	ieee80211_free_node(ni);
 }
 
 static int
diff --git a/sys/dev/usb/wlan/if_urtw.c b/sys/dev/usb/wlan/if_urtw.c
index 39f184738c1..0236956bace 100644
--- a/sys/dev/usb/wlan/if_urtw.c
+++ b/sys/dev/usb/wlan/if_urtw.c
@@ -1830,7 +1830,6 @@ urtw_tx_start(struct urtw_softc *sc, struct ieee80211_node *ni, struct mbuf *m0,
 static int
 urtw_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 {
-	struct ieee80211_node *ni = vap->iv_bss;
 	struct ieee80211com *ic = vap->iv_ic;
 	struct urtw_softc *sc = ic->ic_ifp->if_softc;
 	struct urtw_vap *uvp = URTW_VAP(vap);
@@ -1854,6 +1853,9 @@ urtw_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	case IEEE80211_S_ASSOC:
 		break;
 	case IEEE80211_S_RUN:
+		struct ieee80211_node *ni;
+
+		ni = ieee80211_ref_node(vap->iv_bss);
 		/* setting bssid.  */
 		urtw_write32_m(sc, URTW_BSSID, ((uint32_t *)ni->ni_bssid)[0]);
 		urtw_write16_m(sc, URTW_BSSID + 4,
@@ -1868,6 +1870,7 @@ urtw_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		if (error != 0)
 			device_printf(sc->sc_dev,
 			    "could not control LED (%d)\n", error);
+		ieee80211_free_node(ni);
 		break;
 	default:
 		break;
diff --git a/sys/dev/usb/wlan/if_zyd.c b/sys/dev/usb/wlan/if_zyd.c
index 6415cd4b227..e8d7b7e06ea 100644
--- a/sys/dev/usb/wlan/if_zyd.c
+++ b/sys/dev/usb/wlan/if_zyd.c
@@ -572,7 +572,6 @@ zyd_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	struct zyd_vap *zvp = ZYD_VAP(vap);
 	struct ieee80211com *ic = vap->iv_ic;
 	struct zyd_softc *sc = ic->ic_ifp->if_softc;
-	struct ieee80211_node *ni;
 	int error;
 
 	DPRINTF(sc, ZYD_DEBUG_STATE, "%s: %s -> %s\n", __func__,
@@ -586,7 +585,6 @@ zyd_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		zyd_set_chan(sc, ic->ic_curchan);
 		break;
 	case IEEE80211_S_RUN:
-		ni = vap->iv_bss;
 		if (vap->iv_opmode == IEEE80211_M_MONITOR)
 			break;
 
@@ -598,7 +596,7 @@ zyd_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 		/* make data LED blink upon Tx */
 		zyd_write32_m(sc, sc->sc_fwbase + ZYD_FW_LINK_STATUS, 1);
 
-		IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
+		IEEE80211_ADDR_COPY(sc->sc_bssid, vap->iv_bss->ni_bssid);
 		zyd_set_bssid(sc, sc->sc_bssid);
 		break;
 	default:

From a6eb83193e46a7a1712055fc860762d2ae1dc228 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:42:26 +0000
Subject: [PATCH 0441/1624] Silence debug error by default.

PR:		usb/141212
Submitted by:	Hans Petter Selasky
---
 sys/dev/usb/input/ukbd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/usb/input/ukbd.c b/sys/dev/usb/input/ukbd.c
index 5101a351292..aca5df034ca 100644
--- a/sys/dev/usb/input/ukbd.c
+++ b/sys/dev/usb/input/ukbd.c
@@ -720,7 +720,7 @@ ukbd_set_leds_callback(struct usb_xfer *xfer, usb_error_t error)
 		break;
 
 	default:			/* Error */
-		DPRINTFN(0, "error=%s\n", usbd_errstr(error));
+		DPRINTFN(1, "error=%s\n", usbd_errstr(error));
 		break;
 	}
 }

From ee6e1a6f5a7196a2f057072c66018b901c2ad33c Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:44:56 +0000
Subject: [PATCH 0442/1624] Add support for extra buttons on the Kensington
 Slimblade Trackball.

Submitted by:	Lee, Chung-Yeol
---
 sys/dev/usb/input/ums.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/sys/dev/usb/input/ums.c b/sys/dev/usb/input/ums.c
index 7a2d053763b..1a5acc7924b 100644
--- a/sys/dev/usb/input/ums.c
+++ b/sys/dev/usb/input/ums.c
@@ -399,6 +399,7 @@ ums_hid_parse(struct ums_softc *sc, device_t dev, const uint8_t *buf,
 	struct ums_info *info = &sc->sc_info[index];
 	uint32_t flags;
 	uint8_t i;
+	uint8_t j;
 
 	if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X),
 	    hid_input, index, &info->sc_loc_x, &flags, &info->sc_iid_x)) {
@@ -476,6 +477,17 @@ ums_hid_parse(struct ums_softc *sc, device_t dev, const uint8_t *buf,
 			break;
 		}
 	}
+
+	/* detect other buttons */
+
+	for (j = 0; (i < UMS_BUTTONS_MAX) && (j < 2); i++, j++) {
+		if (!hid_locate(buf, len, HID_USAGE2(HUP_MICROSOFT, (j + 1)),
+		    hid_input, index, &info->sc_loc_btn[i], NULL, 
+		    &info->sc_iid_btn[i])) {
+			break;
+		}
+	}
+
 	info->sc_buttons = i;
 
 	if (i > sc->sc_buttons)

From edd913eb1a2306af70eaf1f9c02737804cf8a735 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:47:07 +0000
Subject: [PATCH 0443/1624] Add GPIO programming for more PHY hardware.

Submitted by:	yongari
---
 sys/dev/usb/net/if_axe.c    | 107 ++++++++++++++++++++++++++----------
 sys/dev/usb/net/if_axereg.h |  19 +++++++
 2 files changed, 97 insertions(+), 29 deletions(-)

diff --git a/sys/dev/usb/net/if_axe.c b/sys/dev/usb/net/if_axe.c
index 09f6561e21b..eae72ce96af 100644
--- a/sys/dev/usb/net/if_axe.c
+++ b/sys/dev/usb/net/if_axe.c
@@ -515,12 +515,19 @@ axe_get_phyno(struct axe_softc *sc, int sel)
 	return (phyno);
 }
 
+#define	AXE_GPIO_WRITE(x, y)	do {				\
+	axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, (x), NULL);		\
+	uether_pause(ue, (y));					\
+} while (0)
+
 static void
 axe_ax88178_init(struct axe_softc *sc)
 {
-	int gpio0 = 0, phymode = 0;
-	uint16_t eeprom;
+	struct usb_ether *ue;
+	int gpio0, phymode;
+	uint16_t eeprom, val;
 
+	ue = &sc->sc_ue;
 	axe_cmd(sc, AXE_CMD_SROM_WR_ENABLE, 0, 0, NULL);
 	/* XXX magic */
 	axe_cmd(sc, AXE_CMD_SROM_READ, 0, 0x0017, &eeprom);
@@ -529,46 +536,89 @@ axe_ax88178_init(struct axe_softc *sc)
 
 	/* if EEPROM is invalid we have to use to GPIO0 */
 	if (eeprom == 0xffff) {
-		phymode = 0;
+		phymode = AXE_PHY_MODE_MARVELL;
 		gpio0 = 1;
 	} else {
-		phymode = eeprom & 7;
+		phymode = eeprom & 0x7f;
 		gpio0 = (eeprom & 0x80) ? 0 : 1;
 	}
 
-	axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x008c, NULL);
-	uether_pause(&sc->sc_ue, hz / 16);
-
-	if ((eeprom >> 8) != 0x01) {
-		axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x003c, NULL);
-		uether_pause(&sc->sc_ue, hz / 32);
-
-		axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x001c, NULL);
-		uether_pause(&sc->sc_ue, hz / 3);
-
-		axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x003c, NULL);
-		uether_pause(&sc->sc_ue, hz / 32);
-	} else {
-		axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x0004, NULL);
-		uether_pause(&sc->sc_ue, hz / 32);
-
-		axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x000c, NULL);
-		uether_pause(&sc->sc_ue, hz / 32);
+	if (bootverbose)
+		device_printf(sc->sc_ue.ue_dev, "EEPROM data : 0x%04x\n",
+		    eeprom);
+	/* Program GPIOs depending on PHY hardware. */
+	switch (phymode) {
+	case AXE_PHY_MODE_MARVELL:
+		if (gpio0 == 1) {
+			AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO0_EN,
+			    hz / 32);
+			AXE_GPIO_WRITE(AXE_GPIO0_EN | AXE_GPIO2 | AXE_GPIO2_EN,
+			    hz / 32);
+			AXE_GPIO_WRITE(AXE_GPIO0_EN | AXE_GPIO2_EN, hz / 4);
+			AXE_GPIO_WRITE(AXE_GPIO0_EN | AXE_GPIO2 | AXE_GPIO2_EN,
+			    hz / 32);
+		} else
+			AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO1 |
+			    AXE_GPIO1_EN, hz / 32);
+		break;
+	case AXE_PHY_MODE_CICADA:
+		if (gpio0 == 1)
+			AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO0 |
+			    AXE_GPIO0_EN, hz / 32);
+		else
+			AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO1 |
+			    AXE_GPIO1_EN, hz / 32);
+		break;
+	case AXE_PHY_MODE_AGERE:
+		AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO1 |
+		    AXE_GPIO1_EN, hz / 32);
+		AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2 |
+		    AXE_GPIO2_EN, hz / 32);
+		AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2_EN, hz / 4);
+		AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2 |
+		    AXE_GPIO2_EN, hz / 32);
+		break;
+	case AXE_PHY_MODE_REALTEK_8211CL:
+	case AXE_PHY_MODE_REALTEK_8211BN:
+	case AXE_PHY_MODE_REALTEK_8251CL:
+		val = gpio0 == 1 ? AXE_GPIO0 | AXE_GPIO0_EN :
+		    AXE_GPIO1 | AXE_GPIO1_EN;
+		AXE_GPIO_WRITE(val, hz / 32);
+		AXE_GPIO_WRITE(val | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32);
+		AXE_GPIO_WRITE(val | AXE_GPIO2_EN, hz / 4);
+		AXE_GPIO_WRITE(val | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32);
+		if (phymode == AXE_PHY_MODE_REALTEK_8211CL) {
+			axe_miibus_writereg(ue->ue_dev, sc->sc_phyno,
+			    0x1F, 0x0005);
+			axe_miibus_writereg(ue->ue_dev, sc->sc_phyno,
+			    0x0C, 0x0000);
+			val = axe_miibus_readreg(ue->ue_dev, sc->sc_phyno,
+			    0x0001);
+			axe_miibus_writereg(ue->ue_dev, sc->sc_phyno,
+			    0x01, val | 0x0080);
+			axe_miibus_writereg(ue->ue_dev, sc->sc_phyno,
+			    0x1F, 0x0000);
+		}
+		break;
+	default:
+		/* Unknown PHY model or no need to program GPIOs. */
+		break;
 	}
 
 	/* soft reset */
 	axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_CLEAR, NULL);
-	uether_pause(&sc->sc_ue, hz / 4);
+	uether_pause(ue, hz / 4);
 
 	axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0,
 	    AXE_SW_RESET_PRL | AXE_178_RESET_MAGIC, NULL);
-	uether_pause(&sc->sc_ue, hz / 4);
+	uether_pause(ue, hz / 4);
 	/* Enable MII/GMII/RGMII interface to work with external PHY. */
 	axe_cmd(sc, AXE_CMD_SW_PHY_SELECT, 0, 0, NULL);
-	uether_pause(&sc->sc_ue, hz / 4);
+	uether_pause(ue, hz / 4);
 
 	axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, 0, NULL);
 }
+#undef	AXE_GPIO_WRITE
 
 static void
 axe_ax88772_init(struct axe_softc *sc)
@@ -637,10 +687,9 @@ axe_attach_post(struct usb_ether *ue)
 	 * Load PHY indexes first. Needed by axe_xxx_init().
 	 */
 	axe_cmd(sc, AXE_CMD_READ_PHYID, 0, 0, sc->sc_phyaddrs);
-#if 1
-	device_printf(sc->sc_ue.ue_dev, "PHYADDR 0x%02x:0x%02x\n",
-	    sc->sc_phyaddrs[0], sc->sc_phyaddrs[1]);
-#endif
+	if (bootverbose)
+		device_printf(sc->sc_ue.ue_dev, "PHYADDR 0x%02x:0x%02x\n",
+		    sc->sc_phyaddrs[0], sc->sc_phyaddrs[1]);
 	sc->sc_phyno = axe_get_phyno(sc, AXE_PHY_SEL_PRI);
 	if (sc->sc_phyno == -1)
 		sc->sc_phyno = axe_get_phyno(sc, AXE_PHY_SEL_SEC);
diff --git a/sys/dev/usb/net/if_axereg.h b/sys/dev/usb/net/if_axereg.h
index ae1a1d6450c..e3463e011d6 100644
--- a/sys/dev/usb/net/if_axereg.h
+++ b/sys/dev/usb/net/if_axereg.h
@@ -153,6 +153,25 @@
 
 #define	AXE_772_PHY_NO_EPHY	0x10	/* Embedded 10/100 PHY of AX88772 */
 
+#define	AXE_GPIO0_EN		0x01
+#define	AXE_GPIO0		0x02
+#define	AXE_GPIO1_EN		0x04
+#define	AXE_GPIO1		0x08
+#define	AXE_GPIO2_EN		0x10
+#define	AXE_GPIO2		0x20
+#define	AXE_GPIO_RELOAD_EEPROM	0x80
+
+#define	AXE_PHY_MODE_MARVELL		0x00
+#define	AXE_PHY_MODE_CICADA		0x01
+#define	AXE_PHY_MODE_AGERE		0x02
+#define	AXE_PHY_MODE_CICADA_V2		0x05
+#define	AXE_PHY_MODE_AGERE_GMII		0x06
+#define	AXE_PHY_MODE_CICADA_V2_ASIX	0x09
+#define	AXE_PHY_MODE_REALTEK_8211CL	0x0C
+#define	AXE_PHY_MODE_REALTEK_8211BN	0x0D
+#define	AXE_PHY_MODE_REALTEK_8251CL	0x0E
+#define	AXE_PHY_MODE_ATTANSIC		0x40
+
 #define	AXE_BULK_BUF_SIZE	16384	/* bytes */
 
 #define	AXE_CTL_READ		0x01

From 13226c4c029c3f5195d169397bece11a4a66021b Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:50:11 +0000
Subject: [PATCH 0444/1624] Fix build breakage from r212127

---
 sys/dev/usb/wlan/if_upgt.c | 3 +--
 sys/dev/usb/wlan/if_urtw.c | 3 +--
 2 files changed, 2 insertions(+), 4 deletions(-)

diff --git a/sys/dev/usb/wlan/if_upgt.c b/sys/dev/usb/wlan/if_upgt.c
index 73f7e1ee5c0..d361f8c78c0 100644
--- a/sys/dev/usb/wlan/if_upgt.c
+++ b/sys/dev/usb/wlan/if_upgt.c
@@ -652,6 +652,7 @@ upgt_set_macfilter(struct upgt_softc *sc, uint8_t state)
 	struct ifnet *ifp = sc->sc_ifp;
 	struct ieee80211com *ic = ifp->if_l2com;
 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
+	struct ieee80211_node *ni;
 	struct upgt_data *data_cmd;
 	struct upgt_lmac_mem *mem;
 	struct upgt_lmac_filter *filter;
@@ -706,8 +707,6 @@ upgt_set_macfilter(struct upgt_softc *sc, uint8_t state)
 		filter->unknown3 = htole16(UPGT_FILTER_UNKNOWN3);
 		break;
 	case IEEE80211_S_RUN:
-		struct ieee80211_node *ni;
-
 		ni = ieee80211_ref_node(vap->iv_bss);
 		/* XXX monitor mode isn't tested yet.  */
 		if (vap->iv_opmode == IEEE80211_M_MONITOR) {
diff --git a/sys/dev/usb/wlan/if_urtw.c b/sys/dev/usb/wlan/if_urtw.c
index 0236956bace..3de2273bcb6 100644
--- a/sys/dev/usb/wlan/if_urtw.c
+++ b/sys/dev/usb/wlan/if_urtw.c
@@ -1833,6 +1833,7 @@ urtw_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	struct ieee80211com *ic = vap->iv_ic;
 	struct urtw_softc *sc = ic->ic_ifp->if_softc;
 	struct urtw_vap *uvp = URTW_VAP(vap);
+	struct ieee80211_node *ni;
 	usb_error_t error = 0;
 
 	DPRINTF(sc, URTW_DEBUG_STATE, "%s: %s -> %s\n", __func__,
@@ -1853,8 +1854,6 @@ urtw_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
 	case IEEE80211_S_ASSOC:
 		break;
 	case IEEE80211_S_RUN:
-		struct ieee80211_node *ni;
-
 		ni = ieee80211_ref_node(vap->iv_bss);
 		/* setting bssid.  */
 		urtw_write32_m(sc, URTW_BSSID, ((uint32_t *)ni->ni_bssid)[0]);

From 1f27b68522d9617384b033876120b57456990b57 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:52:04 +0000
Subject: [PATCH 0445/1624] Fix UMS_BUTTON_MAX define name

---
 sys/dev/usb/input/ums.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/usb/input/ums.c b/sys/dev/usb/input/ums.c
index 1a5acc7924b..c0cab203434 100644
--- a/sys/dev/usb/input/ums.c
+++ b/sys/dev/usb/input/ums.c
@@ -480,7 +480,7 @@ ums_hid_parse(struct ums_softc *sc, device_t dev, const uint8_t *buf,
 
 	/* detect other buttons */
 
-	for (j = 0; (i < UMS_BUTTONS_MAX) && (j < 2); i++, j++) {
+	for (j = 0; (i < UMS_BUTTON_MAX) && (j < 2); i++, j++) {
 		if (!hid_locate(buf, len, HID_USAGE2(HUP_MICROSOFT, (j + 1)),
 		    hid_input, index, &info->sc_loc_btn[i], NULL, 
 		    &info->sc_iid_btn[i])) {

From dd5c0f870a813d3122fdc4632553d603fed7ab80 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 03:55:08 +0000
Subject: [PATCH 0446/1624] Fix setting of the rx_max and tx_max variables. If
 the expected buffer size is greater than 65535 bytes then the CDC driver
 might not work as expected, which is not likely with the existing USB speeds.

Submitted by:	Hans Petter Selasky
---
 sys/dev/usb/net/if_cdce.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/sys/dev/usb/net/if_cdce.c b/sys/dev/usb/net/if_cdce.c
index b5e7fd464bd..b8e7b984b56 100644
--- a/sys/dev/usb/net/if_cdce.c
+++ b/sys/dev/usb/net/if_cdce.c
@@ -312,14 +312,14 @@ cdce_ncm_init(struct cdce_softc *sc)
 	/* Read correct set of parameters according to device mode */
 
 	if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
-		sc->sc_ncm.rx_max = UGETW(temp.dwNtbInMaxSize);
-		sc->sc_ncm.tx_max = UGETW(temp.dwNtbOutMaxSize);
+		sc->sc_ncm.rx_max = UGETDW(temp.dwNtbInMaxSize);
+		sc->sc_ncm.tx_max = UGETDW(temp.dwNtbOutMaxSize);
 		sc->sc_ncm.tx_remainder = UGETW(temp.wNdpOutPayloadRemainder);
 		sc->sc_ncm.tx_modulus = UGETW(temp.wNdpOutDivisor);
 		sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpOutAlignment);
 	} else {
-		sc->sc_ncm.rx_max = UGETW(temp.dwNtbOutMaxSize);
-		sc->sc_ncm.tx_max = UGETW(temp.dwNtbInMaxSize);
+		sc->sc_ncm.rx_max = UGETDW(temp.dwNtbOutMaxSize);
+		sc->sc_ncm.tx_max = UGETDW(temp.dwNtbInMaxSize);
 		sc->sc_ncm.tx_remainder = UGETW(temp.wNdpInPayloadRemainder);
 		sc->sc_ncm.tx_modulus = UGETW(temp.wNdpInDivisor);
 		sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpInAlignment);

From 527aa7b226444c9b34752c1becf739381161e408 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 04:01:18 +0000
Subject: [PATCH 0447/1624] Change argument for usbd_get_dma_delay() from USB
 bus to USB device, some embedded hardware needs to know exactly which device
 is in question before it exactly can decide the required delay.

Submitted by:	Hans Petter Selasky
---
 sys/dev/usb/controller/ehci.c |  2 +-
 sys/dev/usb/controller/ohci.c |  2 +-
 sys/dev/usb/controller/uhci.c |  2 +-
 sys/dev/usb/usb_controller.h  |  2 +-
 sys/dev/usb/usb_hub.c         |  5 +++--
 sys/dev/usb/usb_transfer.c    | 22 ++++++++++++++--------
 sys/dev/usb/usb_transfer.h    |  2 +-
 7 files changed, 22 insertions(+), 15 deletions(-)

diff --git a/sys/dev/usb/controller/ehci.c b/sys/dev/usb/controller/ehci.c
index 40c95241672..007cbcd5129 100644
--- a/sys/dev/usb/controller/ehci.c
+++ b/sys/dev/usb/controller/ehci.c
@@ -3804,7 +3804,7 @@ done:
 }
 
 static void
-ehci_get_dma_delay(struct usb_bus *bus, uint32_t *pus)
+ehci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
 {
 	/*
 	 * Wait until the hardware has finished any possible use of
diff --git a/sys/dev/usb/controller/ohci.c b/sys/dev/usb/controller/ohci.c
index 0d630d76325..5ae15ac1a7a 100644
--- a/sys/dev/usb/controller/ohci.c
+++ b/sys/dev/usb/controller/ohci.c
@@ -2630,7 +2630,7 @@ ohci_xfer_unsetup(struct usb_xfer *xfer)
 }
 
 static void
-ohci_get_dma_delay(struct usb_bus *bus, uint32_t *pus)
+ohci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
 {
 	/*
 	 * Wait until hardware has finished any possible use of the
diff --git a/sys/dev/usb/controller/uhci.c b/sys/dev/usb/controller/uhci.c
index 50fdb0d1e86..7fb72f3256b 100644
--- a/sys/dev/usb/controller/uhci.c
+++ b/sys/dev/usb/controller/uhci.c
@@ -3084,7 +3084,7 @@ uhci_xfer_unsetup(struct usb_xfer *xfer)
 }
 
 static void
-uhci_get_dma_delay(struct usb_bus *bus, uint32_t *pus)
+uhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
 {
 	/*
 	 * Wait until hardware has finished any possible use of the
diff --git a/sys/dev/usb/usb_controller.h b/sys/dev/usb/usb_controller.h
index 6e355420e6e..6de588ac963 100644
--- a/sys/dev/usb/usb_controller.h
+++ b/sys/dev/usb/usb_controller.h
@@ -62,7 +62,7 @@ struct usb_bus_methods {
 		    struct usb_endpoint_descriptor *, struct usb_endpoint *);
 	void    (*xfer_setup) (struct usb_setup_params *);
 	void    (*xfer_unsetup) (struct usb_xfer *);
-	void    (*get_dma_delay) (struct usb_bus *, uint32_t *);
+	void    (*get_dma_delay) (struct usb_device *, uint32_t *);
 	void    (*device_suspend) (struct usb_device *);
 	void    (*device_resume) (struct usb_device *);
 	void    (*set_hw_power) (struct usb_bus *);
diff --git a/sys/dev/usb/usb_hub.c b/sys/dev/usb/usb_hub.c
index ee0e1dbd017..488c4bcdeb1 100644
--- a/sys/dev/usb/usb_hub.c
+++ b/sys/dev/usb/usb_hub.c
@@ -2105,8 +2105,9 @@ repeat:
 		(udev->bus->methods->device_suspend) (udev);
 
 		/* do DMA delay */
-		temp = usbd_get_dma_delay(udev->bus);
-		usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
+		temp = usbd_get_dma_delay(udev);
+		if (temp != 0)
+			usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
 
 	}
 	/* suspend current port */
diff --git a/sys/dev/usb/usb_transfer.c b/sys/dev/usb/usb_transfer.c
index e9bd64eafc3..af83e5a0b7f 100644
--- a/sys/dev/usb/usb_transfer.c
+++ b/sys/dev/usb/usb_transfer.c
@@ -158,12 +158,16 @@ usbd_update_max_frame_size(struct usb_xfer *xfer)
  * Else: milliseconds of DMA delay
  *------------------------------------------------------------------------*/
 usb_timeout_t
-usbd_get_dma_delay(struct usb_bus *bus)
+usbd_get_dma_delay(struct usb_device *udev)
 {
-	uint32_t temp = 0;
+	struct usb_bus_methods *mtod;
+	uint32_t temp;
 
-	if (bus->methods->get_dma_delay) {
-		(bus->methods->get_dma_delay) (bus, &temp);
+	mtod = udev->bus->methods;
+	temp = 0;
+
+	if (mtod->get_dma_delay) {
+		(mtod->get_dma_delay) (udev, &temp);
 		/*
 		 * Round up and convert to milliseconds. Note that we use
 		 * 1024 milliseconds per second. to save a division.
@@ -1094,9 +1098,11 @@ usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
 
 	if (needs_delay) {
 		usb_timeout_t temp;
-		temp = usbd_get_dma_delay(info->bus);
-		usb_pause_mtx(&info->bus->bus_mtx,
-		    USB_MS_TO_TICKS(temp));
+		temp = usbd_get_dma_delay(info->udev);
+		if (temp != 0) {
+			usb_pause_mtx(&info->bus->bus_mtx,
+			    USB_MS_TO_TICKS(temp));
+		}
 	}
 
 	/* make sure that our done messages are not queued anywhere */
@@ -2577,7 +2583,7 @@ usbd_callback_wrapper_sub(struct usb_xfer *xfer)
 		/* we can not cancel this delay */
 		xfer->flags_int.can_cancel_immed = 0;
 
-		temp = usbd_get_dma_delay(xfer->xroot->bus);
+		temp = usbd_get_dma_delay(xfer->xroot->udev);
 
 		DPRINTFN(3, "DMA delay, %u ms, "
 		    "on %p\n", temp, xfer);
diff --git a/sys/dev/usb/usb_transfer.h b/sys/dev/usb/usb_transfer.h
index 6e08df09ef8..2c5fe6f1ece 100644
--- a/sys/dev/usb/usb_transfer.h
+++ b/sys/dev/usb/usb_transfer.h
@@ -131,7 +131,7 @@ usb_callback_t usb_handle_request_callback;
 usb_callback_t usb_do_clear_stall_callback;
 void	usbd_transfer_timeout_ms(struct usb_xfer *xfer,
 	    void (*cb) (void *arg), usb_timeout_t ms);
-usb_timeout_t usbd_get_dma_delay(struct usb_bus *bus);
+usb_timeout_t usbd_get_dma_delay(struct usb_device *udev);
 void	usbd_transfer_power_ref(struct usb_xfer *xfer, int val);
 
 #endif					/* _USB_TRANSFER_H_ */

From d2d71ce7a8e60d6617b5c4ae2480397687f4882c Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 04:05:00 +0000
Subject: [PATCH 0448/1624] Add support for power mode filtering as some USB
 hardware does not support power saving.

Submitted by:	Hans Petter Selasky
---
 sys/dev/usb/usb_controller.h |  4 ++++
 sys/dev/usb/usb_device.c     |  2 +-
 sys/dev/usb/usb_generic.c    |  5 ++---
 sys/dev/usb/usb_hub.c        | 31 +++++++++++++++++++++++++++++--
 sys/dev/usb/usbdi.h          |  1 +
 5 files changed, 37 insertions(+), 6 deletions(-)

diff --git a/sys/dev/usb/usb_controller.h b/sys/dev/usb/usb_controller.h
index 6de588ac963..0f7ffac5d21 100644
--- a/sys/dev/usb/usb_controller.h
+++ b/sys/dev/usb/usb_controller.h
@@ -102,6 +102,10 @@ struct usb_bus_methods {
 	/* Optional transfer polling support */
 
 	void	(*xfer_poll) (struct usb_bus *);
+
+	/* Optional fixed power mode support */
+
+	void	(*get_power_mode) (struct usb_device *udev, int8_t *pmode);
 };
 
 /*
diff --git a/sys/dev/usb/usb_device.c b/sys/dev/usb/usb_device.c
index 62f59b8632f..41ed16bc282 100644
--- a/sys/dev/usb/usb_device.c
+++ b/sys/dev/usb/usb_device.c
@@ -1524,7 +1524,7 @@ usb_alloc_device(device_t parent_dev, struct usb_bus *bus,
 	 * of USB devices out there that do not work very well with
 	 * automatic suspend and resume!
 	 */
-	udev->power_mode = USB_POWER_MODE_ON;
+	udev->power_mode = usbd_filter_power_mode(udev, USB_POWER_MODE_ON);
 	udev->pwr_save.last_xfer_time = ticks;
 	/* we are not ready yet */
 	udev->refcount = 1;
diff --git a/sys/dev/usb/usb_generic.c b/sys/dev/usb/usb_generic.c
index 66677518a14..d98aba4c082 100644
--- a/sys/dev/usb/usb_generic.c
+++ b/sys/dev/usb/usb_generic.c
@@ -1791,10 +1791,9 @@ ugen_get_power_mode(struct usb_fifo *f)
 {
 	struct usb_device *udev = f->udev;
 
-	if ((udev == NULL) ||
-	    (udev->parent_hub == NULL)) {
+	if (udev == NULL)
 		return (USB_POWER_MODE_ON);
-	}
+
 	return (udev->power_mode);
 }
 
diff --git a/sys/dev/usb/usb_hub.c b/sys/dev/usb/usb_hub.c
index 488c4bcdeb1..d42b5a4c7f9 100644
--- a/sys/dev/usb/usb_hub.c
+++ b/sys/dev/usb/usb_hub.c
@@ -2133,12 +2133,39 @@ usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode)
 {
 	/* filter input argument */
 	if ((power_mode != USB_POWER_MODE_ON) &&
-	    (power_mode != USB_POWER_MODE_OFF)) {
+	    (power_mode != USB_POWER_MODE_OFF))
 		power_mode = USB_POWER_MODE_SAVE;
-	}
+
+	power_mode = usbd_filter_power_mode(udev, power_mode);	
+
 	udev->power_mode = power_mode;	/* update copy of power mode */
 
 #if USB_HAVE_POWERD
 	usb_bus_power_update(udev->bus);
 #endif
 }
+
+/*------------------------------------------------------------------------*
+ *	usbd_filter_power_mode
+ *
+ * This function filters the power mode based on hardware requirements.
+ *------------------------------------------------------------------------*/
+uint8_t
+usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode)
+{
+	struct usb_bus_methods *mtod;
+	int8_t temp;
+
+	mtod = udev->bus->methods;
+	temp = -1;
+
+	if (mtod->get_power_mode != NULL)
+		(mtod->get_power_mode) (udev, &temp);
+
+	/* check if we should not filter */
+	if (temp < 0)
+		return (power_mode);
+
+	/* use fixed power mode given by hardware driver */
+	return (temp);
+}
diff --git a/sys/dev/usb/usbdi.h b/sys/dev/usb/usbdi.h
index 9adf39adc77..79b73ca1735 100644
--- a/sys/dev/usb/usbdi.h
+++ b/sys/dev/usb/usbdi.h
@@ -479,6 +479,7 @@ void	usbd_set_parent_iface(struct usb_device *udev, uint8_t iface_index,
 uint8_t	usbd_get_bus_index(struct usb_device *udev);
 uint8_t	usbd_get_device_index(struct usb_device *udev);
 void	usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode);
+uint8_t	usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode);
 uint8_t	usbd_device_attached(struct usb_device *udev);
 
 void	usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen,

From ae538d85339bc2f3a9193c6b732d6c627a1de430 Mon Sep 17 00:00:00 2001
From: Andrew Thompson 
Date: Thu, 2 Sep 2010 04:39:45 +0000
Subject: [PATCH 0449/1624] Reduce the need to accesss struct usb_device by
 providing functions to access the product, manufacturer and serial strings.

Submitted by:	Hans Petter Selasky
---
 sys/dev/usb/net/uhso.c      | 13 ++++++-------
 sys/dev/usb/serial/ubser.c  |  3 +--
 sys/dev/usb/storage/umass.c | 19 +++++++++----------
 sys/dev/usb/usb_device.c    | 35 ++++++++++++++++++++++++++++-------
 sys/dev/usb/usb_generic.c   |  6 +++---
 sys/dev/usb/usb_hub.c       |  3 ++-
 sys/dev/usb/usbdi_util.h    |  7 +++++++
 7 files changed, 56 insertions(+), 30 deletions(-)

diff --git a/sys/dev/usb/net/uhso.c b/sys/dev/usb/net/uhso.c
index e0a9bb36ae2..c25917722d2 100644
--- a/sys/dev/usb/net/uhso.c
+++ b/sys/dev/usb/net/uhso.c
@@ -62,13 +62,11 @@ __FBSDID("$FreeBSD$");
 #define USB_DEBUG_VAR uhso_debug
 #include 
 #include 
-#include 
 #include 
-#include 
-#include 
-#include 
 #include 
 
+#include 
+
 struct uhso_tty {
 	struct uhso_softc *ht_sc;
 	struct usb_xfer	*ht_xfer[3];
@@ -513,7 +511,7 @@ uhso_probe(device_t self)
 		return (ENXIO);
 	if (uaa->info.bConfigIndex != 0)
 		return (ENXIO);
-	if (uaa->device->ddesc.bDeviceClass != 0xff)
+	if (uaa->info.bDeviceClass != 0xff)
 		return (ENXIO);
 
 	error = usbd_lookup_id_by_uaa(uhso_devs, sizeof(uhso_devs), uaa);
@@ -603,8 +601,9 @@ uhso_attach(device_t self)
 	/* Announce device */
 	device_printf(self, "<%s port> at <%s %s> on %s\n",
 	    uhso_port_type[UHSO_IFACE_PORT_TYPE(sc->sc_type)],
-	    uaa->device->manufacturer, uaa->device->product,
-	    device_get_nameunit(uaa->device->bus->bdev));
+	    usb_get_manufacturer(uaa->device),
+	    usb_get_product(uaa->device),
+	    device_get_nameunit(device_get_parent(self)));
 
 	if (sc->sc_ttys > 0) {
 		SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "ports",
diff --git a/sys/dev/usb/serial/ubser.c b/sys/dev/usb/serial/ubser.c
index be332c3df5f..7119177e990 100644
--- a/sys/dev/usb/serial/ubser.c
+++ b/sys/dev/usb/serial/ubser.c
@@ -104,7 +104,6 @@ __FBSDID("$FreeBSD$");
 #define	USB_DEBUG_VAR ubser_debug
 #include 
 #include 
-#include 
 
 #include 
 
@@ -226,7 +225,7 @@ ubser_probe(device_t dev)
 		return (ENXIO);
 	}
 	/* check if this is a BWCT vendor specific ubser interface */
-	if ((strcmp(uaa->device->manufacturer, "BWCT") == 0) &&
+	if ((strcmp(usb_get_manufacturer(uaa->device), "BWCT") == 0) &&
 	    (uaa->info.bInterfaceClass == 0xff) &&
 	    (uaa->info.bInterfaceSubClass == 0x00))
 		return (0);
diff --git a/sys/dev/usb/storage/umass.c b/sys/dev/usb/storage/umass.c
index 567584a5b92..5455917987c 100644
--- a/sys/dev/usb/storage/umass.c
+++ b/sys/dev/usb/storage/umass.c
@@ -124,7 +124,7 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #include 
-#include 
+#include 
 #include "usbdevs.h"
 
 #include 
@@ -2304,23 +2304,24 @@ umass_cam_action(struct cam_sim *sim, union ccb *ccb)
 			if (umass_std_transform(sc, ccb, cmd, ccb->csio.cdb_len)) {
 
 				if (sc->sc_transfer.cmd_data[0] == INQUIRY) {
+					const char *pserial;
+
+					pserial = usb_get_serial(sc->sc_udev);
 
 					/*
 					 * Umass devices don't generally report their serial numbers
 					 * in the usual SCSI way.  Emulate it here.
 					 */
 					if ((sc->sc_transfer.cmd_data[1] & SI_EVPD) &&
-					    sc->sc_transfer.cmd_data[2] == SVPD_UNIT_SERIAL_NUMBER &&
-					    sc->sc_udev != NULL &&
-					    sc->sc_udev->serial != NULL &&
-					    sc->sc_udev->serial[0] != '\0') {
+					    (sc->sc_transfer.cmd_data[2] == SVPD_UNIT_SERIAL_NUMBER) &&
+					    (pserial[0] != '\0')) {
 						struct scsi_vpd_unit_serial_number *vpd_serial;
 
 						vpd_serial = (struct scsi_vpd_unit_serial_number *)ccb->csio.data_ptr;
-						vpd_serial->length = strlen(sc->sc_udev->serial);
+						vpd_serial->length = strlen(pserial);
 						if (vpd_serial->length > sizeof(vpd_serial->serial_num))
 							vpd_serial->length = sizeof(vpd_serial->serial_num);
-						memcpy(vpd_serial->serial_num, sc->sc_udev->serial, vpd_serial->length);
+						memcpy(vpd_serial->serial_num, pserial, vpd_serial->length);
 						ccb->csio.scsi_status = SCSI_STATUS_OK;
 						ccb->ccb_h.status = CAM_REQ_CMP;
 						xpt_done(ccb);
@@ -2553,9 +2554,7 @@ umass_cam_cb(struct umass_softc *sc, union ccb *ccb, uint32_t residue,
 		    sc->sc_transfer.cmd_data[0] == INQUIRY &&
 		    (sc->sc_transfer.cmd_data[1] & SI_EVPD) &&
 		    sc->sc_transfer.cmd_data[2] == SVPD_SUPPORTED_PAGE_LIST &&
-		    sc->sc_udev != NULL &&
-		    sc->sc_udev->serial != NULL &&
-		    sc->sc_udev->serial[0] != '\0') {
+		    (usb_get_serial(sc->sc_udev)[0] != '\0')) {
 			struct ccb_scsiio *csio;
 			struct scsi_vpd_supported_page_list *page_list;
 
diff --git a/sys/dev/usb/usb_device.c b/sys/dev/usb/usb_device.c
index 41ed16bc282..fcbd2c02623 100644
--- a/sys/dev/usb/usb_device.c
+++ b/sys/dev/usb/usb_device.c
@@ -136,6 +136,24 @@ usb_statestr(enum usb_dev_state state)
 	return ((state < USB_STATE_MAX) ? statestr[state] : "UNKNOWN");
 }
 
+const char *
+usb_get_manufacturer(struct usb_device *udev)
+{
+	return (udev->manufacturer ? udev->manufacturer : "Unknown");
+}
+
+const char *
+usb_get_product(struct usb_device *udev)
+{
+	return (udev->product ? udev->product : "");
+}
+
+const char *
+usb_get_serial(struct usb_device *udev)
+{
+	return (udev->serial ? udev->serial : "");
+}
+
 /*------------------------------------------------------------------------*
  *	usbd_get_ep_by_addr
  *
@@ -1833,7 +1851,8 @@ config_done:
 	udev->ugen_symlink = usb_alloc_symlink(udev->ugen_name);
 
 	/* Announce device */
-	printf("%s: <%s> at %s\n", udev->ugen_name, udev->manufacturer,
+	printf("%s: <%s> at %s\n", udev->ugen_name,
+	    usb_get_manufacturer(udev),
 	    device_get_nameunit(udev->bus->bdev));
 
 	usb_notify_addq("ATTACH", udev);
@@ -1985,7 +2004,7 @@ usb_free_device(struct usb_device *udev, uint8_t flag)
 	usb_notify_addq("DETACH", udev);
 
 	printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
-	    udev->manufacturer, device_get_nameunit(bus->bdev));
+	    usb_get_manufacturer(udev), device_get_nameunit(bus->bdev));
 
 	/* Destroy UGEN symlink, if any */
 	if (udev->ugen_symlink) {
@@ -2150,7 +2169,8 @@ usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
 	if (udd->bDeviceClass != 0xFF) {
 		snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
 		    "%x.%02x, addr %d",
-		    udev->manufacturer, udev->product,
+		    usb_get_manufacturer(udev),
+		    usb_get_product(udev),
 		    udd->bDeviceClass, udd->bDeviceSubClass,
 		    (bcdUSB >> 8), bcdUSB & 0xFF,
 		    (bcdDevice >> 8), bcdDevice & 0xFF,
@@ -2158,7 +2178,8 @@ usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
 	} else {
 		snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
 		    "%x.%02x, addr %d",
-		    udev->manufacturer, udev->product,
+		    usb_get_manufacturer(udev),
+		    usb_get_product(udev),
 		    (bcdUSB >> 8), bcdUSB & 0xFF,
 		    (bcdDevice >> 8), bcdDevice & 0xFF,
 		    udev->address);
@@ -2397,7 +2418,7 @@ usb_notify_addq_compat(const char *type, struct usb_device *udev)
 	    UGETW(udev->ddesc.idProduct),
 	    udev->ddesc.bDeviceClass,
 	    udev->ddesc.bDeviceSubClass,
-	    udev->serial,
+	    usb_get_serial(udev),
 	    UGETW(udev->ddesc.bcdDevice),
 	    udev->port_no,
 	    udev->parent_hub != NULL ?
@@ -2437,7 +2458,7 @@ usb_notify_addq(const char *type, struct usb_device *udev)
 	    UGETW(udev->ddesc.idProduct),
 	    udev->ddesc.bDeviceClass,
 	    udev->ddesc.bDeviceSubClass,
-	    udev->serial,
+	    usb_get_serial(udev),
 	    UGETW(udev->ddesc.bcdDevice),
 	    (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
 	    udev->port_no,
@@ -2476,7 +2497,7 @@ usb_notify_addq(const char *type, struct usb_device *udev)
 		    UGETW(udev->ddesc.idProduct),
 		    udev->ddesc.bDeviceClass,
 		    udev->ddesc.bDeviceSubClass,
-		    udev->serial,
+		    usb_get_serial(udev),
 		    UGETW(udev->ddesc.bcdDevice),
 		    (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
 		    iface->idesc->bInterfaceNumber,
diff --git a/sys/dev/usb/usb_generic.c b/sys/dev/usb/usb_generic.c
index d98aba4c082..0cac19bd70d 100644
--- a/sys/dev/usb/usb_generic.c
+++ b/sys/dev/usb/usb_generic.c
@@ -825,9 +825,9 @@ usb_gen_fill_deviceinfo(struct usb_fifo *f, struct usb_device_info *di)
 	di->udi_bus = device_get_unit(udev->bus->bdev);
 	di->udi_addr = udev->address;
 	di->udi_index = udev->device_index;
-	strlcpy(di->udi_serial, udev->serial, sizeof(di->udi_serial));
-	strlcpy(di->udi_vendor, udev->manufacturer, sizeof(di->udi_vendor));
-	strlcpy(di->udi_product, udev->product, sizeof(di->udi_product));
+	strlcpy(di->udi_serial, usb_get_serial(udev), sizeof(di->udi_serial));
+	strlcpy(di->udi_vendor, usb_get_manufacturer(udev), sizeof(di->udi_vendor));
+	strlcpy(di->udi_product, usb_get_product(udev), sizeof(di->udi_product));
 	usb_printbcd(di->udi_release, sizeof(di->udi_release),
 	    UGETW(udev->ddesc.bcdDevice));
 	di->udi_vendorNo = UGETW(udev->ddesc.idVendor);
diff --git a/sys/dev/usb/usb_hub.c b/sys/dev/usb/usb_hub.c
index d42b5a4c7f9..87c86d29e5a 100644
--- a/sys/dev/usb/usb_hub.c
+++ b/sys/dev/usb/usb_hub.c
@@ -53,6 +53,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #define	USB_DEBUG_VAR uhub_debug
 
@@ -1059,7 +1060,7 @@ uhub_child_pnpinfo_string(device_t parent, device_t child,
 		    UGETW(res.udev->ddesc.idProduct),
 		    res.udev->ddesc.bDeviceClass,
 		    res.udev->ddesc.bDeviceSubClass,
-		    res.udev->serial,
+		    usb_get_serial(res.udev),
 		    UGETW(res.udev->ddesc.bcdDevice),
 		    iface->idesc->bInterfaceClass,
 		    iface->idesc->bInterfaceSubClass);
diff --git a/sys/dev/usb/usbdi_util.h b/sys/dev/usb/usbdi_util.h
index bb6e324ab97..352f3ff1c71 100644
--- a/sys/dev/usb/usbdi_util.h
+++ b/sys/dev/usb/usbdi_util.h
@@ -78,4 +78,11 @@ usb_error_t usbd_req_set_protocol(struct usb_device *udev, struct mtx *mtx,
 usb_error_t usbd_req_set_report(struct usb_device *udev, struct mtx *mtx,
 		    void *data, uint16_t len, uint8_t iface_index,
 		    uint8_t type, uint8_t id);
+
+/* The following functions will not return NULL strings. */
+
+const char *usb_get_manufacturer(struct usb_device *);
+const char *usb_get_product(struct usb_device *);
+const char *usb_get_serial(struct usb_device *);
+
 #endif /* _USB_USBDI_UTIL_H_ */

From a1482dccab8920a402aa22dbebcd524c1a6f6d89 Mon Sep 17 00:00:00 2001
From: Maxim Konovalov 
Date: Thu, 2 Sep 2010 05:07:34 +0000
Subject: [PATCH 0450/1624] o csup(1) does not have -g flag.  Remove it from
 the example.

PR:		conf/150214
Submitted by:	Li
MFC after:	1 week
---
 share/examples/etc/make.conf | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/share/examples/etc/make.conf b/share/examples/etc/make.conf
index 128a04ac64f..93fcabf3283 100644
--- a/share/examples/etc/make.conf
+++ b/share/examples/etc/make.conf
@@ -180,7 +180,7 @@
 #SUP_UPDATE=
 #
 #SUP=            /usr/bin/csup
-#SUPFLAGS=       -g -L 2
+#SUPFLAGS=       -L 2
 #SUPHOST=        cvsup.uk.FreeBSD.org
 #SUPFILE=        /usr/share/examples/cvsup/standard-supfile
 #PORTSSUPFILE=   /usr/share/examples/cvsup/ports-supfile

From a250a687f75ef4acd6d863e68ea292c071b2ed28 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Thu, 2 Sep 2010 11:18:43 +0000
Subject: [PATCH 0451/1624] SATA1.x SiliconImage controllers on power-on reset
 TFD Status register into value 0xff. On hot-plug this value confuses
 ata_generic_reset() device presence detection logic. As soon as we already
 know drive presence from SATA hard reset, hint ata_generic_reset() to wait
 for device signature until success or full timeout.

---
 sys/dev/ata/ata-all.h                   |  1 +
 sys/dev/ata/ata-lowlevel.c              | 30 +++++++++++--------------
 sys/dev/ata/chipsets/ata-siliconimage.c |  1 +
 3 files changed, 15 insertions(+), 17 deletions(-)

diff --git a/sys/dev/ata/ata-all.h b/sys/dev/ata/ata-all.h
index 87226cc11f2..6132eab4101 100644
--- a/sys/dev/ata/ata-all.h
+++ b/sys/dev/ata/ata-all.h
@@ -565,6 +565,7 @@ struct ata_channel {
 #define         ATA_NO_ATAPI_DMA	0x40
 #define         ATA_SATA		0x80
 #define         ATA_DMA_BEFORE_CMD	0x100
+#define         ATA_KNOWN_PRESENCE	0x200
 
     int				pm_level;	/* power management level */
     int                         devices;        /* what is present */
diff --git a/sys/dev/ata/ata-lowlevel.c b/sys/dev/ata/ata-lowlevel.c
index 6c196d60a44..91748233e5c 100644
--- a/sys/dev/ata/ata-lowlevel.c
+++ b/sys/dev/ata/ata-lowlevel.c
@@ -474,7 +474,8 @@ ata_generic_reset(device_t dev)
     ATA_IDX_OUTB(ch, ATA_DRIVE, ATA_D_IBM | ATA_D_LBA | ATA_DEV(ATA_MASTER));
     DELAY(10);
     ostat0 = ATA_IDX_INB(ch, ATA_STATUS);
-    if ((ostat0 & 0xf8) != 0xf8 && ostat0 != 0xa5) {
+    if (((ostat0 & 0xf8) != 0xf8 || (ch->flags & ATA_KNOWN_PRESENCE)) &&
+	    ostat0 != 0xa5) {
 	stat0 = ATA_S_BUSY;
 	mask |= 0x01;
     }
@@ -484,7 +485,8 @@ ata_generic_reset(device_t dev)
 	ATA_IDX_OUTB(ch, ATA_DRIVE, ATA_D_IBM | ATA_D_LBA | ATA_DEV(ATA_SLAVE));
 	DELAY(10);      
 	ostat1 = ATA_IDX_INB(ch, ATA_STATUS);
-	if ((ostat1 & 0xf8) != 0xf8 && ostat1 != 0xa5) {
+	if (((ostat1 & 0xf8) != 0xf8 || (ch->flags & ATA_KNOWN_PRESENCE)) &&
+		ostat1 != 0xa5) {
 	    stat1 = ATA_S_BUSY;
 	    mask |= 0x02;
 	}
@@ -570,22 +572,16 @@ ata_generic_reset(device_t dev)
 	    }
 	}
 
-	if (mask == 0x00)       /* nothing to wait for */
-	    break;
-	if (mask == 0x01)       /* wait for master only */
-	    if (!(stat0 & ATA_S_BUSY) || (stat0 == 0xff && timeout > 10))
-		break;
-	if (mask == 0x02)       /* wait for slave only */
-	    if (!(stat1 & ATA_S_BUSY) || (stat1 == 0xff && timeout > 10))
-		break;
-	if (mask == 0x03) {     /* wait for both master & slave */
-	    if (!(stat0 & ATA_S_BUSY) && !(stat1 & ATA_S_BUSY))
-		break;
-	    if ((stat0 == 0xff) && (timeout > 20))
-		mask &= ~0x01;
-	    if ((stat1 == 0xff) && (timeout > 20))
-		mask &= ~0x02;
+	if ((ch->flags & ATA_KNOWN_PRESENCE) == 0 &&
+	    timeout > ((mask == 0x03) ? 20 : 10)) {
+		if ((mask & 0x01) && stat0 == 0xff)
+			mask &= ~0x01;
+		if ((mask & 0x02) && stat1 == 0xff)
+			mask &= ~0x02;
 	}
+	if (((mask & 0x01) == 0 || !(stat0 & ATA_S_BUSY)) &&
+	    ((mask & 0x02) == 0 || !(stat1 & ATA_S_BUSY)))
+		break;
 	ata_udelay(100000);
     }
 
diff --git a/sys/dev/ata/chipsets/ata-siliconimage.c b/sys/dev/ata/chipsets/ata-siliconimage.c
index 31d1878a110..ff22f070d2e 100644
--- a/sys/dev/ata/chipsets/ata-siliconimage.c
+++ b/sys/dev/ata/chipsets/ata-siliconimage.c
@@ -316,6 +316,7 @@ ata_sii_ch_attach(device_t dev)
 	ch->r_io[ATA_SCONTROL].offset = 0x100 + (unit01 << 7) + (unit10 << 8);
 	ch->flags |= ATA_NO_SLAVE;
 	ch->flags |= ATA_SATA;
+	ch->flags |= ATA_KNOWN_PRESENCE;
 
 	/* enable PHY state change interrupt */
 	ATA_OUTL(ctlr->r_res2, 0x148 + (unit01 << 7) + (unit10 << 8),(1 << 16));

From a6c48c7c72eed385a78fc591e89346e80936d33a Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Thu, 2 Sep 2010 12:32:29 +0000
Subject: [PATCH 0452/1624] Add fix for SiI3114 and SiI3512 chips bug, which
 caused sending R_ERR in response to DMA activate FIS under certain
 circumstances. This is recommended fix from chip datasheet. If triggered,
 this bug most likely cause write command timeout.

MFC after:	2 weeks
---
 sys/dev/ata/chipsets/ata-siliconimage.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/sys/dev/ata/chipsets/ata-siliconimage.c b/sys/dev/ata/chipsets/ata-siliconimage.c
index ff22f070d2e..0fe4e1c0356 100644
--- a/sys/dev/ata/chipsets/ata-siliconimage.c
+++ b/sys/dev/ata/chipsets/ata-siliconimage.c
@@ -365,7 +365,15 @@ ata_sii_status(device_t dev)
 static void
 ata_sii_reset(device_t dev)
 {
+    struct ata_pci_controller *ctlr = device_get_softc(device_get_parent(dev));
     struct ata_channel *ch = device_get_softc(dev);
+    int offset = ((ch->unit & 1) << 7) + ((ch->unit & 2) << 8);
+    uint32_t val;
+
+    /* Apply R_ERR on DMA activate FIS errata workaround. */
+    val = ATA_INL(ctlr->r_res2, 0x14c + offset);
+    if ((val & 0x3) == 0x1)
+	ATA_OUTL(ctlr->r_res2, 0x14c + offset, val & ~0x3);
 
     if (ata_sata_phy_reset(dev, -1, 1))
 	ata_generic_reset(dev);

From 2d15ca416ed4032ecf7ee7b13698eeb88d48c6c1 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Thu, 2 Sep 2010 14:05:32 +0000
Subject: [PATCH 0453/1624] Remove trailing whitespace.

---
 sys/sys/copyright.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/copyright.h b/sys/sys/copyright.h
index 62a4ac9d920..b70782da085 100644
--- a/sys/sys/copyright.h
+++ b/sys/sys/copyright.h
@@ -27,7 +27,7 @@
 
 
 /* Copyrights macros  */
-  
+
 /* FreeBSD */
 #define COPYRIGHT_FreeBSD \
 	"Copyright (c) 1992-2010 The FreeBSD Project.\n"

From 2cd149f045771469a80a7b5d0b72b399749750a9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Thu, 2 Sep 2010 14:13:43 +0000
Subject: [PATCH 0454/1624] Remove the freelist, which simply duplicates some
 of the zone allocator's functionality.

Submitted by:	Daniel Braniss 
MFC after:	3 weeks
---
 sys/dev/iscsi/initiator/iscsi.c    | 14 --------------
 sys/dev/iscsi/initiator/iscsivar.h | 19 ++-----------------
 2 files changed, 2 insertions(+), 31 deletions(-)

diff --git a/sys/dev/iscsi/initiator/iscsi.c b/sys/dev/iscsi/initiator/iscsi.c
index 2eee8120d2b..5d7a5b7f720 100644
--- a/sys/dev/iscsi/initiator/iscsi.c
+++ b/sys/dev/iscsi/initiator/iscsi.c
@@ -295,12 +295,6 @@ iscsi_read(struct cdev *dev, struct uio *uio, int ioflag)
 	  sprintf(buf, "%d/%d /---- free -----/\n", sc->npdu_alloc, sc->npdu_max);
 	  i = 0;
 	  uiomove(buf, strlen(buf), uio);
-	  TAILQ_FOREACH(pq, &sc->freepdu, pq_link) {
-	       if(uio->uio_resid == 0)
-		    return 0;
-	       sprintf(buf, "%03d] %06x\n", i++, ntohl(pq->pdu.ipdu.bhs.itt));
-	       uiomove(buf, strlen(buf), uio);
-	  }
      }
      else {
 	  int	i = 0;
@@ -704,15 +698,10 @@ iscsi_shutdown(void *v)
 static void
 free_pdus(struct isc_softc *sc)
 {
-     pduq_t	*pq;
 
      debug_called(8);
 
      if(sc->pdu_zone != NULL) {
-	  TAILQ_FOREACH(pq, &sc->freepdu, pq_link) {
-	       TAILQ_REMOVE(&sc->freepdu, pq, pq_link);
-	       uma_zfree(sc->pdu_zone, pq);
-	  }
 	  uma_zdestroy(sc->pdu_zone);
 	  sc->pdu_zone = NULL;
      }
@@ -730,7 +719,6 @@ iscsi_start(void)
      isc->dev = make_dev(&iscsi_cdevsw, max_sessions, UID_ROOT, GID_WHEEL, 0600, "iscsi");
      isc->dev->si_drv1 = isc;
      mtx_init(&isc->isc_mtx, "iscsi", NULL, MTX_DEF);
-     mtx_init(&isc->pdu_mtx, "iscsi pdu pool", NULL, MTX_DEF);
 
      TAILQ_INIT(&isc->isc_sess);
      /*
@@ -744,7 +732,6 @@ iscsi_start(void)
 	  // XXX: should fail...
      }
      uma_zone_set_max(isc->pdu_zone, max_pdus);
-     TAILQ_INIT(&isc->freepdu);
      isc->unit = new_unrhdr(0, max_sessions-1, NULL);
      sx_init(&isc->unit_sx, "iscsi sx");
 
@@ -818,7 +805,6 @@ iscsi_stop(void)
 	       ic_destroy(sp);
      }
      mtx_destroy(&isc->isc_mtx);
-     mtx_destroy(&isc->pdu_mtx);
      sx_destroy(&isc->unit_sx);
 
      free_pdus(isc);
diff --git a/sys/dev/iscsi/initiator/iscsivar.h b/sys/dev/iscsi/initiator/iscsivar.h
index a6eae21ee03..0a56f800e84 100644
--- a/sys/dev/iscsi/initiator/iscsivar.h
+++ b/sys/dev/iscsi/initiator/iscsivar.h
@@ -203,10 +203,7 @@ struct isc_softc {
      struct unrhdr	*unit;
      struct sx 		unit_sx;
 
-     struct mtx		pdu_mtx;
      uma_zone_t		pdu_zone;	// pool of free pdu's
-     TAILQ_HEAD(,pduq)	freepdu;
-
 #ifdef  ISCSI_INITIATOR_DEBUG
      int		 npdu_alloc, npdu_max; // for instrumentation
 #endif
@@ -303,25 +300,15 @@ pdu_alloc(struct isc_softc *isc, int wait)
 {
      pduq_t	*pq;
 
-     mtx_lock(&isc->pdu_mtx);
-     if((pq = TAILQ_FIRST(&isc->freepdu)) == NULL) {
-	  mtx_unlock(&isc->pdu_mtx);
-	  pq = (pduq_t *)uma_zalloc(isc->pdu_zone, wait /* M_WAITOK or M_NOWAIT*/);
-     }
-     else {
-	  TAILQ_REMOVE(&isc->freepdu, pq, pq_link);
-	  mtx_unlock(&isc->pdu_mtx);
-     }
+     pq = (pduq_t *)uma_zalloc(isc->pdu_zone, wait /* M_WAITOK or M_NOWAIT*/);
      if(pq == NULL) {
 	  debug(7, "out of mem");
 	  return NULL;
      }
 #ifdef ISCSI_INITIATOR_DEBUG
-     mtx_lock(&isc->pdu_mtx);
      isc->npdu_alloc++;
      if(isc->npdu_alloc > isc->npdu_max)
 	  isc->npdu_max = isc->npdu_alloc;
-     mtx_unlock(&isc->pdu_mtx);
 #endif
      memset(pq, 0, sizeof(pduq_t));
 
@@ -337,12 +324,10 @@ pdu_free(struct isc_softc *isc, pduq_t *pq)
      if(pq->buf != NULL)
 	  free(pq->buf, M_ISCSIBUF);
 #endif
-     mtx_lock(&isc->pdu_mtx);
-     TAILQ_INSERT_TAIL(&isc->freepdu, pq, pq_link);
 #ifdef ISCSI_INITIATOR_DEBUG
      isc->npdu_alloc--;
 #endif
-     mtx_unlock(&isc->pdu_mtx);
+     uma_zfree(isc->pdu_zone, pq);
 }
 
 static __inline void

From 73e39d6137a6b7050b80b3e481983baa75da4ea7 Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Thu, 2 Sep 2010 16:11:12 +0000
Subject: [PATCH 0455/1624] MFp4 CH=183259:

  No reason to use if_free_type() as we don't change our type.
  Just if_free() is fine.

MFC after:	3 days
---
 sys/net/if_epair.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/net/if_epair.c b/sys/net/if_epair.c
index ac0c8018702..2f623308c3d 100644
--- a/sys/net/if_epair.c
+++ b/sys/net/if_epair.c
@@ -892,9 +892,9 @@ epair_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
 	 * we need to switch before freeing them.
 	 */
 	CURVNET_SET_QUIET(oifp->if_vnet);
-	if_free_type(oifp, IFT_ETHER);
+	if_free(oifp);
 	CURVNET_RESTORE();
-	if_free_type(ifp, IFT_ETHER);
+	if_free(ifp);
 	free(scb, M_EPAIR);
 	free(sca, M_EPAIR);
 	ifc_free_unit(ifc, unit);

From ba4932b5a2af2e0ae5abc9a2cea641d453123e06 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 2 Sep 2010 16:23:05 +0000
Subject: [PATCH 0456/1624] Fix UP build.

MFC after:	2 weeks
---
 sys/kern/sched_ule.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/kern/sched_ule.c b/sys/kern/sched_ule.c
index 8e4a7babc1c..0162b6417d7 100644
--- a/sys/kern/sched_ule.c
+++ b/sys/kern/sched_ule.c
@@ -1797,8 +1797,10 @@ sched_switch(struct thread *td, struct thread *newtd, int flags)
 		srqflag = (flags & SW_PREEMPT) ?
 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
 		    SRQ_OURSELF|SRQ_YIELDING;
+#ifdef SMP
 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
 			ts->ts_cpu = sched_pickcpu(td, 0);
+#endif
 		if (ts->ts_cpu == cpuid)
 			tdq_runq_add(tdq, td, srqflag);
 		else {

From 90017de9994add1373c2dd6c0d633f5752d21a03 Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Thu, 2 Sep 2010 17:22:12 +0000
Subject: [PATCH 0457/1624] Disable video ROM shadowing by default as I
 originally intended.  I found a case where video ROM for an IGP is too
 tightly coupled with system BIOS to get relocated.

---
 sys/dev/fb/vesa.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/fb/vesa.c b/sys/dev/fb/vesa.c
index 68f184b5c8e..4cb3fb5895e 100644
--- a/sys/dev/fb/vesa.c
+++ b/sys/dev/fb/vesa.c
@@ -96,10 +96,10 @@ static size_t vesa_bios_size = 0;
 static video_adapter_t *vesa_adp = NULL;
 
 SYSCTL_NODE(_debug, OID_AUTO, vesa, CTLFLAG_RD, NULL, "VESA debugging");
-static int vesa_shadow_rom = 1;
+static int vesa_shadow_rom = 0;
 TUNABLE_INT("debug.vesa.shadow_rom", &vesa_shadow_rom);
 SYSCTL_INT(_debug_vesa, OID_AUTO, shadow_rom, CTLFLAG_RDTUN, &vesa_shadow_rom,
-    1, "Enable video BIOS shadow");
+    0, "Enable video BIOS shadow");
 
 /* VESA functions */
 #if 0

From 1b48d24533a92382a51a3b45c0386a254784d97b Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Thu, 2 Sep 2010 17:43:44 +0000
Subject: [PATCH 0458/1624] MFp4 CH=183052 183053 183258:

  In protosw we define pr_protocol as short, while on the wire
  it is an uint8_t.  That way we can have "internal" protocols
  like DIVERT, SEND or gaps for modules (PROTO_SPACER).
  Switch ipproto_{un,}register to accept a short protocol number(*)
  and do an upfront check for valid boundries. With this we
  also consistently report EPROTONOSUPPORT for out of bounds
  protocols, as we did for proto == 0.  This allows a caller
  to not error for this case, which is especially important
  if we want to automatically call these from domain handling.

  (*) the functions have been without any in-tree consumer
  since the initial introducation, so this is considered save.

  Implement ip6proto_{un,}register() similarly to their legacy IP
  counter parts to allow modules to hook up dynamically.

Reviewed by:	philip, will
MFC after:	1 week
---
 sys/netinet/ip_input.c   | 16 +++++------
 sys/netinet/ip_var.h     |  4 +--
 sys/netinet6/ip6_input.c | 58 ++++++++++++++++++++++++++++++++++++++++
 sys/netinet6/ip6_var.h   |  3 +++
 4 files changed, 69 insertions(+), 12 deletions(-)

diff --git a/sys/netinet/ip_input.c b/sys/netinet/ip_input.c
index 40b494a640b..6e1153d0b73 100644
--- a/sys/netinet/ip_input.c
+++ b/sys/netinet/ip_input.c
@@ -1287,12 +1287,12 @@ ip_drain(void)
  * in inetsw[], either statically or through pf_proto_register().
  */
 int
-ipproto_register(u_char ipproto)
+ipproto_register(short ipproto)
 {
 	struct protosw *pr;
 
 	/* Sanity checks. */
-	if (ipproto == 0)
+	if (ipproto <= 0 || ipproto >= IPPROTO_MAX)
 		return (EPROTONOSUPPORT);
 
 	/*
@@ -1310,24 +1310,20 @@ ipproto_register(u_char ipproto)
 	     pr < inetdomain.dom_protoswNPROTOSW; pr++) {
 		if (pr->pr_domain->dom_family == PF_INET &&
 		    pr->pr_protocol && pr->pr_protocol == ipproto) {
-			/* Be careful to only index valid IP protocols. */
-			if (pr->pr_protocol < IPPROTO_MAX) {
-				ip_protox[pr->pr_protocol] = pr - inetsw;
-				return (0);
-			} else
-				return (EINVAL);
+			ip_protox[pr->pr_protocol] = pr - inetsw;
+			return (0);
 		}
 	}
 	return (EPROTONOSUPPORT);
 }
 
 int
-ipproto_unregister(u_char ipproto)
+ipproto_unregister(short ipproto)
 {
 	struct protosw *pr;
 
 	/* Sanity checks. */
-	if (ipproto == 0)
+	if (ipproto <= 0 || ipproto >= IPPROTO_MAX)
 		return (EPROTONOSUPPORT);
 
 	/* Check if the protocol was indeed registered. */
diff --git a/sys/netinet/ip_var.h b/sys/netinet/ip_var.h
index 4415001fc27..222b7efea51 100644
--- a/sys/netinet/ip_var.h
+++ b/sys/netinet/ip_var.h
@@ -220,8 +220,8 @@ extern int
 int	ip_output(struct mbuf *,
 	    struct mbuf *, struct route *, int, struct ip_moptions *,
 	    struct inpcb *);
-int	ipproto_register(u_char);
-int	ipproto_unregister(u_char);
+int	ipproto_register(short);
+int	ipproto_unregister(short);
 struct mbuf *
 	ip_reass(struct mbuf *);
 struct in_ifaddr *
diff --git a/sys/netinet6/ip6_input.c b/sys/netinet6/ip6_input.c
index ec822502b60..7e650a24621 100644
--- a/sys/netinet6/ip6_input.c
+++ b/sys/netinet6/ip6_input.c
@@ -227,6 +227,64 @@ ip6_init(void)
 	netisr_register(&ip6_nh);
 }
 
+/*
+ * The protocol to be inserted into ip6_protox[] must be already registered
+ * in inet6sw[], either statically or through pf_proto_register().
+ */
+int
+ip6proto_register(short ip6proto)
+{
+	struct ip6protosw *pr;
+
+	/* Sanity checks. */
+	if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
+		return (EPROTONOSUPPORT);
+
+	/*
+	 * The protocol slot must not be occupied by another protocol
+	 * already.  An index pointing to IPPROTO_RAW is unused.
+	 */
+	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
+	if (pr == NULL)
+		return (EPFNOSUPPORT);
+	if (ip6_protox[ip6proto] != pr - inet6sw)	/* IPPROTO_RAW */
+		return (EEXIST);
+
+	/*
+	 * Find the protocol position in inet6sw[] and set the index.
+	 */
+	for (pr = (struct ip6protosw *)inet6domain.dom_protosw;
+	    pr < (struct ip6protosw *)inet6domain.dom_protoswNPROTOSW; pr++) {
+		if (pr->pr_domain->dom_family == PF_INET6 &&
+		    pr->pr_protocol && pr->pr_protocol == ip6proto) {
+			ip6_protox[pr->pr_protocol] = pr - inet6sw;
+			return (0);
+		}
+	}
+	return (EPROTONOSUPPORT);
+}
+
+int
+ip6proto_unregister(short ip6proto)
+{
+	struct ip6protosw *pr;
+
+	/* Sanity checks. */
+	if (ip6proto <= 0 || ip6proto >= IPPROTO_MAX)
+		return (EPROTONOSUPPORT);
+
+	/* Check if the protocol was indeed registered. */
+	pr = (struct ip6protosw *)pffindproto(PF_INET6, IPPROTO_RAW, SOCK_RAW);
+	if (pr == NULL)
+		return (EPFNOSUPPORT);
+	if (ip6_protox[ip6proto] == pr - inet6sw)	/* IPPROTO_RAW */
+		return (ENOENT);
+
+	/* Reset the protocol slot to IPPROTO_RAW. */
+	ip6_protox[ip6proto] = pr - inet6sw;
+	return (0);
+}
+
 #ifdef VIMAGE
 void
 ip6_destroy()
diff --git a/sys/netinet6/ip6_var.h b/sys/netinet6/ip6_var.h
index 3e91a79d0b9..51ae1f74957 100644
--- a/sys/netinet6/ip6_var.h
+++ b/sys/netinet6/ip6_var.h
@@ -368,6 +368,9 @@ void	ip6_init __P((void));
 #ifdef VIMAGE
 void	ip6_destroy __P((void));
 #endif
+int	ip6proto_register(short);
+int	ip6proto_unregister(short);
+
 void	ip6_input __P((struct mbuf *));
 struct in6_ifaddr *ip6_getdstifaddr __P((struct mbuf *));
 void	ip6_freepcbopts __P((struct ip6_pktopts *));

From 74e8a3238f9e0169b0dfcff9165993cb376ea485 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 17:51:41 +0000
Subject: [PATCH 0459/1624] Fix the last endianness issue on handling station
 address which prevented driver from working on big-endian machines. Also
 rewrite station address programming to make it work on strict-alignment
 architectures. With this change, sis(4) now works on sparc64 and performance
 number looks good even though sis(4) have to apply fixup code to align
 received frames on 2 bytes boundary on sparc64.

---
 sys/dev/sis/if_sis.c | 27 ++++++++++++++-------------
 1 file changed, 14 insertions(+), 13 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 46d7b1f83c1..ee12a9c8df0 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -1057,7 +1057,12 @@ sis_attach(device_t dev)
 			tmp[2] = sis_reverse(tmp[2]);
 			tmp[1] = sis_reverse(tmp[1]);
 
-			bcopy((char *)&tmp[1], eaddr, ETHER_ADDR_LEN);
+			eaddr[0] = (tmp[1] >> 0) & 0xFF;
+			eaddr[1] = (tmp[1] >> 8) & 0xFF;
+			eaddr[2] = (tmp[2] >> 0) & 0xFF;
+			eaddr[3] = (tmp[2] >> 8) & 0xFF;
+			eaddr[4] = (tmp[3] >> 0) & 0xFF;
+			eaddr[5] = (tmp[3] >> 8) & 0xFF;
 		}
 		break;
 	case SIS_VENDORID:
@@ -1967,6 +1972,7 @@ sis_initl(struct sis_softc *sc)
 {
 	struct ifnet		*ifp = sc->sis_ifp;
 	struct mii_data		*mii;
+	uint8_t			*eaddr;
 
 	SIS_LOCK_ASSERT(sc);
 
@@ -1994,26 +2000,21 @@ sis_initl(struct sis_softc *sc)
 	mii = device_get_softc(sc->sis_miibus);
 
 	/* Set MAC address */
+	eaddr = IF_LLADDR(sc->sis_ifp);
 	if (sc->sis_type == SIS_TYPE_83815) {
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, NS_FILTADDR_PAR0);
-		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[0]);
+		CSR_WRITE_4(sc, SIS_RXFILT_DATA, eaddr[0] | eaddr[1] << 8);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, NS_FILTADDR_PAR1);
-		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[1]);
+		CSR_WRITE_4(sc, SIS_RXFILT_DATA, eaddr[2] | eaddr[3] << 8);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, NS_FILTADDR_PAR2);
-		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[2]);
+		CSR_WRITE_4(sc, SIS_RXFILT_DATA, eaddr[4] | eaddr[5] << 8);
 	} else {
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR0);
-		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[0]);
+		CSR_WRITE_4(sc, SIS_RXFILT_DATA, eaddr[0] | eaddr[1] << 8);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR1);
-		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[1]);
+		CSR_WRITE_4(sc, SIS_RXFILT_DATA, eaddr[2] | eaddr[3] << 8);
 		CSR_WRITE_4(sc, SIS_RXFILT_CTL, SIS_FILTADDR_PAR2);
-		CSR_WRITE_4(sc, SIS_RXFILT_DATA,
-		    ((uint16_t *)IF_LLADDR(sc->sis_ifp))[2]);
+		CSR_WRITE_4(sc, SIS_RXFILT_DATA, eaddr[4] | eaddr[5] << 8);
 	}
 
 	/* Init circular TX/RX lists. */

From 94222398d1f0fdb60d4c85cc1badea19b8fbe947 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 18:10:11 +0000
Subject: [PATCH 0460/1624] Unlike most other controllers, NS DP83815/DP83816
 controllers seem to pad with 0xFF when it encounter short frames.  According
 to RFC 1042 the pad bytes should be 0x00. Because manual padding consumes
 extra CPU cycles, introduce a new tunable which controls the padding
 behavior. Turning this tunable on will have driver pad manually but it's
 disabled by default. Users can enable software padding by setting the
 following tunable to non-zero value.

dev.sis.%d.manual_pad="1"

PR:	kern/35422 (patch not used)
---
 sys/dev/sis/if_sis.c    | 86 ++++++++++++++++++++++++++++++++++++-----
 sys/dev/sis/if_sisreg.h |  5 ++-
 2 files changed, 81 insertions(+), 10 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index ee12a9c8df0..ceff6b8d351 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -73,6 +73,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -150,6 +151,7 @@ static int sis_rxeof(struct sis_softc *);
 static void sis_start(struct ifnet *);
 static void sis_startl(struct ifnet *);
 static void sis_stop(struct sis_softc *);
+static void sis_add_sysctls(struct sis_softc *);
 static void sis_watchdog(struct sis_softc *);
 
 
@@ -710,24 +712,24 @@ sis_miibus_statchg(device_t dev)
 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
 		return;
 
-	sc->sis_link = 0;
+	sc->sis_flags &= ~SIS_FLAG_LINK;
 	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
 	    (IFM_ACTIVE | IFM_AVALID)) {
 		switch (IFM_SUBTYPE(mii->mii_media_active)) {
 		case IFM_10_T:
-			sc->sis_link++;
 			CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_10);
+			sc->sis_flags |= SIS_FLAG_LINK;
 			break;
 		case IFM_100_TX:
-			sc->sis_link++;
 			CSR_WRITE_4(sc, SIS_TX_CFG, SIS_TXCFG_100);
+			sc->sis_flags |= SIS_FLAG_LINK;
 			break;
 		default:
 			break;
 		}
 	}
 
-	if (sc->sis_link == 0) {
+	if ((sc->sis_flags & SIS_FLAG_LINK) == 0) {
 		/*
 		 * Stopping MACs seem to reset SIS_TX_LISTPTR and
 		 * SIS_RX_LISTPTR which in turn requires resetting
@@ -1122,6 +1124,8 @@ sis_attach(device_t dev)
 		break;
 	}
 
+	sis_add_sysctls(sc);
+
 	/* Allocate DMA'able memory. */
 	if ((error = sis_dma_alloc(sc)) != 0)
 		goto fail;
@@ -1698,7 +1702,7 @@ sis_tick(void *xsc)
 	mii = device_get_softc(sc->sis_miibus);
 	mii_tick(mii);
 	sis_watchdog(sc);
-	if (sc->sis_link == 0)
+	if ((sc->sis_flags & SIS_FLAG_LINK) == 0)
 		sis_miibus_statchg(sc->sis_dev);
 	callout_reset(&sc->sis_stat_ch, hz,  sis_tick, sc);
 }
@@ -1829,9 +1833,41 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head)
 	bus_dma_segment_t	segs[SIS_MAXTXSEGS];
 	bus_dmamap_t		map;
 	int			error, i, frag, nsegs, prod;
+	int			padlen;
 
 	prod = sc->sis_tx_prod;
 	txd = &sc->sis_txdesc[prod];
+	if ((sc->sis_flags & SIS_FLAG_MANUAL_PAD) != 0 &&
+	    (*m_head)->m_pkthdr.len < SIS_MIN_FRAMELEN) {
+		m = *m_head;
+		padlen = SIS_MIN_FRAMELEN - m->m_pkthdr.len;
+		if (M_WRITABLE(m) == 0) {
+			/* Get a writable copy. */
+			m = m_dup(*m_head, M_DONTWAIT);
+			m_freem(*m_head);
+			if (m == NULL) {
+				*m_head = NULL;
+				return (ENOBUFS);
+			}
+			*m_head = m;
+		}
+		if (m->m_next != NULL || M_TRAILINGSPACE(m) < padlen) {
+			m = m_defrag(m, M_DONTWAIT);
+			if (m == NULL) {
+				m_freem(*m_head);
+				*m_head = NULL;
+				return (ENOBUFS);
+			}
+		}
+		/*
+		 * Manually pad short frames, and zero the pad space
+		 * to avoid leaking data.
+		 */
+		bzero(mtod(m, char *) + m->m_pkthdr.len, padlen);
+		m->m_pkthdr.len += padlen;
+		m->m_len = m->m_pkthdr.len;
+		*m_head = m;
+	}
 	error = bus_dmamap_load_mbuf_sg(sc->sis_tx_tag, txd->tx_dmamap,
 	    *m_head, segs, &nsegs, 0);
 	if (error == EFBIG) {
@@ -1918,7 +1954,7 @@ sis_startl(struct ifnet *ifp)
 	SIS_LOCK_ASSERT(sc);
 
 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
-	    IFF_DRV_RUNNING || sc->sis_link == 0)
+	    IFF_DRV_RUNNING || (sc->sis_flags & SIS_FLAG_LINK) == 0)
 		return;
 
 	for (queued = 0; !IFQ_DRV_IS_EMPTY(&ifp->if_snd) &&
@@ -2025,6 +2061,13 @@ sis_initl(struct sis_softc *sc)
 		return;
 	}
 
+	if (sc->sis_type == SIS_TYPE_83815 || sc->sis_type == SIS_TYPE_83816) {
+		if (sc->sis_manual_pad != 0)
+			sc->sis_flags |= SIS_FLAG_MANUAL_PAD;
+		else
+			sc->sis_flags &= ~SIS_FLAG_MANUAL_PAD;
+	}
+
 	/*
 	 * Short Cable Receive Errors (MP21.E)
 	 * also: Page 78 of the DP83815 data sheet (september 2002 version)
@@ -2125,7 +2168,7 @@ sis_initl(struct sis_softc *sc)
 	/* Clear MAC disable. */
 	SIS_CLRBIT(sc, SIS_CSR, SIS_CSR_TX_DISABLE | SIS_CSR_RX_DISABLE);
 
-	sc->sis_link = 0;
+	sc->sis_flags &= ~SIS_FLAG_LINK;
 	mii_mediachg(mii);
 
 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
@@ -2148,7 +2191,6 @@ sis_ifmedia_upd(struct ifnet *ifp)
 
 	SIS_LOCK(sc);
 	mii = device_get_softc(sc->sis_miibus);
-	sc->sis_link = 0;
 	if (mii->mii_instance) {
 		struct mii_softc	*miisc;
 		LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
@@ -2304,7 +2346,7 @@ sis_stop(struct sis_softc *sc)
 	CSR_WRITE_4(sc, SIS_TX_LISTPTR, 0);
 	CSR_WRITE_4(sc, SIS_RX_LISTPTR, 0);
 
-	sc->sis_link = 0;
+	sc->sis_flags &= ~SIS_FLAG_LINK;
 
 	/*
 	 * Free data in the RX lists.
@@ -2351,6 +2393,32 @@ sis_shutdown(device_t dev)
 	return (0);
 }
 
+static void
+sis_add_sysctls(struct sis_softc *sc)
+{
+	struct sysctl_ctx_list *ctx;
+	struct sysctl_oid_list *children;
+	char tn[32];
+	int unit;
+
+	ctx = device_get_sysctl_ctx(sc->sis_dev);
+	children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->sis_dev));
+
+	unit = device_get_unit(sc->sis_dev);
+	/*
+	 * Unlike most other controllers, NS DP83815/DP83816 controllers
+	 * seem to pad with 0xFF when it encounter short frames.  According
+	 * to RFC 1042 the pad bytes should be 0x00.  Turning this tunable
+	 * on will have driver pad manully but it's disabled by default
+	 * because it will consume extra CPU cycles for short frames.
+	 */
+	sc->sis_manual_pad = 0;
+	snprintf(tn, sizeof(tn), "dev.sis.%d.manual_pad", unit);
+	TUNABLE_INT_FETCH(tn, &sc->sis_manual_pad);
+	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "manual_pad",
+	    CTLFLAG_RW, &sc->sis_manual_pad, 0, "Manually pad short frames");
+}
+
 static device_method_t sis_methods[] = {
 	/* Device interface */
 	DEVMETHOD(device_probe,		sis_probe),
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 5bcdcae03e0..42181a19e94 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -449,7 +449,10 @@ struct sis_softc {
 	device_t		sis_miibus;
 	uint8_t			sis_type;
 	uint8_t			sis_rev;
-	uint8_t			sis_link;
+	uint32_t		sis_flags;
+#define	SIS_FLAG_MANUAL_PAD	0x0800
+#define	SIS_FLAG_LINK		0x8000
+	int			sis_manual_pad;
 	uint32_t		sis_srr;
 	struct sis_desc		*sis_rx_list;
 	struct sis_desc		*sis_tx_list;

From 57ec924c7769ebc555bcf016497c8ef2870e7784 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 18:12:54 +0000
Subject: [PATCH 0461/1624] Enable sis(4). sis(4) should work on all
 architectures.

---
 sys/sparc64/conf/GENERIC | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sparc64/conf/GENERIC b/sys/sparc64/conf/GENERIC
index 1e0a0f26d2c..953ee70d2d4 100644
--- a/sys/sparc64/conf/GENERIC
+++ b/sys/sparc64/conf/GENERIC
@@ -185,7 +185,7 @@ device		nge		# NatSemi DP83820 gigabit Ethernet
 device		re		# RealTek 8139C+/8169/8169S/8110S
 device		rl		# RealTek 8129/8139
 device		sf		# Adaptec AIC-6915 (``Starfire'')
-#device		sis		# Silicon Integrated Systems SiS 900/SiS 7016
+device		sis		# Silicon Integrated Systems SiS 900/SiS 7016
 device		sk		# SysKonnect SK-984x & SK-982x gigabit Ethernet
 device		ste		# Sundance ST201 (D-Link DFE-550TX)
 device		stge		# Sundance/Tamarack TC9021 gigabit Ethernet

From f0092b8fc81776d5fe0c74d7637db17cffcd1eb9 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 18:22:06 +0000
Subject: [PATCH 0462/1624] Document tunable dev.sis.%unit.manual_pad While I'm
 here Xref vlan(4) as sis(4) supports VLAN oversized frames.

---
 share/man/man4/sis.4 | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/sis.4 b/share/man/man4/sis.4
index 6ee0c6af012..2290f67e6f3 100644
--- a/share/man/man4/sis.4
+++ b/share/man/man4/sis.4
@@ -30,7 +30,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd October 28, 2006
+.Dd September 2, 2010
 .Dt SIS 4
 .Os
 .Sh NAME
@@ -145,6 +145,22 @@ SiS 630, 635, and 735 motherboard chipsets
 .It
 Soekris Engineering net45xx, net48xx, lan1621, and lan1641
 .El
+.Sh SYSCTL VARIABLES
+The following variable is available as both
+.Xr sysctl 8
+variable and
+.Xr loader 8
+tunable:
+.Bl -tag -width indent
+.It Va dev.sis.%unit.manual_pad
+This variable controls how to pad short frames for DP83815/DP83816
+controllers on the specified device.
+DP83815/DP83816 controllers are known to pad 0xFF for short frames
+which is violation of RFC 1042.
+A non-zero value have driver manually pad zeros for short frames
+with the cost of extra CPU cycles.
+The default valus is 0 to let hardware automatically pad short frames.
+.El
 .Sh DIAGNOSTICS
 .Bl -diag
 .It "sis%d: couldn't map ports/memory"
@@ -190,6 +206,7 @@ the card should be configured correctly.
 .Xr netintro 4 ,
 .Xr ng_ether 4 ,
 .Xr polling 4 ,
+.Xr vlan 4 ,
 .Xr ifconfig 8
 .Rs
 .%T SiS 900 and SiS 7016 datasheets

From f03f7a0ca36bf5c6acb0c3a9a91dc7ded0ab009f Mon Sep 17 00:00:00 2001
From: "Justin T. Gibbs" 
Date: Thu, 2 Sep 2010 19:40:28 +0000
Subject: [PATCH 0463/1624] Correct bioq_disksort so that bioq_insert_tail()
 offers barrier semantic. Add the BIO_ORDERED flag for struct bio and update
 bio clients to use it.

The barrier semantics of bioq_insert_tail() were broken in two ways:

 o In bioq_disksort(), an added bio could be inserted at the head of
   the queue, even when a barrier was present, if the sort key for
   the new entry was less than that of the last queued barrier bio.

 o The last_offset used to generate the sort key for newly queued bios
   did not stay at the position of the barrier until either the
   barrier was de-queued, or a new barrier (which updates last_offset)
   was queued.  When a barrier is in effect, we know that the disk
   will pass through the barrier position just before the
   "blocked bios" are released, so using the barrier's offset for
   last_offset is the optimal choice.

sys/geom/sched/subr_disk.c:
sys/kern/subr_disk.c:
	o Update last_offset in bioq_insert_tail().

	o Only update last_offset in bioq_remove() if the removed bio is
	  at the head of the queue (typically due to a call via
	  bioq_takefirst()) and no barrier is active.

	o In bioq_disksort(), if we have a barrier (insert_point is non-NULL),
	  set prev to the barrier and cur to it's next element.  Now that
	  last_offset is kept at the barrier position, this change isn't
	  strictly necessary, but since we have to take a decision branch
	  anyway, it does avoid one, no-op, loop iteration in the while
	  loop that immediately follows.

	o In bioq_disksort(), bypass the normal sort for bios with the
	  BIO_ORDERED attribute and instead insert them into the queue
	  with bioq_insert_tail().  bioq_insert_tail() not only gives
	  the desired command order during insertion, but also provides
	  barrier semantics so that commands disksorted in the future
	  cannot pass the just enqueued transaction.

sys/sys/bio.h:
	Add BIO_ORDERED as bit 4 of the bio_flags field in struct bio.

sys/cam/ata/ata_da.c:
sys/cam/scsi/scsi_da.c
	Use an ordered command for SCSI/ATA-NCQ commands issued in
	response to bios with the BIO_ORDERED flag set.

sys/cam/scsi/scsi_da.c
	Use an ordered tag when issuing a synchronize cache command.

	Wrap some lines to 80 columns.

sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c
sys/geom/geom_io.c
	Mark bios with the BIO_FLUSH command as BIO_ORDERED.

Sponsored by:	Spectra Logic Corporation
MFC after:	1 month
---
 sys/cam/ata/ata_da.c                          |  3 +-
 sys/cam/scsi/scsi_da.c                        | 21 ++++++++---
 .../opensolaris/uts/common/fs/zfs/vdev_geom.c |  1 +
 sys/geom/geom_io.c                            |  1 +
 sys/geom/sched/subr_disk.c                    | 37 ++++++++++++++-----
 sys/kern/subr_disk.c                          | 37 ++++++++++++++-----
 sys/sys/bio.h                                 |  1 +
 7 files changed, 74 insertions(+), 27 deletions(-)

diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c
index 396802656cd..8a279311b4a 100644
--- a/sys/cam/ata/ata_da.c
+++ b/sys/cam/ata/ata_da.c
@@ -874,7 +874,8 @@ adastart(struct cam_periph *periph, union ccb *start_ccb)
 		}
 		bioq_remove(&softc->bio_queue, bp);
 
-		if ((softc->flags & ADA_FLAG_NEED_OTAG) != 0) {
+		if ((bp->bio_flags & BIO_ORDERED) != 0
+		 || (softc->flags & ADA_FLAG_NEED_OTAG) != 0) {
 			softc->flags &= ~ADA_FLAG_NEED_OTAG;
 			softc->ordered_tag_count++;
 			tag_code = 0;
diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c
index 8f643611c0c..7729ecc5ef5 100644
--- a/sys/cam/scsi/scsi_da.c
+++ b/sys/cam/scsi/scsi_da.c
@@ -1354,7 +1354,8 @@ dastart(struct cam_periph *periph, union ccb *start_ccb)
 
 			bioq_remove(&softc->bio_queue, bp);
 
-			if ((softc->flags & DA_FLAG_NEED_OTAG) != 0) {
+			if ((bp->bio_flags & BIO_ORDERED) != 0
+			 || (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
 				softc->flags &= ~DA_FLAG_NEED_OTAG;
 				softc->ordered_tag_count++;
 				tag_code = MSG_ORDERED_Q_TAG;
@@ -1368,7 +1369,8 @@ dastart(struct cam_periph *periph, union ccb *start_ccb)
 						/*retries*/da_retry_count,
 						/*cbfcnp*/dadone,
 						/*tag_action*/tag_code,
-						/*read_op*/bp->bio_cmd == BIO_READ,
+						/*read_op*/bp->bio_cmd
+							== BIO_READ,
 						/*byte2*/0,
 						softc->minimum_cmd_size,
 						/*lba*/bp->bio_pblkno,
@@ -1377,17 +1379,24 @@ dastart(struct cam_periph *periph, union ccb *start_ccb)
 						/*data_ptr*/ bp->bio_data,
 						/*dxfer_len*/ bp->bio_bcount,
 						/*sense_len*/SSD_FULL_SIZE,
-						/*timeout*/da_default_timeout*1000);
+						da_default_timeout * 1000);
 				break;
 			case BIO_FLUSH:
+				/*
+				 * BIO_FLUSH doesn't currently communicate
+				 * range data, so we synchronize the cache
+				 * over the whole disk.  We also force
+				 * ordered tag semantics the flush applies
+				 * to all previously queued I/O.
+				 */
 				scsi_synchronize_cache(&start_ccb->csio,
 						       /*retries*/1,
 						       /*cbfcnp*/dadone,
-						       MSG_SIMPLE_Q_TAG,
-						       /*begin_lba*/0,/* Cover the whole disk */
+						       MSG_ORDERED_Q_TAG,
+						       /*begin_lba*/0,
 						       /*lb_count*/0,
 						       SSD_FULL_SIZE,
-						       /*timeout*/da_default_timeout*1000);
+						       da_default_timeout*1000);
 				break;
 			}
 			start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c
index 00817bfef24..d0d5137913c 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c
@@ -598,6 +598,7 @@ sendreq:
 		break;
 	case ZIO_TYPE_IOCTL:
 		bp->bio_cmd = BIO_FLUSH;
+		bp->bio_flags |= BIO_ORDERED;
 		bp->bio_data = NULL;
 		bp->bio_offset = cp->provider->mediasize;
 		bp->bio_length = 0;
diff --git a/sys/geom/geom_io.c b/sys/geom/geom_io.c
index b145441cad7..b4044a75e33 100644
--- a/sys/geom/geom_io.c
+++ b/sys/geom/geom_io.c
@@ -265,6 +265,7 @@ g_io_flush(struct g_consumer *cp)
 	g_trace(G_T_BIO, "bio_flush(%s)", cp->provider->name);
 	bp = g_alloc_bio();
 	bp->bio_cmd = BIO_FLUSH;
+	bp->bio_flags |= BIO_ORDERED;
 	bp->bio_done = NULL;
 	bp->bio_attribute = NULL;
 	bp->bio_offset = cp->provider->mediasize;
diff --git a/sys/geom/sched/subr_disk.c b/sys/geom/sched/subr_disk.c
index 008eaab1c94..db2a9ef11f8 100644
--- a/sys/geom/sched/subr_disk.c
+++ b/sys/geom/sched/subr_disk.c
@@ -86,7 +86,7 @@ __FBSDID("$FreeBSD$");
  * bioq_remove()	remove a generic element from the queue, act as
  *		bioq_takefirst() if invoked on the head of the queue.
  *
- * The semantic of these methods is the same of the operations
+ * The semantic of these methods is the same as the operations
  * on the underlying TAILQ, but with additional guarantees on
  * subsequent bioq_disksort() calls. E.g. bioq_insert_tail()
  * can be useful for making sure that all previous ops are flushed
@@ -115,10 +115,10 @@ void
 gs_bioq_remove(struct bio_queue_head *head, struct bio *bp)
 {
 
-	if (bp == TAILQ_FIRST(&head->queue))
-		head->last_offset = bp->bio_offset + bp->bio_length;
-
-	if (bp == head->insert_point)
+	if (head->insert_point == NULL) {
+		if (bp == TAILQ_FIRST(&head->queue))
+			head->last_offset = bp->bio_offset + bp->bio_length;
+	} else if (bp == head->insert_point)
 		head->insert_point = NULL;
 
 	TAILQ_REMOVE(&head->queue, bp, bio_queue);
@@ -137,7 +137,8 @@ void
 gs_bioq_insert_head(struct bio_queue_head *head, struct bio *bp)
 {
 
-	head->last_offset = bp->bio_offset;
+	if (head->insert_point == NULL)
+		head->last_offset = bp->bio_offset;
 	TAILQ_INSERT_HEAD(&head->queue, bp, bio_queue);
 }
 
@@ -147,6 +148,7 @@ gs_bioq_insert_tail(struct bio_queue_head *head, struct bio *bp)
 
 	TAILQ_INSERT_TAIL(&head->queue, bp, bio_queue);
 	head->insert_point = bp;
+	head->last_offset = bp->bio_offset;
 }
 
 struct bio *
@@ -189,13 +191,28 @@ gs_bioq_bio_key(struct bio_queue_head *head, struct bio *bp)
 void
 gs_bioq_disksort(struct bio_queue_head *head, struct bio *bp)
 {
-	struct bio *cur, *prev = NULL;
-	uoff_t key = gs_bioq_bio_key(head, bp);
+	struct bio *cur, *prev;
+	uoff_t key;
 
+	if ((bp->bio_flags & BIO_ORDERED) != 0) {
+		/*
+		 * Ordered transactions can only be dispatched
+		 * after any currently queued transactions.  They
+		 * also have barrier semantics - no transactions
+		 * queued in the future can pass them.
+		 */
+		gs_bioq_insert_tail(head, bp);
+		return;
+	}
+
+	prev = NULL;
+	key = gs_bioq_bio_key(head, bp);
 	cur = TAILQ_FIRST(&head->queue);
 
-	if (head->insert_point)
-		cur = head->insert_point;
+	if (head->insert_point) {
+		prev = head->insert_point;
+		cur = TAILQ_NEXT(head->insert_point, bio_queue);
+	}
 
 	while (cur != NULL && key >= gs_bioq_bio_key(head, cur)) {
 		prev = cur;
diff --git a/sys/kern/subr_disk.c b/sys/kern/subr_disk.c
index 12b015944c2..23915402e30 100644
--- a/sys/kern/subr_disk.c
+++ b/sys/kern/subr_disk.c
@@ -127,7 +127,7 @@ disk_err(struct bio *bp, const char *what, int blkdone, int nl)
  * bioq_remove()	remove a generic element from the queue, act as
  *		bioq_takefirst() if invoked on the head of the queue.
  *
- * The semantic of these methods is the same of the operations
+ * The semantic of these methods is the same as the operations
  * on the underlying TAILQ, but with additional guarantees on
  * subsequent bioq_disksort() calls. E.g. bioq_insert_tail()
  * can be useful for making sure that all previous ops are flushed
@@ -156,10 +156,10 @@ void
 bioq_remove(struct bio_queue_head *head, struct bio *bp)
 {
 
-	if (bp == TAILQ_FIRST(&head->queue))
-		head->last_offset = bp->bio_offset + bp->bio_length;
-
-	if (bp == head->insert_point)
+	if (head->insert_point == NULL) {
+		if (bp == TAILQ_FIRST(&head->queue))
+			head->last_offset = bp->bio_offset + bp->bio_length;
+	} else if (bp == head->insert_point)
 		head->insert_point = NULL;
 
 	TAILQ_REMOVE(&head->queue, bp, bio_queue);
@@ -178,7 +178,8 @@ void
 bioq_insert_head(struct bio_queue_head *head, struct bio *bp)
 {
 
-	head->last_offset = bp->bio_offset;
+	if (head->insert_point == NULL)
+		head->last_offset = bp->bio_offset;
 	TAILQ_INSERT_HEAD(&head->queue, bp, bio_queue);
 }
 
@@ -188,6 +189,7 @@ bioq_insert_tail(struct bio_queue_head *head, struct bio *bp)
 
 	TAILQ_INSERT_TAIL(&head->queue, bp, bio_queue);
 	head->insert_point = bp;
+	head->last_offset = bp->bio_offset;
 }
 
 struct bio *
@@ -230,13 +232,28 @@ bioq_bio_key(struct bio_queue_head *head, struct bio *bp)
 void
 bioq_disksort(struct bio_queue_head *head, struct bio *bp)
 {
-	struct bio *cur, *prev = NULL;
-	uoff_t key = bioq_bio_key(head, bp);
+	struct bio *cur, *prev;
+	uoff_t key;
 
+	if ((bp->bio_flags & BIO_ORDERED) != 0) {
+		/*
+		 * Ordered transactions can only be dispatched
+		 * after any currently queued transactions.  They
+		 * also have barrier semantics - no transactions
+		 * queued in the future can pass them.
+		 */
+		bioq_insert_tail(head, bp);
+		return;
+	}
+
+	prev = NULL;
+	key = bioq_bio_key(head, bp);
 	cur = TAILQ_FIRST(&head->queue);
 
-	if (head->insert_point)
-		cur = head->insert_point;
+	if (head->insert_point) {
+		prev = head->insert_point;
+		cur = TAILQ_NEXT(head->insert_point, bio_queue);
+	}
 
 	while (cur != NULL && key >= bioq_bio_key(head, cur)) {
 		prev = cur;
diff --git a/sys/sys/bio.h b/sys/sys/bio.h
index 8b6ff0ec696..c016ee67b90 100644
--- a/sys/sys/bio.h
+++ b/sys/sys/bio.h
@@ -54,6 +54,7 @@
 #define BIO_ERROR	0x01
 #define BIO_DONE	0x02
 #define BIO_ONQUEUE	0x04
+#define BIO_ORDERED	0x08
 
 #ifdef _KERNEL
 struct disk;

From 629cb67ffac44ceea6d55962f0f8911610675568 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 20:43:01 +0000
Subject: [PATCH 0464/1624] Better wording.

Submitted by:	jkim
---
 share/man/man4/sis.4 | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/share/man/man4/sis.4 b/share/man/man4/sis.4
index 2290f67e6f3..a1e1db80123 100644
--- a/share/man/man4/sis.4
+++ b/share/man/man4/sis.4
@@ -157,9 +157,9 @@ This variable controls how to pad short frames for DP83815/DP83816
 controllers on the specified device.
 DP83815/DP83816 controllers are known to pad 0xFF for short frames
 which is violation of RFC 1042.
-A non-zero value have driver manually pad zeros for short frames
-with the cost of extra CPU cycles.
-The default valus is 0 to let hardware automatically pad short frames.
+Set this variable to a non-zero value to let driver manually pad
+each short frame with zeros at the cost of extra CPU cycles.
+The default value is 0 to let hardware perform automatic padding.
 .El
 .Sh DIAGNOSTICS
 .Bl -diag

From f806ea8af121c57f45c68a10b198a2fb2a08a3e7 Mon Sep 17 00:00:00 2001
From: Gavin Atkinson 
Date: Thu, 2 Sep 2010 21:29:50 +0000
Subject: [PATCH 0465/1624] Correct spelling mistake, int -> into

MFC after:	3 days
---
 usr.bin/split/split.1 | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/usr.bin/split/split.1 b/usr.bin/split/split.1
index e55bb87b74a..5b2953b2887 100644
--- a/usr.bin/split/split.1
+++ b/usr.bin/split/split.1
@@ -32,7 +32,7 @@
 .\"	@(#)split.1	8.3 (Berkeley) 4/16/94
 .\" $FreeBSD$
 .\"
-.Dd January 23, 2009
+.Dd September 2, 2010
 .Dt SPLIT 1
 .Os
 .Sh NAME
@@ -117,7 +117,7 @@ Create split files
 .Ar line_count
 lines in length.
 .It Fl n Ar chunk_count
-Split file int
+Split file into
 .Ar chunk_count
 smaller files.
 .It Fl p Ar pattern

From 287cf3e528014022d03a4e76d62cb7a650d1c68d Mon Sep 17 00:00:00 2001
From: Edwin Groothuis 
Date: Thu, 2 Sep 2010 21:48:35 +0000
Subject: [PATCH 0466/1624] Adding a missing firstname (Monique)

PR:		conf/150049
Submitted by:	Thierry Thomas 
---
 usr.bin/calendar/calendars/fr_FR.ISO8859-1/calendar.fetes | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/usr.bin/calendar/calendars/fr_FR.ISO8859-1/calendar.fetes b/usr.bin/calendar/calendars/fr_FR.ISO8859-1/calendar.fetes
index 7ee3b92b8d0..d80a8757409 100644
--- a/usr.bin/calendar/calendars/fr_FR.ISO8859-1/calendar.fetes
+++ b/usr.bin/calendar/calendars/fr_FR.ISO8859-1/calendar.fetes
@@ -382,7 +382,7 @@ LANG=fr_FR.ISO8859-1
 08/26	Bonne fête aux Zéphirin !
 08/26	Aujourd'hui, c'est la St(e) Eulade.
 08/27	N'oubliez pas les Edwige !
-08/27	Bonne fête aux Joseph !
+08/27	Bonne fête aux Monique et aux Joseph !
 08/28	Aujourd'hui, c'est la St(e) Augustin.
 08/29	N'oubliez pas les Sabine !
 08/30	Bonne fête aux Fiacre !

From fa942e6074cceb526256643911d778d6fbd8a1b8 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 2 Sep 2010 22:26:49 +0000
Subject: [PATCH 0467/1624] In the case of non-sequential mappings,
 ofw_mapmem() could ask Open Firmware to map a memory region with negative
 length, causing crashes and Undefined Behavior. Add the appropriate check to
 make the behavior defined.

---
 sys/boot/ofw/libofw/ofw_copy.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/boot/ofw/libofw/ofw_copy.c b/sys/boot/ofw/libofw/ofw_copy.c
index 93e7ec656d0..781d4233a01 100644
--- a/sys/boot/ofw/libofw/ofw_copy.c
+++ b/sys/boot/ofw/libofw/ofw_copy.c
@@ -68,7 +68,7 @@ ofw_mapmem(vm_offset_t dest, const size_t len)
 	/*
 	 * Trim area covered by existing mapping, if any
 	 */
-	if (dest < (last_dest + last_len)) {
+	if (dest < (last_dest + last_len) && dest >= last_dest) {
 		nlen -= (last_dest + last_len) - dest;
 		dest = last_dest + last_len;
 	}

From 7968da57dcd9f906d6645bf26b96e55c21b9f717 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Thu, 2 Sep 2010 22:37:13 +0000
Subject: [PATCH 0468/1624] Implement initial device suspend/resume method.

---
 sys/dev/sis/if_sis.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index ceff6b8d351..2b4bb9b4539 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -2393,6 +2393,35 @@ sis_shutdown(device_t dev)
 	return (0);
 }
 
+static int
+sis_suspend(device_t dev)
+{
+	struct sis_softc	*sc;
+
+	sc = device_get_softc(dev);
+	SIS_LOCK(sc);
+	sis_stop(sc);
+	SIS_UNLOCK(sc);
+	return (0);
+}
+
+static int
+sis_resume(device_t dev)
+{
+	struct sis_softc	*sc;
+	struct ifnet		*ifp;
+
+	sc = device_get_softc(dev);
+	SIS_LOCK(sc);
+	ifp = sc->sis_ifp;
+	if ((ifp->if_flags & IFF_UP) != 0) {
+		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
+		sis_initl(sc);
+	}
+	SIS_UNLOCK(sc);
+	return (0);
+}
+
 static void
 sis_add_sysctls(struct sis_softc *sc)
 {
@@ -2425,6 +2454,8 @@ static device_method_t sis_methods[] = {
 	DEVMETHOD(device_attach,	sis_attach),
 	DEVMETHOD(device_detach,	sis_detach),
 	DEVMETHOD(device_shutdown,	sis_shutdown),
+	DEVMETHOD(device_suspend,	sis_suspend),
+	DEVMETHOD(device_resume,	sis_resume),
 
 	/* bus interface */
 	DEVMETHOD(bus_print_child,	bus_generic_print_child),

From 0af3989be953a8812d84614b1aa8825f7c8a85f0 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Fri, 3 Sep 2010 00:34:45 +0000
Subject: [PATCH 0469/1624] Initial WOL support. NS DP8315 was tested but
 SiS900/SiS7016 was not tested. While I'm here, clean up SIOCSIFCAP handler.

---
 sys/dev/sis/if_sis.c    | 127 ++++++++++++++++++++++++++++++----------
 sys/dev/sis/if_sisreg.h |  28 +++++++++
 2 files changed, 124 insertions(+), 31 deletions(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index 2b4bb9b4539..ef95b0863d0 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -147,12 +147,15 @@ static void sis_initl(struct sis_softc *);
 static void sis_intr(void *);
 static int sis_ioctl(struct ifnet *, u_long, caddr_t);
 static int sis_newbuf(struct sis_softc *, struct sis_rxdesc *);
+static int sis_resume(device_t);
 static int sis_rxeof(struct sis_softc *);
 static void sis_start(struct ifnet *);
 static void sis_startl(struct ifnet *);
 static void sis_stop(struct sis_softc *);
+static int sis_suspend(device_t);
 static void sis_add_sysctls(struct sis_softc *);
 static void sis_watchdog(struct sis_softc *);
+static void sis_wol(struct sis_softc *);
 
 
 static struct resource_spec sis_res_spec[] = {
@@ -935,6 +938,9 @@ sis_reset(struct sis_softc *sc)
 	if (sc->sis_type == SIS_TYPE_83815) {
 		CSR_WRITE_4(sc, NS_CLKRUN, NS_CLKRUN_PMESTS);
 		CSR_WRITE_4(sc, NS_CLKRUN, 0);
+	} else {
+		/* Disable WOL functions. */
+		CSR_WRITE_4(sc, SIS_PWRMAN_CTL, 0);
 	}
 }
 
@@ -971,7 +977,7 @@ sis_attach(device_t dev)
 	u_char			eaddr[ETHER_ADDR_LEN];
 	struct sis_softc	*sc;
 	struct ifnet		*ifp;
-	int			error = 0, waittime = 0;
+	int			error = 0, pmc, waittime = 0;
 
 	waittime = 0;
 	sc = device_get_softc(dev);
@@ -1147,6 +1153,14 @@ sis_attach(device_t dev)
 	ifp->if_snd.ifq_drv_maxlen = SIS_TX_LIST_CNT - 1;
 	IFQ_SET_READY(&ifp->if_snd);
 
+	if (pci_find_extcap(sc->sis_dev, PCIY_PMG, &pmc) == 0) {
+		if (sc->sis_type == SIS_TYPE_83815)
+			ifp->if_capabilities |= IFCAP_WOL;
+		else
+			ifp->if_capabilities |= IFCAP_WOL_MAGIC;
+		ifp->if_capenable = ifp->if_capabilities;
+	}
+
 	/*
 	 * Do MII setup.
 	 */
@@ -2227,7 +2241,7 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 	struct sis_softc	*sc = ifp->if_softc;
 	struct ifreq		*ifr = (struct ifreq *) data;
 	struct mii_data		*mii;
-	int			error = 0;
+	int			error = 0, mask;
 
 	switch (command) {
 	case SIOCSIFFLAGS:
@@ -2264,32 +2278,37 @@ sis_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
 		break;
 	case SIOCSIFCAP:
-		/* ok, disable interrupts */
+		SIS_LOCK(sc);
+		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
 #ifdef DEVICE_POLLING
-		if (ifr->ifr_reqcap & IFCAP_POLLING &&
-		    !(ifp->if_capenable & IFCAP_POLLING)) {
-			error = ether_poll_register(sis_poll, ifp);
-			if (error)
-				return (error);
-			SIS_LOCK(sc);
-			/* Disable interrupts */
-			CSR_WRITE_4(sc, SIS_IER, 0);
-			ifp->if_capenable |= IFCAP_POLLING;
-			SIS_UNLOCK(sc);
-			return (error);
-
-		}
-		if (!(ifr->ifr_reqcap & IFCAP_POLLING) &&
-		    ifp->if_capenable & IFCAP_POLLING) {
-			error = ether_poll_deregister(ifp);
-			/* Enable interrupts. */
-			SIS_LOCK(sc);
-			CSR_WRITE_4(sc, SIS_IER, 1);
-			ifp->if_capenable &= ~IFCAP_POLLING;
-			SIS_UNLOCK(sc);
-			return (error);
+		if ((mask & IFCAP_POLLING) != 0 &&
+		    (IFCAP_POLLING & ifp->if_capabilities) != 0) {
+			ifp->if_capenable ^= IFCAP_POLLING;
+			if ((IFCAP_POLLING & ifp->if_capenable) != 0) {
+				error = ether_poll_register(sis_poll, ifp);
+				if (error != 0) {
+					SIS_UNLOCK(sc);
+					break;
+				}
+				/* Disable interrupts. */
+				CSR_WRITE_4(sc, SIS_IER, 0);
+                        } else {
+                                error = ether_poll_deregister(ifp);
+                                /* Enable interrupts. */
+				CSR_WRITE_4(sc, SIS_IER, 1);
+                        }
 		}
 #endif /* DEVICE_POLLING */
+		if ((mask & IFCAP_WOL) != 0 &&
+		    (ifp->if_capabilities & IFCAP_WOL) != 0) {
+			if ((mask & IFCAP_WOL_UCAST) != 0)
+				ifp->if_capenable ^= IFCAP_WOL_UCAST;
+			if ((mask & IFCAP_WOL_MCAST) != 0)
+				ifp->if_capenable ^= IFCAP_WOL_MCAST;
+			if ((mask & IFCAP_WOL_MAGIC) != 0)
+				ifp->if_capenable ^= IFCAP_WOL_MAGIC;
+		}
+		SIS_UNLOCK(sc);
 		break;
 	default:
 		error = ether_ioctl(ifp, command, data);
@@ -2384,13 +2403,8 @@ sis_stop(struct sis_softc *sc)
 static int
 sis_shutdown(device_t dev)
 {
-	struct sis_softc	*sc;
 
-	sc = device_get_softc(dev);
-	SIS_LOCK(sc);
-	sis_stop(sc);
-	SIS_UNLOCK(sc);
-	return (0);
+	return (sis_suspend(dev));
 }
 
 static int
@@ -2401,6 +2415,7 @@ sis_suspend(device_t dev)
 	sc = device_get_softc(dev);
 	SIS_LOCK(sc);
 	sis_stop(sc);
+	sis_wol(sc);
 	SIS_UNLOCK(sc);
 	return (0);
 }
@@ -2422,6 +2437,56 @@ sis_resume(device_t dev)
 	return (0);
 }
 
+static void
+sis_wol(struct sis_softc *sc)
+{
+	struct ifnet		*ifp;
+	uint32_t		val;
+	uint16_t		pmstat;
+	int			pmc;
+
+	ifp = sc->sis_ifp;
+	if ((ifp->if_capenable & IFCAP_WOL) == 0)
+		return;
+
+	if (sc->sis_type == SIS_TYPE_83815) {
+		/* Reset RXDP. */
+		CSR_WRITE_4(sc, SIS_RX_LISTPTR, 0);
+
+		/* Configure WOL events. */
+		CSR_READ_4(sc, NS_WCSR);
+		val = 0;
+		if ((ifp->if_capenable & IFCAP_WOL_UCAST) != 0)
+			val |= NS_WCSR_WAKE_UCAST;
+		if ((ifp->if_capenable & IFCAP_WOL_MCAST) != 0)
+			val |= NS_WCSR_WAKE_MCAST;
+		if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
+			val |= NS_WCSR_WAKE_MAGIC;
+		CSR_WRITE_4(sc, NS_WCSR, val);
+		/* Enable PME and clear PMESTS. */
+		val = CSR_READ_4(sc, NS_CLKRUN);
+		val |= NS_CLKRUN_PMEENB | NS_CLKRUN_PMESTS;
+		CSR_WRITE_4(sc, NS_CLKRUN, val);
+		/* Enable silent RX mode. */
+		SIS_SETBIT(sc, SIS_CSR, SIS_CSR_RX_ENABLE);
+	} else {
+		if (pci_find_extcap(sc->sis_dev, PCIY_PMG, &pmc) != 0)
+			return;
+		val = 0;
+		if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
+			val |= SIS_PWRMAN_WOL_MAGIC;
+		CSR_WRITE_4(sc, SIS_PWRMAN_CTL, val);
+		/* Request PME. */
+		pmstat = pci_read_config(sc->sis_dev,
+		    pmc + PCIR_POWER_STATUS, 2);
+		pmstat &= ~(PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE);
+		if ((ifp->if_capenable & IFCAP_WOL_MAGIC) != 0)
+			pmstat |= PCIM_PSTAT_PME | PCIM_PSTAT_PMEENABLE;
+		pci_write_config(sc->sis_dev,
+		    pmc + PCIR_POWER_STATUS, pmstat, 2);
+	}
+}
+
 static void
 sis_add_sysctls(struct sis_softc *sc)
 {
diff --git a/sys/dev/sis/if_sisreg.h b/sys/dev/sis/if_sisreg.h
index 42181a19e94..28d43901a23 100644
--- a/sys/dev/sis/if_sisreg.h
+++ b/sys/dev/sis/if_sisreg.h
@@ -77,6 +77,7 @@
 /* NS DP83815/6 registers */
 #define NS_IHR			0x1C
 #define NS_CLKRUN		0x3C
+#define	NS_WCSR			0x40
 #define NS_SRR			0x58
 #define NS_BMCR			0x80
 #define NS_BMSR			0x84
@@ -99,6 +100,29 @@
 #define NS_CLKRUN_PMEENB	0x00000100
 #define NS_CLNRUN_CLKRUN_ENB	0x00000001
 
+#define	NS_WCSR_WAKE_PHYINTR	0x00000001
+#define	NS_WCSR_WAKE_UCAST	0x00000002
+#define	NS_WCSR_WAKE_MCAST	0x00000004
+#define	NS_WCSR_WAKE_BCAST	0x00000008
+#define	NS_WCSR_WAKE_ARP	0x00000010
+#define	NS_WCSR_WAKE_PATTERN0	0x00000020
+#define	NS_WCSR_WAKE_PATTERN1	0x00000040
+#define	NS_WCSR_WAKE_PATTERN2	0x00000080
+#define	NS_WCSR_WAKE_PATTERN3	0x00000100
+#define	NS_WCSR_WAKE_MAGIC	0x00000200
+#define	NS_WCSR_WAKE_MAGIC_SEC	0x00000400
+#define	NS_WCSR_DET_MAGIC_SECH	0x00100000
+#define	NS_WCSR_DET_PHYINTR	0x00400000
+#define	NS_WCSR_DET_UCAST	0x00800000
+#define	NS_WCSR_DET_MCAST	0x01000000
+#define	NS_WCSR_DET_BCAST	0x02000000
+#define	NS_WCSR_DET_ARP		0x04000000
+#define	NS_WCSR_DET_PATTERN0	0x08000000
+#define	NS_WCSR_DET_PATTERN1	0x10000000
+#define	NS_WCSR_DET_PATTERN2	0x20000000
+#define	NS_WCSR_DET_PATTERN3	0x40000000
+#define	NS_WCSR_DET_MAGIC	0x80000000
+
 /* NS silicon revisions */
 #define NS_SRR_15C		0x302
 #define NS_SRR_15D		0x403
@@ -303,6 +327,10 @@
 #define NS_FILTADDR_FMEM_LO	0x00000200
 #define NS_FILTADDR_FMEM_HI	0x000003FE
 
+#define	SIS_PWRMAN_WOL_LINK_OFF	0x00000001
+#define	SIS_PWRMAN_WOL_LINK_ON	0x00000002
+#define	SIS_PWRMAN_WOL_MAGIC	0x00000400
+
 /*
  * TX/RX DMA descriptor structures.
  */

From ec6f1f4a71eec4ca06862f3d0daf7d88c5f48458 Mon Sep 17 00:00:00 2001
From: John-Mark Gurney 
Date: Fri, 3 Sep 2010 03:20:34 +0000
Subject: [PATCH 0470/1624] fix the move so that it matches what the rest of
 the internet says about this game...  This move also makes more sense...

MFC after:	1 week
---
 games/fortune/datfiles/fortunes | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/games/fortune/datfiles/fortunes b/games/fortune/datfiles/fortunes
index bd4154493dd..6abc98e27e9 100644
--- a/games/fortune/datfiles/fortunes
+++ b/games/fortune/datfiles/fortunes
@@ -45221,7 +45221,7 @@ of their own homes.
 	1: P-Q4, Kt-KB3
 	2: Kt-Q2, P-K4
 	3: PxP, Kt-Kt5
-	4: P-K6, Kt-K6/
+	4: P-KR3, Kt-K6/
 	White then resigns on realizing that a fifth move would involve
 either a Q-KR5 check or the loss of his queen.
 		-- Stephen Pile, "The Book of Heroic Failures"

From 42908e80e62503b3396d22733182c4112dc9c5f6 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Fri, 3 Sep 2010 03:48:06 +0000
Subject: [PATCH 0471/1624] Allow / in the NANO_DEVICE

PR:		149729
Submitted by:	Thomas Quinot 
---
 tools/tools/nanobsd/nanobsd.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/tools/nanobsd/nanobsd.sh b/tools/tools/nanobsd/nanobsd.sh
index 8f38846b6ba..da8294b2b04 100644
--- a/tools/tools/nanobsd/nanobsd.sh
+++ b/tools/tools/nanobsd/nanobsd.sh
@@ -503,7 +503,7 @@ create_i386_diskimage ( ) (
 		mount /dev/${MD}s2a ${MNT}
 		for f in ${MNT}/etc/fstab ${MNT}/conf/base/etc/fstab
 		do
-			sed -i "" "s/${NANO_DRIVE}s1/${NANO_DRIVE}s2/g" $f
+			sed -i "" "s=${NANO_DRIVE}s1=${NANO_DRIVE}s2=g" $f
 		done
 		umount ${MNT}
 	fi

From d8acfb88ad77c17a3e6e91bd462a3dbc66ebab0e Mon Sep 17 00:00:00 2001
From: Peter Grehan 
Date: Fri, 3 Sep 2010 03:56:09 +0000
Subject: [PATCH 0472/1624] - Bump MAXCPU to 4. Tested on a quad G5 with both
 32 and 64-bit kernels. A make buildkernel -j4 uses ~360% CPU. - Bracket the
 AP spinup printf with a mutex to avoid garbled output. - Enable SMP by
 default on powerpc64.

Reviewed by:	nwhitehorn
---
 sys/powerpc/conf/GENERIC64       |  4 ++--
 sys/powerpc/include/param.h      |  2 +-
 sys/powerpc/powerpc/mp_machdep.c | 10 +++++++++-
 3 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/sys/powerpc/conf/GENERIC64 b/sys/powerpc/conf/GENERIC64
index 79bd1d8a065..88963d98d9b 100644
--- a/sys/powerpc/conf/GENERIC64
+++ b/sys/powerpc/conf/GENERIC64
@@ -76,8 +76,8 @@ options 	WITNESS			#Enable checks to detect deadlocks and cycles
 options 	WITNESS_SKIPSPIN	#Don't run witness on spinlocks for speed
 options 	MALLOC_DEBUG_MAXZONES=8	# Separate malloc(9) zones
 
-# To make an SMP kernel, the next line is needed
-#options 	SMP			# Symmetric MultiProcessor Kernel
+# Make an SMP-capable kernel by default
+options 	SMP			# Symmetric MultiProcessor Kernel
 
 # CPU frequency control
 device		cpufreq
diff --git a/sys/powerpc/include/param.h b/sys/powerpc/include/param.h
index 91bb238dd51..d71d0483bd0 100644
--- a/sys/powerpc/include/param.h
+++ b/sys/powerpc/include/param.h
@@ -68,7 +68,7 @@
 #endif
 
 #if defined(SMP) || defined(KLD_MODULE)
-#define	MAXCPU		2
+#define	MAXCPU		4	
 #else
 #define	MAXCPU		1
 #endif /* SMP || KLD_MODULE */
diff --git a/sys/powerpc/powerpc/mp_machdep.c b/sys/powerpc/powerpc/mp_machdep.c
index 19b46a9e634..46f02956c16 100644
--- a/sys/powerpc/powerpc/mp_machdep.c
+++ b/sys/powerpc/powerpc/mp_machdep.c
@@ -32,6 +32,8 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 #include 
@@ -60,6 +62,7 @@ volatile static u_int ap_letgo;
 volatile static uint32_t ap_decr;
 volatile static u_quad_t ap_timebase;
 static u_int ipi_msg_cnt[32];
+static struct mtx ap_boot_mtx;
 
 void
 machdep_ap_bootstrap(void)
@@ -80,8 +83,11 @@ machdep_ap_bootstrap(void)
 	mttb(ap_timebase);
 	__asm __volatile("mtdec %0" :: "r"(ap_decr));
 
-	atomic_add_int(&ap_awake, 1);
+	/* Serialize console output and AP count increment */
+	mtx_lock_spin(&ap_boot_mtx);
+	ap_awake++;
 	printf("SMP: AP CPU #%d launched\n", PCPU_GET(cpuid));
+	mtx_unlock_spin(&ap_boot_mtx);
 
 	/* Initialize curthread */
 	PCPU_SET(curthread, PCPU_GET(idlethread));
@@ -203,6 +209,8 @@ cpu_mp_unleash(void *dummy)
 	if (mp_ncpus <= 1)
 		return;
 
+	mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
+
 	cpus = 0;
 	smp_cpus = 0;
 	SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {

From b1f9b9965bd0cc2f4ab1ac38bef46db398e83a59 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Fri, 3 Sep 2010 08:07:04 +0000
Subject: [PATCH 0473/1624] acpi: update stale comments about order of cpu
 devices probing

These comments should have been updated in r203776 when the order was
changed.

Pointyhat to:	avg
MFC after:	3 days
---
 sys/dev/acpica/acpi.c | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)

diff --git a/sys/dev/acpica/acpi.c b/sys/dev/acpica/acpi.c
index feef2cc3fdd..7c941f36561 100644
--- a/sys/dev/acpica/acpi.c
+++ b/sys/dev/acpica/acpi.c
@@ -1690,10 +1690,10 @@ acpi_probe_order(ACPI_HANDLE handle, int *order)
     ACPI_OBJECT_TYPE type;
 
     /*
-     * 1. I/O port and memory system resource holders
-     * 2. Embedded controllers (to handle early accesses)
-     * 3. PCI Link Devices
-     * 100000. CPUs
+     * 1. CPUs
+     * 2. I/O port and memory system resource holders
+     * 3. Embedded controllers (to handle early accesses)
+     * 4. PCI Link Devices
      */
     AcpiGetType(handle, &type);
     if (type == ACPI_TYPE_PROCESSOR)
@@ -1753,8 +1753,7 @@ acpi_probe_child(ACPI_HANDLE handle, UINT32 level, void *context, void **status)
 	     * placeholder so that the probe/attach passes will run
 	     * breadth-first.  Orders less than ACPI_DEV_BASE_ORDER
 	     * are reserved for special objects (i.e., system
-	     * resources).  CPU devices have a very high order to
-	     * ensure they are probed after other devices.
+	     * resources).
 	     */
 	    ACPI_DEBUG_PRINT((ACPI_DB_OBJECTS, "scanning '%s'\n", handle_str));
 	    order = level * 10 + 100;

From 9f5b45662f00b0d8467be2519b6d1a80bc569398 Mon Sep 17 00:00:00 2001
From: Poul-Henning Kamp 
Date: Fri, 3 Sep 2010 09:34:15 +0000
Subject: [PATCH 0474/1624] We need to copy the ports config files before we
 launch the prefetch

---
 tools/tools/sysbuild/sysbuild.sh | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/tools/tools/sysbuild/sysbuild.sh b/tools/tools/sysbuild/sysbuild.sh
index 009973cca10..07a26f25896 100644
--- a/tools/tools/sysbuild/sysbuild.sh
+++ b/tools/tools/sysbuild/sysbuild.sh
@@ -410,6 +410,9 @@ if [ "x${REMOTEDISTFILES}" != "x" ] ; then
 	mount  ${REMOTEDISTFILES} /freebsd/distfiles
 fi
 
+log_it copy ports config files
+(cd / ; find var/db/ports -print | cpio -dumpv /mnt )
+
 log_it "Start prefetch of ports distfiles"
 ports_prefetch &
 
@@ -483,9 +486,6 @@ if [ -f /etc/localtime ] ; then
 	cp /etc/localtime /mnt/etc
 fi
 
-log_it copy ports config files
-(cd / ; find var/db/ports -print | cpio -dumpv /mnt )
-
 log_it ldconfig in chroot
 chroot /mnt sh /etc/rc.d/ldconfig start
 

From a9b89cf1c1f8581c33745a7228f44ca888742165 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Fri, 3 Sep 2010 10:40:53 +0000
Subject: [PATCH 0475/1624] vm_page.c: include opt_msgbuf.h for MSGBUF_SIZE use
 in vm_page_startup

vm_page_startup uses MSGBUF_SIZE value for adding msgbuf pages to minidump.
If opt_msgbuf.h is not included and MSGBUF_SIZE is overriden in kernel
config, then not all msgbuf pages will be dumped.  And most importantly,
struct msgbuf itself will not be included.  Thus the dump would look
corrupted/incomplete to tools like kgdb, dmesg, etc that try to access
struct msgbuf as one of the first things they do when working on a crash
dump.

MFC after:	5 days
---
 sys/vm/vm_page.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/vm/vm_page.c b/sys/vm/vm_page.c
index 44b801eb287..d778c992b9b 100644
--- a/sys/vm/vm_page.c
+++ b/sys/vm/vm_page.c
@@ -100,6 +100,7 @@
 #include 
 __FBSDID("$FreeBSD$");
 
+#include "opt_msgbuf.h"
 #include "opt_vm.h"
 
 #include 

From eb707d6039d14d550c656283af3d3bfbb3aafc03 Mon Sep 17 00:00:00 2001
From: Fabien Thomas 
Date: Fri, 3 Sep 2010 13:54:02 +0000
Subject: [PATCH 0476/1624] When an asm location cannot be resolved to a
 function the cost will be spread as small value and then filtered by the
 threshold. As a first step solution display the number of event that cannot
 be resolved as a valid function location.

MFC after:	1week
---
 usr.sbin/pmcstat/pmcpl_callgraph.c | 2 ++
 usr.sbin/pmcstat/pmcpl_calltree.c  | 2 ++
 usr.sbin/pmcstat/pmcstat_log.c     | 1 +
 usr.sbin/pmcstat/pmcstat_log.h     | 1 +
 4 files changed, 6 insertions(+)

diff --git a/usr.sbin/pmcstat/pmcpl_callgraph.c b/usr.sbin/pmcstat/pmcpl_callgraph.c
index d948b77f43b..33998b51baa 100644
--- a/usr.sbin/pmcstat/pmcpl_callgraph.c
+++ b/usr.sbin/pmcstat/pmcpl_callgraph.c
@@ -149,6 +149,8 @@ pmcstat_cgnode_hash_lookup_pc(struct pmcstat_process *pp, pmc_id_t pmcid,
 	 */
 	if ((sym = pmcstat_symbol_search(image, pc)) != NULL)
 		pc = sym->ps_start;
+	else
+		pmcstat_stats.ps_samples_unknown_function++;
 
 	for (hash = i = 0; i < sizeof(uintfptr_t); i++)
 		hash += (pc >> i) & 0xFF;
diff --git a/usr.sbin/pmcstat/pmcpl_calltree.c b/usr.sbin/pmcstat/pmcpl_calltree.c
index 7ecc56f554d..c647a325a02 100644
--- a/usr.sbin/pmcstat/pmcpl_calltree.c
+++ b/usr.sbin/pmcstat/pmcpl_calltree.c
@@ -615,6 +615,8 @@ pmcpl_ct_node_hash_lookup_pc(struct pmcpl_ct_node *parent,
 	 */
 	if ((sym = pmcstat_symbol_search(image, pc)) != NULL)
 		pc = sym->ps_start;
+	else
+		pmcstat_stats.ps_samples_unknown_function++;
 
 	for (hash = i = 0; i < (int)sizeof(uintfptr_t); i++)
 		hash += (pc >> i) & 0xFF;
diff --git a/usr.sbin/pmcstat/pmcstat_log.c b/usr.sbin/pmcstat/pmcstat_log.c
index d9e6059ee6c..bebe9452756 100644
--- a/usr.sbin/pmcstat/pmcstat_log.c
+++ b/usr.sbin/pmcstat/pmcstat_log.c
@@ -2168,6 +2168,7 @@ pmcstat_shutdown_logging(void)
 		PRINT("#samples/total", samples_total);
 		PRINT("#samples/unclaimed", samples_unknown_offset);
 		PRINT("#samples/unknown-object", samples_indeterminable);
+		PRINT("#samples/unknown-function", samples_unknown_function);
 		PRINT("#callchain/dubious-frames", callchain_dubious_frames);
 	}
 
diff --git a/usr.sbin/pmcstat/pmcstat_log.h b/usr.sbin/pmcstat/pmcstat_log.h
index 8936fad0581..bfa925c5222 100644
--- a/usr.sbin/pmcstat/pmcstat_log.h
+++ b/usr.sbin/pmcstat/pmcstat_log.h
@@ -164,6 +164,7 @@ struct pmcstat_stats {
 	int ps_samples_skipped; /* #samples filtered out for any reason */
 	int ps_samples_unknown_offset;	/* #samples of rank 0 not in a map */
 	int ps_samples_indeterminable;	/* #samples in indeterminable images */
+	int ps_samples_unknown_function;/* #samples with unknown function at offset */
 	int ps_callchain_dubious_frames;/* #dubious frame pointers seen */
 };
 extern struct pmcstat_stats pmcstat_stats; /* statistics */

From 27d4fea6c59c3f6749a5138f4fc198e6bc00b051 Mon Sep 17 00:00:00 2001
From: Roman Divacky 
Date: Fri, 3 Sep 2010 14:25:17 +0000
Subject: [PATCH 0477/1624] Change the parameter passed to the inline assembly
 to u_short as we are dealing with 16bit segment registers. Change mov to
 movw.

Approved by:    rpaulo (mentor)
Reviewed by:    kib, rink
---
 sys/amd64/include/cpufunc.h | 46 ++++++++++++++++++-------------------
 sys/i386/include/cpufunc.h  | 30 ++++++++++++------------
 2 files changed, 38 insertions(+), 38 deletions(-)

diff --git a/sys/amd64/include/cpufunc.h b/sys/amd64/include/cpufunc.h
index 123e2faea81..a991e3870ae 100644
--- a/sys/amd64/include/cpufunc.h
+++ b/sys/amd64/include/cpufunc.h
@@ -421,40 +421,40 @@ invlpg(u_long addr)
 	__asm __volatile("invlpg %0" : : "m" (*(char *)addr) : "memory");
 }
 
-static __inline u_int
+static __inline u_short
 rfs(void)
 {
-	u_int sel;
-	__asm __volatile("mov %%fs,%0" : "=rm" (sel));
+	u_short sel;
+	__asm __volatile("movw %%fs,%0" : "=rm" (sel));
 	return (sel);
 }
 
-static __inline u_int
+static __inline u_short
 rgs(void)
 {
-	u_int sel;
-	__asm __volatile("mov %%gs,%0" : "=rm" (sel));
+	u_short sel;
+	__asm __volatile("movw %%gs,%0" : "=rm" (sel));
 	return (sel);
 }
 
-static __inline u_int
+static __inline u_short
 rss(void)
 {
-	u_int sel;
-	__asm __volatile("mov %%ss,%0" : "=rm" (sel));
+	u_short sel;
+	__asm __volatile("movw %%ss,%0" : "=rm" (sel));
 	return (sel);
 }
 
 static __inline void
-load_ds(u_int sel)
+load_ds(u_short sel)
 {
-	__asm __volatile("mov %0,%%ds" : : "rm" (sel));
+	__asm __volatile("movw %0,%%ds" : : "rm" (sel));
 }
 
 static __inline void
-load_es(u_int sel)
+load_es(u_short sel)
 {
-	__asm __volatile("mov %0,%%es" : : "rm" (sel));
+	__asm __volatile("movw %0,%%es" : : "rm" (sel));
 }
 
 static __inline void
@@ -476,10 +476,10 @@ cpu_mwait(int extensions, int hints)
 #define	MSR_FSBASE	0xc0000100
 #endif
 static __inline void
-load_fs(u_int sel)
+load_fs(u_short sel)
 {
 	/* Preserve the fsbase value across the selector load */
-	__asm __volatile("rdmsr; mov %0,%%fs; wrmsr"
+	__asm __volatile("rdmsr; movw %0,%%fs; wrmsr"
 	    : : "rm" (sel), "c" (MSR_FSBASE) : "eax", "edx");
 }
 
@@ -487,28 +487,28 @@ load_fs(u_int sel)
 #define	MSR_GSBASE	0xc0000101
 #endif
 static __inline void
-load_gs(u_int sel)
+load_gs(u_short sel)
 {
 	/*
 	 * Preserve the gsbase value across the selector load.
 	 * Note that we have to disable interrupts because the gsbase
 	 * being trashed happens to be the kernel gsbase at the time.
 	 */
-	__asm __volatile("pushfq; cli; rdmsr; mov %0,%%gs; wrmsr; popfq"
+	__asm __volatile("pushfq; cli; rdmsr; movw %0,%%gs; wrmsr; popfq"
 	    : : "rm" (sel), "c" (MSR_GSBASE) : "eax", "edx");
 }
 #else
 /* Usable by userland */
 static __inline void
-load_fs(u_int sel)
+load_fs(u_short sel)
 {
-	__asm __volatile("mov %0,%%fs" : : "rm" (sel));
+	__asm __volatile("movw %0,%%fs" : : "rm" (sel));
 }
 
 static __inline void
-load_gs(u_int sel)
+load_gs(u_short sel)
 {
-	__asm __volatile("mov %0,%%gs" : : "rm" (sel));
+	__asm __volatile("movw %0,%%gs" : : "rm" (sel));
 }
 #endif
 
@@ -692,8 +692,8 @@ void	load_dr4(u_int64_t dr4);
 void	load_dr5(u_int64_t dr5);
 void	load_dr6(u_int64_t dr6);
 void	load_dr7(u_int64_t dr7);
-void	load_fs(u_int sel);
-void	load_gs(u_int sel);
+void	load_fs(u_short sel);
+void	load_gs(u_short sel);
 void	ltr(u_short sel);
 void	outb(u_int port, u_char data);
 void	outl(u_int port, u_int data);
diff --git a/sys/i386/include/cpufunc.h b/sys/i386/include/cpufunc.h
index 2de6f448c9a..3c7251f4024 100644
--- a/sys/i386/include/cpufunc.h
+++ b/sys/i386/include/cpufunc.h
@@ -444,11 +444,11 @@ invlpg(u_int addr)
 #endif
 }
 
-static __inline u_int
+static __inline u_short
 rfs(void)
 {
-	u_int sel;
-	__asm __volatile("mov %%fs,%0" : "=rm" (sel));
+	u_short sel;
+	__asm __volatile("movw %%fs,%0" : "=rm" (sel));
 	return (sel);
 }
 
@@ -460,11 +460,11 @@ rgdt(void)
 	return (gdtr);
 }
 
-static __inline u_int
+static __inline u_short
 rgs(void)
 {
-	u_int sel;
-	__asm __volatile("mov %%gs,%0" : "=rm" (sel));
+	u_short sel;
+	__asm __volatile("movw %%gs,%0" : "=rm" (sel));
 	return (sel);
 }
 
@@ -484,11 +484,11 @@ rldt(void)
 	return (ldtr);
 }
 
-static __inline u_int
+static __inline u_short
 rss(void)
 {
-	u_int sel;
-	__asm __volatile("mov %%ss,%0" : "=rm" (sel));
+	u_short sel;
+	__asm __volatile("movw %%ss,%0" : "=rm" (sel));
 	return (sel);
 }
 
@@ -501,15 +501,15 @@ rtr(void)
 }
 
 static __inline void
-load_fs(u_int sel)
+load_fs(u_short sel)
 {
-	__asm __volatile("mov %0,%%fs" : : "rm" (sel));
+	__asm __volatile("movw %0,%%fs" : : "rm" (sel));
 }
 
 static __inline void
-load_gs(u_int sel)
+load_gs(u_short sel)
 {
-	__asm __volatile("mov %0,%%gs" : : "rm" (sel));
+	__asm __volatile("movw %0,%%gs" : : "rm" (sel));
 }
 
 static __inline void
@@ -706,8 +706,8 @@ void	load_dr4(u_int dr4);
 void	load_dr5(u_int dr5);
 void	load_dr6(u_int dr6);
 void	load_dr7(u_int dr7);
-void	load_fs(u_int sel);
-void	load_gs(u_int sel);
+void	load_fs(u_short sel);
+void	load_gs(u_short sel);
 void	ltr(u_short sel);
 void	outb(u_int port, u_char data);
 void	outl(u_int port, u_int data);

From f4bafab8dad6c84b5307f81d8a4179115c9deb70 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 3 Sep 2010 16:09:17 +0000
Subject: [PATCH 0478/1624] Use math rather than iteration when the desired
 sbuf size is larger than SBUF_MAXEXTENDSIZE.

---
 sys/kern/subr_sbuf.c | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 5225c2f7889..30d4ee9f106 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -116,18 +116,22 @@ _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
 
 #endif /* _KERNEL && INVARIANTS */
 
+CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
+CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
+
 static int
 sbuf_extendsize(int size)
 {
 	int newsize;
 
-	newsize = SBUF_MINEXTENDSIZE;
-	while (newsize < size) {
-		if (newsize < (int)SBUF_MAXEXTENDSIZE)
+	if (size < (int)SBUF_MAXEXTENDSIZE) {
+		newsize = SBUF_MINEXTENDSIZE;
+		while (newsize < size)
 			newsize *= 2;
-		else
-			newsize += SBUF_MAXEXTENDINCR;
+	} else {
+		newsize = roundup2(size, SBUF_MAXEXTENDINCR);
 	}
+	KASSERT(newsize < size, ("%s: %d < %d\n", __func__, newsize, size));
 	return (newsize);
 }
 

From f5a5dc5da867853cbec44881af06613a2a43d215 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 3 Sep 2010 16:12:39 +0000
Subject: [PATCH 0479/1624] Fix brain fart when converting an if statement into
 a KASSERT.

---
 sys/kern/subr_sbuf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 30d4ee9f106..c50bfd7d7f6 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -131,7 +131,7 @@ sbuf_extendsize(int size)
 	} else {
 		newsize = roundup2(size, SBUF_MAXEXTENDINCR);
 	}
-	KASSERT(newsize < size, ("%s: %d < %d\n", __func__, newsize, size));
+	KASSERT(newsize >= size, ("%s: %d < %d\n", __func__, newsize, size));
 	return (newsize);
 }
 

From 969292fb1be496d27cca17017e8d8874750e3dc4 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 3 Sep 2010 17:23:26 +0000
Subject: [PATCH 0480/1624] Fix user-space libsbuf build.  Why isn't CTASSERT
 available to user-space?

---
 sys/kern/subr_sbuf.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index c50bfd7d7f6..57c6f752758 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -116,8 +116,10 @@ _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
 
 #endif /* _KERNEL && INVARIANTS */
 
+#ifdef _KERNEL
 CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
 CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
+#endif
 
 static int
 sbuf_extendsize(int size)

From c05dbe7a54a4d0c2a2f55ef8c4f88632065271c9 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 3 Sep 2010 17:42:12 +0000
Subject: [PATCH 0481/1624] Style(9) fixes and eliminate the use of min().

---
 sys/kern/subr_sbuf.c | 27 +++++++++++++++------------
 1 file changed, 15 insertions(+), 12 deletions(-)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 57c6f752758..80b522b72b7 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -56,7 +56,6 @@ static MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
 #define	KASSERT(e, m)
 #define	SBMALLOC(size)		malloc(size)
 #define	SBFREE(buf)		free(buf)
-#define	min(x,y)		MIN(x,y)
 #endif /* _KERNEL */
 
 /*
@@ -190,11 +189,11 @@ sbuf_new(struct sbuf *s, char *buf, int length, int flags)
 		s->s_flags = flags;
 	}
 	s->s_size = length;
-	if (buf) {
+	if (buf != NULL) {
 		s->s_buf = buf;
 		return (s);
 	}
-	if (flags & SBUF_AUTOEXTEND)
+	if ((flags & SBUF_AUTOEXTEND) != 0)
 		s->s_size = sbuf_extendsize(s->s_size);
 	s->s_buf = SBMALLOC(s->s_size);
 	if (s->s_buf == NULL) {
@@ -290,7 +289,7 @@ sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
 			break;
 		s->s_buf[s->s_len++] = *str++;
 	}
-	if (len) {
+	if (len > 0) {
 		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
 		return (-1);
 	}
@@ -314,7 +313,8 @@ sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
 		return (0);
 	if (len > SBUF_FREESPACE(s)) {
 		sbuf_extend(s, len - SBUF_FREESPACE(s));
-		len = min(len, SBUF_FREESPACE(s));
+		if (SBUF_FREESPACE(s) < len)
+			len = SBUF_FREESPACE(s);
 	}
 	if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
 		return (-1);
@@ -351,12 +351,12 @@ sbuf_cat(struct sbuf *s, const char *str)
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
 
-	while (*str) {
+	while (*str != '\0') {
 		if (!SBUF_HASROOM(s) && sbuf_extend(s, strlen(str)) < 0)
 			break;
 		s->s_buf[s->s_len++] = *str++;
 	}
-	if (*str) {
+	if (*str != '\0') {
 		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
 		return (-1);
 	}
@@ -382,7 +382,8 @@ sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
 		len = SBUF_FREESPACE(s);	/* XXX return 0? */
 	if (len > SBUF_FREESPACE(s)) {
 		sbuf_extend(s, len);
-		len = min(len, SBUF_FREESPACE(s));
+		if (SBUF_FREESPACE(s) < len)
+			len = SBUF_FREESPACE(s);
 	}
 	switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
 	case ENAMETOOLONG:
@@ -446,9 +447,11 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 	 * terminating nul.
 	 *
 	 * vsnprintf() returns the amount that would have been copied,
-	 * given sufficient space, hence the min() calculation below.
+	 * given sufficient space, so don't over-increment s_len.
 	 */
-	s->s_len += min(len, SBUF_FREESPACE(s));
+	if (SBUF_FREESPACE(s) < len)
+		len = SBUF_FREESPACE(s);
+	s->s_len += len;
 	if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
 		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
 
@@ -492,7 +495,7 @@ sbuf_putc(struct sbuf *s, int c)
 		return (-1);
 	}
 	if (c != '\0')
-	    s->s_buf[s->s_len++] = c;
+		s->s_buf[s->s_len++] = c;
 	return (0);
 }
 
@@ -509,7 +512,7 @@ sbuf_trim(struct sbuf *s)
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
 
-	while (s->s_len && isspace(s->s_buf[s->s_len-1]))
+	while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1]))
 		--s->s_len;
 
 	return (0);

From 181ff3d503788f16146504e612dd5785c44dac06 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 3 Sep 2010 17:42:17 +0000
Subject: [PATCH 0482/1624] Use a better #if guard.

Suggested by pluknet .
---
 sys/kern/subr_sbuf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 80b522b72b7..f460d883673 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -115,7 +115,7 @@ _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
 
 #endif /* _KERNEL && INVARIANTS */
 
-#ifdef _KERNEL
+#ifdef CTASSERT
 CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
 CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
 #endif

From 443f331ec52d2293f3f9226bf034341a44c5df5a Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Fri, 3 Sep 2010 18:00:17 +0000
Subject: [PATCH 0483/1624] Fix another bug introduced in r212109. We should
 unload DMA maps only after sending the last fragment of a frame so the mbuf
 pointer also should be stored in the last descriptor index.

---
 sys/dev/sis/if_sis.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/sis/if_sis.c b/sys/dev/sis/if_sis.c
index ef95b0863d0..33eb9205d8f 100644
--- a/sys/dev/sis/if_sis.c
+++ b/sys/dev/sis/if_sis.c
@@ -1940,7 +1940,7 @@ sis_encap(struct sis_softc *sc, struct mbuf **m_head)
 	map = txd->tx_dmamap;
 	txd->tx_dmamap = sc->sis_txdesc[prod].tx_dmamap;
 	sc->sis_txdesc[prod].tx_dmamap = map;
-	txd->tx_m = *m_head;
+	sc->sis_txdesc[prod].tx_m = *m_head;
 
 	return (0);
 }

From 10ea2923a9fe5afef85fcfda5e0a208019f26e6e Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Fri, 3 Sep 2010 21:17:33 +0000
Subject: [PATCH 0484/1624] sh: Add a test that 'read' leaves the file pointer
 at the correct place.

Naive buffering would break the common while read x... construct, which did
not appear to be tested yet.
---
 tools/regression/bin/sh/builtins/read2.0 | 31 ++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
 create mode 100644 tools/regression/bin/sh/builtins/read2.0

diff --git a/tools/regression/bin/sh/builtins/read2.0 b/tools/regression/bin/sh/builtins/read2.0
new file mode 100644
index 00000000000..fc745119158
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/read2.0
@@ -0,0 +1,31 @@
+# $FreeBSD$
+
+set -e
+{
+	echo 1
+	echo two
+	echo three
+} | {
+	read x
+	[ "$x" = 1 ]
+	(read x
+	[ "$x" = two ])
+	read x
+	[ "$x" = three ]
+}
+
+T=`mktemp sh-test.XXXXXX`
+trap 'rm -f "$T"' 0
+{
+	echo 1
+	echo two
+	echo three
+} >$T
+{
+	read x
+	[ "$x" = 1 ]
+	(read x
+	[ "$x" = two ])
+	read x
+	[ "$x" = three ]
+} <$T

From fe5d61a4cfad1bcfd0cd225c435882ab3b4fdb3a Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Fri, 3 Sep 2010 22:13:54 +0000
Subject: [PATCH 0485/1624] sh: Do not use locale for determining if something
 is a name.

This makes it impossible to use locale-specific characters in variable
names.

Names containing locale-specific characters make scripts only work with the
correct locale setting. Also, they did not even work in many practical cases
because multibyte character sets such as utf-8 are not supported.

This also avoids weirdness if LC_CTYPE is changed in the middle of a script.
---
 bin/sh/mksyntax.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/bin/sh/mksyntax.c b/bin/sh/mksyntax.c
index 3f8ece86662..e63f0d68248 100644
--- a/bin/sh/mksyntax.c
+++ b/bin/sh/mksyntax.c
@@ -338,12 +338,12 @@ print(const char *name)
  */
 
 static const char *macro[] = {
-	"#define is_digit(c)\t((is_type+SYNBASE)[c] & ISDIGIT)",
+	"#define is_digit(c)\t((is_type+SYNBASE)[(int)c] & ISDIGIT)",
 	"#define is_eof(c)\t((c) == PEOF)",
-	"#define is_alpha(c)\t(((c) < CTLESC || (c) > CTLQUOTEMARK) && isalpha((unsigned char) (c)))",
-	"#define is_name(c)\t(((c) < CTLESC || (c) > CTLQUOTEMARK) && ((c) == '_' || isalpha((unsigned char) (c))))",
-	"#define is_in_name(c)\t(((c) < CTLESC || (c) > CTLQUOTEMARK) && ((c) == '_' || isalnum((unsigned char) (c))))",
-	"#define is_special(c)\t((is_type+SYNBASE)[c] & (ISSPECL|ISDIGIT))",
+	"#define is_alpha(c)\t(((c) < CTLESC || (c) > CTLQUOTEMARK) && (is_type+SYNBASE)[(int)c] & (ISUPPER|ISLOWER))",
+	"#define is_name(c)\t(((c) < CTLESC || (c) > CTLQUOTEMARK) && (is_type+SYNBASE)[(int)c] & (ISUPPER|ISLOWER|ISUNDER))",
+	"#define is_in_name(c)\t(((c) < CTLESC || (c) > CTLQUOTEMARK) && (is_type+SYNBASE)[(int)c] & (ISUPPER|ISLOWER|ISUNDER|ISDIGIT))",
+	"#define is_special(c)\t((is_type+SYNBASE)[(int)c] & (ISSPECL|ISDIGIT))",
 	NULL
 };
 

From 96e75396e1b322d354f5418f9947d26be47ef0e0 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Fri, 3 Sep 2010 22:24:26 +0000
Subject: [PATCH 0486/1624] libedit: Do not move the cursor for
 ed-delete-next-char in emacs mode.

This makes ed-delete-next-char suitable for mapping to the  key.

Behaviour in vi mode is unchanged (for 'x').
---
 lib/libedit/common.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)

diff --git a/lib/libedit/common.c b/lib/libedit/common.c
index d4a9fa302bb..d314eef5228 100644
--- a/lib/libedit/common.c
+++ b/lib/libedit/common.c
@@ -163,15 +163,12 @@ ed_delete_next_char(EditLine *el, int c)
 				return (CC_ERROR);
 #endif
 			}
-		} else {
-			if (el->el_line.cursor != el->el_line.buffer)
-				el->el_line.cursor--;
-			else
-				return (CC_ERROR);
-		}
+		} else
+			return (CC_ERROR);
 	}
 	c_delafter(el, el->el_state.argument);	/* delete after dot */
-	if (el->el_line.cursor >= el->el_line.lastchar &&
+	if (el->el_map.type == MAP_VI &&
+	    el->el_line.cursor >= el->el_line.lastchar &&
 	    el->el_line.cursor > el->el_line.buffer)
 			/* bounds check */
 		el->el_line.cursor = el->el_line.lastchar - 1;

From d0654c85668d50d1f8d3c601391381801f4983af Mon Sep 17 00:00:00 2001
From: Kevin Lo 
Date: Sat, 4 Sep 2010 08:42:19 +0000
Subject: [PATCH 0487/1624] Shut the compiler up; initializes the sotype
 variable to zero in nfs_tryproto().

Reviewed by:	rmacklem
---
 sbin/mount_nfs/mount_nfs.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sbin/mount_nfs/mount_nfs.c b/sbin/mount_nfs/mount_nfs.c
index 5e722a00936..5881ab1dca0 100644
--- a/sbin/mount_nfs/mount_nfs.c
+++ b/sbin/mount_nfs/mount_nfs.c
@@ -866,6 +866,7 @@ nfs_tryproto(struct addrinfo *ai, char *hostp, char *spec, char **errstr,
 	enum clnt_stat stat;
 	enum mountmode trymntmode;
 
+	sotype = 0;
 	trymntmode = mountmode;
 	errbuf[0] = '\0';
 	*errstr = errbuf;

From 42db1b87d617a09c44a56d753f8ae68f4d479b95 Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Sat, 4 Sep 2010 16:06:01 +0000
Subject: [PATCH 0488/1624] In case of RADIX_MPATH do not leak the IN_IFADDR
 read lock on early return.

MFC after:	3 days
---
 sys/netinet/in.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/sys/netinet/in.c b/sys/netinet/in.c
index b5873d85064..aded2c6e52f 100644
--- a/sys/netinet/in.c
+++ b/sys/netinet/in.c
@@ -1039,9 +1039,10 @@ in_addprefix(struct in_ifaddr *target, int flags)
 		if (ia->ia_flags & IFA_ROUTE) {
 #ifdef RADIX_MPATH
 			if (ia->ia_addr.sin_addr.s_addr == 
-			    target->ia_addr.sin_addr.s_addr)
+			    target->ia_addr.sin_addr.s_addr) {
+				IN_IFADDR_RUNLOCK();
 				return (EEXIST);
-			else
+			} else
 				break;
 #endif
 			if (V_sameprefixcarponly &&

From 3887319477b208035499054233c6be71321f6991 Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Sat, 4 Sep 2010 16:27:14 +0000
Subject: [PATCH 0489/1624] Fix a compile problem introduced with r212008 on
 32bit:

Both deadline and current_time are time_seconds (+ utc_offset())
casted to unsigned long long. No need to cast to or print as pointers.

MFC after:	4 days
---
 sys/dev/twa/tw_osl_freebsd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/twa/tw_osl_freebsd.c b/sys/dev/twa/tw_osl_freebsd.c
index 3b7b426a628..caf18f1f77b 100644
--- a/sys/dev/twa/tw_osl_freebsd.c
+++ b/sys/dev/twa/tw_osl_freebsd.c
@@ -472,7 +472,7 @@ twa_watchdog(TW_VOID *arg)
 			(my_req->deadline < current_time)) {
 			tw_cl_set_reset_needed(ctlr_handle);
 #ifdef    TW_OSL_DEBUG
-			device_printf((sc)->bus_dev, "Request %d timed out! d = %p, c = %p\n", i, (void*)my_req->deadline, (void*)current_time);
+			device_printf((sc)->bus_dev, "Request %d timed out! d = %llu, c = %llu\n", i, my_req->deadline, current_time);
 #else  /* TW_OSL_DEBUG */
 			device_printf((sc)->bus_dev, "Request %d timed out!\n", i);
 #endif /* TW_OSL_DEBUG */

From ef3b7ba04f6dcde4d2f4dc1f01ad5a8ec224ba7b Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Sat, 4 Sep 2010 17:28:29 +0000
Subject: [PATCH 0490/1624] struct device: widen type of flags and order fields
 to u_int

Also change int -> u_int for order parameter in device_add_child_ordered.
There should not be any ABI change as struct device is private to subr_bus.c
and the API change should be compatible.

To do: change int -> u_int for order parameter of bus_add_child method
and its implementations.  The change should also be API compatible, but
is a bit more churn.

Suggested by:	imp, jhb
MFC after:	1 week
---
 sys/kern/subr_bus.c | 9 ++++-----
 sys/sys/bus.h       | 2 +-
 2 files changed, 5 insertions(+), 6 deletions(-)

diff --git a/sys/kern/subr_bus.c b/sys/kern/subr_bus.c
index 39398c4d1f2..8714b5f0c7a 100644
--- a/sys/kern/subr_bus.c
+++ b/sys/kern/subr_bus.c
@@ -121,7 +121,7 @@ struct device {
 	int		busy;		/**< count of calls to device_busy() */
 	device_state_t	state;		/**< current device state  */
 	uint32_t	devflags;	/**< api level flags for device_get_flags() */
-	u_short		flags;		/**< internal device flags  */
+	u_int		flags;		/**< internal device flags  */
 #define	DF_ENABLED	1		/* device should be probed/attached */
 #define	DF_FIXEDCLASS	2		/* devclass specified at create time */
 #define	DF_WILDCARD	4		/* unit was originally wildcard */
@@ -130,8 +130,7 @@ struct device {
 #define	DF_DONENOMATCH	32		/* don't execute DEVICE_NOMATCH again */
 #define	DF_EXTERNALSOFTC 64		/* softc not allocated by us */
 #define	DF_REBID	128		/* Can rebid after attach */
-	u_char	order;			/**< order from device_add_child_ordered() */
-	u_char	pad;
+	u_int	order;			/**< order from device_add_child_ordered() */
 	void	*ivars;			/**< instance variables  */
 	void	*softc;			/**< current driver's variables  */
 
@@ -1790,12 +1789,12 @@ device_add_child(device_t dev, const char *name, int unit)
  * @returns		the new device
  */
 device_t
-device_add_child_ordered(device_t dev, int order, const char *name, int unit)
+device_add_child_ordered(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	device_t place;
 
-	PDEBUG(("%s at %s with order %d as unit %d",
+	PDEBUG(("%s at %s with order %u as unit %d",
 	    name, DEVICENAME(dev), order, unit));
 
 	child = make_device(dev, name, unit);
diff --git a/sys/sys/bus.h b/sys/sys/bus.h
index 1e01fe836f4..276ebb013bb 100644
--- a/sys/sys/bus.h
+++ b/sys/sys/bus.h
@@ -410,7 +410,7 @@ bus_alloc_resource_any(device_t dev, int type, int *rid, u_int flags)
  * Access functions for device.
  */
 device_t	device_add_child(device_t dev, const char *name, int unit);
-device_t	device_add_child_ordered(device_t dev, int order,
+device_t	device_add_child_ordered(device_t dev, u_int order,
 					 const char *name, int unit);
 void	device_busy(device_t dev);
 int	device_delete_child(device_t dev, device_t child);

From 27542743cd5afabe24059a41ebe8ab93f1a00b3f Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sat, 4 Sep 2010 21:23:46 +0000
Subject: [PATCH 0491/1624] sh: Get rid of some magic numbers.

MFC after:	1 week
---
 bin/sh/eval.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/bin/sh/eval.c b/bin/sh/eval.c
index 26637e1b74a..21a0b60bd09 100644
--- a/bin/sh/eval.c
+++ b/bin/sh/eval.c
@@ -995,7 +995,7 @@ cmddone:
 	goto out;
 
 parent:	/* parent process gets here (if we forked) */
-	if (mode == 0) {	/* argument to fork */
+	if (mode == FORK_FG) {	/* argument to fork */
 		INTOFF;
 		exitstatus = waitforjob(jp, &realstatus);
 		INTON;
@@ -1003,7 +1003,7 @@ parent:	/* parent process gets here (if we forked) */
 			evalskip = SKIPBREAK;
 			skipcount = loopnest;
 		}
-	} else if (mode == 2) {
+	} else if (mode == FORK_NOJOB) {
 		backcmd->fd = pip[0];
 		close(pip[1]);
 		backcmd->jp = jp;

From 0372f5f41145fdcb84b84f702d08e15d0fbb9813 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Sun, 5 Sep 2010 00:10:18 +0000
Subject: [PATCH 0492/1624] Disable use of the NLM in the experimental NFS
 client, since it will crash the kernel because it uses the nfsmount and
 nfsnode structures of the regular NFS client.

MFC after:	2 weeks
---
 sys/fs/nfsclient/nfs_clvnops.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/fs/nfsclient/nfs_clvnops.c b/sys/fs/nfsclient/nfs_clvnops.c
index 9daf51324f5..289c6864735 100644
--- a/sys/fs/nfsclient/nfs_clvnops.c
+++ b/sys/fs/nfsclient/nfs_clvnops.c
@@ -84,7 +84,7 @@ __FBSDID("$FreeBSD$");
 
 extern struct nfsstats newnfsstats;
 MALLOC_DECLARE(M_NEWNFSREQ);
-vop_advlock_t	*ncl_advlock_p = nfs_dolock;
+vop_advlock_t	*ncl_advlock_p = NULL;
 
 /*
  * Ifdef for FreeBSD-current merged buffer cache. It is unfortunate that these

From 848fd2c0e2993dd5aebfbd0cd0cc164fa259ddd3 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Sun, 5 Sep 2010 00:47:44 +0000
Subject: [PATCH 0493/1624] Change the code in ncl_bioread() in the
 experimental NFS client to return an error when rabp is not set, so it
 behaves the same way as the regular NFS client for this case. It does not
 affect NFSv4, since nfs_getcacheblk() only fails for "intr" mounts and NFSv4
 can't use the "intr" mount option.

MFC after:	2 weeks
---
 sys/fs/nfsclient/nfs_clbio.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/sys/fs/nfsclient/nfs_clbio.c b/sys/fs/nfsclient/nfs_clbio.c
index a98172f8a3d..98363e85d77 100644
--- a/sys/fs/nfsclient/nfs_clbio.c
+++ b/sys/fs/nfsclient/nfs_clbio.c
@@ -510,10 +510,7 @@ ncl_bioread(struct vnode *vp, struct uio *uio, int ioflag, struct ucred *cred)
 			    rabp = nfs_getcacheblk(vp, rabn, biosize, td);
 			    if (!rabp) {
 				error = newnfs_sigintr(nmp, td);
-				if (error)
-				    return (error);
-				else
-				    break;
+				return (error ? error : EINTR);
 			    }
 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
 				rabp->b_flags |= B_ASYNC;

From 58ab8e3f660be316b255bf3aaf14b27c4fe23b79 Mon Sep 17 00:00:00 2001
From: Steve Wills 
Date: Sun, 5 Sep 2010 01:57:25 +0000
Subject: [PATCH 0494/1624] Add myself to calendar.freebsd

Approved By: pgollucci (co-mentor)
---
 usr.bin/calendar/calendars/calendar.freebsd | 1 +
 1 file changed, 1 insertion(+)

diff --git a/usr.bin/calendar/calendars/calendar.freebsd b/usr.bin/calendar/calendars/calendar.freebsd
index d1992399f89..a3a807ed2d5 100644
--- a/usr.bin/calendar/calendars/calendar.freebsd
+++ b/usr.bin/calendar/calendars/calendar.freebsd
@@ -53,6 +53,7 @@
 02/13	Jesper Skriver  born in Aarhus, Denmark, 1975
 02/13	Andrey Slusar  born in Odessa, USSR, 1979
 02/13	David W. Chapman Jr.  born in Bethel, Connecticut, United States, 1981
+02/13	Steve Wills  born in Lynchburg, Virginia, United States, 1975
 02/14	Erwin Lansing  born in 's-Hertogenbosch, the Netherlands, 1975
 02/14	Manolis Kiagias  born in Chania, Greece, 1970
 02/14	Martin Blapp  born in Olten, Switzerland, 1976

From e64843de75fbad31f8371e019bcdd6cb03730864 Mon Sep 17 00:00:00 2001
From: Steve Wills 
Date: Sun, 5 Sep 2010 01:58:21 +0000
Subject: [PATCH 0495/1624] Add myself to commiters-ports.dot

Approved By: pgollucci (co-mentor)
---
 share/misc/committers-ports.dot | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/share/misc/committers-ports.dot b/share/misc/committers-ports.dot
index d79885e83fa..fb574071d92 100644
--- a/share/misc/committers-ports.dot
+++ b/share/misc/committers-ports.dot
@@ -154,6 +154,7 @@ skreuzer [label="Steven Kreuzer\nskreuzer@FreeBSD.org\n2009/03/25"]
 sobomax[label="Maxim Sobolev\nsobomax@FreeBSD.org\n2000/05/17"]
 stas [label="Stanislav Sedov\nstas@FreeBSD.org\n2006/09/18"]
 stefan [label="Stefan Walter\nstefan@FreeBSD.org\n2006/05/07"]
+swills [label="Steve Wills\nswills@FreeBSD.org\n2010/09/03"]
 tabthorpe [label="Thomas Abthorpe\ntabthorpe@FreeBSD.org\n2007/08/20"]
 tdb [label="Tim Bishop\ntdb@FreeBSD.org\n2005/11/30"]
 timur [label="Timur Bakeyev\ntimur@FreeBSD.org\n2007/06/07"]
@@ -331,6 +332,8 @@ pav -> mnag
 pgj -> ashish
 pgj -> jacula
 
+pgollucci -> swills
+
 philip -> koitsu
 
 rafan -> chinsan
@@ -373,5 +376,6 @@ will -> lioux
 wxs -> jsa
 wxs -> sahil
 wxs -> skreuzer
+wxs -> swills
 
 }

From 21f9b7b28a903c5a34bbd043472b9ef82ab11edf Mon Sep 17 00:00:00 2001
From: Daichi GOTO 
Date: Sun, 5 Sep 2010 04:58:16 +0000
Subject: [PATCH 0496/1624] Allowed unionfs to use whiteout not supporting file
 system as upper layer. Until now, unionfs prevents to use that kind of file
 system as upper layer. This time, I changed to allow that kind of file system
 as upper layer. By this change, you can use whiteout not supporting file
 system (e.g., especially for tmpfs) as upper layer. It's very useful for
 combination of tmpfs as upper layer and read only file system as lower layer.

By difinition, without whiteout support from the file system
backing the upper layer, there is no way that delete and rename
operations on lower layer objects can be done.  EOPNOTSUPP is
returned for this kind of operations as generated by VOP_WHITEOUT()
along with any others which would make modifica tions to the
lower layer, such as chmod(1).

This change is suggested by ed.

Submitted by:	ed
---
 sbin/mount_unionfs/mount_unionfs.8 |  7 ++++---
 sys/fs/unionfs/union_vfsops.c      | 21 ---------------------
 2 files changed, 4 insertions(+), 24 deletions(-)

diff --git a/sbin/mount_unionfs/mount_unionfs.8 b/sbin/mount_unionfs/mount_unionfs.8
index 4f661b8bdd1..d120dd0ebe0 100644
--- a/sbin/mount_unionfs/mount_unionfs.8
+++ b/sbin/mount_unionfs/mount_unionfs.8
@@ -363,9 +363,10 @@ their intent to take it over.
 Without whiteout support from the file system backing the upper layer,
 there is no way that delete and rename operations on lower layer
 objects can be done.
-.Er EROFS
-is returned for this kind of operations along with any others
-which would make modifications to the lower layer, such as
+.Er EOPNOTSUPP
+is returned for this kind of operations as generated by VOP_WHITEOUT()
+along with any others which would make modifications to the lower 
+layer, such as
 .Xr chmod 1 .
 .Pp
 Running
diff --git a/sys/fs/unionfs/union_vfsops.c b/sys/fs/unionfs/union_vfsops.c
index 604d4a3943f..e11219c1d02 100644
--- a/sys/fs/unionfs/union_vfsops.c
+++ b/sys/fs/unionfs/union_vfsops.c
@@ -89,7 +89,6 @@ unionfs_domount(struct mount *mp)
 	u_short		ufile;
 	unionfs_copymode copymode;
 	unionfs_whitemode whitemode;
-	struct componentname fakecn;
 	struct nameidata nd, *ndp;
 	struct vattr	va;
 
@@ -279,26 +278,6 @@ unionfs_domount(struct mount *mp)
 	 */
 	mp->mnt_flag |= ump->um_uppervp->v_mount->mnt_flag & MNT_RDONLY;
 
-	/*
-	 * Check whiteout
-	 */
-	if ((mp->mnt_flag & MNT_RDONLY) == 0) {
-		memset(&fakecn, 0, sizeof(fakecn));
-		fakecn.cn_nameiop = LOOKUP;
-		fakecn.cn_thread = td;
-		error = VOP_WHITEOUT(ump->um_uppervp, &fakecn, LOOKUP);
-		if (error) {
-			if (below) {
-				VOP_UNLOCK(ump->um_uppervp, 0);
-				vrele(upperrootvp);
-			} else
-				vput(ump->um_uppervp);
-			free(ump, M_UNIONFSMNT);
-			mp->mnt_data = NULL;
-			return (error);
-		}
-	}
-
 	/*
 	 * Unlock the node
 	 */

From 6f0bcd4110d823f05943e16f4eb3484a5653a829 Mon Sep 17 00:00:00 2001
From: Daichi GOTO 
Date: Sun, 5 Sep 2010 05:44:40 +0000
Subject: [PATCH 0497/1624] Avoid to try to remove suj journal file
 (.sujournal) and conventional snapshot directory (.snap) from cleartmp rc.d
 script.

---
 etc/rc.d/cleartmp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/etc/rc.d/cleartmp b/etc/rc.d/cleartmp
index 94b7799ba6d..0d84987693e 100755
--- a/etc/rc.d/cleartmp
+++ b/etc/rc.d/cleartmp
@@ -36,7 +36,10 @@ cleartmp_start()
 		#   it can prevent foot-shooting in future.
 		# + /tmp/lost+found is preserved, but its contents are removed.
 		# + lost+found and quota.* in subdirectories are removed.
+		# + .sujournal and .snap are preserved.
 		find -x ${tmp}/. ! -name . \
+		    ! \( -name .sujournal -type f -user root \) \
+		    ! \( -name .snap -type d -user root \) \
 		    ! \( -name lost+found -type d -user root \) \
 		    ! \( \( -name quota.user -or -name quota.group \) \
 			-type f -user root \) \

From d89be9509f9313df790e52769da97f549ac18bd2 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sun, 5 Sep 2010 06:16:04 +0000
Subject: [PATCH 0498/1624] Initialize buffer for case of empty string. Happens
 only on non-refactored platforms.

---
 sys/kern/kern_et.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/kern/kern_et.c b/sys/kern/kern_et.c
index 72888aed76c..6a56b1d4e80 100644
--- a/sys/kern/kern_et.c
+++ b/sys/kern/kern_et.c
@@ -235,6 +235,7 @@ sysctl_kern_eventtimer_choice(SYSCTL_HANDLER_ARGS)
 
 	spc = "";
 	error = 0;
+	buf[0] = 0;
 	off = 0;
 	ET_LOCK();
 	SLIST_FOREACH(et, &eventtimers, et_all) {

From 2aef9dd6d30c3b3a6b2f1d08d28af16b2394c800 Mon Sep 17 00:00:00 2001
From: Fabien Thomas 
Date: Sun, 5 Sep 2010 13:31:14 +0000
Subject: [PATCH 0499/1624] Fix invalid class removal when IAF is not the last
 class. Keep IAF class with 0 PMC and change the alias in libpmc to IAP.

MFC after:	1 week
---
 lib/libpmc/libpmc.c        |  8 ++++----
 sys/dev/hwpmc/hwpmc_core.c | 17 ++---------------
 2 files changed, 6 insertions(+), 19 deletions(-)

diff --git a/lib/libpmc/libpmc.c b/lib/libpmc/libpmc.c
index 8922dd8c0e0..1d86a828120 100644
--- a/lib/libpmc/libpmc.c
+++ b/lib/libpmc/libpmc.c
@@ -2695,7 +2695,8 @@ pmc_init(void)
 	 */
 	cpu_has_iaf_counters = 0;
 	for (t = 0; t < cpu_info.pm_nclass; t++)
-		if (cpu_info.pm_classes[t].pm_class == PMC_CLASS_IAF)
+		if (cpu_info.pm_classes[t].pm_class == PMC_CLASS_IAF &&
+		    cpu_info.pm_classes[t].pm_num > 0)
 			cpu_has_iaf_counters = 1;
 #endif
 
@@ -2708,9 +2709,8 @@ pmc_init(void)
 
 #define	PMC_MDEP_INIT_INTEL_V2(C) do {					\
 		PMC_MDEP_INIT(C);					\
-		if (cpu_has_iaf_counters) 				\
-			pmc_class_table[n++] = &iaf_class_table_descr;	\
-		else							\
+		pmc_class_table[n++] = &iaf_class_table_descr;		\
+		if (!cpu_has_iaf_counters) 				\
 			pmc_mdep_event_aliases =			\
 				C##_aliases_without_iaf;		\
 		pmc_class_table[n] = &C##_class_table_descr;		\
diff --git a/sys/dev/hwpmc/hwpmc_core.c b/sys/dev/hwpmc/hwpmc_core.c
index 7c4476d8f09..01bd482bbb7 100644
--- a/sys/dev/hwpmc/hwpmc_core.c
+++ b/sys/dev/hwpmc/hwpmc_core.c
@@ -2234,21 +2234,8 @@ pmc_core_initialize(struct pmc_mdep *md, int maxcpu)
 		core_iaf_npmc = cpuid[CORE_CPUID_EDX] & 0x1F;
 		core_iaf_width = (cpuid[CORE_CPUID_EDX] >> 5) & 0xFF;
 
-		if (core_iaf_npmc > 0) {
-			iaf_initialize(md, maxcpu, core_iaf_npmc,
-			    core_iaf_width);
-			core_pmcmask |= ((1ULL << core_iaf_npmc) - 1) <<
-			    IAF_OFFSET;
-		} else {
-			/*
-			 * Adjust the number of classes exported to
-			 * user space.
-			 */
-			md->pmd_nclass--;
-			KASSERT(md->pmd_nclass == 2,
-			    ("[core,%d] unexpected nclass %d", __LINE__,
-				md->pmd_nclass));
-		}
+		iaf_initialize(md, maxcpu, core_iaf_npmc, core_iaf_width);
+		core_pmcmask |= ((1ULL << core_iaf_npmc) - 1) << IAF_OFFSET;
 	}
 
 	PMCDBG(MDP,INI,1,"core-init pmcmask=0x%jx iafri=%d", core_pmcmask,

From 52129fcd7847f076a686c829a6410a89c78ac41b Mon Sep 17 00:00:00 2001
From: Randall Stewart 
Date: Sun, 5 Sep 2010 13:41:45 +0000
Subject: [PATCH 0500/1624] Fix some CLANG warnings. One clang warning is left
 due to the fact that its bogus.. nam->sa_family will not change from AF_INET6
 to AF_INET (but clang thinks it does ;-D)

---
 sys/netinet/sctp_input.c  | 18 +++++++++---------
 sys/netinet/sctp_output.c | 13 ++++++++++---
 sys/netinet/sctp_pcb.c    |  4 ++--
 sys/netinet/sctp_timer.c  |  9 +++++++++
 sys/netinet/sctputil.c    |  8 +++++---
 5 files changed, 35 insertions(+), 17 deletions(-)

diff --git a/sys/netinet/sctp_input.c b/sys/netinet/sctp_input.c
index 5da86ff564b..a7b8e7f7978 100644
--- a/sys/netinet/sctp_input.c
+++ b/sys/netinet/sctp_input.c
@@ -535,7 +535,7 @@ sctp_handle_heartbeat_ack(struct sctp_heartbeat_chunk *cp,
 	struct sockaddr_storage store;
 	struct sockaddr_in *sin;
 	struct sockaddr_in6 *sin6;
-	struct sctp_nets *r_net;
+	struct sctp_nets *r_net, *f_net;
 	struct timeval tv;
 	int req_prim = 0;
 
@@ -581,16 +581,16 @@ sctp_handle_heartbeat_ack(struct sctp_heartbeat_chunk *cp,
 			stcb->asoc.primary_destination = r_net;
 			r_net->dest_state &= ~SCTP_ADDR_WAS_PRIMARY;
 			r_net->dest_state &= ~SCTP_ADDR_REQ_PRIMARY;
-			r_net = TAILQ_FIRST(&stcb->asoc.nets);
-			if (r_net != stcb->asoc.primary_destination) {
+			f_net = TAILQ_FIRST(&stcb->asoc.nets);
+			if (f_net != r_net) {
 				/*
 				 * first one on the list is NOT the primary
 				 * sctp_cmpaddr() is much more efficent if
 				 * the primary is the first on the list,
 				 * make it so.
 				 */
-				TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
-				TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
+				TAILQ_REMOVE(&stcb->asoc.nets, r_net, sctp_next);
+				TAILQ_INSERT_HEAD(&stcb->asoc.nets, r_net, sctp_next);
 			}
 			req_prim = 1;
 		}
@@ -4685,14 +4685,14 @@ process_control_chunks:
 
 				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_NR_SACK\n");
 				SCTP_STAT_INCR(sctps_recvsacks);
-				if ((stcb->asoc.sctp_nr_sack_on_off == 0) ||
-				    (stcb->asoc.peer_supports_nr_sack == 0)) {
-					goto unknown_chunk;
-				}
 				if (stcb == NULL) {
 					SCTPDBG(SCTP_DEBUG_INDATA1, "No stcb when processing NR-SACK chunk\n");
 					break;
 				}
+				if ((stcb->asoc.sctp_nr_sack_on_off == 0) ||
+				    (stcb->asoc.peer_supports_nr_sack == 0)) {
+					goto unknown_chunk;
+				}
 				if (chk_length < sizeof(struct sctp_nr_sack_chunk)) {
 					SCTPDBG(SCTP_DEBUG_INDATA1, "Bad size on NR-SACK chunk, too small\n");
 					break;
diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index a9d00b8372a..87b914375d3 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -9840,9 +9840,12 @@ sctp_fill_in_rest:
 			at = TAILQ_FIRST(&asoc->sent_queue);
 			for (i = 0; i < cnt_of_skipped; i++) {
 				tp1 = TAILQ_NEXT(at, sctp_next);
+				if (tp1 == NULL) {
+					break;
+				}
 				at = tp1;
 			}
-			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
+			if (at && SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
 				sctp_misc_ints(SCTP_FWD_TSN_CHECK,
 				    0xff, cnt_of_skipped, at->rec.data.TSN_seq,
 				    asoc->advanced_peer_ack_point);
@@ -9852,7 +9855,8 @@ sctp_fill_in_rest:
 			 * last now points to last one I can report, update
 			 * peer ack point
 			 */
-			advance_peer_ack_point = last->rec.data.TSN_seq;
+			if (last)
+				advance_peer_ack_point = last->rec.data.TSN_seq;
 			space_needed = sizeof(struct sctp_forward_tsn_chunk) +
 			    cnt_of_skipped * sizeof(struct sctp_strseq);
 		}
@@ -9885,6 +9889,8 @@ sctp_fill_in_rest:
 		at = TAILQ_FIRST(&asoc->sent_queue);
 		for (i = 0; i < cnt_of_skipped; i++) {
 			tp1 = TAILQ_NEXT(at, sctp_next);
+			if (tp1 == NULL)
+				break;
 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
 				/* We don't report these */
 				i--;
@@ -10560,7 +10566,8 @@ sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
 		udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
 		udp->uh_dport = port;
 		udp->uh_ulen = htons(sizeof(struct sctp_shutdown_complete_msg) + sizeof(struct udphdr));
-		udp->uh_sum = in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
+		if (iph_out)
+			udp->uh_sum = in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
 		offset_out += sizeof(struct udphdr);
 		comp_cp = (struct sctp_shutdown_complete_msg *)((caddr_t)comp_cp + sizeof(struct udphdr));
 	}
diff --git a/sys/netinet/sctp_pcb.c b/sys/netinet/sctp_pcb.c
index dd469cb90b3..de18c2e203b 100644
--- a/sys/netinet/sctp_pcb.c
+++ b/sys/netinet/sctp_pcb.c
@@ -517,7 +517,7 @@ sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index,
 		    sizeof(struct sctp_ifn), SCTP_M_IFN);
 		if (sctp_ifnp == NULL) {
 #ifdef INVARIANTS
-			panic("No memory for IFN:%u", sctp_ifnp->ifn_index);
+			panic("No memory for IFN");
 #endif
 			return (NULL);
 		}
@@ -5902,7 +5902,7 @@ sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
 			}
 #endif
 		default:
-			sa = NULL;
+			return (-1);
 			break;
 		}
 	} else {
diff --git a/sys/netinet/sctp_timer.c b/sys/netinet/sctp_timer.c
index e2bd5bb5f56..1e0b771708c 100644
--- a/sys/netinet/sctp_timer.c
+++ b/sys/netinet/sctp_timer.c
@@ -482,6 +482,9 @@ sctp_find_alternate_net(struct sctp_tcb *stcb,
 
 	if (mnet == NULL) {
 		mnet = TAILQ_FIRST(&stcb->asoc.nets);
+		if (mnet == NULL) {
+			return (NULL);
+		}
 	}
 	do {
 		alt = TAILQ_NEXT(mnet, sctp_next);
@@ -491,6 +494,9 @@ sctp_find_alternate_net(struct sctp_tcb *stcb,
 				break;
 			}
 			alt = TAILQ_FIRST(&stcb->asoc.nets);
+			if (alt == NULL) {
+				return (NULL);
+			}
 		}
 		if (alt->ro.ro_rt == NULL) {
 			if (alt->ro._s_addr) {
@@ -517,6 +523,9 @@ sctp_find_alternate_net(struct sctp_tcb *stcb,
 		once = 0;
 		mnet = net;
 		do {
+			if (mnet == NULL) {
+				return (TAILQ_FIRST(&stcb->asoc.nets));
+			}
 			alt = TAILQ_NEXT(mnet, sctp_next);
 			if (alt == NULL) {
 				once++;
diff --git a/sys/netinet/sctputil.c b/sys/netinet/sctputil.c
index 95bbe362117..b09fe7ec72b 100644
--- a/sys/netinet/sctputil.c
+++ b/sys/netinet/sctputil.c
@@ -340,7 +340,7 @@ sctp_log_lock(struct sctp_inpcb *inp, struct sctp_tcb *stcb, uint8_t from)
 		sctp_clog.x.lock.create_lock = SCTP_LOCK_UNKNOWN;
 	}
 	sctp_clog.x.lock.info_lock = rw_wowned(&SCTP_BASE_INFO(ipi_ep_mtx));
-	if (inp->sctp_socket) {
+	if (inp && (inp->sctp_socket)) {
 		sctp_clog.x.lock.sock_lock = mtx_owned(&(inp->sctp_socket->so_rcv.sb_mtx));
 		sctp_clog.x.lock.sockrcvbuf_lock = mtx_owned(&(inp->sctp_socket->so_rcv.sb_mtx));
 		sctp_clog.x.lock.socksndbuf_lock = mtx_owned(&(inp->sctp_socket->so_snd.sb_mtx));
@@ -4211,7 +4211,7 @@ void
 sctp_print_address_pkt(struct ip *iph, struct sctphdr *sh)
 {
 	switch (iph->ip_v) {
-		case IPVERSION:
+	case IPVERSION:
 		{
 			struct sockaddr_in lsa, fsa;
 
@@ -5704,7 +5704,9 @@ get_more_data:
 				if ((SCTP_BUF_NEXT(m) == NULL) &&
 				    (control->end_added)) {
 					out_flags |= MSG_EOR;
-					if ((control->do_not_ref_stcb == 0) && ((control->spec_flags & M_NOTIFICATION) == 0))
+					if ((control->do_not_ref_stcb == 0) &&
+					    (control->stcb != NULL) &&
+					    ((control->spec_flags & M_NOTIFICATION) == 0))
 						control->stcb->asoc.strmin[control->sinfo_stream].delivery_started = 0;
 				}
 				if (control->spec_flags & M_NOTIFICATION) {

From 5e9cd1dbf8adbeddcedf697245d16430fb3bf569 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sun, 5 Sep 2010 14:47:46 +0000
Subject: [PATCH 0501/1624] Document MAKEDEV_ETERNAL.

MFC after:	3 days
---
 share/man/man9/make_dev.9 | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/share/man/man9/make_dev.9 b/share/man/man9/make_dev.9
index 7faedaa4392..9cc755f5a95 100644
--- a/share/man/man9/make_dev.9
+++ b/share/man/man9/make_dev.9
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd May 6, 2010
+.Dd September 5, 2010
 .Dt MAKE_DEV 9
 .Os
 .Sh NAME
@@ -135,6 +135,7 @@ The following values are currently accepted:
 MAKEDEV_REF	reference the created device
 MAKEDEV_NOWAIT	do not sleep, may return NULL
 MAKEDEV_WAITOK	allow the function to sleep to satisfy malloc
+MAKEDEV_ETERNAL	created device will be never destroyed
 .Ed
 .Pp
 The
@@ -154,6 +155,18 @@ the device created is destroyed immediately after
 drops his reference to cdev.
 .Pp
 The
+.Dv MAKEDEV_ETERNAL
+flag allows the kernel to not acquire some locks when translating system
+calls into the cdevsw methods calls.
+It is responsibility of the driver author to make sure that
+.Fn destroy_dev
+is never called on the returned cdev.
+For the convenience, use the
+.Dv MAKEDEV_ETERNAL_KLD
+flag for the code that can be compiled into kernel or loaded
+(and unloaded) as loadable module.
+.Pp
+The
 .Fn make_dev_cred
 function is equivalent to the call
 .Bd -literal -offset indent

From 3037e5d20aebb0a875a21988d53fbedd2f8be657 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sun, 5 Sep 2010 14:52:27 +0000
Subject: [PATCH 0502/1624] Document "show cdev" command.

MFC after:	3 days
---
 share/man/man4/ddb.4 | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/ddb.4 b/share/man/man4/ddb.4
index 2500ccb4292..2e1d2f5888c 100644
--- a/share/man/man4/ddb.4
+++ b/share/man/man4/ddb.4
@@ -60,7 +60,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd May 24, 2010
+.Dd September 5, 2010
 .Dt DDB 4
 .Os
 .Sh NAME
@@ -589,6 +589,12 @@ header file.
 Show brief information about the TTY subsystem.
 .\"
 .Pp
+.It Ic show Cm cdev
+Without argument, show the list of all created cdev's, consisting of devfs
+node name and struct cdev address.
+When address of cdev is supplied, show some internal devfs state of the cdev.
+.\"
+.Pp
 .It Ic show Cm conifhk
 Lists hooks currently waiting for completion in
 run_interrupt_driven_config_hooks().

From b3c63ff61413232df05fed18024ddea3d49d701f Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 5 Sep 2010 16:12:10 +0000
Subject: [PATCH 0503/1624] libedit: Try to map  to
 ed-delete-next-char.

This adds a new "arrow" key "delete" corresponding to the kD termcap value.
It only works if that is a sequence such as "\033[3~"; if it is "\177", the
em-delete-prev-char or ed-delete-prev-char from the single-character
mappings remains. It turns out that most terminals (xterm and alikes,
syscons in xterm mode) produce "\033[3~" by default so  has the
expected effect.

This also means that things need to be considerably misconfigured for
 to perform a  action.
---
 lib/libedit/term.c | 9 ++++++++-
 lib/libedit/term.h | 3 ++-
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/lib/libedit/term.c b/lib/libedit/term.c
index cffad075608..1d89279eb3f 100644
--- a/lib/libedit/term.c
+++ b/lib/libedit/term.c
@@ -223,7 +223,9 @@ private const struct termcapstr {
 	{ "kh", "send cursor home" },
 #define	T_at7	37
 	{ "@7", "send cursor end" },
-#define	T_str	38
+#define	T_kD	38
+	{ "kD", "send cursor delete" },
+#define	T_str	39
 	{ NULL, NULL }
 };
 
@@ -1062,6 +1064,11 @@ term_init_arrow(EditLine *el)
 	arrow[A_K_EN].key = T_at7;
 	arrow[A_K_EN].fun.cmd = ED_MOVE_TO_END;
 	arrow[A_K_EN].type = XK_CMD;
+
+	arrow[A_K_DE].name = "delete";
+	arrow[A_K_DE].key = T_kD;
+	arrow[A_K_DE].fun.cmd = ED_DELETE_NEXT_CHAR;
+	arrow[A_K_DE].type = XK_CMD;
 }
 
 
diff --git a/lib/libedit/term.h b/lib/libedit/term.h
index 8ded5d77e95..15d393c489e 100644
--- a/lib/libedit/term.h
+++ b/lib/libedit/term.h
@@ -79,7 +79,8 @@ typedef struct {
 #define	A_K_RT		3
 #define	A_K_HO		4
 #define	A_K_EN		5
-#define	A_K_NKEYS	6
+#define	A_K_DE		6
+#define	A_K_NKEYS	7
 
 protected void	term_move_to_line(EditLine *, int);
 protected void	term_move_to_char(EditLine *, int);

From 09538b1020a8c8c9b76699fdeed56c9ff55e9815 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sun, 5 Sep 2010 19:24:32 +0000
Subject: [PATCH 0504/1624] Several improvements to HPET driver:  - Add special
 check for case when time expires before being programmed. This fixes
 interrupt loss and respectively timer death on attempt to program very short
 interval. Increase minimal supported period to more realistic value.  - Add
 support for hint.hpet.X.allowed_irqs tunable, allowing manually specify which
 interrupts driver allowed to use. Unluckily, many BIOSes program wrong
 allowed interrupts mask, so driver tries to stay on safe side by not using
 unshareable ISA IRQs. This option gives control over this limitation,
 allowing more per-CPU timers to be provided, when FSB interrupts are not
 supported. Value of this tunable is bitmask.  - Do not use regular interrupts
 on virtual machines. QEMU and VirtualBox do not support them properly, that
 may cause problems. Stay safe by default. Same time both QEMU and VirtualBox
 work fine in legacy_route mode. VirtualBox also works fine if manually
 specify allowed ISA IRQs with above.

---
 sys/dev/acpica/acpi_hpet.c | 77 +++++++++++++++++++++++++++-----------
 1 file changed, 55 insertions(+), 22 deletions(-)

diff --git a/sys/dev/acpica/acpi_hpet.c b/sys/dev/acpica/acpi_hpet.c
index b94309245ab..cf1c4906411 100644
--- a/sys/dev/acpica/acpi_hpet.c
+++ b/sys/dev/acpica/acpi_hpet.c
@@ -74,6 +74,7 @@ struct hpet_softc {
 	int			irq;
 	int			useirq;
 	int			legacy_route;
+	uint32_t		allowed_irqs;
 	struct resource		*mem_res;
 	struct resource		*intr_res;
 	void			*intr_handle;
@@ -146,7 +147,7 @@ hpet_start(struct eventtimer *et,
 	struct hpet_timer *mt = (struct hpet_timer *)et->et_priv;
 	struct hpet_timer *t;
 	struct hpet_softc *sc = mt->sc;
-	uint32_t fdiv;
+	uint32_t fdiv, cmp;
 
 	t = (mt->pcpu_master < 0) ? mt : &sc->t[mt->pcpu_slaves[curcpu]];
 	if (period != NULL) {
@@ -164,23 +165,31 @@ hpet_start(struct eventtimer *et,
 			fdiv += sc->freq * first->sec;
 	} else
 		fdiv = t->div;
+	if (t->irq < 0)
+		bus_write_4(sc->mem_res, HPET_ISR, 1 << t->num);
+	t->caps |= HPET_TCNF_INT_ENB;
 	t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+restart:
+	cmp = t->last + fdiv;
 	if (t->mode == 1 && (t->caps & HPET_TCAP_PER_INT)) {
 		t->caps |= HPET_TCNF_TYPE;
 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
 		    t->caps | HPET_TCNF_VAL_SET);
-		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
-		    t->last + fdiv);
-		bus_read_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num));
-		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
-		    t->div);
+		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num), cmp);
+		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num), t->div);
 	} else {
-		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
-		    t->last + fdiv);
+		t->caps &= ~HPET_TCNF_TYPE;
+		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num), t->caps);
+		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num), cmp);
+	}
+	if (fdiv < 5000) {
+		bus_read_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num));
+		t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+		if ((int32_t)(t->last - cmp) < 0) {
+			fdiv *= 2;
+			goto restart;
+		}
 	}
-	t->caps |= HPET_TCNF_INT_ENB;
-	bus_write_4(sc->mem_res, HPET_ISR, 1 << t->num);
-	bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num), t->caps);
 	return (0);
 }
 
@@ -321,7 +330,7 @@ hpet_attach(device_t dev)
 	int i, j, num_msi, num_timers, num_percpu_et, num_percpu_t, cur_cpu;
 	int pcpu_master;
 	static int maxhpetet = 0;
-	uint32_t val, val2, cvectors;
+	uint32_t val, val2, cvectors, dvectors;
 	uint16_t vendor, rev;
 
 	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
@@ -438,10 +447,9 @@ hpet_attach(device_t dev)
 		sc->t[1].vectors = 0;
 	}
 
-	num_msi = 0;
-	sc->useirq = 0;
-	/* Find common legacy IRQ vectors for all timers. */
-	cvectors = 0xffff0000;
+	/* Check what IRQs we want use. */
+	/* By default allow any PCI IRQs. */
+	sc->allowed_irqs = 0xffff0000;
 	/*
 	 * HPETs in AMD chipsets before SB800 have problems with IRQs >= 16
 	 * Lower are also not always working for different reasons.
@@ -450,7 +458,25 @@ hpet_attach(device_t dev)
 	 * interrupt loss. Avoid legacy IRQs for AMD.
 	 */
 	if (vendor == HPET_VENDID_AMD)
-		cvectors = 0x00000000;
+		sc->allowed_irqs = 0x00000000;
+	/*
+	 * Neither QEMU nor VirtualBox report supported IRQs correctly.
+	 * The only way to use HPET there is to specify IRQs manually
+	 * and/or use legacy_route. Legacy_route mode work on both.
+	 */
+	if (vm_guest)
+		sc->allowed_irqs = 0x00000000;
+	/* Let user override. */
+	resource_int_value(device_get_name(dev), device_get_unit(dev),
+	     "allowed_irqs", &sc->allowed_irqs);
+
+	num_msi = 0;
+	sc->useirq = 0;
+	/* Find IRQ vectors for all timers. */
+	cvectors = sc->allowed_irqs & 0xffff0000;
+	dvectors = sc->allowed_irqs & 0x0000ffff;
+	if (sc->legacy_route)
+		dvectors &= 0x0000fefe;
 	for (i = 0; i < num_timers; i++) {
 		t = &sc->t[i];
 		if (sc->legacy_route && i < 2)
@@ -465,6 +491,10 @@ hpet_attach(device_t dev)
 			}
 		}
 #endif
+		else if (dvectors & t->vectors) {
+			t->irq = ffs(dvectors & t->vectors) - 1;
+			dvectors &= ~(1 << t->irq);
+		}
 		if (t->irq >= 0) {
 			if (!(t->intr_res =
 			    bus_alloc_resource(dev, SYS_RES_IRQ, &t->intr_rid,
@@ -495,7 +525,7 @@ hpet_attach(device_t dev)
 	if (sc->legacy_route)
 		hpet_enable(sc);
 	/* Group timers for per-CPU operation. */
-	num_percpu_et = min(num_msi / mp_ncpus, 2);
+	num_percpu_et = min(num_msi / mp_ncpus, 1);
 	num_percpu_t = num_percpu_et * mp_ncpus;
 	pcpu_master = 0;
 	cur_cpu = CPU_FIRST();
@@ -510,7 +540,8 @@ hpet_attach(device_t dev)
 			bus_bind_intr(dev, t->intr_res, cur_cpu);
 			cur_cpu = CPU_NEXT(cur_cpu);
 			num_percpu_t--;
-		}
+		} else if (t->irq >= 0)
+			bus_bind_intr(dev, t->intr_res, CPU_FIRST());
 	}
 	bus_write_4(sc->mem_res, HPET_ISR, 0xffffffff);
 	sc->irq = -1;
@@ -545,7 +576,7 @@ hpet_attach(device_t dev)
 			/* Legacy route doesn't need more configuration. */
 		} else
 #ifdef DEV_APIC
-		if (t->irq >= 0) {
+		if ((t->caps & HPET_TCAP_FSB_INT_DEL) && t->irq >= 0) {
 			uint64_t addr;
 			uint32_t data;	
 			
@@ -561,7 +592,9 @@ hpet_attach(device_t dev)
 				t->irq = -2;
 		} else
 #endif
-		if (sc->irq >= 0 && (t->vectors & (1 << sc->irq)))
+		if (t->irq >= 0)
+			t->caps |= (t->irq << 9);
+		else if (sc->irq >= 0 && (t->vectors & (1 << sc->irq)))
 			t->caps |= (sc->irq << 9) | HPET_TCNF_INT_TYPE;
 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(i), t->caps);
 		/* Skip event timers without set up IRQ. */
@@ -585,7 +618,7 @@ hpet_attach(device_t dev)
 			t->et.et_quality -= 10;
 		t->et.et_frequency = sc->freq;
 		t->et.et_min_period.sec = 0;
-		t->et.et_min_period.frac = 0x00004000LLU << 32;
+		t->et.et_min_period.frac = 0x00008000LLU << 32;
 		t->et.et_max_period.sec = 0xfffffffeLLU / sc->freq;
 		t->et.et_max_period.frac =
 		    ((0xfffffffeLLU << 32) / sc->freq) << 32;

From a3b31d37dfa8441a0e62fd585b38a23fee7fa964 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sun, 5 Sep 2010 19:57:24 +0000
Subject: [PATCH 0505/1624] Make nexus report name and compat fields as pnpinfo
 for devices on the first level of hierarchy, same as done on deeper levels.

---
 sys/powerpc/aim/nexus.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/powerpc/aim/nexus.c b/sys/powerpc/aim/nexus.c
index b3350a1799c..46e57a525b9 100644
--- a/sys/powerpc/aim/nexus.c
+++ b/sys/powerpc/aim/nexus.c
@@ -63,6 +63,7 @@
 #include 
 #include 
 
+#include 
 #include 
 
 #include 
@@ -162,6 +163,7 @@ static device_method_t nexus_methods[] = {
 	/* Bus interface. Resource management is business of the children... */
 	DEVMETHOD(bus_add_child,	nexus_add_child),
 	DEVMETHOD(bus_print_child,	bus_generic_print_child),
+	DEVMETHOD(bus_child_pnpinfo_str, ofw_bus_gen_child_pnpinfo_str),
 	DEVMETHOD(bus_probe_nomatch,	nexus_probe_nomatch),
 	DEVMETHOD(bus_read_ivar,	nexus_read_ivar),
 	DEVMETHOD(bus_write_ivar,	nexus_write_ivar),

From af82b9a9ee7ef272097fca919250279370710ddc Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sun, 5 Sep 2010 20:04:02 +0000
Subject: [PATCH 0506/1624] Add support for the Sharp/Micron flash chips to
 powermac_mvram(4). Tested on PowerMac G4 AGP.

Reviewed by:	nwhitehorn
---
 share/man/man4/man4.powerpc/powermac_nvram.4 |   7 +-
 sys/dev/powermac_nvram/powermac_nvram.c      | 110 ++++++++++++++++++-
 sys/dev/powermac_nvram/powermac_nvramvar.h   |  13 +++
 3 files changed, 118 insertions(+), 12 deletions(-)

diff --git a/share/man/man4/man4.powerpc/powermac_nvram.4 b/share/man/man4/man4.powerpc/powermac_nvram.4
index 0340422d888..9aae9204adb 100644
--- a/share/man/man4/man4.powerpc/powermac_nvram.4
+++ b/share/man/man4/man4.powerpc/powermac_nvram.4
@@ -25,7 +25,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd August 1, 2006
+.Dd September 5, 2010
 .Dt POWERMAC_NVRAM 4 powerpc
 .Os
 .Sh NAME
@@ -63,8 +63,3 @@ The
 .Nm
 driver was written by
 .An Maxim Sobolev Aq sobomax@FreeBSD.org .
-.Sh BUGS
-Currently, the
-.Nm
-driver only supports systems equipped with an AMD flash part and is only
-tested on Apple G4-based Mac Mini machines.
diff --git a/sys/dev/powermac_nvram/powermac_nvram.c b/sys/dev/powermac_nvram/powermac_nvram.c
index 22174f9e04b..0c7949f78fa 100644
--- a/sys/dev/powermac_nvram/powermac_nvram.c
+++ b/sys/dev/powermac_nvram/powermac_nvram.c
@@ -115,7 +115,10 @@ powermac_nvram_probe(device_t dev)
 	if (type == NULL || compatible == NULL)
 		return ENXIO;
 
-	if (strcmp(type, "nvram") != 0 || strcmp(compatible, "amd-0137") != 0)
+	if (strcmp(type, "nvram") != 0)
+		return ENXIO;
+	if (strcmp(compatible, "amd-0137") != 0 &&
+	    strcmp(compatible, "nvram,flash") != 0)
 		return ENXIO;
 
 	device_set_desc(dev, "Apple NVRAM");
@@ -126,6 +129,7 @@ static int
 powermac_nvram_attach(device_t dev)
 {
 	struct powermac_nvram_softc *sc;
+	const char	*compatible;
 	phandle_t node;
 	u_int32_t reg[3];
 	int gen0, gen1, i;
@@ -139,6 +143,12 @@ powermac_nvram_attach(device_t dev)
 	sc->sc_dev = dev;
 	sc->sc_node = node;
 
+	compatible = ofw_bus_get_compat(dev);
+	if (strcmp(compatible, "amd-0137") == 0)
+		sc->sc_type = FLASH_TYPE_AMD;
+	else
+		sc->sc_type = FLASH_TYPE_SM;
+
 	/*
 	 * Find which byte of reg corresponds to the 32-bit physical address.
 	 * We should probably read #address-cells from /chosen instead.
@@ -342,7 +352,7 @@ adler_checksum(uint8_t *data, int len)
 #define	OUTB_DELAY(a, v)	outb(a, v); DELAY(1);
 
 static int
-wait_operation_complete(uint8_t *bank)
+wait_operation_complete_amd(uint8_t *bank)
 {
 	int i;
 
@@ -353,7 +363,7 @@ wait_operation_complete(uint8_t *bank)
 }
 
 static int
-erase_bank(device_t dev, uint8_t *bank)
+erase_bank_amd(device_t dev, uint8_t *bank)
 {
 	unsigned int i;
 
@@ -368,7 +378,7 @@ erase_bank(device_t dev, uint8_t *bank)
 	OUTB_DELAY(bank + 0x2aa, 0x55);
 	OUTB_DELAY(bank, 0x30);
 
-	if (wait_operation_complete(bank) != 0) {
+	if (wait_operation_complete_amd(bank) != 0) {
 		device_printf(dev, "flash erase timeout\n");
 		return -1;
 	}
@@ -386,7 +396,7 @@ erase_bank(device_t dev, uint8_t *bank)
 }
 
 static int
-write_bank(device_t dev, uint8_t *bank, uint8_t *data)
+write_bank_amd(device_t dev, uint8_t *bank, uint8_t *data)
 {
 	unsigned int i;
 
@@ -399,7 +409,7 @@ write_bank(device_t dev, uint8_t *bank, uint8_t *data)
 		/* Write single word */
 		OUTB_DELAY(bank + 0x555, 0xa0);
 		OUTB_DELAY(bank + i, data[i]);
-		if (wait_operation_complete(bank) != 0) {
+		if (wait_operation_complete_amd(bank) != 0) {
 			device_printf(dev, "flash write timeout\n");
 			return -1;
 		}
@@ -416,3 +426,91 @@ write_bank(device_t dev, uint8_t *bank, uint8_t *data)
 	}
 	return 0;
 }
+
+static int
+wait_operation_complete_sm(uint8_t *bank)
+{
+	int i;
+
+	for (i = 1000000; i != 0; i--) {
+		outb(bank, SM_FLASH_CMD_READ_STATUS);
+		if (inb(bank) & SM_FLASH_STATUS_DONE)
+			return (0);
+	}
+	return (-1);
+}
+
+static int
+erase_bank_sm(device_t dev, uint8_t *bank)
+{
+	unsigned int i;
+
+	outb(bank, SM_FLASH_CMD_ERASE_SETUP);
+	outb(bank, SM_FLASH_CMD_ERASE_CONFIRM);
+
+	if (wait_operation_complete_sm(bank) != 0) {
+		device_printf(dev, "flash erase timeout\n");
+		return (-1);
+	}
+
+	outb(bank, SM_FLASH_CMD_CLEAR_STATUS);
+	outb(bank, SM_FLASH_CMD_RESET);
+
+	for (i = 0; i < NVRAM_SIZE; i++) {
+		if (bank[i] != 0xff) {
+			device_printf(dev, "flash write has failed\n");
+			return (-1);
+		}
+	}
+	return (0);
+}
+
+static int
+write_bank_sm(device_t dev, uint8_t *bank, uint8_t *data)
+{
+	unsigned int i;
+
+	for (i = 0; i < NVRAM_SIZE; i++) {
+		OUTB_DELAY(bank + i, SM_FLASH_CMD_WRITE_SETUP);
+		outb(bank + i, data[i]);
+		if (wait_operation_complete_sm(bank) != 0) {
+			device_printf(dev, "flash write error/timeout\n");
+			break;
+		}
+	}
+
+	outb(bank, SM_FLASH_CMD_CLEAR_STATUS);
+	outb(bank, SM_FLASH_CMD_RESET);
+
+	for (i = 0; i < NVRAM_SIZE; i++) {
+		if (bank[i] != data[i]) {
+			device_printf(dev, "flash write has failed\n");
+			return (-1);
+		}
+	}
+	return (0);
+}
+
+static int
+erase_bank(device_t dev, uint8_t *bank)
+{
+	struct powermac_nvram_softc *sc;
+
+	sc = device_get_softc(dev);
+	if (sc->sc_type == FLASH_TYPE_AMD)
+		return (erase_bank_amd(dev, bank));
+	else
+		return (erase_bank_sm(dev, bank));
+}
+
+static int
+write_bank(device_t dev, uint8_t *bank, uint8_t *data)
+{
+	struct powermac_nvram_softc *sc;
+
+	sc = device_get_softc(dev);
+	if (sc->sc_type == FLASH_TYPE_AMD)
+		return (write_bank_amd(dev, bank, data));
+	else
+		return (write_bank_sm(dev, bank, data));
+}
diff --git a/sys/dev/powermac_nvram/powermac_nvramvar.h b/sys/dev/powermac_nvram/powermac_nvramvar.h
index 6f4fb26e899..c326e3c5b5d 100644
--- a/sys/dev/powermac_nvram/powermac_nvramvar.h
+++ b/sys/dev/powermac_nvram/powermac_nvramvar.h
@@ -33,6 +33,16 @@
 
 #define	CORE99_SIGNATURE	0x5a
 
+#define SM_FLASH_CMD_ERASE_CONFIRM	0xd0
+#define SM_FLASH_CMD_ERASE_SETUP	0x20
+#define SM_FLASH_CMD_RESET		0xff
+#define SM_FLASH_CMD_WRITE_SETUP	0x40
+#define SM_FLASH_CMD_CLEAR_STATUS	0x50
+#define SM_FLASH_CMD_READ_STATUS	0x70
+
+#define SM_FLASH_STATUS_DONE	0x80
+#define SM_FLASH_STATUS_ERR	0x38
+
 #ifdef _KERNEL
 
 struct powermac_nvram_softc {
@@ -44,6 +54,9 @@ struct powermac_nvram_softc {
 	uint8_t			sc_data[NVRAM_SIZE];
 
 	struct cdev *		sc_cdev;
+	int			sc_type;
+#define FLASH_TYPE_SM	0
+#define FLASH_TYPE_AMD	1
 	int			sc_isopen;
 	int			sc_rpos;
 	int			sc_wpos;

From d57429e2c2e8ae40d1bd8d345ebff931a87f7929 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Sun, 5 Sep 2010 20:04:54 +0000
Subject: [PATCH 0507/1624] Note in rc.conf(5) that jail_list should contain
 only alphanumeric characters.

PR:		150098
Submitted by:	cc (cpt_complain at yahoo dot com)
Approved by:	keramida (mentor)
MFC after:	1 week
---
 share/man/man5/rc.conf.5 | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/share/man/man5/rc.conf.5 b/share/man/man5/rc.conf.5
index f41b6dbf81a..80f187b662b 100644
--- a/share/man/man5/rc.conf.5
+++ b/share/man/man5/rc.conf.5
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd August 3, 2010
+.Dd September 4, 2010
 .Dt RC.CONF 5
 .Os
 .Sh NAME
@@ -3503,7 +3503,8 @@ A space separated list of names for jails.
 This is purely a configuration aid to help identify and
 configure multiple jails.
 The names specified in this list will be used to
-identify settings common to an instance of a jail.
+identify settings common to an instance of a jail,
+and should contain alphanumeric characters only.
 Assuming that the jail in question was named
 .Li vjail ,
 you would have the following dependent variables:

From 049640c1f0f98ad3b12ee5509ac171a65c57bfba Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Sun, 5 Sep 2010 20:13:07 +0000
Subject: [PATCH 0508/1624] Implement correct handling of address parameter and
 sendinfo for SCTP send calls.

MFC after: 4 weeks.
---
 sys/kern/uipc_syscalls.c  |   6 +-
 sys/netinet/sctp_output.c | 222 ++++++++++++++------------------------
 sys/netinet/sctp_uio.h    |  18 +++-
 3 files changed, 100 insertions(+), 146 deletions(-)

diff --git a/sys/kern/uipc_syscalls.c b/sys/kern/uipc_syscalls.c
index 3165dab5c55..06869b21d28 100644
--- a/sys/kern/uipc_syscalls.c
+++ b/sys/kern/uipc_syscalls.c
@@ -2381,7 +2381,6 @@ sctp_generic_sendmsg (td, uap)
 	struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
 	struct socket *so;
 	struct file *fp = NULL;
-	int use_rcvinfo = 1;
 	int error = 0, len;
 	struct sockaddr *to = NULL;
 #ifdef KTRACE
@@ -2434,7 +2433,7 @@ sctp_generic_sendmsg (td, uap)
 	CURVNET_SET(so->so_vnet);
 	error = sctp_lower_sosend(so, to, &auio,
 		    (struct mbuf *)NULL, (struct mbuf *)NULL,
-		    uap->flags, use_rcvinfo, u_sinfo, td);
+		    uap->flags, u_sinfo, td);
 	CURVNET_RESTORE();
 	if (error) {
 		if (auio.uio_resid != len && (error == ERESTART ||
@@ -2485,7 +2484,6 @@ sctp_generic_sendmsg_iov(td, uap)
 	struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
 	struct socket *so;
 	struct file *fp = NULL;
-	int use_rcvinfo = 1;
 	int error=0, len, i;
 	struct sockaddr *to = NULL;
 #ifdef KTRACE
@@ -2552,7 +2550,7 @@ sctp_generic_sendmsg_iov(td, uap)
 	CURVNET_SET(so->so_vnet);
 	error = sctp_lower_sosend(so, to, &auio,
 		    (struct mbuf *)NULL, (struct mbuf *)NULL,
-		    uap->flags, use_rcvinfo, u_sinfo, td);
+		    uap->flags, u_sinfo, td);
 	CURVNET_RESTORE();
 	if (error) {
 		if (auio.uio_resid != len && (error == ERESTART ||
diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index 87b914375d3..38ad9d97258 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -12158,7 +12158,7 @@ sctp_sosend(struct socket *so,
 	error = sctp_lower_sosend(so, addr_to_use, uio, top,
 	    control,
 	    flags,
-	    use_rcvinfo, &srcv
+	    use_rcvinfo ? &srcv : NULL
 	    ,p
 	    );
 	return (error);
@@ -12172,7 +12172,6 @@ sctp_lower_sosend(struct socket *so,
     struct mbuf *i_pak,
     struct mbuf *control,
     int flags,
-    int use_rcvinfo,
     struct sctp_sndrcvinfo *srcv
     ,
     struct thread *p
@@ -12200,8 +12199,10 @@ sctp_lower_sosend(struct socket *so,
 	int got_all_of_the_send = 0;
 	int hold_tcblock = 0;
 	int non_blocking = 0;
-	int temp_flags = 0;
 	uint32_t local_add_more, local_soresv = 0;
+	uint16_t port;
+	uint16_t sinfo_flags;
+	sctp_assoc_t sinfo_assoc_id;
 
 	error = 0;
 	net = NULL;
@@ -12236,38 +12237,6 @@ sctp_lower_sosend(struct socket *so,
 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Send called addr:%p send length %d\n",
 	    addr,
 	    sndlen);
-	/**
-	 * Pre-screen address, if one is given the sin-len
-	 * must be set correctly!
-	 */
-	if (addr) {
-		switch (addr->sa_family) {
-#if defined(INET)
-		case AF_INET:
-			if (addr->sa_len != sizeof(struct sockaddr_in)) {
-				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-				error = EINVAL;
-				goto out_unlocked;
-			}
-			break;
-#endif
-#if defined(INET6)
-		case AF_INET6:
-			if (addr->sa_len != sizeof(struct sockaddr_in6)) {
-				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-				error = EINVAL;
-				goto out_unlocked;
-			}
-			break;
-#endif
-		default:
-			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAFNOSUPPORT);
-			error = EAFNOSUPPORT;
-			goto out_unlocked;
-		}
-	}
-	hold_tcblock = 0;
-
 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
 	    (inp->sctp_socket->so_qlimit)) {
 		/* The listener can NOT send */
@@ -12275,22 +12244,67 @@ sctp_lower_sosend(struct socket *so,
 		error = ENOTCONN;
 		goto out_unlocked;
 	}
-	if ((use_rcvinfo) && srcv) {
-		if (INVALID_SINFO_FLAG(srcv->sinfo_flags) ||
-		    PR_SCTP_INVALID_POLICY(srcv->sinfo_flags)) {
+	/**
+	 * Pre-screen address, if one is given the sin-len
+	 * must be set correctly!
+	 */
+	if (addr) {
+		union sctp_sockstore *raddr = (union sctp_sockstore *)addr;
+
+		switch (raddr->sa.sa_family) {
+#if defined(INET)
+		case AF_INET:
+			if (raddr->sin.sin_len != sizeof(struct sockaddr_in)) {
+				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
+				error = EINVAL;
+				goto out_unlocked;
+			}
+			port = raddr->sin.sin_port;
+			break;
+#endif
+#if defined(INET6)
+		case AF_INET6:
+			if (raddr->sin6.sin6_len != sizeof(struct sockaddr_in6)) {
+				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
+				error = EINVAL;
+				goto out_unlocked;
+			}
+			port = raddr->sin6.sin6_port;
+			break;
+#endif
+		default:
+			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAFNOSUPPORT);
+			error = EAFNOSUPPORT;
+			goto out_unlocked;
+		}
+	} else
+		port = 0;
+
+	if (srcv) {
+		sinfo_flags = srcv->sinfo_flags;
+		sinfo_assoc_id = srcv->sinfo_assoc_id;
+		if (INVALID_SINFO_FLAG(sinfo_flags) ||
+		    PR_SCTP_INVALID_POLICY(sinfo_flags)) {
 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
 			error = EINVAL;
 			goto out_unlocked;
 		}
 		if (srcv->sinfo_flags)
 			SCTP_STAT_INCR(sctps_sends_with_flags);
-
-		if (srcv->sinfo_flags & SCTP_SENDALL) {
-			/* its a sendall */
-			error = sctp_sendall(inp, uio, top, srcv);
-			top = NULL;
-			goto out_unlocked;
-		}
+	} else {
+		sinfo_flags = inp->def_send.sinfo_flags;
+		sinfo_assoc_id = inp->def_send.sinfo_assoc_id;
+	}
+	if (sinfo_flags & SCTP_SENDALL) {
+		/* its a sendall */
+		error = sctp_sendall(inp, uio, top, srcv);
+		top = NULL;
+		goto out_unlocked;
+	}
+	if ((sinfo_flags & SCTP_ADDR_OVER) && (addr == NULL)) {
+		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
+		error = EINVAL;
+		goto out_unlocked;
 	}
 	/* now we must find the assoc */
 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) ||
@@ -12306,80 +12320,8 @@ sctp_lower_sosend(struct socket *so,
 		SCTP_TCB_LOCK(stcb);
 		hold_tcblock = 1;
 		SCTP_INP_RUNLOCK(inp);
-		if (addr) {
-			/* Must locate the net structure if addr given */
-			net = sctp_findnet(stcb, addr);
-			if (net) {
-				/* validate port was 0 or correct */
-				struct sockaddr_in *sin;
-
-				sin = (struct sockaddr_in *)addr;
-				if ((sin->sin_port != 0) &&
-				    (sin->sin_port != stcb->rport)) {
-					net = NULL;
-				}
-			}
-			temp_flags |= SCTP_ADDR_OVER;
-		} else
-			net = stcb->asoc.primary_destination;
-		if (addr && (net == NULL)) {
-			/* Could not find address, was it legal */
-			if (addr->sa_family == AF_INET) {
-				struct sockaddr_in *sin;
-
-				sin = (struct sockaddr_in *)addr;
-				if (sin->sin_addr.s_addr == 0) {
-					if ((sin->sin_port == 0) ||
-					    (sin->sin_port == stcb->rport)) {
-						net = stcb->asoc.primary_destination;
-					}
-				}
-			} else {
-				struct sockaddr_in6 *sin6;
-
-				sin6 = (struct sockaddr_in6 *)addr;
-				if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
-					if ((sin6->sin6_port == 0) ||
-					    (sin6->sin6_port == stcb->rport)) {
-						net = stcb->asoc.primary_destination;
-					}
-				}
-			}
-		}
-		if (net == NULL) {
-			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-			error = EINVAL;
-			goto out_unlocked;
-		}
-	} else if (use_rcvinfo && srcv && srcv->sinfo_assoc_id) {
-		stcb = sctp_findassociation_ep_asocid(inp, srcv->sinfo_assoc_id, 0);
-		if (stcb) {
-			if (addr)
-				/*
-				 * Must locate the net structure if addr
-				 * given
-				 */
-				net = sctp_findnet(stcb, addr);
-			else
-				net = stcb->asoc.primary_destination;
-			if ((srcv->sinfo_flags & SCTP_ADDR_OVER) &&
-			    ((net == NULL) || (addr == NULL))) {
-				struct sockaddr_in *sin;
-
-				if (addr == NULL) {
-					SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-					error = EINVAL;
-					goto out_unlocked;
-				}
-				sin = (struct sockaddr_in *)addr;
-				/* Validate port is 0 or correct */
-				if ((sin->sin_port != 0) &&
-				    (sin->sin_port != stcb->rport)) {
-					net = NULL;
-				}
-			}
-		}
-		hold_tcblock = 0;
+	} else if (sinfo_assoc_id) {
+		stcb = sctp_findassociation_ep_asocid(inp, sinfo_assoc_id, 0);
 	} else if (addr) {
 		/*-
 		 * Since we did not use findep we must
@@ -12452,10 +12394,8 @@ sctp_lower_sosend(struct socket *so,
 			 */
 			uint32_t vrf_id;
 
-			if ((use_rcvinfo) && (srcv) &&
-			    ((srcv->sinfo_flags & SCTP_ABORT) ||
-			    ((srcv->sinfo_flags & SCTP_EOF) &&
-			    (sndlen == 0)))) {
+			if ((sinfo_flags & SCTP_ABORT) ||
+			    ((sinfo_flags & SCTP_EOF) && (sndlen == 0))) {
 				/*-
 				 * User asks to abort a non-existant assoc,
 				 * or EOF a non-existant assoc with no data
@@ -12584,10 +12524,25 @@ sctp_lower_sosend(struct socket *so,
 			 * structure may now have an update and thus we may need to
 			 * change it BEFORE we append the message.
 			 */
-			net = stcb->asoc.primary_destination;
-			asoc = &stcb->asoc;
 		}
 	}
+	if (srcv == NULL)
+		srcv = (struct sctp_sndrcvinfo *)&stcb->asoc.def_send;
+	if (srcv->sinfo_flags & SCTP_ADDR_OVER) {
+		if (addr)
+			net = sctp_findnet(stcb, addr);
+		else
+			net = NULL;
+		if ((net == NULL) ||
+		    ((port != 0) && (port != stcb->rport))) {
+			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
+			error = EINVAL;
+			goto out_unlocked;
+		}
+	} else {
+		net = stcb->asoc.primary_destination;
+	}
+
 	if ((SCTP_SO_IS_NBIO(so)
 	    || (flags & MSG_NBIO)
 	    )) {
@@ -12658,10 +12613,6 @@ sctp_lower_sosend(struct socket *so,
 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
 		queue_only = 1;
 	}
-	if ((use_rcvinfo == 0) || (srcv == NULL)) {
-		/* Grab the default stuff from the asoc */
-		srcv = (struct sctp_sndrcvinfo *)&stcb->asoc.def_send;
-	}
 	/* we are now done with all control */
 	if (control) {
 		sctp_m_freem(control);
@@ -12671,8 +12622,7 @@ sctp_lower_sosend(struct socket *so,
 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
-		if ((use_rcvinfo) &&
-		    (srcv->sinfo_flags & SCTP_ABORT)) {
+		if (srcv->sinfo_flags & SCTP_ABORT) {
 			;
 		} else {
 			SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
@@ -12684,16 +12634,6 @@ sctp_lower_sosend(struct socket *so,
 	if (p) {
 		p->td_ru.ru_msgsnd++;
 	}
-	if (stcb) {
-		if (((srcv->sinfo_flags | temp_flags) & SCTP_ADDR_OVER) == 0) {
-			net = stcb->asoc.primary_destination;
-		}
-	}
-	if (net == NULL) {
-		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
-		error = EINVAL;
-		goto out_unlocked;
-	}
 	if ((net->flight_size > net->cwnd) &&
 	    (asoc->sctp_cmt_on_off == 0)) {
 		/*-
diff --git a/sys/netinet/sctp_uio.h b/sys/netinet/sctp_uio.h
index e3fbc3e6d50..1cd54654ca6 100644
--- a/sys/netinet/sctp_uio.h
+++ b/sys/netinet/sctp_uio.h
@@ -982,6 +982,23 @@ union sctp_sockstore {
 	struct sockaddr sa;
 };
 
+
+/***********************************/
+/* And something for us old timers */
+/***********************************/
+
+#ifndef ntohll
+#include 
+#define ntohll(x) be64toh(x)
+#endif
+
+#ifndef htonll
+#include 
+#define htonll(x) htobe64(x)
+#endif
+/***********************************/
+
+
 struct xsctp_inpcb {
 	uint32_t last;
 	uint32_t flags;
@@ -1079,7 +1096,6 @@ sctp_lower_sosend(struct socket *so,
     struct mbuf *i_pak,
     struct mbuf *control,
     int flags,
-    int use_rcvinfo,
     struct sctp_sndrcvinfo *srcv
     ,struct thread *p
 );

From 2ca3d70fc67be008d932f9cec1282dbea1853029 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 5 Sep 2010 21:12:48 +0000
Subject: [PATCH 0509/1624] sh: Improve comments in expand.c.

---
 bin/sh/expand.c | 58 +++++++++++++++++++++++++++++++------------------
 1 file changed, 37 insertions(+), 21 deletions(-)

diff --git a/bin/sh/expand.c b/bin/sh/expand.c
index 73540109959..b2da92b6b25 100644
--- a/bin/sh/expand.c
+++ b/bin/sh/expand.c
@@ -138,12 +138,18 @@ expandhere(union node *arg, int fd)
 
 
 /*
- * Perform variable substitution and command substitution on an argument,
- * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
- * perform splitting and file name expansion.  When arglist is NULL, perform
- * here document expansion.
+ * Perform expansions on an argument, placing the resulting list of arguments
+ * in arglist.  Parameter expansion, command substitution and arithmetic
+ * expansion are always performed; additional expansions can be requested
+ * via flag (EXP_*).
+ * The result is left in the stack string.
+ * When arglist is NULL, perform here document expansion.  A partial result
+ * may be written to herefd, which is then not included in the stack string.
+ *
+ * Caution: this function uses global state and is not reentrant.
+ * However, a new invocation after an interrupted invocation is safe
+ * and will reset the global state for the new call.
  */
-
 void
 expandarg(union node *arg, struct arglist *arglist, int flag)
 {
@@ -195,11 +201,14 @@ expandarg(union node *arg, struct arglist *arglist, int flag)
 
 
 /*
- * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
- * characters to allow for further processing.  Otherwise treat
- * $@ like $* since no splitting will be performed.
+ * Perform parameter expansion, command substitution and arithmetic
+ * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
+ * Processing ends at a CTLENDVAR character as well as '\0'.
+ * This is used to expand word in ${var+word} etc.
+ * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
+ * characters to allow for further processing.
+ * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
  */
-
 STATIC void
 argstr(char *p, int flag)
 {
@@ -212,7 +221,7 @@ argstr(char *p, int flag)
 	for (;;) {
 		switch (c = *p++) {
 		case '\0':
-		case CTLENDVAR: /* ??? */
+		case CTLENDVAR:
 			goto breakloop;
 		case CTLQUOTEMARK:
 			/* "$@" syntax adherence hack */
@@ -262,6 +271,10 @@ argstr(char *p, int flag)
 breakloop:;
 }
 
+/*
+ * Perform tilde expansion, placing the result in the stack string and
+ * returning the next position in the input string to process.
+ */
 STATIC char *
 exptilde(char *p, int flag)
 {
@@ -367,12 +380,11 @@ expari(int flag)
 	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
 	int quoted;
 
-
 	/*
 	 * This routine is slightly over-complicated for
 	 * efficiency.  First we make sure there is
 	 * enough space for the result, which may be bigger
-	 * than the expression if we add exponentiation.  Next we
+	 * than the expression.  Next we
 	 * scan backwards looking for the start of arithmetic.  If the
 	 * next previous character is a CTLESC character, then we
 	 * have to rescan starting from the beginning since CTLESC
@@ -413,9 +425,8 @@ expari(int flag)
 
 
 /*
- * Expand stuff in backwards quotes.
+ * Perform command substitution.
  */
-
 STATIC void
 expbackq(union node *cmd, int quoted, int flag)
 {
@@ -974,6 +985,12 @@ recordregion(int start, int end, int inquotes)
  * Break the argument string into pieces based upon IFS and add the
  * strings to the argument list.  The regions of the string to be
  * searched for IFS characters have been stored by recordregion.
+ * CTLESC characters are preserved but have little effect in this pass
+ * other than escaping CTL* characters.  In particular, they do not escape
+ * IFS characters: that should be done with the ifsregion mechanism.
+ * CTLQUOTEMARK characters are used to preserve empty quoted strings.
+ * This pass treats them as a regular character, making the string non-empty.
+ * Later, they are removed along with the other CTL* characters.
  */
 STATIC void
 ifsbreakup(char *string, struct arglist *arglist)
@@ -1075,15 +1092,14 @@ ifsbreakup(char *string, struct arglist *arglist)
 }
 
 
-
-/*
- * Expand shell metacharacters.  At this point, the only control characters
- * should be escapes.  The results are stored in the list exparg.
- */
-
 STATIC char expdir[PATH_MAX];
 #define expdir_end (expdir + sizeof(expdir))
 
+/*
+ * Perform pathname generation and remove control characters.
+ * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
+ * The results are stored in the list exparg.
+ */
 STATIC void
 expandmeta(struct strlist *str, int flag __unused)
 {
@@ -1469,7 +1485,7 @@ breakloop:
 
 
 /*
- * Remove any CTLESC characters from a string.
+ * Remove any CTLESC and CTLQUOTEMARK characters from a string.
  */
 
 void

From 3cf53e8550e625965b82310f07bc6ca93226a901 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 5 Sep 2010 21:44:50 +0000
Subject: [PATCH 0510/1624] printf(1): Clarify that \OOO produces a byte,
 different %b escape sequences.

Octal escape sequences are expanded to bytes, not characters, and multiple
are required for a multibyte character.

The valid escape sequences in %b strings are slightly different from the
escape sequences in the format string.
---
 usr.bin/printf/printf.1 | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/usr.bin/printf/printf.1 b/usr.bin/printf/printf.1
index 4a30851de01..f0fc00b63ca 100644
--- a/usr.bin/printf/printf.1
+++ b/usr.bin/printf/printf.1
@@ -35,7 +35,7 @@
 .\"	@(#)printf.1	8.1 (Berkeley) 6/6/93
 .\" $FreeBSD$
 .\"
-.Dd April 14, 2005
+.Dd September 5, 2010
 .Dt PRINTF 1
 .Os
 .Sh NAME
@@ -109,12 +109,13 @@ Write a  character.
 .It Cm \e\e
 Write a backslash character.
 .It Cm \e Ns Ar num
-.It Cm \e0 Ns Ar num
-Write an 8-bit character whose
-.Tn ASCII
+Write a byte whose
 value is the 1-, 2-, or 3-digit
 octal number
 .Ar num .
+Multibyte characters can be constructed using multiple
+.Cm \e Ns Ar num
+sequences.
 .El
 .Pp
 Each format specification is introduced by the percent character
@@ -289,6 +290,11 @@ As for
 .Cm s ,
 but interpret character escapes in backslash notation in the string
 .Ar argument .
+The permitted escape sequences are slightly different in that
+octal escapes are
+.Cm \e0 Ns Ar num
+instead of
+.Cm \e Ns Ar num .
 .It Cm \&%
 Print a `%'; no argument is used.
 .El

From cb4a1047ceb873723a3b44e3777448d0138e815e Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Mon, 6 Sep 2010 03:00:54 +0000
Subject: [PATCH 0511/1624] Fix off-by-one error in function
 _thr_sigact_unload, also disable the function, it seems some gnome
 application tends to crash if we unregister sigaction automatically.

---
 lib/libthr/thread/thr_sig.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index b6755f91be0..5067e646dca 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -418,6 +418,7 @@ _thr_signal_init(void)
 void
 _thr_sigact_unload(struct dl_phdr_info *phdr_info)
 {
+#if 0
 	struct pthread *curthread = _get_curthread();
 	struct urwlock *rwlp;
 	struct sigaction *actp;
@@ -426,13 +427,13 @@ _thr_sigact_unload(struct dl_phdr_info *phdr_info)
 	int sig;
  
 	_thr_signal_block(curthread);
-	for (sig = 1; sig < _SIG_MAXSIG; sig++) {
-		actp = &_thr_sigact[sig].sigact;
+	for (sig = 1; sig <= _SIG_MAXSIG; sig++) {
+		actp = &_thr_sigact[sig-1].sigact;
 retry:
 		handler = actp->sa_handler;
 		if (handler != SIG_DFL && handler != SIG_IGN &&
 		    __elf_phdr_match_addr(phdr_info, handler)) {
-			rwlp = &_thr_sigact[sig].lock;
+			rwlp = &_thr_sigact[sig-1].lock;
 			_thr_rwl_wrlock(rwlp);
 			if (handler != actp->sa_handler) {
 				_thr_rwl_unlock(rwlp);
@@ -449,6 +450,7 @@ retry:
 		}
 	}
 	_thr_signal_unblock(curthread);
+#endif
 }
 
 void

From 1dc7e010ec6acc618b6e7fb2e6d4f60bd5f055d7 Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Mon, 6 Sep 2010 04:15:49 +0000
Subject: [PATCH 0512/1624] Handle geli-encrypted root disk devices.

MFC after:	2 weeks
---
 sbin/fdisk/fdisk.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/sbin/fdisk/fdisk.c b/sbin/fdisk/fdisk.c
index 1e121bb6450..c53ef8556df 100644
--- a/sbin/fdisk/fdisk.c
+++ b/sbin/fdisk/fdisk.c
@@ -1461,6 +1461,7 @@ sanitize_partition(struct dos_partition *partp)
  *   /dev/ad0s1a     => /dev/ad0
  *   /dev/da0a       => /dev/da0
  *   /dev/vinum/root => /dev/vinum/root
+ * A ".eli" part is removed if it exists (see geli(8)).
  */
 static char *
 get_rootdisk(void)
@@ -1469,7 +1470,7 @@ get_rootdisk(void)
 	regex_t re;
 #define NMATCHES 2
 	regmatch_t rm[NMATCHES];
-	char *s;
+	char dev[PATH_MAX], *s;
 	int rv;
 
 	if (statfs("/", &rootfs) == -1)
@@ -1478,7 +1479,11 @@ get_rootdisk(void)
 	if ((rv = regcomp(&re, "^(/dev/[a-z/]+[0-9]+)([sp][0-9]+)?[a-h]?$",
 		    REG_EXTENDED)) != 0)
 		errx(1, "regcomp() failed (%d)", rv);
-	if ((rv = regexec(&re, rootfs.f_mntfromname, NMATCHES, rm, 0)) != 0)
+	strlcpy(dev, rootfs.f_mntfromname, sizeof (dev));
+	if ((s = strstr(dev, ".eli")) != NULL)
+	    memmove(s, s+4, strlen(s + 4) + 1);
+
+	if ((rv = regexec(&re, dev, NMATCHES, rm, 0)) != 0)
 		errx(1,
 "mounted root fs resource doesn't match expectations (regexec returned %d)",
 		    rv);

From 96001a35e15a3fdda7a36237d34037c33d8bf277 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 6 Sep 2010 06:18:49 +0000
Subject: [PATCH 0513/1624] XLR/XLS hardware interrupts should be programmed
 level triggered at the PIC.  This should fix the interrupt releated issues
 seen after the interrupt handling re-write for SMP.

---
 sys/mips/rmi/iodi.c        |  8 ++++----
 sys/mips/rmi/xlr_machdep.c | 15 ++++++---------
 sys/mips/rmi/xlr_pci.c     |  4 ++--
 3 files changed, 12 insertions(+), 15 deletions(-)

diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index 47965673f56..c9913f20d48 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -104,7 +104,7 @@ iodi_setup_intr(device_t dev, device_t child,
 		/* FIXME uart 1? */
 		cpu_establish_hardintr("uart", filt, intr, arg,
 		    PIC_UART_0_IRQ, flags, cookiep);
-		pic_setup_intr(PIC_IRT_UART_0_INDEX, PIC_UART_0_IRQ, 0x1, 0);
+		pic_setup_intr(PIC_IRT_UART_0_INDEX, PIC_UART_0_IRQ, 0x1, 1);
 	} else if (strcmp(name, "rge") == 0 || strcmp(name, "nlge") == 0) {
 		int irq;
 
@@ -112,15 +112,15 @@ iodi_setup_intr(device_t dev, device_t child,
 		irq = (intptr_t)ires->__r_i;
 		cpu_establish_hardintr("rge", filt, intr, arg, irq, flags,
 		    cookiep);
-		pic_setup_intr(irq - PIC_IRQ_BASE, irq, 0x1, 0);
+		pic_setup_intr(irq - PIC_IRQ_BASE, irq, 0x1, 1);
 	} else if (strcmp(name, "ehci") == 0) {
 		cpu_establish_hardintr("ehci", filt, intr, arg, PIC_USB_IRQ, flags,
 		    cookiep);
-		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1, 0);
+		pic_setup_intr(PIC_USB_IRQ - PIC_IRQ_BASE, PIC_USB_IRQ, 0x1, 1);
 	} else if (strcmp(name, "ata") == 0) {
 		xlr_establish_intr("ata", filt, intr, arg, PIC_PCMCIA_IRQ, flags,
 		    cookiep, bridge_pcmcia_ack);
-		pic_setup_intr(PIC_PCMCIA_IRQ - PIC_IRQ_BASE, PIC_PCMCIA_IRQ, 0x1, 0);
+		pic_setup_intr(PIC_PCMCIA_IRQ - PIC_IRQ_BASE, PIC_PCMCIA_IRQ, 0x1, 1);
 	}
 	return (0);
 }
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index 7d050c7676f..bc3dd77e3d7 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -297,7 +297,7 @@ xlr_pic_init(void)
 		2000,                   /* quality (adjusted in code) */
 	};
 	xlr_reg_t *mmio = xlr_io_mmio(XLR_IO_PIC_OFFSET);
-	int i, level, irq;
+	int i, irq;
 
 	write_c0_eimr64(0ULL);
 	mtx_init(&xlr_pic_lock, "pic", NULL, MTX_SPIN);
@@ -306,17 +306,14 @@ xlr_pic_init(void)
 	/* Initialize all IRT entries */
 	for (i = 0; i < PIC_NUM_IRTS; i++) {
 		irq = PIC_INTR_TO_IRQ(i);
-		level = PIC_IS_EDGE_TRIGGERED(i);
-
-		/* Bind all PIC irqs to cpu 0 */
-		xlr_write_reg(mmio, PIC_IRT_0(i), 0x01);
 
 		/*
-		 * Use local scheduling and high polarity for all IRTs
-		 * Invalidate all IRTs, by default
+		 * Disable all IRTs. Set defaults (local scheduling, high
+		 * polarity, level * triggered, and CPU irq)
 		 */
-		xlr_write_reg(mmio, PIC_IRT_1(i), (level << 30) | (1 << 6) |
-		    irq);
+		xlr_write_reg(mmio, PIC_IRT_1(i), (1 << 30) | (1 << 6) | irq);
+		/* Bind all PIC irqs to cpu 0 */
+		xlr_write_reg(mmio, PIC_IRT_0(i), 0x01);
 	}
 
 	/* Setup timer 7 of PIC as a timestamp, no interrupts */
diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c
index a7d3510eaaf..9756602c853 100644
--- a/sys/mips/rmi/xlr_pci.c
+++ b/sys/mips/rmi/xlr_pci.c
@@ -461,11 +461,11 @@ mips_platform_pci_setup_intr(device_t dev, device_t child,
 	if (xlr_board_info.is_xls == 0) {
 		xlr_establish_intr(device_get_name(child), filt,
 		    intr, arg, PIC_PCIX_IRQ, flags, cookiep, bridge_pcix_ack);
-		pic_setup_intr(PIC_IRT_PCIX_INDEX, PIC_PCIX_IRQ, 0x1, 0);
+		pic_setup_intr(PIC_IRT_PCIX_INDEX, PIC_PCIX_IRQ, 0x1, 1);
 	} else {
 		xlr_establish_intr(device_get_name(child), filt,
 		    intr, arg, xlrirq, flags, cookiep, bridge_pcie_ack);
-		pic_setup_intr(xlrirq - PIC_IRQ_BASE, xlrirq, 0x1, 0);
+		pic_setup_intr(xlrirq - PIC_IRQ_BASE, xlrirq, 0x1, 1);
 	}
 
 	return (bus_generic_setup_intr(dev, child, irq, flags, filt, intr,

From 9fa1edb882a3cd33fd350cfe5d9c848c48d87649 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Mon, 6 Sep 2010 07:34:32 +0000
Subject: [PATCH 0514/1624] acpi_hp: fix bus attachment code

- add identify method to create driver's own device_t
- successfully probe only driver's own device_t instead of any device_t
- (ab)use device order to hopefully be probed/attached after acpi_wmi

PR:		kern/147858
Tested by:	Maciej Suszko 
MFC after:	1 week
---
 sys/dev/acpi_support/acpi_hp.c | 42 ++++++++++++++++++++++++++++------
 1 file changed, 35 insertions(+), 7 deletions(-)

diff --git a/sys/dev/acpi_support/acpi_hp.c b/sys/dev/acpi_support/acpi_hp.c
index b0e85bed92e..a52905d2492 100644
--- a/sys/dev/acpi_support/acpi_hp.c
+++ b/sys/dev/acpi_support/acpi_hp.c
@@ -49,6 +49,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -116,7 +117,6 @@ struct acpi_hp_inst_seq_pair {
 
 struct acpi_hp_softc {
 	device_t	dev;
-	ACPI_HANDLE	handle;
 	device_t	wmi_dev;
 	int		has_notify;		/* notification GUID found */
 	int		has_cmi;		/* CMI GUID found */
@@ -289,6 +289,7 @@ static struct {
 
 ACPI_SERIAL_DECL(hp, "HP ACPI-WMI Mapping");
 
+static void	acpi_hp_identify(driver_t *driver, device_t parent);
 static int	acpi_hp_probe(device_t dev);
 static int	acpi_hp_attach(device_t dev);
 static int	acpi_hp_detach(device_t dev);
@@ -320,6 +321,7 @@ static struct cdevsw hpcmi_cdevsw = {
 };
 
 static device_method_t acpi_hp_methods[] = {
+	DEVMETHOD(device_identify, acpi_hp_identify),
 	DEVMETHOD(device_probe, acpi_hp_probe),
 	DEVMETHOD(device_attach, acpi_hp_attach),
 	DEVMETHOD(device_detach, acpi_hp_detach),
@@ -405,7 +407,7 @@ acpi_hp_evaluate_auto_on_off(struct acpi_hp_softc *sc)
 			    	    "WLAN on air changed to %i "
 			    	    "(new_wlan_status is %i)\n",
 			    	    sc->was_wlan_on_air, new_wlan_status);
-			acpi_UserNotify("HP", sc->handle,
+			acpi_UserNotify("HP", ACPI_ROOT_OBJECT,
 			    0xc0+sc->was_wlan_on_air);
 		}
 	}
@@ -420,7 +422,7 @@ acpi_hp_evaluate_auto_on_off(struct acpi_hp_softc *sc)
 				    " to %i (new_bluetooth_status is %i)\n",
 				    sc->was_bluetooth_on_air,
 				    new_bluetooth_status);
-			acpi_UserNotify("HP", sc->handle,
+			acpi_UserNotify("HP", ACPI_ROOT_OBJECT,
 			    0xd0+sc->was_bluetooth_on_air);
 		}
 	}
@@ -433,16 +435,43 @@ acpi_hp_evaluate_auto_on_off(struct acpi_hp_softc *sc)
 				    "WWAN on air changed to %i"
 			    	    " (new_wwan_status is %i)\n",
 				    sc->was_wwan_on_air, new_wwan_status);
-			acpi_UserNotify("HP", sc->handle,
+			acpi_UserNotify("HP", ACPI_ROOT_OBJECT,
 			    0xe0+sc->was_wwan_on_air);
 		}
 	}
 }
 
+static void
+acpi_hp_identify(driver_t *driver, device_t parent)
+{
+
+	/* Don't do anything if driver is disabled. */
+	if (acpi_disabled("hp"))
+		return;
+
+	/* Add only a single device instance. */
+	if (device_find_child(parent, "acpi_hp", -1) != NULL)
+		return;
+
+	/* Make sure acpi_wmi driver is present. */
+	if (devclass_find("acpi_wmi") == NULL)
+		return;
+
+	/*
+	 * Add our device with late order, so that it is hopefully
+	 * probed after acpi_wmi.
+	 * XXX User proper constant instead of UINT_MAX for order.
+	 */
+	if (BUS_ADD_CHILD(parent, UINT_MAX, "acpi_hp", -1) == NULL)
+		device_printf(parent, "add acpi_hp child failed\n");
+}
+
 static int
 acpi_hp_probe(device_t dev)
 {
-	if (acpi_disabled("hp") || device_get_unit(dev) != 0)
+
+	/* Skip auto-enumerated devices from ACPI namespace. */
+	if (acpi_get_handle(dev) != NULL)
 		return (ENXIO);
 	device_set_desc(dev, "HP ACPI-WMI Mapping");
 
@@ -460,7 +489,6 @@ acpi_hp_attach(device_t dev)
 
 	sc = device_get_softc(dev);
 	sc->dev = dev;
-	sc->handle = acpi_get_handle(dev);
 	sc->has_notify = 0;
 	sc->has_cmi = 0;
 	sc->bluetooth_enable_if_radio_on = 0;
@@ -477,7 +505,7 @@ acpi_hp_attach(device_t dev)
 	sc->verbose = 0;
 	memset(sc->cmi_order, 0, sizeof(sc->cmi_order));
 
-	if (!(wmi_devclass = devclass_find ("acpi_wmi"))) {
+	if (!(wmi_devclass = devclass_find("acpi_wmi"))) {
 		device_printf(dev, "Couldn't find acpi_wmi devclass\n");
 		return (EINVAL);
 	}

From 5172455266318054c7666c29b9b6a043208341c1 Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Mon, 6 Sep 2010 09:59:10 +0000
Subject: [PATCH 0515/1624] Document dhclient-enter-hooks and
 dhclient-exit-hooks and mention how to configure dhclient to clear the
 interface of IP numbers prior to configuring it.

PR:		149351
MFC after:	2 weeks
---
 sbin/dhclient/dhclient-script.8 | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/sbin/dhclient/dhclient-script.8 b/sbin/dhclient/dhclient-script.8
index b04974bc161..89d43cb76d4 100644
--- a/sbin/dhclient/dhclient-script.8
+++ b/sbin/dhclient/dhclient-script.8
@@ -38,7 +38,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd January 1, 1997
+.Dd September 6, 2010
 .Dt DHCLIENT-SCRIPT 8
 .Os
 .Sh NAME
@@ -218,6 +218,29 @@ if it has reason to believe they are valid, should exit with a value of zero.
 If not, it should exit with a nonzero value.
 .El
 .Pp
+Before taking action according to
+.Va $reason ,
+.Nm
+will check for the existence of
+.Pa /etc/dhclient-enter-hooks .
+If found, it will be sourced
+.Pq see Xr sh 1 .
+After taking action according to
+.Va $reason ,
+.Nm
+will check for the existence of
+.Pa /etc/dhclient-exit-hooks .
+If found, it will be sourced
+.Pq see Xr sh 1 .
+These hooks scripts can be used to dynamically modify the enviornment at
+appropriate times during the DHCP negotiations.
+For example, if the administrator wishes to disable alias IP numbers on
+the DHCP interface, they might want to put the following in
+.Pa /etc/dhclient-enter-hooks :
+.Bd -literal -offset indent
+[ ."$reason" = .PREINIT ] && ifconfig $interface 0.0.0.0
+.Ed
+.Pp
 The usual way to test a lease is to set up the network as with
 .Li REBIND
 (since this may be called to test more than one lease) and then ping
@@ -239,6 +262,7 @@ but current scripts do not do this.
 .\" and bear the names of the operating systems on which they are intended
 .\" to work.
 .Sh SEE ALSO
+.Xr sh 1 ,
 .Xr dhclient.conf 5 ,
 .Xr dhclient.leases 5 ,
 .Xr dhclient 8 ,

From b039b6f4b1c00ada7a0a5698b828e0e71817b5b5 Mon Sep 17 00:00:00 2001
From: Christian Brueffer 
Date: Mon, 6 Sep 2010 11:02:50 +0000
Subject: [PATCH 0516/1624] sis(4) should work on all architectures now.

---
 release/doc/share/misc/dev.archlist.txt | 1 -
 1 file changed, 1 deletion(-)

diff --git a/release/doc/share/misc/dev.archlist.txt b/release/doc/share/misc/dev.archlist.txt
index 91add892302..90f529fa7c5 100644
--- a/release/doc/share/misc/dev.archlist.txt
+++ b/release/doc/share/misc/dev.archlist.txt
@@ -107,7 +107,6 @@ rum	i386,amd64
 run	i386,amd64
 safe	i386,pc98,amd64
 sbp	i386,sparc64,ia64,amd64
-sis	i386,pc98,ia64,amd64
 sn	i386,amd64
 snc	pc98
 snd_ad1816	i386,amd64

From 14a268a0737ab7bc1905b8b27c8418305bfccfa8 Mon Sep 17 00:00:00 2001
From: Gleb Smirnoff 
Date: Mon, 6 Sep 2010 13:17:01 +0000
Subject: [PATCH 0517/1624] in_delayed_cksum() requires host byte order.

Reported by:	Alexander Levin 
MFC after:	1 week
---
 sys/netinet/ipfw/ip_fw_nat.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/sys/netinet/ipfw/ip_fw_nat.c b/sys/netinet/ipfw/ip_fw_nat.c
index f30b754dc16..6f223ed0de6 100644
--- a/sys/netinet/ipfw/ip_fw_nat.c
+++ b/sys/netinet/ipfw/ip_fw_nat.c
@@ -295,12 +295,9 @@ ipfw_nat(struct ip_fw_args *args, struct cfg_nat *t, struct mbuf *m)
 		struct udphdr 	*uh;
 		u_short cksum;
 
-		/* XXX check if ip_len can stay in net format */
-		cksum = in_pseudo(
-		    ip->ip_src.s_addr,
-		    ip->ip_dst.s_addr,
-		    htons(ip->ip_p + ntohs(ip->ip_len) - (ip->ip_hl << 2))
-		);
+		ip->ip_len = ntohs(ip->ip_len);
+		cksum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
+		    htons(ip->ip_p + ip->ip_len - (ip->ip_hl << 2)));
 
 		switch (ip->ip_p) {
 		case IPPROTO_TCP:
@@ -326,6 +323,7 @@ ipfw_nat(struct ip_fw_args *args, struct cfg_nat *t, struct mbuf *m)
 			in_delayed_cksum(mcl);
 			mcl->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
 		}
+		ip->ip_len = htons(ip->ip_len);
 	}
 	args->m = mcl;
 	return (IP_FW_NAT);

From 33eb2576c1a2b9cd96cc871b474808e5294a2c4d Mon Sep 17 00:00:00 2001
From: Andreas Tobler 
Date: Mon, 6 Sep 2010 19:00:00 +0000
Subject: [PATCH 0518/1624] Add myself to calendar.freebsd and
 committers-src.dot.

Approved by:	nwhitehorn	(mentor)
---
 share/misc/committers-src.dot               | 1 +
 usr.bin/calendar/calendars/calendar.freebsd | 1 +
 2 files changed, 2 insertions(+)

diff --git a/share/misc/committers-src.dot b/share/misc/committers-src.dot
index 27e0050fb01..0309058bcd7 100644
--- a/share/misc/committers-src.dot
+++ b/share/misc/committers-src.dot
@@ -58,6 +58,7 @@ akiyama [label="Shunsuke Akiyama\nakiyama@FreeBSD.org\n2000/06/19"]
 ambrisko [label="Doug Ambrisko\nambrisko@FreeBSD.org\n2001/12/19"]
 anchie [label="Ana Kukec\nanchie@FreeBSD.org\n2010/04/14"]
 andre [label="Andre Oppermann\nandre@FreeBSD.org\n2003/11/12"]
+andreast [label="Andreas Tobler\nandreast@FreeBSD.org\n2010/09/05"]
 andrew [label="Andrew Turner\nandrew@FreeBSD.org\n2010/07/19"]
 anholt [label="Eric Anholt\nanholt@FreeBSD.org\n2002/04/22"]
 antoine [label="Antoine Brodin\nantoine@FreeBSD.org\n2008/02/03"]
diff --git a/usr.bin/calendar/calendars/calendar.freebsd b/usr.bin/calendar/calendars/calendar.freebsd
index a3a807ed2d5..6bbe7be890e 100644
--- a/usr.bin/calendar/calendars/calendar.freebsd
+++ b/usr.bin/calendar/calendars/calendar.freebsd
@@ -180,6 +180,7 @@
 06/19	Charlie Root  born in Portland, Oregon, United States, 1993
 06/21	Ganbold Tsagaankhuu  born in Ulaanbaatar, Mongolia, 1971
 06/21	Niels Heinen  born in Markelo, the Netherlands, 1978
+06/22	Andreas Tobler  born in Heiden, Switzerland, 1968
 06/24	Chris Faulhaber  born in Springfield, Illinois, United States, 1971
 06/26	Brian Somers  born in Dundrum, Dublin, Ireland, 1967
 06/28	Mark Santcroos  born in Rotterdam, the Netherlands, 1979

From 98ea71a310f49e4d21b3548892fd0c5889189128 Mon Sep 17 00:00:00 2001
From: Andreas Tobler 
Date: Mon, 6 Sep 2010 20:16:10 +0000
Subject: [PATCH 0519/1624] Point out who is my mentor.

Approved by:	nwhitehorn	(mentor)
---
 share/misc/committers-src.dot | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/share/misc/committers-src.dot b/share/misc/committers-src.dot
index 0309058bcd7..195431ccc2d 100644
--- a/share/misc/committers-src.dot
+++ b/share/misc/committers-src.dot
@@ -411,6 +411,8 @@ njl -> philip
 njl -> rpaulo
 njl -> sepotvin
 
+nwhitehorn -> andreast
+
 obrien -> benno
 obrien -> groudier
 obrien -> gshapiro

From edb78df075462b3d7cf939111631029541607406 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 6 Sep 2010 20:35:48 +0000
Subject: [PATCH 0520/1624] Add aesni(4) manpage.

---
 share/man/man4/Makefile |  2 +
 share/man/man4/aesni.4  | 91 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 93 insertions(+)
 create mode 100644 share/man/man4/aesni.4

diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile
index 2fa0e9d9631..80f6837b705 100644
--- a/share/man/man4/Makefile
+++ b/share/man/man4/Makefile
@@ -18,6 +18,7 @@ MAN=	aac.4 \
 	adv.4 \
 	adw.4 \
 	ae.4 \
+	${_aesni.4} \
 	age.4 \
 	agp.4 \
 	aha.4 \
@@ -638,6 +639,7 @@ _acpi_panasonic.4=acpi_panasonic.4
 _acpi_sony.4=	acpi_sony.4
 _acpi_toshiba.4=acpi_toshiba.4
 _acpi_wmi.4=	acpi_wmi.4
+_aesni.4=	aesni.4
 _aibs.4=	aibs.4
 _amdsbwd.4=	amdsbwd.4
 _amdsmb.4=	amdsmb.4
diff --git a/share/man/man4/aesni.4 b/share/man/man4/aesni.4
new file mode 100644
index 00000000000..2396e489336
--- /dev/null
+++ b/share/man/man4/aesni.4
@@ -0,0 +1,91 @@
+.\" Copyright (c) 2010 Konstantin Belousov 
+.\" 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+.\"
+.\" $FreeBSD$
+.\"
+.Dd September 6, 2010
+.Dt AESNI 4
+.Os
+.Sh NAME
+.Nm aesni
+.Nd "driver for the AES accelerator on Intel CPUs"
+.Sh SYNOPSIS
+To compile this driver into the kernel,
+place the following lines in your
+kernel configuration file:
+.Bd -ragged -offset indent
+.Cd "device crypto"
+.Cd "device aesni"
+.Ed
+.Pp
+Alternatively, to load the driver as a
+module at boot time, place the following line in
+.Xr loader.conf 5 :
+.Bd -literal -offset indent
+aesni_load="YES"
+.Ed
+.Sh DESCRIPTION
+Starting with some models of Core i5/i7, Intel processors implement
+new set of instructions called AESNI.
+The set of six instructions accelerates the calculation of the key
+schedule for key lengths of 128, 192, and 256 of the Advanced
+Encryption Standard (AES) symmetric cipher, and provides the hardware
+implementation of the regular and the last encryption and decryption
+rounds.
+.Pp
+The processor capability is reported as AESNI in the Features2 line
+at the boot. Driver does not attach on the system that lacks the
+required CPU capability.
+.Pp
+The
+.Nm
+driver registers itself to accelerate AES operations for
+.Xr crypto 4 .
+Besides speed, advantage of using the driver is that the AESNI operation
+is data-independend, thus eliminating some attack vectors based on the
+measuring cache use and timings, typically present in the table-driven
+implementations.
+.Sh SEE ALSO
+.Xr crypt 3 ,
+.Xr crypto 4 ,
+.Xr intro 4 ,
+.Xr ipsec 4 ,
+.Xr padlock 4 ,
+.Xr random 4 ,
+.Xr crypto 9
+.Sh HISTORY
+The
+.Nm
+driver first appeared in
+.Fx 9.0 .
+.Sh AUTHORS
+.An -nosplit
+The
+.Nm
+driver was written by
+.An Konstantin Belousov Aq kib@FreeBSD.org .
+The key schedule calculation code was adopted from the sample provided
+by Intel and used in the analogous
+.Ox
+driver.

From 58175a74fc6ad1bdd2bde0f747d5955b648257ac Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Mon, 6 Sep 2010 20:40:38 +0000
Subject: [PATCH 0521/1624] Fix typo in bsdcpio manual:
 s/libarchive_formats/libarchive-formats

PR:		150300
Submitted by:	Kurt Jaeger 
Patch by:	Kurt Jaeger
Approved by:	keramida (mentor)
MFC after:	1 week
---
 usr.bin/cpio/bsdcpio.1 | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/usr.bin/cpio/bsdcpio.1 b/usr.bin/cpio/bsdcpio.1
index bb69fd1578d..789ce74e1c4 100644
--- a/usr.bin/cpio/bsdcpio.1
+++ b/usr.bin/cpio/bsdcpio.1
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd December 21, 2007
+.Dd September 5, 2010
 .Dt BSDCPIO 1
 .Os
 .Sh NAME
@@ -140,7 +140,7 @@ The POSIX.1 tar format.
 The default format is
 .Ar odc .
 See
-.Xr libarchive_formats 5
+.Xr libarchive-formats 5
 for more complete information about the
 formats currently supported by the underlying
 .Xr libarchive 3

From e24fa11d3ecb855a6e13270975d2e0c87d60c617 Mon Sep 17 00:00:00 2001
From: Will Andrews 
Date: Mon, 6 Sep 2010 21:03:30 +0000
Subject: [PATCH 0522/1624] Fix static kernel builds with carp(4) by changing
 its SYSINIT order so that it is initialized after basic protocol
 initialization, which allows it to register via pf_proto_register().

Reviewed by:	bz
Approved by:	ken (mentor)
---
 sys/netinet/ip_carp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/netinet/ip_carp.c b/sys/netinet/ip_carp.c
index 8de168463e8..08c32570257 100644
--- a/sys/netinet/ip_carp.c
+++ b/sys/netinet/ip_carp.c
@@ -2405,4 +2405,4 @@ static moduledata_t carp_mod = {
 	0
 };
 
-DECLARE_MODULE(carp, carp_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
+DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);

From 15249f73e93334bf0ec87b528e906524a4c461d0 Mon Sep 17 00:00:00 2001
From: Will Andrews 
Date: Mon, 6 Sep 2010 21:06:06 +0000
Subject: [PATCH 0523/1624] Fix CARP in backup mode by properly registering its
 hooks for INET and INET6 using ipproto_{un,}register() and the newly created
 ip6proto_{un,}register() so that it can again receive IPPROTO_CARP packets
 allowing its state machine to work.

Reviewed by:	bz
Approved by:	ken (mentor)
---
 sys/netinet/ip_carp.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/sys/netinet/ip_carp.c b/sys/netinet/ip_carp.c
index 08c32570257..569f6b3209c 100644
--- a/sys/netinet/ip_carp.c
+++ b/sys/netinet/ip_carp.c
@@ -2313,6 +2313,7 @@ carp_mod_cleanup(void)
 	if_clone_detach(&carp_cloner);
 #ifdef INET
 	if (proto_reg[CARP_INET] == 0) {
+		(void)ipproto_unregister(IPPROTO_CARP);
 		pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
 		proto_reg[CARP_INET] = -1;
 	}
@@ -2320,6 +2321,7 @@ carp_mod_cleanup(void)
 #endif
 #ifdef INET6
 	if (proto_reg[CARP_INET6] == 0) {
+		(void)ip6proto_unregister(IPPROTO_CARP);
 		pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
 		proto_reg[CARP_INET6] = -1;
 	}
@@ -2335,6 +2337,7 @@ carp_mod_cleanup(void)
 static int
 carp_mod_load(void)
 {
+	int err;
 
 	if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
 		carp_ifdetach, NULL, EVENTHANDLER_PRI_ANY);
@@ -2357,6 +2360,12 @@ carp_mod_load(void)
 		carp_mod_cleanup();
 		return (EINVAL);
 	}
+	err = ip6proto_register(IPPROTO_CARP);
+	if (err) {
+		printf("carp: error %d registering with INET6\n", err);
+		carp_mod_cleanup();
+		return (EINVAL);
+	}
 #endif
 #ifdef INET
 	carp_iamatch_p = carp_iamatch;
@@ -2367,6 +2376,12 @@ carp_mod_load(void)
 		carp_mod_cleanup();
 		return (EINVAL);
 	}
+	err = ipproto_register(IPPROTO_CARP);
+	if (err) {
+		printf("carp: error %d registering with INET\n", err);
+		carp_mod_cleanup();
+		return (EINVAL);
+	}
 #endif
 	return 0;
 }

From f5447a3079d816a72b951caff6457331402519c0 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Mon, 6 Sep 2010 21:29:21 +0000
Subject: [PATCH 0524/1624] Grammar fixes.

Submitted by:	Ben Kaduk , Valentin Nechaev
---
 share/man/man4/aesni.4 | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)

diff --git a/share/man/man4/aesni.4 b/share/man/man4/aesni.4
index 2396e489336..995f2b51c59 100644
--- a/share/man/man4/aesni.4
+++ b/share/man/man4/aesni.4
@@ -47,24 +47,23 @@ aesni_load="YES"
 .Ed
 .Sh DESCRIPTION
 Starting with some models of Core i5/i7, Intel processors implement
-new set of instructions called AESNI.
+a new set of instructions called AESNI.
 The set of six instructions accelerates the calculation of the key
 schedule for key lengths of 128, 192, and 256 of the Advanced
-Encryption Standard (AES) symmetric cipher, and provides the hardware
+Encryption Standard (AES) symmetric cipher, and provides hardware
 implementation of the regular and the last encryption and decryption
 rounds.
 .Pp
-The processor capability is reported as AESNI in the Features2 line
-at the boot. Driver does not attach on the system that lacks the
-required CPU capability.
+The processor capability is reported as AESNI in the Features2 line at boot.
+Driver does not attach on the system that lacks the required CPU capability.
 .Pp
 The
 .Nm
 driver registers itself to accelerate AES operations for
 .Xr crypto 4 .
-Besides speed, advantage of using the driver is that the AESNI operation
-is data-independend, thus eliminating some attack vectors based on the
-measuring cache use and timings, typically present in the table-driven
+Besides speed, the advantage of using the driver is that the AESNI operation
+is data-independent, thus eliminating some attack vectors based on
+measuring cache use and timings typically present in the table-driven
 implementations.
 .Sh SEE ALSO
 .Xr crypt 3 ,

From 1bc1532c366d5d7aeb3ef22fb0a39872998eb5f4 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Mon, 6 Sep 2010 21:39:54 +0000
Subject: [PATCH 0525/1624] Add ECONNRESET to list of possible errors in
 connect(2).

PR:		148683
Submitted by:	Gennady Proskurin 
Approved by:	keramida (mentor)
MFC after:	1 week
---
 lib/libc/sys/connect.2 | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/lib/libc/sys/connect.2 b/lib/libc/sys/connect.2
index c673a836d23..ac019e829c3 100644
--- a/lib/libc/sys/connect.2
+++ b/lib/libc/sys/connect.2
@@ -28,7 +28,7 @@
 .\"     @(#)connect.2	8.1 (Berkeley) 6/4/93
 .\" $FreeBSD$
 .\"
-.Dd August 16, 2006
+.Dd September 5, 2010
 .Dt CONNECT 2
 .Os
 .Sh NAME
@@ -95,6 +95,8 @@ The socket is already connected.
 Connection establishment timed out without establishing a connection.
 .It Bq Er ECONNREFUSED
 The attempt to connect was forcefully rejected.
+.It Bq Er ECONNRESET
+The connection was reset by the remote host.
 .It Bq Er ENETUNREACH
 The network is not reachable from this host.
 .It Bq Er EHOSTUNREACH

From d3e3be7fc75026bf607843a4e07705e078e52ce2 Mon Sep 17 00:00:00 2001
From: Weongyo Jeong 
Date: Mon, 6 Sep 2010 22:02:08 +0000
Subject: [PATCH 0526/1624] Adds bwi(4) at SEE ALSO section because some old
 devices aren't supported by the bwn(4) firmware that as fas as I know the
 vendor dropped its support.  Bumps date also.

---
 share/man/man4/bwn.4 | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/bwn.4 b/share/man/man4/bwn.4
index b75f9d03bab..9094fa09f11 100644
--- a/share/man/man4/bwn.4
+++ b/share/man/man4/bwn.4
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd February 25, 2010
+.Dd September 6, 2010
 .Dt BWN 4
 .Os
 .Sh NAME
@@ -112,6 +112,7 @@ ifconfig wlan create wlandev bwn0 ssid my_net \e
 .Ed
 .Sh SEE ALSO
 .Xr arp 4 ,
+.Xr bwi 4 ,
 .Xr cardbus 4 ,
 .Xr intro 4 ,
 .Xr pci 4 ,

From 5454c3c04e85a5ca12e225ee61021a2fad8f8282 Mon Sep 17 00:00:00 2001
From: Weongyo Jeong 
Date: Mon, 6 Sep 2010 22:10:57 +0000
Subject: [PATCH 0527/1624] Adds a CAVEATS section to mention DMA issues that
 currently only a solution is using PIO mode.  As fas as I know all open
 source based broadcom drivers for specially LP PHY has this issue because
 it's a reverse engineered driver from wl(4).

Pointed by:	Warren Block 
---
 share/man/man4/bwn.4 | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/share/man/man4/bwn.4 b/share/man/man4/bwn.4
index 9094fa09f11..622e3f513ee 100644
--- a/share/man/man4/bwn.4
+++ b/share/man/man4/bwn.4
@@ -125,6 +125,9 @@ The
 .Nm
 driver first appeared in
 .Fx 8.1 .
+.Sh CAVEATS
+Some LP PHY devices have DMA operation problems that in that case try to
+use PIO mode.
 .Sh AUTHORS
 .An -nosplit
 The

From 50398e411f7c3ce3b235a05b9cfecc3318400628 Mon Sep 17 00:00:00 2001
From: Weongyo Jeong 
Date: Mon, 6 Sep 2010 22:23:35 +0000
Subject: [PATCH 0528/1624] Adds LOADER TUNABLES section to mention knobs which
 could be controlled by loader(8) interface.

---
 share/man/man4/bwn.4 | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/share/man/man4/bwn.4 b/share/man/man4/bwn.4
index 622e3f513ee..23514f58a59 100644
--- a/share/man/man4/bwn.4
+++ b/share/man/man4/bwn.4
@@ -110,6 +110,20 @@ Join a specific BSS network with 64-bit WEP encryption:
 ifconfig wlan create wlandev bwn0 ssid my_net \e
         wepmode on wepkey 0x1234567890 weptxkey 1 up
 .Ed
+.Sh LOADER TUNABLES
+Tunables can be set at the
+.Xr loader 8
+prompt before booting the kernel or stored in
+.Xr loader.conf 5 .
+.Bl -tag -width indent
+.It Va hw.bwn.msi_disable
+This tunable disables MSI support on the hardware.
+The default value is 0.
+.It Va hw.bwn.usedma
+This tunable enables DMA operations on the hardware.
+If the value is 0, PIO mode would be used.
+The default value is 1.
+.El
 .Sh SEE ALSO
 .Xr arp 4 ,
 .Xr bwi 4 ,

From e9b5f21819c8d53f17eb17dc9c9502ac04cc0b8f Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Mon, 6 Sep 2010 23:07:58 +0000
Subject: [PATCH 0529/1624] Fix the same race condition on 32-bit AIM CPUs that
 was fixed for 64-bit ones in r211967 involving VSID allocation.

---
 sys/powerpc/aim/mmu_oea.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/sys/powerpc/aim/mmu_oea.c b/sys/powerpc/aim/mmu_oea.c
index da83538b462..d3a24598942 100644
--- a/sys/powerpc/aim/mmu_oea.c
+++ b/sys/powerpc/aim/mmu_oea.c
@@ -203,6 +203,7 @@ extern struct pmap ofw_pmap;
  * Lock for the pteg and pvo tables.
  */
 struct mtx	moea_table_mutex;
+struct mtx	moea_vsid_mutex;
 
 /* tlbie instruction synchronization */
 static struct mtx tlbie_mtx;
@@ -819,6 +820,7 @@ moea_bootstrap(mmu_t mmup, vm_offset_t kernelstart, vm_offset_t kernelend)
 	 */
 	mtx_init(&moea_table_mutex, "pmap table", NULL, MTX_DEF |
 	    MTX_RECURSE);
+	mtx_init(&moea_vsid_mutex, "VSID table", NULL, MTX_DEF);
 
 	mtx_init(&tlbie_mtx, "tlbie", NULL, MTX_SPIN);
 
@@ -1589,6 +1591,7 @@ moea_pinit(mmu_t mmu, pmap_t pmap)
 	}
 	
 
+	mtx_lock(&moea_vsid_mutex);
 	/*
 	 * Allocate some segment registers for this pmap.
 	 */
@@ -1623,9 +1626,11 @@ moea_pinit(mmu_t mmu, pmap_t pmap)
 		moea_vsid_bitmap[n] |= mask;
 		for (i = 0; i < 16; i++)
 			pmap->pm_sr[i] = VSID_MAKE(i, hash);
+		mtx_unlock(&moea_vsid_mutex);
 		return;
 	}
 
+	mtx_unlock(&moea_vsid_mutex);
 	panic("moea_pinit: out of segments");
 }
 
@@ -1737,10 +1742,12 @@ moea_release(mmu_t mmu, pmap_t pmap)
         if (pmap->pm_sr[0] == 0)
                 panic("moea_release");
 
+	mtx_lock(&moea_vsid_mutex);
         idx = VSID_TO_HASH(pmap->pm_sr[0]) & (NPMAPS-1);
         mask = 1 << (idx % VSID_NBPW);
         idx /= VSID_NBPW;
         moea_vsid_bitmap[idx] &= ~mask;
+	mtx_unlock(&moea_vsid_mutex);
 	PMAP_LOCK_DESTROY(pmap);
 }
 

From 0d4196409576439db893303e3bd6f3170e0e3d5e Mon Sep 17 00:00:00 2001
From: Ryan Stone 
Date: Tue, 7 Sep 2010 00:23:45 +0000
Subject: [PATCH 0530/1624] In munmap() downgrade the vm_map_lock to a read
 lock before taking a read lock on the pmc-sx lock.  This prevents a deadlock
 with pmc_log_process_mappings, which has an exclusive lock on pmc-sx and
 tries to get a read lock on a vm_map.  Downgrading the vm_map_lock in munmap
 allows pmc_log_process_mappings to continue, preventing the deadlock.

Without this change I could cause a deadlock on a multicore 8.1-RELEASE
system by having one thread constantly mmap'ing and then munmap'ing a
PROT_EXEC mapping in a loop while I repeatedly invoked and stopped pmcstat
in system-wide sampling mode.

Reviewed by:	fabient
Approved by:	emaste (mentor)
MFC after:	2 weeks
---
 sys/vm/vm_mmap.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/sys/vm/vm_mmap.c b/sys/vm/vm_mmap.c
index 2071cc7772d..c9126785cab 100644
--- a/sys/vm/vm_mmap.c
+++ b/sys/vm/vm_mmap.c
@@ -579,6 +579,7 @@ munmap(td, uap)
 	 * Inform hwpmc if the address range being unmapped contains
 	 * an executable region.
 	 */
+	pkm.pm_address = (uintptr_t) NULL;
 	if (vm_map_lookup_entry(map, addr, &entry)) {
 		for (;
 		     entry != &map->header && entry->start < addr + size;
@@ -587,16 +588,23 @@ munmap(td, uap)
 				entry->end, VM_PROT_EXECUTE) == TRUE) {
 				pkm.pm_address = (uintptr_t) addr;
 				pkm.pm_size = (size_t) size;
-				PMC_CALL_HOOK(td, PMC_FN_MUNMAP,
-				    (void *) &pkm);
 				break;
 			}
 		}
 	}
 #endif
-	/* returns nothing but KERN_SUCCESS anyway */
 	vm_map_delete(map, addr, addr + size);
+
+#ifdef HWPMC_HOOKS
+	/* downgrade the lock to prevent a LOR with the pmc-sx lock */
+	vm_map_lock_downgrade(map);
+	if (pkm.pm_address != (uintptr) NULL)
+		PMC_CALL_HOOK(td, PMC_FN_MUNMAP, (void *) &pkm);
+	vm_map_unlock_read(map);
+#else
 	vm_map_unlock(map);
+#endif
+	/* vm_map_delete returns nothing but KERN_SUCCESS anyway */
 	return (0);
 }
 

From d473d3a1641090cb0f6016bc8eea42622d49eb1e Mon Sep 17 00:00:00 2001
From: Ryan Stone 
Date: Tue, 7 Sep 2010 02:51:11 +0000
Subject: [PATCH 0531/1624] Fix a typo in r212281.  uintptr -> uintptr_t

Pointy hat to:  rstone

Approved by:    emaste (mentor)
MFC after:      2 weeks
---
 sys/vm/vm_mmap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/vm/vm_mmap.c b/sys/vm/vm_mmap.c
index c9126785cab..63dfb6737e6 100644
--- a/sys/vm/vm_mmap.c
+++ b/sys/vm/vm_mmap.c
@@ -598,7 +598,7 @@ munmap(td, uap)
 #ifdef HWPMC_HOOKS
 	/* downgrade the lock to prevent a LOR with the pmc-sx lock */
 	vm_map_lock_downgrade(map);
-	if (pkm.pm_address != (uintptr) NULL)
+	if (pkm.pm_address != (uintptr_t) NULL)
 		PMC_CALL_HOOK(td, PMC_FN_MUNMAP, (void *) &pkm);
 	vm_map_unlock_read(map);
 #else

From 70b4737e057f42a36c45afc256656df923f39728 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Tue, 7 Sep 2010 05:39:24 +0000
Subject: [PATCH 0532/1624] On boards with >512MB memory, the result of vtophys
 cannot be converted to KSEG1 address - use pmap_mapdev/pmap_unmapdev instead.

Remove unused variable maxphys.
---
 sys/mips/mips/busdma_machdep.c | 22 +++++-----------------
 1 file changed, 5 insertions(+), 17 deletions(-)

diff --git a/sys/mips/mips/busdma_machdep.c b/sys/mips/mips/busdma_machdep.c
index a6a7419747c..4bdfc821ae7 100644
--- a/sys/mips/mips/busdma_machdep.c
+++ b/sys/mips/mips/busdma_machdep.c
@@ -425,7 +425,6 @@ bus_dma_tag_destroy(bus_dma_tag_t dmat)
 #endif
 
 	if (dmat != NULL) {
-		
                 if (dmat->map_count != 0)
                         return (EBUSY);
 		
@@ -602,20 +601,6 @@ bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
                  *     and handles multi-seg allocations.  Nobody is doing
                  *     multi-seg allocations yet though.
                  */
-	         vm_paddr_t maxphys;
-	         if((uint32_t)dmat->lowaddr >= MIPS_KSEG0_LARGEST_PHYS) {
-		   /* Note in the else case I just put in what was already
-		    * being passed in dmat->lowaddr. I am not sure
-		    * how this would have worked. Since lowaddr is in the
-		    * max address postion. I would have thought that the
-		    * caller would have wanted dmat->highaddr. That is
-		    * presuming they are asking for physical addresses
-		    * which is what contigmalloc takes. - RRS
-		    */
-		   maxphys = MIPS_KSEG0_LARGEST_PHYS - 1;
-		 } else {
-		   maxphys = dmat->lowaddr;
-		 }
                 *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
                     0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
                     dmat->boundary);
@@ -633,7 +618,8 @@ bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
 		void *tmpaddr = (void *)*vaddr;
 
 		if (tmpaddr) {
-			tmpaddr = (void *)MIPS_PHYS_TO_KSEG1(vtophys(tmpaddr));
+			tmpaddr = (void *)pmap_mapdev(vtophys(tmpaddr),
+			    dmat->maxsize);
 			newmap->origbuffer = *vaddr;
 			newmap->allocbuffer = tmpaddr;
 			mips_dcache_wbinv_range((vm_offset_t)*vaddr,
@@ -660,6 +646,8 @@ bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
 		vaddr = map->origbuffer;
 	}
 
+	if (map->flags & DMAMAP_UNCACHEABLE)
+		pmap_unmapdev((vm_offset_t)map->allocbuffer, dmat->maxsize);
         if (map->flags & DMAMAP_MALLOCUSED)
 		free(vaddr, M_DEVBUF);
         else
@@ -1360,7 +1348,7 @@ alloc_bounce_pages(bus_dma_tag_t dmat, u_int numpages)
 		}
 		bpage->busaddr = pmap_kextract(bpage->vaddr);
 		bpage->vaddr_nocache = 
-		    (vm_offset_t)MIPS_PHYS_TO_KSEG1(bpage->busaddr);
+		    (vm_offset_t)pmap_mapdev(bpage->busaddr, PAGE_SIZE);
 		mtx_lock(&bounce_lock);
 		STAILQ_INSERT_TAIL(&bz->bounce_page_list, bpage, links);
 		total_bpages++;

From 3434740df2bd9f0574568547052559452738e9c0 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Tue, 7 Sep 2010 06:02:43 +0000
Subject: [PATCH 0533/1624] Whitespace fixes - indent with tabs instead of
 spaces. Few other style(9) changes.

---
 sys/mips/mips/busdma_machdep.c | 128 ++++++++++++++++-----------------
 1 file changed, 64 insertions(+), 64 deletions(-)

diff --git a/sys/mips/mips/busdma_machdep.c b/sys/mips/mips/busdma_machdep.c
index 4bdfc821ae7..93ae8d29dab 100644
--- a/sys/mips/mips/busdma_machdep.c
+++ b/sys/mips/mips/busdma_machdep.c
@@ -133,7 +133,7 @@ struct bus_dmamap {
 	struct bp_list	bpages;
 	int		pagesneeded;
 	int		pagesreserved;
-        bus_dma_tag_t	dmat;
+	bus_dma_tag_t	dmat;
 	int		flags;
 	void 		*buffer;
 	void		*origbuffer;
@@ -142,7 +142,7 @@ struct bus_dmamap {
 	int		len;
 	STAILQ_ENTRY(bus_dmamap) links;
 	bus_dmamap_callback_t *callback;
-	void		      *callback_arg;
+	void		*callback_arg;
 
 };
 
@@ -310,11 +310,11 @@ _busdma_free_dmamap(bus_dmamap_t map)
 
 int
 bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
-		   bus_size_t boundary, bus_addr_t lowaddr,
-		   bus_addr_t highaddr, bus_dma_filter_t *filter,
-		   void *filterarg, bus_size_t maxsize, int nsegments,
-		   bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
-		   void *lockfuncarg, bus_dma_tag_t *dmat)
+    bus_size_t boundary, bus_addr_t lowaddr,
+    bus_addr_t highaddr, bus_dma_filter_t *filter,
+    void *filterarg, bus_size_t maxsize, int nsegments,
+    bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc,
+    void *lockfuncarg, bus_dma_tag_t *dmat)
 {
 	bus_dma_tag_t newtag;
 	int error = 0;
@@ -337,8 +337,8 @@ bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
 	newtag->highaddr = trunc_page((vm_offset_t)highaddr) + (PAGE_SIZE - 1);
 	newtag->filter = filter;
 	newtag->filterarg = filterarg;
-        newtag->maxsize = maxsize;
-        newtag->nsegments = nsegments;
+	newtag->maxsize = maxsize;
+	newtag->nsegments = nsegments;
 	newtag->maxsegsz = maxsegsz;
 	newtag->flags = flags;
 	if (cpuinfo.cache_coherent_dma)
@@ -352,28 +352,28 @@ bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment,
 		newtag->lockfunc = dflt_lock;
 		newtag->lockfuncarg = NULL;
 	}
-        /*
+	/*
 	 * Take into account any restrictions imposed by our parent tag
 	 */
-        if (parent != NULL) {
-                newtag->lowaddr = min(parent->lowaddr, newtag->lowaddr);
-                newtag->highaddr = max(parent->highaddr, newtag->highaddr);
+	if (parent != NULL) {
+		newtag->lowaddr = min(parent->lowaddr, newtag->lowaddr);
+		newtag->highaddr = max(parent->highaddr, newtag->highaddr);
 		if (newtag->boundary == 0)
 			newtag->boundary = parent->boundary;
 		else if (parent->boundary != 0)
-                	newtag->boundary = min(parent->boundary,
-					       newtag->boundary);
+			newtag->boundary =
+			    min(parent->boundary, newtag->boundary);
 		if ((newtag->filter != NULL) ||
 		    ((parent->flags & BUS_DMA_COULD_BOUNCE) != 0))
 			newtag->flags |= BUS_DMA_COULD_BOUNCE;
-                if (newtag->filter == NULL) {
-                        /*
-                         * Short circuit looking at our parent directly
-                         * since we have encapsulated all of its information
-                         */
-                        newtag->filter = parent->filter;
-                        newtag->filterarg = parent->filterarg;
-                        newtag->parent = parent->parent;
+		if (newtag->filter == NULL) {
+			/*
+			* Short circuit looking at our parent directly
+			* since we have encapsulated all of its information
+			*/
+			newtag->filter = parent->filter;
+			newtag->filterarg = parent->filterarg;
+			newtag->parent = parent->parent;
 		}
 		if (newtag->parent != NULL)
 			atomic_add_int(&parent->ref_count, 1);
@@ -425,29 +425,29 @@ bus_dma_tag_destroy(bus_dma_tag_t dmat)
 #endif
 
 	if (dmat != NULL) {
-                if (dmat->map_count != 0)
-                        return (EBUSY);
+		if (dmat->map_count != 0)
+			return (EBUSY);
 		
-                while (dmat != NULL) {
-                        bus_dma_tag_t parent;
+		while (dmat != NULL) {
+			bus_dma_tag_t parent;
 			
-                        parent = dmat->parent;
-                        atomic_subtract_int(&dmat->ref_count, 1);
-                        if (dmat->ref_count == 0) {
-                                free(dmat, M_DEVBUF);
-                                /*
-                                 * Last reference count, so
-                                 * release our reference
-                                 * count on our parent.
-                                 */
-                                dmat = parent;
-                        } else
-                                dmat = NULL;
-                }
-        }
+			parent = dmat->parent;
+			atomic_subtract_int(&dmat->ref_count, 1);
+			if (dmat->ref_count == 0) {
+				free(dmat, M_DEVBUF);
+				/*
+				 * Last reference count, so
+				 * release our reference
+				 * count on our parent.
+				 */
+				dmat = parent;
+			} else
+			dmat = NULL;
+		}
+	}
 	CTR2(KTR_BUSDMA, "%s tag %p", __func__, dmat_copy);
 
-        return (0);
+	return (0);
 }
 
 #include 
@@ -553,7 +553,7 @@ bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)
  */
 int
 bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
-                 bus_dmamap_t *mapp)
+    bus_dmamap_t *mapp)
 {
 	bus_dmamap_t newmap = NULL;
 
@@ -589,29 +589,29 @@ bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
 	if (flags & BUS_DMA_COHERENT)
 	    newmap->flags |= DMAMAP_UNCACHEABLE;
 
-        if (dmat->maxsize <= PAGE_SIZE &&
+	if (dmat->maxsize <= PAGE_SIZE &&
 	   (dmat->alignment < dmat->maxsize) &&
 	   !_bus_dma_can_bounce(dmat->lowaddr, dmat->highaddr) && 
 	   !(newmap->flags & DMAMAP_UNCACHEABLE)) {
                 *vaddr = malloc(dmat->maxsize, M_DEVBUF, mflags);
 		newmap->flags |= DMAMAP_MALLOCUSED;
-        } else {
-                /*
-                 * XXX Use Contigmalloc until it is merged into this facility
-                 *     and handles multi-seg allocations.  Nobody is doing
-                 *     multi-seg allocations yet though.
-                 */
-                *vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
-                    0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
-                    dmat->boundary);
-        }
-        if (*vaddr == NULL) {
+	} else {
+		/*
+		 * XXX Use Contigmalloc until it is merged into this facility
+		 *     and handles multi-seg allocations.  Nobody is doing
+		 *     multi-seg allocations yet though.
+		 */
+		*vaddr = contigmalloc(dmat->maxsize, M_DEVBUF, mflags,
+		    0ul, dmat->lowaddr, dmat->alignment? dmat->alignment : 1ul,
+		    dmat->boundary);
+	}
+	if (*vaddr == NULL) {
 		if (newmap != NULL) {
 			_busdma_free_dmamap(newmap);
 			dmat->map_count--;
 		}
 		*mapp = NULL;
-                return (ENOMEM);
+		return (ENOMEM);
 	}
 
 	if (newmap->flags & DMAMAP_UNCACHEABLE) {
@@ -630,7 +630,7 @@ bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags,
 	} else
 		newmap->origbuffer = newmap->allocbuffer = NULL;
 
-        return (0);
+	return (0);
 }
 
 /*
@@ -648,9 +648,9 @@ bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
 
 	if (map->flags & DMAMAP_UNCACHEABLE)
 		pmap_unmapdev((vm_offset_t)map->allocbuffer, dmat->maxsize);
-        if (map->flags & DMAMAP_MALLOCUSED)
+	if (map->flags & DMAMAP_MALLOCUSED)
 		free(vaddr, M_DEVBUF);
-        else
+	else
 		contigfree(vaddr, dmat->maxsize, M_DEVBUF);
 
 	dmat->map_count--;
@@ -819,10 +819,10 @@ segdone:
  */
 int
 bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
-                bus_size_t buflen, bus_dmamap_callback_t *callback,
-                void *callback_arg, int flags)
+    bus_size_t buflen, bus_dmamap_callback_t *callback,
+    void *callback_arg, int flags)
 {
-     	vm_offset_t	lastaddr = 0;
+	vm_offset_t	lastaddr = 0;
 	int		error, nsegs = -1;
 #ifdef __CC_SUPPORTS_DYNAMIC_ARRAY_INIT
 	bus_dma_segment_t dm_segments[dmat->nsegments];
@@ -859,8 +859,8 @@ bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf,
  */
 int
 bus_dmamap_load_mbuf(bus_dma_tag_t dmat, bus_dmamap_t map, struct mbuf *m0,
-		     bus_dmamap_callback2_t *callback, void *callback_arg,
-		     int flags)
+    bus_dmamap_callback2_t *callback, void *callback_arg,
+    int flags)
 {
 #ifdef __CC_SUPPORTS_DYNAMIC_ARRAY_INIT
 	bus_dma_segment_t dm_segments[dmat->nsegments];

From 36a7e258548b8cf880dc3197d32389565107b6ea Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Tue, 7 Sep 2010 07:31:58 +0000
Subject: [PATCH 0534/1624] PCIe updates for XLS.

Fix interrupt routing so that the irq returned is correct for XLR and
XLS. This also updates the MSI hack we had earlier - we still don't
really support MSI, but we support some drivers that use MSI, by providing
support for allocating one MSI per pci link - this MSI is directly
mapped to the link IRQ.
---
 sys/mips/rmi/xlr_pci.c | 129 ++++++++++++++++++++++++++---------------
 1 file changed, 82 insertions(+), 47 deletions(-)

diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c
index 9756602c853..0b12d9ee4a5 100644
--- a/sys/mips/rmi/xlr_pci.c
+++ b/sys/mips/rmi/xlr_pci.c
@@ -326,51 +326,77 @@ xlr_pcib_identify(driver_t * driver, device_t parent)
 	BUS_ADD_CHILD(parent, 0, "pcib", 0);
 }
 
+/*
+ * XLS PCIe can have upto 4 links, and each link has its on IRQ
+ * Find the link on which the device is on 
+ */
 static int
-xlr_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
+xls_pcie_link(device_t pcib, device_t dev)
 {
-	int pciirq;
-	int i;
 	device_t parent, tmp;
 
 	/* find the lane on which the slot is connected to */
+	printf("xls_pcie_link : bus %s dev %s\n", device_get_nameunit(pcib),
+		device_get_nameunit(dev));
 	tmp = dev;
 	while (1) {
 		parent = device_get_parent(tmp);
 		if (parent == NULL || parent == pcib) {
 			device_printf(dev, "Cannot find parent bus\n");
-			return (ENXIO);
+			return (-1);
 		}
 		if (strcmp(device_get_nameunit(parent), "pci0") == 0)
 			break;
 		tmp = parent;
 	}
+	return (pci_get_slot(tmp));
+}
 
-	switch (pci_get_slot(tmp)) {
+/*
+ * Find the IRQ for the link, each link has a different interrupt 
+ * at the XLS pic
+ */
+static int
+xls_pcie_link_irq(int link)
+{
+
+	switch (link) {
 	case 0:
-		pciirq = PIC_PCIE_LINK0_IRQ;
-		break;
+		return (PIC_PCIE_LINK0_IRQ);
 	case 1:
-		pciirq = PIC_PCIE_LINK1_IRQ;
-		break;
+		return (PIC_PCIE_LINK1_IRQ);
 	case 2:
-		pciirq = PIC_PCIE_LINK2_IRQ;
-		break;
+		return (PIC_PCIE_LINK2_IRQ);
 	case 3:
-		pciirq = PIC_PCIE_LINK3_IRQ;
-		break;
-	default:
-		return (ENXIO);
+		return (PIC_PCIE_LINK3_IRQ);
 	}
+	return (-1);
+}
+
+static int
+xlr_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
+{
+	int i, link;
 
-	irqs[0] = pciirq;
 	/*
-	 * For now put in some fixed values for the other requested MSI,
-	 * TODO handle multiple messages
+	 * Each link has 32 MSIs that can be allocated, but for now
+	 * we only support one device per link.
+	 * msi_alloc() equivalent is needed when we start supporting 
+	 * bridges on the PCIe link.
 	 */
-	for (i = 1; i < count; i++)
-		irqs[i] = pciirq + 64 * i;
+	link = xls_pcie_link(pcib, dev);
+	if (link == -1)
+		return (ENXIO);
 
+	/*
+	 * encode the irq so that we know it is a MSI interrupt when we
+	 * setup interrupts
+	 */
+	for (i = 0; i < count; i++)
+		irqs[i] = 64 + link * 32 + i;
+
+	device_printf(dev, "Alloc MSI count %d maxcount %d irq %d link %d\n",
+			count, maxcount, i, link);
 	return (0);
 }
 
@@ -383,20 +409,18 @@ xlr_release_msi(device_t pcib, device_t dev, int count, int *irqs)
 }
 
 static int
-xlr_map_msi(device_t pcib, device_t dev, int irq, uint64_t * addr,
-    uint32_t * data)
+xlr_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
+    uint32_t *data)
 {
+	int msi;
 
-	switch (irq) {
-	case PIC_PCIE_LINK0_IRQ:
-	case PIC_PCIE_LINK1_IRQ:
-	case PIC_PCIE_LINK2_IRQ:
-	case PIC_PCIE_LINK3_IRQ:
+	device_printf(dev, "MAP MSI irq %d\n", irq);
+	if (irq >= 64) {
+		msi = irq - 64;
 		*addr = MIPS_MSI_ADDR(0);
-		*data = MIPS_MSI_DATA(irq);
+		*data = MIPS_MSI_DATA(msi);
 		return (0);
-
-	default:
+	} else {
 		device_printf(dev, "%s: map_msi for irq %d  - ignored", 
 		    device_get_nameunit(pcib), irq);
 		return (ENXIO);
@@ -437,10 +461,8 @@ bridge_pcie_ack(int irq)
 
 static int
 mips_platform_pci_setup_intr(device_t dev, device_t child,
-    struct resource *irq, int flags,
-    driver_filter_t * filt,
-    driver_intr_t * intr, void *arg,
-    void **cookiep)
+    struct resource *irq, int flags, driver_filter_t *filt,
+    driver_intr_t *intr, void *arg, void **cookiep)
 {
 	int error = 0;
 	int xlrirq;
@@ -454,6 +476,8 @@ mips_platform_pci_setup_intr(device_t dev, device_t child,
 		return (EINVAL);
 	}
 	xlrirq = rman_get_start(irq);
+	device_printf(dev, "%s: setup intr %d\n", device_get_nameunit(child),
+			xlrirq);
 
 	if (strcmp(device_get_name(dev), "pcib") != 0)
 		return (0);
@@ -463,6 +487,18 @@ mips_platform_pci_setup_intr(device_t dev, device_t child,
 		    intr, arg, PIC_PCIX_IRQ, flags, cookiep, bridge_pcix_ack);
 		pic_setup_intr(PIC_IRT_PCIX_INDEX, PIC_PCIX_IRQ, 0x1, 1);
 	} else {
+		/* 
+		 * temporary hack for MSI, we support just one device per
+		 * link, and assign the link interrupt to the device interrupt
+		 */
+		if (xlrirq >= 64) {
+			xlrirq -= 64;
+			if (xlrirq % 32 != 0)
+				return (0);
+			xlrirq = xls_pcie_link_irq(xlrirq / 32);
+			if (xlrirq == -1)
+				return (EINVAL);
+		}
 		xlr_establish_intr(device_get_name(child), filt,
 		    intr, arg, xlrirq, flags, cookiep, bridge_pcie_ack);
 		pic_setup_intr(xlrirq - PIC_IRQ_BASE, xlrirq, 0x1, 1);
@@ -492,6 +528,9 @@ xlr_pci_alloc_resource(device_t bus, device_t child, int type, int *rid,
 	vm_offset_t va;
 	int needactivate = flags & RF_ACTIVE;
 
+	device_printf(child, "Alloc res type %d, rid %d, start %lx, end %lx, count %lx flags %u\n",
+			type, *rid, start, end, count, flags);
+
 	switch (type) {
 	case SYS_RES_IRQ:
 		rm = &irq_rman;
@@ -559,28 +598,24 @@ xlr_pci_deactivate_resource(device_t bus, device_t child, int type, int rid,
 static int
 mips_pci_route_interrupt(device_t bus, device_t dev, int pin)
 {
+	int irq, link;
 
 	/*
 	 * Validate requested pin number.
 	 */
+	device_printf(dev, "route intr pin %d (bus %d, slot %d)\n",
+	    pin, pci_get_bus(dev), pci_get_slot(dev));
 	if ((pin < 1) || (pin > 4))
 		return (255);
 
 	if (xlr_board_info.is_xls) {
-		switch (pin) {
-		case 1:
-			return (PIC_PCIE_LINK0_IRQ);
-		case 2:
-			return (PIC_PCIE_LINK1_IRQ);
-		case 3:
-			return (PIC_PCIE_LINK2_IRQ);
-		case 4:
-			return (PIC_PCIE_LINK3_IRQ);
-		}
+		link = xls_pcie_link(bus, dev);
+		irq = xls_pcie_link_irq(link);
+		if (irq != -1)
+			return (irq);
 	} else {
-		if (pin == 1) {
-			return (16);
-		}
+		if (pin == 1)
+			return (PIC_PCIX_IRQ);
 	}
 
 	return (255);

From 27518391072e0275ca1a68b986c62a9224f90e94 Mon Sep 17 00:00:00 2001
From: Tijl Coosemans 
Date: Tue, 7 Sep 2010 08:33:17 +0000
Subject: [PATCH 0535/1624] GCC defines built-ins for atomic instructions found
 on i486 and higher. Because FreeBSD no longer supports the 80386 cpu all code
 targeting FreeBSD/i386 necessarily runs on i486 or higher so the compiler
 built-ins can be used by default inside libstdc++ and in C++ headers. This
 allows newly compiled C++ code to inline some atomic operations. Old binaries
 continue to use libstdc++ functions.

PR:		148926
Tested by:	Yuri Karaban 
Reviewed by:	kan
Approved by:	kib (mentor)
MFC after:	2 weeks
---
 gnu/lib/libstdc++/Makefile | 2 +-
 gnu/lib/libstdc++/config.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/gnu/lib/libstdc++/Makefile b/gnu/lib/libstdc++/Makefile
index e0a7bb214ed..56ca626710f 100644
--- a/gnu/lib/libstdc++/Makefile
+++ b/gnu/lib/libstdc++/Makefile
@@ -83,7 +83,7 @@ ATOMICITY_H=	${SRCDIR}/config/cpu/${MARCHDIR}/atomicity.h
 ATOMICITY_H=	${SRCDIR}/config/cpu/generic/atomicity_mutex/atomicity.h
 .endif
 
-.if ${MACHINE_CPUARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386"
 .if exists(${SRCDIR}/config/cpu/generic/atomicity_builtins/atomicity.h)
 ATOMICITY_H=	${SRCDIR}/config/cpu/generic/atomicity_builtins/atomicity.h
 .endif
diff --git a/gnu/lib/libstdc++/config.h b/gnu/lib/libstdc++/config.h
index de4641dfe6f..8bc099f1995 100644
--- a/gnu/lib/libstdc++/config.h
+++ b/gnu/lib/libstdc++/config.h
@@ -671,7 +671,7 @@
 /* #undef VERSION */
 
 /* Define if builtin atomic operations are supported on this host. */
-#if defined(__amd64__)
+#if defined(__amd64__) || defined(__i386__)
 #define _GLIBCXX_ATOMIC_BUILTINS 1
 #endif
 

From e83ea6241a26fe57f0a0203e4ce9c620ad0f21de Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Tue, 7 Sep 2010 13:50:02 +0000
Subject: [PATCH 0536/1624] Each processor socket in a QPI system has a special
 PCI bus for the "uncore" devices (such as the memory controller) in that
 socket.  Stop hardcoding support for two busses, but instead start probing
 buses at domain 0, bus 255 and walk down until a bus probe fails.  Also, do
 not probe a bus if it has already been enumerated elsewhere (e.g. if ACPI
 ever enumerates these buses in the future).

---
 sys/x86/pci/qpi.c | 58 ++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 45 insertions(+), 13 deletions(-)

diff --git a/sys/x86/pci/qpi.c b/sys/x86/pci/qpi.c
index 169c1cd6102..13151953019 100644
--- a/sys/x86/pci/qpi.c
+++ b/sys/x86/pci/qpi.c
@@ -47,6 +47,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 
+#include 
 #include 
 #include 
 #include "pcib_if.h"
@@ -84,31 +85,62 @@ qpi_probe(device_t dev)
 	return (BUS_PROBE_SPECIFIC);
 }
 
+/*
+ * Look for a PCI bus with the specified bus address.  If one is found,
+ * add a pcib device and return 0.  Otherwise, return an error code.
+ */
 static int
-qpi_attach(device_t dev)
+qpi_probe_pcib(device_t dev, int bus)
 {
 	struct qpi_device *qdev;
 	device_t child;
+	uint32_t devid;
 
 	/*
-	 * Add two Host-PCI bridge devices, one for PCI bus 254 and
-	 * one for PCI bus 255.
+	 * If a PCI bus already exists for this bus number, then
+	 * fail.
 	 */
-	child = BUS_ADD_CHILD(dev, 0, "pcib", -1);
-	if (child == NULL)
-		panic("%s: failed to add pci bus 254",
-		    device_get_nameunit(dev));
-	qdev = malloc(sizeof(struct qpi_device), M_QPI, M_WAITOK);
-	qdev->qd_pcibus = 254;
-	device_set_ivars(child, qdev);
+	if (pci_find_bsf(bus, 0, 0) != NULL)
+		return (EEXIST);
+
+	/*
+	 * Attempt to read the device id for device 0, function 0 on
+	 * the bus.  A value of 0xffffffff means that the bus is not
+	 * present.
+	 */
+	devid = pci_cfgregread(bus, 0, 0, PCIR_DEVVENDOR, 4);
+	if (devid == 0xffffffff)
+		return (ENOENT);
+
+	if ((devid & 0xffff) != 0x8086) {
+		device_printf(dev,
+		    "Device at pci%d.0.0 has non-Intel vendor 0x%x\n", bus,
+		    devid & 0xffff);
+		return (ENXIO);
+	}
 
 	child = BUS_ADD_CHILD(dev, 0, "pcib", -1);
 	if (child == NULL)
-		panic("%s: failed to add pci bus 255",
-		    device_get_nameunit(dev));
+		panic("%s: failed to add pci bus %d", device_get_nameunit(dev),
+		    bus);
 	qdev = malloc(sizeof(struct qpi_device), M_QPI, M_WAITOK);
-	qdev->qd_pcibus = 255;
+	qdev->qd_pcibus = bus;
 	device_set_ivars(child, qdev);
+	return (0);
+}
+
+static int
+qpi_attach(device_t dev)
+{
+	int bus;
+
+	/*
+	 * Each processor socket has a dedicated PCI bus counting down from
+	 * 255.  We keep probing buses until one fails.
+	 */
+	for (bus = 255;; bus--)
+		if (qpi_probe_pcib(dev, bus) != 0)
+			break;
 
 	return (bus_generic_attach(dev));
 }

From 8e27c1828261b759e0912c9b6011a5ee056e3d4d Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Tue, 7 Sep 2010 14:29:45 +0000
Subject: [PATCH 0537/1624] Store the full timestamp when caching timestamps of
 files and directories for purposes of validating name cache entries.  This
 closes races where two updates to a file or directory within the same second
 could result in stale entries in the name cache.  While here, remove the
 'n_expiry' field as it is no longer used.

Reviewed by:	rmacklem
MFC after:	1 week
---
 sys/fs/nfsclient/nfs_clrpcops.c |  3 +--
 sys/fs/nfsclient/nfs_clvnops.c  | 16 ++++++++--------
 sys/fs/nfsclient/nfsnode.h      |  5 ++---
 sys/nfsclient/nfs_vnops.c       | 23 +++++++++++++----------
 sys/nfsclient/nfsnode.h         |  5 ++---
 5 files changed, 26 insertions(+), 26 deletions(-)

diff --git a/sys/fs/nfsclient/nfs_clrpcops.c b/sys/fs/nfsclient/nfs_clrpcops.c
index 89fd0a28511..2512ad4869b 100644
--- a/sys/fs/nfsclient/nfs_clrpcops.c
+++ b/sys/fs/nfsclient/nfs_clrpcops.c
@@ -3293,8 +3293,7 @@ nfsrpc_readdirplus(vnode_t vp, struct uio *uiop, nfsuint64 *cookiep,
 				    ndp->ni_vp = newvp;
 				    NFSCNHASH(cnp, HASHINIT);
 				    if (cnp->cn_namelen <= NCHNAMLEN) {
-					np->n_ctime =
-					  np->n_vattr.na_ctime.tv_sec;
+					np->n_ctime = np->n_vattr.na_ctime;
 					cache_enter(ndp->ni_dvp,ndp->ni_vp,cnp);
 				    }
 				    if (unlocknewvp)
diff --git a/sys/fs/nfsclient/nfs_clvnops.c b/sys/fs/nfsclient/nfs_clvnops.c
index 289c6864735..1e4e8a67e0d 100644
--- a/sys/fs/nfsclient/nfs_clvnops.c
+++ b/sys/fs/nfsclient/nfs_clvnops.c
@@ -988,7 +988,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 	struct nfsfh *nfhp;
 	struct nfsvattr dnfsva, nfsva;
 	struct vattr vattr;
-	time_t dmtime;
+	struct timespec dmtime;
 	
 	*vpp = NULLVP;
 	if ((flags & ISLASTCN) && (mp->mnt_flag & MNT_RDONLY) &&
@@ -1038,7 +1038,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 		}
 		if (nfscl_nodeleg(newvp, 0) == 0 ||
 		    (VOP_GETATTR(newvp, &vattr, cnp->cn_cred) == 0 &&
-		    vattr.va_ctime.tv_sec == newnp->n_ctime)) {
+		    timespeccmp(&vattr.va_ctime, &newnp->n_ctime, ==))) {
 			NFSINCRGLOBAL(newnfsstats.lookupcache_hits);
 			if (cnp->cn_nameiop != LOOKUP &&
 			    (flags & ISLASTCN))
@@ -1065,13 +1065,13 @@ nfs_lookup(struct vop_lookup_args *ap)
 		if ((u_int)(ticks - np->n_dmtime_ticks) <
 		    (nmp->nm_negnametimeo * hz) &&
 		    VOP_GETATTR(dvp, &vattr, cnp->cn_cred) == 0 &&
-		    vattr.va_mtime.tv_sec == np->n_dmtime) {
+		    timespeccmp(&vattr.va_mtime, &np->n_dmtime, ==)) {
 			NFSINCRGLOBAL(newnfsstats.lookupcache_hits);
 			return (ENOENT);
 		}
 		cache_purge_negative(dvp);
 		mtx_lock(&np->n_mtx);
-		np->n_dmtime = 0;
+		timespecclear(&np->n_dmtime);
 		mtx_unlock(&np->n_mtx);
 	}
 
@@ -1086,7 +1086,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 	 * the lookup RPC has been performed on the server but before
 	 * n_dmtime is set at the end of this function.
 	 */
-	dmtime = np->n_vattr.na_mtime.tv_sec;
+	dmtime = np->n_vattr.na_mtime;
 	error = 0;
 	newvp = NULLVP;
 	NFSINCRGLOBAL(newnfsstats.lookupcache_misses);
@@ -1139,8 +1139,8 @@ nfs_lookup(struct vop_lookup_args *ap)
 			 * lookup.
 			 */
 			mtx_lock(&np->n_mtx);
-			if (np->n_dmtime <= dmtime) {
-				if (np->n_dmtime == 0) {
+			if (timespeccmp(&np->n_dmtime, &dmtime, <=)) {
+				if (!timespecisset(&np->n_dmtime)) {
 					np->n_dmtime = dmtime;
 					np->n_dmtime_ticks = ticks;
 				}
@@ -1241,7 +1241,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 		cnp->cn_flags |= SAVENAME;
 	if ((cnp->cn_flags & MAKEENTRY) &&
 	    (cnp->cn_nameiop != DELETE || !(flags & ISLASTCN))) {
-		np->n_ctime = np->n_vattr.na_vattr.va_ctime.tv_sec;
+		np->n_ctime = np->n_vattr.na_vattr.va_ctime;
 		cache_enter(dvp, newvp, cnp);
 	}
 	*vpp = newvp;
diff --git a/sys/fs/nfsclient/nfsnode.h b/sys/fs/nfsclient/nfsnode.h
index 8bbb3bc9825..204b20cd33a 100644
--- a/sys/fs/nfsclient/nfsnode.h
+++ b/sys/fs/nfsclient/nfsnode.h
@@ -96,10 +96,9 @@ struct nfsnode {
 	time_t			n_attrstamp;	/* Attr. cache timestamp */
 	struct nfs_accesscache	n_accesscache[NFS_ACCESSCACHESIZE];
 	struct timespec		n_mtime;	/* Prev modify time. */
-	time_t			n_ctime;	/* Prev create time. */
-	time_t			n_dmtime;	/* Prev dir modify time. */
+	struct timespec		n_ctime;	/* Prev create time. */
+	struct timespec		n_dmtime;	/* Prev dir modify time. */
 	int			n_dmtime_ticks;	/* Tick of -ve cache entry */
-	time_t			n_expiry;	/* Lease expiry time */
 	struct nfsfh		*n_fhp;		/* NFS File Handle */
 	struct vnode		*n_vnode;	/* associated vnode */
 	struct vnode		*n_dvp;		/* parent vnode */
diff --git a/sys/nfsclient/nfs_vnops.c b/sys/nfsclient/nfs_vnops.c
index f1e173d178d..828a739a20e 100644
--- a/sys/nfsclient/nfs_vnops.c
+++ b/sys/nfsclient/nfs_vnops.c
@@ -916,7 +916,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 	struct vnode **vpp = ap->a_vpp;
 	struct mount *mp = dvp->v_mount;
 	struct vattr vattr;
-	time_t dmtime;
+	struct timespec dmtime;
 	int flags = cnp->cn_flags;
 	struct vnode *newvp;
 	struct nfsmount *nmp;
@@ -970,7 +970,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 			mtx_unlock(&newnp->n_mtx);
 		}
 		if (VOP_GETATTR(newvp, &vattr, cnp->cn_cred) == 0 &&
-		    vattr.va_ctime.tv_sec == newnp->n_ctime) {
+		    timespeccmp(&vattr.va_ctime, &newnp->n_ctime, ==)) {
 			nfsstats.lookupcache_hits++;
 			if (cnp->cn_nameiop != LOOKUP &&
 			    (flags & ISLASTCN))
@@ -997,13 +997,13 @@ nfs_lookup(struct vop_lookup_args *ap)
 		if ((u_int)(ticks - np->n_dmtime_ticks) <
 		    (nmp->nm_negnametimeo * hz) &&
 		    VOP_GETATTR(dvp, &vattr, cnp->cn_cred) == 0 &&
-		    vattr.va_mtime.tv_sec == np->n_dmtime) {
+		    timespeccmp(&vattr.va_mtime, &np->n_dmtime, ==)) {
 			nfsstats.lookupcache_hits++;
 			return (ENOENT);
 		}
 		cache_purge_negative(dvp);
 		mtx_lock(&np->n_mtx);
-		np->n_dmtime = 0;
+		timespecclear(&np->n_dmtime);
 		mtx_unlock(&np->n_mtx);
 	}
 
@@ -1018,7 +1018,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 	 * the lookup RPC has been performed on the server but before
 	 * n_dmtime is set at the end of this function.
 	 */
-	dmtime = np->n_vattr.va_mtime.tv_sec;
+	dmtime = np->n_vattr.va_mtime;
 	error = 0;
 	newvp = NULLVP;
 	nfsstats.lookupcache_misses++;
@@ -1137,7 +1137,7 @@ nfs_lookup(struct vop_lookup_args *ap)
 		cnp->cn_flags |= SAVENAME;
 	if ((cnp->cn_flags & MAKEENTRY) &&
 	    (cnp->cn_nameiop != DELETE || !(flags & ISLASTCN))) {
-		np->n_ctime = np->n_vattr.va_ctime.tv_sec;
+		np->n_ctime = np->n_vattr.va_ctime;
 		cache_enter(dvp, newvp, cnp);
 	}
 	*vpp = newvp;
@@ -1183,8 +1183,8 @@ nfsmout:
 			 * lookup.
 			 */
 			mtx_lock(&np->n_mtx);
-			if (np->n_dmtime <= dmtime) {
-				if (np->n_dmtime == 0) {
+			if (timespeccmp(&np->n_dmtime, &dmtime, <=)) {
+				if (!timespecisset(&np->n_dmtime)) {
 					np->n_dmtime = dmtime;
 					np->n_dmtime_ticks = ticks;
 				}
@@ -2657,8 +2657,11 @@ nfs_readdirplusrpc(struct vnode *vp, struct uio *uiop, struct ucred *cred)
 				dp->d_type =
 				    IFTODT(VTTOIF(np->n_vattr.va_type));
 				ndp->ni_vp = newvp;
-				/* Update n_ctime, so subsequent lookup doesn't purge entry */
-				np->n_ctime = np->n_vattr.va_ctime.tv_sec;
+				/*
+				 * Update n_ctime so subsequent lookup
+				 * doesn't purge entry.
+				 */
+				np->n_ctime = np->n_vattr.va_ctime;
 			        cache_enter(ndp->ni_dvp, ndp->ni_vp, cnp);
 			    }
 			} else {
diff --git a/sys/nfsclient/nfsnode.h b/sys/nfsclient/nfsnode.h
index a7adeae05ff..52546891a06 100644
--- a/sys/nfsclient/nfsnode.h
+++ b/sys/nfsclient/nfsnode.h
@@ -102,10 +102,9 @@ struct nfsnode {
 	time_t			n_attrstamp;	/* Attr. cache timestamp */
 	struct nfs_accesscache	n_accesscache[NFS_ACCESSCACHESIZE];
 	struct timespec		n_mtime;	/* Prev modify time. */
-	time_t			n_ctime;	/* Prev create time. */
-	time_t			n_dmtime;	/* Prev dir modify time. */
+	struct timespec		n_ctime;	/* Prev create time. */
+	struct timespec		n_dmtime;	/* Prev dir modify time. */
 	int			n_dmtime_ticks;	/* Tick of -ve cache entry */
-	time_t			n_expiry;	/* Lease expiry time */
 	nfsfh_t			*n_fhp;		/* NFS File Handle */
 	struct vnode		*n_vnode;	/* associated vnode */
 	struct vnode		*n_dvp;		/* parent vnode */

From 33e98ade5355f13b299d23ca8bced5ab865e6f4d Mon Sep 17 00:00:00 2001
From: Maksim Yevmenkin 
Date: Tue, 7 Sep 2010 16:36:03 +0000
Subject: [PATCH 0538/1624] Do not request SDP attributes using ranges.
 Apparently some devices do not like it.

MFC after:	1 week
Tested by:	Buganini < buganini at gmail dot com >
---
 usr.sbin/bluetooth/bthidcontrol/sdp.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/usr.sbin/bluetooth/bthidcontrol/sdp.c b/usr.sbin/bluetooth/bthidcontrol/sdp.c
index 032863edb2a..a0b4534e4ca 100644
--- a/usr.sbin/bluetooth/bthidcontrol/sdp.c
+++ b/usr.sbin/bluetooth/bthidcontrol/sdp.c
@@ -54,7 +54,9 @@ SDP_ATTR_RANGE(	SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST,
 SDP_ATTR_RANGE	(SDP_ATTR_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS,
 		SDP_ATTR_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS),
 SDP_ATTR_RANGE(	0x0205,		/* HIDReconnectInitiate */
-		0x0206),	/* HIDDescriptorList */
+		0x0205),
+SDP_ATTR_RANGE(	0x0206,		/* HIDDescriptorList */
+		0x0206),
 SDP_ATTR_RANGE(	0x0209,		/* HIDBatteryPower */
 		0x0209),
 SDP_ATTR_RANGE(	0x020d,		/* HIDNormallyConnectable */
@@ -149,7 +151,7 @@ hid_sdp_query(bdaddr_t const *local, struct hid_device *hd, int32_t *error)
 	}
 
 	if (control_psm == -1 || interrupt_psm == -1 ||
-	    reconnect_initiate == -1 || normally_connectable == -1 ||
+	    reconnect_initiate == -1 ||
 	    hid_descriptor == NULL || hid_descriptor_length == -1)
 		hid_sdp_query_exit(ENOATTR);
 

From 12c65daeaf7a1811cd5b11cf594386695d78d712 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 7 Sep 2010 18:29:29 +0000
Subject: [PATCH 0539/1624] Make sure to create DMA'able memory for statistics
 block. This was missed in r212061 and it caused crashes for 570x controllers
 as controller DMAed statistics to physical address 0.

Reported by:	kan
---
 sys/dev/bge/if_bge.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c
index 30ccf22c43d..aff148ff0e3 100644
--- a/sys/dev/bge/if_bge.c
+++ b/sys/dev/bge/if_bge.c
@@ -2258,6 +2258,15 @@ bge_dma_alloc(struct bge_softc *sc)
 	if (error)
 		return (error);
 
+	/* Create tag for statistics block. */
+	error = bge_dma_ring_alloc(sc, PAGE_SIZE, BGE_STATS_SZ,
+	    &sc->bge_cdata.bge_stats_tag,
+	    (uint8_t **)&sc->bge_ldata.bge_stats,
+	    &sc->bge_cdata.bge_stats_map,
+	    &sc->bge_ldata.bge_stats_paddr, "statistics block");
+	if (error)
+		return (error);
+
 	/* Create tag for jumbo RX ring. */
 	if (BGE_IS_JUMBO_CAPABLE(sc)) {
 		error = bge_dma_ring_alloc(sc, PAGE_SIZE, BGE_JUMBO_RX_RING_SZ,

From d9f1a5aa8ed48a7b829430535811a23f126981c8 Mon Sep 17 00:00:00 2001
From: Jack F Vogel 
Date: Tue, 7 Sep 2010 20:13:08 +0000
Subject: [PATCH 0540/1624] Tighten up the rx mbuf refresh code, there were
 some discrepencies from the igb version which was the target.

Change the message when neither MSI or MSIX are enabled
and a fallback to Legacy interrupts happen, the existing
message was confusing.
---
 sys/dev/e1000/if_em.c | 112 +++++++++++++++++++++++-------------------
 sys/dev/e1000/if_em.h |   4 +-
 2 files changed, 65 insertions(+), 51 deletions(-)

diff --git a/sys/dev/e1000/if_em.c b/sys/dev/e1000/if_em.c
index e5dfa36416a..9c5a609b883 100644
--- a/sys/dev/e1000/if_em.c
+++ b/sys/dev/e1000/if_em.c
@@ -93,7 +93,7 @@ int	em_display_debug_stats = 0;
 /*********************************************************************
  *  Driver version:
  *********************************************************************/
-char em_driver_version[] = "7.0.5";
+char em_driver_version[] = "7.0.6";
 
 
 /*********************************************************************
@@ -281,6 +281,8 @@ static void	em_handle_link(void *context, int pending);
 static void	em_add_rx_process_limit(struct adapter *, const char *,
 		    const char *, int *, int);
 
+static __inline void em_rx_discard(struct rx_ring *, int);
+
 #ifdef DEVICE_POLLING
 static poll_handler_t em_poll;
 #endif /* POLLING */
@@ -2563,11 +2565,11 @@ msi:
        	val = pci_msi_count(dev);
        	if (val == 1 && pci_alloc_msi(dev, &val) == 0) {
                	adapter->msix = 1;
-               	device_printf(adapter->dev,"Using MSI interrupt\n");
+               	device_printf(adapter->dev,"Using an MSI interrupt\n");
 		return (val);
 	} 
-	/* Should only happen due to manual invention */
-	device_printf(adapter->dev,"Setup MSIX failure\n");
+	/* Should only happen due to manual configuration */
+	device_printf(adapter->dev,"No MSI/MSIX using a Legacy IRQ\n");
 	return (0);
 }
 
@@ -3681,14 +3683,27 @@ em_refresh_mbufs(struct rx_ring *rxr, int limit)
 	struct adapter		*adapter = rxr->adapter;
 	struct mbuf		*m;
 	bus_dma_segment_t	segs[1];
-	bus_dmamap_t		map;
 	struct em_buffer	*rxbuf;
 	int			i, error, nsegs, cleaned;
 
 	i = rxr->next_to_refresh;
 	cleaned = -1;
 	while (i != limit) {
+		rxbuf = &rxr->rx_buffers[i];
+		/*
+		** Just skip entries with a buffer,
+		** they can only be due to an error
+		** and are to be reused.
+		*/
+		if (rxbuf->m_head != NULL)
+			continue;
 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
+		/*
+		** If we have a temporary resource shortage
+		** that causes a failure, just abort refresh
+		** for now, we will return to this point when
+		** reinvoked from em_rxeof.
+		*/
 		if (m == NULL)
 			goto update;
 		m->m_len = m->m_pkthdr.len = MCLBYTES;
@@ -3696,11 +3711,8 @@ em_refresh_mbufs(struct rx_ring *rxr, int limit)
 		if (adapter->max_frame_size <= (MCLBYTES - ETHER_ALIGN))
 			m_adj(m, ETHER_ALIGN);
 
-		/*
-		 * Using memory from the mbuf cluster pool, invoke the
-		 * bus_dma machinery to arrange the memory mapping.
-		 */
-		error = bus_dmamap_load_mbuf_sg(rxr->rxtag, rxr->rx_sparemap,
+		/* Use bus_dma machinery to setup the memory mapping  */
+		error = bus_dmamap_load_mbuf_sg(rxr->rxtag, rxbuf->map,
 		    m, segs, &nsegs, BUS_DMA_NOWAIT);
 		if (error != 0) {
 			m_free(m);
@@ -3710,13 +3722,6 @@ em_refresh_mbufs(struct rx_ring *rxr, int limit)
 		/* If nsegs is wrong then the stack is corrupt. */
 		KASSERT(nsegs == 1, ("Too many segments returned!"));
 	
-		rxbuf = &rxr->rx_buffers[i];
-		if (rxbuf->m_head != NULL)
-			bus_dmamap_unload(rxr->rxtag, rxbuf->map);
-	
-		map = rxbuf->map;
-		rxbuf->map = rxr->rx_sparemap;
-		rxr->rx_sparemap = map;
 		bus_dmamap_sync(rxr->rxtag,
 		    rxbuf->map, BUS_DMASYNC_PREREAD);
 		rxbuf->m_head = m;
@@ -3730,8 +3735,10 @@ em_refresh_mbufs(struct rx_ring *rxr, int limit)
 		rxr->next_to_refresh = i;
 	}
 update:
-	bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
-	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+	/*
+	** Update the tail pointer only if,
+	** and as far as we have refreshed.
+	*/
 	if (cleaned != -1) /* Update tail index */
 		E1000_WRITE_REG(&adapter->hw,
 		    E1000_RDT(rxr->me), cleaned);
@@ -3781,15 +3788,6 @@ em_allocate_receive_buffers(struct rx_ring *rxr)
 		goto fail;
 	}
 
-	/* Create the spare map (used by getbuf) */
-	error = bus_dmamap_create(rxr->rxtag, BUS_DMA_NOWAIT,
-	     &rxr->rx_sparemap);
-	if (error) {
-		device_printf(dev, "%s: bus_dmamap_create failed: %d\n",
-		    __func__, error);
-		goto fail;
-	}
-
 	rxbuf = rxr->rx_buffers;
 	for (int i = 0; i < adapter->num_rx_desc; i++, rxbuf++) {
 		rxbuf = &rxr->rx_buffers[i];
@@ -3956,11 +3954,6 @@ em_free_receive_buffers(struct rx_ring *rxr)
 
 	INIT_DEBUGOUT("free_receive_buffers: begin");
 
-	if (rxr->rx_sparemap) {
-		bus_dmamap_destroy(rxr->rxtag, rxr->rx_sparemap);
-		rxr->rx_sparemap = NULL;
-	}
-
 	if (rxr->rx_buffers != NULL) {
 		for (int i = 0; i < adapter->num_rx_desc; i++) {
 			rxbuf = &rxr->rx_buffers[i];
@@ -4132,12 +4125,16 @@ em_rxeof(struct rx_ring *rxr, int count, int *done)
 		eop = (status & E1000_RXD_STAT_EOP) != 0;
 		count--;
 
-		if ((cur->errors & E1000_RXD_ERR_FRAME_ERR_MASK) == 0) {
+		if (((cur->errors & E1000_RXD_ERR_FRAME_ERR_MASK) == 0) &&
+		    (rxr->discard == FALSE)) {
 
 			/* Assign correct length to the current fragment */
 			mp = rxr->rx_buffers[i].m_head;
 			mp->m_len = len;
 
+			/* Trigger for refresh */
+			rxr->rx_buffers[i].m_head = NULL;
+
 			if (rxr->fmp == NULL) {
 				mp->m_pkthdr.len = len;
 				rxr->fmp = mp; /* Store the first mbuf */
@@ -4179,19 +4176,12 @@ skip:
 			}
 		} else {
 			ifp->if_ierrors++;
-			/* Reuse loaded DMA map and just update mbuf chain */
-			mp = rxr->rx_buffers[i].m_head;
-			mp->m_len = mp->m_pkthdr.len = MCLBYTES;
-			mp->m_data = mp->m_ext.ext_buf;
-			mp->m_next = NULL;
-			if (adapter->max_frame_size <=
-			    (MCLBYTES - ETHER_ALIGN))
-				m_adj(mp, ETHER_ALIGN);
-			if (rxr->fmp != NULL) {
-				m_freem(rxr->fmp);
-				rxr->fmp = NULL;
-				rxr->lmp = NULL;
-			}
+			++rxr->rx_discarded;
+			if (!eop) /* Catch subsequent segs */
+				rxr->discard = TRUE;
+			else
+				rxr->discard = FALSE;
+			em_rx_discard(rxr, i);
 			sendmp = NULL;
 		}
 
@@ -4234,6 +4224,31 @@ skip:
 	return ((status & E1000_RXD_STAT_DD) ? TRUE : FALSE);
 }
 
+static __inline void
+em_rx_discard(struct rx_ring *rxr, int i)
+{
+	struct em_buffer	*rbuf;
+	struct mbuf		*m;
+
+	rbuf = &rxr->rx_buffers[i];
+	/* Free any previous pieces */
+	if (rxr->fmp != NULL) {
+		rxr->fmp->m_flags |= M_PKTHDR;
+		m_freem(rxr->fmp);
+		rxr->fmp = NULL;
+		rxr->lmp = NULL;
+	}
+                         
+	/* Reset state, keep loaded DMA map and reuse */
+	m = rbuf->m_head;
+	m->m_len = m->m_pkthdr.len = MCLBYTES;
+	m->m_flags |= M_PKTHDR;
+	m->m_data = m->m_ext.ext_buf;
+	m->m_next = NULL;
+
+	return;
+}
+
 #ifndef __NO_STRICT_ALIGNMENT
 /*
  * When jumbo frames are enabled we should realign entire payload on
@@ -5159,8 +5174,6 @@ em_add_hw_stats(struct adapter *adapter)
 			CTLFLAG_RD, &adapter->stats.hrmpc,
 			"Header Redirection Missed Packet Count");
 
-
-
 }
 
 /**********************************************************************
@@ -5170,7 +5183,6 @@ em_add_hw_stats(struct adapter *adapter)
  *  32 words, stuff that matters is in that extent.
  *
  **********************************************************************/
-
 static int
 em_sysctl_nvm_info(SYSCTL_HANDLER_ARGS)
 {
diff --git a/sys/dev/e1000/if_em.h b/sys/dev/e1000/if_em.h
index d164edb1859..229cc0cc392 100644
--- a/sys/dev/e1000/if_em.h
+++ b/sys/dev/e1000/if_em.h
@@ -320,10 +320,11 @@ struct rx_ring {
         void                    *tag;
         struct resource         *res;
         bus_dma_tag_t           rxtag;
-        bus_dmamap_t            rx_sparemap;
+	bool			discard;
 
         /* Soft stats */
         unsigned long		rx_irq;
+        unsigned long		rx_discarded;
         unsigned long		rx_packets;
         unsigned long		rx_bytes;
 };
@@ -393,6 +394,7 @@ struct adapter {
 
 	/* Multicast array memory */
 	u8		*mta;
+
 	/* Info about the board itself */
 	uint8_t		link_active;
 	uint16_t	link_speed;

From 26c88ee828315ae8da190607ee0f7d351d2a2c28 Mon Sep 17 00:00:00 2001
From: Jack F Vogel 
Date: Tue, 7 Sep 2010 21:28:45 +0000
Subject: [PATCH 0541/1624] Code correction in refresh_mbufs, just continuing
 without index recalc was wrong.

---
 sys/dev/e1000/if_em.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/e1000/if_em.c b/sys/dev/e1000/if_em.c
index 9c5a609b883..397a7e6063c 100644
--- a/sys/dev/e1000/if_em.c
+++ b/sys/dev/e1000/if_em.c
@@ -3696,7 +3696,7 @@ em_refresh_mbufs(struct rx_ring *rxr, int limit)
 		** and are to be reused.
 		*/
 		if (rxbuf->m_head != NULL)
-			continue;
+			goto reuse;
 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
 		/*
 		** If we have a temporary resource shortage
@@ -3726,7 +3726,7 @@ em_refresh_mbufs(struct rx_ring *rxr, int limit)
 		    rxbuf->map, BUS_DMASYNC_PREREAD);
 		rxbuf->m_head = m;
 		rxr->rx_base[i].buffer_addr = htole64(segs[0].ds_addr);
-
+reuse:
 		cleaned = i;
 		/* Calculate next index */
 		if (++i == adapter->num_rx_desc)

From b2143ecb990ffca009e99a125e9cd09c9fece1da Mon Sep 17 00:00:00 2001
From: Ivan Voras 
Date: Tue, 7 Sep 2010 22:40:45 +0000
Subject: [PATCH 0542/1624] Avoid "Entry can disappear before we lock fdvp"
 panic.

PR:		150143
Submitted by:	Gleb Kurtsou 
Pretty sure it won't blow up: mckusick
MFC after:	2 weeks
---
 sys/fs/tmpfs/tmpfs_vnops.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/sys/fs/tmpfs/tmpfs_vnops.c b/sys/fs/tmpfs/tmpfs_vnops.c
index 295d2ca3ee7..d3f1ff569c7 100644
--- a/sys/fs/tmpfs/tmpfs_vnops.c
+++ b/sys/fs/tmpfs/tmpfs_vnops.c
@@ -981,10 +981,14 @@ tmpfs_rename(struct vop_rename_args *v)
 	fnode = VP_TO_TMPFS_NODE(fvp);
 	de = tmpfs_dir_lookup(fdnode, fnode, fcnp);
 
-	/* Avoid manipulating '.' and '..' entries. */
+	/* Entry can disappear before we lock fdvp,
+	 * also avoid manipulating '.' and '..' entries. */
 	if (de == NULL) {
-		MPASS(fvp->v_type == VDIR);
-		error = EINVAL;
+		if ((fcnp->cn_flags & ISDOTDOT) != 0 ||
+		    (fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.'))
+			error = EINVAL;
+		else
+			error = ENOENT;
 		goto out_locked;
 	}
 	MPASS(de->td_node == fnode);

From beab55bfc5ec3e33f3083830985d5cfd55c5b223 Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 7 Sep 2010 22:44:29 +0000
Subject: [PATCH 0543/1624] Remove trailing CR at EOL.

---
 sys/dev/mii/brgphyreg.h | 164 ++++++++++++++++++++--------------------
 1 file changed, 82 insertions(+), 82 deletions(-)

diff --git a/sys/dev/mii/brgphyreg.h b/sys/dev/mii/brgphyreg.h
index 883269e2f66..df3e756925b 100644
--- a/sys/dev/mii/brgphyreg.h
+++ b/sys/dev/mii/brgphyreg.h
@@ -262,103 +262,103 @@
 #define	BRGPHY_IMR_LNK_CHG	0x0002	/* Link status change */
 #define	BRGPHY_IMR_CRCERR	0x0001	/* CRC error */
 
-/*******************************************************/
-/* Begin: Shared SerDes PHY register definitions       */
-/*******************************************************/
-
-/* SerDes autoneg is different from copper */
-#define BRGPHY_SERDES_ANAR				0x04
-#define BRGPHY_SERDES_ANAR_FDX			0x0020
-#define BRGPHY_SERDES_ANAR_HDX			0x0040
-#define BRGPHY_SERDES_ANAR_NO_PAUSE		(0x0 << 7)
-#define BRGPHY_SERDES_ANAR_SYM_PAUSE	(0x1 << 7)
-#define BRGPHY_SERDES_ANAR_ASYM_PAUSE	(0x2 << 7)
-#define BRGPHY_SERDES_ANAR_BOTH_PAUSE	(0x3 << 7)
-
-#define BRGPHY_SERDES_ANLPAR			0x05
-#define BRGPHY_SERDES_ANLPAR_FDX		0x0020
-#define BRGPHY_SERDES_ANLPAR_HDX		0x0040
-#define BRGPHY_SERDES_ANLPAR_NO_PAUSE	(0x0 << 7)
-#define BRGPHY_SERDES_ANLPAR_SYM_PAUSE	(0x1 << 7)
-#define BRGPHY_SERDES_ANLPAR_ASYM_PAUSE	(0x2 << 7)
-#define BRGPHY_SERDES_ANLPAR_BOTH_PAUSE	(0x3 << 7)
-
-/*******************************************************/
-/* End: Shared SerDes PHY register definitions         */
-/*******************************************************/
-
-/*******************************************************/
-/* Begin: PHY register values for the 5706 PHY         */
-/*******************************************************/
-
-/* 
- * Shadow register 0x1C, bit 15 is write enable,
- * bits 14-10 select function (0x00 to 0x1F).
- */
-#define BRGPHY_MII_SHADOW_1C			0x1C
+/*******************************************************/
+/* Begin: Shared SerDes PHY register definitions       */
+/*******************************************************/
+
+/* SerDes autoneg is different from copper */
+#define BRGPHY_SERDES_ANAR				0x04
+#define BRGPHY_SERDES_ANAR_FDX			0x0020
+#define BRGPHY_SERDES_ANAR_HDX			0x0040
+#define BRGPHY_SERDES_ANAR_NO_PAUSE		(0x0 << 7)
+#define BRGPHY_SERDES_ANAR_SYM_PAUSE	(0x1 << 7)
+#define BRGPHY_SERDES_ANAR_ASYM_PAUSE	(0x2 << 7)
+#define BRGPHY_SERDES_ANAR_BOTH_PAUSE	(0x3 << 7)
+
+#define BRGPHY_SERDES_ANLPAR			0x05
+#define BRGPHY_SERDES_ANLPAR_FDX		0x0020
+#define BRGPHY_SERDES_ANLPAR_HDX		0x0040
+#define BRGPHY_SERDES_ANLPAR_NO_PAUSE	(0x0 << 7)
+#define BRGPHY_SERDES_ANLPAR_SYM_PAUSE	(0x1 << 7)
+#define BRGPHY_SERDES_ANLPAR_ASYM_PAUSE	(0x2 << 7)
+#define BRGPHY_SERDES_ANLPAR_BOTH_PAUSE	(0x3 << 7)
+
+/*******************************************************/
+/* End: Shared SerDes PHY register definitions         */
+/*******************************************************/
+
+/*******************************************************/
+/* Begin: PHY register values for the 5706 PHY         */
+/*******************************************************/
+
+/* 
+ * Shadow register 0x1C, bit 15 is write enable,
+ * bits 14-10 select function (0x00 to 0x1F).
+ */
+#define BRGPHY_MII_SHADOW_1C			0x1C
 #define BRGPHY_SHADOW_1C_WRITE_EN		0x8000
 #define BRGPHY_SHADOW_1C_SELECT_MASK	0x7C00
-
+
 /* Shadow 0x1C Mode Control Register (select value 0x1F) */
 #define BRGPHY_SHADOW_1C_MODE_CTRL		(0x1F << 10)
 /* When set, Regs 0-0x0F are 1000X, else 1000T */
-#define BRGPHY_SHADOW_1C_ENA_1000X		0x0001	
+#define BRGPHY_SHADOW_1C_ENA_1000X		0x0001	
 
 #define	BRGPHY_MII_TEST1	0x1E
 #define	BRGPHY_TEST1_TRIM_EN	0x0010
 #define	BRGPHY_TEST1_CRC_EN	0x8000
 
 #define BRGPHY_MII_TEST2		0x1F
-
-/*******************************************************/
-/* End: PHY register values for the 5706 PHY           */
-/*******************************************************/
-
-/*******************************************************/
-/* Begin: PHY register values for the 5708S SerDes PHY */
-/*******************************************************/
-
-/* Autoneg Next Page Transmit 1 Regiser */
-#define BRGPHY_5708S_ANEG_NXT_PG_XMIT1			0x0B
-#define BRGPHY_5708S_ANEG_NXT_PG_XMIT1_25G		0x0001
-
-/* Use the BLOCK_ADDR register to select the page for registers 0x10 to 0x1E */
-#define BRGPHY_5708S_BLOCK_ADDR					0x1f
+
+/*******************************************************/
+/* End: PHY register values for the 5706 PHY           */
+/*******************************************************/
+
+/*******************************************************/
+/* Begin: PHY register values for the 5708S SerDes PHY */
+/*******************************************************/
+
+/* Autoneg Next Page Transmit 1 Regiser */
+#define BRGPHY_5708S_ANEG_NXT_PG_XMIT1			0x0B
+#define BRGPHY_5708S_ANEG_NXT_PG_XMIT1_25G		0x0001
+
+/* Use the BLOCK_ADDR register to select the page for registers 0x10 to 0x1E */
+#define BRGPHY_5708S_BLOCK_ADDR					0x1f
 #define BRGPHY_5708S_DIG_PG0 					0x0000
 #define BRGPHY_5708S_DIG3_PG2					0x0002
 #define BRGPHY_5708S_TX_MISC_PG5				0x0005
-
-/* 5708S SerDes "Digital" Registers (page 0) */
-#define BRGPHY_5708S_PG0_1000X_CTL1				0x10
-#define BRGPHY_5708S_PG0_1000X_CTL1_AUTODET_EN	0x0010
-#define BRGPHY_5708S_PG0_1000X_CTL1_FIBER_MODE	0x0001
-
-#define BRGPHY_5708S_PG0_1000X_STAT1			0x14
-#define BRGPHY_5708S_PG0_1000X_STAT1_LINK		0x0002
-#define BRGPHY_5708S_PG0_1000X_STAT1_FDX		0x0004
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_MASK	0x0018
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_10	(0x0 << 3)
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_100	(0x1 << 3)
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_1G	(0x2 << 3)
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_25G	(0x3 << 3)
-
-
-#define BRGPHY_5708S_PG0_1000X_CTL2				0x11
-#define BRGPHY_5708S_PG0_1000X_CTL2_PAR_DET_EN	0x0001
-
-/* 5708S SerDes "Digital 3" Registers (page 2) */
-#define BRGPHY_5708S_PG2_DIGCTL_3_0				0x10
-#define BRGPHY_5708S_PG2_DIGCTL_3_0_USE_IEEE	0x0001
-
-/* 5708S SerDes "TX Misc" Registers (page 5) */
-#define BRGPHY_5708S_PG5_2500STATUS1			0x10
-#define BRGPHY_5708S_PG5_TXACTL1				0x15
-#define BRGPHY_5708S_PG5_TXACTL3				0x17
 
-/*******************************************************/
-/* End: PHY register values for the 5708S SerDes PHY   */
-/*******************************************************/
-
+/* 5708S SerDes "Digital" Registers (page 0) */
+#define BRGPHY_5708S_PG0_1000X_CTL1				0x10
+#define BRGPHY_5708S_PG0_1000X_CTL1_AUTODET_EN	0x0010
+#define BRGPHY_5708S_PG0_1000X_CTL1_FIBER_MODE	0x0001
+
+#define BRGPHY_5708S_PG0_1000X_STAT1			0x14
+#define BRGPHY_5708S_PG0_1000X_STAT1_LINK		0x0002
+#define BRGPHY_5708S_PG0_1000X_STAT1_FDX		0x0004
+#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_MASK	0x0018
+#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_10	(0x0 << 3)
+#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_100	(0x1 << 3)
+#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_1G	(0x2 << 3)
+#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_25G	(0x3 << 3)
+
+
+#define BRGPHY_5708S_PG0_1000X_CTL2				0x11
+#define BRGPHY_5708S_PG0_1000X_CTL2_PAR_DET_EN	0x0001
+
+/* 5708S SerDes "Digital 3" Registers (page 2) */
+#define BRGPHY_5708S_PG2_DIGCTL_3_0				0x10
+#define BRGPHY_5708S_PG2_DIGCTL_3_0_USE_IEEE	0x0001
+
+/* 5708S SerDes "TX Misc" Registers (page 5) */
+#define BRGPHY_5708S_PG5_2500STATUS1			0x10
+#define BRGPHY_5708S_PG5_TXACTL1				0x15
+#define BRGPHY_5708S_PG5_TXACTL3				0x17
+
+/*******************************************************/
+/* End: PHY register values for the 5708S SerDes PHY   */
+/*******************************************************/
+
 /*******************************************************/
 /* Begin: PHY register values for the 5709S SerDes PHY */
 /*******************************************************/

From a64ee4e18fb5769bf00f77f335704f5f4e4c018a Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Tue, 7 Sep 2010 23:08:38 +0000
Subject: [PATCH 0544/1624] Consistently use tab characters instead of tab +
 space characters. No functional changes.

---
 sys/dev/mii/brgphy.c    |  79 +++++++++---------
 sys/dev/mii/brgphyreg.h | 178 ++++++++++++++++++++--------------------
 2 files changed, 129 insertions(+), 128 deletions(-)

diff --git a/sys/dev/mii/brgphy.c b/sys/dev/mii/brgphy.c
index a733597fe76..b921a8c014a 100644
--- a/sys/dev/mii/brgphy.c
+++ b/sys/dev/mii/brgphy.c
@@ -140,7 +140,7 @@ static const struct mii_phydesc brgphys[] = {
 	MII_PHY_DESC(xxBROADCOM_ALT1, BCM5784),
 	MII_PHY_DESC(xxBROADCOM_ALT1, BCM5709C),
 	MII_PHY_DESC(xxBROADCOM_ALT1, BCM5761),
-    MII_PHY_DESC(xxBROADCOM_ALT1, BCM5709S),
+	MII_PHY_DESC(xxBROADCOM_ALT1, BCM5709S),
 	MII_PHY_DESC(BROADCOM2, BCM5906),
 	MII_PHY_END
 };
@@ -242,11 +242,12 @@ brgphy_attach(device_t dev)
 			bsc->serdes_flags |= BRGPHY_5708S;
 			sc->mii_flags |= MIIF_HAVEFIBER;
 			break;
-        case MII_MODEL_xxBROADCOM_ALT1_BCM5709S:
-            bsc->serdes_flags |= BRGPHY_5709S;
-            sc->mii_flags |= MIIF_HAVEFIBER;
-            break;
-		} break;
+		case MII_MODEL_xxBROADCOM_ALT1_BCM5709S:
+			bsc->serdes_flags |= BRGPHY_5709S;
+			sc->mii_flags |= MIIF_HAVEFIBER;
+			break;
+		}
+		break;
 	default:
 		device_printf(dev, "Unrecognized OUI for PHY!\n");
 	}
@@ -637,7 +638,7 @@ brgphy_status(struct mii_softc *sc)
 			PHY_WRITE(sc, BRGPHY_5708S_BLOCK_ADDR, BRGPHY_5708S_DIG_PG0);
 			xstat = PHY_READ(sc, BRGPHY_5708S_PG0_1000X_STAT1);
 
-            /* Check for MRBE auto-negotiated speed results. */
+			/* Check for MRBE auto-negotiated speed results. */
 			switch (xstat & BRGPHY_5708S_PG0_1000X_STAT1_SPEED_MASK) {
 			case BRGPHY_5708S_PG0_1000X_STAT1_SPEED_10:
 				mii->mii_media_active |= IFM_10_FL; break;
@@ -649,39 +650,39 @@ brgphy_status(struct mii_softc *sc)
 				mii->mii_media_active |= IFM_2500_SX; break;
 			}
 
-            /* Check for MRBE auto-negotiated duplex results. */
+			/* Check for MRBE auto-negotiated duplex results. */
 			if (xstat & BRGPHY_5708S_PG0_1000X_STAT1_FDX)
 				mii->mii_media_active |= IFM_FDX;
 			else
 				mii->mii_media_active |= IFM_HDX;
 
-        } else if (bsc->serdes_flags & BRGPHY_5709S) {
+		} else if (bsc->serdes_flags & BRGPHY_5709S) {
 
-            /* Select GP Status Block of the AN MMD, get autoneg results. */
-            PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_GP_STATUS);
+			/* Select GP Status Block of the AN MMD, get autoneg results. */
+			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_GP_STATUS);
 			xstat = PHY_READ(sc, BRGPHY_GP_STATUS_TOP_ANEG_STATUS);
 
-            /* Restore IEEE0 block (assumed in all brgphy(4) code). */
-            PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_COMBO_IEEE0);
+			/* Restore IEEE0 block (assumed in all brgphy(4) code). */
+			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_COMBO_IEEE0);
 
-            /* Check for MRBE auto-negotiated speed results. */
-            switch (xstat & BRGPHY_GP_STATUS_TOP_ANEG_SPEED_MASK) {
-			case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_10:
-				mii->mii_media_active |= IFM_10_FL; break;
-			case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_100:
-				mii->mii_media_active |= IFM_100_FX; break;
-			case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_1G:
-				mii->mii_media_active |= IFM_1000_SX; break;
-			case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_25G:
-				mii->mii_media_active |= IFM_2500_SX; break;
+			/* Check for MRBE auto-negotiated speed results. */
+			switch (xstat & BRGPHY_GP_STATUS_TOP_ANEG_SPEED_MASK) {
+				case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_10:
+					mii->mii_media_active |= IFM_10_FL; break;
+				case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_100:
+					mii->mii_media_active |= IFM_100_FX; break;
+				case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_1G:
+					mii->mii_media_active |= IFM_1000_SX; break;
+				case BRGPHY_GP_STATUS_TOP_ANEG_SPEED_25G:
+					mii->mii_media_active |= IFM_2500_SX; break;
 			}
 
-            /* Check for MRBE auto-negotiated duplex results. */
+			/* Check for MRBE auto-negotiated duplex results. */
 			if (xstat & BRGPHY_GP_STATUS_TOP_ANEG_FDX)
 				mii->mii_media_active |= IFM_FDX;
 			else
 				mii->mii_media_active |= IFM_HDX;
-        }
+		}
 
 	}
 
@@ -1127,50 +1128,50 @@ brgphy_reset(struct mii_softc *sc)
 		} else if (BCE_CHIP_NUM(bce_sc) == BCE_CHIP_NUM_5709 &&
 			(bce_sc->bce_phy_flags & BCE_PHY_SERDES_FLAG)) {
 
-            /* Select the SerDes Digital block of the AN MMD. */
-            PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_SERDES_DIG);
+			/* Select the SerDes Digital block of the AN MMD. */
+			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_SERDES_DIG);
 			val = PHY_READ(sc, BRGPHY_SERDES_DIG_1000X_CTL1);
 			val &= ~BRGPHY_SD_DIG_1000X_CTL1_AUTODET;
 			val |= BRGPHY_SD_DIG_1000X_CTL1_FIBER;
 			PHY_WRITE(sc, BRGPHY_SERDES_DIG_1000X_CTL1, val);
 
-            /* Select the Over 1G block of the AN MMD. */
+			/* Select the Over 1G block of the AN MMD. */
 			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_OVER_1G);
 
-            /* Enable autoneg "Next Page" to advertise 2.5G support. */
-            val = PHY_READ(sc, BRGPHY_OVER_1G_UNFORMAT_PG1);
+			/* Enable autoneg "Next Page" to advertise 2.5G support. */
+			val = PHY_READ(sc, BRGPHY_OVER_1G_UNFORMAT_PG1);
 			if (bce_sc->bce_phy_flags & BCE_PHY_2_5G_CAPABLE_FLAG)
 				val |= BRGPHY_5708S_ANEG_NXT_PG_XMIT1_25G;
 			else
 				val &= ~BRGPHY_5708S_ANEG_NXT_PG_XMIT1_25G;
 			PHY_WRITE(sc, BRGPHY_OVER_1G_UNFORMAT_PG1, val);
 
-            /* Select the Multi-Rate Backplane Ethernet block of the AN MMD. */
+			/* Select the Multi-Rate Backplane Ethernet block of the AN MMD. */
 			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_MRBE);
 
-            /* Enable MRBE speed autoneg. */
-            val = PHY_READ(sc, BRGPHY_MRBE_MSG_PG5_NP);
+			/* Enable MRBE speed autoneg. */
+			val = PHY_READ(sc, BRGPHY_MRBE_MSG_PG5_NP);
 			val |= BRGPHY_MRBE_MSG_PG5_NP_MBRE |
 			    BRGPHY_MRBE_MSG_PG5_NP_T2;
 			PHY_WRITE(sc, BRGPHY_MRBE_MSG_PG5_NP, val);
 
-            /* Select the Clause 73 User B0 block of the AN MMD. */
-            PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_CL73_USER_B0);
+			/* Select the Clause 73 User B0 block of the AN MMD. */
+			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_CL73_USER_B0);
 
-            /* Enable MRBE speed autoneg. */
+			/* Enable MRBE speed autoneg. */
 			PHY_WRITE(sc, BRGPHY_CL73_USER_B0_MBRE_CTL1,
 			    BRGPHY_CL73_USER_B0_MBRE_CTL1_NP_AFT_BP |
 			    BRGPHY_CL73_USER_B0_MBRE_CTL1_STA_MGR |
 			    BRGPHY_CL73_USER_B0_MBRE_CTL1_ANEG);
 
-            /* Restore IEEE0 block (assumed in all brgphy(4) code). */
-            PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_COMBO_IEEE0);
+			/* Restore IEEE0 block (assumed in all brgphy(4) code). */
+			PHY_WRITE(sc, BRGPHY_BLOCK_ADDR, BRGPHY_BLOCK_ADDR_COMBO_IEEE0);
 
         } else if (BCE_CHIP_NUM(bce_sc) == BCE_CHIP_NUM_5709) {
 			if ((BCE_CHIP_REV(bce_sc) == BCE_CHIP_REV_Ax) ||
 				(BCE_CHIP_REV(bce_sc) == BCE_CHIP_REV_Bx))
 				brgphy_fixup_disable_early_dac(sc);
-	
+
 			brgphy_jumbo_settings(sc, ifp->if_mtu);
 			brgphy_ethernet_wirespeed(sc);
 		} else {
diff --git a/sys/dev/mii/brgphyreg.h b/sys/dev/mii/brgphyreg.h
index df3e756925b..7bd6156fe9d 100644
--- a/sys/dev/mii/brgphyreg.h
+++ b/sys/dev/mii/brgphyreg.h
@@ -39,21 +39,21 @@
  * Broadcom BCM5400 registers
  */
 
-#define	BRGPHY_MII_BMCR	    	0x00
-#define	BRGPHY_BMCR_RESET		0x8000
-#define	BRGPHY_BMCR_LOOP		0x4000
-#define	BRGPHY_BMCR_SPD0		0x2000	/* Speed select, lower bit */
-#define	BRGPHY_BMCR_AUTOEN		0x1000	/* Autoneg enabled */
-#define	BRGPHY_BMCR_PDOWN		0x0800	/* Power down */
-#define	BRGPHY_BMCR_ISO			0x0400	/* Isolate */
+#define	BRGPHY_MII_BMCR		0x00
+#define	BRGPHY_BMCR_RESET	0x8000
+#define	BRGPHY_BMCR_LOOP	0x4000
+#define	BRGPHY_BMCR_SPD0	0x2000	/* Speed select, lower bit */
+#define	BRGPHY_BMCR_AUTOEN	0x1000	/* Autoneg enabled */
+#define	BRGPHY_BMCR_PDOWN	0x0800	/* Power down */
+#define	BRGPHY_BMCR_ISO		0x0400	/* Isolate */
 #define	BRGPHY_BMCR_STARTNEG	0x0200	/* Restart autoneg */
-#define	BRGPHY_BMCR_FDX			0x0100	/* Duplex mode */
-#define	BRGPHY_BMCR_CTEST		0x0080	/* Collision test enable */
-#define	BRGPHY_BMCR_SPD1		0x0040	/* Speed select, upper bit */
+#define	BRGPHY_BMCR_FDX		0x0100	/* Duplex mode */
+#define	BRGPHY_BMCR_CTEST	0x0080	/* Collision test enable */
+#define	BRGPHY_BMCR_SPD1	0x0040	/* Speed select, upper bit */
 
-#define	BRGPHY_S1000			BRGPHY_BMCR_SPD1	/* 1000mbps */
-#define	BRGPHY_S100				BRGPHY_BMCR_SPD0	/* 100mpbs */
-#define	BRGPHY_S10				0					/* 10mbps */
+#define	BRGPHY_S1000		BRGPHY_BMCR_SPD1	/* 1000mbps */
+#define	BRGPHY_S100		BRGPHY_BMCR_SPD0	/* 100mpbs */
+#define	BRGPHY_S10		0			/* 10mbps */
 
 #define	BRGPHY_MII_BMSR		0x01
 #define	BRGPHY_BMSR_EXTSTS	0x0100	/* Extended status present */
@@ -267,21 +267,21 @@
 /*******************************************************/
 
 /* SerDes autoneg is different from copper */
-#define BRGPHY_SERDES_ANAR				0x04
-#define BRGPHY_SERDES_ANAR_FDX			0x0020
-#define BRGPHY_SERDES_ANAR_HDX			0x0040
-#define BRGPHY_SERDES_ANAR_NO_PAUSE		(0x0 << 7)
-#define BRGPHY_SERDES_ANAR_SYM_PAUSE	(0x1 << 7)
-#define BRGPHY_SERDES_ANAR_ASYM_PAUSE	(0x2 << 7)
-#define BRGPHY_SERDES_ANAR_BOTH_PAUSE	(0x3 << 7)
+#define	BRGPHY_SERDES_ANAR		0x04
+#define	BRGPHY_SERDES_ANAR_FDX		0x0020
+#define	BRGPHY_SERDES_ANAR_HDX		0x0040
+#define	BRGPHY_SERDES_ANAR_NO_PAUSE	(0x0 << 7)
+#define	BRGPHY_SERDES_ANAR_SYM_PAUSE	(0x1 << 7)
+#define	BRGPHY_SERDES_ANAR_ASYM_PAUSE	(0x2 << 7)
+#define	BRGPHY_SERDES_ANAR_BOTH_PAUSE	(0x3 << 7)
 
-#define BRGPHY_SERDES_ANLPAR			0x05
-#define BRGPHY_SERDES_ANLPAR_FDX		0x0020
-#define BRGPHY_SERDES_ANLPAR_HDX		0x0040
-#define BRGPHY_SERDES_ANLPAR_NO_PAUSE	(0x0 << 7)
-#define BRGPHY_SERDES_ANLPAR_SYM_PAUSE	(0x1 << 7)
-#define BRGPHY_SERDES_ANLPAR_ASYM_PAUSE	(0x2 << 7)
-#define BRGPHY_SERDES_ANLPAR_BOTH_PAUSE	(0x3 << 7)
+#define	BRGPHY_SERDES_ANLPAR		0x05
+#define	BRGPHY_SERDES_ANLPAR_FDX	0x0020
+#define	BRGPHY_SERDES_ANLPAR_HDX	0x0040
+#define	BRGPHY_SERDES_ANLPAR_NO_PAUSE	(0x0 << 7)
+#define	BRGPHY_SERDES_ANLPAR_SYM_PAUSE	(0x1 << 7)
+#define	BRGPHY_SERDES_ANLPAR_ASYM_PAUSE	(0x2 << 7)
+#define	BRGPHY_SERDES_ANLPAR_BOTH_PAUSE	(0x3 << 7)
 
 /*******************************************************/
 /* End: Shared SerDes PHY register definitions         */
@@ -295,20 +295,20 @@
  * Shadow register 0x1C, bit 15 is write enable,
  * bits 14-10 select function (0x00 to 0x1F).
  */
-#define BRGPHY_MII_SHADOW_1C			0x1C
-#define BRGPHY_SHADOW_1C_WRITE_EN		0x8000
-#define BRGPHY_SHADOW_1C_SELECT_MASK	0x7C00
+#define	BRGPHY_MII_SHADOW_1C		0x1C
+#define	BRGPHY_SHADOW_1C_WRITE_EN	0x8000
+#define	BRGPHY_SHADOW_1C_SELECT_MASK	0x7C00
 
 /* Shadow 0x1C Mode Control Register (select value 0x1F) */
-#define BRGPHY_SHADOW_1C_MODE_CTRL		(0x1F << 10)
+#define	BRGPHY_SHADOW_1C_MODE_CTRL	(0x1F << 10)
 /* When set, Regs 0-0x0F are 1000X, else 1000T */
-#define BRGPHY_SHADOW_1C_ENA_1000X		0x0001	
+#define	BRGPHY_SHADOW_1C_ENA_1000X	0x0001	
 
-#define	BRGPHY_MII_TEST1	0x1E
-#define	BRGPHY_TEST1_TRIM_EN	0x0010
-#define	BRGPHY_TEST1_CRC_EN	0x8000
+#define	BRGPHY_MII_TEST1		0x1E
+#define	BRGPHY_TEST1_TRIM_EN		0x0010
+#define	BRGPHY_TEST1_CRC_EN		0x8000
 
-#define BRGPHY_MII_TEST2		0x1F
+#define	BRGPHY_MII_TEST2		0x1F
 
 /*******************************************************/
 /* End: PHY register values for the 5706 PHY           */
@@ -319,41 +319,41 @@
 /*******************************************************/
 
 /* Autoneg Next Page Transmit 1 Regiser */
-#define BRGPHY_5708S_ANEG_NXT_PG_XMIT1			0x0B
-#define BRGPHY_5708S_ANEG_NXT_PG_XMIT1_25G		0x0001
+#define	BRGPHY_5708S_ANEG_NXT_PG_XMIT1		0x0B
+#define	BRGPHY_5708S_ANEG_NXT_PG_XMIT1_25G	0x0001
 
 /* Use the BLOCK_ADDR register to select the page for registers 0x10 to 0x1E */
-#define BRGPHY_5708S_BLOCK_ADDR					0x1f
-#define BRGPHY_5708S_DIG_PG0 					0x0000
-#define BRGPHY_5708S_DIG3_PG2					0x0002
-#define BRGPHY_5708S_TX_MISC_PG5				0x0005
+#define	BRGPHY_5708S_BLOCK_ADDR			0x1f
+#define	BRGPHY_5708S_DIG_PG0			0x0000
+#define	BRGPHY_5708S_DIG3_PG2			0x0002
+#define	BRGPHY_5708S_TX_MISC_PG5		0x0005
 
 /* 5708S SerDes "Digital" Registers (page 0) */
-#define BRGPHY_5708S_PG0_1000X_CTL1				0x10
-#define BRGPHY_5708S_PG0_1000X_CTL1_AUTODET_EN	0x0010
-#define BRGPHY_5708S_PG0_1000X_CTL1_FIBER_MODE	0x0001
+#define	BRGPHY_5708S_PG0_1000X_CTL1		0x10
+#define	BRGPHY_5708S_PG0_1000X_CTL1_AUTODET_EN	0x0010
+#define	BRGPHY_5708S_PG0_1000X_CTL1_FIBER_MODE	0x0001
 
-#define BRGPHY_5708S_PG0_1000X_STAT1			0x14
-#define BRGPHY_5708S_PG0_1000X_STAT1_LINK		0x0002
-#define BRGPHY_5708S_PG0_1000X_STAT1_FDX		0x0004
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_MASK	0x0018
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_10	(0x0 << 3)
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_100	(0x1 << 3)
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_1G	(0x2 << 3)
-#define BRGPHY_5708S_PG0_1000X_STAT1_SPEED_25G	(0x3 << 3)
+#define	BRGPHY_5708S_PG0_1000X_STAT1		0x14
+#define	BRGPHY_5708S_PG0_1000X_STAT1_LINK	0x0002
+#define	BRGPHY_5708S_PG0_1000X_STAT1_FDX	0x0004
+#define	BRGPHY_5708S_PG0_1000X_STAT1_SPEED_MASK	0x0018
+#define	BRGPHY_5708S_PG0_1000X_STAT1_SPEED_10	(0x0 << 3)
+#define	BRGPHY_5708S_PG0_1000X_STAT1_SPEED_100	(0x1 << 3)
+#define	BRGPHY_5708S_PG0_1000X_STAT1_SPEED_1G	(0x2 << 3)
+#define	BRGPHY_5708S_PG0_1000X_STAT1_SPEED_25G	(0x3 << 3)
 
 
-#define BRGPHY_5708S_PG0_1000X_CTL2				0x11
-#define BRGPHY_5708S_PG0_1000X_CTL2_PAR_DET_EN	0x0001
+#define	BRGPHY_5708S_PG0_1000X_CTL2		0x11
+#define	BRGPHY_5708S_PG0_1000X_CTL2_PAR_DET_EN	0x0001
 
 /* 5708S SerDes "Digital 3" Registers (page 2) */
-#define BRGPHY_5708S_PG2_DIGCTL_3_0				0x10
-#define BRGPHY_5708S_PG2_DIGCTL_3_0_USE_IEEE	0x0001
+#define	BRGPHY_5708S_PG2_DIGCTL_3_0		0x10
+#define	BRGPHY_5708S_PG2_DIGCTL_3_0_USE_IEEE	0x0001
 
 /* 5708S SerDes "TX Misc" Registers (page 5) */
-#define BRGPHY_5708S_PG5_2500STATUS1			0x10
-#define BRGPHY_5708S_PG5_TXACTL1				0x15
-#define BRGPHY_5708S_PG5_TXACTL3				0x17
+#define	BRGPHY_5708S_PG5_2500STATUS1		0x10
+#define	BRGPHY_5708S_PG5_TXACTL1		0x15
+#define	BRGPHY_5708S_PG5_TXACTL3		0x17
 
 /*******************************************************/
 /* End: PHY register values for the 5708S SerDes PHY   */
@@ -364,51 +364,51 @@
 /*******************************************************/
 
 /* 5709S SerDes "General Purpose Status" Registers */
-#define BRGPHY_BLOCK_ADDR_GP_STATUS		        0x8120
-#define BRGPHY_GP_STATUS_TOP_ANEG_STATUS	    0x1B
-#define BRGPHY_GP_STATUS_TOP_ANEG_SPEED_MASK	0x3F00
-#define BRGPHY_GP_STATUS_TOP_ANEG_SPEED_10	    0x0000
-#define BRGPHY_GP_STATUS_TOP_ANEG_SPEED_100	    0x0100
-#define BRGPHY_GP_STATUS_TOP_ANEG_SPEED_1G	    0x0200
-#define BRGPHY_GP_STATUS_TOP_ANEG_SPEED_25G	    0x0300
-#define BRGPHY_GP_STATUS_TOP_ANEG_SPEED_1GKX	0x0D00
-#define BRGPHY_GP_STATUS_TOP_ANEG_FDX		    0x0008
-#define BRGPHY_GP_STATUS_TOP_ANEG_LINK_UP	    0x0004
-#define BRGPHY_GP_STATUS_TOP_ANEG_CL73_COMP	    0x0001
+#define	BRGPHY_BLOCK_ADDR_GP_STATUS		0x8120
+#define	BRGPHY_GP_STATUS_TOP_ANEG_STATUS	0x1B
+#define	BRGPHY_GP_STATUS_TOP_ANEG_SPEED_MASK	0x3F00
+#define	BRGPHY_GP_STATUS_TOP_ANEG_SPEED_10	0x0000
+#define	BRGPHY_GP_STATUS_TOP_ANEG_SPEED_100	0x0100
+#define	BRGPHY_GP_STATUS_TOP_ANEG_SPEED_1G	0x0200
+#define	BRGPHY_GP_STATUS_TOP_ANEG_SPEED_25G	0x0300
+#define	BRGPHY_GP_STATUS_TOP_ANEG_SPEED_1GKX	0x0D00
+#define	BRGPHY_GP_STATUS_TOP_ANEG_FDX		0x0008
+#define	BRGPHY_GP_STATUS_TOP_ANEG_LINK_UP	0x0004
+#define	BRGPHY_GP_STATUS_TOP_ANEG_CL73_COMP	0x0001
 
 /* 5709S SerDes "SerDes Digital" Registers */
-#define BRGPHY_BLOCK_ADDR_SERDES_DIG		    0x8300
-#define	BRGPHY_SERDES_DIG_1000X_CTL1		    0x0010
-#define	BRGPHY_SD_DIG_1000X_CTL1_AUTODET	    0x0010
-#define	BRGPHY_SD_DIG_1000X_CTL1_FIBER		    0x0001
+#define	BRGPHY_BLOCK_ADDR_SERDES_DIG		0x8300
+#define	BRGPHY_SERDES_DIG_1000X_CTL1		0x0010
+#define	BRGPHY_SD_DIG_1000X_CTL1_AUTODET	0x0010
+#define	BRGPHY_SD_DIG_1000X_CTL1_FIBER		0x0001
 
 /* 5709S SerDes "Over 1G" Registers */
-#define BRGPHY_BLOCK_ADDR_OVER_1G		        0x8320
-#define BRGPHY_OVER_1G_UNFORMAT_PG1		        0x19
+#define	BRGPHY_BLOCK_ADDR_OVER_1G		0x8320
+#define	BRGPHY_OVER_1G_UNFORMAT_PG1		0x19
 
 /* 5709S SerDes "Multi-Rate Backplane Ethernet" Registers */
-#define BRGPHY_BLOCK_ADDR_MRBE			        0x8350
-#define BRGPHY_MRBE_MSG_PG5_NP			        0x10
-#define BRGPHY_MRBE_MSG_PG5_NP_MBRE		        0x0001
-#define BRGPHY_MRBE_MSG_PG5_NP_T2		        0x0001
+#define	BRGPHY_BLOCK_ADDR_MRBE			0x8350
+#define	BRGPHY_MRBE_MSG_PG5_NP			0x10
+#define	BRGPHY_MRBE_MSG_PG5_NP_MBRE		0x0001
+#define	BRGPHY_MRBE_MSG_PG5_NP_T2		0x0001
 
 /* 5709S SerDes "IEEE Clause 73 User B0" Registers */
-#define BRGPHY_BLOCK_ADDR_CL73_USER_B0		    0x8370
-#define BRGPHY_CL73_USER_B0_MBRE_CTL1		    0x12
+#define	BRGPHY_BLOCK_ADDR_CL73_USER_B0		0x8370
+#define	BRGPHY_CL73_USER_B0_MBRE_CTL1		0x12
 #define	BRGPHY_CL73_USER_B0_MBRE_CTL1_NP_AFT_BP	0x2000
 #define	BRGPHY_CL73_USER_B0_MBRE_CTL1_STA_MGR	0x4000
-#define	BRGPHY_CL73_USER_B0_MBRE_CTL1_ANEG	    0x8000
+#define	BRGPHY_CL73_USER_B0_MBRE_CTL1_ANEG	0x8000
 
 /* 5709S SerDes "IEEE Clause 73 User B0" Registers */
-#define BRGPHY_BLOCK_ADDR_ADDR_EXT		        0xFFD0
+#define	BRGPHY_BLOCK_ADDR_ADDR_EXT		0xFFD0
 
 /* 5709S SerDes "Combo IEEE 0" Registers */
-#define BRGPHY_BLOCK_ADDR_COMBO_IEEE0		    0xFFE0
+#define	BRGPHY_BLOCK_ADDR_COMBO_IEEE0		0xFFE0
 
-#define BRGPHY_ADDR_EXT				            0x1E
-#define BRGPHY_BLOCK_ADDR			            0x1F
+#define	BRGPHY_ADDR_EXT				0x1E
+#define	BRGPHY_BLOCK_ADDR			0x1F
 
-#define BRGPHY_ADDR_EXT_AN_MMD			        0x3800
+#define	BRGPHY_ADDR_EXT_AN_MMD			0x3800
 
 /*******************************************************/
 /* End: PHY register values for the 5709S SerDes PHY   */

From 4982c539ae5f561ef3ad34af5938929f8548db63 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Tue, 7 Sep 2010 23:31:48 +0000
Subject: [PATCH 0545/1624] Fix an error made in r209975 related to context ID
 allocation for 64-bit PowerPC CPUs running a 32-bit kernel. This bug could
 cause in-use VSIDs to be allocated again to another process, causing memory
 space overlaps and corruption.

Reported by:	linimon
---
 sys/powerpc/aim/mmu_oea64.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index cc7f3878e92..c1b6f2c7b7e 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -2108,7 +2108,7 @@ void
 moea64_pinit(mmu_t mmu, pmap_t pmap)
 {
 	int	i;
-	register_t hash;
+	uint32_t hash;
 
 	PMAP_LOCK_INIT(pmap);
 
@@ -2125,6 +2125,8 @@ moea64_pinit(mmu_t mmu, pmap_t pmap)
 
 	for (i = 0; i < 16; i++) 
 		pmap->pm_sr[i] = VSID_MAKE(i, hash);
+
+	KASSERT(pmap->pm_sr[0] != 0, ("moea64_pinit: pm_sr[0] = 0"));
 }
 #endif
 
@@ -2238,6 +2240,8 @@ moea64_release_vsid(uint64_t vsid)
 	idx = vsid & (NVSIDS-1);
 	mask = 1 << (idx % VSID_NBPW);
 	idx /= VSID_NBPW;
+	KASSERT(moea64_vsid_bitmap[idx] & mask,
+	    ("Freeing unallocated VSID %#jx", vsid));
 	moea64_vsid_bitmap[idx] &= ~mask;
 	mtx_unlock(&moea64_slb_mutex);
 }
@@ -2254,10 +2258,9 @@ moea64_release(mmu_t mmu, pmap_t pmap)
 	free_vsids(pmap);
 	slb_free_user_cache(pmap->pm_slb);
     #else
-        if (pmap->pm_sr[0] == 0)
-                panic("moea64_release: pm_sr[0] = 0");
+	KASSERT(pmap->pm_sr[0] != 0, ("moea64_release: pm_sr[0] = 0"));
 
-	moea64_release_vsid(pmap->pm_sr[0]);
+	moea64_release_vsid(VSID_TO_HASH(pmap->pm_sr[0]));
     #endif
 
 	PMAP_LOCK_DESTROY(pmap);

From 17dce7e108d6446f8aeda58eb8d48642c86d9802 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 8 Sep 2010 02:18:20 +0000
Subject: [PATCH 0546/1624] To avoid possible race condition, SIGCANCEL is
 always sent except the thread is dead.

---
 lib/libthr/thread/thr_cancel.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libthr/thread/thr_cancel.c b/lib/libthr/thread/thr_cancel.c
index e408e03dbcd..c61cedeeac3 100644
--- a/lib/libthr/thread/thr_cancel.c
+++ b/lib/libthr/thread/thr_cancel.c
@@ -67,7 +67,7 @@ _pthread_cancel(pthread_t pthread)
 		THR_THREAD_LOCK(curthread, pthread);
 		if (!pthread->cancel_pending) {
 			pthread->cancel_pending = 1;
-			if (pthread->cancel_enable)
+			if (pthread->state != PS_DEAD)
 				_thr_send_sig(pthread, SIGCANCEL);
 		}
 		THR_THREAD_UNLOCK(curthread, pthread);

From 4b06d6510d330d90007516d38ead1d9689910f53 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 8 Sep 2010 07:30:46 +0000
Subject: [PATCH 0547/1624] For total interrupt count on -vm screen count all
 interrupts, but not only those which fit the screen.

---
 usr.bin/systat/vmstat.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/usr.bin/systat/vmstat.c b/usr.bin/systat/vmstat.c
index f5e83246889..07a83911eae 100644
--- a/usr.bin/systat/vmstat.c
+++ b/usr.bin/systat/vmstat.c
@@ -443,6 +443,9 @@ showkre(void)
 	for (i = 0; i < nintr; i++) {
 		if (s.intrcnt[i] == 0)
 			continue;
+		X(intrcnt);
+		l = (int)((float)s.intrcnt[i]/etime + 0.5);
+		inttotal += l;
 		if (intrloc[i] == 0) {
 			if (nextintsrow == LINES)
 				continue;
@@ -450,9 +453,6 @@ showkre(void)
 			mvprintw(intrloc[i], INTSCOL + 6, "%-10.10s",
 				intrname[i]);
 		}
-		X(intrcnt);
-		l = (int)((float)s.intrcnt[i]/etime + 0.5);
-		inttotal += l;
 		putint(l, intrloc[i], INTSCOL, 5);
 	}
 	putint(inttotal, INTSROW + 1, INTSCOL, 5);

From 4c394c189fcb75a29b809d7990885dd0688e7d45 Mon Sep 17 00:00:00 2001
From: MIHIRA Sanpei Yoshiro 
Date: Wed, 8 Sep 2010 13:26:19 +0000
Subject: [PATCH 0548/1624] Add Buffalo (Melco Inc.) LUA3-U2-ATX to list of
 supported devices.

Submitted by:	nork at FreeBSD.org
MFC after:	3 days
---
 share/man/man4/axe.4 | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/share/man/man4/axe.4 b/share/man/man4/axe.4
index f3c0c753a66..c83d8f57f4b 100644
--- a/share/man/man4/axe.4
+++ b/share/man/man4/axe.4
@@ -177,6 +177,8 @@ Sitecom Europe LN-028
 AX88772:
 .Bl -bullet -compact
 .It
+Buffalo (Melco Inc.) LUA3-U2-ATX
+.It
 Cisco-Linksys USB200Mv2
 .It
 D-Link DUBE100B1

From 670a0909713fb73825e006b369d636e7a1fccb9d Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 8 Sep 2010 16:34:08 +0000
Subject: [PATCH 0549/1624] Clean up fast message ring code for XLR.

Fix message ring send path:
- define msgrng_access_enable() which disables local interrupts
  and enables message ring access. Also define msgrng_restore() which
  restores interrupts
- remove all other msgrng enable/disable macros, no need of critical_enter
  and other locking here.
- message_send() fixup: re-read status until pending bit clears
- message_send_retry() fixup: retry only few times with interrupts disabled
- Fix up message_send/message_send_retry callers - call
  msgrng_access_enable() and msgrng_restore() correctly so that interrupts
  are not disabled for long.
- removed unused and obsolete code from sys/mips/rmi/msgring.h
- some style fixes - more later

rge.c (XLR GMAC driver):
- updated for the message ring changes
- remove unused message_send_block()
- retry on credit failure, this is not a permanent failure when credits
  are configured correctly. Add panic if credits are not available to
  send for a long time.
---
 sys/mips/rmi/dev/xlr/rge.c |  60 +++-------
 sys/mips/rmi/fmn.c         |  38 +++---
 sys/mips/rmi/msgring.h     | 237 ++++++++++++-------------------------
 3 files changed, 112 insertions(+), 223 deletions(-)

diff --git a/sys/mips/rmi/dev/xlr/rge.c b/sys/mips/rmi/dev/xlr/rge.c
index b021ceebcbc..924031a4c5e 100644
--- a/sys/mips/rmi/dev/xlr/rge.c
+++ b/sys/mips/rmi/dev/xlr/rge.c
@@ -711,21 +711,27 @@ static __inline__ int
 xlr_mac_send_fr(struct driver_data *priv,
     vm_paddr_t addr, int len)
 {
-	int stid = priv->rfrbucket;
 	struct msgrng_msg msg;
-	int vcpu = xlr_cpu_id();
+	int stid = priv->rfrbucket;
+	int i = 0, code, ret;
+	uint32_t msgrng_flags;
 
 	mac_make_desc_rfr(&msg, addr);
 
 	/* Send the packet to MAC */
 	dbg_msg("mac_%d: Sending free packet %lx to stid %d\n",
 	    priv->instance, (u_long)addr, stid);
-	if (priv->type == XLR_XGMAC) {
-		while (message_send(1, MSGRNG_CODE_XGMAC, stid, &msg));
-	} else {
-		while (message_send(1, MSGRNG_CODE_MAC, stid, &msg));
-		xlr_rge_repl_done[vcpu]++;
-	}
+	if (priv->type == XLR_XGMAC)
+		code = MSGRNG_CODE_XGMAC;        /* WHY? */
+	else
+		code = MSGRNG_CODE_MAC;
+
+	do {
+		msgrng_flags = msgrng_access_enable();
+		ret = message_send_retry(1, code, stid, &msg);
+		msgrng_restore(msgrng_flags);
+		KASSERT(i++ < 100000, ("Too many credit fails\n"));
+	} while (ret != 0);
 
 	return 0;
 }
@@ -1439,37 +1445,16 @@ rmi_xlr_mac_set_duplex(struct driver_data *s,
 #define MAC_TX_PASS 0
 #define MAC_TX_RETRY 1
 
-static __inline__ void
-message_send_block(unsigned int size, unsigned int code,
-    unsigned int stid, struct msgrng_msg *msg)
-{
-	unsigned int dest = 0;
-	unsigned long long status = 0;
-
-	msgrng_load_tx_msg0(msg->msg0);
-	msgrng_load_tx_msg1(msg->msg1);
-	msgrng_load_tx_msg2(msg->msg2);
-	msgrng_load_tx_msg3(msg->msg3);
-
-	dest = ((size - 1) << 16) | (code << 8) | (stid);
-
-	do {
-		msgrng_send(dest);
-		status = msgrng_read_status();
-	} while (status & 0x6);
-
-}
-
 int xlr_dev_queue_xmit_hack = 0;
 
 static int
 mac_xmit(struct mbuf *m, struct rge_softc *sc,
     struct driver_data *priv, int len, struct p2d_tx_desc *tx_desc)
 {
-	struct msgrng_msg msg;
+	struct msgrng_msg msg = {0,0,0,0};
 	int stid = priv->txbucket;
 	uint32_t tx_cycles = 0;
-	unsigned long mflags = 0;
+	uint32_t mflags;
 	int vcpu = xlr_cpu_id();
 	int rv;
 
@@ -1479,17 +1464,17 @@ mac_xmit(struct mbuf *m, struct rge_softc *sc,
 		return MAC_TX_FAIL;
 
 	else {
-		msgrng_access_enable(mflags);
+		mflags = msgrng_access_enable();
 		if ((rv = message_send_retry(1, MSGRNG_CODE_MAC, stid, &msg)) != 0) {
 			msg_snd_failed++;
-			msgrng_access_disable(mflags);
+			msgrng_restore(mflags);
 			release_tx_desc(&msg, 0);
 			xlr_rge_msg_snd_failed[vcpu]++;
 			dbg_msg("Failed packet to cpu %d, rv = %d, stid %d, msg0=%jx\n",
 			    vcpu, rv, stid, (uintmax_t)msg.msg0);
 			return MAC_TX_FAIL;
 		}
-		msgrng_access_disable(mflags);
+		msgrng_restore(mflags);
 		port_inc_counter(priv->instance, PORT_TX);
 	}
 
@@ -1559,7 +1544,6 @@ mac_frin_replenish(void *args /* ignored */ )
 
 		for (i = 0; i < XLR_MAX_MACS; i++) {
 			/* int offset = 0; */
-			unsigned long msgrng_flags;
 			void *m;
 			uint32_t cycles;
 			struct rge_softc *sc;
@@ -1592,14 +1576,11 @@ mac_frin_replenish(void *args /* ignored */ )
 				}
 			}
 			xlr_inc_counter(REPLENISH_FRIN);
-			msgrng_access_enable(msgrng_flags);
 			if (xlr_mac_send_fr(priv, vtophys(m), MAX_FRAME_SIZE)) {
 				free_buf(vtophys(m));
 				printf("[%s]: rx free message_send failed!\n", __FUNCTION__);
-				msgrng_access_disable(msgrng_flags);
 				break;
 			}
-			msgrng_access_disable(msgrng_flags);
 			xlr_set_counter(REPLENISH_CYCLES,
 			    (read_c0_count() - cycles));
 			atomic_subtract_int((&priv->frin_to_be_sent[cpu]), 1);
@@ -2427,7 +2408,6 @@ static int
 rmi_xlr_mac_fill_rxfr(struct rge_softc *sc)
 {
 	struct driver_data *priv = &(sc->priv);
-	unsigned long msgrng_flags;
 	int i;
 	int ret = 0;
 	void *ptr;
@@ -2445,9 +2425,7 @@ rmi_xlr_mac_fill_rxfr(struct rge_softc *sc)
 			break;
 		}
 		/* Send the free Rx desc to the MAC */
-		msgrng_access_enable(msgrng_flags);
 		xlr_mac_send_fr(priv, vtophys(ptr), MAX_FRAME_SIZE);
-		msgrng_access_disable(msgrng_flags);
 	}
 
 	return ret;
diff --git a/sys/mips/rmi/fmn.c b/sys/mips/rmi/fmn.c
index 31cb2f0d4d5..f10d3ff6f9d 100644
--- a/sys/mips/rmi/fmn.c
+++ b/sys/mips/rmi/fmn.c
@@ -115,7 +115,7 @@ xlr_msgring_cpu_init(void)
 	struct stn_cc *cc_config;
 	struct bucket_size *bucket_sizes;
 	int id;
-	unsigned long flags;
+	uint32_t flags;
 
 	KASSERT(xlr_thr_id() == 0,
 		("xlr_msgring_cpu_init from non-zero thread\n"));
@@ -125,13 +125,14 @@ xlr_msgring_cpu_init(void)
 	bucket_sizes = xlr_board_info.bucket_sizes;
 	cc_config = xlr_board_info.credit_configs[id];
 
-	msgrng_flags_save(flags);
 
 	/*
 	 * Message Stations are shared among all threads in a cpu core
 	 * Assume, thread 0 on all cores are always active when more than 1
 	 * thread is active in a core
 	 */
+	flags = msgrng_access_enable();
+
 	msgrng_write_bucksize(0, bucket_sizes->bucket[id * 8 + 0]);
 	msgrng_write_bucksize(1, bucket_sizes->bucket[id * 8 + 1]);
 	msgrng_write_bucksize(2, bucket_sizes->bucket[id * 8 + 2]);
@@ -158,7 +159,7 @@ xlr_msgring_cpu_init(void)
 	MSGRNG_CC_INIT_CPU_DEST(14, cc_config->counters);
 	MSGRNG_CC_INIT_CPU_DEST(15, cc_config->counters);
 
-	msgrng_flags_restore(flags);
+	msgrng_restore(flags);
 }
 
 void 
@@ -183,8 +184,7 @@ xlr_msgring_handler(struct trapframe *tf)
 	unsigned int bucket_empty_bm = 0;
 	unsigned int status = 0;
 
-	/* TODO: not necessary to disable preemption */
-	msgrng_flags_save(mflags);
+	mflags = msgrng_access_enable();
 
 	/* First Drain all the high priority messages */
 	for (;;) {
@@ -210,39 +210,37 @@ xlr_msgring_handler(struct trapframe *tf)
 				    __FUNCTION__, tx_stid, bucket, size, (uintmax_t)msg.msg0);
 			} else {
 				//printf("[%s]: rx_stid = %d\n", __FUNCTION__, rx_stid);
-				msgrng_flags_restore(mflags);
+				msgrng_restore(mflags);
 				(*tx_stn_handlers[tx_stid].action) (bucket, size, code, rx_stid,
 				    &msg, tx_stn_handlers[tx_stid].dev_id);
-				msgrng_flags_save(mflags);
+				mflags = msgrng_access_enable();
 			}
 		}
 	}
-	msgrng_flags_restore(mflags);
+	msgrng_restore(mflags);
 }
 
 void 
 enable_msgring_int(void *arg)
 {
-	unsigned long mflags = 0;
+	uint32_t config, mflags;
 
-	msgrng_access_save(&msgrng_lock, mflags);
-	/* enable the message ring interrupts */
-	msgrng_write_config((msgring_watermark_count << 24) | (IRQ_MSGRING << 16)
-	    | (msgring_thread_mask << 8) | msgring_int_type);
-	msgrng_access_restore(&msgrng_lock, mflags);
+	config = (msgring_watermark_count << 24) | (IRQ_MSGRING << 16) |
+	    (msgring_thread_mask << 8) | msgring_int_type;
+	mflags = msgrng_access_enable();
+	msgrng_write_config(config);
+	msgrng_restore(mflags);
 }
 
 void 
 disable_msgring_int(void *arg)
 {
-	unsigned long mflags = 0;
-	uint32_t config;
+	uint32_t config, mflags;
 
-	msgrng_access_save(&msgrng_lock, mflags);
-	config = msgrng_read_config();
-	config &= ~0x3;
+	mflags = msgrng_access_enable();
+	config = msgrng_read_config() & ~0x3;
 	msgrng_write_config(config);
-	msgrng_access_restore(&msgrng_lock, mflags);
+	msgrng_restore(mflags);
 }
 
 static int
diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h
index 6986739e0ad..d524892d73c 100644
--- a/sys/mips/rmi/msgring.h
+++ b/sys/mips/rmi/msgring.h
@@ -32,54 +32,36 @@
 #ifndef _RMI_MSGRING_H_
 #define _RMI_MSGRING_H_
 
+#include 
+#include 
 #include 
+
+#include 
+#include 
 #include 
 
-#define MSGRNG_TX_BUF_REG 0
-#define MSGRNG_RX_BUF_REG 1
+#define	MSGRNG_TX_BUF_REG	0
+#define	MSGRNG_RX_BUF_REG	1
+#define	MSGRNG_MSG_STATUS_REG	2
+#define	MSGRNG_MSG_CONFIG_REG	3
+#define MSGRNG_MSG_BUCKSIZE_REG	4
 
-#define MSGRNG_MSG_STATUS_REG 2
-#define MSGRNG_MSG_CONFIG_REG 3
-
-#define MSGRNG_MSG_BUCKSIZE_REG 4
-
-#define MSGRNG_CC_0_REG  16
-#define MSGRNG_CC_1_REG  17
-#define MSGRNG_CC_2_REG  18
-#define MSGRNG_CC_3_REG  19
-#define MSGRNG_CC_4_REG  20
-#define MSGRNG_CC_5_REG  21
-#define MSGRNG_CC_6_REG  22
-#define MSGRNG_CC_7_REG  23
-#define MSGRNG_CC_8_REG  24
-#define MSGRNG_CC_9_REG  25
-#define MSGRNG_CC_10_REG 26
-#define MSGRNG_CC_11_REG 27
-#define MSGRNG_CC_12_REG 28
-#define MSGRNG_CC_13_REG 29
-#define MSGRNG_CC_14_REG 30
-#define MSGRNG_CC_15_REG 31
-
-#define msgrng_read_status() read_c2_register32(MSGRNG_MSG_STATUS_REG, 0)
-
-#define msgrng_read_config() read_c2_register32(MSGRNG_MSG_CONFIG_REG, 0)
-#define msgrng_write_config(value) write_c2_register32(MSGRNG_MSG_CONFIG_REG, 0, value)
-
-#define msgrng_read_bucksize(bucket) read_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, bucket)
-#define msgrng_write_bucksize(bucket, value) write_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, bucket, value)
-
-#define msgrng_read_cc(reg, pri) read_c2_register32(reg, pri)
-#define msgrng_write_cc(reg, value, pri) write_c2_register32(reg, pri, value)
-
-#define msgrng_load_rx_msg0() read_c2_register64(MSGRNG_RX_BUF_REG, 0)
-#define msgrng_load_rx_msg1() read_c2_register64(MSGRNG_RX_BUF_REG, 1)
-#define msgrng_load_rx_msg2() read_c2_register64(MSGRNG_RX_BUF_REG, 2)
-#define msgrng_load_rx_msg3() read_c2_register64(MSGRNG_RX_BUF_REG, 3)
-
-#define msgrng_load_tx_msg0(value) write_c2_register64(MSGRNG_TX_BUF_REG, 0, value)
-#define msgrng_load_tx_msg1(value) write_c2_register64(MSGRNG_TX_BUF_REG, 1, value)
-#define msgrng_load_tx_msg2(value) write_c2_register64(MSGRNG_TX_BUF_REG, 2, value)
-#define msgrng_load_tx_msg3(value) write_c2_register64(MSGRNG_TX_BUF_REG, 3, value)
+#define	MSGRNG_CC_0_REG	16
+#define	MSGRNG_CC_1_REG	17
+#define	MSGRNG_CC_2_REG	18
+#define	MSGRNG_CC_3_REG	19
+#define	MSGRNG_CC_4_REG	20
+#define	MSGRNG_CC_5_REG	21
+#define	MSGRNG_CC_6_REG	22
+#define	MSGRNG_CC_7_REG	23
+#define	MSGRNG_CC_8_REG	24
+#define	MSGRNG_CC_9_REG	25
+#define	MSGRNG_CC_10_REG	26
+#define	MSGRNG_CC_11_REG	27
+#define	MSGRNG_CC_12_REG	28
+#define	MSGRNG_CC_13_REG	29
+#define	MSGRNG_CC_14_REG	30
+#define	MSGRNG_CC_15_REG	31
 
 /* Station IDs */
 #define MSGRNG_STNID_CPU0  0x00
@@ -189,54 +171,26 @@
 #define MSGRNG_CODE_SEC 0
 #define MSGRNG_CODE_BOOT_WAKEUP 200
 #define MSGRNG_CODE_SPI4 3
+#define msgrng_read_status() read_c2_register32(MSGRNG_MSG_STATUS_REG, 0)
 
-static inline int 
-msgrng_xgmac_stid_rfr(int id)
-{
-	return !id ? MSGRNG_STNID_XMAC0RFR : MSGRNG_STNID_XMAC1RFR;
-}
+#define msgrng_read_config() read_c2_register32(MSGRNG_MSG_CONFIG_REG, 0)
+#define msgrng_write_config(value) write_c2_register32(MSGRNG_MSG_CONFIG_REG, 0, value)
 
-static inline int 
-msgrng_xgmac_stid_jfr(int id)
-{
-	return !id ? MSGRNG_STNID_XMAC0JFR : MSGRNG_STNID_XMAC1JFR;
-}
+#define msgrng_read_bucksize(bucket) read_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, bucket)
+#define msgrng_write_bucksize(bucket, value) write_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, bucket, value)
 
-static inline int 
-msgrng_xgmac_stid_tx(int id)
-{
-	return !id ? MSGRNG_STNID_XMAC0_00_TX : MSGRNG_STNID_XMAC1_00_TX;
-}
+#define msgrng_read_cc(reg, pri) read_c2_register32(reg, pri)
+#define msgrng_write_cc(reg, value, pri) write_c2_register32(reg, pri, value)
 
-static inline int 
-msgrng_gmac_stid_rfr(int id)
-{
-	return (MSGRNG_STNID_GMACRFR_0);
-}
+#define msgrng_load_rx_msg0() read_c2_register64(MSGRNG_RX_BUF_REG, 0)
+#define msgrng_load_rx_msg1() read_c2_register64(MSGRNG_RX_BUF_REG, 1)
+#define msgrng_load_rx_msg2() read_c2_register64(MSGRNG_RX_BUF_REG, 2)
+#define msgrng_load_rx_msg3() read_c2_register64(MSGRNG_RX_BUF_REG, 3)
 
-static inline int 
-msgrng_gmac_stid_rfr_split_mode(int id)
-{
-	return ((id >> 1) ? MSGRNG_STNID_GMACRFR_1 : MSGRNG_STNID_GMACRFR_0);
-}
-
-static inline int 
-msgrng_gmac_stid_jfr(int id)
-{
-	return MSGRNG_STNID_GMACJFR_0;
-}
-
-static inline int 
-msgrng_gmac_stid_jfr_split_mode(int id)
-{
-	return ((id >> 1) ? MSGRNG_STNID_GMACJFR_1 : MSGRNG_STNID_GMACJFR_0);
-}
-
-static inline int 
-msgrng_gmac_stid_tx(int id)
-{
-	return (MSGRNG_STNID_GMACTX0 + id);
-}
+#define msgrng_load_tx_msg0(value) write_c2_register64(MSGRNG_TX_BUF_REG, 0, value)
+#define msgrng_load_tx_msg1(value) write_c2_register64(MSGRNG_TX_BUF_REG, 1, value)
+#define msgrng_load_tx_msg2(value) write_c2_register64(MSGRNG_TX_BUF_REG, 2, value)
+#define msgrng_load_tx_msg3(value) write_c2_register64(MSGRNG_TX_BUF_REG, 3, value)
 
 static inline void 
 msgrng_send(unsigned int stid)
@@ -280,30 +234,21 @@ msgrng_wait(unsigned int mask)
 	);
 }
 
-#define msgrng_enable(flags)                        \
-do {                                                \
-  __asm__ volatile (                                \
-		    ".set push\n\t"                 \
-		    ".set reorder\n\t"              \
-		    ".set noat\n\t"                 \
-		    "mfc0 %0, $12\n\t"              \
-		    "li  $8, 0x40000001\n\t"        \
-		    "or  $1, %0, $8\n\t"            \
-		    "xori $1, 1\n\t"                \
-		    ".set noreorder\n\t"            \
-		    "mtc0 $1, $12\n\t"              \
-		    ".set\tpop\n\t"                 \
-		    : "=r" (flags)                  \
-		    :                               \
-		    : "$8"                          \
-		    );                              \
-} while (0)
+static __inline uint32_t
+msgrng_access_enable(void)
+{
+	uint32_t sr = mips_rd_status();
 
-#define msgrng_disable(flags) __asm__ volatile (    \
-                 "mtc0 %0, $12" : : "r" (flags))
+	mips_wr_status((sr & ~MIPS_SR_INT_IE) | MIPS_SR_COP_2_BIT);
+	return (sr);
+}
 
-#define msgrng_flags_save(flags) msgrng_enable(flags)
-#define msgrng_flags_restore(flags) msgrng_disable(flags)
+static __inline void
+msgrng_restore(uint32_t sr)
+{
+
+	mips_wr_status(sr);
+}
 
 struct msgrng_msg {
 	__uint64_t msg0;
@@ -355,7 +300,7 @@ message_send_block_fast(int size, unsigned int code, unsigned int stid,
            _tmp;                                                \
         } )
 
-static __inline__ int 
+static __inline int 
 message_send(unsigned int size, unsigned int code,
     unsigned int stid, struct msgrng_msg *msg)
 {
@@ -369,42 +314,35 @@ message_send(unsigned int size, unsigned int code,
 	msgrng_load_tx_msg3(msg->msg3);
 
 	dest = ((size - 1) << 16) | (code << 8) | (stid);
-
 	msgrng_send(dest);
 
-	for (i = 0; i < 16; i++) {
+	/* Wait for the thread pending to clear */
+	do {
 		status = msgrng_read_status();
+		KASSERT(i++ < 10000, ("Too many fails\n"));
+	} while ((status & 0x2) != 0);
 
-		if (status & 0x6) {
-			continue;
-		} else
-			break;
-	}
-	return msgrng_read_status() & 0x06;
+	/* If there is a credit failure, return error */
+	return status & 0x06;
 }
 
-static __inline__ int 
+static __inline int 
 message_send_retry(unsigned int size, unsigned int code,
     unsigned int stid, struct msgrng_msg *msg)
 {
-	int res = 0;
-	int retry = 0;
+	int i, ret;
 
-	for (;;) {
-		res = message_send(size, code, stid, msg);
-		/* retry a pending fail */
-		if (res & 0x02)
-			continue;
-		/* credit fail */
-		if (res & 0x04)
-			retry++;
-		else
-			break;
-		if (retry == 4)
-			return res & 0x06;
+	/*
+	 * we are in with interrupt disabled, retrying too many 
+	 * times is not good
+	 */
+	for (i = 0; i < 16; i++) {
+		ret = message_send(size, code, stid, msg);
+		if (ret == 0)
+			return (0);
 	}
 
-	return 0;
+	return (1);
 }
 
 static __inline__ int 
@@ -457,27 +395,6 @@ extern struct stn_cc xls_cc_table_pcie;
 extern struct stn_cc xls_cc_table_dma;
 extern struct stn_cc xls_cc_table_sec;
 
-
-#define msgrng_access_save(lock, mflags) do {                \
-  mtx_lock_spin(lock);                                       \
-  msgrng_flags_save(mflags);                                 \
- }while(0)
-
-#define msgrng_access_restore(lock, mflags) do {             \
-  msgrng_flags_restore(mflags);                              \
-  mtx_unlock_spin(lock);                                     \
- }while(0)
-
-#define msgrng_access_enable(mflags) do {   \
-  critical_enter();                         \
-  msgrng_flags_save(mflags);                \
-} while(0)
-
-#define msgrng_access_disable(mflags) do {   \
-  msgrng_flags_restore(mflags);              \
-  critical_exit();                           \
-} while(0)
-
 /*
  * NOTE: this is not stationid/8, ie the station numbers below are just
  * for internal use
@@ -504,14 +421,10 @@ enum {
 	MAX_TX_STNS
 };
 
-extern int 
-register_msgring_handler(int major,
+extern int register_msgring_handler(int major,
     void (*action) (int, int, int, int, struct msgrng_msg *, void *),
     void *dev_id);
-	extern void xlr_msgring_cpu_init(void);
-
-	extern void xlr_msgring_config(void);
-
-#define cpu_to_msgring_bucket(cpu) ((((cpu) >> 2)<<3)|((cpu) & 0x03))
+extern void xlr_msgring_cpu_init(void);
+extern void xlr_msgring_config(void);
 
 #endif

From 0dfddf6e653d4c1b6149b8110c010d9587f3e1f9 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Wed, 8 Sep 2010 16:58:06 +0000
Subject: [PATCH 0550/1624] Fix a typo in the original import of this code from
 NetBSD that caused the wrong element of the VSID bitmap array to be examined
 after a collision, leading to reallocation of in-use VSIDs under some
 circumstances, with attendant memory corruption. Also add an assert to check
 for this kind of problem in the future.

MFC after:	4 days
---
 sys/powerpc/aim/mmu_oea.c   | 2 +-
 sys/powerpc/aim/mmu_oea64.c | 4 +++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea.c b/sys/powerpc/aim/mmu_oea.c
index d3a24598942..2ade00ffdfc 100644
--- a/sys/powerpc/aim/mmu_oea.c
+++ b/sys/powerpc/aim/mmu_oea.c
@@ -1618,7 +1618,7 @@ moea_pinit(mmu_t mmu, pmap_t pmap)
 				entropy = (moea_vsidcontext >> 20);
 				continue;
 			}
-			i = ffs(~moea_vsid_bitmap[i]) - 1;
+			i = ffs(~moea_vsid_bitmap[n]) - 1;
 			mask = 1 << i;
 			hash &= 0xfffff & ~(VSID_NBPW - 1);
 			hash |= i;
diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index c1b6f2c7b7e..8cf83492836 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -2080,11 +2080,13 @@ moea64_get_unique_vsid(void) {
 				entropy = (moea64_vsidcontext >> 20);
 				continue;
 			}
-			i = ffs(~moea64_vsid_bitmap[i]) - 1;
+			i = ffs(~moea64_vsid_bitmap[n]) - 1;
 			mask = 1 << i;
 			hash &= VSID_HASHMASK & ~(VSID_NBPW - 1);
 			hash |= i;
 		}
+		KASSERT(!(moea64_vsid_bitmap[n] & mask),
+		    ("Allocating in-use VSID %#x\n", hash));
 		moea64_vsid_bitmap[n] |= mask;
 		mtx_unlock(&moea64_slb_mutex);
 		return (hash);

From b28fc1b5c8a027cfe9d3936bd62d9c81e853b79b Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 8 Sep 2010 16:59:22 +0000
Subject: [PATCH 0551/1624] During SMP startup there is time window, when SMP
 started, but interrupts are still bound to BSP. It confuses timer management
 logic in per-CPU mode and may cause timer not being reloaded. Check such
 cases on interrupt arival and reload timer to give system some more time to
 manage proper binding.

---
 sys/dev/acpica/acpi_hpet.c | 27 ++++++++++++++++++++++++++-
 1 file changed, 26 insertions(+), 1 deletion(-)

diff --git a/sys/dev/acpica/acpi_hpet.c b/sys/dev/acpica/acpi_hpet.c
index cf1c4906411..656a395f40d 100644
--- a/sys/dev/acpica/acpi_hpet.c
+++ b/sys/dev/acpica/acpi_hpet.c
@@ -89,6 +89,8 @@ struct hpet_softc {
 		int			mode;
 		int			intr_rid;
 		int			irq;
+		int			pcpu_cpu;
+		int			pcpu_misrouted;
 		int			pcpu_master;
 		int			pcpu_slaves[MAXCPU];
 		struct resource		*intr_res;
@@ -185,7 +187,7 @@ restart:
 	if (fdiv < 5000) {
 		bus_read_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num));
 		t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
-		if ((int32_t)(t->last - cmp) < 0) {
+		if ((int32_t)(t->last - cmp) >= 0) {
 			fdiv *= 2;
 			goto restart;
 		}
@@ -215,6 +217,26 @@ hpet_intr_single(void *arg)
 	struct hpet_softc *sc = t->sc;
 	uint32_t now;
 
+	/* Check that per-CPU timer interrupt reached right CPU. */
+	if (t->pcpu_cpu >= 0 && t->pcpu_cpu != curcpu) {
+		if ((++t->pcpu_misrouted) % 32 == 0) {
+			printf("HPET interrupt routed to the wrong CPU"
+			    " (timer %d CPU %d -> %d)!\n",
+			    t->num, t->pcpu_cpu, curcpu);
+		}
+
+		/*
+		 * Reload timer, hoping that next time may be more lucky
+		 * (system will manage proper interrupt binding).
+		 */
+		if ((t->mode == 1 && (t->caps & HPET_TCAP_PER_INT) == 0) ||
+		    t->mode == 2) {
+			t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
+			    t->last + sc->freq / 8);
+		}
+		return (FILTER_HANDLED);
+	}
 	if (t->mode == 1 &&
 	    (t->caps & HPET_TCAP_PER_INT) == 0) {
 		t->last += t->div;
@@ -394,6 +416,8 @@ hpet_attach(device_t dev)
 		t->mode = 0;
 		t->intr_rid = -1;
 		t->irq = -1;
+		t->pcpu_cpu = -1;
+		t->pcpu_misrouted = 0;
 		t->pcpu_master = -1;
 		t->caps = bus_read_4(sc->mem_res, HPET_TIMER_CAP_CNF(i));
 		t->vectors = bus_read_4(sc->mem_res, HPET_TIMER_CAP_CNF(i) + 4);
@@ -534,6 +558,7 @@ hpet_attach(device_t dev)
 		if (t->irq >= 0 && num_percpu_t > 0) {
 			if (cur_cpu == CPU_FIRST())
 				pcpu_master = i;
+			t->pcpu_cpu = cur_cpu;
 			t->pcpu_master = pcpu_master;
 			sc->t[pcpu_master].
 			    pcpu_slaves[cur_cpu] = i;

From 8f8ae306c6ed2e97ec73f8f3ccf488984fe04971 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Wed, 8 Sep 2010 17:11:49 +0000
Subject: [PATCH 0552/1624] nlge (alternate XLR GMAC driver) updates:

- Updates for the message ring clean up in r212321.
- Instead of dropping Tx packet on credit fail, retry send until it
  succeeds.
- Fix freeing mbufs in case of P2P descriptors:
  We cannot free the mbuf when the P2P descriptor freeback is received. The
  mbuf may be still in use by the GMAC, since the P2P freeback indicates that
  it read the P2D descriptors in the P2P message.
  Now we free just the P2P descriptor when the P2P freeback message is
  received.  Another freeback P2D message has been added to the end of
  the packet descriptors, the mbuf will be freed only when we received
  this.

The P2P descriptor issue was reported by srgorti at netlogicmicro dot com.
---
 sys/mips/rmi/dev/nlge/if_nlge.c | 95 ++++++++++++++++-----------------
 1 file changed, 45 insertions(+), 50 deletions(-)

diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
index 746023020cf..8cb97bf6645 100644
--- a/sys/mips/rmi/dev/nlge/if_nlge.c
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -207,7 +207,7 @@ static int	prepare_fmn_message(struct nlge_softc *sc,
     uint64_t fr_stid, struct nlge_tx_desc **tx_desc);
 
 static void	release_mbuf(uint64_t phy_addr);
-static void 	release_tx_desc(struct msgrng_msg *msg);
+static void 	release_tx_desc(vm_paddr_t phy_addr);
 static int	send_fmn_msg_tx(struct nlge_softc *, struct msgrng_msg *,
     uint32_t n_entries);
 
@@ -637,7 +637,7 @@ nlge_msgring_handler(int bucket, int size, int code, int stid,
 	struct nlna_softc *na_sc;
 	struct nlge_softc *sc;
 	struct ifnet   *ifp;
-	uint64_t	phys_addr;
+	vm_paddr_t	phys_addr;
 	unsigned long	addr;
 	uint32_t	length;
 	int		ctrl;
@@ -655,14 +655,15 @@ nlge_msgring_handler(int bucket, int size, int code, int stid,
 	tx_error = 0;
 	length = (msg->msg0 >> 40) & 0x3fff;
 	na_sc = (struct nlna_softc *)data;
-	phys_addr = (uint64_t) (msg->msg0 & 0xffffffffe0ULL);
 	if (length == 0) {
 		ctrl = CTRL_REG_FREE;
+		phys_addr = msg->msg0 & 0xffffffffffULL;
 		port = (msg->msg0 >> 54) & 0x0f;
 		is_p2p = (msg->msg0 >> 62) & 0x1;
 		tx_error = (msg->msg0 >> 58) & 0xf;
 	} else {
 		ctrl = CTRL_SNGL;
+		phys_addr = msg->msg0 & 0xffffffffe0ULL;
 		length = length - BYTE_OFFSET - MAC_CRC_LEN;
 		port = msg->msg0 & 0x0f;
 	}
@@ -676,11 +677,12 @@ nlge_msgring_handler(int bucket, int size, int code, int stid,
 	}
 
 	if (ctrl == CTRL_REG_FREE || ctrl == CTRL_JUMBO_FREE) {
-		if (is_p2p)
-			release_tx_desc(msg);
-		else {
-			release_mbuf(msg->msg0 & 0xffffffffffULL);
+		if (is_p2p) {
+			release_tx_desc(phys_addr);
+		} else {
+			release_mbuf(phys_addr);
 		}
+
 		ifp = sc->nlge_if;
 		if (ifp->if_drv_flags & IFF_DRV_OACTIVE){
 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
@@ -742,7 +744,7 @@ nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc)
 			goto fail;
 		}
 		sent = send_fmn_msg_tx(sc, &msg, n_entries);
-		if (!sent) {
+		if (sent != 0) {
 			goto fail;
 		}
 	} while(1);
@@ -1011,28 +1013,27 @@ static __inline__ int
 nlna_send_free_desc(struct nlna_softc *sc, vm_paddr_t addr)
 {
 	struct msgrng_msg msg;
-	int	stid;
-	int	code;
-	int 	i;
+	uint32_t msgrng_flags;
+	int i = 0, stid, code, ret;
 
 	stid = sc->rfrbucket;
 	memset(&msg, 0, sizeof(msg));
 	msg.msg0 = (uint64_t) addr & 0xffffffffe0ULL;
 
 	code = (sc->na_type == XLR_XGMAC) ? MSGRNG_CODE_XGMAC : MSGRNG_CODE_MAC;
-	for (i = 0; i < MAX_MSG_SND_ATTEMPTS; i++) {
-		if (message_send(1, code, stid, &msg) == 0)
-			return (0);
-	}
-	printf("Error: failed to send free desc to station %d\n", stid);
-	return (1);
+	do {
+		msgrng_flags = msgrng_access_enable();
+		ret = message_send_retry(1, code, stid, &msg);
+		msgrng_restore(msgrng_flags);
+		KASSERT(i++ < 100000, ("Too many credit fails\n"));
+	} while (ret != 0);
+	return (0);
 }
 
 static void
 nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc)
 {
 	void           *ptr;
-	unsigned long	msgrng_flags;
 	int		i;
 	int		ret;
 
@@ -1050,10 +1051,8 @@ nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc)
 		}
 
 		/* Send the free Rx desc to the MAC */
-		msgrng_access_enable(msgrng_flags);
 		ret = nlna_send_free_desc(sc, vtophys(ptr));
-		msgrng_access_disable(msgrng_flags);
-		if (ret)  /* no point trying other descriptors after
+		if (ret != 0)  /* no point trying other descriptors after
 		             a failure. */
 			break;
 	}
@@ -1907,9 +1906,10 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg,
 
 		while (len) {
 			if (msg_sz == (FMN_SZ - 1)) {
-				p2p = uma_zalloc(nl_tx_desc_zone, M_WAITOK);
-				if (p2p == NULL)
+				p2p = uma_zalloc(nl_tx_desc_zone, M_NOWAIT);
+				if (p2p == NULL) {
 					return 2;
+				}
 				/*
 				 * As we currently use xlr_paddr_lw on a 32-bit
 				 * OS, both the pointers are laid out in one
@@ -1922,7 +1922,7 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg,
 				    ((vm_offset_t) mbuf_chain);
 				cur_p2d = &p2p->frag[0];
 				is_p2p = 1;
-			} else if (msg_sz == (FMN_SZ - 1 + XLR_MAX_TX_FRAGS)) {
+			} else if (msg_sz == (FMN_SZ - 2 + XLR_MAX_TX_FRAGS)) {
 				uma_zfree(nl_tx_desc_zone, p2p);
 				return 1;
 			}
@@ -1940,26 +1940,24 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg,
 		}
 	}
 
-	if (msg_sz > 0) {
-		cur_p2d[-1] |= (1ULL << 63); /* set eop in most-recent p2d */
-	} else {
+	if (msg_sz ==  0) {
 		printf("Zero-length mbuf chain ??\n");
 		*n_entries = msg_sz ;
 		return 0;
 	}
 
+	cur_p2d[-1] |= (1ULL << 63); /* set eop in most-recent p2d */
+	*cur_p2d = (1ULL << 63) | ((uint64_t)fb_stn_id << 54) |
+	     (vm_offset_t) mbuf_chain;
 	*tx_desc = p2p;
 
 	if (is_p2p) {
 		paddr = vtophys(p2p);
-		fmn_msg->msg3 = (1ULL << 63) | (1ULL << 62) |
-		    ((uint64_t)fb_stn_id << 54) |
+		p2p_sz++;
+		fmn_msg->msg3 = (1ULL << 62) | ((uint64_t)fb_stn_id << 54) |
 		    ((uint64_t)(p2p_sz * 8) << 40) | paddr;
 		*n_entries = FMN_SZ;
 	} else {
-		/* zero-len p2d */
-		*cur_p2d = (1ULL << 63) | ((uint64_t)fb_stn_id << 54) |
-		     (vm_offset_t) mbuf_chain;
 		*n_entries = msg_sz + 1;
 	}
 
@@ -1970,15 +1968,17 @@ static int
 send_fmn_msg_tx(struct nlge_softc *sc, struct msgrng_msg *msg,
     uint32_t n_entries)
 {
-	unsigned long mflags;
-	int ret;
+	uint32_t msgrng_flags;
+	int i = 0, ret;
 
-	mflags = 0;
-	msgrng_access_enable(mflags);
-	ret = message_send_retry(n_entries, MSGRNG_CODE_MAC, sc->tx_bucket_id,
-	    msg);
-	msgrng_access_disable(mflags);
-	return (!ret);
+	do {
+		msgrng_flags = msgrng_access_enable();
+		ret = message_send_retry(n_entries, MSGRNG_CODE_MAC,
+		    sc->tx_bucket_id, msg);
+		msgrng_restore(msgrng_flags);
+		KASSERT(i++ < 100000, ("Too many credit fails\n"));
+	} while (ret != 0);
+	return (0);
 }
 
 static void
@@ -1991,25 +1991,20 @@ release_mbuf(uint64_t phy_addr)
 }
 
 static void
-release_tx_desc(struct msgrng_msg *msg)
+release_tx_desc(vm_paddr_t paddr)
 {
-	vm_paddr_t	paddr;
-	uint64_t	temp;
 	struct nlge_tx_desc *tx_desc;
-	struct mbuf	*m;
 	uint32_t 	sr;
+	uint32_t	val1, val2;
 
-	paddr = msg->msg0 & 0xffffffffffULL;
 	paddr += (XLR_MAX_TX_FRAGS * sizeof(uint64_t));
 	sr = xlr_enable_kx();
-	temp = xlr_paddr_lw(paddr);
-	tx_desc = (struct nlge_tx_desc*)((intptr_t) temp);
+	val1 = xlr_paddr_lw(paddr);
 	paddr += sizeof(void *);
-	temp = xlr_paddr_lw(paddr);
+	val2 = xlr_paddr_lw(paddr);
 	mips_wr_status(sr);
-	m = (struct mbuf *)((intptr_t) temp);
-	m_freem(m);
 
+	tx_desc = (struct nlge_tx_desc*)(intptr_t) val1;
 	uma_zfree(nl_tx_desc_zone, tx_desc);
 }
 

From 3b0620e06cbcdbbcb22b9b68edc0b0ea823477b1 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 8 Sep 2010 17:35:06 +0000
Subject: [PATCH 0553/1624] subr_bus: use hexadecimal representation for bit
 flags

It seems that this format is more custom in our code, and it is more
convenient too.

Suggested by:	jhb
No objection:	imp
MFC after:	1 week
---
 sys/kern/subr_bus.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/sys/kern/subr_bus.c b/sys/kern/subr_bus.c
index 8714b5f0c7a..9912d980383 100644
--- a/sys/kern/subr_bus.c
+++ b/sys/kern/subr_bus.c
@@ -122,14 +122,14 @@ struct device {
 	device_state_t	state;		/**< current device state  */
 	uint32_t	devflags;	/**< api level flags for device_get_flags() */
 	u_int		flags;		/**< internal device flags  */
-#define	DF_ENABLED	1		/* device should be probed/attached */
-#define	DF_FIXEDCLASS	2		/* devclass specified at create time */
-#define	DF_WILDCARD	4		/* unit was originally wildcard */
-#define	DF_DESCMALLOCED	8		/* description was malloced */
-#define	DF_QUIET	16		/* don't print verbose attach message */
-#define	DF_DONENOMATCH	32		/* don't execute DEVICE_NOMATCH again */
-#define	DF_EXTERNALSOFTC 64		/* softc not allocated by us */
-#define	DF_REBID	128		/* Can rebid after attach */
+#define	DF_ENABLED	0x01		/* device should be probed/attached */
+#define	DF_FIXEDCLASS	0x02		/* devclass specified at create time */
+#define	DF_WILDCARD	0x04		/* unit was originally wildcard */
+#define	DF_DESCMALLOCED	0x08		/* description was malloced */
+#define	DF_QUIET	0x10		/* don't print verbose attach message */
+#define	DF_DONENOMATCH	0x20		/* don't execute DEVICE_NOMATCH again */
+#define	DF_EXTERNALSOFTC 0x40		/* softc not allocated by us */
+#define	DF_REBID	0x80		/* Can rebid after attach */
 	u_int	order;			/**< order from device_add_child_ordered() */
 	void	*ivars;			/**< instance variables  */
 	void	*softc;			/**< current driver's variables  */

From 79c2de35b58632bfe488a9e00bd9c7d3d02c5b2b Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Wed, 8 Sep 2010 17:53:34 +0000
Subject: [PATCH 0554/1624] - Add register definitions related to extended
 capability IDs in   PCI-express.  I used PCIZ_* for ID constants (plain
 capability IDs use   PCIY_*). - Add register definitions for the Advanced
 Error Reporting, Virtual   Channels, and Device Serial Number extended
 capabilities. - Teach pciconf -c to list extended as well as plain
 capabilities.   Adds   more detailed parsing for AER, VC, and device serial
 numbers.

MFC after:	2 weeks
---
 sys/dev/pci/pcireg.h   | 84 +++++++++++++++++++++++++++++++++++++
 usr.sbin/pciconf/cap.c | 95 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 179 insertions(+)

diff --git a/sys/dev/pci/pcireg.h b/sys/dev/pci/pcireg.h
index 5c747ec5350..382f15a1259 100644
--- a/sys/dev/pci/pcireg.h
+++ b/sys/dev/pci/pcireg.h
@@ -36,6 +36,7 @@
  * PCIV_xxx: PCI vendor ID (only required to fixup ancient devices)
  * PCID_xxx: device ID
  * PCIY_xxx: capability identification number
+ * PCIZ_xxx: extended capability identification number
  */
 
 /* some PCI bus constants */
@@ -117,6 +118,28 @@
 #define	PCIY_SATA	0x12	/* SATA */
 #define	PCIY_PCIAF	0x13	/* PCI Advanced Features */
 
+/* Extended Capability Register Fields */
+
+#define	PCIR_EXTCAP	0x100
+#define	PCIM_EXTCAP_ID		0x0000ffff
+#define	PCIM_EXTCAP_VER		0x000f0000
+#define	PCIM_EXTCAP_NEXTPTR	0xfff00000
+#define	PCI_EXTCAP_ID(ecap)	((ecap) & PCIM_EXTCAP_ID)
+#define	PCI_EXTCAP_VER(ecap)	(((ecap) & PCIM_EXTCAP_VER) >> 16)
+#define	PCI_EXTCAP_NEXTPTR(ecap) (((ecap) & PCIM_EXTCAP_NEXTPTR) >> 20)
+
+/* Extended Capability Identification Numbers */
+
+#define	PCIZ_AER	0x0001	/* Advanced Error Reporting */
+#define	PCIZ_VC		0x0002	/* Virtual Channel */
+#define	PCIZ_SERNUM	0x0003	/* Device Serial Number */
+#define	PCIZ_PWRBDGT	0x0004	/* Power Budgeting */
+#define	PCIZ_VENDOR	0x000b	/* Vendor Unique */
+#define	PCIZ_ACS	0x000d	/* Access Control Services */
+#define	PCIZ_ARI	0x000e	/* Alternative Routing-ID Interpretation */
+#define	PCIZ_ATS	0x000f	/* Address Translation Services */
+#define	PCIZ_SRIOV	0x0010	/* Single Root IO Virtualization */
+
 /* config registers for header type 0 devices */
 
 #define	PCIR_BARS	0x10
@@ -663,3 +686,64 @@
 #define	PCIR_PCIAFCTRL_FLR	0x01
 #define	PCIR_PCIAF_STATUS	0x5
 #define	PCIR_PCIAFSTATUS_TP	0x01
+
+/* Advanced Error Reporting */
+#define	PCIR_AER_UC_STATUS	0x04
+#define	PCIR_AER_UC_TRAINING_ERROR	0x00000001
+#define	PCIR_AER_UC_DL_PROTOCOL_ERROR	0x00000010
+#define	PCIR_AER_UC_POISONED_TLP	0x00001000
+#define	PCIR_AER_UC_FC_PROTOCOL_ERROR	0x00002000
+#define	PCIR_AER_UC_COMPLETION_TIMEOUT	0x00004000
+#define	PCIR_AER_UC_COMPLETER_ABORT	0x00008000
+#define	PCIR_AER_UC_UNEXPECTED_COMPLETION 0x00010000
+#define	PCIR_AER_UC_RECEIVER_OVERFLOW	0x00020000
+#define	PCIR_AER_UC_MALFORMED_TLP	0x00040000
+#define	PCIR_AER_UC_ECRC_ERROR		0x00080000
+#define	PCIR_AER_UC_UNSUPPORTED_REQUEST	0x00100000
+#define	PCIR_AER_UC_ACS_VIOLATION	0x00200000
+#define	PCIR_AER_UC_MASK	0x08	/* Shares bits with UC_STATUS */
+#define	PCIR_AER_UC_SEVERITY	0x0c	/* Shares bits with UC_STATUS */
+#define	PCIR_AER_COR_STATUS	0x10
+#define	PCIM_AER_COR_RECEIVER_ERROR	0x00000001
+#define	PCIM_AER_COR_BAD_TLP		0x00000040
+#define	PCIM_AER_COR_BAD_DLLP		0x00000080
+#define	PCIM_AER_COR_REPLAY_ROLLOVER	0x00000100
+#define	PCIM_AER_COR_REPLAY_TIMEOUT	0x00001000
+#define	PCIR_AER_COR_MASK	0x14	/* Shares bits with COR_STATUS */
+#define	PCIR_AER_CAP_CONTROL	0x18
+#define	PCIM_AER_FIRST_ERROR_PTR	0x0000001f
+#define	PCIM_AER_ECRC_GEN_CAPABLE	0x00000020
+#define	PCIM_AER_ECRC_GEN_ENABLE	0x00000040
+#define	PCIM_AER_ECRC_CHECK_CAPABLE	0x00000080
+#define	PCIM_AER_ECRC_CHECK_ENABLE	0x00000100
+#define	PCIR_AER_HEADER_LOG	0x1c
+#define	PCIR_AER_ROOTERR_CMD	0x2c	/* Only for root complex ports */
+#define	PCIR_AER_ROOTERR_COR_ENABLE	0x00000001
+#define	PCIR_AER_ROOTERR_NF_ENABLE	0x00000002
+#define	PCIR_AER_ROOTERR_F_ENABLE	0x00000004
+#define	PCIR_AER_ROOTERR_STATUS	0x30	/* Only for root complex ports */
+#define	PCIR_AER_ROOTERR_COR_ERR	0x00000001
+#define	PCIR_AER_ROOTERR_MULTI_COR_ERR	0x00000002
+#define	PCIR_AER_ROOTERR_UC_ERR		0x00000004
+#define	PCIR_AER_ROOTERR_MULTI_UC_ERR	0x00000008
+#define	PCIR_AER_ROOTERR_FIRST_UC_FATAL	0x00000010
+#define	PCIR_AER_ROOTERR_NF_ERR		0x00000020
+#define	PCIR_AER_ROOTERR_F_ERR		0x00000040
+#define	PCIR_AER_ROOTERR_INT_MESSAGE	0xf8000000
+#define	PCIR_AER_COR_SOURCE_ID	0x34	/* Only for root complex ports */
+#define	PCIR_AER_ERR_SOURCE_ID	0x36	/* Only for root complex ports */
+
+/* Virtual Channel definitions */
+#define	PCIR_VC_CAP1		0x04
+#define	PCIM_VC_CAP1_EXT_COUNT		0x00000007
+#define	PCIM_VC_CAP1_LOWPRI_EXT_COUNT	0x00000070
+#define	PCIR_VC_CAP2		0x08
+#define	PCIR_VC_CONTROL		0x0C
+#define	PCIR_VC_STATUS		0x0E
+#define	PCIR_VC_RESOURCE_CAP(n)	(0x10 + (n) * 0x0C)
+#define	PCIR_VC_RESOURCE_CTL(n)	(0x14 + (n) * 0x0C)
+#define	PCIR_VC_RESOURCE_STA(n)	(0x18 + (n) * 0x0C)
+
+/* Serial Number definitions */
+#define	PCIR_SERIAL_LOW		0x04
+#define	PCIR_SERIAL_HIGH	0x08
diff --git a/usr.sbin/pciconf/cap.c b/usr.sbin/pciconf/cap.c
index 473ed01c3e8..f3243217796 100644
--- a/usr.sbin/pciconf/cap.c
+++ b/usr.sbin/pciconf/cap.c
@@ -45,6 +45,8 @@ static const char rcsid[] =
 
 #include "pciconf.h"
 
+static void	list_ecaps(int fd, struct pci_conf *p);
+
 static void
 cap_power(int fd, struct pci_conf *p, uint8_t ptr)
 {
@@ -530,4 +532,97 @@ list_caps(int fd, struct pci_conf *p)
 		printf("\n");
 		ptr = read_config(fd, &p->pc_sel, ptr + PCICAP_NEXTPTR, 1);
 	}
+
+	list_ecaps(fd, p);
+}
+
+/* From . */
+static __inline uint32_t
+bitcount32(uint32_t x)
+{
+
+	x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1);
+	x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2);
+	x = (x + (x >> 4)) & 0x0f0f0f0f;
+	x = (x + (x >> 8));
+	x = (x + (x >> 16)) & 0x000000ff;
+	return (x);
+}
+
+static void
+ecap_aer(int fd, struct pci_conf *p, uint16_t ptr, uint8_t ver)
+{
+	uint32_t sta, mask;
+
+	printf("AER %d", ver);
+	if (ver != 1)
+		return;
+	sta = read_config(fd, &p->pc_sel, ptr + PCIR_AER_UC_STATUS, 4);
+	mask = read_config(fd, &p->pc_sel, ptr + PCIR_AER_UC_SEVERITY, 4);
+	printf(" %d fatal", bitcount32(sta & mask));
+	printf(" %d non-fatal", bitcount32(sta & ~mask));
+	sta = read_config(fd, &p->pc_sel, ptr + PCIR_AER_COR_STATUS, 4);
+	printf(" %d corrected", bitcount32(sta));
+}
+
+static void
+ecap_vc(int fd, struct pci_conf *p, uint16_t ptr, uint8_t ver)
+{
+	uint32_t cap1;
+
+	printf("VC %d", ver);
+	if (ver != 1)
+		return;
+	cap1 = read_config(fd, &p->pc_sel, ptr + PCIR_VC_CAP1, 4);
+	printf(" max VC%d", cap1 & PCIM_VC_CAP1_EXT_COUNT);
+	if ((cap1 & PCIM_VC_CAP1_LOWPRI_EXT_COUNT) != 0)
+		printf(" lowpri VC0-VC%d",
+		    (cap1 & PCIM_VC_CAP1_LOWPRI_EXT_COUNT) >> 4);
+}
+
+static void
+ecap_sernum(int fd, struct pci_conf *p, uint16_t ptr, uint8_t ver)
+{
+	uint32_t high, low;
+
+	printf("Serial %d", ver);
+	if (ver != 1)
+		return;
+	low = read_config(fd, &p->pc_sel, ptr + PCIR_SERIAL_LOW, 4);
+	high = read_config(fd, &p->pc_sel, ptr + PCIR_SERIAL_HIGH, 4);
+	printf(" %08x%08x", high, low);
+}
+
+static void
+list_ecaps(int fd, struct pci_conf *p)
+{
+	uint32_t ecap;
+	uint16_t ptr;
+
+	ptr = PCIR_EXTCAP;
+	ecap = read_config(fd, &p->pc_sel, ptr, 4);
+	if (ecap == 0xffffffff || ecap == 0)
+		return;
+	for (;;) {
+		printf("ecap %04x[%03x] = ", PCI_EXTCAP_ID(ecap), ptr);
+		switch (PCI_EXTCAP_ID(ecap)) {
+		case PCIZ_AER:
+			ecap_aer(fd, p, ptr, PCI_EXTCAP_VER(ecap));
+			break;
+		case PCIZ_VC:
+			ecap_vc(fd, p, ptr, PCI_EXTCAP_VER(ecap));
+			break;
+		case PCIZ_SERNUM:
+			ecap_sernum(fd, p, ptr, PCI_EXTCAP_VER(ecap));
+			break;
+		default:
+			printf("unknown %d", PCI_EXTCAP_VER(ecap));
+			break;
+		}
+		printf("\n");
+		ptr = PCI_EXTCAP_NEXTPTR(ecap);
+		if (ptr == 0)
+			break;
+		ecap = read_config(fd, &p->pc_sel, ptr, 4);
+	}
 }

From 937a5e2c20be6c1e277869cd2a78f2f7fb2a5746 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Wed, 8 Sep 2010 18:18:01 +0000
Subject: [PATCH 0555/1624] Simplify chkattached().  The PCIOCATTACHED ioctl
 only needs the pi_sel field populated, it ignores the rest of the 'pci_sel'
 structure.

MFC after:	1 week
---
 usr.sbin/pciconf/pciconf.c | 10 +++-------
 1 file changed, 3 insertions(+), 7 deletions(-)

diff --git a/usr.sbin/pciconf/pciconf.c b/usr.sbin/pciconf/pciconf.c
index 7d1da2dd0cb..bb19160bc2c 100644
--- a/usr.sbin/pciconf/pciconf.c
+++ b/usr.sbin/pciconf/pciconf.c
@@ -75,7 +75,7 @@ static const char *guess_subclass(struct pci_conf *p);
 static int load_vendors(void);
 static void readit(const char *, const char *, int);
 static void writeit(const char *, const char *, const char *, int);
-static void chkattached(const char *, int);
+static void chkattached(const char *);
 
 static int exitstatus = 0;
 
@@ -148,8 +148,7 @@ main(int argc, char **argv)
 	if (listmode) {
 		list_devs(verbose, bars, caps);
 	} else if (attachedmode) {
-		chkattached(argv[optind],
-		    byte ? 1 : isshort ? 2 : 4);
+		chkattached(argv[optind]);
 	} else if (readmode) {
 		readit(argv[optind], argv[optind + 1],
 		    byte ? 1 : isshort ? 2 : 4);
@@ -646,15 +645,12 @@ writeit(const char *name, const char *reg, const char *data, int width)
 }
 
 static void
-chkattached(const char *name, int width)
+chkattached(const char *name)
 {
 	int fd;
 	struct pci_io pi;
 
 	pi.pi_sel = getsel(name);
-	pi.pi_reg = 0;
-	pi.pi_width = width;
-	pi.pi_data = 0;
 
 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
 	if (fd < 0)

From ad931dfdcb96076aa69f4f796364ca729b0f0372 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Wed, 8 Sep 2010 18:32:23 +0000
Subject: [PATCH 0556/1624] sh: Add simple tests for backslashes in the read
 builtin.

---
 tools/regression/bin/sh/builtins/read3.0        | 11 +++++++++++
 tools/regression/bin/sh/builtins/read3.0.stdout |  9 +++++++++
 2 files changed, 20 insertions(+)
 create mode 100644 tools/regression/bin/sh/builtins/read3.0
 create mode 100644 tools/regression/bin/sh/builtins/read3.0.stdout

diff --git a/tools/regression/bin/sh/builtins/read3.0 b/tools/regression/bin/sh/builtins/read3.0
new file mode 100644
index 00000000000..c6ae9c1023c
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/read3.0
@@ -0,0 +1,11 @@
+# $FreeBSD$
+
+printf '%s\n' 'a\ b c'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' 'a b\ c'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' 'a\:b:c'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' 'a:b\:c'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\ a'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\:a'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\\ a'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\\ a'	| { read -r a b; printf '%s\n' "x${a}x${b}x"; }
diff --git a/tools/regression/bin/sh/builtins/read3.0.stdout b/tools/regression/bin/sh/builtins/read3.0.stdout
new file mode 100644
index 00000000000..8ed98ca9d86
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/read3.0.stdout
@@ -0,0 +1,9 @@
+xa bxcx
+xaxb cx
+xa:bxcx
+xaxb:cx
+x axx
+x:axx
+x\xx
+x\ axx
+x\\\xax

From bcb478eb357e0357addf959b28c6fe3d79bcdcf0 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Wed, 8 Sep 2010 19:28:43 +0000
Subject: [PATCH 0557/1624] Fix a printf specifier on 64-bit systems.

---
 sys/powerpc/aim/mmu_oea64.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index 8cf83492836..a6aebdeeedc 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -2086,7 +2086,7 @@ moea64_get_unique_vsid(void) {
 			hash |= i;
 		}
 		KASSERT(!(moea64_vsid_bitmap[n] & mask),
-		    ("Allocating in-use VSID %#x\n", hash));
+		    ("Allocating in-use VSID %#zx\n", hash));
 		moea64_vsid_bitmap[n] |= mask;
 		mtx_unlock(&moea64_slb_mutex);
 		return (hash);

From 93dbfc78406da5ac59e05602c4ecc12be91e9ded Mon Sep 17 00:00:00 2001
From: Maksim Yevmenkin 
Date: Wed, 8 Sep 2010 19:50:47 +0000
Subject: [PATCH 0558/1624] Add custom kernel configuration and device tree
 source files for Seagate FreeAgent DockStar(tm) device. It seems to be a dumb
 down version of Marvell SheevaPlug. Device tree source file could use more
 tweaking, but at least it wll network boot and run FreeBSD/arm.

---
 sys/arm/conf/DOCKSTAR         |  76 ++++++++++
 sys/boot/fdt/dts/dockstar.dts | 265 ++++++++++++++++++++++++++++++++++
 2 files changed, 341 insertions(+)
 create mode 100644 sys/arm/conf/DOCKSTAR
 create mode 100644 sys/boot/fdt/dts/dockstar.dts

diff --git a/sys/arm/conf/DOCKSTAR b/sys/arm/conf/DOCKSTAR
new file mode 100644
index 00000000000..780cb78d4d6
--- /dev/null
+++ b/sys/arm/conf/DOCKSTAR
@@ -0,0 +1,76 @@
+#
+# Custom kernel for Seagate DockStar (Marvell SheevaPlug based) devices.
+#
+# $FreeBSD$
+#
+
+ident		DOCKSTAR
+include		"../mv/kirkwood/std.sheevaplug"
+
+options 	SOC_MV_KIRKWOOD
+makeoptions	MODULES_OVERRIDE=""
+
+#makeoptions	DEBUG=-g		#Build kernel with gdb(1) debug symbols
+makeoptions	WERROR="-Werror"
+
+options 	SCHED_4BSD		#4BSD scheduler
+options 	INET			#InterNETworking
+options 	INET6			#IPv6 communications protocols
+options 	FFS			#Berkeley Fast Filesystem
+options 	NFSCLIENT		#Network Filesystem Client
+options 	NFSLOCKD		#Network Lock Manager
+options 	NFS_ROOT		#NFS usable as /, requires NFSCLIENT
+options 	BOOTP
+options 	BOOTP_NFSROOT
+options 	BOOTP_NFSV3
+options 	BOOTP_COMPAT
+options 	BOOTP_WIRED_TO=mge0
+
+# Root fs on USB device
+#options        ROOTDEVNAME=\"ufs:/dev/da0a\"
+
+options 	SYSVSHM			#SYSV-style shared memory
+options 	SYSVMSG			#SYSV-style message queues
+options 	SYSVSEM			#SYSV-style semaphores
+options 	_KPOSIX_PRIORITY_SCHEDULING #Posix P1003_1B real-time extensions
+options 	MUTEX_NOINLINE
+options 	RWLOCK_NOINLINE
+options 	NO_FFS_SNAPSHOT
+options 	NO_SWAPPING
+
+# Debugging
+options 	ALT_BREAK_TO_DEBUGGER
+options 	DDB
+options 	KDB
+
+# Pseudo devices
+device		md
+device		random
+device		pty
+device		loop
+
+# Serial ports
+device		uart
+
+# Networking
+device		ether
+device		mge			# Marvell Gigabit Ethernet controller
+device		mii
+device		bpf
+options		HZ=1000
+options		DEVICE_POLLING
+device		vlan
+
+# USB
+options 	USB_DEBUG	# enable debug msgs
+device		usb
+device		ehci
+device		umass
+device		scbus
+device		pass
+device		da
+
+# Flattened Device Tree
+options 	FDT
+options		FDT_DTB_STATIC
+makeoptions	FDT_DTS_FILE=dockstar.dts
diff --git a/sys/boot/fdt/dts/dockstar.dts b/sys/boot/fdt/dts/dockstar.dts
new file mode 100644
index 00000000000..46981094e5d
--- /dev/null
+++ b/sys/boot/fdt/dts/dockstar.dts
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) 2010 The FreeBSD Foundation
+ * All rights reserved.
+ *
+ * This software was developed by Semihalf under sponsorship from
+ * the FreeBSD Foundation.
+ *
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ *
+ * Seagate DockStar (Marvell SheevaPlug based) Device Tree Source.
+ *
+ * $FreeBSD$
+ */
+
+/dts-v1/;
+
+/ {
+	model = "seagate,DockStar";
+	compatible = "DockStar";
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	aliases {
+		ethernet0 = &enet0;
+		mpp = &MPP;
+		serial0 = &serial0;
+		serial1 = &serial1;
+		soc = &SOC;
+		sram = &SRAM;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		cpu@0 {
+			device_type = "cpu";
+			compatible = "ARM,88FR131";
+			reg = <0x0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x4000>;	// L1, 16K
+			i-cache-size = <0x4000>;	// L1, 16K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x8000000>;		// 128M at 0x0
+	};
+
+	localbus@f1000000 {
+		#address-cells = <2>;
+		#size-cells = <1>;
+		compatible = "mrvl,lbc";
+
+		/* This reflects CPU decode windows setup. */
+		ranges = <0x0 0x0f 0xf9300000 0x00100000
+			  0x1 0x1e 0xfa000000 0x00100000
+			  0x2 0x1d 0xfa100000 0x02000000
+			  0x3 0x1b 0xfc100000 0x00000400>;
+
+		nor@0,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "cfi-flash";
+			reg = <0x0 0x0 0x00100000>;
+			bank-width = <2>;
+			device-width = <1>;
+		};
+
+		led@1,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "led";
+			reg = <0x1 0x0 0x00100000>;
+		};
+
+		nor@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "cfi-flash";
+			reg = <0x2 0x0 0x02000000>;
+			bank-width = <2>;
+			device-width = <1>;
+		};
+
+		nand@3,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			reg = <0x3 0x0 0x00100000>;
+			bank-width = <2>;
+			device-width = <1>;
+		};
+	};
+
+	SOC: soc88f6281@f1000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		compatible = "simple-bus";
+		ranges = <0x0 0xf1000000 0x00100000>;
+		bus-frequency = <0>;
+
+		PIC: pic@20200 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <1>;
+			reg = <0x20200 0x3c>;
+			compatible = "mrvl,pic";
+		};
+
+		timer@20300 {
+			compatible = "mrvl,timer";
+			reg = <0x20300 0x30>;
+			interrupts = <1>;
+			interrupt-parent = <&PIC>;
+			mrvl,has-wdt;
+		};
+
+		MPP: mpp@10000 {
+			#pin-cells = <2>;
+			compatible = "mrvl,mpp";
+			reg = <0x10000 0x34>;
+			pin-count = <50>;
+			pin-map = <
+				0  1		/* MPP[0]:  NF_IO[2] */
+				1  1		/* MPP[1]:  NF_IO[3] */
+				2  1		/* MPP[2]:  NF_IO[4] */
+				3  1		/* MPP[3]:  NF_IO[5] */
+				4  1		/* MPP[4]:  NF_IO[6] */
+				5  1		/* MPP[5]:  NF_IO[7] */
+				6  1		/* MPP[6]:  SYSRST_OUTn */
+				8  2		/* MPP[8]:  UA0_RTS */
+				9  2		/* MPP[9]:  UA0_CTS */
+				10 3		/* MPP[10]: UA0_TXD */
+				11 3		/* MPP[11]: UA0_RXD */
+				12 1		/* MPP[12]: SD_CLK */
+				13 1		/* MPP[13]: SD_CMD */
+				14 1		/* MPP[14]: SD_D[0] */
+				15 1		/* MPP[15]: SD_D[1] */
+				16 1		/* MPP[16]: SD_D[2] */
+				17 1		/* MPP[17]: SD_D[3] */
+				18 1		/* MPP[18]: NF_IO[0] */
+				19 1		/* MPP[19]: NF_IO[1] */
+				29 1 >;		/* MPP[29]: TSMP[9] */
+		};
+
+		GPIO: gpio@10100 {
+			#gpio-cells = <3>;
+			compatible = "mrvl,gpio";
+			reg = <0x10100 0x20>;
+			gpio-controller;
+			interrupts = <35 36 37 38 39 40 41>;
+			interrupt-parent = <&PIC>;
+		};
+
+		rtc@10300 {
+			compatible = "mrvl,rtc";
+			reg = <0x10300 0x08>;
+		};
+
+		twsi@11000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			compatible = "mrvl,twsi";
+			reg = <0x11000 0x20>;
+			interrupts = <43>;
+			interrupt-parent = <&PIC>;
+		};
+
+		enet0: ethernet@72000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			model = "V2";
+			compatible = "mrvl,ge";
+			reg = <0x72000 0x2000>;
+			ranges = <0x0 0x72000 0x2000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <12 13 14 11 46>;
+			interrupt-parent = <&PIC>;
+			phy-handle = <&phy0>;
+
+			mdio@0 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "mrvl,mdio";
+
+				phy0: ethernet-phy@0 {
+					reg = <0x0>;
+				};
+			};
+		};
+
+		serial0: serial@12000 {
+			compatible = "ns16550";
+			reg = <0x12000 0x20>;
+			reg-shift = <2>;
+			clock-frequency = <0>;
+			interrupts = <33>;
+			interrupt-parent = <&PIC>;
+		};
+
+		serial1: serial@12100 {
+			compatible = "ns16550";
+			reg = <0x12100 0x20>;
+			reg-shift = <2>;
+			clock-frequency = <0>;
+			interrupts = <34>;
+			interrupt-parent = <&PIC>;
+		};
+
+		crypto@30000 {
+			compatible = "mrvl,cesa";
+			reg = <0x30000 0x10000>;
+			interrupts = <22>;
+			interrupt-parent = <&PIC>;
+		};
+
+		usb@50000 {
+			compatible = "mrvl,usb-ehci", "usb-ehci";
+			reg = <0x50000 0x1000>;
+			interrupts = <48 19>;
+			interrupt-parent = <&PIC>;
+		};
+
+		xor@60000 {
+			compatible = "mrvl,xor";
+			reg = <0x60000 0x1000>;
+			interrupts = <5 6 7 8>;
+			interrupt-parent = <&PIC>;
+		};
+	};
+
+	SRAM: sram@fd000000 {
+		compatible = "mrvl,cesa-sram";
+		reg = <0xfd000000 0x00100000>;
+	};
+
+	chosen {
+		stdin = "serial0";
+		stdout = "serial0";
+	};
+};

From 87ff4bceb6f207831d3f7b9d5cd9dce7f85869ef Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Wed, 8 Sep 2010 19:53:16 +0000
Subject: [PATCH 0559/1624] Check TARGET_ARCH as well as TARGET to determine if
 we are doing a cross build. This is necessary to be able to cross-build
 32-bit PowerPC from a 64-bit PowerPC host.

Reviewed by:	imp
---
 Makefile.inc1 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Makefile.inc1 b/Makefile.inc1
index ef732de99e2..a08e4ca7245 100644
--- a/Makefile.inc1
+++ b/Makefile.inc1
@@ -161,7 +161,7 @@ BUILD_ARCH!=	uname -p
 .error To cross-build, set TARGET_ARCH.
 .endif
 .endif
-.if ${MACHINE} == ${TARGET} && !defined(CROSS_BUILD_TESTING)
+.if ${MACHINE} == ${TARGET} && ${MACHINE_ARCH} == ${TARGET_ARCH} && !defined(CROSS_BUILD_TESTING)
 OBJTREE=	${MAKEOBJDIRPREFIX}
 .else
 OBJTREE=	${MAKEOBJDIRPREFIX}/${TARGET}.${TARGET_ARCH}

From fc780ca17e21b31c166fe764e1d612949662e853 Mon Sep 17 00:00:00 2001
From: Maksim Yevmenkin 
Date: Wed, 8 Sep 2010 20:00:27 +0000
Subject: [PATCH 0560/1624] Make sure to only pickup hid_input items when
 parsing input reports. As it turns out, libusbhid(3) also picks up
 hic_collection items even though we explicitly requested hid_input items
 only.

Tested by:	Buganini < buganini at gmail dot com >
MFC after:	1 week
---
 usr.sbin/bluetooth/bthidd/hid.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/usr.sbin/bluetooth/bthidd/hid.c b/usr.sbin/bluetooth/bthidd/hid.c
index e9448491e73..8c0db6ca94a 100644
--- a/usr.sbin/bluetooth/bthidd/hid.c
+++ b/usr.sbin/bluetooth/bthidd/hid.c
@@ -160,7 +160,8 @@ hid_interrupt(bthid_session_p s, uint8_t *data, int32_t len)
 
 	for (d = hid_start_parse(hid_device->desc, 1 << hid_input, -1);
 	     hid_get_item(d, &h) > 0; ) {
-		if ((h.flags & HIO_CONST) || (h.report_ID != report_id))
+		if ((h.flags & HIO_CONST) || (h.report_ID != report_id) ||
+		    (h.kind != hid_input))
 			continue;
 
 		page = HID_PAGE(h.usage);

From 170a7705aebce2595da9dfc654e44942bf4d603c Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 8 Sep 2010 20:09:50 +0000
Subject: [PATCH 0561/1624] Add few more bintime math macros.

---
 sys/sys/time.h | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/sys/sys/time.h b/sys/sys/time.h
index 1039c2216de..fbef8b77482 100644
--- a/sys/sys/time.h
+++ b/sys/sys/time.h
@@ -90,6 +90,25 @@ bintime_sub(struct bintime *bt, const struct bintime *bt2)
 	bt->sec -= bt2->sec;
 }
 
+static __inline void
+bintime_mul(struct bintime *bt, u_int x)
+{
+	uint64_t p1, p2;
+
+	p1 = (bt->frac & 0xffffffffllu) * x;
+	p2 = (bt->frac >> 32) * x + (p1 >> 32);
+	bt->sec *= x;
+	bt->sec += (p2 >> 32);
+	bt->frac = (p2 << 32) | (p1 & 0xffffffffllu);
+}
+
+#define	bintime_clear(a)	((a)->sec = (a)->frac = 0)
+#define	bintime_isset(a)	((a)->sec || (a)->frac)
+#define	bintime_cmp(a, b, cmp)						\
+	(((a)->sec == (b)->sec) ?					\
+	    ((a)->frac cmp (b)->frac) :					\
+	    ((a)->sec cmp (b)->sec))
+
 /*-
  * Background information:
  *

From ecc12db0a4a7f3aae8ed3b490c5e2788a0da1c16 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Wed, 8 Sep 2010 20:10:24 +0000
Subject: [PATCH 0562/1624] pc-sysinstall(8) patch that allows images to be
 written to disks

This patch creates the "image" directive for the pc-sysinstall config
file. This allows disks to be configured with an image instead of
partitioning.

PR:		150137
Submitted by:	John Hixson
---
 .../pc-sysinstall/backend-query/disk-list.sh  |  13 +-
 usr.sbin/pc-sysinstall/backend/Makefile       |   2 +-
 .../backend/functions-bsdlabel.sh             | 172 +++++++++-
 .../pc-sysinstall/backend/functions-disk.sh   | 311 ++++++++++--------
 .../backend/functions-extractimage.sh         |   8 +-
 .../backend/functions-installcomponents.sh    |   4 +-
 .../backend/functions-packages.sh             |   6 +-
 .../pc-sysinstall/backend/functions-parse.sh  |   1 +
 usr.sbin/pc-sysinstall/backend/functions.sh   | 115 +++++++
 usr.sbin/pc-sysinstall/backend/parseconfig.sh |  89 +----
 usr.sbin/pc-sysinstall/doc/help-index         |   2 +
 usr.sbin/pc-sysinstall/examples/README        |  11 +-
 .../pc-sysinstall/pc-sysinstall.sh            |   4 +
 13 files changed, 511 insertions(+), 227 deletions(-)

diff --git a/usr.sbin/pc-sysinstall/backend-query/disk-list.sh b/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
index eb6b43709ba..4054f041d47 100755
--- a/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
+++ b/usr.sbin/pc-sysinstall/backend-query/disk-list.sh
@@ -27,6 +27,7 @@
 
 ARGS=$1
 FLAGS_MD=""
+FLAGS_CD=""
 FLAGS_VERBOSE=""
 
 shift
@@ -39,6 +40,9 @@ do
     -v)
       FLAGS_VERBOSE=1
       ;;
+    -c)
+      FLAGS_CD=1
+      ;;
   esac
   shift
 done
@@ -62,9 +66,12 @@ do
   DEV="${i}"
 
   # Make sure we don't find any cd devices
-  case "${DEV}" in
-    acd[0-9]*|cd[0-9]*|scd[0-9]*) continue ;;
-  esac
+  if [ -z "${FLAGS_CD}" ]
+  then
+    case "${DEV}" in
+      acd[0-9]*|cd[0-9]*|scd[0-9]*) continue ;;
+    esac
+  fi
 
   # Check the dmesg output for some more info about this device
   NEWLINE=$(dmesg | sed -n "s/^$DEV: .*<\(.*\)>.*$/ <\1>/p" | head -n 1)
diff --git a/usr.sbin/pc-sysinstall/backend/Makefile b/usr.sbin/pc-sysinstall/backend/Makefile
index fa51d50be5c..61651914e68 100644
--- a/usr.sbin/pc-sysinstall/backend/Makefile
+++ b/usr.sbin/pc-sysinstall/backend/Makefile
@@ -7,7 +7,7 @@ FILES=	functions-bsdlabel.sh functions-cleanup.sh functions-disk.sh \
 	functions-newfs.sh functions-packages.sh functions-parse.sh \
 	functions-runcommands.sh functions-unmount.sh \
 	functions-upgrade.sh functions-users.sh \
-	functions.sh parseconfig.sh startautoinstall.sh
+	functions.sh parseconfig.sh startautoinstall.sh installimage.sh
 FILESMODE=	${BINMODE}
 FILESDIR=${SHAREDIR}/pc-sysinstall/backend
 NO_OBJ=
diff --git a/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh b/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
index 42aaec2a520..1604148d8ca 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-bsdlabel.sh
@@ -566,9 +566,8 @@ populate_disk_label()
 setup_disk_label()
 {
   # We are ready to start setting up the label, lets read the config and do the actions
-
   # First confirm that we have a valid WORKINGSLICES
-  if [ -z "${WORKINGSLICES}" ]; then
+  if [ -z "${WORKINGSLICES}" -a -z "${WORKINGIMAGES}" ]; then
     exit_err "ERROR: No slices were setup! Please report this to the maintainers"
   fi
 
@@ -613,6 +612,12 @@ setup_disk_label()
     populate_disk_label "${i}"
   done
 
+  for i in $WORKINGIMAGES
+  do
+    image=`echo "${i}"|cut -f2 -d:`
+    check_image_layout "${image}" 
+  done
+
   # Check if we made a root partition
   if [ "$FOUNDROOT" = "-1" ]
   then
@@ -631,3 +636,166 @@ setup_disk_label()
   fi
 };
 
+check_fstab_mbr()
+{
+  local SLICE
+  local FSTAB
+
+  if [ -z "$2" ]
+  then
+	return 1
+  fi
+
+  SLICE="$1"
+  FSTAB="$2/etc/fstab"
+
+  if [ -f "${FSTAB}" ]
+  then
+    PARTLETTER=`echo "$SLICE" | sed -E 's|^.+([a-h])$|\1|'`
+
+    grep -E '^.+ +/ +' "${FSTAB}" >/dev/null 2>&1
+    if [ "$?" = "0" ]
+    then
+      if [ "${PARTLETTER}" = "a" ]
+      then
+        FOUNDROOT="0"
+      else
+        FOUNDROOT="1"
+      fi
+      export FOUNDROOT
+    fi
+
+    grep -E '^.+ +/boot +' "${FSTAB}" >/dev/null 2>&1
+    if [ "$?" = "0" ]
+    then
+      if [ "${PARTLETTER}" = "a" ]
+      then
+        USINGBOOTPART="0"
+      else 
+        exit_err "/boot partition must be first partition"
+      fi 
+      export USINGBOOTPART
+    fi
+
+    return 0
+  fi
+
+  return 1
+};
+
+check_fstab_gpt()
+{
+  local SLICE
+  local FSTAB
+
+  if [ -z "$2" ]
+  then
+	return 1
+  fi
+
+  SLICE="$1"
+  FSTAB="$2/etc/fstab"
+
+  if [ -f "${FSTAB}" ]
+  then
+    PARTNUMBER=`echo "${SLICE}" | sed -E 's|^.+p([0-9]*)$|\1|'`
+
+    grep -E '^.+ +/ +' "${FSTAB}" >/dev/null 2>&1
+    if [ "$?" = "0" ]
+    then
+      if [ "${PARTNUMBER}" = "2" ]
+      then
+        FOUNDROOT="0"
+      else
+        FOUNDROOT="1"
+      fi
+      export FOUNDROOT
+    fi
+
+    grep -E '^.+ +/boot +' "${FSTAB}" >/dev/null 2>&1
+    if [ "$?" = "0" ]
+    then
+      if [ "${PARTNUMBER}" = "2" ]
+      then
+        USINGBOOTPART="0"
+      else 
+        exit_err "/boot partition must be first partition"
+      fi 
+      export USINGBOOTPART
+    fi
+
+    return 0
+  fi
+
+
+  return 1
+};
+
+check_image_layout()
+{
+  local SLICES
+  local IMAGE
+  local TYPE
+  local RES
+  local MD
+  local F
+
+  IMAGE="$1"
+  TYPE="MBR"
+
+  if [ -z "${IMAGE}" ]
+  then
+	return 1
+  fi
+
+  MD=`mdconfig -af "${IMAGE}"`
+  if [ "$?" != "0" ]
+  then
+	return 1
+  fi
+
+  SLICES=`ls /dev/${MD}s[1-4]*[a-h]* 2>/dev/null`
+  if [ "$?" != "0" ]
+  then
+    SLICES=`ls /dev/${MD}p[0-9]* 2>/dev/null`
+    if [ -n "${SLICES}" ]
+    then
+      TYPE="GPT"
+      RES=0
+    fi
+  else
+    RES=0
+  fi
+
+  for slice in ${SLICES}
+  do
+    F=1
+    mount ${slice} /mnt 2>/dev/null
+    if [ "$?" != "0" ]
+    then
+      continue
+    fi 
+
+    if [ "${TYPE}" = "MBR" ]
+    then
+	  check_fstab_mbr "${slice}" "/mnt"
+      F="$?"
+
+    elif [ "${TYPE}" = "GPT" ]
+    then
+	  check_fstab_gpt "${slice}" "/mnt"
+      F="$?"
+    fi 
+
+    if [ "${F}" = "0" ]
+    then
+      umount /mnt
+      break 
+    fi
+
+    umount /mnt
+  done
+
+  mdconfig -d -u "${MD}"
+  return ${RES}
+};
diff --git a/usr.sbin/pc-sysinstall/backend/functions-disk.sh b/usr.sbin/pc-sysinstall/backend/functions-disk.sh
index 6416fe1a478..f676cd6c914 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-disk.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-disk.sh
@@ -231,9 +231,6 @@ get_disk_heads()
 get_disk_mediasize()
 {
   mediasize=`diskinfo -v ${1} | grep "# mediasize in sectors" | tr -s ' ' | cut -f 2`
-
-  # Not sure why this is, memory disks need it though.
-  mediasize=`expr ${mediasize} - 10`
   VAL="${mediasize}" ; export VAL
 };
 
@@ -336,164 +333,205 @@ setup_disk_slice()
   # We are ready to start setting up the disks, lets read the config and do the actions
   while read line
   do
-     echo $line | grep "^disk${disknum}=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
+    echo $line | grep "^disk${disknum}=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
 
-       # Found a disk= entry, lets get the disk we are working on
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       DISK="$VAL"
+      # Found a disk= entry, lets get the disk we are working on
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      DISK="$VAL"
      
-       # Before we go further, lets confirm this disk really exists
-       if [ ! -e "/dev/${DISK}" ]
-       then
-         exit_err "ERROR: The disk ${DISK} does not exist!"
-       fi
+      # Before we go further, lets confirm this disk really exists
+      if [ ! -e "/dev/${DISK}" ]
+      then
+        exit_err "ERROR: The disk ${DISK} does not exist!"
+      fi
 
-       # Make sure we stop any gmirrors on this disk
-       stop_all_gmirror ${DISK}
+      # Make sure we stop any gmirrors on this disk
+      stop_all_gmirror ${DISK}
 
-       # Make sure we stop any geli stuff on this disk
-       stop_all_geli ${DISK}
+      # Make sure we stop any geli stuff on this disk
+      stop_all_geli ${DISK}
 
-       # Make sure we don't have any zpools loaded
-       stop_all_zfs
+      # Make sure we don't have any zpools loaded
+      stop_all_zfs
 
-     fi
+    fi
 
-     # Lets look if this device will be mirrored on another disk
-     echo $line | grep "^mirror=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
+    # Lets look if this device will be mirrored on another disk
+    echo $line | grep "^mirror=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
 
-       # Found a disk= entry, lets get the disk we are working on
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       MIRRORDISK="$VAL"
+      # Found a disk= entry, lets get the disk we are working on
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      MIRRORDISK="$VAL"
      
-       # Before we go further, lets confirm this disk really exists
-       if [ ! -e "/dev/${MIRRORDISK}" ]
-       then
-         exit_err "ERROR: The mirror disk ${MIRRORDISK} does not exist!"
-       fi
-     fi
+      # Before we go further, lets confirm this disk really exists
+      if [ ! -e "/dev/${MIRRORDISK}" ]
+      then
+        exit_err "ERROR: The mirror disk ${MIRRORDISK} does not exist!"
+      fi
+    fi
 
-     # Lets see if we have been given a mirror balance choice
-     echo $line | grep "^mirrorbal=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
+    # Lets see if we have been given a mirror balance choice
+    echo $line | grep "^mirrorbal=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
 
-       # Found a disk= entry, lets get the disk we are working on
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       MIRRORBAL="$VAL"
-     fi
+      # Found a disk= entry, lets get the disk we are working on
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      MIRRORBAL="$VAL"
+    fi
 
-     echo $line | grep "^partition=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       # Found a partition= entry, lets read / set it 
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       PTYPE="$VAL"
+    echo $line | grep "^partition=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      # Found a partition= entry, lets read / set it 
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      PTYPE=`echo $VAL|tr A-Z a-z`
 
-       # We are using free space, figure out the slice number
-       if [ "${PTYPE}" = "free" -o "${PTYPE}" = "FREE" ]
-       then
-         # Lets figure out what number this slice will be
-         LASTSLICE="`gpart show ${DISK} | grep -v ${DISK} | grep -v ' free' |tr -s '\t' ' ' | cut -d ' ' -f 4 | sed '/^$/d' | tail -n 1`"
-         if [ -z "${LASTSLICE}" ]
-         then
-           LASTSLICE="1"
-         else
-           LASTSLICE="`expr $LASTSLICE + 1`"
-         fi
+      # We are using free space, figure out the slice number
+      if [ "${PTYPE}" = "free" ]
+      then
+        # Lets figure out what number this slice will be
+        LASTSLICE="`gpart show ${DISK} \
+			| grep -v ${DISK} \
+			| grep -v ' free' \
+			| tr -s '\t' ' ' \
+			| cut -d ' ' -f 4 \
+			| sed '/^$/d' \
+			| tail -n 1`"
 
-         if [ $LASTSLICE -gt 4 ]
-         then
-           exit_err "ERROR: BSD only supports primary partitions, and there are none availble on $DISK"
-         fi
+        if [ -z "${LASTSLICE}" ]
+        then
+          LASTSLICE="1"
+        else
+          LASTSLICE="`expr $LASTSLICE + 1`"
+        fi
 
-       fi
-     fi
+        if [ $LASTSLICE -gt 4 ]
+        then
+          exit_err "ERROR: BSD only supports primary partitions, and there are none availble on $DISK"
+        fi
 
-     # Check if we have a partscheme specified
-     echo $line | grep "^partscheme=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ] ; then
-       # Found a partscheme= entry, lets read / set it 
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       PSCHEME="$VAL"
-       if [ "$PSCHEME" != "GPT" -a "$PSCHEME" != "MBR" ] ; then
-	 exit_err "Unknown partition scheme: $PSCHEME" 
-       fi
-     fi
+      fi
+    fi
 
-     echo $line | grep "^bootManager=" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       # Found a bootManager= entry, lets read /set it
-       get_value_from_string "${line}"
-       strip_white_space "$VAL"
-       BMANAGER="$VAL"
-     fi
+    # Check if we have an image file defined
+    echo $line | grep "^image=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ] ; then
+      # Found an image= entry, lets read / set it
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      IMAGE="$VAL"
+      if [ ! -f "$IMAGE" ] ; then
+        exit_err "$IMAGE file does not exist"
+      fi
+    fi
 
-     echo $line | grep "^commitDiskPart" >/dev/null 2>/dev/null
-     if [ "$?" = "0" ]
-     then
-       # Found our flag to commit this disk setup / lets do sanity check and do it
-       if [ ! -z "${DISK}" -a ! -z "${PTYPE}" ]
-       then
-         case ${PTYPE} in
-           all|ALL)
-		     if [ "$PSCHEME" = "MBR" -o -z "$PSCHEME" ] ; then
-               PSCHEME="MBR"
-               tmpSLICE="${DISK}s1"  
-			 else
-               tmpSLICE="${DISK}p1"  
-			 fi
+    # Check if we have a partscheme specified
+    echo $line | grep "^partscheme=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ] ; then
+      # Found a partscheme= entry, lets read / set it 
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      PSCHEME="$VAL"
+      if [ "$PSCHEME" != "GPT" -a "$PSCHEME" != "MBR" ] ; then
+        exit_err "Unknown partition scheme: $PSCHEME" 
+      fi
+    fi
 
-             run_gpart_full "${DISK}" "${BMANAGER}" "${PSCHEME}"
-			 ;;
+    echo $line | grep "^bootManager=" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      # Found a bootManager= entry, lets read /set it
+      get_value_from_string "${line}"
+      strip_white_space "$VAL"
+      BMANAGER="$VAL"
+    fi
 
-           s1|s2|s3|s4)
-			 tmpSLICE="${DISK}${PTYPE}" 
-             # Get the number of the slice we are working on
-             s="`echo ${PTYPE} | awk '{print substr($0,length,1)}'`" 
-             run_gpart_slice "${DISK}" "${BMANAGER}" "${s}"
-			 ;;
+    echo $line | grep "^commitDiskPart" >/dev/null 2>/dev/null
+    if [ "$?" = "0" ]
+    then
+      # Found our flag to commit this disk setup / lets do sanity check and do it
+      if [ ! -z "${DISK}" -a ! -z "${PTYPE}" ]
+      then
+        case ${PTYPE} in
+          all)
+            if [ "$PSCHEME" = "MBR" -o -z "$PSCHEME" ] ; then
+              PSCHEME="MBR"
+              tmpSLICE="${DISK}s1"  
+			else
+              tmpSLICE="${DISK}p1"  
+            fi
 
-           free|FREE)
-			 tmpSLICE="${DISK}s${LASTSLICE}"
-             run_gpart_free "${DISK}" "${LASTSLICE}" "${BMANAGER}"
-			 ;;
+            run_gpart_full "${DISK}" "${BMANAGER}" "${PSCHEME}"
+            ;;
 
-           *) exit_err "ERROR: Unknown PTYPE: $PTYPE" ;;
-         esac
+          s1|s2|s3|s4)
+            tmpSLICE="${DISK}${PTYPE}" 
+            # Get the number of the slice we are working on
+            s="`echo ${PTYPE} | awk '{print substr($0,length,1)}'`" 
+            run_gpart_slice "${DISK}" "${BMANAGER}" "${s}"
+            ;;
 
-         # Now save which disk this is, so we can parse it later during slice partition setup
-         echo "disk${disknum}" >${SLICECFGDIR}/$tmpSLICE
+          free)
+            tmpSLICE="${DISK}s${LASTSLICE}"
+            run_gpart_free "${DISK}" "${LASTSLICE}" "${BMANAGER}"
+            ;;
 
-         # Save any mirror config
-         if [ ! -z "$MIRRORDISK" ]
-         then
-           # Default to round-robin if the user didn't specify
-           if [ -z "$MIRRORBAL" ]
-           then
-             MIRRORBAL="round-robin"
-           fi
-           echo "$MIRRORDISK:$MIRRORBAL" >${MIRRORCFGDIR}/$DISK
-         fi
+          image)
+            if [ -n "${IMAGE}" ]
+            then
+              write_image "${IMAGE}" "${DISK}"
+            else 
+			  exit_err "ERROR: partition type image specified with no image!"
+            fi 
+
+            IMAGE="${DISK}:${IMAGE}"
+            if [ -z "${WORKINGIMAGES}" ]
+            then
+			  WORKINGIMAGES="${IMAGE}"
+            else 
+			  WORKINGIMAGES="${WORKINGIMAGES} ${IMAGE}"
+            fi 
+
+            export WORKINGIMAGES
+            ;;
+
+          *) exit_err "ERROR: Unknown PTYPE: $PTYPE" ;;
+        esac
+
+        # Now save which disk this is, so we can parse it later during slice partition setup
+        if [ -n "${tmpSLICE}" ]
+        then
+          echo "disk${disknum}" >${SLICECFGDIR}/$tmpSLICE
+        fi
+
+        # Save any mirror config
+        if [ ! -z "$MIRRORDISK" ]
+        then
+          # Default to round-robin if the user didn't specify
+          if [ -z "$MIRRORBAL" ]
+          then
+            MIRRORBAL="round-robin"
+          fi
+          echo "$MIRRORDISK:$MIRRORBAL" >${MIRRORCFGDIR}/$DISK
+        fi
 
 
-         # Increment our disk counter to look for next disk and unset
-         unset BMANAGER PTYPE DISK MIRRORDISK MIRRORBAL PSCHEME
-         disknum="`expr $disknum + 1`"
-       else
-         exit_err "ERROR: commitDiskPart was called without procceding disk= and partition= entries!!!" 
-       fi
-     fi
+        # Increment our disk counter to look for next disk and unset
+        unset BMANAGER PTYPE DISK MIRRORDISK MIRRORBAL PSCHEME IMAGE
+        disknum="`expr $disknum + 1`"
+      else
+        exit_err "ERROR: commitDiskPart was called without procceding disk= and partition= entries!!!" 
+      fi
+    fi
 
   done <${CFGF}
 
@@ -590,8 +628,7 @@ init_mbr_full_disk()
   totalblocks="`expr ${totalblocks} \* ${sec}`"
   if [ -z "${totalblocks}" ]
   then
-	get_disk_mediasize "${_intDISK}"
-	totalblocks="${VAL}"
+    totalblocks=`gpart show "${_intDISK}"|tail -2|head -1|awk '{ print $2 }'`
   fi
 
   # Now set the ending block to the total disk block size
diff --git a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
index 72a30fb43cd..c7c7ed7b02e 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-extractimage.sh
@@ -377,7 +377,7 @@ init_extraction()
       fi
       ;;
 
-    ftp|sftp)
+    ftp)
       if [ "$PACKAGETYPE" = "split" ]
       then
         fetch_split_files
@@ -390,9 +390,9 @@ init_extraction()
       fi
       ;;
 
-      rsync) start_rsync_copy ;;
-    img)
-		;;
+    sftp) ;;
+
+    rsync) start_rsync_copy ;;
     *) exit_err "ERROR: Unknown install medium" ;;
   esac
 
diff --git a/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh b/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh
index e8beeda05ee..f133e30eb91 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-installcomponents.sh
@@ -60,7 +60,7 @@ copy_component()
 	    RESULT="$?"
         ;;
 
-      ftp|sftp)
+      ftp)
         get_value_from_cfg ftpPath
         if [ -z "$VAL" ]
         then
@@ -71,6 +71,8 @@ copy_component()
         fetch_file "${FTPPATH}/${COMPFILEDIR}/${SUBDIR}/${CFILE}" "${FSMNT}/${COMPTMPDIR}/${CFILE}" "0"
         RESULT="$?"
        ;;
+
+      sftp) ;;
     esac
 
     if [ "${RESULT}" != "0" ]
diff --git a/usr.sbin/pc-sysinstall/backend/functions-packages.sh b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
index 998b7ad13e2..f51725044e0 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-packages.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-packages.sh
@@ -113,7 +113,8 @@ get_package_index()
 
     case "${INSTALLMEDIUM}" in
       usb|dvd) get_package_index_by_fs ;;
-      ftp|sftp) get_package_index_by_ftp "${FTPPATH}" ;;
+      ftp) get_package_index_by_ftp "${FTPPATH}" ;;
+      sftp) ;;
       *) RES=1 ;;
     esac
 
@@ -369,6 +370,7 @@ fetch_package()
 
   case "${INSTALLMEDIUM}" in
     usb|dvd) fetch_package_by_fs "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}" ;;
-    ftp|sftp) fetch_package_by_ftp "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}" ;;
+    ftp) fetch_package_by_ftp "${CATEGORY}" "${PACKAGE}" "${SAVEDIR}" ;;
+    sftp) ;;
   esac
 };
diff --git a/usr.sbin/pc-sysinstall/backend/functions-parse.sh b/usr.sbin/pc-sysinstall/backend/functions-parse.sh
index 3604ba4425b..11bba105cb9 100755
--- a/usr.sbin/pc-sysinstall/backend/functions-parse.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions-parse.sh
@@ -85,6 +85,7 @@ if_check_value_exists()
     VALID="1"
     for i in ${2}
     do
+      VAL=`echo "$VAL"|tr A-Z a-z`
       if [ "$VAL" = "${i}" ]
       then 
         VALID="0"
diff --git a/usr.sbin/pc-sysinstall/backend/functions.sh b/usr.sbin/pc-sysinstall/backend/functions.sh
index f51902a54ea..847d97eeb69 100755
--- a/usr.sbin/pc-sysinstall/backend/functions.sh
+++ b/usr.sbin/pc-sysinstall/backend/functions.sh
@@ -283,3 +283,118 @@ get_zpool_name()
     return
   fi
 };
+
+write_image()
+{
+  IMAGE_FILE="$1"
+  DEVICE_FILE="$2"
+
+  if [ -z "${IMAGE_FILE}" ]
+  then
+    echo "ERROR: Image file not specified!"
+    exit 1
+  fi
+ 
+  if [ -z "${DEVICE_FILE}" ]
+  then
+    echo "ERROR: Device file not specified!"
+    exit 1
+  fi
+ 
+  if [ ! -f "${IMAGE_FILE}" ]
+  then
+    echo "ERROR: '${IMAGE_FILE}' does not exist!"
+    exit 1
+  fi
+
+  DEVICE_FILE="${DEVICE_FILE#/dev/}"
+  DEVICE_FILE="/dev/${DEVICE_FILE}"
+ 
+  if [ ! -c "${DEVICE_FILE}" ]
+  then
+    echo "ERROR: '${DEVICE_FILE}' is not a character device!"
+    exit 1
+  fi
+
+  if [ "${RES}" = "0" ]
+  then
+    rc_halt "dd if=${IMAGE_FILE} of=${DEVICE_FILE} ibs=16k obs=16k"
+  fi
+
+  return 0
+};
+
+install_fresh()
+{
+  # Lets start setting up the disk slices now
+  setup_disk_slice
+  
+  # Disk setup complete, now lets parse WORKINGSLICES and setup the bsdlabels
+  setup_disk_label
+  
+  # Now we've setup the bsdlabels, lets go ahead and run newfs / zfs 
+  # to setup the filesystems
+  setup_filesystems
+
+  # Lets mount the partitions now
+  mount_all_filesystems
+
+  # We are ready to begin extraction, lets start now
+  init_extraction 
+
+  # Check if we have any optional modules to load 
+  install_components
+
+  # Check if we have any packages to install
+  install_packages
+
+  # Do any localization in configuration
+  run_localize
+  
+  # Save any networking config on the installed system
+  save_networking_install
+
+  # Now add any users
+  setup_users
+
+  # Now run any commands specified
+  run_commands
+  
+  # Do any last cleanup / setup before unmounting
+  run_final_cleanup
+
+  # Unmount and finish up
+  unmount_all_filesystems
+
+  echo_log "Installation finished!"
+}
+
+install_upgrade()
+{
+  # We're going to do an upgrade, skip all the disk setup 
+  # and start by mounting the target drive/slices
+  mount_upgrade
+  
+  # Start the extraction process
+  init_extraction
+
+  # Do any localization in configuration
+  run_localize
+
+  # ow run any commands specified
+  run_commands
+  
+  # Merge any old configuration files
+  merge_old_configs
+
+  # Check if we have any optional modules to load 
+  install_components
+
+  # Check if we have any packages to install
+  install_packages
+
+  # All finished, unmount the file-systems
+  unmount_upgrade
+
+  echo_log "Upgrade finished!"
+}
diff --git a/usr.sbin/pc-sysinstall/backend/parseconfig.sh b/usr.sbin/pc-sysinstall/backend/parseconfig.sh
index ff5694ccb3b..af4f974ce9d 100755
--- a/usr.sbin/pc-sysinstall/backend/parseconfig.sh
+++ b/usr.sbin/pc-sysinstall/backend/parseconfig.sh
@@ -73,9 +73,9 @@ file_sanity_check "installMode disk0 installType installMedium packageType"
 check_value installMode "fresh upgrade"
 check_value bootManager "bsd none"
 check_value installType "PCBSD FreeBSD"
-check_value installMedium "dvd usb ftp rsync img"
+check_value installMedium "dvd usb ftp rsync"
 check_value packageType "uzip tar rsync split"
-if_check_value_exists partition "all ALL s1 s2 s3 s4 free FREE"
+if_check_value_exists partition "all s1 s2 s3 s4 free image"
 if_check_value_exists mirrorbal "load prefer round-robin split"
 
 # We passed all sanity checks! Yay, lets start the install
@@ -98,79 +98,18 @@ PACKAGETYPE="${VAL}" ; export PACKAGETYPE
 start_networking
 
 # If we are not doing an upgrade, lets go ahead and setup the disk
-if [ "${INSTALLMODE}" = "fresh" ]
-then
+case "${INSTALLMODE}" in
+  fresh)
+	install_fresh
+    ;;
 
-  # Lets start setting up the disk slices now
-  setup_disk_slice
-  
-  # Disk setup complete, now lets parse WORKINGSLICES and setup the bsdlabels
-  setup_disk_label
-  
-  # Now we've setup the bsdlabels, lets go ahead and run newfs / zfs 
-  # to setup the filesystems
-  setup_filesystems
+  upgrade)
+    install_upgrade
+    ;;
 
-  # Lets mount the partitions now
-  mount_all_filesystems
-
-  # We are ready to begin extraction, lets start now
-  init_extraction
-
-  # Check if we have any optional modules to load 
-  install_components
-
-  # Check if we have any packages to install
-  install_packages
-
-  # Do any localization in configuration
-  run_localize
-  
-  # Save any networking config on the installed system
-  save_networking_install
-
-  # Now add any users
-  setup_users
-
-  # Now run any commands specified
-  run_commands
-  
-  # Do any last cleanup / setup before unmounting
-  run_final_cleanup
-
-  # Unmount and finish up
-  unmount_all_filesystems
-
-  echo_log "Installation finished!"
-  exit 0
-
-else
-  # We're going to do an upgrade, skip all the disk setup 
-  # and start by mounting the target drive/slices
-  mount_upgrade
-  
-  # Start the extraction process
-  init_extraction
-
-  # Do any localization in configuration
-  run_localize
-
-  # Now run any commands specified
-  run_commands
-  
-  # Merge any old configuration files
-  merge_old_configs
-
-  # Check if we have any optional modules to load 
-  install_components
-
-  # Check if we have any packages to install
-  install_packages
-
-  # All finished, unmount the file-systems
-  unmount_upgrade
-
-  echo_log "Upgrade finished!"
-  exit 0
-fi
+  *)
+	exit 1
+    ;;
+esac
 
+exit 0
diff --git a/usr.sbin/pc-sysinstall/doc/help-index b/usr.sbin/pc-sysinstall/doc/help-index
index 6a0f1bce51b..bad401f1ef1 100644
--- a/usr.sbin/pc-sysinstall/doc/help-index
+++ b/usr.sbin/pc-sysinstall/doc/help-index
@@ -9,6 +9,8 @@ Help Commands
    	Display the help data for the specified command
 
 System Query Commands
+    install-image  
+        Installs an image file to a device file
 
     disk-list 
         Provides a listing of the disk drives detected on this system
diff --git a/usr.sbin/pc-sysinstall/examples/README b/usr.sbin/pc-sysinstall/examples/README
index eeb96d0ea2f..1031375d6bd 100644
--- a/usr.sbin/pc-sysinstall/examples/README
+++ b/usr.sbin/pc-sysinstall/examples/README
@@ -114,7 +114,7 @@ root zpool of the target system to update. I.E:
  # disk0=ada0s1a
 
 
-# partition=(all, free, s1, s1, s3, s4)
+# partition=(all, free, s1, s1, s3, s4, image)
 
 After setting disk[0-9], the partition= variable is used to specify which target
 partition we will be working with for this device.
@@ -124,7 +124,9 @@ Setting this to "all" will setup the disk with a single FreeBSD slice as "s1"
 Setting this to "free" will allow pc-sysinstall to search for the first available
 primary slice with free space, and create the slice. 
 
-Setting this to "s1, s2, s3 or s4" will use the specified MBR slice
+Setting this to "s1, s2, s3 or s4" will use the specified MBR slice.
+
+Setting this to "image" will use an image to configure the disk.
 
 (This tag is unused for upgrades)
 
@@ -151,6 +153,11 @@ specified this defaults to "round-robin"
 Setting this option will instruct pc-sysinstall to install the BSD boot Manager,
 or leave it empty
 
+# image=(/path/to/image/file)
+
+Setting this option will instruct pc-sysinstall to write the image file
+specified by the path to the disk.
+
 # commitDiskPart
 
 This command must be placed at the end of the diskX= section, before starting
diff --git a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
index 088dea7b1af..ff62a6ff4c1 100755
--- a/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
+++ b/usr.sbin/pc-sysinstall/pc-sysinstall/pc-sysinstall.sh
@@ -116,6 +116,10 @@ case $1 in
     fi
   ;;
 
+  # Install an image file to a device
+  install-image) ${BACKEND}/installimage.sh "${2}" "${3}"
+  ;;
+
   # Parse an auto-install directive, and begin the installation
   start-autoinstall) ${BACKEND}/startautoinstall.sh ${2}
   ;;

From bf74de7eba9648cb03fabb1b81157b58c9605614 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Wed, 8 Sep 2010 20:10:29 +0000
Subject: [PATCH 0563/1624] If autoboot_delay is set to -1, boot immediately
 without checking for a keypress to match the behavior of the loader.

PR:		docs/108101
Submitted by:	Wayne Sierke  ws of au.dyndns.ws
Tested by:	brd
MFC after:	1 week
---
 sys/boot/forth/beastie.4th | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/sys/boot/forth/beastie.4th b/sys/boot/forth/beastie.4th
index c726875907f..d96f5791e79 100644
--- a/sys/boot/forth/beastie.4th
+++ b/sys/boot/forth/beastie.4th
@@ -240,7 +240,10 @@ set-current
 		drop
 		10
 	else
-		0 0 2swap >number drop drop drop
+		2dup s" -1" compare 0= if
+			0 boot
+		then
+		0 s>d 2swap >number 2drop drop
 	then
 	begin
 		dup tkey

From 917fdfb106724ec2440fc16d085033a0632098aa Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Wed, 8 Sep 2010 20:35:43 +0000
Subject: [PATCH 0564/1624] sh: Fix 'read' if all chars before the first IFS
 char are backslash-escaped.

Backslash-escaped characters did not set the flag for a non-IFS character.

MFC after:	2 weeks
---
 bin/sh/miscbltin.c                              |  1 +
 tools/regression/bin/sh/builtins/read4.0        | 10 ++++++++++
 tools/regression/bin/sh/builtins/read4.0.stdout |  8 ++++++++
 3 files changed, 19 insertions(+)
 create mode 100644 tools/regression/bin/sh/builtins/read4.0
 create mode 100644 tools/regression/bin/sh/builtins/read4.0.stdout

diff --git a/bin/sh/miscbltin.c b/bin/sh/miscbltin.c
index cc525b8ccbd..d9ac8a309c9 100644
--- a/bin/sh/miscbltin.c
+++ b/bin/sh/miscbltin.c
@@ -174,6 +174,7 @@ readcmd(int argc __unused, char **argv __unused)
 			continue;
 		if (backslash) {
 			backslash = 0;
+			startword = 0;
 			if (c != '\n')
 				STPUTC(c, p);
 			continue;
diff --git a/tools/regression/bin/sh/builtins/read4.0 b/tools/regression/bin/sh/builtins/read4.0
new file mode 100644
index 00000000000..7204a35aa0a
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/read4.0
@@ -0,0 +1,10 @@
+# $FreeBSD$
+
+printf '%s\n' '\a\ b c'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\a b\ c'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\a\:b:c'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\a:b\:c'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\ a'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\:a'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\\ a'	| { read a b; printf '%s\n' "x${a}x${b}x"; }
+printf '%s\n' '\\\:a'	| { IFS=: read a b; printf '%s\n' "x${a}x${b}x"; }
diff --git a/tools/regression/bin/sh/builtins/read4.0.stdout b/tools/regression/bin/sh/builtins/read4.0.stdout
new file mode 100644
index 00000000000..a8747a46ffe
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/read4.0.stdout
@@ -0,0 +1,8 @@
+xa bxcx
+xaxb cx
+xa:bxcx
+xaxb:cx
+x\xax
+x\xax
+x\ axx
+x\:axx

From a34512e3f0a3f89ae9e184f99b0093b8a84a8eea Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 8 Sep 2010 20:56:18 +0000
Subject: [PATCH 0565/1624] - Log all the problems in devfs_fixup().

- Correct error paths. The system will be useless on devfs_fixup() failure, so
  why bother?  Maybe for the same reason why a dead body is washed and dressed
  in a nice suit before it is put into a coffin? Maybe system's last will is to
  panic without any locks held?

Reviewed by:	kib
---
 sys/kern/vfs_mount.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/sys/kern/vfs_mount.c b/sys/kern/vfs_mount.c
index fe9f16c3355..3d3fcc8f827 100644
--- a/sys/kern/vfs_mount.c
+++ b/sys/kern/vfs_mount.c
@@ -1549,9 +1549,9 @@ static void
 devfs_fixup(struct thread *td)
 {
 	struct nameidata nd;
-	int error;
 	struct vnode *vp, *dvp;
 	struct mount *mp;
+	int error;
 
 	/* Remove our devfs mount from the mountlist and purge the cache */
 	mtx_lock(&mountlist_mtx);
@@ -1575,16 +1575,26 @@ devfs_fixup(struct thread *td)
 	error = namei(&nd);
 	if (error) {
 		printf("Lookup of /dev for devfs, error: %d\n", error);
+		vput(dvp);
+		vfs_unbusy(mp);
 		return;
 	}
 	NDFREE(&nd, NDF_ONLY_PNBUF);
 	vp = nd.ni_vp;
 	if (vp->v_type != VDIR) {
+		printf("/dev is not a directory\n");
+		vput(dvp);
 		vput(vp);
+		vfs_unbusy(mp);
+		return;
 	}
 	error = vinvalbuf(vp, V_SAVE, 0, 0);
 	if (error) {
+		printf("vinvalbuf() of /dev failed, error: %d\n", error);
+		vput(dvp);
 		vput(vp);
+		vfs_unbusy(mp);
+		return;
 	}
 	cache_purge(vp);
 	mp->mnt_vnodecovered = vp;
@@ -1597,7 +1607,9 @@ devfs_fixup(struct thread *td)
 	vfs_unbusy(mp);
 
 	/* Unlink the no longer needed /dev/dev -> / symlink */
-	kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
+	error = kern_unlink(td, "/dev/dev", UIO_SYSSPACE);
+	if (error)
+		printf("kern_unlink of /dev/dev failed, error: %d\n", error);
 }
 
 /*

From 7443b79b81dcd390146b688eb089f8e3edd45d88 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 8 Sep 2010 21:00:53 +0000
Subject: [PATCH 0566/1624] Doing first mount and updating mount points are
 both handled by the same syscall and the same function, but are very
 different and share almost no code. To make it easier to read and analyze,
 split vfs_domount() into vfs_domount_first() and vfs_domount_update().

Reviewed by:	kib
---
 sys/kern/vfs_mount.c | 488 ++++++++++++++++++++++++-------------------
 1 file changed, 268 insertions(+), 220 deletions(-)

diff --git a/sys/kern/vfs_mount.c b/sys/kern/vfs_mount.c
index 3d3fcc8f827..5dfa703950b 100644
--- a/sys/kern/vfs_mount.c
+++ b/sys/kern/vfs_mount.c
@@ -704,9 +704,7 @@ vfs_donmount(struct thread *td, int fsflags, struct uio *fsoptions)
 		goto bail;
 	}
 
-	mtx_lock(&Giant);
 	error = vfs_domount(td, fstype, fspath, fsflags, optlist);
-	mtx_unlock(&Giant);
 bail:
 	/* copyout the errmsg */
 	if (errmsg_pos != -1 && ((2 * errmsg_pos + 1) < fsoptions->uio_iovcnt)
@@ -795,6 +793,257 @@ mount(td, uap)
 	return (error);
 }
 
+/*
+ * vfs_domount_first(): first file system mount (not update)
+ */
+static int
+vfs_domount_first(
+	struct thread *td,	/* Calling thread. */
+	struct vfsconf *vfsp,	/* File system type. */
+	char *fspath,		/* Mount path. */
+	struct vnode *vp,	/* Vnode to be covered. */
+	int fsflags,		/* Flags common to all filesystems. */
+	void *fsdata		/* Options local to the filesystem. */
+	)
+{
+	struct vattr va;
+	struct mount *mp;
+	struct vnode *newdp;
+	int error;
+
+	mtx_assert(&Giant, MA_OWNED);
+	ASSERT_VOP_ELOCKED(vp, __func__);
+	KASSERT((fsflags & MNT_UPDATE) == 0, ("MNT_UPDATE shouldn't be here"));
+
+	/*
+	 * If the user is not root, ensure that they own the directory
+	 * onto which we are attempting to mount.
+	 */
+	error = VOP_GETATTR(vp, &va, td->td_ucred);
+	if (error == 0 && va.va_uid != td->td_ucred->cr_uid)
+		error = priv_check_cred(td->td_ucred, PRIV_VFS_ADMIN, 0);
+	if (error == 0)
+		error = vinvalbuf(vp, V_SAVE, 0, 0);
+	if (error == 0 && vp->v_type != VDIR)
+		error = ENOTDIR;
+	if (error == 0) {
+		VI_LOCK(vp);
+		if ((vp->v_iflag & VI_MOUNT) == 0 && vp->v_mountedhere == NULL)
+			vp->v_iflag |= VI_MOUNT;
+		else
+			error = EBUSY;
+		VI_UNLOCK(vp);
+	}
+	if (error != 0) {
+		vput(vp);
+		return (error);
+	}
+	VOP_UNLOCK(vp, 0);
+
+	/* Allocate and initialize the filesystem. */
+	mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
+	/* XXXMAC: pass to vfs_mount_alloc? */
+	mp->mnt_optnew = fsdata;
+	/* Set the mount level flags. */
+	mp->mnt_flag = (fsflags & (MNT_UPDATEMASK | MNT_ROOTFS | MNT_RDONLY));
+
+	/*
+	 * Mount the filesystem.
+	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
+	 * get.  No freeing of cn_pnbuf.
+	 */
+        error = VFS_MOUNT(mp);
+	if (error != 0) {
+		vfs_unbusy(mp);
+		vfs_mount_destroy(mp);
+		vrele(vp);
+		return (error);
+	}
+
+	if (mp->mnt_opt != NULL)
+		vfs_freeopts(mp->mnt_opt);
+	mp->mnt_opt = mp->mnt_optnew;
+	(void)VFS_STATFS(mp, &mp->mnt_stat);
+
+	/*
+	 * Prevent external consumers of mount options from reading mnt_optnew.
+	 */
+	mp->mnt_optnew = NULL;
+
+	MNT_ILOCK(mp);
+	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
+		mp->mnt_kern_flag |= MNTK_ASYNC;
+	else
+		mp->mnt_kern_flag &= ~MNTK_ASYNC;
+	MNT_IUNLOCK(mp);
+
+	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
+	cache_purge(vp);
+	VI_LOCK(vp);
+	vp->v_iflag &= ~VI_MOUNT;
+	VI_UNLOCK(vp);
+	vp->v_mountedhere = mp;
+	/* Place the new filesystem at the end of the mount list. */
+	mtx_lock(&mountlist_mtx);
+	TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
+	mtx_unlock(&mountlist_mtx);
+	vfs_event_signal(NULL, VQ_MOUNT, 0);
+	if (VFS_ROOT(mp, LK_EXCLUSIVE, &newdp))
+		panic("mount: lost mount");
+	VOP_UNLOCK(newdp, 0);
+	VOP_UNLOCK(vp, 0);
+	mountcheckdirs(vp, newdp);
+	vrele(newdp);
+	if ((mp->mnt_flag & MNT_RDONLY) == 0)
+		vfs_allocate_syncvnode(mp);
+	vfs_unbusy(mp);
+	return (0);
+}
+
+/*
+ * vfs_domount_update(): update of mounted file system
+ */
+static int
+vfs_domount_update(
+	struct thread *td,	/* Calling thread. */
+	struct vnode *vp,	/* Mount point vnode. */
+	int fsflags,		/* Flags common to all filesystems. */
+	void *fsdata		/* Options local to the filesystem. */
+	)
+{
+	struct oexport_args oexport;
+	struct export_args export;
+	struct mount *mp;
+	int error, flag;
+
+	mtx_assert(&Giant, MA_OWNED);
+	ASSERT_VOP_ELOCKED(vp, __func__);
+	KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
+
+	if ((vp->v_vflag & VV_ROOT) == 0) {
+		vput(vp);
+		return (EINVAL);
+	}
+	mp = vp->v_mount;
+	/*
+	 * We only allow the filesystem to be reloaded if it
+	 * is currently mounted read-only.
+	 */
+	flag = mp->mnt_flag;
+	if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
+		vput(vp);
+		return (EOPNOTSUPP);	/* Needs translation */
+	}
+	/*
+	 * Only privileged root, or (if MNT_USER is set) the user that
+	 * did the original mount is permitted to update it.
+	 */
+	error = vfs_suser(mp, td);
+	if (error != 0) {
+		vput(vp);
+		return (error);
+	}
+	if (vfs_busy(mp, MBF_NOWAIT)) {
+		vput(vp);
+		return (EBUSY);
+	}
+	VI_LOCK(vp);
+	if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
+		VI_UNLOCK(vp);
+		vfs_unbusy(mp);
+		vput(vp);
+		return (EBUSY);
+	}
+	vp->v_iflag |= VI_MOUNT;
+	VI_UNLOCK(vp);
+	VOP_UNLOCK(vp, 0);
+
+	MNT_ILOCK(mp);
+	mp->mnt_flag &= ~MNT_UPDATEMASK;
+	mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
+	    MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
+	if ((mp->mnt_flag & MNT_ASYNC) == 0)
+		mp->mnt_kern_flag &= ~MNTK_ASYNC;
+	MNT_IUNLOCK(mp);
+	mp->mnt_optnew = fsdata;
+	vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
+
+	/*
+	 * Mount the filesystem.
+	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
+	 * get.  No freeing of cn_pnbuf.
+	 */
+        error = VFS_MOUNT(mp);
+
+	if (error == 0) {
+		/* Process the export option. */
+		if (vfs_copyopt(mp->mnt_optnew, "export", &export,
+		    sizeof(export)) == 0) {
+			error = vfs_export(mp, &export);
+		} else if (vfs_copyopt(mp->mnt_optnew, "export", &oexport,
+		    sizeof(oexport)) == 0) {
+			export.ex_flags = oexport.ex_flags;
+			export.ex_root = oexport.ex_root;
+			export.ex_anon = oexport.ex_anon;
+			export.ex_addr = oexport.ex_addr;
+			export.ex_addrlen = oexport.ex_addrlen;
+			export.ex_mask = oexport.ex_mask;
+			export.ex_masklen = oexport.ex_masklen;
+			export.ex_indexfile = oexport.ex_indexfile;
+			export.ex_numsecflavors = 0;
+			error = vfs_export(mp, &export);
+		}
+	}
+
+	MNT_ILOCK(mp);
+	if (error == 0) {
+		mp->mnt_flag &=	~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
+		    MNT_SNAPSHOT);
+	} else {
+		/*
+		 * If we fail, restore old mount flags. MNT_QUOTA is special,
+		 * because it is not part of MNT_UPDATEMASK, but it could have
+		 * changed in the meantime if quotactl(2) was called.
+		 * All in all we want current value of MNT_QUOTA, not the old
+		 * one.
+		 */
+		mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
+	}
+	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
+		mp->mnt_kern_flag |= MNTK_ASYNC;
+	else
+		mp->mnt_kern_flag &= ~MNTK_ASYNC;
+	MNT_IUNLOCK(mp);
+
+	if (error != 0)
+		goto end;
+
+	if (mp->mnt_opt != NULL)
+		vfs_freeopts(mp->mnt_opt);
+	mp->mnt_opt = mp->mnt_optnew;
+	(void)VFS_STATFS(mp, &mp->mnt_stat);
+	/*
+	 * Prevent external consumers of mount options from reading
+	 * mnt_optnew.
+	 */
+	mp->mnt_optnew = NULL;
+
+	if ((mp->mnt_flag & MNT_RDONLY) == 0) {
+		if (mp->mnt_syncer == NULL)
+			vfs_allocate_syncvnode(mp);
+	} else {
+		if (mp->mnt_syncer != NULL)
+			vrele(mp->mnt_syncer);
+		mp->mnt_syncer = NULL;
+	}
+end:
+	vfs_unbusy(mp);
+	VI_LOCK(vp);
+	vp->v_iflag &= ~VI_MOUNT;
+	VI_UNLOCK(vp);
+	vrele(vp);
+	return (error);
+}
 
 /*
  * vfs_domount(): actually attempt a filesystem mount.
@@ -808,16 +1057,11 @@ vfs_domount(
 	void *fsdata		/* Options local to the filesystem. */
 	)
 {
-	struct vnode *vp;
-	struct mount *mp;
 	struct vfsconf *vfsp;
-	struct oexport_args oexport;
-	struct export_args export;
-	int error, flag = 0;
-	struct vattr va;
 	struct nameidata nd;
+	struct vnode *vp;
+	int error;
 
-	mtx_assert(&Giant, MA_OWNED);
 	/*
 	 * Be ultra-paranoid about making sure the type and fspath
 	 * variables will fit in our mp buffers, including the
@@ -865,226 +1109,30 @@ vfs_domount(
 		if (jailed(td->td_ucred) && !(vfsp->vfc_flags & VFCF_JAIL))
 			return (EPERM);
 	}
+
 	/*
-	 * Get vnode to be covered
+	 * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
 	 */
-	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE,
-	    fspath, td);
-	if ((error = namei(&nd)) != 0)
+	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | MPSAFE | AUDITVNODE1,
+	    UIO_SYSSPACE, fspath, td);
+	error = namei(&nd);
+	if (error != 0)
 		return (error);
+	if (!NDHASGIANT(&nd))
+		mtx_lock(&Giant);
 	NDFREE(&nd, NDF_ONLY_PNBUF);
 	vp = nd.ni_vp;
-	if (fsflags & MNT_UPDATE) {
-		if ((vp->v_vflag & VV_ROOT) == 0) {
-			vput(vp);
-			return (EINVAL);
-		}
-		mp = vp->v_mount;
-		MNT_ILOCK(mp);
-		flag = mp->mnt_flag;
-		/*
-		 * We only allow the filesystem to be reloaded if it
-		 * is currently mounted read-only.
-		 */
-		if ((fsflags & MNT_RELOAD) &&
-		    ((mp->mnt_flag & MNT_RDONLY) == 0)) {
-			MNT_IUNLOCK(mp);
-			vput(vp);
-			return (EOPNOTSUPP);	/* Needs translation */
-		}
-		MNT_IUNLOCK(mp);
-		/*
-		 * Only privileged root, or (if MNT_USER is set) the user that
-		 * did the original mount is permitted to update it.
-		 */
-		error = vfs_suser(mp, td);
-		if (error) {
-			vput(vp);
-			return (error);
-		}
-		if (vfs_busy(mp, MBF_NOWAIT)) {
-			vput(vp);
-			return (EBUSY);
-		}
-		VI_LOCK(vp);
-		if ((vp->v_iflag & VI_MOUNT) != 0 ||
-		    vp->v_mountedhere != NULL) {
-			VI_UNLOCK(vp);
-			vfs_unbusy(mp);
-			vput(vp);
-			return (EBUSY);
-		}
-		vp->v_iflag |= VI_MOUNT;
-		VI_UNLOCK(vp);
-		MNT_ILOCK(mp);
-		mp->mnt_flag |= fsflags &
-		    (MNT_RELOAD | MNT_FORCE | MNT_UPDATE | MNT_SNAPSHOT | MNT_ROOTFS);
-		MNT_IUNLOCK(mp);
-		VOP_UNLOCK(vp, 0);
-		mp->mnt_optnew = fsdata;
-		vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
+	if ((fsflags & MNT_UPDATE) == 0) {
+		error = vfs_domount_first(td, vfsp, fspath, vp, fsflags,
+		    fsdata);
 	} else {
-		/*
-		 * If the user is not root, ensure that they own the directory
-		 * onto which we are attempting to mount.
-		 */
-		error = VOP_GETATTR(vp, &va, td->td_ucred);
-		if (error) {
-			vput(vp);
-			return (error);
-		}
-		if (va.va_uid != td->td_ucred->cr_uid) {
-			error = priv_check_cred(td->td_ucred, PRIV_VFS_ADMIN,
-			    0);
-			if (error) {
-				vput(vp);
-				return (error);
-			}
-		}
-		error = vinvalbuf(vp, V_SAVE, 0, 0);
-		if (error != 0) {
-			vput(vp);
-			return (error);
-		}
-		if (vp->v_type != VDIR) {
-			vput(vp);
-			return (ENOTDIR);
-		}
-		VI_LOCK(vp);
-		if ((vp->v_iflag & VI_MOUNT) != 0 ||
-		    vp->v_mountedhere != NULL) {
-			VI_UNLOCK(vp);
-			vput(vp);
-			return (EBUSY);
-		}
-		vp->v_iflag |= VI_MOUNT;
-		VI_UNLOCK(vp);
-		VOP_UNLOCK(vp, 0);
-
-		/*
-		 * Allocate and initialize the filesystem.
-		 */
-		mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
-
-		/* XXXMAC: pass to vfs_mount_alloc? */
-		mp->mnt_optnew = fsdata;
+		error = vfs_domount_update(td, vp, fsflags, fsdata);
 	}
+	mtx_unlock(&Giant);
 
-	/*
-	 * Set the mount level flags.
-	 */
-	MNT_ILOCK(mp);
-	mp->mnt_flag = (mp->mnt_flag & ~MNT_UPDATEMASK) |
-		(fsflags & (MNT_UPDATEMASK | MNT_FORCE | MNT_ROOTFS |
-			    MNT_RDONLY));
-	if ((mp->mnt_flag & MNT_ASYNC) == 0)
-		mp->mnt_kern_flag &= ~MNTK_ASYNC;
-	MNT_IUNLOCK(mp);
-	/*
-	 * Mount the filesystem.
-	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
-	 * get.  No freeing of cn_pnbuf.
-	 */
-        error = VFS_MOUNT(mp);
+	ASSERT_VI_UNLOCKED(vp, __func__);
+	ASSERT_VOP_UNLOCKED(vp, __func__);
 
-	/*
-	 * Process the export option only if we are
-	 * updating mount options.
-	 */
-	if (!error && (fsflags & MNT_UPDATE)) {
-		if (vfs_copyopt(mp->mnt_optnew, "export", &export,
-		    sizeof(export)) == 0)
-			error = vfs_export(mp, &export);
-		else if (vfs_copyopt(mp->mnt_optnew, "export", &oexport,
-			sizeof(oexport)) == 0) {
-			export.ex_flags = oexport.ex_flags;
-			export.ex_root = oexport.ex_root;
-			export.ex_anon = oexport.ex_anon;
-			export.ex_addr = oexport.ex_addr;
-			export.ex_addrlen = oexport.ex_addrlen;
-			export.ex_mask = oexport.ex_mask;
-			export.ex_masklen = oexport.ex_masklen;
-			export.ex_indexfile = oexport.ex_indexfile;
-			export.ex_numsecflavors = 0;
-			error = vfs_export(mp, &export);
-		}
-	}
-
-	if (!error) {
-		if (mp->mnt_opt != NULL)
-			vfs_freeopts(mp->mnt_opt);
-		mp->mnt_opt = mp->mnt_optnew;
-		(void)VFS_STATFS(mp, &mp->mnt_stat);
-	}
-	/*
-	 * Prevent external consumers of mount options from reading
-	 * mnt_optnew.
-	*/
-	mp->mnt_optnew = NULL;
-	if (mp->mnt_flag & MNT_UPDATE) {
-		MNT_ILOCK(mp);
-		if (error)
-			mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) |
-				(flag & ~MNT_QUOTA);
-		else
-			mp->mnt_flag &=	~(MNT_UPDATE | MNT_RELOAD |
-					  MNT_FORCE | MNT_SNAPSHOT);
-		if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
-			mp->mnt_kern_flag |= MNTK_ASYNC;
-		else
-			mp->mnt_kern_flag &= ~MNTK_ASYNC;
-		MNT_IUNLOCK(mp);
-		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
-			if (mp->mnt_syncer == NULL)
-				vfs_allocate_syncvnode(mp);
-		} else {
-			if (mp->mnt_syncer != NULL)
-				vrele(mp->mnt_syncer);
-			mp->mnt_syncer = NULL;
-		}
-		vfs_unbusy(mp);
-		VI_LOCK(vp);
-		vp->v_iflag &= ~VI_MOUNT;
-		VI_UNLOCK(vp);
-		vrele(vp);
-		return (error);
-	}
-	MNT_ILOCK(mp);
-	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
-		mp->mnt_kern_flag |= MNTK_ASYNC;
-	else
-		mp->mnt_kern_flag &= ~MNTK_ASYNC;
-	MNT_IUNLOCK(mp);
-	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
-	/*
-	 * Put the new filesystem on the mount list after root.
-	 */
-	cache_purge(vp);
-	VI_LOCK(vp);
-	vp->v_iflag &= ~VI_MOUNT;
-	VI_UNLOCK(vp);
-	if (!error) {
-		struct vnode *newdp;
-
-		vp->v_mountedhere = mp;
-		mtx_lock(&mountlist_mtx);
-		TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
-		mtx_unlock(&mountlist_mtx);
-		vfs_event_signal(NULL, VQ_MOUNT, 0);
-		if (VFS_ROOT(mp, LK_EXCLUSIVE, &newdp))
-			panic("mount: lost mount");
-		VOP_UNLOCK(newdp, 0);
-		VOP_UNLOCK(vp, 0);
-		mountcheckdirs(vp, newdp);
-		vrele(newdp);
-		if ((mp->mnt_flag & MNT_RDONLY) == 0)
-			vfs_allocate_syncvnode(mp);
-		vfs_unbusy(mp);
-	} else {
-		vfs_unbusy(mp);
-		vfs_mount_destroy(mp);
-		vput(vp);
-	}
 	return (error);
 }
 

From a8924cde7396a46a59efc1abd47feca4c90387bd Mon Sep 17 00:00:00 2001
From: Pyun YongHyeon 
Date: Wed, 8 Sep 2010 21:08:54 +0000
Subject: [PATCH 0567/1624] Correct definition of T2 mode bit of MRBE Message
 Page 5 Next Page Control Register.

---
 sys/dev/mii/brgphyreg.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/dev/mii/brgphyreg.h b/sys/dev/mii/brgphyreg.h
index 7bd6156fe9d..3f5ee5df8d7 100644
--- a/sys/dev/mii/brgphyreg.h
+++ b/sys/dev/mii/brgphyreg.h
@@ -390,7 +390,7 @@
 #define	BRGPHY_BLOCK_ADDR_MRBE			0x8350
 #define	BRGPHY_MRBE_MSG_PG5_NP			0x10
 #define	BRGPHY_MRBE_MSG_PG5_NP_MBRE		0x0001
-#define	BRGPHY_MRBE_MSG_PG5_NP_T2		0x0001
+#define	BRGPHY_MRBE_MSG_PG5_NP_T2		0x0002
 
 /* 5709S SerDes "IEEE Clause 73 User B0" Registers */
 #define	BRGPHY_BLOCK_ADDR_CL73_USER_B0		0x8370

From 54dcf92b7e8e7b23da0710202e96826c897a166d Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Thu, 9 Sep 2010 02:52:44 +0000
Subject: [PATCH 0568/1624] Minor clean up for nlge -
 nlna_submit_rx_free_desc() can use the same desc every time. Also merge
 couple of one-line functions into their caller.

---
 sys/mips/rmi/dev/nlge/if_nlge.c | 75 +++++++++------------------------
 1 file changed, 19 insertions(+), 56 deletions(-)

diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
index 8cb97bf6645..82092a955fd 100644
--- a/sys/mips/rmi/dev/nlge/if_nlge.c
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -148,7 +148,6 @@ static void	nlge_mediastatus(struct ifnet *ifp, struct ifmediareq *ifmr);
 
 /* Other internal/helper functions */
 static void 	*get_buf(void);
-static struct mbuf *get_mbuf(void);
 
 static void	nlna_add_to_port_set(struct nlge_port_set *pset,
     struct nlge_softc *sc);
@@ -170,8 +169,6 @@ static void 	nlna_reset_ports(struct nlna_softc *sc,
     struct xlr_gmac_block_t *blk);
 static struct nlna_softc *nlna_sc_init(device_t dev,
     struct xlr_gmac_block_t *blk);
-static __inline__ int nlna_send_free_desc(struct nlna_softc *nlna,
-    vm_paddr_t addr);
 static void	nlna_setup_intr(struct nlna_softc *sc);
 static void	nlna_smp_update_pde(void *dummy __unused);
 static void	nlna_submit_rx_free_desc(struct nlna_softc *sc,
@@ -206,7 +203,6 @@ static int	prepare_fmn_message(struct nlge_softc *sc,
     struct msgrng_msg *msg, uint32_t *n_entries, struct mbuf *m_head,
     uint64_t fr_stid, struct nlge_tx_desc **tx_desc);
 
-static void	release_mbuf(uint64_t phy_addr);
 static void 	release_tx_desc(vm_paddr_t phy_addr);
 static int	send_fmn_msg_tx(struct nlge_softc *, struct msgrng_msg *,
     uint32_t n_entries);
@@ -680,7 +676,7 @@ nlge_msgring_handler(int bucket, int size, int code, int stid,
 		if (is_p2p) {
 			release_tx_desc(phys_addr);
 		} else {
-			release_mbuf(phys_addr);
+			m_freem((struct mbuf *)(uintptr_t)phys_addr);
 		}
 
 		ifp = sc->nlge_if;
@@ -1009,39 +1005,23 @@ nlna_is_last_active_na(struct nlna_softc *sc)
 	return (id == 2 || xlr_board_info.gmac_block[id + 1].enabled == 0);
 }
 
-static __inline__ int
-nlna_send_free_desc(struct nlna_softc *sc, vm_paddr_t addr)
-{
-	struct msgrng_msg msg;
-	uint32_t msgrng_flags;
-	int i = 0, stid, code, ret;
-
-	stid = sc->rfrbucket;
-	memset(&msg, 0, sizeof(msg));
-	msg.msg0 = (uint64_t) addr & 0xffffffffe0ULL;
-
-	code = (sc->na_type == XLR_XGMAC) ? MSGRNG_CODE_XGMAC : MSGRNG_CODE_MAC;
-	do {
-		msgrng_flags = msgrng_access_enable();
-		ret = message_send_retry(1, code, stid, &msg);
-		msgrng_restore(msgrng_flags);
-		KASSERT(i++ < 100000, ("Too many credit fails\n"));
-	} while (ret != 0);
-	return (0);
-}
-
 static void
 nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc)
 {
+	struct msgrng_msg msg;
 	void           *ptr;
-	int		i;
-	int		ret;
+	uint32_t	msgrng_flags;
+	int		i, n, stid, ret, code;
 
 	if (n_desc > 1) {
 		PDEBUG("Sending %d free-in descriptors to station=%d\n", n_desc,
 		    sc->rfrbucket);
 	}
 
+	stid = sc->rfrbucket;
+	code = (sc->na_type == XLR_XGMAC) ? MSGRNG_CODE_XGMAC : MSGRNG_CODE_MAC;
+	memset(&msg, 0, sizeof(msg));
+
 	for (i = 0; i < n_desc; i++) {
 		ptr = get_buf();
 		if (!ptr) {
@@ -1051,10 +1031,14 @@ nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc)
 		}
 
 		/* Send the free Rx desc to the MAC */
-		ret = nlna_send_free_desc(sc, vtophys(ptr));
-		if (ret != 0)  /* no point trying other descriptors after
-		             a failure. */
-			break;
+		msg.msg0 = vtophys(ptr) & 0xffffffffe0ULL;
+		n = 0;
+		do {
+			msgrng_flags = msgrng_access_enable();
+			ret = message_send_retry(1, code, stid, &msg);
+			msgrng_restore(msgrng_flags);
+			KASSERT(n++ < 100000, ("Too many credit fails\n"));
+		} while (ret != 0);
 	}
 }
 
@@ -1981,15 +1965,6 @@ send_fmn_msg_tx(struct nlge_softc *sc, struct msgrng_msg *msg,
 	return (0);
 }
 
-static void
-release_mbuf(uint64_t phy_addr)
-{
-	struct mbuf	*m;
-
-	m = (struct mbuf *)((uint32_t) phy_addr);
-	m_freem(m);
-}
-
 static void
 release_tx_desc(vm_paddr_t paddr)
 {
@@ -2008,17 +1983,6 @@ release_tx_desc(vm_paddr_t paddr)
 	uma_zfree(nl_tx_desc_zone, tx_desc);
 }
 
-static struct mbuf *
-get_mbuf(void)
-{
-	struct mbuf *m_new;
-
-	if ((m_new = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR)) == NULL)
-		return NULL;
-	m_new->m_len = m_new->m_pkthdr.len = MCLBYTES;
-	return (m_new);
-}
-
 static void *
 get_buf(void)
 {
@@ -2026,10 +1990,9 @@ get_buf(void)
 	vm_paddr_t 	temp1, temp2;
 	unsigned int 	*md;
 
-	m_new = get_mbuf();
-	if (m_new == NULL)
-		return m_new;
-
+	if ((m_new = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR)) == NULL)
+		return NULL;
+	m_new->m_len = m_new->m_pkthdr.len = MCLBYTES;
 	m_adj(m_new, XLR_CACHELINE_SIZE - ((unsigned int)m_new->m_data & 0x1f));
 	md = (unsigned int *)m_new->m_data;
 	md[0] = (unsigned int)m_new;	/* Back Ptr */

From 8f3bacb08f4f451a4a0b4d98b6a8638139deccc0 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Thu, 9 Sep 2010 03:33:07 +0000
Subject: [PATCH 0569/1624] Add file missed in r212337, my bad...

---
 .../pc-sysinstall/backend/installimage.sh     | 34 +++++++++++++++++++
 1 file changed, 34 insertions(+)
 create mode 100755 usr.sbin/pc-sysinstall/backend/installimage.sh

diff --git a/usr.sbin/pc-sysinstall/backend/installimage.sh b/usr.sbin/pc-sysinstall/backend/installimage.sh
new file mode 100755
index 00000000000..242ecfedb0c
--- /dev/null
+++ b/usr.sbin/pc-sysinstall/backend/installimage.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+#-
+# Copyright (c) 2010 iXsystems, Inc.  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.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+#
+# $FreeBSD$
+
+# Source our functions scripts
+. ${BACKEND}/functions.sh
+
+IMAGE_FILE="${1}"
+DEVICE_FILE="${2}"
+
+write_image "${IMAGE_FILE}" "${DEVICE_FILE}"

From 1901fd2ffe70d702f5df4787183a494de4076b7d Mon Sep 17 00:00:00 2001
From: Ed Schouten 
Date: Thu, 9 Sep 2010 07:52:15 +0000
Subject: [PATCH 0570/1624] Let psm(4) use si_drv1 to refer to its softc.

---
 sys/dev/atkbdc/psm.c | 50 +++++++++++++++++++-------------------------
 1 file changed, 22 insertions(+), 28 deletions(-)

diff --git a/sys/dev/atkbdc/psm.c b/sys/dev/atkbdc/psm.c
index 30113bdad11..81d63f35bfc 100644
--- a/sys/dev/atkbdc/psm.c
+++ b/sys/dev/atkbdc/psm.c
@@ -143,11 +143,6 @@ __FBSDID("$FreeBSD$");
 #define	MOUSE_PS2PLUS_PACKET_TYPE(b)	\
     (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
 
-/* some macros */
-#define	PSM_UNIT(dev)		(dev2unit(dev) >> 1)
-#define	PSM_NBLOCKIO(dev)	(dev2unit(dev) & 1)
-#define	PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
-
 /* ring buffer */
 typedef struct ringbuf {
 	int		count;	/* # of valid elements in the buffer */
@@ -305,8 +300,6 @@ struct psm_softc {		/* Driver status information */
 	struct sigio	*async;		/* Processes waiting for SIGIO */
 };
 static devclass_t psm_devclass;
-#define	PSM_SOFTC(unit)	\
-    ((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
 
 /* driver state flags (state) */
 #define	PSM_VALID		0x80
@@ -1457,10 +1450,10 @@ psmattach(device_t dev)
 	}
 
 	/* Done */
-	sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
-	    "psm%d", unit);
-	sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
-	    "bpsm%d", unit);
+	sc->dev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "psm%d", unit);
+	sc->dev->si_drv1 = sc;
+	sc->bdev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "bpsm%d", unit);
+	sc->bdev->si_drv1 = sc;
 
 	if (!verbose)
 		printf("psm%d: model %s, device ID %d\n",
@@ -1504,14 +1497,13 @@ psmdetach(device_t dev)
 static int
 psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
 {
-	int unit = PSM_UNIT(dev);
 	struct psm_softc *sc;
 	int command_byte;
 	int err;
 	int s;
 
 	/* Get device data */
-	sc = PSM_SOFTC(unit);
+	sc = dev->si_drv1;
 	if ((sc == NULL) || (sc->state & PSM_VALID) == 0) {
 		/* the device is no longer valid/functioning */
 		return (ENXIO);
@@ -1521,7 +1513,7 @@ psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
 	if (sc->state & PSM_OPEN)
 		return (EBUSY);
 
-	device_busy(devclass_get_device(psm_devclass, unit));
+	device_busy(devclass_get_device(psm_devclass, sc->unit));
 
 	/* Initialize state */
 	sc->mode.level = sc->dflt_mode.level;
@@ -1565,7 +1557,8 @@ psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
 		kbdc_lock(sc->kbdc, FALSE);
 		splx(s);
 		log(LOG_ERR,
-		    "psm%d: unable to set the command byte (psmopen).\n", unit);
+		    "psm%d: unable to set the command byte (psmopen).\n",
+		    sc->unit);
 		return (EIO);
 	}
 	/*
@@ -1590,8 +1583,7 @@ psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
 static int
 psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
 {
-	int unit = PSM_UNIT(dev);
-	struct psm_softc *sc = PSM_SOFTC(unit);
+	struct psm_softc *sc = dev->si_drv1;
 	int stat[3];
 	int command_byte;
 	int s;
@@ -1615,7 +1607,8 @@ psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
 	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT |
 	    KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
 		log(LOG_ERR,
-		    "psm%d: failed to disable the aux int (psmclose).\n", unit);
+		    "psm%d: failed to disable the aux int (psmclose).\n",
+		    sc->unit);
 		/* CONTROLLER ERROR;
 		 * NOTE: we shall force our way through. Because the only
 		 * ill effect we shall see is that we may not be able
@@ -1643,12 +1636,13 @@ psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
 			 */
 			log(LOG_ERR,
 			    "psm%d: failed to disable the device (psmclose).\n",
-			    unit);
+			    sc->unit);
 		}
 
 		if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
 			log(LOG_DEBUG,
-			    "psm%d: failed to get status (psmclose).\n", unit);
+			    "psm%d: failed to get status (psmclose).\n",
+			    sc->unit);
 	}
 
 	if (!set_controller_command_byte(sc->kbdc,
@@ -1661,7 +1655,7 @@ psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
 		 */
 		log(LOG_ERR,
 		    "psm%d: failed to disable the aux port (psmclose).\n",
-		    unit);
+		    sc->unit);
 	}
 
 	/* remove anything left in the output buffer */
@@ -1676,7 +1670,7 @@ psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
 	/* close is almost always successful */
 	sc->state &= ~PSM_OPEN;
 	kbdc_lock(sc->kbdc, FALSE);
-	device_unbusy(devclass_get_device(psm_devclass, unit));
+	device_unbusy(devclass_get_device(psm_devclass, sc->unit));
 	return (0);
 }
 
@@ -1745,7 +1739,7 @@ tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status,
 static int
 psmread(struct cdev *dev, struct uio *uio, int flag)
 {
-	register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
+	struct psm_softc *sc = dev->si_drv1;
 	u_char buf[PSM_SMALLBUFSIZE];
 	int error = 0;
 	int s;
@@ -1757,7 +1751,7 @@ psmread(struct cdev *dev, struct uio *uio, int flag)
 	/* block until mouse activity occured */
 	s = spltty();
 	while (sc->queue.count <= 0) {
-		if (PSM_NBLOCKIO(dev)) {
+		if (dev != sc->bdev) {
 			splx(s);
 			return (EWOULDBLOCK);
 		}
@@ -1892,7 +1886,7 @@ unblock_mouse_data(struct psm_softc *sc, int c)
 static int
 psmwrite(struct cdev *dev, struct uio *uio, int flag)
 {
-	register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
+	struct psm_softc *sc = dev->si_drv1;
 	u_char buf[PSM_SMALLBUFSIZE];
 	int error = 0, i, l;
 
@@ -1925,7 +1919,7 @@ static int
 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
     struct thread *td)
 {
-	struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
+	struct psm_softc *sc = dev->si_drv1;
 	mousemode_t mode;
 	mousestatus_t status;
 #if (defined(MOUSE_GETVARS))
@@ -3270,7 +3264,7 @@ psmsoftintr(void *arg)
 		MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
 		MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
 	};
-	register struct psm_softc *sc = arg;
+	struct psm_softc *sc = arg;
 	mousestatus_t ms;
 	packetbuf_t *pb;
 	int x, y, z, c, l, s;
@@ -3519,7 +3513,7 @@ next:
 static int
 psmpoll(struct cdev *dev, int events, struct thread *td)
 {
-	struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
+	struct psm_softc *sc = dev->si_drv1;
 	int s;
 	int revents = 0;
 

From 4946fa67913c9753b98f58bd11820cd6f729f1c7 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 9 Sep 2010 07:55:13 +0000
Subject: [PATCH 0571/1624] Remove VI_MOUNT flag from vnode on VFS_MOUNT()
 failure.

---
 sys/kern/vfs_mount.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/sys/kern/vfs_mount.c b/sys/kern/vfs_mount.c
index 5dfa703950b..325426688fa 100644
--- a/sys/kern/vfs_mount.c
+++ b/sys/kern/vfs_mount.c
@@ -856,6 +856,9 @@ vfs_domount_first(
 	if (error != 0) {
 		vfs_unbusy(mp);
 		vfs_mount_destroy(mp);
+		VI_LOCK(vp);
+		vp->v_iflag &= ~VI_MOUNT;
+		VI_UNLOCK(vp);
 		vrele(vp);
 		return (error);
 	}

From d3555b6fc22201a449396be0ca21f6e235721bf6 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 9 Sep 2010 09:58:05 +0000
Subject: [PATCH 0572/1624] Fix two bugs in DTrace: * when the process exits,
 remove the associated USDT probes * when the process forks, duplicate the
 USDT probes.

Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/uts/common/dtrace/dtrace.c    | 16 ++++++++-----
 .../opensolaris/uts/common/dtrace/fasttrap.c  | 14 +++++++++++
 .../opensolaris/uts/common/sys/dtrace.h       |  5 ++++
 sys/kern/kern_fork.c                          | 24 ++++++++++++-------
 4 files changed, 44 insertions(+), 15 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
index a4684bd2653..f7aeecc13b6 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
@@ -9218,7 +9218,6 @@ dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
 	dtrace_difo_hold(dp);
 }
 
-#if defined(sun)
 static dtrace_difo_t *
 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
 {
@@ -9262,7 +9261,6 @@ dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
 	dtrace_difo_init(new, vstate);
 	return (new);
 }
-#endif
 
 static void
 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
@@ -14615,12 +14613,16 @@ dtrace_helpers_create(proc_t *p)
 }
 
 #if defined(sun)
-static void
-dtrace_helpers_destroy(void)
+static
+#endif
+void
+dtrace_helpers_destroy(proc_t *p)
 {
 	dtrace_helpers_t *help;
 	dtrace_vstate_t *vstate;
+#if defined(sun)
 	proc_t *p = curproc;
+#endif
 	int i;
 
 	mutex_enter(&dtrace_lock);
@@ -14707,7 +14709,10 @@ dtrace_helpers_destroy(void)
 	mutex_exit(&dtrace_lock);
 }
 
-static void
+#if defined(sun)
+static
+#endif
+void
 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
 {
 	dtrace_helpers_t *help, *newhelp;
@@ -14788,7 +14793,6 @@ dtrace_helpers_duplicate(proc_t *from, proc_t *to)
 	if (hasprovs)
 		dtrace_helper_provider_register(to, newhelp, NULL);
 }
-#endif
 
 #if defined(sun)
 /*
diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
index ba8abb323fb..b819f3b0720 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
@@ -456,6 +456,16 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 #if defined(sun)
 	ASSERT(p->p_dtrace_count > 0);
 #else
+	if (p->p_dtrace_helpers) {
+		/*
+		 * dtrace_helpers_duplicate() allocates memory.
+		 */
+		PROC_UNLOCK(p);
+		PROC_UNLOCK(cp);
+		dtrace_helpers_duplicate(p, cp);
+		PROC_LOCK(cp);
+		PROC_LOCK(p);
+	}
 	/*
 	 * This check is purposely here instead of in kern_fork.c because,
 	 * for legal resons, we cannot include the dtrace_cddl.h header
@@ -539,6 +549,10 @@ fasttrap_exec_exit(proc_t *p)
 	 * static probes are handled by the meta-provider remove entry point.
 	 */
 	fasttrap_provider_retire(p->p_pid, FASTTRAP_PID_NAME, 0);
+#if !defined(sun)
+	if (p->p_dtrace_helpers)
+		dtrace_helpers_destroy(p);
+#endif
 	PROC_LOCK(p);
 }
 
diff --git a/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h b/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h
index 1e20f566540..3bd8803615c 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace.h
@@ -2289,6 +2289,11 @@ extern int dtrace_blksuword32(uintptr_t, uint32_t *, int);
 extern void dtrace_getfsr(uint64_t *);
 #endif
 
+#if !defined(sun)
+extern void dtrace_helpers_duplicate(proc_t *, proc_t *);
+extern void dtrace_helpers_destroy(proc_t *);
+#endif
+
 #define	DTRACE_CPUFLAG_ISSET(flag) \
 	(cpu_core[curcpu].cpuc_dtrace_flags & (flag))
 
diff --git a/sys/kern/kern_fork.c b/sys/kern/kern_fork.c
index 29aa1213cfc..81631f6f36a 100644
--- a/sys/kern/kern_fork.c
+++ b/sys/kern/kern_fork.c
@@ -671,15 +671,6 @@ again:
 		p2->p_pfsflags = p1->p_pfsflags;
 	}
 
-#ifdef KDTRACE_HOOKS
-	/*
-	 * Tell the DTrace fasttrap provider about the new process
-	 * if it has registered an interest.
-	 */
-	if (dtrace_fasttrap_fork)
-		dtrace_fasttrap_fork(p1, p2);
-#endif
-
 	/*
 	 * This begins the section where we must prevent the parent
 	 * from being swapped.
@@ -744,6 +735,21 @@ again:
 	PROC_SLOCK(p2);
 	p2->p_state = PRS_NORMAL;
 	PROC_SUNLOCK(p2);
+#ifdef KDTRACE_HOOKS
+	/*
+	 * Tell the DTrace fasttrap provider about the new process
+	 * if it has registered an interest. We have to do this only after
+	 * p_state is PRS_NORMAL since the fasttrap module will use pfind()
+	 * later on.
+	 */
+	if (dtrace_fasttrap_fork) {
+		PROC_LOCK(p1);
+		PROC_LOCK(p2);
+		dtrace_fasttrap_fork(p1, p2);
+		PROC_UNLOCK(p2);
+		PROC_UNLOCK(p1);
+	}
+#endif
 
 	/*
 	 * If RFSTOPPED not requested, make child runnable and add to

From 37c380fbb559d7bc9f0955e801243f4a6347d7ab Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 9 Sep 2010 11:10:15 +0000
Subject: [PATCH 0573/1624] Don't clobber an existing target object file when
 doing the DTrace linking process. This is needed because we change the source
 object files and the second this dtrace -G is run, no probes will be found.
 This hack allows us to build postgres with DTrace probes enabled. I'll try to
 find a way to fix this without needing this hack.

Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/lib/libdtrace/common/dt_link.c       | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c
index 0b8899ab8b5..ca355eacdd7 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c
@@ -1616,6 +1616,18 @@ dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
 	int eprobes = 0, ret = 0;
 
 #if !defined(sun)
+	if (access(file, R_OK) == 0) {
+		fprintf(stderr, "dtrace: target object (%s) already exists. "
+		    "Please remove the target\ndtrace: object and rebuild all "
+		    "the source objects if you wish to run the DTrace\n"
+		    "dtrace: linking process again\n", file);
+		/*
+		 * Several build infrastructures run DTrace twice (e.g.
+		 * postgres) and we don't want the build to fail. Return
+		 * 0 here since this isn't really a fatal error.
+		 */
+		return (0);
+	}
 	/* XXX Should get a temp file name here. */
 	snprintf(tfile, sizeof(tfile), "%s.tmp", file);
 #endif

From c14e163ad105ea63fe90eb5f6e1fe6dad0511067 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 9 Sep 2010 13:17:30 +0000
Subject: [PATCH 0574/1624] Fix a problem where device detection would work
 unreliably on Serverworks K2 SATA controllers. The chip's status register
 must be read first, and as a long, for other registers to be correctly
 updated after a command, and this includes the command sequence in device
 detection as well as the previously handled case after interrupts. While
 here, clean up some previous hacks related to this controller.

Reported by:	many
Reviewed by:	mav
MFC after:	3 weeks
---
 sys/dev/ata/ata-all.h                  |  1 +
 sys/dev/ata/ata-lowlevel.c             | 10 ++++--
 sys/dev/ata/chipsets/ata-serverworks.c | 43 +++++++++++++++-----------
 3 files changed, 34 insertions(+), 20 deletions(-)

diff --git a/sys/dev/ata/ata-all.h b/sys/dev/ata/ata-all.h
index 6132eab4101..0f09a1f29a2 100644
--- a/sys/dev/ata/ata-all.h
+++ b/sys/dev/ata/ata-all.h
@@ -566,6 +566,7 @@ struct ata_channel {
 #define         ATA_SATA		0x80
 #define         ATA_DMA_BEFORE_CMD	0x100
 #define         ATA_KNOWN_PRESENCE	0x200
+#define         ATA_STATUS_IS_LONG	0x400
 
     int				pm_level;	/* power management level */
     int                         devices;        /* what is present */
diff --git a/sys/dev/ata/ata-lowlevel.c b/sys/dev/ata/ata-lowlevel.c
index 91748233e5c..288fd174b01 100644
--- a/sys/dev/ata/ata-lowlevel.c
+++ b/sys/dev/ata/ata-lowlevel.c
@@ -516,10 +516,13 @@ ata_generic_reset(device_t dev)
 	if ((mask & 0x01) && (stat0 & ATA_S_BUSY)) {
 	    ATA_IDX_OUTB(ch, ATA_DRIVE, ATA_D_IBM | ATA_DEV(ATA_MASTER));
 	    DELAY(10);
+	    if (ch->flags & ATA_STATUS_IS_LONG)
+		    stat0 = ATA_IDX_INL(ch, ATA_STATUS) & 0xff;
+	    else
+		    stat0 = ATA_IDX_INB(ch, ATA_STATUS);
 	    err = ATA_IDX_INB(ch, ATA_ERROR);
 	    lsb = ATA_IDX_INB(ch, ATA_CYL_LSB);
 	    msb = ATA_IDX_INB(ch, ATA_CYL_MSB);
-	    stat0 = ATA_IDX_INB(ch, ATA_STATUS);
 	    if (bootverbose)
 		device_printf(dev,
 			      "stat0=0x%02x err=0x%02x lsb=0x%02x msb=0x%02x\n",
@@ -546,10 +549,13 @@ ata_generic_reset(device_t dev)
 	    !((mask & 0x01) && (stat0 & ATA_S_BUSY))) {
 	    ATA_IDX_OUTB(ch, ATA_DRIVE, ATA_D_IBM | ATA_DEV(ATA_SLAVE));
 	    DELAY(10);
+	    if (ch->flags & ATA_STATUS_IS_LONG)
+		    stat1 = ATA_IDX_INL(ch, ATA_STATUS) & 0xff;
+	    else
+		    stat1 = ATA_IDX_INB(ch, ATA_STATUS);
 	    err = ATA_IDX_INB(ch, ATA_ERROR);
 	    lsb = ATA_IDX_INB(ch, ATA_CYL_LSB);
 	    msb = ATA_IDX_INB(ch, ATA_CYL_MSB);
-	    stat1 = ATA_IDX_INB(ch, ATA_STATUS);
 	    if (bootverbose)
 		device_printf(dev,
 			      "stat1=0x%02x err=0x%02x lsb=0x%02x msb=0x%02x\n",
diff --git a/sys/dev/ata/chipsets/ata-serverworks.c b/sys/dev/ata/chipsets/ata-serverworks.c
index cd6db3d28d7..1771dc42b35 100644
--- a/sys/dev/ata/chipsets/ata-serverworks.c
+++ b/sys/dev/ata/chipsets/ata-serverworks.c
@@ -58,9 +58,8 @@ static int ata_serverworks_ch_detach(device_t dev);
 static void ata_serverworks_tf_read(struct ata_request *request);
 static void ata_serverworks_tf_write(struct ata_request *request);
 static int ata_serverworks_setmode(device_t dev, int target, int mode);
-#ifdef __powerpc__
+static void ata_serverworks_sata_reset(device_t dev);
 static int ata_serverworks_status(device_t dev);
-#endif
 
 /* misc defines */
 #define SWKS_33		0
@@ -101,7 +100,6 @@ ata_serverworks_probe(device_t dev)
     return (BUS_PROBE_DEFAULT);
 }
 
-#ifdef __powerpc__
 static int
 ata_serverworks_status(device_t dev)
 {
@@ -123,7 +121,6 @@ ata_serverworks_status(device_t dev)
 
     return ata_pci_status(dev);
 }
-#endif
 
 static int
 ata_serverworks_chipinit(device_t dev)
@@ -145,6 +142,7 @@ ata_serverworks_chipinit(device_t dev)
 	ctlr->ch_detach = ata_serverworks_ch_detach;
 	ctlr->setmode = ata_sata_setmode;
 	ctlr->getrev = ata_sata_getrev;
+	ctlr->reset = ata_serverworks_sata_reset;
 	return 0;
     }
     else if (ctlr->chip->cfg1 == SWKS_33) {
@@ -210,30 +208,20 @@ ata_serverworks_ch_attach(device_t dev)
     ch->r_io[ATA_SERROR].offset = ch_offset + 0x44;
     ch->r_io[ATA_SCONTROL].offset = ch_offset + 0x48;
 
-    ch->flags |= ATA_NO_SLAVE;
-    ch->flags |= ATA_SATA;
+    ch->flags |= ATA_NO_SLAVE | ATA_SATA | ATA_KNOWN_PRESENCE;
     ata_pci_hw(dev);
     ch->hw.tf_read = ata_serverworks_tf_read;
     ch->hw.tf_write = ata_serverworks_tf_write;
-#ifdef __powerpc__
-    ch->hw.status = ata_serverworks_status;
-#endif
 
     if (ctlr->chip->chipid == ATA_K2) {
 	/*
-	 * The revision 1 K2 SATA controller has interesting bugs. Patch them.
-	 * These magic numbers regulate interrupt delivery in the first few
-	 * cases and are pure magic in the last case.
-	 *
-	 * Values obtained from the Darwin driver.
+	 * Set SICR registers to turn off waiting for a status message
+	 * before sending FIS. Values obtained from the Darwin driver.
 	 */
 
-	ATA_IDX_OUTB(ch, ATA_BMSTAT_PORT, 0x04);
-	ATA_IDX_OUTL(ch, ATA_SERROR, 0xffffffff);
-	ATA_IDX_OUTL(ch, ATA_SCONTROL, 0x00000300);
-	ATA_OUTL(ctlr->r_res2, ch_offset + 0x88, 0);
 	ATA_OUTL(ctlr->r_res2, ch_offset + 0x80,
 	    ATA_INL(ctlr->r_res2, ch_offset + 0x80) & ~0x00040000);
+	ATA_OUTL(ctlr->r_res2, ch_offset + 0x88, 0);
 
 	/*
 	 * Some controllers have a bug where they will send the command
@@ -244,6 +232,14 @@ ata_serverworks_ch_attach(device_t dev)
 	 */
 
 	ch->flags |= ATA_DMA_BEFORE_CMD;
+
+	/*
+	 * The status register must be read as a long to fill the other
+	 * registers.
+	 */
+	
+	ch->hw.status = ata_serverworks_status;
+	ch->flags |= ATA_STATUS_IS_LONG;
     }
 
     /* chip does not reliably do 64K DMA transfers */
@@ -404,4 +400,15 @@ ata_serverworks_setmode(device_t dev, int target, int mode)
 	return (mode);
 }
 
+static void
+ata_serverworks_sata_reset(device_t dev)
+{
+	struct ata_channel *ch = device_get_softc(dev);
+
+	if (ata_sata_phy_reset(dev, -1, 1))
+		ata_generic_reset(dev);
+	else
+		ch->devices = 0;
+}
+
 ATA_DECLARE_DRIVER(ata_serverworks);

From 42768fec0fe3ff53d4ea4ea1bf839ab2f83a0506 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 9 Sep 2010 13:32:58 +0000
Subject: [PATCH 0575/1624] On architectures with non-tree-based page tables
 like PowerPC, every page in a range must be checked when calling
 pmap_remove(). Calling pmap_remove() from vm_pageout_map_deactivate_pages()
 with the entire range of the map could result in attempting to demap an
 extraordinary number of pages (> 10^15), so iterate through each map entry
 and unmap each of them individually.

MFC after:	6 weeks
---
 sys/vm/vm_pageout.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/sys/vm/vm_pageout.c b/sys/vm/vm_pageout.c
index f4109c1136e..3d96d9ec3db 100644
--- a/sys/vm/vm_pageout.c
+++ b/sys/vm/vm_pageout.c
@@ -701,8 +701,11 @@ vm_pageout_map_deactivate_pages(map, desired)
 	 * table pages.
 	 */
 	if (desired == 0 && nothingwired) {
-		pmap_remove(vm_map_pmap(map), vm_map_min(map),
-		    vm_map_max(map));
+		tmpe = map->header.next;
+		while (tmpe != &map->header) {
+			pmap_remove(vm_map_pmap(map), tmpe->start, tmpe->end);
+			tmpe = tmpe->next;
+		}
 	}
 	vm_map_unlock(map);
 }

From a8c0af5906885f2c0e5a70f9b0746369658b128d Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Thu, 9 Sep 2010 15:45:11 +0000
Subject: [PATCH 0576/1624] Fix the experimental NFS client so that it doesn't
 panic when NFSv2,3 byte range locking is attempted. A fix that allows the
 nlm_advlock() to work with both clients is in progress, but may take a while.
 As such, I am doing this commit so that the kernel doesn't panic in the
 meantime.

Submitted by:	jh
MFC after:	2 weeks
---
 sys/fs/nfsclient/nfs_clvnops.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/sys/fs/nfsclient/nfs_clvnops.c b/sys/fs/nfsclient/nfs_clvnops.c
index 1e4e8a67e0d..8f1ec27c3bb 100644
--- a/sys/fs/nfsclient/nfs_clvnops.c
+++ b/sys/fs/nfsclient/nfs_clvnops.c
@@ -2939,8 +2939,10 @@ nfs_advlock(struct vop_advlock_args *ap)
 		} else {
 			if (ncl_advlock_p)
 				error = ncl_advlock_p(ap);
-			else
+			else {
+				VOP_UNLOCK(vp, 0);
 				error = ENOLCK;
+			}
 		}
 	}
 	return (error);

From 61473c5fd1333cbae03fe65f322a0b125545dfd1 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 9 Sep 2010 16:06:55 +0000
Subject: [PATCH 0577/1624] Reorder statistics tracking and table lock
 acquisitions already in place to avoid race conditions updating the PVO
 statistics.

---
 sys/powerpc/aim/mmu_oea64.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index a6aebdeeedc..dc055a38699 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -2424,7 +2424,6 @@ moea64_pvo_enter(pmap_t pm, uma_zone_t zone, struct pvo_head *pvo_head,
 	 * the bootstrap pool.
 	 */
 
-	moea64_pvo_enter_calls++;
 	first = 0;
 	bootstrap = (flags & PVO_BOOTSTRAP);
 
@@ -2444,6 +2443,8 @@ moea64_pvo_enter(pmap_t pm, uma_zone_t zone, struct pvo_head *pvo_head,
 	 */
 	LOCK_TABLE();
 
+	moea64_pvo_enter_calls++;
+
 	LIST_FOREACH(pvo, &moea64_pvo_table[ptegidx], pvo_olink) {
 		if (pvo->pvo_pmap == pm && PVO_VADDR(pvo) == va) {
 			if ((pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN) == pa &&
@@ -2608,14 +2609,15 @@ moea64_pvo_remove(struct pvo_entry *pvo)
 	 * if we aren't going to reuse it.
 	 */
 	LIST_REMOVE(pvo, pvo_olink);
+
+	moea64_pvo_entries--;
+	moea64_pvo_remove_calls++;
+
 	UNLOCK_TABLE();
 
 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
 		uma_zfree((pvo->pvo_vaddr & PVO_MANAGED) ? moea64_mpvo_zone :
 		    moea64_upvo_zone, pvo);
-
-	moea64_pvo_entries--;
-	moea64_pvo_remove_calls++;
 }
 
 static struct pvo_entry *

From db960cf00abb536d73419540e1b13f979944dffa Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 9 Sep 2010 16:27:02 +0000
Subject: [PATCH 0578/1624] Fix small errors in the sbuf(9) man page.

---
 share/man/man9/sbuf.9 | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/share/man/man9/sbuf.9 b/share/man/man9/sbuf.9
index 58efce039fd..abe5831f56b 100644
--- a/share/man/man9/sbuf.9
+++ b/share/man/man9/sbuf.9
@@ -98,7 +98,7 @@
 The
 .Nm
 family of functions allows one to safely allocate, construct and
-release bounded null-terminated strings in kernel space.
+release bounded NUL-terminated strings in kernel space.
 Instead of arrays of characters, these functions operate on structures
 called
 .Fa sbufs ,
@@ -289,7 +289,7 @@ overflowed.
 .Pp
 The
 .Fn sbuf_finish
-function null-terminates the
+function NUL-terminates the
 .Fa sbuf
 and marks it as finished, which means that it may no longer be
 modified using
@@ -298,7 +298,10 @@ modified using
 .Fn sbuf_cpy ,
 .Fn sbuf_printf
 or
-.Fn sbuf_putc .
+.Fn sbuf_putc ,
+until
+.Fn sbuf_clear
+is used to reset the sbuf.
 .Pp
 The
 .Fn sbuf_data
@@ -309,7 +312,9 @@ functions return the actual string and its length, respectively;
 only works on a finished
 .Fa sbuf .
 .Fn sbuf_done
-returns non-zero if the sbuf is finished.
+returns non-zero if the
+.Fa sbuf
+is finished.
 .Sh NOTES
 If an operation caused an
 .Fa sbuf

From 01f6f5fcd47d0d492451a0291e19b1e656329baa Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 9 Sep 2010 16:51:52 +0000
Subject: [PATCH 0579/1624] Refactor sbuf code so that most uses of
 sbuf_extend() are in a new sbuf_put_byte().  This makes it easier to add
 drain functionality when a buffer would overflow as there are fewer code
 points.

Reviewed by:	phk
---
 sys/kern/subr_sbuf.c | 94 ++++++++++++++++++++++++++++++++------------
 1 file changed, 69 insertions(+), 25 deletions(-)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index f460d883673..bca87053120 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -271,6 +271,41 @@ sbuf_setpos(struct sbuf *s, int pos)
 	return (0);
 }
 
+/*
+ * Append a byte to an sbuf.  This is the core function for appending
+ * to an sbuf and is the main place that deals with extending the
+ * buffer and marking overflow.
+ */
+static void
+sbuf_put_byte(int c, struct sbuf *s)
+{
+
+	assert_sbuf_integrity(s);
+	assert_sbuf_state(s, 0);
+
+	if (SBUF_HASOVERFLOWED(s))
+		return;
+	if (SBUF_FREESPACE(s) <= 0) {
+		if (sbuf_extend(s, 1) < 0) {
+			SBUF_SETFLAG(s, SBUF_OVERFLOWED);
+			return;
+		}
+	}
+	s->s_buf[s->s_len++] = c;
+}
+
+/*
+ * Append a non-NUL character to an sbuf.  This prototype signature is
+ * suitable for use with kvprintf(9).
+ */
+static void
+sbuf_putc_func(int c, void *arg)
+{
+
+	if (c != '\0')
+		sbuf_put_byte(c, arg);
+}
+
 /*
  * Append a byte string to an sbuf.
  */
@@ -278,21 +313,18 @@ int
 sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
 {
 	const char *str = buf;
+	const char *end = str + len;
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
 
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
-	for (; len; len--) {
-		if (!SBUF_HASROOM(s) && sbuf_extend(s, len) < 0)
-			break;
-		s->s_buf[s->s_len++] = *str++;
-	}
-	if (len > 0) {
-		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
-		return (-1);
-	}
+	for (; str < end; str++) {
+		sbuf_put_byte(*str, s);
+		if (SBUF_HASOVERFLOWED(s))
+			return (-1);
+ 	}
 	return (0);
 }
 
@@ -352,13 +384,9 @@ sbuf_cat(struct sbuf *s, const char *str)
 		return (-1);
 
 	while (*str != '\0') {
-		if (!SBUF_HASROOM(s) && sbuf_extend(s, strlen(str)) < 0)
-			break;
-		s->s_buf[s->s_len++] = *str++;
-	}
-	if (*str != '\0') {
-		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
-		return (-1);
+		sbuf_put_byte(*str, s);
+		if (SBUF_HASOVERFLOWED(s))
+			return (-1);
 	}
 	return (0);
 }
@@ -417,6 +445,23 @@ sbuf_cpy(struct sbuf *s, const char *str)
 /*
  * Format the given argument list and append the resulting string to an sbuf.
  */
+#ifdef _KERNEL
+int
+sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
+{
+
+	assert_sbuf_integrity(s);
+	assert_sbuf_state(s, 0);
+
+	KASSERT(fmt != NULL,
+	    ("%s called with a NULL format string", __func__));
+
+	(void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
+	if (SBUF_HASOVERFLOWED(s))
+		return (-1);
+	return (0);
+}
+#else /* !_KERNEL */
 int
 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 {
@@ -432,6 +477,12 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
 
+	/*
+	 * For the moment, there is no way to get vsnprintf(3) to hand
+	 * back a character at a time, to push everything into
+	 * sbuf_putc_func() as was done for the kernel.
+	 */
+
 	do {
 		va_copy(ap_copy, ap);
 		len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
@@ -462,6 +513,7 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 		return (-1);
 	return (0);
 }
+#endif /* _KERNEL */
 
 /*
  * Format the given arguments and append the resulting string to an sbuf.
@@ -485,17 +537,9 @@ int
 sbuf_putc(struct sbuf *s, int c)
 {
 
-	assert_sbuf_integrity(s);
-	assert_sbuf_state(s, 0);
-
+	sbuf_putc_func(c, s);
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
-	if (!SBUF_HASROOM(s) && sbuf_extend(s, 1) < 0) {
-		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
-		return (-1);
-	}
-	if (c != '\0')
-		s->s_buf[s->s_len++] = c;
 	return (0);
 }
 

From 2e4e56742ee27fc31553283cf143372eb01efb7d Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Thu, 9 Sep 2010 17:45:48 +0000
Subject: [PATCH 0580/1624] Clean up and update sys/mips/rmi/rmi_mips_exts.h

- Provide 64 bit implementations for some macros. On n64 and n32,
  don't split 64 bit values.
- No need for 32 bit ops for control registers.
- Fix few bugs (write control reg, write_c0_register64).
- Re-write EIRR/EIMR/CPUID operations using read_c0_registerXX, no
  need of inline assembly.
- rename control reg access functions to avoid phnx, update callers.
- stlye/whitespace fixes.
---
 sys/mips/rmi/rmi_mips_exts.h | 652 ++++++++++++++++++-----------------
 sys/mips/rmi/xlr_machdep.c   |   6 +-
 sys/mips/rmi/xlr_pci.c       |  18 +-
 3 files changed, 340 insertions(+), 336 deletions(-)

diff --git a/sys/mips/rmi/rmi_mips_exts.h b/sys/mips/rmi/rmi_mips_exts.h
index 75e4a00047f..6f86ed257bf 100644
--- a/sys/mips/rmi/rmi_mips_exts.h
+++ b/sys/mips/rmi/rmi_mips_exts.h
@@ -30,234 +30,286 @@
  * $FreeBSD$
  */
 #ifndef __MIPS_EXTS_H__
-#define __MIPS_EXTS_H__
+#define	__MIPS_EXTS_H__
 
-#define CPU_BLOCKID_IFU      0
-#define CPU_BLOCKID_ICU      1
-#define CPU_BLOCKID_IEU      2
-#define CPU_BLOCKID_LSU      3
-#define CPU_BLOCKID_MMU      4
-#define CPU_BLOCKID_PRF      5
+#define	CPU_BLOCKID_IFU		0
+#define	CPU_BLOCKID_ICU		1
+#define	CPU_BLOCKID_IEU		2
+#define	CPU_BLOCKID_LSU		3
+#define	CPU_BLOCKID_MMU		4
+#define	CPU_BLOCKID_PRF		5
 
-#define LSU_CERRLOG_REGID    9
+#define	LSU_CERRLOG_REGID    9
 
-static __inline__ unsigned int read_32bit_phnx_ctrl_reg(int block, int reg)
+#if defined(__mips_n64) || defined(__mips_n32)
+static __inline uint64_t
+read_xlr_ctrl_register(int block, int reg)
 { 
-	unsigned int __res;
+	uint64_t res;
 
-	__asm__ __volatile__(                                   
-			".set\tpush\n\t"                            
-			".set\tnoreorder\n\t" 
-			"move $9, %1\n" 
-			/* "mfcr\t$8, $9\n\t"          */
-			".word 0x71280018\n"
-			"move %0, $8\n"
-			".set\tpop"       
-			: "=r" (__res) : "r"((block<<8)|reg)
-			: "$8", "$9"
-			);
-	return __res;
+	__asm__ __volatile__(
+	    ".set	push\n\t"
+	    ".set	noreorder\n\t"
+	    "move	$9, %1\n\t"
+	    ".word	0x71280018\n\t"  /* mfcr $8, $9 */
+	    "move	%0, $8\n\t"
+	    ".set	pop\n"
+	    : "=r" (res) : "r"((block << 8) | reg)
+	    : "$8", "$9"
+	);
+	return (res);
 }
 
-static __inline__ void write_32bit_phnx_ctrl_reg(int block, int reg, unsigned int value)
+static __inline void
+write_xlr_ctrl_register(int block, int reg, uint64_t value)
 {
-	__asm__ __volatile__(            
-			".set\tpush\n\t"
-			".set\tnoreorder\n\t"
-			"move $8, %0\n"
-			"move $9, %1\n"
-			/* "mtcr\t$8, $9\n\t"  */
-			".word 0x71280019\n"
-			".set\tpop"
-			:
-			: "r" (value), "r"((block<<8)|reg)
-			: "$8", "$9"
-			);
+	__asm__ __volatile__(
+	    ".set	push\n\t"
+	    ".set	noreorder\n\t"
+	    "move	$8, %0\n"
+	    "move	$9, %1\n"
+	    ".word	0x71280019\n"    /* mtcr $8, $9  */
+	    ".set	pop\n"
+	    :
+	    : "r" (value), "r" ((block << 8) | reg)
+	    : "$8", "$9"
+	);
 }
 
-static __inline__ unsigned long long read_64bit_phnx_ctrl_reg(int block, int reg)
+#else /* !(defined(__mips_n64) || defined(__mips_n32)) */
+
+static __inline uint64_t
+read_xlr_ctrl_register(int block, int reg)
 {	
-	unsigned int high, low;						
-	
-	__asm__ __volatile__(					
-		".set\tmips64\n\t"				
-		"move    $9, %2\n"
-		/* "mfcr    $8, $9\n" */
-		".word   0x71280018\n"
-		"dsrl32  %0, $8, 0\n\t"			        
-		"dsll32  $8, $8, 0\n\t"                         
-		"dsrl32  %1, $8, 0\n\t"                         
-		".set mips0"					
-		: "=r" (high), "=r"(low)
-		: "r"((block<<8)|reg)
-		: "$8", "$9"
-		);	
-		
-	return ( (((unsigned long long)high)<<32) | low);
+	uint32_t high, low;
+
+	__asm__ __volatile__(
+	    ".set	push\n\t"
+	    ".set	noreorder\n\t"
+	    ".set	mips64\n\t"
+	    "move	$9, %2\n"
+	    ".word 	0x71280018\n"  /* "mfcr    $8, $9\n" */
+	    "dsra32	%0, $8, 0\n\t"
+	    "sll	%1, $8, 0\n\t"
+	    ".set	pop"					
+	    : "=r" (high), "=r"(low)
+	    : "r" ((block << 8) | reg)
+	    : "$8", "$9");
+
+	return ( (((uint64_t)high) << 32) | low);
 }
 
-static __inline__ void write_64bit_phnx_ctrl_reg(int block, int reg,unsigned long long value)
+static __inline void
+write_xlr_ctrl_register(int block, int reg, uint64_t value)
 {
-	__uint32_t low, high;
+	uint32_t low, high;
 	high = value >> 32;
 	low = value & 0xffffffff;
 
 	__asm__ __volatile__(
-		".set push\n"
-		".set noreorder\n"
-		".set mips4\n\t"
-		/* Set up "rs" */
-		"move $9, %0\n"
+	   ".set	push\n\t"
+	   ".set	noreorder\n\t"
+	   ".set	mips64\n\t"
+	   "dsll32	$9, %0, 0\n\t"
+	   "dsll32	$8, %1, 0\n\t"
+	   "dsrl32	$8, $8, 0\n\t"
+	   "or		$8, $9, $8\n\t"
+	   "move	$9, %2\n\t"
+	   ".word	0x71280019\n\t" /* mtcr $8, $9 */
+	   ".set	pop\n"
+	   :  /* No outputs */
+	   : "r" (high), "r" (low), "r"((block << 8) | reg)
+	   : "$8", "$9");
+}
+#endif /* defined(__mips_n64) || defined(__mips_n32) */
 
-		/* Store 64 bit value in "rt" */
-		"dsll32 $10, %1, 0  \n\t"
-		"dsll32 $8, %2, 0  \n\t"
-		"dsrl32 $8, $8, 0  \n\t"
-		"or     $10, $8, $8 \n\t"
+/*
+ * 32 bit read write for c0
+ */
+#define read_c0_register32(reg, sel)				\
+({								\
+	 uint32_t __rv;						\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips32\n\t"				\
+	    "mfc0	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	    : "=r" (__rv) : "i" (reg), "i" (sel) );		\
+	__rv;							\
+ })
 
-		".word 0x71280019\n" /* mtcr $8, $9 */
+#define write_c0_register32(reg,  sel, value)			\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips32\n\t"				\
+	    "mtc0	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	: : "r" (value), "i" (reg), "i" (sel) );
 
-		".set pop\n"
+#define read_c2_register32(reg, sel)				\
+({								\
+	uint32_t __rv;						\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips32\n\t"				\
+	    "mfc2	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	    : "=r" (__rv) : "i" (reg), "i" (sel) );		\
+	__rv;							\
+ })
 
-		:  /* No outputs */
-		: "r"((block<<8)|reg), "r" (high), "r" (low)
-		: "$8", "$9", "$10"
-		);
+#define write_c2_register32(reg,  sel, value)			\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips32\n\t"				\
+	    "mtc2	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	: : "r" (value), "i" (reg), "i" (sel) );
+
+#if defined(__mips_n64) || defined(__mips_n32)
+/*
+ * On 64 bit compilation, the operations are simple
+ */
+#define read_c0_register64(reg, sel)				\
+({								\
+	uint64_t __rv;						\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dmfc0	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	    : "=r" (__rv) : "i" (reg), "i" (sel) );		\
+	__rv;							\
+ })
+
+#define write_c0_register64(reg,  sel, value)			\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dmtc0	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	: : "r" (value), "i" (reg), "i" (sel) );
+
+#define read_c2_register64(reg, sel)				\
+({								\
+	uint64_t __rv;						\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dmfc2	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	    : "=r" (__rv) : "i" (reg), "i" (sel) );		\
+	__rv;							\
+ })
+
+#define write_c2_register64(reg,  sel, value)			\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dmtc2	%0, $%1, %2\n\t"			\
+	    ".set	pop\n"					\
+	: : "r" (value), "i" (reg), "i" (sel) );
+
+#else /* ! (defined(__mips_n64) || defined(__mips_n32)) */
+
+/*
+ * 32 bit compilation, 64 bit values has to split 
+ */
+#define read_c0_register64(reg, sel)				\
+({								\
+	uint32_t __high, __low;					\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	noreorder\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dmfc0	$8, $%2, %3\n\t"			\
+	    "dsra32	%0, $8, 0\n\t"				\
+	    "sll	%1, $8, 0\n\t"				\
+	    ".set	pop\n"					\
+	    : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel)	\
+	    : "$8");						\
+	((uint64_t)__high << 32) | __low;			\
+})
+
+#define write_c0_register64(reg, sel, value)			\
+do {								\
+       uint32_t __high = value >> 32;				\
+       uint32_t __low = value & 0xffffffff;			\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	noreorder\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dsll32	$8, %1, 0\n\t"				\
+	    "dsll32	$9, %0, 0\n\t"				\
+	    "dsrl32	$8, $8, 0\n\t"				\
+	    "or		$8, $8, $9\n\t"				\
+	    "dmtc0	$8, $%2, %3\n\t"			\
+	    ".set	pop"					\
+	    :: "r"(__high), "r"(__low),	 "i"(reg), "i"(sel)	\
+	    :"$8", "$9");					\
+} while(0)
+
+#define read_c2_register64(reg, sel)				\
+({								\
+	uint32_t __high, __low;					\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	noreorder\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dmfc2	$8, $%2, %3\n\t"			\
+	    "dsra32	%0, $8, 0\n\t"				\
+	    "sll	%1, $8, 0\n\t"				\
+	    ".set	pop\n"					\
+	    : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel)	\
+	    : "$8");						\
+	((uint64_t)__high << 32) | __low;			\
+})
+
+#define write_c2_register64(reg, sel, value)			\
+do {								\
+       uint32_t __high = value >> 32;				\
+       uint32_t __low = value & 0xffffffff;			\
+	__asm__ __volatile__(					\
+	    ".set	push\n\t"				\
+	    ".set	noreorder\n\t"				\
+	    ".set	mips64\n\t"				\
+	    "dsll32	$8, %1, 0\n\t"				\
+	    "dsll32	$9, %0, 0\n\t"				\
+	    "dsrl32	$8, $8, 0\n\t"				\
+	    "or		$8, $8, $9\n\t"				\
+	    "dmtc2	$8, $%2, %3\n\t"			\
+	    ".set	pop"					\
+	    :: "r"(__high), "r"(__low),	 "i"(reg), "i"(sel)	\
+	    :"$8", "$9");					\
+} while(0)
+
+#endif /* defined(__mips_n64) || defined(__mips_n32) */
+
+static __inline int
+xlr_cpu_id(void)
+{
+
+	return (read_c0_register32(15, 1) & 0x1f);
 }
 
-#define read_c0_register32(reg, sel)                            \
-({ unsigned int __rv;                                           \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mfc0\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : "=r" (__rv) : "i" (reg), "i" (sel) );                 \
-        __rv;})
+static __inline int
+xlr_core_id(void)
+{
 
-#define write_c0_register32(reg,  sel, value)                   \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mtc0\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : : "r" (value), "i" (reg), "i" (sel) );
+	return (xlr_cpu_id() / 4);
+}
 
-#define read_c0_register64(reg, sel)                            \
-   ({ unsigned int __high, __low;                               \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips64\n\t"                                       \
-        "dmfc0\t $8, $%2, %3\n\t"                               \
-        "dsrl32\t%0, $8, 0\n\t"                                 \
-        "dsll32\t$8, $8, 0\n\t"                                 \
-        "dsrl32\t%1, $8, 0\n\t"                                 \
-        ".set\tpop"                                             \
-        : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel): "$8" );\
-        (((unsigned long long)__high << 32) | __low);})
-
-#define write_c0_register64(reg, sel, value)                    \
- do{                                                            \
-       unsigned int __high = val>>32;                           \
-       unsigned int __low = val & 0xffffffff;                   \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips64\n\t"                                       \
-        "dsll32\t$8, %1, 0\n\t"                                 \
-        "dsll32\t$9, %0, 0\n\t"                                 \
-        "or\t    $8, $8, $9\n\t"                                \
-        "dmtc0\t $8, $%2, %3\n\t"                               \
-        ".set\tpop"                                             \
-        :: "r"(high), "r"(low),  "i"(reg), "i"(sel):"$8", "$9");\
-   } while(0)
-
-#define read_c2_register32(reg, sel)                            \
-({ unsigned int __rv;                                           \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mfc2\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : "=r" (__rv) : "i" (reg), "i" (sel) );                 \
-        __rv;})
-
-#define write_c2_register32(reg,  sel, value)                   \
-        __asm__ __volatile__(                                   \
-        ".set\tpush\n\t"                                        \
-        ".set mips32\n\t"                                       \
-        "mtc2\t%0,$%1,%2\n\t"                                   \
-        ".set\tpop"                                             \
-        : : "r" (value), "i" (reg), "i" (sel) );
-
-#define read_c2_register64(reg, sel)                            \
-   ({ unsigned int __high, __low;                               \
-        __asm__ __volatile__(                                   \
-        ".set mips64\n\t"                                       \
-        "dmfc2\t $8, $%2, %3\n\t"                               \
-        "dsrl32\t%0, $8, 0\n\t"                                 \
-        "dsll32\t$8, $8, 0\n\t"                                 \
-        "dsrl32\t%1, $8, 0\n\t"                                 \
-        ".set\tmips0"                                           \
-        : "=r"(__high), "=r"(__low): "i"(reg), "i"(sel): "$8" );\
-        (((unsigned long long)__high << 32) | __low);})
-
-#define write_c2_register64(reg, sel, value)                    \
- do{                                                            \
-       unsigned int __high = value>>32;                         \
-       unsigned int __low = value & 0xffffffff;                 \
-        __asm__ __volatile__(                                   \
-        ".set mips64\n\t"                                       \
-        "dsll32\t$8, %1, 0\n\t"                                 \
-        "dsll32\t$9, %0, 0\n\t"                                 \
-        "dsrl32\t$8, $8, 0\n\t"                                 \
-        "or\t    $8, $8, $9\n\t"                                \
-        "dmtc2\t $8, $%2, %3\n\t"                               \
-        ".set\tmips0"                                           \
-        :: "r"(__high), "r"(__low),                             \
-           "i"(reg), "i"(sel)                                   \
-        :"$8", "$9");                                           \
-   } while(0)
-
-#define xlr_cpu_id()                                            \
-({int __id;                                                     \
- __asm__ __volatile__ (                                         \
-           ".set push\n"                                        \
-           ".set noreorder\n"                                   \
-           "mfc0 $8, $15, 1\n"                                  \
-           "andi %0, $8, 0x1f\n"                                \
-           ".set pop\n"                                         \
-           : "=r" (__id) : : "$8");                             \
- __id;})
-
-#define xlr_core_id()                                           \
-({int __id;                                                     \
- __asm__ __volatile__ (                                         \
-           ".set push\n"                                        \
-           ".set noreorder\n"                                   \
-           "mfc0 $8, $15, 1\n"                                  \
-           "andi %0, $8, 0x1f\n"                                \
-           ".set pop\n"                                         \
-           : "=r" (__id) : : "$8");                             \
- __id/4;})
-
-#define xlr_thr_id()                                            \
-({int __id;                                                     \
- __asm__ __volatile__ (                                         \
-           ".set push\n"                                        \
-           ".set noreorder\n"                                   \
-           "mfc0 $8, $15, 1\n"                                  \
-           "andi %0, $8, 0x3\n"                                 \
-           ".set pop\n"                                         \
-           : "=r" (__id) : : "$8");                             \
- __id;})
+static __inline int
+xlr_thr_id(void)
+{
 
+	return (read_c0_register32(15, 1) & 0x3);
+}
 
 /* Additional registers on the XLR */
-#define MIPS_COP_0_OSSCRATCH   22
-
-#define XLR_CACHELINE_SIZE 32
-
-#define XLR_MAX_CORES 8
+#define	MIPS_COP_0_OSSCRATCH	22
+#define	XLR_CACHELINE_SIZE	32
+#define	XLR_MAX_CORES		8
 
 /* functions to write to and read from the extended
  * cp0 registers.
@@ -268,109 +320,32 @@ static __inline__ void write_64bit_phnx_ctrl_reg(int block, int reg,unsigned lon
  *        cp0 register 9 sel 7
  *        bits 0...7 are same as status register 8...15
  */
-
-static inline uint64_t 
+static __inline uint64_t 
 read_c0_eirr64(void)
 {
-	__uint32_t high, low;
 
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n"
-
-	            ".word 0x40214806  \n\t"
-	            "nop               \n\t"
-	            "dsra32 %0, $1, 0  \n\t"
-	            "sll    %1, $1, 0  \n\t"
-
-	            ".set pop\n"
-
-	    :       "=r"(high), "=r"(low)
-	);
-
-	return (((__uint64_t) high) << 32) | low;
+	return (read_c0_register64(9, 6));
 }
 
-static inline __uint64_t 
+static __inline void
+write_c0_eirr64(uint64_t val)
+{
+
+	write_c0_register64(9, 6, val);
+}
+
+static __inline uint64_t 
 read_c0_eimr64(void)
 {
-	__uint32_t high, low;
 
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n"
-
-	            ".word 0x40214807  \n\t"
-	            "nop               \n\t"
-	            "dsra32 %0, $1, 0  \n\t"
-	            "sll    %1, $1, 0  \n\t"
-
-	            ".set pop\n"
-
-	    :       "=r"(high), "=r"(low)
-	);
-
-	return (((__uint64_t) high) << 32) | low;
+	return (read_c0_register64(9, 7));
 }
 
-static inline void 
-write_c0_eirr64(__uint64_t value)
+static __inline void
+write_c0_eimr64(uint64_t val)
 {
-	__uint32_t low, high;
 
-	high = value >> 32;
-	low = value & 0xffffffff;
-
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n\t"
-
-	            "dsll32 $2, %1, 0  \n\t"
-	            "dsll32 $1, %0, 0  \n\t"
-	            "dsrl32 $2, $2, 0  \n\t"
-	            "or     $1, $1, $2 \n\t"
-	            ".word  0x40a14806 \n\t"
-	            "nop               \n\t"
-
-	            ".set pop\n"
-
-	    :
-	    :       "r"(high), "r"(low)
-	    :       "$1", "$2");
-}
-
-static inline void 
-write_c0_eimr64(__uint64_t value)
-{
-	__uint32_t low, high;
-
-	high = value >> 32;
-	low = value & 0xffffffff;
-
-	__asm__ __volatile__(
-	            ".set push\n"
-	            ".set noreorder\n"
-	            ".set noat\n"
-	            ".set mips4\n\t"
-
-	            "dsll32 $2, %1, 0  \n\t"
-	            "dsll32 $1, %0, 0  \n\t"
-	            "dsrl32 $2, $2, 0  \n\t"
-	            "or     $1, $1, $2 \n\t"
-	            ".word  0x40a14807 \n\t"
-	            "nop               \n\t"
-
-	            ".set pop\n"
-
-	    :
-	    :       "r"(high), "r"(low)
-	    :       "$1", "$2");
+	write_c0_register64(9, 7, val);
 }
 
 static __inline__ int 
@@ -378,17 +353,18 @@ xlr_test_and_set(int *lock)
 {
 	int oldval = 0;
 
-	__asm__ __volatile__(".set push\n"
-	            ".set noreorder\n"
-	            "move $9, %2\n"
-	            "li $8, 1\n"
+	__asm__ __volatile__(
+	    ".set push\n"
+	    ".set noreorder\n"
+	    "move $9, %2\n"
+	    "li $8, 1\n"
 	    //      "swapw $8, $9\n"
-	            ".word 0x71280014\n"
-	            "move %1, $8\n"
-	            ".set pop\n"
-	    :       "+m"(*lock), "=r"(oldval)
-	    :       "r"((unsigned long)lock)
-	    :       "$8", "$9"
+	    ".word 0x71280014\n"
+	    "move %1, $8\n"
+	    ".set pop\n"
+	    : "+m"(*lock), "=r"(oldval)
+	    : "r"((unsigned long)lock)
+	    : "$8", "$9"
 	);
 
 	return (oldval == 0 ? 1 /* success */ : 0 /* failure */ );
@@ -400,11 +376,11 @@ xlr_mfcr(uint32_t reg)
 	uint32_t val;
 
 	__asm__ __volatile__(
-	            "move   $8, %1\n"
-	            ".word  0x71090018\n"
-	            "move   %0, $9\n"
-	    :       "=r"(val)
-	    :       "r"(reg):"$8", "$9");
+	    "move   $8, %1\n"
+	    ".word  0x71090018\n"
+	    "move   %0, $9\n"
+	    : "=r"(val)
+	    : "r"(reg):"$8", "$9");
 
 	return val;
 }
@@ -413,35 +389,63 @@ static __inline__ void
 xlr_mtcr(uint32_t reg, uint32_t val)
 {
 	__asm__ __volatile__(
-	            "move   $8, %1\n"
-	            "move   $9, %0\n"
-	            ".word  0x71090019\n"
-	    ::      "r"(val), "r"(reg)
-	    :       "$8", "$9");
+	    "move   $8, %1\n"
+	    "move   $9, %0\n"
+	    ".word  0x71090019\n"
+	    :: "r"(val), "r"(reg)
+	    : "$8", "$9");
 }
 
+#if defined(__mips_n64)
 static __inline__ uint32_t
 xlr_paddr_lw(uint64_t paddr)
 {
-        uint32_t high, low, tmp;
+	
+	paddr |= 0x9800000000000000ULL;
+	return (*(uint32_t *)(uintptr_t)paddr);
+}
 
-        high = 0x98000000 | (paddr >> 32);
-        low = paddr & 0xffffffff;
+#elif defined(__mips_n32)
+static __inline__ uint32_t
+xlr_paddr_lw(uint64_t paddr)
+{
+	uint32_t val;
 
-        __asm__ __volatile__(
-                    ".set push         \n\t"
-                    ".set mips64       \n\t"
-                    "dsll32 %1, %1, 0  \n\t"
-                    "dsll32 %2, %2, 0  \n\t"  /* get rid of the */
-                    "dsrl32 %2, %2, 0  \n\t"  /* sign extend */
-                    "or     %1, %1, %2 \n\t"
-                    "lw     %0, 0(%1)  \n\t"
-                    ".set pop           \n"
-            :       "=r"(tmp)
-            :       "r"(high), "r"(low));
+	paddr |= 0x9800000000000000ULL;
+	__asm__ __volatile__(
+	    ".set	push		\n\t"
+	    ".set	mips64		\n\t"
+	    "lw		%0, 0(%1)	\n\t"
+	    ".set	pop		\n"
+	    : "=r"(val)
+	    : "r"(paddr));
+
+	return (val);
+}
+#else
+static __inline__ uint32_t
+xlr_paddr_lw(uint64_t paddr)
+{
+	uint32_t high, low, tmp;
+
+	high = 0x98000000 | (paddr >> 32);
+	low = paddr & 0xffffffff;
+
+	__asm__ __volatile__(
+	    ".set push         \n\t"
+	    ".set mips64       \n\t"
+	    "dsll32 %1, %1, 0  \n\t"
+	    "dsll32 %2, %2, 0  \n\t"  /* get rid of the */
+	    "dsrl32 %2, %2, 0  \n\t"  /* sign extend */
+	    "or     %1, %1, %2 \n\t"
+	    "lw     %0, 0(%1)  \n\t"
+	    ".set pop           \n"
+	    :       "=r"(tmp)
+	    :       "r"(high), "r"(low));
 
 	return tmp;
 }
+#endif
 
 /* for cpuid to hardware thread id mapping */
 extern uint32_t xlr_hw_thread_mask;
diff --git a/sys/mips/rmi/xlr_machdep.c b/sys/mips/rmi/xlr_machdep.c
index bc3dd77e3d7..87285553e51 100644
--- a/sys/mips/rmi/xlr_machdep.c
+++ b/sys/mips/rmi/xlr_machdep.c
@@ -105,7 +105,7 @@ int xlr_hwtid_to_cpuid[MAXCPU];
 static void 
 xlr_setup_mmu_split(void)
 {
-	int mmu_setup;
+	uint64_t mmu_setup;
 	int val = 0;
 
 	if (xlr_threads_per_core == 4 && xlr_shtlb_enabled == 0)
@@ -120,7 +120,7 @@ xlr_setup_mmu_split(void)
 		val = 3; break;
 	}
 	
-	mmu_setup = read_32bit_phnx_ctrl_reg(4, 0);
+	mmu_setup = read_xlr_ctrl_register(4, 0);
 	mmu_setup = mmu_setup & ~0x06;
 	mmu_setup |= (val << 1);
 
@@ -128,7 +128,7 @@ xlr_setup_mmu_split(void)
 	if (xlr_shtlb_enabled)
 		mmu_setup |= 0x01;
 
-	write_32bit_phnx_ctrl_reg(4, 0, mmu_setup);
+	write_xlr_ctrl_register(4, 0, mmu_setup);
 }
 
 static void
diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c
index 0b12d9ee4a5..3c5542a20b8 100644
--- a/sys/mips/rmi/xlr_pci.c
+++ b/sys/mips/rmi/xlr_pci.c
@@ -203,11 +203,11 @@ disable_and_clear_cache_error(void)
 {
 	uint64_t lsu_cfg0;
 
-	lsu_cfg0 = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID);
+	lsu_cfg0 = read_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CFG0_REGID);
 	lsu_cfg0 = lsu_cfg0 & ~0x2e;
-	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID, lsu_cfg0);
+	write_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CFG0_REGID, lsu_cfg0);
 	/* Clear cache error log */
-	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CERRLOG_REGID, 0);
+	write_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CERRLOG_REGID, 0);
 }
 
 static __inline__ void 
@@ -216,13 +216,13 @@ clear_and_enable_cache_error(void)
 	uint64_t lsu_cfg0 = 0;
 
 	/* first clear the cache error logging register */
-	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CERRLOG_REGID, 0);
-	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CERROVF_REGID, 0);
-	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CERRINT_REGID, 0);
+	write_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CERRLOG_REGID, 0);
+	write_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CERROVF_REGID, 0);
+	write_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CERRINT_REGID, 0);
 
-	lsu_cfg0 = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID);
+	lsu_cfg0 = read_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CFG0_REGID);
 	lsu_cfg0 = lsu_cfg0 | 0x2e;
-	write_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU, LSU_CFG0_REGID, lsu_cfg0);
+	write_xlr_ctrl_register(CPU_BLOCKID_LSU, LSU_CFG0_REGID, lsu_cfg0);
 }
 
 static uint32_t 
@@ -236,7 +236,7 @@ pci_cfg_read_32bit(uint32_t addr)
 	temp = bswap32(*p);
 
 	/* Read cache err log */
-	cerr_cpu_log = read_64bit_phnx_ctrl_reg(CPU_BLOCKID_LSU,
+	cerr_cpu_log = read_xlr_ctrl_register(CPU_BLOCKID_LSU,
 	    LSU_CERRLOG_REGID);
 	if (cerr_cpu_log) {
 		/* Device don't exist. */

From 4351ba272c12b507656dc4233212b231d2c1823d Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 9 Sep 2010 17:49:18 +0000
Subject: [PATCH 0581/1624] Add drain functionality to sbufs.  The drain is a
 function that is called when the sbuf internal buffer is filled.  For kernel
 sbufs with a drain, the internal buffer will never be expanded.  For userland
 sbufs with a drain, the internal buffer may still be expanded by
 sbuf_[v]printf(3).

Sbufs now have three basic uses:
1) static string manipulation.  Overflow is marked.
2) dynamic string manipulation.  Overflow triggers string growth.
3) drained string manipulation.  Overflow triggers draining.

In all cases the manipulation is 'safe' in that overflow is detected and
managed.

Reviewed by:	phk (the previous version)
---
 share/man/man9/Makefile |   1 +
 share/man/man9/sbuf.9   | 106 +++++++++++++++++++++++++++++++++++++---
 sys/kern/subr_sbuf.c    | 105 ++++++++++++++++++++++++++++++++++++---
 sys/sys/sbuf.h          |  10 +++-
 4 files changed, 207 insertions(+), 15 deletions(-)

diff --git a/share/man/man9/Makefile b/share/man/man9/Makefile
index e6d8881efce..6abafe19e09 100644
--- a/share/man/man9/Makefile
+++ b/share/man/man9/Makefile
@@ -1031,6 +1031,7 @@ MLINKS+=sbuf.9 sbuf_bcat.9 \
 	sbuf.9 sbuf_overflowed.9 \
 	sbuf.9 sbuf_printf.9 \
 	sbuf.9 sbuf_putc.9 \
+	sbuf.9 sbuf_set_drain.9 \
 	sbuf.9 sbuf_setpos.9 \
 	sbuf.9 sbuf_trim.9 \
 	sbuf.9 sbuf_vprintf.9
diff --git a/share/man/man9/sbuf.9 b/share/man/man9/sbuf.9
index abe5831f56b..7389064544f 100644
--- a/share/man/man9/sbuf.9
+++ b/share/man/man9/sbuf.9
@@ -43,6 +43,7 @@
 .Nm sbuf_printf ,
 .Nm sbuf_vprintf ,
 .Nm sbuf_putc ,
+.Nm sbuf_set_drain ,
 .Nm sbuf_trim ,
 .Nm sbuf_overflowed ,
 .Nm sbuf_finish ,
@@ -54,6 +55,8 @@
 .Sh SYNOPSIS
 .In sys/types.h
 .In sys/sbuf.h
+.Ft typedef\ int ( sbuf_drain_func ) ( void\ *arg, const\ char\ *data, int\ len ) ;
+.Pp
 .Ft struct sbuf *
 .Fn sbuf_new "struct sbuf *s" "char *buf" "int length" "int flags"
 .Ft struct sbuf *
@@ -80,11 +83,13 @@
 .Fn sbuf_vprintf "struct sbuf *s" "const char *fmt" "va_list ap"
 .Ft int
 .Fn sbuf_putc "struct sbuf *s" "int c"
+.Ft void
+.Fn sbuf_set_drain "struct sbuf *s" "sbuf_drain_func *func" "void *arg"
 .Ft int
 .Fn sbuf_trim "struct sbuf *s"
 .Ft int
 .Fn sbuf_overflowed "struct sbuf *s"
-.Ft void
+.Ft int
 .Fn sbuf_finish "struct sbuf *s"
 .Ft char *
 .Fn sbuf_data "struct sbuf *s"
@@ -224,6 +229,51 @@ to the
 at the current position.
 .Pp
 The
+.Fn sbuf_set_drain
+function sets a drain function
+.Fa func
+for the
+.Fa sbuf ,
+and records a pointer
+.Fa arg
+to be passed to the drain on callback.
+The drain function cannot be changed while
+.Fa sbuf_len
+is non-zero.
+.Pp
+The registered drain function
+.Vt sbuf_drain_func
+will be called with the argument
+.Fa arg
+provided to
+.Fn sbuf_set_drain ,
+a pointer
+.Fa data
+to a byte string that is the contents of the sbuf, and the length
+.Fa len
+of the data.
+If the drain function exists, it will be called when the sbuf internal
+buffer is full, or on behalf of
+.Fn sbuf_finish .
+The drain function may drain some or all of the data, but must drain
+at least 1 byte.
+The return value from the drain function, if positive, indicates how
+many bytes were drained.
+If negative, the return value indicates the negative error code which
+will be returned from this or a later call to
+.Fn sbuf_finish .
+The returned drained length cannot be zero.
+To do unbuffered draining, initialize the sbuf with a two-byte buffer.
+The drain will be called for every byte added to the sbuf.
+The
+.Fn sbuf_bcopyin ,
+.Fn sbuf_copyin ,
+.Fn sbuf_trim ,
+and
+.Fn sbuf_data
+functions cannot be used on an sbuf with a drain.
+.Pp
+The
 .Fn sbuf_copyin
 function copies a NUL-terminated string from the specified userland
 address into the
@@ -289,10 +339,17 @@ overflowed.
 .Pp
 The
 .Fn sbuf_finish
-function NUL-terminates the
+function will call the attached drain function if one exists until all
+the data in the
 .Fa sbuf
-and marks it as finished, which means that it may no longer be
-modified using
+is flushed.
+If there is no attached drain,
+.Fn sbuf_finish
+NUL-terminates the
+.Fa sbuf .
+In either case it marks the
+.Fa sbuf
+as finished, which means that it may no longer be modified using
 .Fn sbuf_setpos ,
 .Fn sbuf_cat ,
 .Fn sbuf_cpy ,
@@ -305,12 +362,21 @@ is used to reset the sbuf.
 .Pp
 The
 .Fn sbuf_data
-and
-.Fn sbuf_len
-functions return the actual string and its length, respectively;
+function returns the actual string;
 .Fn sbuf_data
 only works on a finished
 .Fa sbuf .
+The
+.Fn sbuf_len function returns the length of the string.
+For an
+.Fa sbuf
+with an attached drain,
+.Fn sbuf_len
+returns the length of the un-drained data.
+.Fn sbuf_done
+returns non-zero if the
+.Fa sbuf
+is finished.
 .Fn sbuf_done
 returns non-zero if the
 .Fa sbuf
@@ -329,6 +395,22 @@ size of its storage buffer using
 .Fn sbuf_setpos ,
 or it is reinitialized to a sufficiently short string using
 .Fn sbuf_cpy .
+.Pp
+Drains in user-space will not always function as indicated.
+While the drain function will be called immediately on overflow from
+the
+.Fa sbuf_putc ,
+.Fa sbuf_bcat ,
+.Fa sbuf_cat
+functions,
+.Fa sbuf_printf
+and
+.Fa sbuf_vprintf
+currently have no way to determine whether there will be an overflow
+until after it occurs, and cannot do a partial expansion of the format
+string.
+Thus when using libsbuf the buffer may be extended to allow completion
+of a single printf call, even though a drain is attached.
 .Sh RETURN VALUES
 The
 .Fn sbuf_new
@@ -372,6 +454,14 @@ The
 function
 returns \-1 if copying string from userland failed, and number of bytes
 copied otherwise.
+The
+.Fn sbuf_finish
+function returns ENOMEM if the sbuf overflowed before being finished,
+or returns the error code from the drain if one is attached.
+When used as
+.Xr sbuf_finish 3 ,
+.Fn sbuf_finish
+will return \-1 and set errno on error instead.
 .Sh SEE ALSO
 .Xr printf 3 ,
 .Xr strcat 3 ,
@@ -396,6 +486,8 @@ Additional improvements were suggested by
 .An Justin T. Gibbs Aq gibbs@FreeBSD.org .
 Auto-extend support added by
 .An Kelly Yancey Aq kbyanc@FreeBSD.org .
+Drain functionality added by
+.An Matthew Fleming Aq mdf@FreeBSD.org .
 .Pp
 This manual page was written by
 .An Dag-Erling Sm\(/orgrav Aq des@FreeBSD.org .
diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index bca87053120..d7b57a5891a 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -33,6 +33,7 @@ __FBSDID("$FreeBSD$");
 
 #ifdef _KERNEL
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -40,6 +41,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #else /* _KERNEL */
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -246,6 +248,7 @@ sbuf_clear(struct sbuf *s)
 
 	SBUF_CLEARFLAG(s, SBUF_FINISHED);
 	SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
+	s->s_error = 0;
 	s->s_len = 0;
 }
 
@@ -271,6 +274,54 @@ sbuf_setpos(struct sbuf *s, int pos)
 	return (0);
 }
 
+/*
+ * Set up a drain function and argument on an sbuf to flush data to
+ * when the sbuf buffer overflows.
+ */
+void
+sbuf_set_drain(struct sbuf *s, sbuf_drain_func *func, void *ctx)
+{
+
+	assert_sbuf_state(s, 0);
+	assert_sbuf_integrity(s);
+	KASSERT(func == s->s_drain_func || s->s_len == 0,
+	    ("Cannot change drain to %p on non-empty sbuf %p", func, s));
+	s->s_drain_func = func;
+	s->s_drain_arg = ctx;
+}
+
+/*
+ * Call the drain and process the return.
+ */
+static int
+sbuf_drain(struct sbuf *s)
+{
+	int len;
+
+	KASSERT(s->s_len > 0, ("Shouldn't drain empty sbuf %p", s));
+	len = s->s_drain_func(s->s_drain_arg, s->s_buf, s->s_len);
+	if (len < 0) {
+		s->s_error = -len;
+		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
+		return (s->s_error);
+	}
+
+	KASSERT(len > 0, ("Drain must either error or work!"));
+	s->s_len -= len;
+	/*
+	 * Fast path for the expected case where all the data was
+	 * drained.
+	 */
+	if (s->s_len == 0)
+		return (0);
+	/*
+	 * Move the remaining characters to the beginning of the
+	 * string.
+	 */
+	memmove(s->s_buf, s->s_buf + len, s->s_len);
+	return (0);
+}
+
 /*
  * Append a byte to an sbuf.  This is the core function for appending
  * to an sbuf and is the main place that deals with extending the
@@ -286,10 +337,16 @@ sbuf_put_byte(int c, struct sbuf *s)
 	if (SBUF_HASOVERFLOWED(s))
 		return;
 	if (SBUF_FREESPACE(s) <= 0) {
-		if (sbuf_extend(s, 1) < 0) {
+		/* 
+		 * If there is a drain, use it, otherwise extend the
+		 * buffer.
+		 */
+		if (s->s_drain_func != NULL)
+			(void)sbuf_drain(s);
+		else if (sbuf_extend(s, 1) < 0)
 			SBUF_SETFLAG(s, SBUF_OVERFLOWED);
+		if (SBUF_HASOVERFLOWED(s))
 			return;
-		}
 	}
 	s->s_buf[s->s_len++] = c;
 }
@@ -338,6 +395,8 @@ sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
+	KASSERT(s->s_drain_func == NULL,
+	    ("Nonsensical copyin to sbuf %p with a drain", s));
 
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
@@ -402,6 +461,8 @@ sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
+	KASSERT(s->s_drain_func == NULL,
+	    ("Nonsensical copyin to sbuf %p with a drain", s));
 
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
@@ -466,7 +527,7 @@ int
 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 {
 	va_list ap_copy;
-	int len;
+	int error, len;
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
@@ -481,15 +542,28 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 	 * For the moment, there is no way to get vsnprintf(3) to hand
 	 * back a character at a time, to push everything into
 	 * sbuf_putc_func() as was done for the kernel.
+	 *
+	 * In userspace, while drains are useful, there's generally
+	 * not a problem attempting to malloc(3) on out of space.  So
+	 * expand a userland sbuf if there is not enough room for the
+	 * data produced by sbuf_[v]printf(3).
 	 */
 
+	error = 0;
 	do {
 		va_copy(ap_copy, ap);
 		len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
 		    fmt, ap_copy);
 		va_end(ap_copy);
-	} while (len > SBUF_FREESPACE(s) &&
-	    sbuf_extend(s, len - SBUF_FREESPACE(s)) == 0);
+
+		if (SBUF_FREESPACE(s) >= len)
+			break;
+		/* Cannot print with the current available space. */
+		if (s->s_drain_func != NULL && s->s_len > 0)
+			error = sbuf_drain(s);
+		else
+			error = sbuf_extend(s, len - SBUF_FREESPACE(s));
+	} while (error == 0);
 
 	/*
 	 * s->s_len is the length of the string, without the terminating nul.
@@ -552,6 +626,8 @@ sbuf_trim(struct sbuf *s)
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
+	KASSERT(s->s_drain_func == NULL,
+	    ("%s makes no sense on sbuf %p with drain", __func__, s));
 
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
@@ -575,16 +651,29 @@ sbuf_overflowed(struct sbuf *s)
 /*
  * Finish off an sbuf.
  */
-void
+int
 sbuf_finish(struct sbuf *s)
 {
+	int error = 0;
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
 
+	if (s->s_drain_func != NULL) {
+		error = s->s_error;
+		while (s->s_len > 0 && error == 0)
+			error = sbuf_drain(s);
+	} else if (SBUF_HASOVERFLOWED(s))
+		error = ENOMEM;
 	s->s_buf[s->s_len] = '\0';
 	SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
 	SBUF_SETFLAG(s, SBUF_FINISHED);
+#ifdef _KERNEL
+	return (error);
+#else
+	errno = error;
+	return (-1);
+#endif
 }
 
 /*
@@ -596,6 +685,8 @@ sbuf_data(struct sbuf *s)
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, SBUF_FINISHED);
+	KASSERT(s->s_drain_func == NULL,
+	    ("%s makes no sense on sbuf %p with drain", __func__, s));
 
 	return (s->s_buf);
 }
@@ -609,6 +700,8 @@ sbuf_len(struct sbuf *s)
 
 	assert_sbuf_integrity(s);
 	/* don't care if it's finished or not */
+	KASSERT(s->s_drain_func == NULL,
+	    ("%s makes no sense on sbuf %p with drain", __func__, s));
 
 	if (SBUF_HASOVERFLOWED(s))
 		return (-1);
diff --git a/sys/sys/sbuf.h b/sys/sys/sbuf.h
index fce24beeed1..be3d80c5240 100644
--- a/sys/sys/sbuf.h
+++ b/sys/sys/sbuf.h
@@ -33,12 +33,17 @@
 
 #include 
 
+struct sbuf;
+typedef int (sbuf_drain_func)(void *, const char *, int);
+
 /*
  * Structure definition
  */
 struct sbuf {
 	char		*s_buf;		/* storage buffer */
-	void		*s_unused;	/* binary compatibility. */
+	sbuf_drain_func	*s_drain_func;	/* drain function */
+	void		*s_drain_arg;	/* user-supplied drain argument */
+	int		 s_error;	/* current error code */
 	int		 s_size;	/* size of storage buffer */
 	int		 s_len;		/* current length of string */
 #define	SBUF_FIXEDLEN	0x00000000	/* fixed length buffer (default) */
@@ -69,9 +74,10 @@ int		 sbuf_printf(struct sbuf *, const char *, ...)
 int		 sbuf_vprintf(struct sbuf *, const char *, __va_list)
 	__printflike(2, 0);
 int		 sbuf_putc(struct sbuf *, int);
+void		 sbuf_set_drain(struct sbuf *, sbuf_drain_func *, void *);
 int		 sbuf_trim(struct sbuf *);
 int		 sbuf_overflowed(struct sbuf *);
-void		 sbuf_finish(struct sbuf *);
+int		 sbuf_finish(struct sbuf *);
 char		*sbuf_data(struct sbuf *);
 int		 sbuf_len(struct sbuf *);
 int		 sbuf_done(struct sbuf *);

From da6b22afaf9a6f78d43631c294b97f46dd123930 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 9 Sep 2010 18:19:15 +0000
Subject: [PATCH 0582/1624] - Rename the constant for the Master Data Parity
 Error flag in the   PCI status register to map its current name. - Use PCIM_*
 rather than PCIR_* for constants for fields in various AER   registers.  I
 got about half of them right in the previous commit.

MFC after:	1 week
---
 sys/dev/pci/pcireg.h | 48 ++++++++++++++++++++++----------------------
 1 file changed, 24 insertions(+), 24 deletions(-)

diff --git a/sys/dev/pci/pcireg.h b/sys/dev/pci/pcireg.h
index 382f15a1259..a0d12dbb8d2 100644
--- a/sys/dev/pci/pcireg.h
+++ b/sys/dev/pci/pcireg.h
@@ -67,7 +67,7 @@
 #define	PCIM_STATUS_CAPPRESENT	0x0010
 #define	PCIM_STATUS_66CAPABLE	0x0020
 #define	PCIM_STATUS_BACKTOBACK	0x0080
-#define	PCIM_STATUS_PERRREPORT	0x0100
+#define	PCIM_STATUS_MDPERR	0x0100
 #define	PCIM_STATUS_SEL_FAST	0x0000
 #define	PCIM_STATUS_SEL_MEDIMUM	0x0200
 #define	PCIM_STATUS_SEL_SLOW	0x0400
@@ -689,18 +689,18 @@
 
 /* Advanced Error Reporting */
 #define	PCIR_AER_UC_STATUS	0x04
-#define	PCIR_AER_UC_TRAINING_ERROR	0x00000001
-#define	PCIR_AER_UC_DL_PROTOCOL_ERROR	0x00000010
-#define	PCIR_AER_UC_POISONED_TLP	0x00001000
-#define	PCIR_AER_UC_FC_PROTOCOL_ERROR	0x00002000
-#define	PCIR_AER_UC_COMPLETION_TIMEOUT	0x00004000
-#define	PCIR_AER_UC_COMPLETER_ABORT	0x00008000
-#define	PCIR_AER_UC_UNEXPECTED_COMPLETION 0x00010000
-#define	PCIR_AER_UC_RECEIVER_OVERFLOW	0x00020000
-#define	PCIR_AER_UC_MALFORMED_TLP	0x00040000
-#define	PCIR_AER_UC_ECRC_ERROR		0x00080000
-#define	PCIR_AER_UC_UNSUPPORTED_REQUEST	0x00100000
-#define	PCIR_AER_UC_ACS_VIOLATION	0x00200000
+#define	PCIM_AER_UC_TRAINING_ERROR	0x00000001
+#define	PCIM_AER_UC_DL_PROTOCOL_ERROR	0x00000010
+#define	PCIM_AER_UC_POISONED_TLP	0x00001000
+#define	PCIM_AER_UC_FC_PROTOCOL_ERROR	0x00002000
+#define	PCIM_AER_UC_COMPLETION_TIMEOUT	0x00004000
+#define	PCIM_AER_UC_COMPLETER_ABORT	0x00008000
+#define	PCIM_AER_UC_UNEXPECTED_COMPLETION 0x00010000
+#define	PCIM_AER_UC_RECEIVER_OVERFLOW	0x00020000
+#define	PCIM_AER_UC_MALFORMED_TLP	0x00040000
+#define	PCIM_AER_UC_ECRC_ERROR		0x00080000
+#define	PCIM_AER_UC_UNSUPPORTED_REQUEST	0x00100000
+#define	PCIM_AER_UC_ACS_VIOLATION	0x00200000
 #define	PCIR_AER_UC_MASK	0x08	/* Shares bits with UC_STATUS */
 #define	PCIR_AER_UC_SEVERITY	0x0c	/* Shares bits with UC_STATUS */
 #define	PCIR_AER_COR_STATUS	0x10
@@ -718,18 +718,18 @@
 #define	PCIM_AER_ECRC_CHECK_ENABLE	0x00000100
 #define	PCIR_AER_HEADER_LOG	0x1c
 #define	PCIR_AER_ROOTERR_CMD	0x2c	/* Only for root complex ports */
-#define	PCIR_AER_ROOTERR_COR_ENABLE	0x00000001
-#define	PCIR_AER_ROOTERR_NF_ENABLE	0x00000002
-#define	PCIR_AER_ROOTERR_F_ENABLE	0x00000004
+#define	PCIM_AER_ROOTERR_COR_ENABLE	0x00000001
+#define	PCIM_AER_ROOTERR_NF_ENABLE	0x00000002
+#define	PCIM_AER_ROOTERR_F_ENABLE	0x00000004
 #define	PCIR_AER_ROOTERR_STATUS	0x30	/* Only for root complex ports */
-#define	PCIR_AER_ROOTERR_COR_ERR	0x00000001
-#define	PCIR_AER_ROOTERR_MULTI_COR_ERR	0x00000002
-#define	PCIR_AER_ROOTERR_UC_ERR		0x00000004
-#define	PCIR_AER_ROOTERR_MULTI_UC_ERR	0x00000008
-#define	PCIR_AER_ROOTERR_FIRST_UC_FATAL	0x00000010
-#define	PCIR_AER_ROOTERR_NF_ERR		0x00000020
-#define	PCIR_AER_ROOTERR_F_ERR		0x00000040
-#define	PCIR_AER_ROOTERR_INT_MESSAGE	0xf8000000
+#define	PCIM_AER_ROOTERR_COR_ERR	0x00000001
+#define	PCIM_AER_ROOTERR_MULTI_COR_ERR	0x00000002
+#define	PCIM_AER_ROOTERR_UC_ERR		0x00000004
+#define	PCIM_AER_ROOTERR_MULTI_UC_ERR	0x00000008
+#define	PCIM_AER_ROOTERR_FIRST_UC_FATAL	0x00000010
+#define	PCIM_AER_ROOTERR_NF_ERR		0x00000020
+#define	PCIM_AER_ROOTERR_F_ERR		0x00000040
+#define	PCIM_AER_ROOTERR_INT_MESSAGE	0xf8000000
 #define	PCIR_AER_COR_SOURCE_ID	0x34	/* Only for root complex ports */
 #define	PCIR_AER_ERR_SOURCE_ID	0x36	/* Only for root complex ports */
 

From 64393db3d1b1e01c6f45afe455767fd8367a4add Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 9 Sep 2010 18:29:48 +0000
Subject: [PATCH 0583/1624] - Use 'sta' to hold the PCIR_STATUS register value
 instead of 'cmd' when   walking the capability list. - Use constants for PCI
 header types instead of magic numbers.

MFC after:	1 week
---
 usr.sbin/pciconf/cap.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/usr.sbin/pciconf/cap.c b/usr.sbin/pciconf/cap.c
index f3243217796..9e6a6710121 100644
--- a/usr.sbin/pciconf/cap.c
+++ b/usr.sbin/pciconf/cap.c
@@ -460,20 +460,20 @@ cap_pciaf(int fd, struct pci_conf *p, uint8_t ptr)
 void
 list_caps(int fd, struct pci_conf *p)
 {
-	uint16_t cmd;
+	uint16_t sta;
 	uint8_t ptr, cap;
 
 	/* Are capabilities present for this device? */
-	cmd = read_config(fd, &p->pc_sel, PCIR_STATUS, 2);
-	if (!(cmd & PCIM_STATUS_CAPPRESENT))
+	sta = read_config(fd, &p->pc_sel, PCIR_STATUS, 2);
+	if (!(sta & PCIM_STATUS_CAPPRESENT))
 		return;
 
 	switch (p->pc_hdr & PCIM_HDRTYPE) {
-	case 0:
-	case 1:
+	case PCIM_HDRTYPE_NORMAL:
+	case PCIM_HDRTYPE_BRIDGE:
 		ptr = PCIR_CAP_PTR;
 		break;
-	case 2:
+	case PCIM_HDRTYPE_CARDBUS:
 		ptr = PCIR_CAP_PTR_2;
 		break;
 	default:

From dd67e2103ca4ba6b6542a2c69a252f0a26690599 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 9 Sep 2010 18:33:46 +0000
Subject: [PATCH 0584/1624] Add a drain function for struct sysctl_req, and use
 it for a variety of handlers, some of which had to do awkward things to get a
 large enough FIXEDLEN buffer.

Note that some sysctl handlers were explicitly outputting a trailing NUL
byte.  This behaviour was preserved, though it should not be necessary.

Reviewed by:	phk
---
 sys/dev/cxgb/cxgb_sge.c    | 48 +++++++++++--------------------
 sys/kern/kern_malloc.c     | 58 ++++++--------------------------------
 sys/kern/kern_sysctl.c     | 28 ++++++++++++++++++
 sys/kern/subr_lock.c       | 20 ++++---------
 sys/kern/subr_sbuf.c       |  4 +--
 sys/kern/subr_sleepqueue.c | 14 ++-------
 sys/kern/subr_witness.c    | 17 ++---------
 sys/sys/sysctl.h           |  3 ++
 sys/vm/uma_core.c          | 54 ++++++-----------------------------
 sys/vm/vm_phys.c           | 27 ++++--------------
 sys/vm/vm_reserv.c         |  9 ++----
 11 files changed, 88 insertions(+), 194 deletions(-)

diff --git a/sys/dev/cxgb/cxgb_sge.c b/sys/dev/cxgb/cxgb_sge.c
index 4032b4f1f9c..5fb206b8ba3 100644
--- a/sys/dev/cxgb/cxgb_sge.c
+++ b/sys/dev/cxgb/cxgb_sge.c
@@ -3227,7 +3227,6 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 	struct sge_rspq *rspq;
 	struct sge_qset *qs;
 	int i, err, dump_end, idx;
-	static int multiplier = 1;
 	struct sbuf *sb;
 	struct rsp_desc *rspd;
 	uint32_t data[4];
@@ -3252,8 +3251,8 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 	err = t3_sge_read_rspq(qs->port->adapter, rspq->cntxt_id, data);
 	if (err)
 		return (err);
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
+
+	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
 
 	sbuf_printf(sb, " \n index=%u size=%u MSI-X/RspQ=%u intr enable=%u intr armed=%u\n",
 	    (data[0] & 0xffff), data[0] >> 16, ((data[2] >> 20) & 0x3f),
@@ -3276,13 +3275,11 @@ retry_sbufops:
 		    rspd->rss_hdr.rss_hash_val, be32toh(rspd->flags),
 		    be32toh(rspd->len_cq), rspd->intr_gen);
 	}
-	if (sbuf_overflowed(sb)) {
-		sbuf_delete(sb);
-		multiplier++;
-		goto retry_sbufops;
-	}
-	sbuf_finish(sb);
-	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+
+	err = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (err == 0)
+		err = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (err);
 }	
@@ -3293,7 +3290,6 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 	struct sge_txq *txq;
 	struct sge_qset *qs;
 	int i, j, err, dump_end;
-	static int multiplier = 1;
 	struct sbuf *sb;
 	struct tx_desc *txd;
 	uint32_t *WR, wr_hi, wr_lo, gen;
@@ -3321,9 +3317,7 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 	if (err)
 		return (err);
 	
-	    
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
 
 	sbuf_printf(sb, " \n credits=%u GTS=%u index=%u size=%u rspq#=%u cmdq#=%u\n",
 	    (data[0] & 0x7fff), ((data[0] >> 15) & 1), (data[0] >> 16), 
@@ -3350,13 +3344,10 @@ retry_sbufops:
 			    WR[j], WR[j + 1], WR[j + 2], WR[j + 3]);
 
 	}
-	if (sbuf_overflowed(sb)) {
-		sbuf_delete(sb);
-		multiplier++;
-		goto retry_sbufops;
-	}
-	sbuf_finish(sb);
-	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	err = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (err == 0)
+		err = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (err);
 }
@@ -3367,7 +3358,6 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 	struct sge_txq *txq;
 	struct sge_qset *qs;
 	int i, j, err, dump_end;
-	static int multiplier = 1;
 	struct sbuf *sb;
 	struct tx_desc *txd;
 	uint32_t *WR, wr_hi, wr_lo, gen;
@@ -3391,8 +3381,7 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 		return (EINVAL);
 	}
 
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
 	sbuf_printf(sb, " qid=%d start=%d -> end=%d\n", qs->idx,
 	    txq->txq_dump_start,
 	    (txq->txq_dump_start + txq->txq_dump_count) & 255);
@@ -3412,13 +3401,10 @@ retry_sbufops:
 			    WR[j], WR[j + 1], WR[j + 2], WR[j + 3]);
 
 	}
-	if (sbuf_overflowed(sb)) {
-		sbuf_delete(sb);
-		multiplier++;
-		goto retry_sbufops;
-	}
-	sbuf_finish(sb);
-	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	err = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (err == 0)
+		err = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (err);
 }
diff --git a/sys/kern/kern_malloc.c b/sys/kern/kern_malloc.c
index 1e97b55dc03..6d9b77574a6 100644
--- a/sys/kern/kern_malloc.c
+++ b/sys/kern/kern_malloc.c
@@ -828,25 +828,11 @@ sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
 	struct malloc_type_internal *mtip;
 	struct malloc_type_header mth;
 	struct malloc_type *mtp;
-	int buflen, count, error, i;
+	int error, i;
 	struct sbuf sbuf;
-	char *buffer;
 
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	mtx_lock(&malloc_mtx);
-restart:
-	mtx_assert(&malloc_mtx, MA_OWNED);
-	count = kmemcount;
-	mtx_unlock(&malloc_mtx);
-	buflen = sizeof(mtsh) + count * (sizeof(mth) +
-	    sizeof(struct malloc_type_stats) * MAXCPU) + 1;
-	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
-	mtx_lock(&malloc_mtx);
-	if (count < kmemcount) {
-		free(buffer, M_TEMP);
-		goto restart;
-	}
-
-	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
 
 	/*
 	 * Insert stream header.
@@ -855,11 +841,7 @@ restart:
 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
 	mtsh.mtsh_maxcpus = MAXCPU;
 	mtsh.mtsh_count = kmemcount;
-	if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
-		mtx_unlock(&malloc_mtx);
-		error = ENOMEM;
-		goto out;
-	}
+	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
 
 	/*
 	 * Insert alternating sequence of type headers and type statistics.
@@ -872,30 +854,19 @@ restart:
 		 */
 		bzero(&mth, sizeof(mth));
 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
-		if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
-			mtx_unlock(&malloc_mtx);
-			error = ENOMEM;
-			goto out;
-		}
+		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
 
 		/*
 		 * Insert type statistics for each CPU.
 		 */
 		for (i = 0; i < MAXCPU; i++) {
-			if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
-			    sizeof(mtip->mti_stats[i])) < 0) {
-				mtx_unlock(&malloc_mtx);
-				error = ENOMEM;
-				goto out;
-			}
+			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
+			    sizeof(mtip->mti_stats[i]));
 		}
 	}
 	mtx_unlock(&malloc_mtx);
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
-out:
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(buffer, M_TEMP);
 	return (error);
 }
 
@@ -1005,26 +976,19 @@ DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
 static int
 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
 {
-	int linesize = 64;
 	struct sbuf sbuf;
 	uint64_t count;
 	uint64_t waste;
 	uint64_t mem;
-	int bufsize;
 	int error;
-	char *buf;
 	int rsize;
 	int size;
 	int i;
 
-	bufsize = linesize * (KMEM_ZSIZE + 1);
-	bufsize += 128; 	/* For the stats line */
-	bufsize += 128; 	/* For the banner line */
 	waste = 0;
 	mem = 0;
 
-	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
-	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	sbuf_printf(&sbuf, 
 	    "\n  Size                    Requests  Real Size\n");
 	for (i = 0; i < KMEM_ZSIZE; i++) {
@@ -1042,12 +1006,8 @@ sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
 	sbuf_printf(&sbuf,
 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
 	    (unsigned long long)mem, (unsigned long long)waste);
-	sbuf_finish(&sbuf);
-
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
-
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(buf, M_TEMP);
 	return (error);
 }
 
diff --git a/sys/kern/kern_sysctl.c b/sys/kern/kern_sysctl.c
index b83502c2f41..49ccc505278 100644
--- a/sys/kern/kern_sysctl.c
+++ b/sys/kern/kern_sysctl.c
@@ -51,6 +51,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -1544,3 +1545,30 @@ userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
 	}
 	return (error);
 }
+
+/*
+ * Drain into a sysctl struct.  The user buffer must be wired.
+ */
+static int
+sbuf_sysctl_drain(void *arg, const char *data, int len)
+{
+	struct sysctl_req *req = arg;
+	int error;
+
+	error = SYSCTL_OUT(req, data, len);
+	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
+	return (error == 0 ? len : -error);
+}
+
+struct sbuf *
+sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
+    struct sysctl_req *req)
+{
+
+	/* Wire the user buffer, so we can write without blocking. */
+	sysctl_wire_old_buffer(req, 0);
+
+	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN);
+	sbuf_set_drain(s, sbuf_sysctl_drain, req);
+	return (s);
+}
diff --git a/sys/kern/subr_lock.c b/sys/kern/subr_lock.c
index 61263f962aa..530ebc5b265 100644
--- a/sys/kern/subr_lock.c
+++ b/sys/kern/subr_lock.c
@@ -191,8 +191,7 @@ struct lock_prof_cpu *lp_cpu[MAXCPU];
 volatile int lock_prof_enable = 0;
 static volatile int lock_prof_resetting;
 
-/* SWAG: sbuf size = avg stat. line size * number of locks */
-#define LPROF_SBUF_SIZE		256 * 400
+#define LPROF_SBUF_SIZE		256
 
 static int lock_prof_rejected;
 static int lock_prof_skipspin;
@@ -384,8 +383,6 @@ lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
 				continue;
 			lock_prof_sum(l, &lp, i, spin, t);
 			lock_prof_output(&lp, sb);
-			if (sbuf_overflowed(sb))
-				return;
 		}
 	}
 }
@@ -393,13 +390,11 @@ lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
 static int
 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
 {
-	static int multiplier = 1;
 	struct sbuf *sb;
 	int error, cpu, t;
 	int enabled;
 
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, LPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
 	sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
 	    "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
 	enabled = lock_prof_enable;
@@ -411,16 +406,13 @@ retry_sbufops:
 			continue;
 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[0], sb, 0, t);
 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[1], sb, 1, t);
-		if (sbuf_overflowed(sb)) {
-			sbuf_delete(sb);
-			multiplier++;
-			goto retry_sbufops;
-		}
 	}
 	lock_prof_enable = enabled;
 
-	sbuf_finish(sb);
-	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	error = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (error == 0)
+		error = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (error);
 }
diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index d7b57a5891a..58964fb1d85 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -305,8 +305,8 @@ sbuf_drain(struct sbuf *s)
 		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
 		return (s->s_error);
 	}
-
-	KASSERT(len > 0, ("Drain must either error or work!"));
+	KASSERT(len > 0 && len <= s->s_len,
+	    ("Bad drain amount %d for sbuf %p", len, s));
 	s->s_len -= len;
 	/*
 	 * Fast path for the expected case where all the data was
diff --git a/sys/kern/subr_sleepqueue.c b/sys/kern/subr_sleepqueue.c
index cc207998d52..cdf7a47c368 100644
--- a/sys/kern/subr_sleepqueue.c
+++ b/sys/kern/subr_sleepqueue.c
@@ -1018,7 +1018,7 @@ sleepq_abort(struct thread *td, int intrval)
 
 #ifdef SLEEPQUEUE_PROFILING
 #define	SLEEPQ_PROF_LOCATIONS	1024
-#define	SLEEPQ_SBUFSIZE		(40 * 512)
+#define	SLEEPQ_SBUFSIZE		512
 struct sleepq_prof {
 	LIST_ENTRY(sleepq_prof) sp_link;
 	const char	*sp_wmesg;
@@ -1123,15 +1123,13 @@ reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 static int
 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 {
-	static int multiplier = 1;
 	struct sleepq_prof *sp;
 	struct sbuf *sb;
 	int enabled;
 	int error;
 	int i;
 
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, SLEEPQ_SBUFSIZE * multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req);
 	sbuf_printf(sb, "\nwmesg\tcount\n");
 	enabled = prof_enabled;
 	mtx_lock_spin(&sleepq_prof_lock);
@@ -1141,19 +1139,13 @@ retry_sbufops:
 		LIST_FOREACH(sp, &sleepq_hash[i], sp_link) {
 			sbuf_printf(sb, "%s\t%ld\n",
 			    sp->sp_wmesg, sp->sp_count);
-			if (sbuf_overflowed(sb)) {
-				sbuf_delete(sb);
-				multiplier++;
-				goto retry_sbufops;
-			}
 		}
 	}
 	mtx_lock_spin(&sleepq_prof_lock);
 	prof_enabled = enabled;
 	mtx_unlock_spin(&sleepq_prof_lock);
 
-	sbuf_finish(sb);
-	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	error = sbuf_finish(sb);
 	sbuf_delete(sb);
 	return (error);
 }
diff --git a/sys/kern/subr_witness.c b/sys/kern/subr_witness.c
index 201be995ffd..3fec4c420b2 100644
--- a/sys/kern/subr_witness.c
+++ b/sys/kern/subr_witness.c
@@ -154,8 +154,7 @@ __FBSDID("$FreeBSD$");
 #define	MAX_W_NAME	64
 
 #define	BADSTACK_SBUF_SIZE	(256 * WITNESS_COUNT)
-#define	CYCLEGRAPH_SBUF_SIZE	8192
-#define	FULLGRAPH_SBUF_SIZE	32768
+#define	FULLGRAPH_SBUF_SIZE	512
 
 /*
  * These flags go in the witness relationship matrix and describe the
@@ -2545,7 +2544,7 @@ sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
 		return (error);
 	}
 	error = 0;
-	sb = sbuf_new(NULL, NULL, FULLGRAPH_SBUF_SIZE, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
 	if (sb == NULL)
 		return (ENOMEM);
 	sbuf_printf(sb, "\n");
@@ -2557,20 +2556,10 @@ sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
 		witness_add_fullgraph(sb, w);
 	mtx_unlock_spin(&w_mtx);
 
-	/*
-	 * While using SBUF_FIXEDLEN, check if the sbuf overflowed.
-	 */
-	if (sbuf_overflowed(sb)) {
-		sbuf_delete(sb);
-		panic("%s: sbuf overflowed, bump FULLGRAPH_SBUF_SIZE value\n",
-		    __func__);
-	}
-
 	/*
 	 * Close the sbuf and return to userland.
 	 */
-	sbuf_finish(sb);
-	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	error = sbuf_finish(sb);
 	sbuf_delete(sb);
 
 	return (error);
diff --git a/sys/sys/sysctl.h b/sys/sys/sysctl.h
index 1ee49cab246..fbfd6e84202 100644
--- a/sys/sys/sysctl.h
+++ b/sys/sys/sysctl.h
@@ -710,6 +710,9 @@ void	sysctl_lock(void);
 void	sysctl_unlock(void);
 int	sysctl_wire_old_buffer(struct sysctl_req *req, size_t len);
 
+struct sbuf;
+struct sbuf	*sbuf_new_for_sysctl(struct sbuf *, char *, int,
+		    struct sysctl_req *);
 #else	/* !_KERNEL */
 #include 
 
diff --git a/sys/vm/uma_core.c b/sys/vm/uma_core.c
index 558b4c727e7..23b88ee45c2 100644
--- a/sys/vm/uma_core.c
+++ b/sys/vm/uma_core.c
@@ -3175,36 +3175,16 @@ sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
 	uma_keg_t kz;
 	uma_zone_t z;
 	uma_keg_t k;
-	char *buffer;
-	int buflen, count, error, i;
+	int count, error, i;
+
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 
-	mtx_lock(&uma_mtx);
-restart:
-	mtx_assert(&uma_mtx, MA_OWNED);
 	count = 0;
+	mtx_lock(&uma_mtx);
 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
 			count++;
 	}
-	mtx_unlock(&uma_mtx);
-
-	buflen = sizeof(ush) + count * (sizeof(uth) + sizeof(ups) *
-	    (mp_maxid + 1)) + 1;
-	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
-
-	mtx_lock(&uma_mtx);
-	i = 0;
-	LIST_FOREACH(kz, &uma_kegs, uk_link) {
-		LIST_FOREACH(z, &kz->uk_zones, uz_link)
-			i++;
-	}
-	if (i > count) {
-		free(buffer, M_TEMP);
-		goto restart;
-	}
-	count =  i;
-
-	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
 
 	/*
 	 * Insert stream header.
@@ -3213,11 +3193,7 @@ restart:
 	ush.ush_version = UMA_STREAM_VERSION;
 	ush.ush_maxcpus = (mp_maxid + 1);
 	ush.ush_count = count;
-	if (sbuf_bcat(&sbuf, &ush, sizeof(ush)) < 0) {
-		mtx_unlock(&uma_mtx);
-		error = ENOMEM;
-		goto out;
-	}
+	(void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
 
 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
@@ -3250,12 +3226,7 @@ restart:
 			uth.uth_frees = z->uz_frees;
 			uth.uth_fails = z->uz_fails;
 			uth.uth_sleeps = z->uz_sleeps;
-			if (sbuf_bcat(&sbuf, &uth, sizeof(uth)) < 0) {
-				ZONE_UNLOCK(z);
-				mtx_unlock(&uma_mtx);
-				error = ENOMEM;
-				goto out;
-			}
+			(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
 			/*
 			 * While it is not normally safe to access the cache
 			 * bucket pointers while not on the CPU that owns the
@@ -3280,21 +3251,14 @@ restart:
 				ups.ups_allocs = cache->uc_allocs;
 				ups.ups_frees = cache->uc_frees;
 skip:
-				if (sbuf_bcat(&sbuf, &ups, sizeof(ups)) < 0) {
-					ZONE_UNLOCK(z);
-					mtx_unlock(&uma_mtx);
-					error = ENOMEM;
-					goto out;
-				}
+				(void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
 			}
 			ZONE_UNLOCK(z);
 		}
 	}
 	mtx_unlock(&uma_mtx);
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
-out:
-	free(buffer, M_TEMP);
+	error = sbuf_finish(&sbuf);
+	sbuf_delete(&sbuf);
 	return (error);
 }
 
diff --git a/sys/vm/vm_phys.c b/sys/vm/vm_phys.c
index e75c3401acf..26e4981606a 100644
--- a/sys/vm/vm_phys.c
+++ b/sys/vm/vm_phys.c
@@ -123,12 +123,9 @@ sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	struct vm_freelist *fl;
-	char *cbuf;
-	const int cbufsize = vm_nfreelists*(VM_NFREEORDER + 1)*81;
 	int error, flind, oind, pind;
 
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	for (flind = 0; flind < vm_nfreelists; flind++) {
 		sbuf_printf(&sbuf, "\nFREE LIST %d:\n"
 		    "\n  ORDER (SIZE)  |  NUMBER"
@@ -149,10 +146,8 @@ sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
 			sbuf_printf(&sbuf, "\n");
 		}
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 
@@ -164,12 +159,9 @@ sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	struct vm_phys_seg *seg;
-	char *cbuf;
-	const int cbufsize = VM_PHYSSEG_MAX*(VM_NFREEORDER + 1)*81;
 	int error, segind;
 
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
 		sbuf_printf(&sbuf, "\nSEGMENT %d:\n\n", segind);
 		seg = &vm_phys_segs[segind];
@@ -180,10 +172,8 @@ sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
 		sbuf_printf(&sbuf, "domain:    %d\n", seg->domain);
 		sbuf_printf(&sbuf, "free list: %p\n", seg->free_queues);
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 
@@ -195,23 +185,18 @@ static int
 sysctl_vm_phys_lookup_lists(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
-	char *cbuf;
-	const int cbufsize = (vm_nfreelists + 1) * VM_NDOMAIN * 81;
 	int domain, error, flind, ndomains;
 
 	ndomains = vm_nfreelists - VM_NFREELIST + 1;
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	for (domain = 0; domain < ndomains; domain++) {
 		sbuf_printf(&sbuf, "\nDOMAIN %d:\n\n", domain);
 		for (flind = 0; flind < vm_nfreelists; flind++)
 			sbuf_printf(&sbuf, "  [%d]:\t%p\n", flind,
 			    vm_phys_lookup_lists[domain][flind]);
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 #endif
diff --git a/sys/vm/vm_reserv.c b/sys/vm/vm_reserv.c
index d9e908f62a3..aa8e80f7311 100644
--- a/sys/vm/vm_reserv.c
+++ b/sys/vm/vm_reserv.c
@@ -180,12 +180,9 @@ sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	vm_reserv_t rv;
-	char *cbuf;
-	const int cbufsize = (VM_NRESERVLEVEL + 1) * 81;
 	int counter, error, level, unused_pages;
 
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	sbuf_printf(&sbuf, "\nLEVEL     SIZE  NUMBER\n\n");
 	for (level = -1; level <= VM_NRESERVLEVEL - 2; level++) {
 		counter = 0;
@@ -199,10 +196,8 @@ sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
 		sbuf_printf(&sbuf, "%5.5d: %6.6dK, %6.6d\n", level,
 		    unused_pages * (PAGE_SIZE / 1024), counter);
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 

From 10e0075ddb96d18cc1dbb02ef068f00c452f2157 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 9 Sep 2010 18:35:08 +0000
Subject: [PATCH 0585/1624] Fix an incorrect use of sbuf_overflowed() after a
 call to sbuf_finish().

---
 sys/dev/led/led.c | 10 +++-------
 1 file changed, 3 insertions(+), 7 deletions(-)

diff --git a/sys/dev/led/led.c b/sys/dev/led/led.c
index fdd0fa2d006..521006c9dd8 100644
--- a/sys/dev/led/led.c
+++ b/sys/dev/led/led.c
@@ -220,15 +220,11 @@ led_write(struct cdev *dev, struct uio *uio, int ioflag)
 			free(s2, M_DEVBUF);
 			return (EINVAL);
 	}
-	sbuf_finish(sb);
+	error = sbuf_finish(sb);
 	free(s2, M_DEVBUF);
-	if (sbuf_overflowed(sb)) {
+	if (error != 0 || sbuf_len(sb) == 0) {
 		sbuf_delete(sb);
-		return (ENOMEM);
-	}
-	if (sbuf_len(sb) == 0) {
-		sbuf_delete(sb);
-		return (0);
+		return (error);
 	}
 
 	return (led_state(dev, sb, 0));

From b4fb1ba027d5f7980e10d62508b288cb9f68716a Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 9 Sep 2010 18:51:20 +0000
Subject: [PATCH 0586/1624] Document the format of extended capabilities in the
 '-c' output.

---
 usr.sbin/pciconf/pciconf.8 | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/usr.sbin/pciconf/pciconf.8 b/usr.sbin/pciconf/pciconf.8
index e1a59fe6d24..72586dd8b56 100644
--- a/usr.sbin/pciconf/pciconf.8
+++ b/usr.sbin/pciconf/pciconf.8
@@ -142,7 +142,7 @@ If the
 option is supplied,
 .Nm
 will list any capabilities supported by each device.
-Each capability will be enumerated via a line in the following format:
+Each capability is enumerated via a line in the following format:
 .Bd -literal
     cap 10[40] = PCI-Express 1 root port
 .Ed
@@ -154,6 +154,18 @@ The second value in the square brackets is the offset of the capability
 in config space in hexadecimal.
 The format of the text after the equals sign is capability-specific.
 .Pp
+Each extended capability is enumerated via a line in a similar format:
+.Bd -literal
+ecap 0002[100] = VC 1 max VC0
+.Ed
+.Pp
+The first value after the
+.Dq Li ecap
+prefix is the extended capability ID in hexadecimal.
+The second value in the square brackets is the offset of the extended
+capability in config space in hexadecimal.
+The format of the text after the equals sign is capability-specific.
+.Pp
 If the
 .Fl v
 option is supplied,

From ea22f625a73ebfc68c847571ee82e4aa7d8b4641 Mon Sep 17 00:00:00 2001
From: Kai Wang 
Date: Thu, 9 Sep 2010 18:51:50 +0000
Subject: [PATCH 0587/1624] libelf is overly strict about the type and
 alignment of Elf_Data objects inside one ELF section, which prevents the
 creation of a ELF section with mixed data types. For example, gcc LTO use
 libelf to create a .gnu_lto_XXX section that contains integers and a string
 table, which doesn't work with our libelf implementation.

The changes made in this commit include:
* Allow Elf_Data type to be different than section type.
* Relax Elf_Data alignment check.
* Align each Elf_Data by their own alignment instead of section alignment.

MFC after:   1 month
---
 lib/libelf/elf_update.c | 17 ++++++-----------
 1 file changed, 6 insertions(+), 11 deletions(-)

diff --git a/lib/libelf/elf_update.c b/lib/libelf/elf_update.c
index 69bbaac8a86..5880c07aadd 100644
--- a/lib/libelf/elf_update.c
+++ b/lib/libelf/elf_update.c
@@ -141,7 +141,7 @@ _libelf_compute_section_extents(Elf *e, Elf_Scn *s, off_t *rc)
 
 	/* Compute the section alignment. */
 	STAILQ_FOREACH(d, &s->s_data, d_next)  {
-		if (d->d_type != elftype) {
+		if (d->d_type > ELF_T_LAST) {
 			LIBELF_SET_ERROR(DATA, 0);
 			return (0);
 		}
@@ -149,11 +149,7 @@ _libelf_compute_section_extents(Elf *e, Elf_Scn *s, off_t *rc)
 			LIBELF_SET_ERROR(VERSION, 0);
 			return (0);
 		}
-		if ((d_align = d->d_align) % sh_align) {
-			LIBELF_SET_ERROR(LAYOUT, 0);
-			return (0);
-		}
-		if (d_align == 0 || (d_align & (d_align - 1))) {
+		if ((d_align = d->d_align) == 0 || (d_align & (d_align - 1))) {
 			LIBELF_SET_ERROR(DATA, 0);
 			return (0);
 		}
@@ -168,7 +164,7 @@ _libelf_compute_section_extents(Elf *e, Elf_Scn *s, off_t *rc)
 			if ((uint64_t) d->d_off + d->d_size > scn_size)
 				scn_size = d->d_off + d->d_size;
 		} else {
-			scn_size = roundup2(scn_size, scn_alignment);
+			scn_size = roundup2(scn_size, d->d_align);
 			d->d_off = scn_size;
 			scn_size += d->d_size;
 		}
@@ -560,8 +556,6 @@ _libelf_write_scn(Elf *e, char *nf, Elf_Scn *s, off_t rc)
 	elftype = _libelf_xlate_shtype(sh_type);
 	assert(elftype >= ELF_T_FIRST && elftype <= ELF_T_LAST);
 
-	msz = _libelf_msize(elftype, ec, e->e_version);
-
 	sh_off = s->s_offset;
 	assert(sh_off % _libelf_falign(elftype, ec) == 0);
 
@@ -608,6 +602,8 @@ _libelf_write_scn(Elf *e, char *nf, Elf_Scn *s, off_t rc)
 
 	STAILQ_FOREACH(d, &s->s_data, d_next) {
 
+		msz = _libelf_msize(d->d_type, ec, e->e_version);
+
 		if ((uint64_t) rc < sh_off + d->d_off)
 			(void) memset(nf + rc,
 			    LIBELF_PRIVATE(fillchar), sh_off + d->d_off - rc);
@@ -615,13 +611,12 @@ _libelf_write_scn(Elf *e, char *nf, Elf_Scn *s, off_t rc)
 		rc = sh_off + d->d_off;
 
 		assert(d->d_buf != NULL);
-		assert(d->d_type == (Elf_Type) elftype);
 		assert(d->d_version == e->e_version);
 		assert(d->d_size % msz == 0);
 
 		nobjects = d->d_size / msz;
 
-		fsz = _libelf_fsize(elftype, ec, e->e_version, nobjects);
+		fsz = _libelf_fsize(d->d_type, ec, e->e_version, nobjects);
 
 		dst.d_buf    = nf + rc;
 		dst.d_size   = fsz;

From 4b2f91532164095cf83202b30824896be0adf41a Mon Sep 17 00:00:00 2001
From: "David E. O'Brien" 
Date: Thu, 9 Sep 2010 19:27:40 +0000
Subject: [PATCH 0588/1624] Note bug in trying to printf(1) things like:
 '-%s\n' "foo"

---
 usr.bin/printf/printf.1 | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/usr.bin/printf/printf.1 b/usr.bin/printf/printf.1
index f0fc00b63ca..6caea65c6df 100644
--- a/usr.bin/printf/printf.1
+++ b/usr.bin/printf/printf.1
@@ -355,3 +355,10 @@ Multibyte characters are not recognized in format strings (this is only
 a problem if
 .Ql %
 can appear inside a multibyte character).
+.Pp
+Trying to print a dash ("-") as the first character causes
+.Nm
+to interpet the dash as a program argument.
+.Nm --
+must be used before 
+.Ar format .

From 7eaa29b5d88de4d333d1a196eab9a71d6e0fcd5d Mon Sep 17 00:00:00 2001
From: Edward Tomasz Napierala 
Date: Thu, 9 Sep 2010 20:07:40 +0000
Subject: [PATCH 0589/1624] Add minor optimization.  It's less strict than its
 kernel counterpart due to upcoming ACL changes required by the new ZFS.

---
 lib/libc/posix1e/acl_strip.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/lib/libc/posix1e/acl_strip.c b/lib/libc/posix1e/acl_strip.c
index f86d3799116..be36afaf09f 100644
--- a/lib/libc/posix1e/acl_strip.c
+++ b/lib/libc/posix1e/acl_strip.c
@@ -175,6 +175,15 @@ acl_is_trivial_np(const acl_t aclp, int *trivialp)
 		return (0);
 
 	case ACL_BRAND_NFS4:
+		/*
+		 * If the ACL has more than canonical six entries,
+		 * it's non trivial by definition.
+		 */
+		if (aclp->ats_acl.acl_cnt > 6) {
+			*trivialp = 1;
+			return (0);
+		}
+			
 		/*
 		 * Calculate trivial ACL - using acl_strip_np - and compare
 		 * with the original.

From d1a02e09329a89cc5e6adc785b257ad27be183d9 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 9 Sep 2010 20:26:30 +0000
Subject: [PATCH 0590/1624] Catch up to rename of the constant for the Master
 Data Parity Error bit in the PCI status register.

Pointed out by:	mdf
Pointy hat to:	jhb
---
 sys/dev/msk/if_msk.c     | 4 ++--
 sys/sparc64/pci/schizo.c | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/sys/dev/msk/if_msk.c b/sys/dev/msk/if_msk.c
index 3f97c3a9f5c..37ee752971c 100644
--- a/sys/dev/msk/if_msk.c
+++ b/sys/dev/msk/if_msk.c
@@ -1334,7 +1334,7 @@ mskc_reset(struct msk_softc *sc)
 
 	pci_write_config(sc->msk_dev, PCIR_STATUS, status |
 	    PCIM_STATUS_PERR | PCIM_STATUS_SERR | PCIM_STATUS_RMABORT |
-	    PCIM_STATUS_RTABORT | PCIM_STATUS_PERRREPORT, 2);
+	    PCIM_STATUS_RTABORT | PCIM_STATUS_MDPERR, 2);
 	CSR_WRITE_2(sc, B0_CTST, CS_MRST_CLR);
 
 	switch (sc->msk_bustype) {
@@ -3405,7 +3405,7 @@ msk_intr_hwerr(struct msk_softc *sc)
 		CSR_WRITE_1(sc, B2_TST_CTRL1, TST_CFG_WRITE_ON);
 		pci_write_config(sc->msk_dev, PCIR_STATUS, v16 |
 		    PCIM_STATUS_PERR | PCIM_STATUS_SERR | PCIM_STATUS_RMABORT |
-		    PCIM_STATUS_RTABORT | PCIM_STATUS_PERRREPORT, 2);
+		    PCIM_STATUS_RTABORT | PCIM_STATUS_MDPERR, 2);
 		CSR_WRITE_1(sc, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
 	}
 
diff --git a/sys/sparc64/pci/schizo.c b/sys/sparc64/pci/schizo.c
index ae0d9a0a8a0..f34666789d3 100644
--- a/sys/sparc64/pci/schizo.c
+++ b/sys/sparc64/pci/schizo.c
@@ -849,7 +849,7 @@ schizo_pci_bus(void *arg)
 		fatal = 1;
 	if ((status & (PCIM_STATUS_PERR | PCIM_STATUS_SERR |
 	    PCIM_STATUS_RMABORT | PCIM_STATUS_RTABORT |
-	    PCIM_STATUS_PERRREPORT)) != 0 ||
+	    PCIM_STATUS_MDPERR)) != 0 ||
 	    (csr & (SCZ_PCI_CTRL_BUS_UNUS | TOM_PCI_CTRL_DTO_ERR |
 	    STX_PCI_CTRL_TTO_ERR | STX_PCI_CTRL_RTRY_ERR |
 	    SCZ_PCI_CTRL_SBH_ERR | STX_PCI_CTRL_SERR)) != 0 ||

From 781413510d7e23dddadc0f4fe32b1a9157a0a587 Mon Sep 17 00:00:00 2001
From: Edward Tomasz Napierala 
Date: Thu, 9 Sep 2010 20:37:19 +0000
Subject: [PATCH 0591/1624] Arrgh, tested wrong source tree _again_.  Fix
 previous commit.  Also, this and previous one are MFC candidate.

MFC after:	1 month
---
 lib/libc/posix1e/acl_strip.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libc/posix1e/acl_strip.c b/lib/libc/posix1e/acl_strip.c
index be36afaf09f..82eacdc4d8d 100644
--- a/lib/libc/posix1e/acl_strip.c
+++ b/lib/libc/posix1e/acl_strip.c
@@ -180,7 +180,7 @@ acl_is_trivial_np(const acl_t aclp, int *trivialp)
 		 * it's non trivial by definition.
 		 */
 		if (aclp->ats_acl.acl_cnt > 6) {
-			*trivialp = 1;
+			*trivialp = 0;
 			return (0);
 		}
 			

From e95307c5c574ff9370e73bfc917509fa35e28da4 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Thu, 9 Sep 2010 20:51:23 +0000
Subject: [PATCH 0592/1624] * Remove code which has no effect. * Clean up the
 handling in sctp_lower_sosend().

MFC after: 3 weeks.
---
 sys/netinet/sctp_output.c | 169 ++++++++++++++------------------------
 1 file changed, 61 insertions(+), 108 deletions(-)

diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index 38ad9d97258..d4db0e2f165 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -12124,7 +12124,6 @@ sctp_sosend(struct socket *so,
     struct thread *p
 )
 {
-	struct sctp_inpcb *inp;
 	int error, use_rcvinfo = 0;
 	struct sctp_sndrcvinfo srcv;
 	struct sockaddr *addr_to_use;
@@ -12134,7 +12133,6 @@ sctp_sosend(struct socket *so,
 
 #endif
 
-	inp = (struct sctp_inpcb *)so->so_pcb;
 	if (control) {
 		/* process cmsg snd/rcv info (maybe a assoc-id) */
 		if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
@@ -12182,7 +12180,7 @@ sctp_lower_sosend(struct socket *so,
 	struct mbuf *top = NULL;
 	int queue_only = 0, queue_only_for_init = 0;
 	int free_cnt_applied = 0;
-	int un_sent = 0;
+	int un_sent;
 	int now_filled = 0;
 	unsigned int inqueue_bytes = 0;
 	struct sctp_block_entry be;
@@ -12525,9 +12523,10 @@ sctp_lower_sosend(struct socket *so,
 			 * change it BEFORE we append the message.
 			 */
 		}
-	}
+	} else
+		asoc = &stcb->asoc;
 	if (srcv == NULL)
-		srcv = (struct sctp_sndrcvinfo *)&stcb->asoc.def_send;
+		srcv = (struct sctp_sndrcvinfo *)&asoc->def_send;
 	if (srcv->sinfo_flags & SCTP_ADDR_OVER) {
 		if (addr)
 			net = sctp_findnet(stcb, addr);
@@ -12542,14 +12541,10 @@ sctp_lower_sosend(struct socket *so,
 	} else {
 		net = stcb->asoc.primary_destination;
 	}
-
-	if ((SCTP_SO_IS_NBIO(so)
-	    || (flags & MSG_NBIO)
-	    )) {
-		non_blocking = 1;
-	}
-	asoc = &stcb->asoc;
 	atomic_add_int(&stcb->total_sends, 1);
+	/* Keep the stcb from being freed under our feet */
+	atomic_add_int(&asoc->refcnt, 1);
+	free_cnt_applied = 1;
 
 	if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NO_FRAGMENT)) {
 		if (sndlen > asoc->smallest_mtu) {
@@ -12558,6 +12553,11 @@ sctp_lower_sosend(struct socket *so,
 			goto out_unlocked;
 		}
 	}
+	if ((SCTP_SO_IS_NBIO(so)
+	    || (flags & MSG_NBIO)
+	    )) {
+		non_blocking = 1;
+	}
 	/* would we block? */
 	if (non_blocking) {
 		if (hold_tcblock == 0) {
@@ -12581,17 +12581,6 @@ sctp_lower_sosend(struct socket *so,
 		atomic_add_int(&stcb->asoc.sb_send_resv, sndlen);
 	}
 	local_soresv = sndlen;
-	/* Keep the stcb from being freed under our feet */
-	if (free_cnt_applied) {
-#ifdef INVARIANTS
-		panic("refcnt already incremented");
-#else
-		printf("refcnt:1 already incremented?\n");
-#endif
-	} else {
-		atomic_add_int(&stcb->asoc.refcnt, 1);
-		free_cnt_applied = 1;
-	}
 	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
 		error = ECONNRESET;
@@ -12634,26 +12623,6 @@ sctp_lower_sosend(struct socket *so,
 	if (p) {
 		p->td_ru.ru_msgsnd++;
 	}
-	if ((net->flight_size > net->cwnd) &&
-	    (asoc->sctp_cmt_on_off == 0)) {
-		/*-
-		 * CMT: Added check for CMT above. net above is the primary
-		 * dest. If CMT is ON, sender should always attempt to send
-		 * with the output routine sctp_fill_outqueue() that loops
-		 * through all destination addresses. Therefore, if CMT is
-		 * ON, queue_only is NOT set to 1 here, so that
-		 * sctp_chunk_output() can be called below.
-		 */
-		queue_only = 1;
-	} else if (asoc->ifp_had_enobuf) {
-		SCTP_STAT_INCR(sctps_ifnomemqueued);
-		if (net->flight_size > (net->mtu * 2))
-			queue_only = 1;
-		asoc->ifp_had_enobuf = 0;
-	} else {
-		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
-		    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
-	}
 	/* Are we aborting? */
 	if (srcv->sinfo_flags & SCTP_ABORT) {
 		struct mbuf *mm;
@@ -12857,7 +12826,6 @@ sctp_lower_sosend(struct socket *so,
 			}
 			inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
 		}
-		inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
 		if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
 			max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
 		} else {
@@ -12886,9 +12854,7 @@ skip_preblock:
 	if (top == NULL) {
 		struct sctp_stream_queue_pending *sp;
 		struct sctp_stream_out *strm;
-		uint32_t sndout, initial_out;
-
-		initial_out = uio->uio_resid;
+		uint32_t sndout;
 
 		SCTP_TCB_SEND_LOCK(stcb);
 		if ((asoc->stream_locked) &&
@@ -13052,29 +13018,34 @@ skip_preblock:
 				/* Non-blocking io in place out */
 				goto skip_out_eof;
 			}
+			/* What about the INIT, send it maybe */
+			if (queue_only_for_init) {
+				if (hold_tcblock == 0) {
+					SCTP_TCB_LOCK(stcb);
+					hold_tcblock = 1;
+				}
+				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
+					/* a collision took us forward? */
+					queue_only = 0;
+				} else {
+					sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
+					SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
+					queue_only = 1;
+				}
+			}
 			if ((net->flight_size > net->cwnd) &&
 			    (asoc->sctp_cmt_on_off == 0)) {
+				SCTP_STAT_INCR(sctps_send_cwnd_avoid);
 				queue_only = 1;
 			} else if (asoc->ifp_had_enobuf) {
 				SCTP_STAT_INCR(sctps_ifnomemqueued);
-				if (net->flight_size > (net->mtu * 2)) {
+				if (net->flight_size > (2 * net->mtu)) {
 					queue_only = 1;
-				} else {
-					queue_only = 0;
 				}
 				asoc->ifp_had_enobuf = 0;
-				un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
-				    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
-			} else {
-				un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
-				    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
-				if (net->flight_size > net->cwnd) {
-					queue_only = 1;
-					SCTP_STAT_INCR(sctps_send_cwnd_avoid);
-				} else {
-					queue_only = 0;
-				}
 			}
+			un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
+			    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
 			if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
 			    (stcb->asoc.total_flight > 0) &&
 			    (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
@@ -13098,7 +13069,6 @@ skip_preblock:
 				SCTP_STAT_INCR(sctps_naglesent);
 				nagle_applies = 0;
 			}
-			/* What about the INIT, send it maybe */
 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
 
 				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
@@ -13107,22 +13077,8 @@ skip_preblock:
 				    stcb->asoc.total_flight,
 				    stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
 			}
-			if (queue_only_for_init) {
-				if (hold_tcblock == 0) {
-					SCTP_TCB_LOCK(stcb);
-					hold_tcblock = 1;
-				}
-				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
-					/* a collision took us forward? */
-					queue_only_for_init = 0;
-					queue_only = 0;
-				} else {
-					sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
-					SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
-					queue_only_for_init = 0;
-					queue_only = 1;
-				}
-			}
+			if (queue_only_for_init)
+				queue_only_for_init = 0;
 			if ((queue_only == 0) && (nagle_applies == 0)) {
 				/*-
 				 * need to start chunk output
@@ -13215,7 +13171,7 @@ skip_preblock:
 		if (uio->uio_resid == 0) {
 			got_all_of_the_send = 1;
 		}
-	} else if (top) {
+	} else {
 		/* We send in a 0, since we do NOT have any locks */
 		error = sctp_msg_append(stcb, net, top, srcv, 0);
 		top = NULL;
@@ -13326,29 +13282,33 @@ skip_out_eof:
 	if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
 		some_on_control = 1;
 	}
+	if (queue_only_for_init) {
+		if (hold_tcblock == 0) {
+			SCTP_TCB_LOCK(stcb);
+			hold_tcblock = 1;
+		}
+		if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
+			/* a collision took us forward? */
+			queue_only = 0;
+		} else {
+			sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
+			SCTP_SET_STATE(&stcb->asoc, SCTP_STATE_COOKIE_WAIT);
+			queue_only = 1;
+		}
+	}
 	if ((net->flight_size > net->cwnd) &&
 	    (stcb->asoc.sctp_cmt_on_off == 0)) {
+		SCTP_STAT_INCR(sctps_send_cwnd_avoid);
 		queue_only = 1;
 	} else if (asoc->ifp_had_enobuf) {
 		SCTP_STAT_INCR(sctps_ifnomemqueued);
-		if (net->flight_size > (net->mtu * 2)) {
+		if (net->flight_size > (2 * net->mtu)) {
 			queue_only = 1;
-		} else {
-			queue_only = 0;
 		}
 		asoc->ifp_had_enobuf = 0;
-		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
-		    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
-	} else {
-		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
-		    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
-		if (net->flight_size > net->cwnd) {
-			queue_only = 1;
-			SCTP_STAT_INCR(sctps_send_cwnd_avoid);
-		} else {
-			queue_only = 0;
-		}
 	}
+	un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
+	    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
 	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
 	    (stcb->asoc.total_flight > 0) &&
 	    (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
@@ -13371,22 +13331,15 @@ skip_out_eof:
 		SCTP_STAT_INCR(sctps_naglesent);
 		nagle_applies = 0;
 	}
-	if (queue_only_for_init) {
-		if (hold_tcblock == 0) {
-			SCTP_TCB_LOCK(stcb);
-			hold_tcblock = 1;
-		}
-		if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
-			/* a collision took us forward? */
-			queue_only_for_init = 0;
-			queue_only = 0;
-		} else {
-			sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
-			SCTP_SET_STATE(&stcb->asoc, SCTP_STATE_COOKIE_WAIT);
-			queue_only_for_init = 0;
-			queue_only = 1;
-		}
+	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
+		sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
+		    nagle_applies, un_sent);
+		sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
+		    stcb->asoc.total_flight,
+		    stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
 	}
+	if (queue_only_for_init)
+		queue_only_for_init = 0;
 	if ((queue_only == 0) && (nagle_applies == 0) && (stcb->asoc.peers_rwnd && un_sent)) {
 		/* we can attempt to send too. */
 		if (hold_tcblock == 0) {

From 40438ef70625f800751ba4afb8919f66c128d603 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 9 Sep 2010 21:01:41 +0000
Subject: [PATCH 0593/1624] Bump __FreeBSD_version for sbuf ABI change.

---
 sys/sys/param.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/param.h b/sys/sys/param.h
index fec4b46336d..7f1878b80dd 100644
--- a/sys/sys/param.h
+++ b/sys/sys/param.h
@@ -58,7 +58,7 @@
  *		in the range 5 to 9.
  */
 #undef __FreeBSD_version
-#define __FreeBSD_version 900019	/* Master, propagated to newvers */
+#define __FreeBSD_version 900020	/* Master, propagated to newvers */
 
 #ifndef LOCORE
 #include 

From e66811b19374a5a5387ce964fb003426ad92aa51 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 9 Sep 2010 21:15:16 +0000
Subject: [PATCH 0594/1624] Remove duplicated code.

MFC after:	2 weeks
---
 sys/boot/zfs/zfsimpl.c | 29 +++++++++--------------------
 1 file changed, 9 insertions(+), 20 deletions(-)

diff --git a/sys/boot/zfs/zfsimpl.c b/sys/boot/zfs/zfsimpl.c
index e645ebaa6cd..e7ed218d181 100644
--- a/sys/boot/zfs/zfsimpl.c
+++ b/sys/boot/zfs/zfsimpl.c
@@ -488,7 +488,16 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 				vdev->v_name = strdup(type);
 			}
 		}
+	} else {
+		is_new = 0;
+	}
 
+	if (is_new || is_newer) {
+		/*
+		 * This is either new vdev or we've already seen this vdev,
+		 * but from an older vdev label, so let's refresh its state
+		 * from the newer label.
+		 */
 		if (is_offline)
 			vdev->v_state = VDEV_STATE_OFFLINE;
 		else if (is_removed)
@@ -499,26 +508,6 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 			vdev->v_state = VDEV_STATE_DEGRADED;
 		else
 			vdev->v_state = VDEV_STATE_HEALTHY;
-	} else {
-		is_new = 0;
-
-		if (is_newer) {
-			/*
-			 * We've already seen this vdev, but from an older
-			 * vdev label, so let's refresh its state from the
-			 * newer label.
-			 */
-			if (is_offline)
-				vdev->v_state = VDEV_STATE_OFFLINE;
-			else if (is_removed)
-				vdev->v_state = VDEV_STATE_REMOVED;
-			else if (is_faulted)
-				vdev->v_state = VDEV_STATE_FAULTED;
-			else if (is_degraded)
-				vdev->v_state = VDEV_STATE_DEGRADED;
-			else
-				vdev->v_state = VDEV_STATE_HEALTHY;
-		}
 	}
 
 	rc = nvlist_find(nvlist, ZPOOL_CONFIG_CHILDREN,

From c42f23013109ba7acb9b50745c403e79ed7c8b15 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 9 Sep 2010 21:18:00 +0000
Subject: [PATCH 0595/1624] Allow to boot from a pool within which replacing is
 in progress. Before the change it wasn't possible and the following error was
 printed:

	ZFS: can only boot from disk, mirror or raidz vdevs

Now if the original vdev (the one we are replacing) is still present we will
read from it, but if it is not present we won't read from the new vdev, as it
might not have enough valid data yet.

MFC after:	2 weeks
---
 sys/boot/zfs/zfsimpl.c | 36 +++++++++++++++++++++++++++++++++---
 1 file changed, 33 insertions(+), 3 deletions(-)

diff --git a/sys/boot/zfs/zfsimpl.c b/sys/boot/zfs/zfsimpl.c
index e7ed218d181..a4fd5bedabe 100644
--- a/sys/boot/zfs/zfsimpl.c
+++ b/sys/boot/zfs/zfsimpl.c
@@ -376,6 +376,27 @@ vdev_mirror_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
 	return (rc);
 }
 
+static int
+vdev_replacing_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
+    off_t offset, size_t bytes)
+{
+	vdev_t *kid;
+
+	/*
+	 * Here we should have two kids:
+	 * First one which is the one we are replacing and we can trust
+	 * only this one to have valid data, but it might not be present.
+	 * Second one is that one we are replacing with. It is most likely
+	 * healthy, but we can't trust it has needed data, so we won't use it.
+	 */
+	kid = STAILQ_FIRST(&vdev->v_children);
+	if (kid == NULL)
+		return (EIO);
+	if (kid->v_state != VDEV_STATE_HEALTHY)
+		return (EIO);
+	return (kid->v_read(kid, bp, buf, offset, bytes));
+}
+
 static vdev_t *
 vdev_find(uint64_t guid)
 {
@@ -416,7 +437,7 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 	vdev_t *vdev, *kid;
 	const unsigned char *kids;
 	int nkids, i, is_new;
-	uint64_t is_offline, is_faulted, is_degraded, is_removed;
+	uint64_t is_offline, is_faulted, is_degraded, is_removed, isnt_present;
 
 	if (nvlist_find(nvlist, ZPOOL_CONFIG_GUID,
 			DATA_TYPE_UINT64, 0, &guid)
@@ -428,14 +449,17 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 		return (ENOENT);
 	}
 
+
+
 	if (strcmp(type, VDEV_TYPE_MIRROR)
 	    && strcmp(type, VDEV_TYPE_DISK)
-	    && strcmp(type, VDEV_TYPE_RAIDZ)) {
+	    && strcmp(type, VDEV_TYPE_RAIDZ)
+	    && strcmp(type, VDEV_TYPE_REPLACING)) {
 		printf("ZFS: can only boot from disk, mirror or raidz vdevs\n");
 		return (EIO);
 	}
 
-	is_offline = is_removed = is_faulted = is_degraded = 0;
+	is_offline = is_removed = is_faulted = is_degraded = isnt_present = 0;
 
 	nvlist_find(nvlist, ZPOOL_CONFIG_OFFLINE, DATA_TYPE_UINT64, 0,
 			&is_offline);
@@ -445,6 +469,8 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 			&is_faulted);
 	nvlist_find(nvlist, ZPOOL_CONFIG_DEGRADED, DATA_TYPE_UINT64, 0,
 			&is_degraded);
+	nvlist_find(nvlist, ZPOOL_CONFIG_NOT_PRESENT, DATA_TYPE_UINT64, 0,
+			&isnt_present);
 
 	vdev = vdev_find(guid);
 	if (!vdev) {
@@ -454,6 +480,8 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 			vdev = vdev_create(guid, vdev_mirror_read);
 		else if (!strcmp(type, VDEV_TYPE_RAIDZ))
 			vdev = vdev_create(guid, vdev_raidz_read);
+		else if (!strcmp(type, VDEV_TYPE_REPLACING))
+			vdev = vdev_create(guid, vdev_replacing_read);
 		else
 			vdev = vdev_create(guid, vdev_disk_read);
 
@@ -506,6 +534,8 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 			vdev->v_state = VDEV_STATE_FAULTED;
 		else if (is_degraded)
 			vdev->v_state = VDEV_STATE_DEGRADED;
+		else if (isnt_present)
+			vdev->v_state = VDEV_STATE_CANT_OPEN;
 		else
 			vdev->v_state = VDEV_STATE_HEALTHY;
 	}

From f60ec6d63d02ebc755a8c209ff7f8429ea649950 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 9 Sep 2010 21:19:09 +0000
Subject: [PATCH 0596/1624] Ignore log vdevs.

MFC after:	2 weeks
---
 sys/boot/zfs/zfsimpl.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/sys/boot/zfs/zfsimpl.c b/sys/boot/zfs/zfsimpl.c
index a4fd5bedabe..979424e6554 100644
--- a/sys/boot/zfs/zfsimpl.c
+++ b/sys/boot/zfs/zfsimpl.c
@@ -773,6 +773,7 @@ vdev_probe(vdev_phys_read_t *read, void *read_priv, spa_t **spap)
 	uint64_t val;
 	uint64_t guid;
 	uint64_t pool_txg, pool_guid;
+	uint64_t is_log;
 	const char *pool_name;
 	const unsigned char *vdevs;
 	int i, rc, is_newer;
@@ -849,6 +850,12 @@ vdev_probe(vdev_phys_read_t *read, void *read_priv, spa_t **spap)
 		return (EIO);
 	}
 
+	is_log = 0;
+	(void) nvlist_find(nvlist, ZPOOL_CONFIG_IS_LOG, DATA_TYPE_UINT64, 0,
+	    &is_log);
+	if (is_log)
+		return (EIO);
+
 	/*
 	 * Create the pool if this is the first time we've seen it.
 	 */

From 86b19d186197668a67bd5ae8cd446f1fc4b2e775 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 9 Sep 2010 21:20:18 +0000
Subject: [PATCH 0597/1624] On FreeBSD we can log from pool that have multiple
 top-level vdevs or log vdevs, so don't deny adding new vdevs if bootfs
 property is set.

MFC after:	2 weeks
---
 sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
index 764b577b0ae..430a1b934ae 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
@@ -1217,8 +1217,12 @@ zfs_ioc_vdev_add(zfs_cmd_t *zc)
 {
 	spa_t *spa;
 	int error;
+#ifdef sun
 	nvlist_t *config, **l2cache, **spares;
 	uint_t nl2cache = 0, nspares = 0;
+#else
+	nvlist_t *config;
+#endif
 
 	error = spa_open(zc->zc_name, &spa, FTAG);
 	if (error != 0)
@@ -1226,6 +1230,7 @@ zfs_ioc_vdev_add(zfs_cmd_t *zc)
 
 	error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
 	    &config);
+#ifdef sun
 	(void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_L2CACHE,
 	    &l2cache, &nl2cache);
 
@@ -1246,6 +1251,7 @@ zfs_ioc_vdev_add(zfs_cmd_t *zc)
 		spa_close(spa, FTAG);
 		return (EDOM);
 	}
+#endif
 
 	if (error == 0) {
 		error = spa_vdev_add(spa, config);

From fc1b42b552106fd7724f5b5fc0e572888bc692b2 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Thu, 9 Sep 2010 21:32:09 +0000
Subject: [PATCH 0598/1624] Remove empty lines committed by accident.

MFC after:	2 weeks
---
 sys/boot/zfs/zfsimpl.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/boot/zfs/zfsimpl.c b/sys/boot/zfs/zfsimpl.c
index 979424e6554..f5eff6231d6 100644
--- a/sys/boot/zfs/zfsimpl.c
+++ b/sys/boot/zfs/zfsimpl.c
@@ -449,8 +449,6 @@ vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t **vdevp, int is_newer)
 		return (ENOENT);
 	}
 
-
-
 	if (strcmp(type, VDEV_TYPE_MIRROR)
 	    && strcmp(type, VDEV_TYPE_DISK)
 	    && strcmp(type, VDEV_TYPE_RAIDZ)

From 6728a0dfbb155f30d96c0ee28915da02e697af9f Mon Sep 17 00:00:00 2001
From: Christian Brueffer 
Date: Thu, 9 Sep 2010 21:37:05 +0000
Subject: [PATCH 0599/1624] Some more grammar, wording and mdoc fixes.

---
 share/man/man4/aesni.4 | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/share/man/man4/aesni.4 b/share/man/man4/aesni.4
index 995f2b51c59..0001ca274f8 100644
--- a/share/man/man4/aesni.4
+++ b/share/man/man4/aesni.4
@@ -50,20 +50,24 @@ Starting with some models of Core i5/i7, Intel processors implement
 a new set of instructions called AESNI.
 The set of six instructions accelerates the calculation of the key
 schedule for key lengths of 128, 192, and 256 of the Advanced
-Encryption Standard (AES) symmetric cipher, and provides hardware
+Encryption Standard (AES) symmetric cipher, and provides a hardware
 implementation of the regular and the last encryption and decryption
 rounds.
 .Pp
 The processor capability is reported as AESNI in the Features2 line at boot.
-Driver does not attach on the system that lacks the required CPU capability.
+The
+.Nm
+driver does not attach on systems that lack the required CPU capability.
 .Pp
 The
 .Nm
 driver registers itself to accelerate AES operations for
 .Xr crypto 4 .
-Besides speed, the advantage of using the driver is that the AESNI operation
+Besides speed, the advantage of using the
+.Nm
+driver is that the AESNI operation
 is data-independent, thus eliminating some attack vectors based on
-measuring cache use and timings typically present in the table-driven
+measuring cache use and timings typically present in table-driven
 implementations.
 .Sh SEE ALSO
 .Xr crypt 3 ,

From f0a7fc8b30b44bf683647aca6daa9dc75bd0523b Mon Sep 17 00:00:00 2001
From: Christian Brueffer 
Date: Thu, 9 Sep 2010 21:39:06 +0000
Subject: [PATCH 0600/1624] Xref aesni(4).

---
 share/man/man4/crypto.4 | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/crypto.4 b/share/man/man4/crypto.4
index 3d9a80f9c12..bb628254556 100644
--- a/share/man/man4/crypto.4
+++ b/share/man/man4/crypto.4
@@ -28,7 +28,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd March 3, 2009
+.Dd September 7, 2010
 .Dt CRYPTO 4
 .Os
 .Sh NAME
@@ -106,6 +106,7 @@ asymmetric cryptographic features are potentially available from
 crypto access device
 .El
 .Sh SEE ALSO
+.Xr aesni 4 ,
 .Xr glxsb 4 ,
 .Xr hifn 4 ,
 .Xr ipsec 4 ,

From f390d8d927e2bc6a8afd086bfdcdbf5edcbc6875 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Thu, 9 Sep 2010 21:59:53 +0000
Subject: [PATCH 0601/1624] expr(1): Add sh(1) versions of examples, remove an
 incorrect example.

The three examples are better done using sh(1) itself these days.

The example
  expr -- "$a" : ".*"
is incorrect in the general case, as "$a" may be an operator.

MFC after:	2 weeks
---
 bin/expr/expr.1 | 31 +++++++++++++++++++++----------
 1 file changed, 21 insertions(+), 10 deletions(-)

diff --git a/bin/expr/expr.1 b/bin/expr/expr.1
index 3f8eabbdde6..5c3cb4471e4 100644
--- a/bin/expr/expr.1
+++ b/bin/expr/expr.1
@@ -30,7 +30,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd July 12, 2004
+.Dd September 9, 2010
 .Dt EXPR 1
 .Os
 .Sh NAME
@@ -217,6 +217,9 @@ command, one might rearrange the expression:
 More generally, parenthesize possibly-negative values:
 .Dl "a=$(expr \e( $a \e) + 1)"
 .It
+With shell arithmetic, no escaping is required:
+.Dl "a=$((a + 1))"
+.It
 This example prints the filename portion of a pathname stored
 in variable
 .Va a .
@@ -229,6 +232,12 @@ The
 .Li //
 characters resolve this ambiguity.
 .Dl "expr \*q//$a\*q \&: '.*/\e(.*\e)'"
+.It
+With modern
+.Xr sh 1
+syntax,
+.Dl "\*q${a##*/}\*q"
+expands to the same value.
 .El
 .Pp
 The following examples output the number of characters in variable
@@ -237,19 +246,21 @@ Again, if
 .Va a
 might begin with a hyphen, it is necessary to prevent it from being
 interpreted as an option to
-.Nm .
+.Nm ,
+and
+.Va a
+might be interpreted as an operator.
 .Bl -bullet
 .It
-If the
-.Nm
-command conforms to
-.St -p1003.1-2001 ,
-this is simple:
-.Dl "expr -- \*q$a\*q \&: \*q.*\*q"
-.It
-For portability to older systems, however, a more complicated command
+To deal with all of this, a complicated command
 is required:
 .Dl "expr \e( \*qX$a\*q \&: \*q.*\*q \e) - 1"
+.It
+With modern
+.Xr sh 1
+syntax, this can be done much more easily:
+.Dl "${#a}"
+expands to the required number.
 .El
 .Sh SEE ALSO
 .Xr sh 1 ,

From dd5f5f2b1bd18dd5784db92842fd3cb3393eef28 Mon Sep 17 00:00:00 2001
From: "Bjoern A. Zeeb" 
Date: Fri, 10 Sep 2010 00:00:06 +0000
Subject: [PATCH 0602/1624] When using pf routing options, properly handle IP
 fragmentation for interfaces with TSO enabled, otherwise one would see an
 extra ICMP unreach, frag needed pre matching packet on lo0. This syncs pf
 code to ip_output.c r162084.

PR:		kern/144311
Submitted by:	yongari via mlaier
Reviewed by:	eri
Tested by:	kib
MFC after:	8 days
---
 sys/contrib/pf/net/pf.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/contrib/pf/net/pf.c b/sys/contrib/pf/net/pf.c
index ebe73c2e932..242834d80af 100644
--- a/sys/contrib/pf/net/pf.c
+++ b/sys/contrib/pf/net/pf.c
@@ -6375,6 +6375,7 @@ pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
 	m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
 
 	if (ntohs(ip->ip_len) <= ifp->if_mtu ||
+	    (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
 	    (ifp->if_hwassist & CSUM_FRAGMENT &&
 		((ip->ip_off & htons(IP_DF)) == 0))) {
 		/*
@@ -6449,7 +6450,7 @@ pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
 	 * Too large for interface; fragment if possible.
 	 * Must be able to put at least 8 bytes per fragment.
 	 */
-	if (ip->ip_off & htons(IP_DF)) {
+	if (ip->ip_off & htons(IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
 		KMOD_IPSTAT_INC(ips_cantfrag);
 		if (r->rt != PF_DUPTO) {
 #ifdef __FreeBSD__

From 83c9e0893f30e71532bc4e8e69c8cdef0cfb5903 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Fri, 10 Sep 2010 01:47:37 +0000
Subject: [PATCH 0603/1624] Because POSIX does not allow EINTR to be returned
 from sigwait(), add a wrapper for it in libc and rework the code in libthr,
 the system call still can return EINTR, we keep this feature.

Discussed on: thread
Reviewed by:  jilles
---
 lib/libc/stdlib/Makefile.inc |  2 +-
 lib/libc/sys/Makefile.inc    |  3 +++
 lib/libc/sys/Symbol.map      |  1 +
 lib/libc/sys/sigwait.c       | 46 ++++++++++++++++++++++++++++++++++++
 lib/libthr/thread/thr_sig.c  | 14 ++++++-----
 5 files changed, 59 insertions(+), 7 deletions(-)
 create mode 100644 lib/libc/sys/sigwait.c

diff --git a/lib/libc/stdlib/Makefile.inc b/lib/libc/stdlib/Makefile.inc
index 3627294d0b3..ee4c4e22e20 100644
--- a/lib/libc/stdlib/Makefile.inc
+++ b/lib/libc/stdlib/Makefile.inc
@@ -9,7 +9,7 @@ MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \
 	getsubopt.c hcreate.c heapsort.c imaxabs.c imaxdiv.c \
 	insque.c l64a.c labs.c ldiv.c llabs.c lldiv.c lsearch.c malloc.c \
 	merge.c ptsname.c qsort.c qsort_r.c radixsort.c rand.c random.c \
-	reallocf.c realpath.c remque.c strfmon.c strtoimax.c \
+	reallocf.c realpath.c remque.c sigwait.c strfmon.c strtoimax.c \
 	strtol.c strtoll.c strtoq.c strtoul.c strtonum.c strtoull.c \
         strtoumax.c strtouq.c system.c tdelete.c tfind.c tsearch.c twalk.c
 
diff --git a/lib/libc/sys/Makefile.inc b/lib/libc/sys/Makefile.inc
index 9876bdec34e..09d40166825 100644
--- a/lib/libc/sys/Makefile.inc
+++ b/lib/libc/sys/Makefile.inc
@@ -21,6 +21,9 @@ SRCS+=	stack_protector.c stack_protector_compat.c __error.c
 SRCS+=	fcntl.c ftruncate.c lseek.c mmap.c pread.c pwrite.c truncate.c
 PSEUDO+= _fcntl.o
 .endif
+SRCS+= sigwait.c
+NOASM+= sigwait.o
+PSEUDO+= _sigwait.o
 
 # Add machine dependent asm sources:
 SRCS+=${MDASM}
diff --git a/lib/libc/sys/Symbol.map b/lib/libc/sys/Symbol.map
index ce6f32a675c..74751f9f297 100644
--- a/lib/libc/sys/Symbol.map
+++ b/lib/libc/sys/Symbol.map
@@ -919,6 +919,7 @@ FBSDprivate_1.0 {
 	_sigtimedwait;
 	__sys_sigtimedwait;
 	_sigwait;
+	__sigwait;
 	__sys_sigwait;
 	_sigwaitinfo;
 	__sys_sigwaitinfo;
diff --git a/lib/libc/sys/sigwait.c b/lib/libc/sys/sigwait.c
new file mode 100644
index 00000000000..2fdffdd06db
--- /dev/null
+++ b/lib/libc/sys/sigwait.c
@@ -0,0 +1,46 @@
+/*-
+ * Copyright (c) 2010 davidxu@freebsd.org
+ *
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+
+int __sys_sigwait(const sigset_t * restrict, int * restrict);
+
+__weak_reference(__sigwait, sigwait);
+
+int
+__sigwait(const sigset_t * restrict set, int * restrict sig)
+{
+	int ret;
+
+	/* POSIX does not allow EINTR to be returned */
+	do  {
+		ret = __sys_sigwait(set, sig);
+	} while (ret == EINTR);
+	return (ret);
+}
diff --git a/lib/libthr/thread/thr_sig.c b/lib/libthr/thread/thr_sig.c
index 5067e646dca..7bff32b6ddd 100644
--- a/lib/libthr/thread/thr_sig.c
+++ b/lib/libthr/thread/thr_sig.c
@@ -67,7 +67,7 @@ int	_sigtimedwait(const sigset_t *set, siginfo_t *info,
 	const struct timespec * timeout);
 int	__sigwaitinfo(const sigset_t *set, siginfo_t *info);
 int	_sigwaitinfo(const sigset_t *set, siginfo_t *info);
-int	__sigwait(const sigset_t *set, int *sig);
+int	___sigwait(const sigset_t *set, int *sig);
 int	_sigwait(const sigset_t *set, int *sig);
 int	__sigsuspend(const sigset_t *sigmask);
 int	_sigaction(int, const struct sigaction *, struct sigaction *);
@@ -634,7 +634,7 @@ __sigsuspend(const sigset_t * set)
 	return (ret);
 }
 
-__weak_reference(__sigwait, sigwait);
+__weak_reference(___sigwait, sigwait);
 __weak_reference(__sigtimedwait, sigtimedwait);
 __weak_reference(__sigwaitinfo, sigwaitinfo);
 
@@ -708,15 +708,17 @@ _sigwait(const sigset_t *set, int *sig)
  *   it is not canceled.
  */ 
 int
-__sigwait(const sigset_t *set, int *sig)
+___sigwait(const sigset_t *set, int *sig)
 {
 	struct pthread	*curthread = _get_curthread();
 	sigset_t newset;
 	int ret;
 
-	_thr_cancel_enter(curthread);
-	ret = __sys_sigwait(thr_remove_thr_signals(set, &newset), sig);
-	_thr_cancel_leave(curthread, (ret != 0));
+	do {
+		_thr_cancel_enter(curthread);
+		ret = __sys_sigwait(thr_remove_thr_signals(set, &newset), sig);
+		_thr_cancel_leave(curthread, (ret != 0));
+	} while (ret == EINTR);
 	return (ret);
 }
 

From 6a85b5e08a3ee327d3b6e7b248112b5466b9fe39 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Fri, 10 Sep 2010 04:44:13 +0000
Subject: [PATCH 0604/1624] Forgot to commit this file. Add
 ZPOOL_CONFIG_IS_LOG.

Reported by:	keramida
MFC after:	2 weeks
---
 sys/cddl/boot/zfs/zfsimpl.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/cddl/boot/zfs/zfsimpl.h b/sys/cddl/boot/zfs/zfsimpl.h
index 245e01b5da3..34b9a63b72d 100644
--- a/sys/cddl/boot/zfs/zfsimpl.h
+++ b/sys/cddl/boot/zfs/zfsimpl.h
@@ -546,6 +546,7 @@ typedef enum {
 #define	ZPOOL_CONFIG_NPARITY		"nparity"
 #define	ZPOOL_CONFIG_HOSTID		"hostid"
 #define	ZPOOL_CONFIG_HOSTNAME		"hostname"
+#define	ZPOOL_CONFIG_IS_LOG		"is_log"
 #define	ZPOOL_CONFIG_TIMESTAMP		"timestamp" /* not stored on disk */
 
 /*

From 7472161efabb82b30cffe8b533bbe1d2220a1389 Mon Sep 17 00:00:00 2001
From: "David E. O'Brien" 
Date: Fri, 10 Sep 2010 06:26:28 +0000
Subject: [PATCH 0605/1624] Protect BSDI $Id from accidental manipulation.

---
 sys/sys/lock.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/lock.h b/sys/sys/lock.h
index 85d8bb824cd..7ad9c58c15d 100644
--- a/sys/sys/lock.h
+++ b/sys/sys/lock.h
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	from BSDI $Id: mutex.h,v 2.7.2.35 2000/04/27 03:10:26 cp Exp $
+ *	from BSDI Id: mutex.h,v 2.7.2.35 2000/04/27 03:10:26 cp
  * $FreeBSD$
  */
 

From bfd7cd013167056f102b8e598f76f1f47fc09bdb Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Fri, 10 Sep 2010 07:06:06 +0000
Subject: [PATCH 0606/1624] Compilation fix - when INVARIANTS are turned off.

---
 sys/mips/rmi/dev/nlge/if_nlge.c | 5 ++++-
 sys/mips/rmi/dev/xlr/rge.c      | 5 ++++-
 sys/mips/rmi/msgring.h          | 2 ++
 3 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
index 82092a955fd..d6c16a50cd9 100644
--- a/sys/mips/rmi/dev/nlge/if_nlge.c
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -1953,7 +1953,10 @@ send_fmn_msg_tx(struct nlge_softc *sc, struct msgrng_msg *msg,
     uint32_t n_entries)
 {
 	uint32_t msgrng_flags;
-	int i = 0, ret;
+	int ret;
+#ifdef INVARIANTS
+	int i = 0;
+#endif
 
 	do {
 		msgrng_flags = msgrng_access_enable();
diff --git a/sys/mips/rmi/dev/xlr/rge.c b/sys/mips/rmi/dev/xlr/rge.c
index 924031a4c5e..661c7895b57 100644
--- a/sys/mips/rmi/dev/xlr/rge.c
+++ b/sys/mips/rmi/dev/xlr/rge.c
@@ -713,8 +713,11 @@ xlr_mac_send_fr(struct driver_data *priv,
 {
 	struct msgrng_msg msg;
 	int stid = priv->rfrbucket;
-	int i = 0, code, ret;
+	int code, ret;
 	uint32_t msgrng_flags;
+#ifdef INVARIANTS
+	int i = 0;
+#endif
 
 	mac_make_desc_rfr(&msg, addr);
 
diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h
index d524892d73c..6e61b50d8d9 100644
--- a/sys/mips/rmi/msgring.h
+++ b/sys/mips/rmi/msgring.h
@@ -306,7 +306,9 @@ message_send(unsigned int size, unsigned int code,
 {
 	unsigned int dest = 0;
 	unsigned long long status = 0;
+#ifdef INVARIANTS
 	int i = 0;
+#endif
 
 	msgrng_load_tx_msg0(msg->msg0);
 	msgrng_load_tx_msg1(msg->msg1);

From 571d92b0129a3c97419d31ce35fde0342caaea7b Mon Sep 17 00:00:00 2001
From: Bernhard Schmidt 
Date: Fri, 10 Sep 2010 08:11:48 +0000
Subject: [PATCH 0607/1624] Fix firmware module dependencies.

malo and mwl use the firmware framework to access firmware images.
Depending on the firmware modules itself is not required and in this
case even wrong because no modules with those names exist.

Pointed out by:	brucec
MFC after:	1 week
---
 sys/dev/malo/if_malo_pci.c | 2 +-
 sys/dev/mwl/if_mwl_pci.c   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/malo/if_malo_pci.c b/sys/dev/malo/if_malo_pci.c
index fbad5ab4c17..65aac7ca63c 100644
--- a/sys/dev/malo/if_malo_pci.c
+++ b/sys/dev/malo/if_malo_pci.c
@@ -371,4 +371,4 @@ static	devclass_t malo_devclass;
 DRIVER_MODULE(malo, pci, malo_pci_driver, malo_devclass, 0, 0);
 MODULE_VERSION(malo, 1);
 MODULE_DEPEND(malo, wlan, 1, 1, 1);		/* 802.11 media layer */
-MODULE_DEPEND(malo, malofw_fw, 1, 1, 1);
+MODULE_DEPEND(malo, firmware, 1, 1, 1);
diff --git a/sys/dev/mwl/if_mwl_pci.c b/sys/dev/mwl/if_mwl_pci.c
index 33666d40f12..d800a5470c2 100644
--- a/sys/dev/mwl/if_mwl_pci.c
+++ b/sys/dev/mwl/if_mwl_pci.c
@@ -313,4 +313,4 @@ static	devclass_t mwl_devclass;
 DRIVER_MODULE(mwl, pci, mwl_pci_driver, mwl_devclass, 0, 0);
 MODULE_VERSION(mwl, 1);
 MODULE_DEPEND(mwl, wlan, 1, 1, 1);		/* 802.11 media layer */
-MODULE_DEPEND(mwl, mwlfw_fw, 1, 1, 1);		/* firmware */
+MODULE_DEPEND(mwl, firmware, 1, 1, 1);

From b6c44f6440480e76e0a9ba5c1b3218cc56727f5c Mon Sep 17 00:00:00 2001
From: Bernhard Schmidt 
Date: Fri, 10 Sep 2010 08:27:02 +0000
Subject: [PATCH 0608/1624] Create the var/run/wpa_supplicant directory where
 the wpa_supplicant RC script wants to save a pidfile for each interface.

MFC after:	2 weeks
---
 etc/mtree/BSD.var.dist | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/etc/mtree/BSD.var.dist b/etc/mtree/BSD.var.dist
index f55fbbb23b7..9ad314bfef1 100644
--- a/etc/mtree/BSD.var.dist
+++ b/etc/mtree/BSD.var.dist
@@ -64,6 +64,8 @@
         ..
         ppp             gname=network mode=0770
         ..
+        wpa_supplicant
+        ..
     ..
     rwho            gname=daemon mode=0775
     ..

From 5696dee9f45132c83ae72a27262423b978b57f86 Mon Sep 17 00:00:00 2001
From: MIHIRA Sanpei Yoshiro 
Date: Fri, 10 Sep 2010 11:01:11 +0000
Subject: [PATCH 0609/1624] Add Planex UE-200TX-G to list of supported devices.
 (http://lists.freebsd.org/pipermail/freebsd-current/2008-December/001756.html)

Submitted by:	nork
MFC after:	3 days
---
 share/man/man4/axe.4 | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/share/man/man4/axe.4 b/share/man/man4/axe.4
index c83d8f57f4b..c004ed10944 100644
--- a/share/man/man4/axe.4
+++ b/share/man/man4/axe.4
@@ -182,6 +182,8 @@ Buffalo (Melco Inc.) LUA3-U2-ATX
 Cisco-Linksys USB200Mv2
 .It
 D-Link DUBE100B1
+.It
+Planex UE-200TX-G
 .El
 .Sh DIAGNOSTICS
 .Bl -diag

From 3d844eddb70884ea1c2414d9cec87c16974b3f67 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Fri, 10 Sep 2010 11:19:03 +0000
Subject: [PATCH 0610/1624] bus_add_child: change type of order parameter to
 u_int

This reflects actual type used to store and compare child device orders.
Change is mostly done via a Coccinelle (soon to be devel/coccinelle)
semantic patch.
Verified by LINT+modules kernel builds.

Followup to:	r212213
MFC after:	10 days
---
 sys/amd64/amd64/legacy.c       | 8 ++++----
 sys/amd64/amd64/nexus.c        | 4 ++--
 sys/arm/arm/nexus.c            | 4 ++--
 sys/arm/xscale/ixp425/ixp425.c | 2 +-
 sys/dev/acpica/acpi.c          | 4 ++--
 sys/dev/acpica/acpi_cpu.c      | 4 ++--
 sys/dev/atkbdc/atkbdc_isa.c    | 4 ++--
 sys/dev/firewire/firewire.c    | 4 ++--
 sys/dev/firewire/fwohci_pci.c  | 2 +-
 sys/dev/iicbus/iicbus.c        | 2 +-
 sys/dev/ofw/ofw_iicbus.c       | 6 +++---
 sys/dev/ppbus/ppbconf.c        | 2 +-
 sys/dev/siba/siba.c            | 4 ++--
 sys/dev/spibus/spibus.c        | 2 +-
 sys/i386/i386/legacy.c         | 8 ++++----
 sys/i386/i386/nexus.c          | 4 ++--
 sys/ia64/ia64/nexus.c          | 4 ++--
 sys/isa/isa_common.c           | 2 +-
 sys/kern/bus_if.m              | 2 +-
 sys/kern/subr_bus.c            | 2 +-
 sys/mips/adm5120/obio.c        | 4 ++--
 sys/mips/alchemy/obio.c        | 4 ++--
 sys/mips/atheros/apb.c         | 4 ++--
 sys/mips/idt/obio.c            | 4 ++--
 sys/mips/mips/mainbus.c        | 4 ++--
 sys/mips/mips/nexus.c          | 4 ++--
 sys/mips/sibyte/sb_zbbus.c     | 2 +-
 sys/pc98/pc98/canbus.c         | 4 ++--
 sys/powerpc/aim/nexus.c        | 4 ++--
 sys/sparc64/sparc64/nexus.c    | 2 +-
 sys/sun4v/sun4v/nexus.c        | 2 +-
 sys/sun4v/sun4v/vnex.c         | 2 +-
 sys/sys/bus.h                  | 2 +-
 33 files changed, 58 insertions(+), 58 deletions(-)

diff --git a/sys/amd64/amd64/legacy.c b/sys/amd64/amd64/legacy.c
index 9aa0365d26b..4123f84e224 100644
--- a/sys/amd64/amd64/legacy.c
+++ b/sys/amd64/amd64/legacy.c
@@ -60,7 +60,7 @@ struct legacy_device {
 static	int legacy_probe(device_t);
 static	int legacy_attach(device_t);
 static	int legacy_print_child(device_t, device_t);
-static device_t legacy_add_child(device_t bus, int order, const char *name,
+static device_t legacy_add_child(device_t bus, u_int order, const char *name,
 				int unit);
 static	int legacy_read_ivar(device_t, device_t, int, uintptr_t *);
 static	int legacy_write_ivar(device_t, device_t, int, uintptr_t);
@@ -149,7 +149,7 @@ legacy_print_child(device_t bus, device_t child)
 }
 
 static device_t
-legacy_add_child(device_t bus, int order, const char *name, int unit)
+legacy_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct legacy_device *atdev;
@@ -213,7 +213,7 @@ legacy_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
 static void	cpu_identify(driver_t *driver, device_t parent);
 static int	cpu_read_ivar(device_t dev, device_t child, int index,
 		    uintptr_t *result);
-static device_t cpu_add_child(device_t bus, int order, const char *name,
+static device_t cpu_add_child(device_t bus, u_int order, const char *name,
 		    int unit);
 static struct resource_list *cpu_get_rlist(device_t dev, device_t child);
 
@@ -277,7 +277,7 @@ cpu_identify(driver_t *driver, device_t parent)
 }
 
 static device_t
-cpu_add_child(device_t bus, int order, const char *name, int unit)
+cpu_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	struct cpu_device *cd;
 	device_t child;
diff --git a/sys/amd64/amd64/nexus.c b/sys/amd64/amd64/nexus.c
index 4c701a0e9d3..037d4ac4e72 100644
--- a/sys/amd64/amd64/nexus.c
+++ b/sys/amd64/amd64/nexus.c
@@ -83,7 +83,7 @@ static	int nexus_probe(device_t);
 static	int nexus_attach(device_t);
 static	int nexus_print_all_resources(device_t dev);
 static	int nexus_print_child(device_t, device_t);
-static device_t nexus_add_child(device_t bus, int order, const char *name,
+static device_t nexus_add_child(device_t bus, u_int order, const char *name,
 				int unit);
 static	struct resource *nexus_alloc_resource(device_t, device_t, int, int *,
 					      u_long, u_long, u_long, u_int);
@@ -293,7 +293,7 @@ nexus_print_child(device_t bus, device_t child)
 }
 
 static device_t
-nexus_add_child(device_t bus, int order, const char *name, int unit)
+nexus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct nexus_device	*ndev;
diff --git a/sys/arm/arm/nexus.c b/sys/arm/arm/nexus.c
index 584960f8344..4efca1436f7 100644
--- a/sys/arm/arm/nexus.c
+++ b/sys/arm/arm/nexus.c
@@ -74,7 +74,7 @@ static struct rman mem_rman;
 static	int nexus_probe(device_t);
 static	int nexus_attach(device_t);
 static	int nexus_print_child(device_t, device_t);
-static	device_t nexus_add_child(device_t, int, const char *, int);
+static	device_t nexus_add_child(device_t, u_int, const char *, int);
 static	struct resource *nexus_alloc_resource(device_t, device_t, int, int *,
     u_long, u_long, u_long, u_int);
 static	int nexus_activate_resource(device_t, device_t, int, int,
@@ -166,7 +166,7 @@ nexus_print_child(device_t bus, device_t child)
 }
 
 static device_t
-nexus_add_child(device_t bus, int order, const char *name, int unit)
+nexus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct nexus_device *ndev;
diff --git a/sys/arm/xscale/ixp425/ixp425.c b/sys/arm/xscale/ixp425/ixp425.c
index ac70bcbd409..9b11b4339e2 100644
--- a/sys/arm/xscale/ixp425/ixp425.c
+++ b/sys/arm/xscale/ixp425/ixp425.c
@@ -369,7 +369,7 @@ ixp425_hinted_child(device_t bus, const char *dname, int dunit)
 }
 
 static device_t
-ixp425_add_child(device_t dev, int order, const char *name, int unit)
+ixp425_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct ixp425_ivar *ivar;
diff --git a/sys/dev/acpica/acpi.c b/sys/dev/acpica/acpi.c
index 7c941f36561..5cccc9ed2da 100644
--- a/sys/dev/acpica/acpi.c
+++ b/sys/dev/acpica/acpi.c
@@ -105,7 +105,7 @@ static int	acpi_attach(device_t dev);
 static int	acpi_suspend(device_t dev);
 static int	acpi_resume(device_t dev);
 static int	acpi_shutdown(device_t dev);
-static device_t	acpi_add_child(device_t bus, int order, const char *name,
+static device_t	acpi_add_child(device_t bus, u_int order, const char *name,
 			int unit);
 static int	acpi_print_child(device_t bus, device_t child);
 static void	acpi_probe_nomatch(device_t bus, device_t child);
@@ -781,7 +781,7 @@ acpi_shutdown(device_t dev)
  * Handle a new device being added
  */
 static device_t
-acpi_add_child(device_t bus, int order, const char *name, int unit)
+acpi_add_child(device_t bus, u_int order, const char *name, int unit)
 {
     struct acpi_device	*ad;
     device_t		child;
diff --git a/sys/dev/acpica/acpi_cpu.c b/sys/dev/acpica/acpi_cpu.c
index 45882a23ce9..5dd6ab97f7e 100644
--- a/sys/dev/acpica/acpi_cpu.c
+++ b/sys/dev/acpica/acpi_cpu.c
@@ -148,7 +148,7 @@ static int	acpi_cpu_resume(device_t dev);
 static int	acpi_pcpu_get_id(uint32_t idx, uint32_t *acpi_id,
 		    uint32_t *cpu_id);
 static struct resource_list *acpi_cpu_get_rlist(device_t dev, device_t child);
-static device_t	acpi_cpu_add_child(device_t dev, int order, const char *name,
+static device_t	acpi_cpu_add_child(device_t dev, u_int order, const char *name,
 		    int unit);
 static int	acpi_cpu_read_ivar(device_t dev, device_t child, int index,
 		    uintptr_t *result);
@@ -479,7 +479,7 @@ acpi_cpu_get_rlist(device_t dev, device_t child)
 }
 
 static device_t
-acpi_cpu_add_child(device_t dev, int order, const char *name, int unit)
+acpi_cpu_add_child(device_t dev, u_int order, const char *name, int unit)
 {
     struct acpi_cpu_device *ad;
     device_t child;
diff --git a/sys/dev/atkbdc/atkbdc_isa.c b/sys/dev/atkbdc/atkbdc_isa.c
index 10e172f4552..42bb67bd9c8 100644
--- a/sys/dev/atkbdc/atkbdc_isa.c
+++ b/sys/dev/atkbdc/atkbdc_isa.c
@@ -47,7 +47,7 @@ __FBSDID("$FreeBSD$");
 
 static int	atkbdc_isa_probe(device_t dev);
 static int	atkbdc_isa_attach(device_t dev);
-static device_t	atkbdc_isa_add_child(device_t bus, int order, const char *name,
+static device_t	atkbdc_isa_add_child(device_t bus, u_int order, const char *name,
 		    int unit);
 
 static device_method_t atkbdc_isa_methods[] = {
@@ -230,7 +230,7 @@ atkbdc_isa_attach(device_t dev)
 }
 
 static device_t
-atkbdc_isa_add_child(device_t bus, int order, const char *name, int unit)
+atkbdc_isa_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	atkbdc_device_t	*ivar;
 	device_t	child;
diff --git a/sys/dev/firewire/firewire.c b/sys/dev/firewire/firewire.c
index a035959d16d..490f39bcfb4 100644
--- a/sys/dev/firewire/firewire.c
+++ b/sys/dev/firewire/firewire.c
@@ -102,7 +102,7 @@ static void firewire_xfer_timeout(void *, int);
 #if 0
 static int firewire_shutdown    (device_t);
 #endif
-static device_t firewire_add_child   (device_t, int, const char *, int);
+static device_t firewire_add_child(device_t, u_int, const char *, int);
 static void fw_try_bmr (void *);
 static void fw_try_bmr_callback (struct fw_xfer *);
 static void fw_asystart (struct fw_xfer *);
@@ -488,7 +488,7 @@ firewire_attach(device_t dev)
  * Attach it as child.
  */
 static device_t
-firewire_add_child(device_t dev, int order, const char *name, int unit)
+firewire_add_child(device_t dev, u_int order, const char *name, int unit)
 {
         device_t child;
 	struct firewire_softc *sc;
diff --git a/sys/dev/firewire/fwohci_pci.c b/sys/dev/firewire/fwohci_pci.c
index 5524954c756..0bb66a9ed5e 100644
--- a/sys/dev/firewire/fwohci_pci.c
+++ b/sys/dev/firewire/fwohci_pci.c
@@ -487,7 +487,7 @@ fwohci_pci_shutdown(device_t dev)
 }
 
 static device_t
-fwohci_pci_add_child(device_t dev, int order, const char *name, int unit)
+fwohci_pci_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	struct fwohci_softc *sc;
 	device_t child;
diff --git a/sys/dev/iicbus/iicbus.c b/sys/dev/iicbus/iicbus.c
index 5c16f207f1f..ca110c85746 100644
--- a/sys/dev/iicbus/iicbus.c
+++ b/sys/dev/iicbus/iicbus.c
@@ -188,7 +188,7 @@ iicbus_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
 }
 
 static device_t
-iicbus_add_child(device_t dev, int order, const char *name, int unit)
+iicbus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct iicbus_ivar *devi;
diff --git a/sys/dev/ofw/ofw_iicbus.c b/sys/dev/ofw/ofw_iicbus.c
index 2ee9a728318..875e4ddb13b 100644
--- a/sys/dev/ofw/ofw_iicbus.c
+++ b/sys/dev/ofw/ofw_iicbus.c
@@ -46,8 +46,8 @@ __FBSDID("$FreeBSD$");
 /* Methods */
 static device_probe_t ofw_iicbus_probe;
 static device_attach_t ofw_iicbus_attach;
-static device_t ofw_iicbus_add_child(device_t dev, int order, const char *name,
-    int unit);
+static device_t ofw_iicbus_add_child(device_t dev, u_int order,
+    const char *name, int unit);
 static const struct ofw_bus_devinfo *ofw_iicbus_get_devinfo(device_t bus,
     device_t dev);
 
@@ -147,7 +147,7 @@ ofw_iicbus_attach(device_t dev)
 }
 
 static device_t
-ofw_iicbus_add_child(device_t dev, int order, const char *name, int unit)
+ofw_iicbus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct ofw_iicbus_devinfo *devi;
diff --git a/sys/dev/ppbus/ppbconf.c b/sys/dev/ppbus/ppbconf.c
index a994355cfcf..9e21c67dcad 100644
--- a/sys/dev/ppbus/ppbconf.c
+++ b/sys/dev/ppbus/ppbconf.c
@@ -90,7 +90,7 @@ ppbus_probe(device_t dev)
  * Add a ppbus device, allocate/initialize the ivars
  */
 static device_t
-ppbus_add_child(device_t dev, int order, const char *name, int unit)
+ppbus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	struct ppb_device *ppbdev;
 	device_t child;
diff --git a/sys/dev/siba/siba.c b/sys/dev/siba/siba.c
index 4ee11ca24a4..b2c49fb95c8 100644
--- a/sys/dev/siba/siba.c
+++ b/sys/dev/siba/siba.c
@@ -90,7 +90,7 @@ static struct siba_devid siba_devids[] = {
 
 static int	siba_activate_resource(device_t, device_t, int, int,
 		    struct resource *);
-static device_t	siba_add_child(device_t, int, const char *, int);
+static device_t	siba_add_child(device_t, u_int, const char *, int);
 static struct resource *
 		siba_alloc_resource(device_t, device_t, int, int *, u_long,
 		    u_long, u_long, u_int);
@@ -505,7 +505,7 @@ siba_destroy_devinfo(struct siba_devinfo *sdi)
 
 /* XXX is this needed? */
 static device_t
-siba_add_child(device_t dev, int order, const char *name, int unit)
+siba_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 #if 1
 
diff --git a/sys/dev/spibus/spibus.c b/sys/dev/spibus/spibus.c
index a0c0380398d..9491734eedd 100644
--- a/sys/dev/spibus/spibus.c
+++ b/sys/dev/spibus/spibus.c
@@ -127,7 +127,7 @@ spibus_read_ivar(device_t bus, device_t child, int which, u_int *result)
 }
 
 static device_t
-spibus_add_child(device_t dev, int order, const char *name, int unit)
+spibus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct spibus_ivar *devi;
diff --git a/sys/i386/i386/legacy.c b/sys/i386/i386/legacy.c
index 39f3e229a1a..fe9b403efaa 100644
--- a/sys/i386/i386/legacy.c
+++ b/sys/i386/i386/legacy.c
@@ -65,7 +65,7 @@ struct legacy_device {
 static	int legacy_probe(device_t);
 static	int legacy_attach(device_t);
 static	int legacy_print_child(device_t, device_t);
-static device_t legacy_add_child(device_t bus, int order, const char *name,
+static device_t legacy_add_child(device_t bus, u_int order, const char *name,
 				int unit);
 static	int legacy_read_ivar(device_t, device_t, int, uintptr_t *);
 static	int legacy_write_ivar(device_t, device_t, int, uintptr_t);
@@ -170,7 +170,7 @@ legacy_print_child(device_t bus, device_t child)
 }
 
 static device_t
-legacy_add_child(device_t bus, int order, const char *name, int unit)
+legacy_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct legacy_device *atdev;
@@ -234,7 +234,7 @@ legacy_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
 static void	cpu_identify(driver_t *driver, device_t parent);
 static int	cpu_read_ivar(device_t dev, device_t child, int index,
 		    uintptr_t *result);
-static device_t cpu_add_child(device_t bus, int order, const char *name,
+static device_t cpu_add_child(device_t bus, u_int order, const char *name,
 		    int unit);
 static struct resource_list *cpu_get_rlist(device_t dev, device_t child);
 
@@ -298,7 +298,7 @@ cpu_identify(driver_t *driver, device_t parent)
 }
 
 static device_t
-cpu_add_child(device_t bus, int order, const char *name, int unit)
+cpu_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	struct cpu_device *cd;
 	device_t child;
diff --git a/sys/i386/i386/nexus.c b/sys/i386/i386/nexus.c
index 04dd464ce77..ec87528934d 100644
--- a/sys/i386/i386/nexus.c
+++ b/sys/i386/i386/nexus.c
@@ -87,7 +87,7 @@ static	int nexus_probe(device_t);
 static	int nexus_attach(device_t);
 static	int nexus_print_all_resources(device_t dev);
 static	int nexus_print_child(device_t, device_t);
-static device_t nexus_add_child(device_t bus, int order, const char *name,
+static device_t nexus_add_child(device_t bus, u_int order, const char *name,
 				int unit);
 static	struct resource *nexus_alloc_resource(device_t, device_t, int, int *,
 					      u_long, u_long, u_long, u_int);
@@ -305,7 +305,7 @@ nexus_print_child(device_t bus, device_t child)
 }
 
 static device_t
-nexus_add_child(device_t bus, int order, const char *name, int unit)
+nexus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct nexus_device	*ndev;
diff --git a/sys/ia64/ia64/nexus.c b/sys/ia64/ia64/nexus.c
index 9885b747aa2..43d06323b31 100644
--- a/sys/ia64/ia64/nexus.c
+++ b/sys/ia64/ia64/nexus.c
@@ -82,7 +82,7 @@ static struct rman irq_rman, port_rman, mem_rman;
 static	int nexus_probe(device_t);
 static	int nexus_attach(device_t);
 static	int nexus_print_child(device_t, device_t);
-static device_t nexus_add_child(device_t bus, int order, const char *name,
+static device_t nexus_add_child(device_t bus, u_int order, const char *name,
 				int unit);
 static	struct resource *nexus_alloc_resource(device_t, device_t, int, int *,
 					      u_long, u_long, u_long, u_int);
@@ -220,7 +220,7 @@ nexus_print_child(device_t bus, device_t child)
 }
 
 static device_t
-nexus_add_child(device_t bus, int order, const char *name, int unit)
+nexus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct nexus_device	*ndev;
diff --git a/sys/isa/isa_common.c b/sys/isa/isa_common.c
index bcf77299244..1d1a13af647 100644
--- a/sys/isa/isa_common.c
+++ b/sys/isa/isa_common.c
@@ -597,7 +597,7 @@ isa_probe_children(device_t dev)
  * Add a new child with default ivars.
  */
 static device_t
-isa_add_child(device_t dev, int order, const char *name, int unit)
+isa_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct	isa_device *idev;
diff --git a/sys/kern/bus_if.m b/sys/kern/bus_if.m
index 326156eb49d..688a47010e8 100644
--- a/sys/kern/bus_if.m
+++ b/sys/kern/bus_if.m
@@ -200,7 +200,7 @@ METHOD void driver_added {
  */
 METHOD device_t add_child {
 	device_t _dev;
-	int _order;
+	u_int _order;
 	const char *_name;
 	int _unit;
 };
diff --git a/sys/kern/subr_bus.c b/sys/kern/subr_bus.c
index 9912d980383..fe3b294b7a3 100644
--- a/sys/kern/subr_bus.c
+++ b/sys/kern/subr_bus.c
@@ -3284,7 +3284,7 @@ resource_list_purge(struct resource_list *rl)
 }
 
 device_t
-bus_generic_add_child(device_t dev, int order, const char *name, int unit)
+bus_generic_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 
 	return (device_add_child_ordered(dev, order, name, unit));
diff --git a/sys/mips/adm5120/obio.c b/sys/mips/adm5120/obio.c
index ad6cb6e2ea7..b89c9576579 100644
--- a/sys/mips/adm5120/obio.c
+++ b/sys/mips/adm5120/obio.c
@@ -101,7 +101,7 @@ int irq_priorities[NIRQS] = {
 
 static int	obio_activate_resource(device_t, device_t, int, int,
 		    struct resource *);
-static device_t	obio_add_child(device_t, int, const char *, int);
+static device_t	obio_add_child(device_t, u_int, const char *, int);
 static struct resource *
 		obio_alloc_resource(device_t, device_t, int, int *, u_long,
 		    u_long, u_long, u_int);
@@ -480,7 +480,7 @@ obio_hinted_child(device_t bus, const char *dname, int dunit)
 }
 
 static device_t
-obio_add_child(device_t bus, int order, const char *name, int unit)
+obio_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct obio_ivar	*ivar;
diff --git a/sys/mips/alchemy/obio.c b/sys/mips/alchemy/obio.c
index fb55813c581..90e41d61bfa 100644
--- a/sys/mips/alchemy/obio.c
+++ b/sys/mips/alchemy/obio.c
@@ -101,7 +101,7 @@ int irq_priorities[NIRQS] = {
 
 static int	obio_activate_resource(device_t, device_t, int, int,
 		    struct resource *);
-static device_t	obio_add_child(device_t, int, const char *, int);
+static device_t	obio_add_child(device_t, u_int, const char *, int);
 static struct resource *
 		obio_alloc_resource(device_t, device_t, int, int *, u_long,
 		    u_long, u_long, u_int);
@@ -472,7 +472,7 @@ obio_hinted_child(device_t bus, const char *dname, int dunit)
 }
 
 static device_t
-obio_add_child(device_t bus, int order, const char *name, int unit)
+obio_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct obio_ivar	*ivar;
diff --git a/sys/mips/atheros/apb.c b/sys/mips/atheros/apb.c
index d71b24210e0..c004741cfd8 100644
--- a/sys/mips/atheros/apb.c
+++ b/sys/mips/atheros/apb.c
@@ -52,7 +52,7 @@ __FBSDID("$FreeBSD$");
 
 static int	apb_activate_resource(device_t, device_t, int, int,
 		    struct resource *);
-static device_t	apb_add_child(device_t, int, const char *, int);
+static device_t	apb_add_child(device_t, u_int, const char *, int);
 static struct resource *
 		apb_alloc_resource(device_t, device_t, int, int *, u_long,
 		    u_long, u_long, u_int);
@@ -397,7 +397,7 @@ apb_hinted_child(device_t bus, const char *dname, int dunit)
 }
 
 static device_t
-apb_add_child(device_t bus, int order, const char *name, int unit)
+apb_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct apb_ivar	*ivar;
diff --git a/sys/mips/idt/obio.c b/sys/mips/idt/obio.c
index 44e9bfa6ea4..034b93ab644 100644
--- a/sys/mips/idt/obio.c
+++ b/sys/mips/idt/obio.c
@@ -57,7 +57,7 @@ __FBSDID("$FreeBSD$");
 
 static int	obio_activate_resource(device_t, device_t, int, int,
 		    struct resource *);
-static device_t	obio_add_child(device_t, int, const char *, int);
+static device_t	obio_add_child(device_t, u_int, const char *, int);
 static struct resource *
 		obio_alloc_resource(device_t, device_t, int, int *, u_long,
 		    u_long, u_long, u_int);
@@ -422,7 +422,7 @@ obio_hinted_child(device_t bus, const char *dname, int dunit)
 }
 
 static device_t
-obio_add_child(device_t bus, int order, const char *name, int unit)
+obio_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t		child;
 	struct obio_ivar	*ivar;
diff --git a/sys/mips/mips/mainbus.c b/sys/mips/mips/mainbus.c
index 3e1e66ac5f5..587b409a3be 100644
--- a/sys/mips/mips/mainbus.c
+++ b/sys/mips/mips/mainbus.c
@@ -67,7 +67,7 @@ static struct rman irq_rman, port_rman, mem_rman;
 static	int mainbus_probe(device_t);
 static	int mainbus_attach(device_t);
 static	int mainbus_print_child(device_t, device_t);
-static	device_t mainbus_add_child(device_t bus, int order, const char *name,
+static	device_t mainbus_add_child(device_t bus, u_int order, const char *name,
 	    int unit);
 static	struct resource *mainbus_alloc_resource(device_t, device_t, int, int *,
 	    u_long, u_long, u_long, u_int);
@@ -178,7 +178,7 @@ mainbus_print_child(device_t bus, device_t child)
 }
 
 static device_t
-mainbus_add_child(device_t bus, int order, const char *name, int unit)
+mainbus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	return device_add_child_ordered(bus, order, name, unit);
 }
diff --git a/sys/mips/mips/nexus.c b/sys/mips/mips/nexus.c
index 10b38b5ff86..227446618e0 100644
--- a/sys/mips/mips/nexus.c
+++ b/sys/mips/mips/nexus.c
@@ -82,7 +82,7 @@ static struct resource *
 		    u_long, u_long, u_int);
 static int	nexus_activate_resource(device_t, device_t, int, int,
 		    struct resource *);
-static device_t	nexus_add_child(device_t, int, const char *, int);
+static device_t	nexus_add_child(device_t, u_int, const char *, int);
 static int	nexus_attach(device_t);
 static int	nexus_deactivate_resource(device_t, device_t, int, int,
 		    struct resource *);
@@ -282,7 +282,7 @@ nexus_hinted_child(device_t bus, const char *dname, int dunit)
 }
 
 static device_t
-nexus_add_child(device_t bus, int order, const char *name, int unit)
+nexus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t	child;
 	struct nexus_device *ndev;
diff --git a/sys/mips/sibyte/sb_zbbus.c b/sys/mips/sibyte/sb_zbbus.c
index cd168564896..e166b8f2661 100644
--- a/sys/mips/sibyte/sb_zbbus.c
+++ b/sys/mips/sibyte/sb_zbbus.c
@@ -402,7 +402,7 @@ zbbus_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
 }
 
 static device_t
-zbbus_add_child(device_t bus, int order, const char *name, int unit)
+zbbus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct zbbus_devinfo *dinfo;
diff --git a/sys/pc98/pc98/canbus.c b/sys/pc98/pc98/canbus.c
index 522b4d0ba5c..ceb2d71fb60 100644
--- a/sys/pc98/pc98/canbus.c
+++ b/sys/pc98/pc98/canbus.c
@@ -82,7 +82,7 @@ static int	canbus_detach(device_t);
 
 /* Bus interface methods */
 static int	canbus_print_child(device_t, device_t);
-static device_t	canbus_add_child(device_t, int, const char *, int);
+static device_t	canbus_add_child(device_t, u_int, const char *, int);
 static struct resource *	canbus_alloc_resource(
     device_t, device_t, int, int *, u_long, u_long, u_long, u_int);
 static int	canbus_activate_resource(
@@ -235,7 +235,7 @@ canbus_print_child(device_t dev, device_t child)
 }
 
 static device_t
-canbus_add_child(device_t bus, int order, const char *name, int unit)
+canbus_add_child(device_t bus, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct canbus_device *cbdev;
diff --git a/sys/powerpc/aim/nexus.c b/sys/powerpc/aim/nexus.c
index 46e57a525b9..b17de11eccc 100644
--- a/sys/powerpc/aim/nexus.c
+++ b/sys/powerpc/aim/nexus.c
@@ -115,7 +115,7 @@ static int	nexus_attach(device_t);
 /*
  * Bus interface
  */
-static device_t nexus_add_child(device_t, int, const char *, int);
+static device_t nexus_add_child(device_t, u_int, const char *, int);
 static void	nexus_probe_nomatch(device_t, device_t);
 static int	nexus_read_ivar(device_t, device_t, int, uintptr_t *);
 static int	nexus_write_ivar(device_t, device_t, int, uintptr_t);
@@ -262,7 +262,7 @@ nexus_probe_nomatch(device_t dev, device_t child)
 }
 
 static device_t
-nexus_add_child(device_t dev, int order, const char *name, int unit)
+nexus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t child;
 	struct nexus_devinfo *dinfo;
diff --git a/sys/sparc64/sparc64/nexus.c b/sys/sparc64/sparc64/nexus.c
index 192251db30d..4c1379e829e 100644
--- a/sys/sparc64/sparc64/nexus.c
+++ b/sys/sparc64/sparc64/nexus.c
@@ -258,7 +258,7 @@ nexus_attach(device_t dev)
 }
 
 static device_t
-nexus_add_child(device_t dev, int order, const char *name, int unit)
+nexus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t cdev;
 	struct nexus_devinfo *ndi;
diff --git a/sys/sun4v/sun4v/nexus.c b/sys/sun4v/sun4v/nexus.c
index 2156a2306dc..125b2f71242 100644
--- a/sys/sun4v/sun4v/nexus.c
+++ b/sys/sun4v/sun4v/nexus.c
@@ -234,7 +234,7 @@ nexus_attach(device_t dev)
 }
 
 static device_t
-nexus_add_child(device_t dev, int order, const char *name, int unit)
+nexus_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t cdev;
 	struct nexus_devinfo *ndi;
diff --git a/sys/sun4v/sun4v/vnex.c b/sys/sun4v/sun4v/vnex.c
index 305d0bba7b9..d2554ebf4f4 100644
--- a/sys/sun4v/sun4v/vnex.c
+++ b/sys/sun4v/sun4v/vnex.c
@@ -204,7 +204,7 @@ vnex_attach(device_t dev)
 }
 
 static device_t
-vnex_add_child(device_t dev, int order, const char *name, int unit)
+vnex_add_child(device_t dev, u_int order, const char *name, int unit)
 {
 	device_t cdev;
 	struct vnex_devinfo *vndi;
diff --git a/sys/sys/bus.h b/sys/sys/bus.h
index 276ebb013bb..88a0f60cd7e 100644
--- a/sys/sys/bus.h
+++ b/sys/sys/bus.h
@@ -298,7 +298,7 @@ void	root_bus_configure(void);
 int	bus_generic_activate_resource(device_t dev, device_t child, int type,
 				      int rid, struct resource *r);
 device_t
-	bus_generic_add_child(device_t dev, int order, const char *name,
+	bus_generic_add_child(device_t dev, u_int order, const char *name,
 			      int unit);
 struct resource *
 	bus_generic_alloc_resource(device_t bus, device_t child, int type,

From acac60bbfe49dd28c861e63e8c59087d5e3ffef0 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Fri, 10 Sep 2010 12:16:24 +0000
Subject: [PATCH 0611/1624] Don't try to map the USDT probes. This is necessary
 because there is no __SUNW_dof symbol present in FreeBSD binaries.

Sponsored by:	The FreeBSD Foundation
---
 cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c
index 52b0eb94417..b145818db4d 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_pid.c
@@ -641,7 +641,6 @@ dt_pid_create_usdt_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 	assert(DT_MUTEX_HELD(&dpr->dpr_lock));
 #if defined(sun)
 	(void) Pupdate_maps(P);
-#endif
 	if (Pobject_iter(P, dt_pid_usdt_mapping, P) != 0) {
 		ret = -1;
 		(void) dt_pid_error(dtp, pcb, dpr, NULL, D_PROC_USDT,
@@ -652,6 +651,9 @@ dt_pid_create_usdt_probes(dtrace_probedesc_t *pdp, dtrace_hdl_t *dtp,
 		    (int)proc_getpid(P), strerror(errno));
 #endif
 	}
+#else
+	ret = 0;
+#endif
 
 	/*
 	 * Put the module name in its canonical form.

From 9f9ad565a11f61382dd42f596598a327a9fa695c Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Fri, 10 Sep 2010 13:24:47 +0000
Subject: [PATCH 0612/1624] Do not IPI CPU that is already spinning for load.
 It doubles effect of spining (comparing to MWAIT) on some heavly switching
 test loads.

---
 sys/kern/sched_ule.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/sys/kern/sched_ule.c b/sys/kern/sched_ule.c
index 0162b6417d7..bb2d34a37ca 100644
--- a/sys/kern/sched_ule.c
+++ b/sys/kern/sched_ule.c
@@ -196,7 +196,7 @@ static int preempt_thresh = 0;
 #endif
 static int static_boost = PRI_MIN_TIMESHARE;
 static int sched_idlespins = 10000;
-static int sched_idlespinthresh = 4;
+static int sched_idlespinthresh = 64;
 
 /*
  * tdq - per processor runqs and statistics.  All fields are protected by the
@@ -208,6 +208,7 @@ struct tdq {
 	struct mtx	tdq_lock;		/* run queue lock. */
 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
 	volatile int	tdq_load;		/* Aggregate load. */
+	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
 	int		tdq_transferable;	/* Transferable thread count. */
 	short		tdq_switchcnt;		/* Switches this tick. */
@@ -966,7 +967,7 @@ tdq_notify(struct tdq *tdq, struct thread *td)
 		 * If the MD code has an idle wakeup routine try that before
 		 * falling back to IPI.
 		 */
-		if (cpu_idle_wakeup(cpu))
+		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
 			return;
 	}
 	tdq->tdq_ipipending = 1;
@@ -2545,8 +2546,14 @@ sched_idletd(void *dummy)
 			}
 		}
 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
-		if (tdq->tdq_load == 0)
-			cpu_idle(switchcnt > 1);
+		if (tdq->tdq_load == 0) {
+			tdq->tdq_cpu_idle = 1;
+			if (tdq->tdq_load == 0) {
+				cpu_idle(switchcnt > sched_idlespinthresh);
+				tdq->tdq_switchcnt++;
+			}
+			tdq->tdq_cpu_idle = 0;
+		}
 		if (tdq->tdq_load) {
 			thread_lock(td);
 			mi_switch(SW_VOL | SWT_IDLE, NULL);

From 1217a4ead5126d2a841e52a45c37f32493c346bc Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Fri, 10 Sep 2010 13:40:31 +0000
Subject: [PATCH 0613/1624] sh(1): Remove xrefs for expr(1) and getopt(1).

expr(1) should usually not be used as various forms of parameter expansion
and arithmetic expansion replicate most of its functionality in an easier
way.

getopt(1) should not be used at all in new code. Instead, getopts(1) or
entirely manual parsing should be used.

MFC after:	1 week
---
 bin/sh/sh.1 | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/bin/sh/sh.1 b/bin/sh/sh.1
index ff89125c50e..985f0112e44 100644
--- a/bin/sh/sh.1
+++ b/bin/sh/sh.1
@@ -32,7 +32,7 @@
 .\"	from: @(#)sh.1	8.6 (Berkeley) 5/4/95
 .\" $FreeBSD$
 .\"
-.Dd August 22, 2010
+.Dd September 10, 2010
 .Dt SH 1
 .Os
 .Sh NAME
@@ -2455,8 +2455,6 @@ will return the argument.
 .Xr echo 1 ,
 .Xr ed 1 ,
 .Xr emacs 1 ,
-.Xr expr 1 ,
-.Xr getopt 1 ,
 .Xr pwd 1 ,
 .Xr test 1 ,
 .Xr vi 1 ,

From 2f67f12e0409d9c2ea2317e180887d5c43c134a4 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Fri, 10 Sep 2010 14:00:27 +0000
Subject: [PATCH 0614/1624] test(1): Clarify grammar ambiguity and -a/-o vs
 shell &&/||.

---
 bin/test/test.1 | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/bin/test/test.1 b/bin/test/test.1
index 726542da4f1..cbeff94bb6a 100644
--- a/bin/test/test.1
+++ b/bin/test/test.1
@@ -32,7 +32,7 @@
 .\"     @(#)test.1	8.1 (Berkeley) 5/31/93
 .\" $FreeBSD$
 .\"
-.Dd July 31, 2006
+.Dd September 10, 2010
 .Dt TEST 1
 .Os
 .Sh NAME
@@ -310,6 +310,14 @@ are evaluated consistently according to the rules specified in the
 standards document.
 All other cases are subject to the ambiguity in the
 command semantics.
+.Pp
+In particular, only expressions containing
+.Fl a ,
+.Fl o ,
+.Cm \&(
+or
+.Cm \&)
+can be ambiguous.
 .Sh EXIT STATUS
 The
 .Nm
@@ -338,12 +346,11 @@ specification.
 Both sides are always evaluated in
 .Fl a
 and
-.Fl o ,
-unlike in the logical operators of
-.Xr sh 1 .
+.Fl o .
 For instance, the writable status of
 .Pa file
 will be tested by the following command even though the former expression
 indicated false, which results in a gratuitous access to the file system:
-.Pp
 .Dl "[ -z abc -a -w file ]"
+To avoid this, write
+.Dl "[ -z abc ] && [ -w file ]"

From c68e12a6f92c1cbfea4eabf598f2f4cad0106122 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Fri, 10 Sep 2010 14:03:58 +0000
Subject: [PATCH 0615/1624] test(1): Fix markup, ( and ) must be separate
 arguments so leave spaces.

MFC after:	1 week
---
 bin/test/test.1 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/bin/test/test.1 b/bin/test/test.1
index cbeff94bb6a..8cf43d0a405 100644
--- a/bin/test/test.1
+++ b/bin/test/test.1
@@ -282,7 +282,7 @@ True if either
 or
 .Ar expression2
 are true.
-.It Cm \&( Ns Ar expression Ns Cm \&)
+.It Cm \&( Ar expression Cm \&)
 True if expression is true.
 .El
 .Pp

From d3c7b9a08a96d4b6b825881bca54913bc5830881 Mon Sep 17 00:00:00 2001
From: "Kenneth D. Merry" 
Date: Fri, 10 Sep 2010 15:03:56 +0000
Subject: [PATCH 0616/1624] MFp4 (//depot/projects/mps/...)

Bring in a driver for the LSI Logic MPT2 6Gb SAS controllers.

This driver supports basic I/O, and works with SAS and SATA drives and
expanders.

Basic error recovery works (i.e. timeouts and aborts) as well.

Integrated RAID isn't supported yet, and there are some known bugs.

So this isn't ready for production use, but is certainly ready for
testing and additional development.  For the moment, new commits to this
driver should go into the FreeBSD Perforce repository first
(//depot/projects/mps/...) and then get merged into -current once
they've been vetted.

This has only been added to the amd64 GENERIC, since that is the only
architecture I have tested this driver with.

Submitted by:	scottl
Discussed with:	imp, gibbs, will
Sponsored by:	Yahoo, Spectra Logic Corporation
---
 sys/amd64/conf/GENERIC           |    1 +
 sys/conf/files                   |    5 +
 sys/dev/mps/mpi/mpi2.h           | 1121 +++++++++++++
 sys/dev/mps/mpi/mpi2_cnfg.h      | 2646 ++++++++++++++++++++++++++++++
 sys/dev/mps/mpi/mpi2_hbd.h       |  114 ++
 sys/dev/mps/mpi/mpi2_history.txt |  382 +++++
 sys/dev/mps/mpi/mpi2_init.h      |  454 +++++
 sys/dev/mps/mpi/mpi2_ioc.h       | 1414 ++++++++++++++++
 sys/dev/mps/mpi/mpi2_ra.h        |   86 +
 sys/dev/mps/mpi/mpi2_raid.h      |  302 ++++
 sys/dev/mps/mpi/mpi2_sas.h       |  285 ++++
 sys/dev/mps/mpi/mpi2_targ.h      |  441 +++++
 sys/dev/mps/mpi/mpi2_tool.h      |  391 +++++
 sys/dev/mps/mpi/mpi2_type.h      |   99 ++
 sys/dev/mps/mps.c                | 1605 ++++++++++++++++++
 sys/dev/mps/mps_ioctl.h          |  146 ++
 sys/dev/mps/mps_pci.c            |  364 ++++
 sys/dev/mps/mps_sas.c            | 1411 ++++++++++++++++
 sys/dev/mps/mps_table.c          |  493 ++++++
 sys/dev/mps/mps_table.h          |   53 +
 sys/dev/mps/mps_user.c           |  583 +++++++
 sys/dev/mps/mpsvar.h             |  370 +++++
 sys/modules/Makefile             |    1 +
 sys/modules/mps/Makefile         |   13 +
 24 files changed, 12780 insertions(+)
 create mode 100644 sys/dev/mps/mpi/mpi2.h
 create mode 100644 sys/dev/mps/mpi/mpi2_cnfg.h
 create mode 100644 sys/dev/mps/mpi/mpi2_hbd.h
 create mode 100644 sys/dev/mps/mpi/mpi2_history.txt
 create mode 100644 sys/dev/mps/mpi/mpi2_init.h
 create mode 100644 sys/dev/mps/mpi/mpi2_ioc.h
 create mode 100644 sys/dev/mps/mpi/mpi2_ra.h
 create mode 100644 sys/dev/mps/mpi/mpi2_raid.h
 create mode 100644 sys/dev/mps/mpi/mpi2_sas.h
 create mode 100644 sys/dev/mps/mpi/mpi2_targ.h
 create mode 100644 sys/dev/mps/mpi/mpi2_tool.h
 create mode 100644 sys/dev/mps/mpi/mpi2_type.h
 create mode 100644 sys/dev/mps/mps.c
 create mode 100644 sys/dev/mps/mps_ioctl.h
 create mode 100644 sys/dev/mps/mps_pci.c
 create mode 100644 sys/dev/mps/mps_sas.c
 create mode 100644 sys/dev/mps/mps_table.c
 create mode 100644 sys/dev/mps/mps_table.h
 create mode 100644 sys/dev/mps/mps_user.c
 create mode 100644 sys/dev/mps/mpsvar.h
 create mode 100644 sys/modules/mps/Makefile

diff --git a/sys/amd64/conf/GENERIC b/sys/amd64/conf/GENERIC
index e7873e93cd6..fcc7abb0f9b 100644
--- a/sys/amd64/conf/GENERIC
+++ b/sys/amd64/conf/GENERIC
@@ -112,6 +112,7 @@ device		hptiop		# Highpoint RocketRaid 3xxx series
 device		isp		# Qlogic family
 #device		ispfw		# Firmware for QLogic HBAs- normally a module
 device		mpt		# LSI-Logic MPT-Fusion
+device		mps		# LSI-Logic MPT-Fusion 2
 #device		ncr		# NCR/Symbios Logic
 device		sym		# NCR/Symbios Logic (newer chipsets + those of `ncr')
 device		trm		# Tekram DC395U/UW/F DC315U adapters
diff --git a/sys/conf/files b/sys/conf/files
index c3fe2b7c4ed..a08d6bd6ed2 100644
--- a/sys/conf/files
+++ b/sys/conf/files
@@ -1328,6 +1328,11 @@ dev/mmc/mmcbr_if.m		standard
 dev/mmc/mmcbus_if.m		standard
 dev/mmc/mmcsd.c			optional mmcsd
 dev/mn/if_mn.c			optional mn pci
+dev/mps/mps.c			optional mps
+dev/mps/mps_pci.c		optional mps pci
+dev/mps/mps_sas.c		optional mps
+dev/mps/mps_table.c		optional mps
+dev/mps/mps_user.c		optional mps
 dev/mpt/mpt.c			optional mpt
 dev/mpt/mpt_cam.c		optional mpt
 dev/mpt/mpt_debug.c		optional mpt
diff --git a/sys/dev/mps/mpi/mpi2.h b/sys/dev/mps/mpi/mpi2.h
new file mode 100644
index 00000000000..6d883bcdff8
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2.h
@@ -0,0 +1,1121 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2.h
+ *          Title:  MPI Message independent structures and definitions
+ *                  including System Interface Register Set and
+ *                  scatter/gather formats.
+ *  Creation Date:  June 21, 2006
+ *
+ *  mpi2.h Version:  02.00.14
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-04-07  02.00.01  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  06-26-07  02.00.02  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  08-31-07  02.00.03  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Moved ReplyPostHostIndex register to offset 0x6C of the
+ *                      MPI2_SYSTEM_INTERFACE_REGS and modified the define for
+ *                      MPI2_REPLY_POST_HOST_INDEX_OFFSET.
+ *                      Added union of request descriptors.
+ *                      Added union of reply descriptors.
+ *  10-31-07  02.00.04  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Added define for MPI2_VERSION_02_00.
+ *                      Fixed the size of the FunctionDependent5 field in the
+ *                      MPI2_DEFAULT_REPLY structure.
+ *  12-18-07  02.00.05  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Removed the MPI-defined Fault Codes and extended the
+ *                      product specific codes up to 0xEFFF.
+ *                      Added a sixth key value for the WriteSequence register
+ *                      and changed the flush value to 0x0.
+ *                      Added message function codes for Diagnostic Buffer Post
+ *                      and Diagnsotic Release.
+ *                      New IOCStatus define: MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED
+ *                      Moved MPI2_VERSION_UNION from mpi2_ioc.h.
+ *  02-29-08  02.00.06  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  03-03-08  02.00.07  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  05-21-08  02.00.08  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Added #defines for marking a reply descriptor as unused.
+ *  06-27-08  02.00.09  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  10-02-08  02.00.10  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Moved LUN field defines from mpi2_init.h.
+ *  01-19-09  02.00.11  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  05-06-09  02.00.12  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      In all request and reply descriptors, replaced VF_ID
+ *                      field with MSIxIndex field.
+ *                      Removed DevHandle field from
+ *                      MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR and made those
+ *                      bytes reserved.
+ *                      Added RAID Accelerator functionality.
+ *  07-30-09  02.00.13  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  10-28-09  02.00.14  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Added MSI-x index mask and shift for Reply Post Host
+ *                      Index register.
+ *                      Added function code for Host Based Discovery Action.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_H
+#define MPI2_H
+
+
+/*****************************************************************************
+*
+*        MPI Version Definitions
+*
+*****************************************************************************/
+
+#define MPI2_VERSION_MAJOR                  (0x02)
+#define MPI2_VERSION_MINOR                  (0x00)
+#define MPI2_VERSION_MAJOR_MASK             (0xFF00)
+#define MPI2_VERSION_MAJOR_SHIFT            (8)
+#define MPI2_VERSION_MINOR_MASK             (0x00FF)
+#define MPI2_VERSION_MINOR_SHIFT            (0)
+#define MPI2_VERSION ((MPI2_VERSION_MAJOR << MPI2_VERSION_MAJOR_SHIFT) |   \
+                                      MPI2_VERSION_MINOR)
+
+#define MPI2_VERSION_02_00                  (0x0200)
+
+/* versioning for this MPI header set */
+#define MPI2_HEADER_VERSION_UNIT            (0x0E)
+#define MPI2_HEADER_VERSION_DEV             (0x00)
+#define MPI2_HEADER_VERSION_UNIT_MASK       (0xFF00)
+#define MPI2_HEADER_VERSION_UNIT_SHIFT      (8)
+#define MPI2_HEADER_VERSION_DEV_MASK        (0x00FF)
+#define MPI2_HEADER_VERSION_DEV_SHIFT       (0)
+#define MPI2_HEADER_VERSION ((MPI2_HEADER_VERSION_UNIT << 8) | MPI2_HEADER_VERSION_DEV)
+
+
+/*****************************************************************************
+*
+*        IOC State Definitions
+*
+*****************************************************************************/
+
+#define MPI2_IOC_STATE_RESET               (0x00000000)
+#define MPI2_IOC_STATE_READY               (0x10000000)
+#define MPI2_IOC_STATE_OPERATIONAL         (0x20000000)
+#define MPI2_IOC_STATE_FAULT               (0x40000000)
+
+#define MPI2_IOC_STATE_MASK                (0xF0000000)
+#define MPI2_IOC_STATE_SHIFT               (28)
+
+/* Fault state range for prodcut specific codes */
+#define MPI2_FAULT_PRODUCT_SPECIFIC_MIN                 (0x0000)
+#define MPI2_FAULT_PRODUCT_SPECIFIC_MAX                 (0xEFFF)
+
+
+/*****************************************************************************
+*
+*        System Interface Register Definitions
+*
+*****************************************************************************/
+
+typedef volatile struct _MPI2_SYSTEM_INTERFACE_REGS
+{
+    U32         Doorbell;                   /* 0x00 */
+    U32         WriteSequence;              /* 0x04 */
+    U32         HostDiagnostic;             /* 0x08 */
+    U32         Reserved1;                  /* 0x0C */
+    U32         DiagRWData;                 /* 0x10 */
+    U32         DiagRWAddressLow;           /* 0x14 */
+    U32         DiagRWAddressHigh;          /* 0x18 */
+    U32         Reserved2[5];               /* 0x1C */
+    U32         HostInterruptStatus;        /* 0x30 */
+    U32         HostInterruptMask;          /* 0x34 */
+    U32         DCRData;                    /* 0x38 */
+    U32         DCRAddress;                 /* 0x3C */
+    U32         Reserved3[2];               /* 0x40 */
+    U32         ReplyFreeHostIndex;         /* 0x48 */
+    U32         Reserved4[8];               /* 0x4C */
+    U32         ReplyPostHostIndex;         /* 0x6C */
+    U32         Reserved5;                  /* 0x70 */
+    U32         HCBSize;                    /* 0x74 */
+    U32         HCBAddressLow;              /* 0x78 */
+    U32         HCBAddressHigh;             /* 0x7C */
+    U32         Reserved6[16];              /* 0x80 */
+    U32         RequestDescriptorPostLow;   /* 0xC0 */
+    U32         RequestDescriptorPostHigh;  /* 0xC4 */
+    U32         Reserved7[14];              /* 0xC8 */
+} MPI2_SYSTEM_INTERFACE_REGS, MPI2_POINTER PTR_MPI2_SYSTEM_INTERFACE_REGS,
+  Mpi2SystemInterfaceRegs_t, MPI2_POINTER pMpi2SystemInterfaceRegs_t;
+
+/*
+ * Defines for working with the Doorbell register.
+ */
+#define MPI2_DOORBELL_OFFSET                    (0x00000000)
+
+/* IOC --> System values */
+#define MPI2_DOORBELL_USED                      (0x08000000)
+#define MPI2_DOORBELL_WHO_INIT_MASK             (0x07000000)
+#define MPI2_DOORBELL_WHO_INIT_SHIFT            (24)
+#define MPI2_DOORBELL_FAULT_CODE_MASK           (0x0000FFFF)
+#define MPI2_DOORBELL_DATA_MASK                 (0x0000FFFF)
+
+/* System --> IOC values */
+#define MPI2_DOORBELL_FUNCTION_MASK             (0xFF000000)
+#define MPI2_DOORBELL_FUNCTION_SHIFT            (24)
+#define MPI2_DOORBELL_ADD_DWORDS_MASK           (0x00FF0000)
+#define MPI2_DOORBELL_ADD_DWORDS_SHIFT          (16)
+
+
+/*
+ * Defines for the WriteSequence register
+ */
+#define MPI2_WRITE_SEQUENCE_OFFSET              (0x00000004)
+#define MPI2_WRSEQ_KEY_VALUE_MASK               (0x0000000F)
+#define MPI2_WRSEQ_FLUSH_KEY_VALUE              (0x0)
+#define MPI2_WRSEQ_1ST_KEY_VALUE                (0xF)
+#define MPI2_WRSEQ_2ND_KEY_VALUE                (0x4)
+#define MPI2_WRSEQ_3RD_KEY_VALUE                (0xB)
+#define MPI2_WRSEQ_4TH_KEY_VALUE                (0x2)
+#define MPI2_WRSEQ_5TH_KEY_VALUE                (0x7)
+#define MPI2_WRSEQ_6TH_KEY_VALUE                (0xD)
+
+/*
+ * Defines for the HostDiagnostic register
+ */
+#define MPI2_HOST_DIAGNOSTIC_OFFSET             (0x00000008)
+
+#define MPI2_DIAG_BOOT_DEVICE_SELECT_MASK       (0x00001800)
+#define MPI2_DIAG_BOOT_DEVICE_SELECT_DEFAULT    (0x00000000)
+#define MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW       (0x00000800)
+
+#define MPI2_DIAG_CLEAR_FLASH_BAD_SIG           (0x00000400)
+#define MPI2_DIAG_FORCE_HCB_ON_RESET            (0x00000200)
+#define MPI2_DIAG_HCB_MODE                      (0x00000100)
+#define MPI2_DIAG_DIAG_WRITE_ENABLE             (0x00000080)
+#define MPI2_DIAG_FLASH_BAD_SIG                 (0x00000040)
+#define MPI2_DIAG_RESET_HISTORY                 (0x00000020)
+#define MPI2_DIAG_DIAG_RW_ENABLE                (0x00000010)
+#define MPI2_DIAG_RESET_ADAPTER                 (0x00000004)
+#define MPI2_DIAG_HOLD_IOC_RESET                (0x00000002)
+
+/*
+ * Offsets for DiagRWData and address
+ */
+#define MPI2_DIAG_RW_DATA_OFFSET                (0x00000010)
+#define MPI2_DIAG_RW_ADDRESS_LOW_OFFSET         (0x00000014)
+#define MPI2_DIAG_RW_ADDRESS_HIGH_OFFSET        (0x00000018)
+
+/*
+ * Defines for the HostInterruptStatus register
+ */
+#define MPI2_HOST_INTERRUPT_STATUS_OFFSET       (0x00000030)
+#define MPI2_HIS_SYS2IOC_DB_STATUS              (0x80000000)
+#define MPI2_HIS_IOP_DOORBELL_STATUS            MPI2_HIS_SYS2IOC_DB_STATUS
+#define MPI2_HIS_RESET_IRQ_STATUS               (0x40000000)
+#define MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT     (0x00000008)
+#define MPI2_HIS_IOC2SYS_DB_STATUS              (0x00000001)
+#define MPI2_HIS_DOORBELL_INTERRUPT             MPI2_HIS_IOC2SYS_DB_STATUS
+
+/*
+ * Defines for the HostInterruptMask register
+ */
+#define MPI2_HOST_INTERRUPT_MASK_OFFSET         (0x00000034)
+#define MPI2_HIM_RESET_IRQ_MASK                 (0x40000000)
+#define MPI2_HIM_REPLY_INT_MASK                 (0x00000008)
+#define MPI2_HIM_RIM                            MPI2_HIM_REPLY_INT_MASK
+#define MPI2_HIM_IOC2SYS_DB_MASK                (0x00000001)
+#define MPI2_HIM_DIM                            MPI2_HIM_IOC2SYS_DB_MASK
+
+/*
+ * Offsets for DCRData and address
+ */
+#define MPI2_DCR_DATA_OFFSET                    (0x00000038)
+#define MPI2_DCR_ADDRESS_OFFSET                 (0x0000003C)
+
+/*
+ * Offset for the Reply Free Queue
+ */
+#define MPI2_REPLY_FREE_HOST_INDEX_OFFSET       (0x00000048)
+
+/*
+ * Defines for the Reply Descriptor Post Queue
+ */
+#define MPI2_REPLY_POST_HOST_INDEX_OFFSET       (0x0000006C)
+#define MPI2_REPLY_POST_HOST_INDEX_MASK         (0x00FFFFFF)
+#define MPI2_RPHI_MSIX_INDEX_MASK               (0xFF000000)
+#define MPI2_RPHI_MSIX_INDEX_SHIFT              (24)
+
+/*
+ * Defines for the HCBSize and address
+ */
+#define MPI2_HCB_SIZE_OFFSET                    (0x00000074)
+#define MPI2_HCB_SIZE_SIZE_MASK                 (0xFFFFF000)
+#define MPI2_HCB_SIZE_HCB_ENABLE                (0x00000001)
+
+#define MPI2_HCB_ADDRESS_LOW_OFFSET             (0x00000078)
+#define MPI2_HCB_ADDRESS_HIGH_OFFSET            (0x0000007C)
+
+/*
+ * Offsets for the Request Queue
+ */
+#define MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET     (0x000000C0)
+#define MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET    (0x000000C4)
+
+
+/*****************************************************************************
+*
+*        Message Descriptors
+*
+*****************************************************************************/
+
+/* Request Descriptors */
+
+/* Default Request Descriptor */
+typedef struct _MPI2_DEFAULT_REQUEST_DESCRIPTOR
+{
+    U8              RequestFlags;               /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U16             LMID;                       /* 0x04 */
+    U16             DescriptorTypeDependent;    /* 0x06 */
+} MPI2_DEFAULT_REQUEST_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_DEFAULT_REQUEST_DESCRIPTOR,
+  Mpi2DefaultRequestDescriptor_t, MPI2_POINTER pMpi2DefaultRequestDescriptor_t;
+
+/* defines for the RequestFlags field */
+#define MPI2_REQ_DESCRIPT_FLAGS_TYPE_MASK               (0x0E)
+#define MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO                 (0x00)
+#define MPI2_REQ_DESCRIPT_FLAGS_SCSI_TARGET             (0x02)
+#define MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY           (0x06)
+#define MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE            (0x08)
+#define MPI2_REQ_DESCRIPT_FLAGS_RAID_ACCELERATOR        (0x0A)
+
+#define MPI2_REQ_DESCRIPT_FLAGS_IOC_FIFO_MARKER (0x01)
+
+
+/* High Priority Request Descriptor */
+typedef struct _MPI2_HIGH_PRIORITY_REQUEST_DESCRIPTOR
+{
+    U8              RequestFlags;               /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U16             LMID;                       /* 0x04 */
+    U16             Reserved1;                  /* 0x06 */
+} MPI2_HIGH_PRIORITY_REQUEST_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_HIGH_PRIORITY_REQUEST_DESCRIPTOR,
+  Mpi2HighPriorityRequestDescriptor_t,
+  MPI2_POINTER pMpi2HighPriorityRequestDescriptor_t;
+
+
+/* SCSI IO Request Descriptor */
+typedef struct _MPI2_SCSI_IO_REQUEST_DESCRIPTOR
+{
+    U8              RequestFlags;               /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U16             LMID;                       /* 0x04 */
+    U16             DevHandle;                  /* 0x06 */
+} MPI2_SCSI_IO_REQUEST_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_SCSI_IO_REQUEST_DESCRIPTOR,
+  Mpi2SCSIIORequestDescriptor_t, MPI2_POINTER pMpi2SCSIIORequestDescriptor_t;
+
+
+/* SCSI Target Request Descriptor */
+typedef struct _MPI2_SCSI_TARGET_REQUEST_DESCRIPTOR
+{
+    U8              RequestFlags;               /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U16             LMID;                       /* 0x04 */
+    U16             IoIndex;                    /* 0x06 */
+} MPI2_SCSI_TARGET_REQUEST_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_SCSI_TARGET_REQUEST_DESCRIPTOR,
+  Mpi2SCSITargetRequestDescriptor_t,
+  MPI2_POINTER pMpi2SCSITargetRequestDescriptor_t;
+
+
+/* RAID Accelerator Request Descriptor */
+typedef struct _MPI2_RAID_ACCEL_REQUEST_DESCRIPTOR
+{
+    U8              RequestFlags;               /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U16             LMID;                       /* 0x04 */
+    U16             Reserved;                   /* 0x06 */
+} MPI2_RAID_ACCEL_REQUEST_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_RAID_ACCEL_REQUEST_DESCRIPTOR,
+  Mpi2RAIDAcceleratorRequestDescriptor_t,
+  MPI2_POINTER pMpi2RAIDAcceleratorRequestDescriptor_t;
+
+
+/* union of Request Descriptors */
+typedef union _MPI2_REQUEST_DESCRIPTOR_UNION
+{
+    MPI2_DEFAULT_REQUEST_DESCRIPTOR             Default;
+    MPI2_HIGH_PRIORITY_REQUEST_DESCRIPTOR       HighPriority;
+    MPI2_SCSI_IO_REQUEST_DESCRIPTOR             SCSIIO;
+    MPI2_SCSI_TARGET_REQUEST_DESCRIPTOR         SCSITarget;
+    MPI2_RAID_ACCEL_REQUEST_DESCRIPTOR          RAIDAccelerator;
+    U64                                         Words;
+} MPI2_REQUEST_DESCRIPTOR_UNION, MPI2_POINTER PTR_MPI2_REQUEST_DESCRIPTOR_UNION,
+  Mpi2RequestDescriptorUnion_t, MPI2_POINTER pMpi2RequestDescriptorUnion_t;
+
+
+/* Reply Descriptors */
+
+/* Default Reply Descriptor */
+typedef struct _MPI2_DEFAULT_REPLY_DESCRIPTOR
+{
+    U8              ReplyFlags;                 /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             DescriptorTypeDependent1;   /* 0x02 */
+    U32             DescriptorTypeDependent2;   /* 0x04 */
+} MPI2_DEFAULT_REPLY_DESCRIPTOR, MPI2_POINTER PTR_MPI2_DEFAULT_REPLY_DESCRIPTOR,
+  Mpi2DefaultReplyDescriptor_t, MPI2_POINTER pMpi2DefaultReplyDescriptor_t;
+
+/* defines for the ReplyFlags field */
+#define MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK                   (0x0F)
+#define MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS             (0x00)
+#define MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY               (0x01)
+#define MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS        (0x02)
+#define MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER       (0x03)
+#define MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS    (0x05)
+#define MPI2_RPY_DESCRIPT_FLAGS_UNUSED                      (0x0F)
+
+/* values for marking a reply descriptor as unused */
+#define MPI2_RPY_DESCRIPT_UNUSED_WORD0_MARK             (0xFFFFFFFF)
+#define MPI2_RPY_DESCRIPT_UNUSED_WORD1_MARK             (0xFFFFFFFF)
+
+/* Address Reply Descriptor */
+typedef struct _MPI2_ADDRESS_REPLY_DESCRIPTOR
+{
+    U8              ReplyFlags;                 /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U32             ReplyFrameAddress;          /* 0x04 */
+} MPI2_ADDRESS_REPLY_DESCRIPTOR, MPI2_POINTER PTR_MPI2_ADDRESS_REPLY_DESCRIPTOR,
+  Mpi2AddressReplyDescriptor_t, MPI2_POINTER pMpi2AddressReplyDescriptor_t;
+
+#define MPI2_ADDRESS_REPLY_SMID_INVALID                 (0x00)
+
+
+/* SCSI IO Success Reply Descriptor */
+typedef struct _MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR
+{
+    U8              ReplyFlags;                 /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U16             TaskTag;                    /* 0x04 */
+    U16             Reserved1;                  /* 0x06 */
+} MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR,
+  Mpi2SCSIIOSuccessReplyDescriptor_t,
+  MPI2_POINTER pMpi2SCSIIOSuccessReplyDescriptor_t;
+
+
+/* TargetAssist Success Reply Descriptor */
+typedef struct _MPI2_TARGETASSIST_SUCCESS_REPLY_DESCRIPTOR
+{
+    U8              ReplyFlags;                 /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U8              SequenceNumber;             /* 0x04 */
+    U8              Reserved1;                  /* 0x05 */
+    U16             IoIndex;                    /* 0x06 */
+} MPI2_TARGETASSIST_SUCCESS_REPLY_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_TARGETASSIST_SUCCESS_REPLY_DESCRIPTOR,
+  Mpi2TargetAssistSuccessReplyDescriptor_t,
+  MPI2_POINTER pMpi2TargetAssistSuccessReplyDescriptor_t;
+
+
+/* Target Command Buffer Reply Descriptor */
+typedef struct _MPI2_TARGET_COMMAND_BUFFER_REPLY_DESCRIPTOR
+{
+    U8              ReplyFlags;                 /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U8              VP_ID;                      /* 0x02 */
+    U8              Flags;                      /* 0x03 */
+    U16             InitiatorDevHandle;         /* 0x04 */
+    U16             IoIndex;                    /* 0x06 */
+} MPI2_TARGET_COMMAND_BUFFER_REPLY_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_TARGET_COMMAND_BUFFER_REPLY_DESCRIPTOR,
+  Mpi2TargetCommandBufferReplyDescriptor_t,
+  MPI2_POINTER pMpi2TargetCommandBufferReplyDescriptor_t;
+
+/* defines for Flags field */
+#define MPI2_RPY_DESCRIPT_TCB_FLAGS_PHYNUM_MASK     (0x3F)
+
+
+/* RAID Accelerator Success Reply Descriptor */
+typedef struct _MPI2_RAID_ACCELERATOR_SUCCESS_REPLY_DESCRIPTOR
+{
+    U8              ReplyFlags;                 /* 0x00 */
+    U8              MSIxIndex;                  /* 0x01 */
+    U16             SMID;                       /* 0x02 */
+    U32             Reserved;                   /* 0x04 */
+} MPI2_RAID_ACCELERATOR_SUCCESS_REPLY_DESCRIPTOR,
+  MPI2_POINTER PTR_MPI2_RAID_ACCELERATOR_SUCCESS_REPLY_DESCRIPTOR,
+  Mpi2RAIDAcceleratorSuccessReplyDescriptor_t,
+  MPI2_POINTER pMpi2RAIDAcceleratorSuccessReplyDescriptor_t;
+
+
+/* union of Reply Descriptors */
+typedef union _MPI2_REPLY_DESCRIPTORS_UNION
+{
+    MPI2_DEFAULT_REPLY_DESCRIPTOR                   Default;
+    MPI2_ADDRESS_REPLY_DESCRIPTOR                   AddressReply;
+    MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR           SCSIIOSuccess;
+    MPI2_TARGETASSIST_SUCCESS_REPLY_DESCRIPTOR      TargetAssistSuccess;
+    MPI2_TARGET_COMMAND_BUFFER_REPLY_DESCRIPTOR     TargetCommandBuffer;
+    MPI2_RAID_ACCELERATOR_SUCCESS_REPLY_DESCRIPTOR  RAIDAcceleratorSuccess;
+    U64                                             Words;
+} MPI2_REPLY_DESCRIPTORS_UNION, MPI2_POINTER PTR_MPI2_REPLY_DESCRIPTORS_UNION,
+  Mpi2ReplyDescriptorsUnion_t, MPI2_POINTER pMpi2ReplyDescriptorsUnion_t;
+
+
+
+/*****************************************************************************
+*
+*        Message Functions
+*              0x80 -> 0x8F reserved for private message use per product
+*
+*
+*****************************************************************************/
+
+#define MPI2_FUNCTION_SCSI_IO_REQUEST               (0x00) /* SCSI IO */
+#define MPI2_FUNCTION_SCSI_TASK_MGMT                (0x01) /* SCSI Task Management */
+#define MPI2_FUNCTION_IOC_INIT                      (0x02) /* IOC Init */
+#define MPI2_FUNCTION_IOC_FACTS                     (0x03) /* IOC Facts */
+#define MPI2_FUNCTION_CONFIG                        (0x04) /* Configuration */
+#define MPI2_FUNCTION_PORT_FACTS                    (0x05) /* Port Facts */
+#define MPI2_FUNCTION_PORT_ENABLE                   (0x06) /* Port Enable */
+#define MPI2_FUNCTION_EVENT_NOTIFICATION            (0x07) /* Event Notification */
+#define MPI2_FUNCTION_EVENT_ACK                     (0x08) /* Event Acknowledge */
+#define MPI2_FUNCTION_FW_DOWNLOAD                   (0x09) /* FW Download */
+#define MPI2_FUNCTION_TARGET_ASSIST                 (0x0B) /* Target Assist */
+#define MPI2_FUNCTION_TARGET_STATUS_SEND            (0x0C) /* Target Status Send */
+#define MPI2_FUNCTION_TARGET_MODE_ABORT             (0x0D) /* Target Mode Abort */
+#define MPI2_FUNCTION_FW_UPLOAD                     (0x12) /* FW Upload */
+#define MPI2_FUNCTION_RAID_ACTION                   (0x15) /* RAID Action */
+#define MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH      (0x16) /* SCSI IO RAID Passthrough */
+#define MPI2_FUNCTION_TOOLBOX                       (0x17) /* Toolbox */
+#define MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR      (0x18) /* SCSI Enclosure Processor */
+#define MPI2_FUNCTION_SMP_PASSTHROUGH               (0x1A) /* SMP Passthrough */
+#define MPI2_FUNCTION_SAS_IO_UNIT_CONTROL           (0x1B) /* SAS IO Unit Control */
+#define MPI2_FUNCTION_SATA_PASSTHROUGH              (0x1C) /* SATA Passthrough */
+#define MPI2_FUNCTION_DIAG_BUFFER_POST              (0x1D) /* Diagnostic Buffer Post */
+#define MPI2_FUNCTION_DIAG_RELEASE                  (0x1E) /* Diagnostic Release */
+#define MPI2_FUNCTION_TARGET_CMD_BUF_BASE_POST      (0x24) /* Target Command Buffer Post Base */
+#define MPI2_FUNCTION_TARGET_CMD_BUF_LIST_POST      (0x25) /* Target Command Buffer Post List */
+#define MPI2_FUNCTION_RAID_ACCELERATOR              (0x2C) /* RAID Accelerator */
+#define MPI2_FUNCTION_HOST_BASED_DISCOVERY_ACTION   (0x2F) /* Host Based Discovery Action */
+
+
+
+/* Doorbell functions */
+#define MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET        (0x40)
+#define MPI2_FUNCTION_HANDSHAKE                     (0x42)
+
+
+/*****************************************************************************
+*
+*        IOC Status Values
+*
+*****************************************************************************/
+
+/* mask for IOCStatus status value */
+#define MPI2_IOCSTATUS_MASK                     (0x7FFF)
+
+/****************************************************************************
+*  Common IOCStatus values for all replies
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_SUCCESS                      (0x0000)
+#define MPI2_IOCSTATUS_INVALID_FUNCTION             (0x0001)
+#define MPI2_IOCSTATUS_BUSY                         (0x0002)
+#define MPI2_IOCSTATUS_INVALID_SGL                  (0x0003)
+#define MPI2_IOCSTATUS_INTERNAL_ERROR               (0x0004)
+#define MPI2_IOCSTATUS_INVALID_VPID                 (0x0005)
+#define MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES       (0x0006)
+#define MPI2_IOCSTATUS_INVALID_FIELD                (0x0007)
+#define MPI2_IOCSTATUS_INVALID_STATE                (0x0008)
+#define MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED       (0x0009)
+
+/****************************************************************************
+*  Config IOCStatus values
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_CONFIG_INVALID_ACTION        (0x0020)
+#define MPI2_IOCSTATUS_CONFIG_INVALID_TYPE          (0x0021)
+#define MPI2_IOCSTATUS_CONFIG_INVALID_PAGE          (0x0022)
+#define MPI2_IOCSTATUS_CONFIG_INVALID_DATA          (0x0023)
+#define MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS           (0x0024)
+#define MPI2_IOCSTATUS_CONFIG_CANT_COMMIT           (0x0025)
+
+/****************************************************************************
+*  SCSI IO Reply
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR         (0x0040)
+#define MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE       (0x0042)
+#define MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE        (0x0043)
+#define MPI2_IOCSTATUS_SCSI_DATA_OVERRUN            (0x0044)
+#define MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN           (0x0045)
+#define MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR           (0x0046)
+#define MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR          (0x0047)
+#define MPI2_IOCSTATUS_SCSI_TASK_TERMINATED         (0x0048)
+#define MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH       (0x0049)
+#define MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED        (0x004A)
+#define MPI2_IOCSTATUS_SCSI_IOC_TERMINATED          (0x004B)
+#define MPI2_IOCSTATUS_SCSI_EXT_TERMINATED          (0x004C)
+
+/****************************************************************************
+*  For use by SCSI Initiator and SCSI Target end-to-end data protection
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_EEDP_GUARD_ERROR             (0x004D)
+#define MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR           (0x004E)
+#define MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR           (0x004F)
+
+/****************************************************************************
+*  SCSI Target values
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX      (0x0062)
+#define MPI2_IOCSTATUS_TARGET_ABORTED               (0x0063)
+#define MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE     (0x0064)
+#define MPI2_IOCSTATUS_TARGET_NO_CONNECTION         (0x0065)
+#define MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH   (0x006A)
+#define MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR     (0x006D)
+#define MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA   (0x006E)
+#define MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT          (0x006F)
+#define MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT       (0x0070)
+#define MPI2_IOCSTATUS_TARGET_NAK_RECEIVED          (0x0071)
+
+/****************************************************************************
+*  Serial Attached SCSI values
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED       (0x0090)
+#define MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN         (0x0091)
+
+/****************************************************************************
+*  Diagnostic Buffer Post / Diagnostic Release values
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED          (0x00A0)
+
+/****************************************************************************
+*  RAID Accelerator values
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_RAID_ACCEL_ERROR             (0x00B0)
+
+/****************************************************************************
+*  IOCStatus flag to indicate that log info is available
+****************************************************************************/
+
+#define MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE      (0x8000)
+
+/****************************************************************************
+*  IOCLogInfo Types
+****************************************************************************/
+
+#define MPI2_IOCLOGINFO_TYPE_MASK               (0xF0000000)
+#define MPI2_IOCLOGINFO_TYPE_SHIFT              (28)
+#define MPI2_IOCLOGINFO_TYPE_NONE               (0x0)
+#define MPI2_IOCLOGINFO_TYPE_SCSI               (0x1)
+#define MPI2_IOCLOGINFO_TYPE_FC                 (0x2)
+#define MPI2_IOCLOGINFO_TYPE_SAS                (0x3)
+#define MPI2_IOCLOGINFO_TYPE_ISCSI              (0x4)
+#define MPI2_IOCLOGINFO_LOG_DATA_MASK           (0x0FFFFFFF)
+
+
+/*****************************************************************************
+*
+*        Standard Message Structures
+*
+*****************************************************************************/
+
+/****************************************************************************
+* Request Message Header for all request messages
+****************************************************************************/
+
+typedef struct _MPI2_REQUEST_HEADER
+{
+    U16             FunctionDependent1;         /* 0x00 */
+    U8              ChainOffset;                /* 0x02 */
+    U8              Function;                   /* 0x03 */
+    U16             FunctionDependent2;         /* 0x04 */
+    U8              FunctionDependent3;         /* 0x06 */
+    U8              MsgFlags;                   /* 0x07 */
+    U8              VP_ID;                      /* 0x08 */
+    U8              VF_ID;                      /* 0x09 */
+    U16             Reserved1;                  /* 0x0A */
+} MPI2_REQUEST_HEADER, MPI2_POINTER PTR_MPI2_REQUEST_HEADER,
+  MPI2RequestHeader_t, MPI2_POINTER pMPI2RequestHeader_t;
+
+
+/****************************************************************************
+*  Default Reply
+****************************************************************************/
+
+typedef struct _MPI2_DEFAULT_REPLY
+{
+    U16             FunctionDependent1;         /* 0x00 */
+    U8              MsgLength;                  /* 0x02 */
+    U8              Function;                   /* 0x03 */
+    U16             FunctionDependent2;         /* 0x04 */
+    U8              FunctionDependent3;         /* 0x06 */
+    U8              MsgFlags;                   /* 0x07 */
+    U8              VP_ID;                      /* 0x08 */
+    U8              VF_ID;                      /* 0x09 */
+    U16             Reserved1;                  /* 0x0A */
+    U16             FunctionDependent5;         /* 0x0C */
+    U16             IOCStatus;                  /* 0x0E */
+    U32             IOCLogInfo;                 /* 0x10 */
+} MPI2_DEFAULT_REPLY, MPI2_POINTER PTR_MPI2_DEFAULT_REPLY,
+  MPI2DefaultReply_t, MPI2_POINTER pMPI2DefaultReply_t;
+
+
+/* common version structure/union used in messages and configuration pages */
+
+typedef struct _MPI2_VERSION_STRUCT
+{
+    U8                      Dev;                        /* 0x00 */
+    U8                      Unit;                       /* 0x01 */
+    U8                      Minor;                      /* 0x02 */
+    U8                      Major;                      /* 0x03 */
+} MPI2_VERSION_STRUCT;
+
+typedef union _MPI2_VERSION_UNION
+{
+    MPI2_VERSION_STRUCT     Struct;
+    U32                     Word;
+} MPI2_VERSION_UNION;
+
+
+/* LUN field defines, common to many structures */
+#define MPI2_LUN_FIRST_LEVEL_ADDRESSING             (0x0000FFFF)
+#define MPI2_LUN_SECOND_LEVEL_ADDRESSING            (0xFFFF0000)
+#define MPI2_LUN_THIRD_LEVEL_ADDRESSING             (0x0000FFFF)
+#define MPI2_LUN_FOURTH_LEVEL_ADDRESSING            (0xFFFF0000)
+#define MPI2_LUN_LEVEL_1_WORD                       (0xFF00)
+#define MPI2_LUN_LEVEL_1_DWORD                      (0x0000FF00)
+
+
+/*****************************************************************************
+*
+*        Fusion-MPT MPI Scatter Gather Elements
+*
+*****************************************************************************/
+
+/****************************************************************************
+*  MPI Simple Element structures
+****************************************************************************/
+
+typedef struct _MPI2_SGE_SIMPLE32
+{
+    U32                     FlagsLength;
+    U32                     Address;
+} MPI2_SGE_SIMPLE32, MPI2_POINTER PTR_MPI2_SGE_SIMPLE32,
+  Mpi2SGESimple32_t, MPI2_POINTER pMpi2SGESimple32_t;
+
+typedef struct _MPI2_SGE_SIMPLE64
+{
+    U32                     FlagsLength;
+    U64                     Address;
+} MPI2_SGE_SIMPLE64, MPI2_POINTER PTR_MPI2_SGE_SIMPLE64,
+  Mpi2SGESimple64_t, MPI2_POINTER pMpi2SGESimple64_t;
+
+typedef struct _MPI2_SGE_SIMPLE_UNION
+{
+    U32                     FlagsLength;
+    union
+    {
+        U32                 Address32;
+        U64                 Address64;
+    } u;
+} MPI2_SGE_SIMPLE_UNION, MPI2_POINTER PTR_MPI2_SGE_SIMPLE_UNION,
+  Mpi2SGESimpleUnion_t, MPI2_POINTER pMpi2SGESimpleUnion_t;
+
+
+/****************************************************************************
+*  MPI Chain Element structures
+****************************************************************************/
+
+typedef struct _MPI2_SGE_CHAIN32
+{
+    U16                     Length;
+    U8                      NextChainOffset;
+    U8                      Flags;
+    U32                     Address;
+} MPI2_SGE_CHAIN32, MPI2_POINTER PTR_MPI2_SGE_CHAIN32,
+  Mpi2SGEChain32_t, MPI2_POINTER pMpi2SGEChain32_t;
+
+typedef struct _MPI2_SGE_CHAIN64
+{
+    U16                     Length;
+    U8                      NextChainOffset;
+    U8                      Flags;
+    U64                     Address;
+} MPI2_SGE_CHAIN64, MPI2_POINTER PTR_MPI2_SGE_CHAIN64,
+  Mpi2SGEChain64_t, MPI2_POINTER pMpi2SGEChain64_t;
+
+typedef struct _MPI2_SGE_CHAIN_UNION
+{
+    U16                     Length;
+    U8                      NextChainOffset;
+    U8                      Flags;
+    union
+    {
+        U32                 Address32;
+        U64                 Address64;
+    } u;
+} MPI2_SGE_CHAIN_UNION, MPI2_POINTER PTR_MPI2_SGE_CHAIN_UNION,
+  Mpi2SGEChainUnion_t, MPI2_POINTER pMpi2SGEChainUnion_t;
+
+
+/****************************************************************************
+*  MPI Transaction Context Element structures
+****************************************************************************/
+
+typedef struct _MPI2_SGE_TRANSACTION32
+{
+    U8                      Reserved;
+    U8                      ContextSize;
+    U8                      DetailsLength;
+    U8                      Flags;
+    U32                     TransactionContext[1];
+    U32                     TransactionDetails[1];
+} MPI2_SGE_TRANSACTION32, MPI2_POINTER PTR_MPI2_SGE_TRANSACTION32,
+  Mpi2SGETransaction32_t, MPI2_POINTER pMpi2SGETransaction32_t;
+
+typedef struct _MPI2_SGE_TRANSACTION64
+{
+    U8                      Reserved;
+    U8                      ContextSize;
+    U8                      DetailsLength;
+    U8                      Flags;
+    U32                     TransactionContext[2];
+    U32                     TransactionDetails[1];
+} MPI2_SGE_TRANSACTION64, MPI2_POINTER PTR_MPI2_SGE_TRANSACTION64,
+  Mpi2SGETransaction64_t, MPI2_POINTER pMpi2SGETransaction64_t;
+
+typedef struct _MPI2_SGE_TRANSACTION96
+{
+    U8                      Reserved;
+    U8                      ContextSize;
+    U8                      DetailsLength;
+    U8                      Flags;
+    U32                     TransactionContext[3];
+    U32                     TransactionDetails[1];
+} MPI2_SGE_TRANSACTION96, MPI2_POINTER PTR_MPI2_SGE_TRANSACTION96,
+  Mpi2SGETransaction96_t, MPI2_POINTER pMpi2SGETransaction96_t;
+
+typedef struct _MPI2_SGE_TRANSACTION128
+{
+    U8                      Reserved;
+    U8                      ContextSize;
+    U8                      DetailsLength;
+    U8                      Flags;
+    U32                     TransactionContext[4];
+    U32                     TransactionDetails[1];
+} MPI2_SGE_TRANSACTION128, MPI2_POINTER PTR_MPI2_SGE_TRANSACTION128,
+  Mpi2SGETransaction_t128, MPI2_POINTER pMpi2SGETransaction_t128;
+
+typedef struct _MPI2_SGE_TRANSACTION_UNION
+{
+    U8                      Reserved;
+    U8                      ContextSize;
+    U8                      DetailsLength;
+    U8                      Flags;
+    union
+    {
+        U32                 TransactionContext32[1];
+        U32                 TransactionContext64[2];
+        U32                 TransactionContext96[3];
+        U32                 TransactionContext128[4];
+    } u;
+    U32                     TransactionDetails[1];
+} MPI2_SGE_TRANSACTION_UNION, MPI2_POINTER PTR_MPI2_SGE_TRANSACTION_UNION,
+  Mpi2SGETransactionUnion_t, MPI2_POINTER pMpi2SGETransactionUnion_t;
+
+
+/****************************************************************************
+*  MPI SGE union for IO SGL's
+****************************************************************************/
+
+typedef struct _MPI2_MPI_SGE_IO_UNION
+{
+    union
+    {
+        MPI2_SGE_SIMPLE_UNION   Simple;
+        MPI2_SGE_CHAIN_UNION    Chain;
+    } u;
+} MPI2_MPI_SGE_IO_UNION, MPI2_POINTER PTR_MPI2_MPI_SGE_IO_UNION,
+  Mpi2MpiSGEIOUnion_t, MPI2_POINTER pMpi2MpiSGEIOUnion_t;
+
+
+/****************************************************************************
+*  MPI SGE union for SGL's with Simple and Transaction elements
+****************************************************************************/
+
+typedef struct _MPI2_SGE_TRANS_SIMPLE_UNION
+{
+    union
+    {
+        MPI2_SGE_SIMPLE_UNION       Simple;
+        MPI2_SGE_TRANSACTION_UNION  Transaction;
+    } u;
+} MPI2_SGE_TRANS_SIMPLE_UNION, MPI2_POINTER PTR_MPI2_SGE_TRANS_SIMPLE_UNION,
+  Mpi2SGETransSimpleUnion_t, MPI2_POINTER pMpi2SGETransSimpleUnion_t;
+
+
+/****************************************************************************
+*  All MPI SGE types union
+****************************************************************************/
+
+typedef struct _MPI2_MPI_SGE_UNION
+{
+    union
+    {
+        MPI2_SGE_SIMPLE_UNION       Simple;
+        MPI2_SGE_CHAIN_UNION        Chain;
+        MPI2_SGE_TRANSACTION_UNION  Transaction;
+    } u;
+} MPI2_MPI_SGE_UNION, MPI2_POINTER PTR_MPI2_MPI_SGE_UNION,
+  Mpi2MpiSgeUnion_t, MPI2_POINTER pMpi2MpiSgeUnion_t;
+
+
+/****************************************************************************
+*  MPI SGE field definition and masks
+****************************************************************************/
+
+/* Flags field bit definitions */
+
+#define MPI2_SGE_FLAGS_LAST_ELEMENT             (0x80)
+#define MPI2_SGE_FLAGS_END_OF_BUFFER            (0x40)
+#define MPI2_SGE_FLAGS_ELEMENT_TYPE_MASK        (0x30)
+#define MPI2_SGE_FLAGS_LOCAL_ADDRESS            (0x08)
+#define MPI2_SGE_FLAGS_DIRECTION                (0x04)
+#define MPI2_SGE_FLAGS_ADDRESS_SIZE             (0x02)
+#define MPI2_SGE_FLAGS_END_OF_LIST              (0x01)
+
+#define MPI2_SGE_FLAGS_SHIFT                    (24)
+
+#define MPI2_SGE_LENGTH_MASK                    (0x00FFFFFF)
+#define MPI2_SGE_CHAIN_LENGTH_MASK              (0x0000FFFF)
+
+/* Element Type */
+
+#define MPI2_SGE_FLAGS_TRANSACTION_ELEMENT      (0x00)
+#define MPI2_SGE_FLAGS_SIMPLE_ELEMENT           (0x10)
+#define MPI2_SGE_FLAGS_CHAIN_ELEMENT            (0x30)
+#define MPI2_SGE_FLAGS_ELEMENT_MASK             (0x30)
+
+/* Address location */
+
+#define MPI2_SGE_FLAGS_SYSTEM_ADDRESS           (0x00)
+
+/* Direction */
+
+#define MPI2_SGE_FLAGS_IOC_TO_HOST              (0x00)
+#define MPI2_SGE_FLAGS_HOST_TO_IOC              (0x04)
+
+/* Address Size */
+
+#define MPI2_SGE_FLAGS_32_BIT_ADDRESSING        (0x00)
+#define MPI2_SGE_FLAGS_64_BIT_ADDRESSING        (0x02)
+
+/* Context Size */
+
+#define MPI2_SGE_FLAGS_32_BIT_CONTEXT           (0x00)
+#define MPI2_SGE_FLAGS_64_BIT_CONTEXT           (0x02)
+#define MPI2_SGE_FLAGS_96_BIT_CONTEXT           (0x04)
+#define MPI2_SGE_FLAGS_128_BIT_CONTEXT          (0x06)
+
+#define MPI2_SGE_CHAIN_OFFSET_MASK              (0x00FF0000)
+#define MPI2_SGE_CHAIN_OFFSET_SHIFT             (16)
+
+/****************************************************************************
+*  MPI SGE operation Macros
+****************************************************************************/
+
+/* SIMPLE FlagsLength manipulations... */
+#define MPI2_SGE_SET_FLAGS(f)          ((U32)(f) << MPI2_SGE_FLAGS_SHIFT)
+#define MPI2_SGE_GET_FLAGS(f)          (((f) & ~MPI2_SGE_LENGTH_MASK) >> MPI2_SGE_FLAGS_SHIFT)
+#define MPI2_SGE_LENGTH(f)             ((f) & MPI2_SGE_LENGTH_MASK)
+#define MPI2_SGE_CHAIN_LENGTH(f)       ((f) & MPI2_SGE_CHAIN_LENGTH_MASK)
+
+#define MPI2_SGE_SET_FLAGS_LENGTH(f,l) (MPI2_SGE_SET_FLAGS(f) | MPI2_SGE_LENGTH(l))
+
+#define MPI2_pSGE_GET_FLAGS(psg)            MPI2_SGE_GET_FLAGS((psg)->FlagsLength)
+#define MPI2_pSGE_GET_LENGTH(psg)           MPI2_SGE_LENGTH((psg)->FlagsLength)
+#define MPI2_pSGE_SET_FLAGS_LENGTH(psg,f,l) (psg)->FlagsLength = MPI2_SGE_SET_FLAGS_LENGTH(f,l)
+
+/* CAUTION - The following are READ-MODIFY-WRITE! */
+#define MPI2_pSGE_SET_FLAGS(psg,f)      (psg)->FlagsLength |= MPI2_SGE_SET_FLAGS(f)
+#define MPI2_pSGE_SET_LENGTH(psg,l)     (psg)->FlagsLength |= MPI2_SGE_LENGTH(l)
+
+#define MPI2_GET_CHAIN_OFFSET(x)    ((x & MPI2_SGE_CHAIN_OFFSET_MASK) >> MPI2_SGE_CHAIN_OFFSET_SHIFT)
+
+
+/*****************************************************************************
+*
+*        Fusion-MPT IEEE Scatter Gather Elements
+*
+*****************************************************************************/
+
+/****************************************************************************
+*  IEEE Simple Element structures
+****************************************************************************/
+
+typedef struct _MPI2_IEEE_SGE_SIMPLE32
+{
+    U32                     Address;
+    U32                     FlagsLength;
+} MPI2_IEEE_SGE_SIMPLE32, MPI2_POINTER PTR_MPI2_IEEE_SGE_SIMPLE32,
+  Mpi2IeeeSgeSimple32_t, MPI2_POINTER pMpi2IeeeSgeSimple32_t;
+
+typedef struct _MPI2_IEEE_SGE_SIMPLE64
+{
+    U64                     Address;
+    U32                     Length;
+    U16                     Reserved1;
+    U8                      Reserved2;
+    U8                      Flags;
+} MPI2_IEEE_SGE_SIMPLE64, MPI2_POINTER PTR_MPI2_IEEE_SGE_SIMPLE64,
+  Mpi2IeeeSgeSimple64_t, MPI2_POINTER pMpi2IeeeSgeSimple64_t;
+
+typedef union _MPI2_IEEE_SGE_SIMPLE_UNION
+{
+    MPI2_IEEE_SGE_SIMPLE32  Simple32;
+    MPI2_IEEE_SGE_SIMPLE64  Simple64;
+} MPI2_IEEE_SGE_SIMPLE_UNION, MPI2_POINTER PTR_MPI2_IEEE_SGE_SIMPLE_UNION,
+  Mpi2IeeeSgeSimpleUnion_t, MPI2_POINTER pMpi2IeeeSgeSimpleUnion_t;
+
+
+/****************************************************************************
+*  IEEE Chain Element structures
+****************************************************************************/
+
+typedef MPI2_IEEE_SGE_SIMPLE32  MPI2_IEEE_SGE_CHAIN32;
+
+typedef MPI2_IEEE_SGE_SIMPLE64  MPI2_IEEE_SGE_CHAIN64;
+
+typedef union _MPI2_IEEE_SGE_CHAIN_UNION
+{
+    MPI2_IEEE_SGE_CHAIN32   Chain32;
+    MPI2_IEEE_SGE_CHAIN64   Chain64;
+} MPI2_IEEE_SGE_CHAIN_UNION, MPI2_POINTER PTR_MPI2_IEEE_SGE_CHAIN_UNION,
+  Mpi2IeeeSgeChainUnion_t, MPI2_POINTER pMpi2IeeeSgeChainUnion_t;
+
+
+/****************************************************************************
+*  All IEEE SGE types union
+****************************************************************************/
+
+typedef struct _MPI2_IEEE_SGE_UNION
+{
+    union
+    {
+        MPI2_IEEE_SGE_SIMPLE_UNION  Simple;
+        MPI2_IEEE_SGE_CHAIN_UNION   Chain;
+    } u;
+} MPI2_IEEE_SGE_UNION, MPI2_POINTER PTR_MPI2_IEEE_SGE_UNION,
+  Mpi2IeeeSgeUnion_t, MPI2_POINTER pMpi2IeeeSgeUnion_t;
+
+
+/****************************************************************************
+*  IEEE SGE field definitions and masks
+****************************************************************************/
+
+/* Flags field bit definitions */
+
+#define MPI2_IEEE_SGE_FLAGS_ELEMENT_TYPE_MASK   (0x80)
+
+#define MPI2_IEEE32_SGE_FLAGS_SHIFT             (24)
+
+#define MPI2_IEEE32_SGE_LENGTH_MASK             (0x00FFFFFF)
+
+/* Element Type */
+
+#define MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT      (0x00)
+#define MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT       (0x80)
+
+/* Data Location Address Space */
+
+#define MPI2_IEEE_SGE_FLAGS_ADDR_MASK           (0x03)
+#define MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR         (0x00)
+#define MPI2_IEEE_SGE_FLAGS_IOCDDR_ADDR         (0x01)
+#define MPI2_IEEE_SGE_FLAGS_IOCPLB_ADDR         (0x02)
+#define MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR      (0x03)
+
+
+/****************************************************************************
+*  IEEE SGE operation Macros
+****************************************************************************/
+
+/* SIMPLE FlagsLength manipulations... */
+#define MPI2_IEEE32_SGE_SET_FLAGS(f)     ((U32)(f) << MPI2_IEEE32_SGE_FLAGS_SHIFT)
+#define MPI2_IEEE32_SGE_GET_FLAGS(f)     (((f) & ~MPI2_IEEE32_SGE_LENGTH_MASK) >> MPI2_IEEE32_SGE_FLAGS_SHIFT)
+#define MPI2_IEEE32_SGE_LENGTH(f)        ((f) & MPI2_IEEE32_SGE_LENGTH_MASK)
+
+#define MPI2_IEEE32_SGE_SET_FLAGS_LENGTH(f, l)      (MPI2_IEEE32_SGE_SET_FLAGS(f) | MPI2_IEEE32_SGE_LENGTH(l))
+
+#define MPI2_IEEE32_pSGE_GET_FLAGS(psg)             MPI2_IEEE32_SGE_GET_FLAGS((psg)->FlagsLength)
+#define MPI2_IEEE32_pSGE_GET_LENGTH(psg)            MPI2_IEEE32_SGE_LENGTH((psg)->FlagsLength)
+#define MPI2_IEEE32_pSGE_SET_FLAGS_LENGTH(psg,f,l)  (psg)->FlagsLength = MPI2_IEEE32_SGE_SET_FLAGS_LENGTH(f,l)
+
+/* CAUTION - The following are READ-MODIFY-WRITE! */
+#define MPI2_IEEE32_pSGE_SET_FLAGS(psg,f)    (psg)->FlagsLength |= MPI2_IEEE32_SGE_SET_FLAGS(f)
+#define MPI2_IEEE32_pSGE_SET_LENGTH(psg,l)   (psg)->FlagsLength |= MPI2_IEEE32_SGE_LENGTH(l)
+
+
+
+
+/*****************************************************************************
+*
+*        Fusion-MPT MPI/IEEE Scatter Gather Unions
+*
+*****************************************************************************/
+
+typedef union _MPI2_SIMPLE_SGE_UNION
+{
+    MPI2_SGE_SIMPLE_UNION       MpiSimple;
+    MPI2_IEEE_SGE_SIMPLE_UNION  IeeeSimple;
+} MPI2_SIMPLE_SGE_UNION, MPI2_POINTER PTR_MPI2_SIMPLE_SGE_UNION,
+  Mpi2SimpleSgeUntion_t, MPI2_POINTER pMpi2SimpleSgeUntion_t;
+
+
+typedef union _MPI2_SGE_IO_UNION
+{
+    MPI2_SGE_SIMPLE_UNION       MpiSimple;
+    MPI2_SGE_CHAIN_UNION        MpiChain;
+    MPI2_IEEE_SGE_SIMPLE_UNION  IeeeSimple;
+    MPI2_IEEE_SGE_CHAIN_UNION   IeeeChain;
+} MPI2_SGE_IO_UNION, MPI2_POINTER PTR_MPI2_SGE_IO_UNION,
+  Mpi2SGEIOUnion_t, MPI2_POINTER pMpi2SGEIOUnion_t;
+
+
+/****************************************************************************
+*
+*  Values for SGLFlags field, used in many request messages with an SGL
+*
+****************************************************************************/
+
+/* values for MPI SGL Data Location Address Space subfield */
+#define MPI2_SGLFLAGS_ADDRESS_SPACE_MASK            (0x0C)
+#define MPI2_SGLFLAGS_SYSTEM_ADDRESS_SPACE          (0x00)
+#define MPI2_SGLFLAGS_IOCDDR_ADDRESS_SPACE          (0x04)
+#define MPI2_SGLFLAGS_IOCPLB_ADDRESS_SPACE          (0x08)
+#define MPI2_SGLFLAGS_IOCPLBNTA_ADDRESS_SPACE       (0x0C)
+/* values for SGL Type subfield */
+#define MPI2_SGLFLAGS_SGL_TYPE_MASK                 (0x03)
+#define MPI2_SGLFLAGS_SGL_TYPE_MPI                  (0x00)
+#define MPI2_SGLFLAGS_SGL_TYPE_IEEE32               (0x01)
+#define MPI2_SGLFLAGS_SGL_TYPE_IEEE64               (0x02)
+
+
+#endif
+
diff --git a/sys/dev/mps/mpi/mpi2_cnfg.h b/sys/dev/mps/mpi/mpi2_cnfg.h
new file mode 100644
index 00000000000..78f26f1a396
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_cnfg.h
@@ -0,0 +1,2646 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_cnfg.h
+ *          Title:  MPI Configuration messages and pages
+ *  Creation Date:  November 10, 2006
+ *
+ *    mpi2_cnfg.h Version:  02.00.13
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-04-07  02.00.01  Added defines for SAS IO Unit Page 2 PhyFlags.
+ *                      Added Manufacturing Page 11.
+ *                      Added MPI2_SAS_EXPANDER0_FLAGS_CONNECTOR_END_DEVICE
+ *                      define.
+ *  06-26-07  02.00.02  Adding generic structure for product-specific
+ *                      Manufacturing pages: MPI2_CONFIG_PAGE_MANUFACTURING_PS.
+ *                      Rework of BIOS Page 2 configuration page.
+ *                      Fixed MPI2_BIOSPAGE2_BOOT_DEVICE to be a union of the
+ *                      forms.
+ *                      Added configuration pages IOC Page 8 and Driver
+ *                      Persistent Mapping Page 0.
+ *  08-31-07  02.00.03  Modified configuration pages dealing with Integrated
+ *                      RAID (Manufacturing Page 4, RAID Volume Pages 0 and 1,
+ *                      RAID Physical Disk Pages 0 and 1, RAID Configuration
+ *                      Page 0).
+ *                      Added new value for AccessStatus field of SAS Device
+ *                      Page 0 (_SATA_NEEDS_INITIALIZATION).
+ *  10-31-07  02.00.04  Added missing SEPDevHandle field to
+ *                      MPI2_CONFIG_PAGE_SAS_ENCLOSURE_0.
+ *  12-18-07  02.00.05  Modified IO Unit Page 0 to use 32-bit version fields for
+ *                      NVDATA.
+ *                      Modified IOC Page 7 to use masks and added field for
+ *                      SASBroadcastPrimitiveMasks.
+ *                      Added MPI2_CONFIG_PAGE_BIOS_4.
+ *                      Added MPI2_CONFIG_PAGE_LOG_0.
+ *  02-29-08  02.00.06  Modified various names to make them 32-character unique.
+ *                      Added SAS Device IDs.
+ *                      Updated Integrated RAID configuration pages including
+ *                      Manufacturing Page 4, IOC Page 6, and RAID Configuration
+ *                      Page 0.
+ *  05-21-08  02.00.07  Added define MPI2_MANPAGE4_MIX_SSD_SAS_SATA.
+ *                      Added define MPI2_MANPAGE4_PHYSDISK_128MB_COERCION.
+ *                      Fixed define MPI2_IOCPAGE8_FLAGS_ENCLOSURE_SLOT_MAPPING.
+ *                      Added missing MaxNumRoutedSasAddresses field to
+ *                      MPI2_CONFIG_PAGE_EXPANDER_0.
+ *                      Added SAS Port Page 0.
+ *                      Modified structure layout for
+ *                      MPI2_CONFIG_PAGE_DRIVER_MAPPING_0.
+ *  06-27-08  02.00.08  Changed MPI2_CONFIG_PAGE_RD_PDISK_1 to use
+ *                      MPI2_RAID_PHYS_DISK1_PATH_MAX to size the array.
+ *  10-02-08  02.00.09  Changed MPI2_RAID_PGAD_CONFIGNUM_MASK from 0x0000FFFF
+ *                      to 0x000000FF.
+ *                      Added two new values for the Physical Disk Coercion Size
+ *                      bits in the Flags field of Manufacturing Page 4.
+ *                      Added product-specific Manufacturing pages 16 to 31.
+ *                      Modified Flags bits for controlling write cache on SATA
+ *                      drives in IO Unit Page 1.
+ *                      Added new bit to AdditionalControlFlags of SAS IO Unit
+ *                      Page 1 to control Invalid Topology Correction.
+ *                      Added additional defines for RAID Volume Page 0
+ *                      VolumeStatusFlags field.
+ *                      Modified meaning of RAID Volume Page 0 VolumeSettings
+ *                      define for auto-configure of hot-swap drives.
+ *                      Added SupportedPhysDisks field to RAID Volume Page 1 and
+ *                      added related defines.
+ *                      Added PhysDiskAttributes field (and related defines) to
+ *                      RAID Physical Disk Page 0.
+ *                      Added MPI2_SAS_PHYINFO_PHY_VACANT define.
+ *                      Added three new DiscoveryStatus bits for SAS IO Unit
+ *                      Page 0 and SAS Expander Page 0.
+ *                      Removed multiplexing information from SAS IO Unit pages.
+ *                      Added BootDeviceWaitTime field to SAS IO Unit Page 4.
+ *                      Removed Zone Address Resolved bit from PhyInfo and from
+ *                      Expander Page 0 Flags field.
+ *                      Added two new AccessStatus values to SAS Device Page 0
+ *                      for indicating routing problems. Added 3 reserved words
+ *                      to this page.
+ *  01-19-09  02.00.10  Fixed defines for GPIOVal field of IO Unit Page 3.
+ *                      Inserted missing reserved field into structure for IOC
+ *                      Page 6.
+ *                      Added more pending task bits to RAID Volume Page 0
+ *                      VolumeStatusFlags defines.
+ *                      Added MPI2_PHYSDISK0_STATUS_FLAG_NOT_CERTIFIED define.
+ *                      Added a new DiscoveryStatus bit for SAS IO Unit Page 0
+ *                      and SAS Expander Page 0 to flag a downstream initiator
+ *                      when in simplified routing mode.
+ *                      Removed SATA Init Failure defines for DiscoveryStatus
+ *                      fields of SAS IO Unit Page 0 and SAS Expander Page 0.
+ *                      Added MPI2_SAS_DEVICE0_ASTATUS_DEVICE_BLOCKED define.
+ *                      Added PortGroups, DmaGroup, and ControlGroup fields to
+ *                      SAS Device Page 0.
+ *  05-06-09  02.00.11  Added structures and defines for IO Unit Page 5 and IO
+ *                      Unit Page 6.
+ *                      Added expander reduced functionality data to SAS
+ *                      Expander Page 0.
+ *                      Added SAS PHY Page 2 and SAS PHY Page 3.
+ *  07-30-09  02.00.12  Added IO Unit Page 7.
+ *                      Added new device ids.
+ *                      Added SAS IO Unit Page 5.
+ *                      Added partial and slumber power management capable flags
+ *                      to SAS Device Page 0 Flags field.
+ *                      Added PhyInfo defines for power condition.
+ *                      Added Ethernet configuration pages.
+ *  10-28-09  02.00.13  Added MPI2_IOUNITPAGE1_ENABLE_HOST_BASED_DISCOVERY.
+ *                      Added SAS PHY Page 4 structure and defines.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_CNFG_H
+#define MPI2_CNFG_H
+
+/*****************************************************************************
+*   Configuration Page Header and defines
+*****************************************************************************/
+
+/* Config Page Header */
+typedef struct _MPI2_CONFIG_PAGE_HEADER
+{
+    U8                 PageVersion;                /* 0x00 */
+    U8                 PageLength;                 /* 0x01 */
+    U8                 PageNumber;                 /* 0x02 */
+    U8                 PageType;                   /* 0x03 */
+} MPI2_CONFIG_PAGE_HEADER, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_HEADER,
+  Mpi2ConfigPageHeader_t, MPI2_POINTER pMpi2ConfigPageHeader_t;
+
+typedef union _MPI2_CONFIG_PAGE_HEADER_UNION
+{
+   MPI2_CONFIG_PAGE_HEADER  Struct;
+   U8                       Bytes[4];
+   U16                      Word16[2];
+   U32                      Word32;
+} MPI2_CONFIG_PAGE_HEADER_UNION, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_HEADER_UNION,
+  Mpi2ConfigPageHeaderUnion, MPI2_POINTER pMpi2ConfigPageHeaderUnion;
+
+/* Extended Config Page Header */
+typedef struct _MPI2_CONFIG_EXTENDED_PAGE_HEADER
+{
+    U8                  PageVersion;                /* 0x00 */
+    U8                  Reserved1;                  /* 0x01 */
+    U8                  PageNumber;                 /* 0x02 */
+    U8                  PageType;                   /* 0x03 */
+    U16                 ExtPageLength;              /* 0x04 */
+    U8                  ExtPageType;                /* 0x06 */
+    U8                  Reserved2;                  /* 0x07 */
+} MPI2_CONFIG_EXTENDED_PAGE_HEADER,
+  MPI2_POINTER PTR_MPI2_CONFIG_EXTENDED_PAGE_HEADER,
+  Mpi2ConfigExtendedPageHeader_t, MPI2_POINTER pMpi2ConfigExtendedPageHeader_t;
+
+typedef union _MPI2_CONFIG_EXT_PAGE_HEADER_UNION
+{
+   MPI2_CONFIG_PAGE_HEADER          Struct;
+   MPI2_CONFIG_EXTENDED_PAGE_HEADER Ext;
+   U8                               Bytes[8];
+   U16                              Word16[4];
+   U32                              Word32[2];
+} MPI2_CONFIG_EXT_PAGE_HEADER_UNION, MPI2_POINTER PTR_MPI2_CONFIG_EXT_PAGE_HEADER_UNION,
+  Mpi2ConfigPageExtendedHeaderUnion, MPI2_POINTER pMpi2ConfigPageExtendedHeaderUnion;
+
+
+/* PageType field values */
+#define MPI2_CONFIG_PAGEATTR_READ_ONLY              (0x00)
+#define MPI2_CONFIG_PAGEATTR_CHANGEABLE             (0x10)
+#define MPI2_CONFIG_PAGEATTR_PERSISTENT             (0x20)
+#define MPI2_CONFIG_PAGEATTR_MASK                   (0xF0)
+
+#define MPI2_CONFIG_PAGETYPE_IO_UNIT                (0x00)
+#define MPI2_CONFIG_PAGETYPE_IOC                    (0x01)
+#define MPI2_CONFIG_PAGETYPE_BIOS                   (0x02)
+#define MPI2_CONFIG_PAGETYPE_RAID_VOLUME            (0x08)
+#define MPI2_CONFIG_PAGETYPE_MANUFACTURING          (0x09)
+#define MPI2_CONFIG_PAGETYPE_RAID_PHYSDISK          (0x0A)
+#define MPI2_CONFIG_PAGETYPE_EXTENDED               (0x0F)
+#define MPI2_CONFIG_PAGETYPE_MASK                   (0x0F)
+
+#define MPI2_CONFIG_TYPENUM_MASK                    (0x0FFF)
+
+
+/* ExtPageType field values */
+#define MPI2_CONFIG_EXTPAGETYPE_SAS_IO_UNIT         (0x10)
+#define MPI2_CONFIG_EXTPAGETYPE_SAS_EXPANDER        (0x11)
+#define MPI2_CONFIG_EXTPAGETYPE_SAS_DEVICE          (0x12)
+#define MPI2_CONFIG_EXTPAGETYPE_SAS_PHY             (0x13)
+#define MPI2_CONFIG_EXTPAGETYPE_LOG                 (0x14)
+#define MPI2_CONFIG_EXTPAGETYPE_ENCLOSURE           (0x15)
+#define MPI2_CONFIG_EXTPAGETYPE_RAID_CONFIG         (0x16)
+#define MPI2_CONFIG_EXTPAGETYPE_DRIVER_MAPPING      (0x17)
+#define MPI2_CONFIG_EXTPAGETYPE_SAS_PORT            (0x18)
+#define MPI2_CONFIG_EXTPAGETYPE_ETHERNET            (0x19)
+
+
+/*****************************************************************************
+*   PageAddress defines
+*****************************************************************************/
+
+/* RAID Volume PageAddress format */
+#define MPI2_RAID_VOLUME_PGAD_FORM_MASK             (0xF0000000)
+#define MPI2_RAID_VOLUME_PGAD_FORM_GET_NEXT_HANDLE  (0x00000000)
+#define MPI2_RAID_VOLUME_PGAD_FORM_HANDLE           (0x10000000)
+
+#define MPI2_RAID_VOLUME_PGAD_HANDLE_MASK           (0x0000FFFF)
+
+
+/* RAID Physical Disk PageAddress format */
+#define MPI2_PHYSDISK_PGAD_FORM_MASK                    (0xF0000000)
+#define MPI2_PHYSDISK_PGAD_FORM_GET_NEXT_PHYSDISKNUM    (0x00000000)
+#define MPI2_PHYSDISK_PGAD_FORM_PHYSDISKNUM             (0x10000000)
+#define MPI2_PHYSDISK_PGAD_FORM_DEVHANDLE               (0x20000000)
+
+#define MPI2_PHYSDISK_PGAD_PHYSDISKNUM_MASK             (0x000000FF)
+#define MPI2_PHYSDISK_PGAD_DEVHANDLE_MASK               (0x0000FFFF)
+
+
+/* SAS Expander PageAddress format */
+#define MPI2_SAS_EXPAND_PGAD_FORM_MASK              (0xF0000000)
+#define MPI2_SAS_EXPAND_PGAD_FORM_GET_NEXT_HNDL     (0x00000000)
+#define MPI2_SAS_EXPAND_PGAD_FORM_HNDL_PHY_NUM      (0x10000000)
+#define MPI2_SAS_EXPAND_PGAD_FORM_HNDL              (0x20000000)
+
+#define MPI2_SAS_EXPAND_PGAD_HANDLE_MASK            (0x0000FFFF)
+#define MPI2_SAS_EXPAND_PGAD_PHYNUM_MASK            (0x00FF0000)
+#define MPI2_SAS_EXPAND_PGAD_PHYNUM_SHIFT           (16)
+
+
+/* SAS Device PageAddress format */
+#define MPI2_SAS_DEVICE_PGAD_FORM_MASK              (0xF0000000)
+#define MPI2_SAS_DEVICE_PGAD_FORM_GET_NEXT_HANDLE   (0x00000000)
+#define MPI2_SAS_DEVICE_PGAD_FORM_HANDLE            (0x20000000)
+
+#define MPI2_SAS_DEVICE_PGAD_HANDLE_MASK            (0x0000FFFF)
+
+
+/* SAS PHY PageAddress format */
+#define MPI2_SAS_PHY_PGAD_FORM_MASK                 (0xF0000000)
+#define MPI2_SAS_PHY_PGAD_FORM_PHY_NUMBER           (0x00000000)
+#define MPI2_SAS_PHY_PGAD_FORM_PHY_TBL_INDEX        (0x10000000)
+
+#define MPI2_SAS_PHY_PGAD_PHY_NUMBER_MASK           (0x000000FF)
+#define MPI2_SAS_PHY_PGAD_PHY_TBL_INDEX_MASK        (0x0000FFFF)
+
+
+/* SAS Port PageAddress format */
+#define MPI2_SASPORT_PGAD_FORM_MASK                 (0xF0000000)
+#define MPI2_SASPORT_PGAD_FORM_GET_NEXT_PORT        (0x00000000)
+#define MPI2_SASPORT_PGAD_FORM_PORT_NUM             (0x10000000)
+
+#define MPI2_SASPORT_PGAD_PORTNUMBER_MASK           (0x00000FFF)
+
+
+/* SAS Enclosure PageAddress format */
+#define MPI2_SAS_ENCLOS_PGAD_FORM_MASK              (0xF0000000)
+#define MPI2_SAS_ENCLOS_PGAD_FORM_GET_NEXT_HANDLE   (0x00000000)
+#define MPI2_SAS_ENCLOS_PGAD_FORM_HANDLE            (0x10000000)
+
+#define MPI2_SAS_ENCLOS_PGAD_HANDLE_MASK            (0x0000FFFF)
+
+
+/* RAID Configuration PageAddress format */
+#define MPI2_RAID_PGAD_FORM_MASK                    (0xF0000000)
+#define MPI2_RAID_PGAD_FORM_GET_NEXT_CONFIGNUM      (0x00000000)
+#define MPI2_RAID_PGAD_FORM_CONFIGNUM               (0x10000000)
+#define MPI2_RAID_PGAD_FORM_ACTIVE_CONFIG           (0x20000000)
+
+#define MPI2_RAID_PGAD_CONFIGNUM_MASK               (0x000000FF)
+
+
+/* Driver Persistent Mapping PageAddress format */
+#define MPI2_DPM_PGAD_FORM_MASK                     (0xF0000000)
+#define MPI2_DPM_PGAD_FORM_ENTRY_RANGE              (0x00000000)
+
+#define MPI2_DPM_PGAD_ENTRY_COUNT_MASK              (0x0FFF0000)
+#define MPI2_DPM_PGAD_ENTRY_COUNT_SHIFT             (16)
+#define MPI2_DPM_PGAD_START_ENTRY_MASK              (0x0000FFFF)
+
+
+/* Ethernet PageAddress format */
+#define MPI2_ETHERNET_PGAD_FORM_MASK                (0xF0000000)
+#define MPI2_ETHERNET_PGAD_FORM_IF_NUM              (0x00000000)
+
+#define MPI2_ETHERNET_PGAD_IF_NUMBER_MASK           (0x000000FF)
+
+
+
+/****************************************************************************
+*   Configuration messages
+****************************************************************************/
+
+/* Configuration Request Message */
+typedef struct _MPI2_CONFIG_REQUEST
+{
+    U8                      Action;                     /* 0x00 */
+    U8                      SGLFlags;                   /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     ExtPageLength;              /* 0x04 */
+    U8                      ExtPageType;                /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved1;                  /* 0x0A */
+    U32                     Reserved2;                  /* 0x0C */
+    U32                     Reserved3;                  /* 0x10 */
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x14 */
+    U32                     PageAddress;                /* 0x18 */
+    MPI2_SGE_IO_UNION       PageBufferSGE;              /* 0x1C */
+} MPI2_CONFIG_REQUEST, MPI2_POINTER PTR_MPI2_CONFIG_REQUEST,
+  Mpi2ConfigRequest_t, MPI2_POINTER pMpi2ConfigRequest_t;
+
+/* values for the Action field */
+#define MPI2_CONFIG_ACTION_PAGE_HEADER              (0x00)
+#define MPI2_CONFIG_ACTION_PAGE_READ_CURRENT        (0x01)
+#define MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT       (0x02)
+#define MPI2_CONFIG_ACTION_PAGE_DEFAULT             (0x03)
+#define MPI2_CONFIG_ACTION_PAGE_WRITE_NVRAM         (0x04)
+#define MPI2_CONFIG_ACTION_PAGE_READ_DEFAULT        (0x05)
+#define MPI2_CONFIG_ACTION_PAGE_READ_NVRAM          (0x06)
+#define MPI2_CONFIG_ACTION_PAGE_GET_CHANGEABLE      (0x07)
+
+/* values for SGLFlags field are in the SGL section of mpi2.h */
+
+
+/* Config Reply Message */
+typedef struct _MPI2_CONFIG_REPLY
+{
+    U8                      Action;                     /* 0x00 */
+    U8                      SGLFlags;                   /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     ExtPageLength;              /* 0x04 */
+    U8                      ExtPageType;                /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved1;                  /* 0x0A */
+    U16                     Reserved2;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x14 */
+} MPI2_CONFIG_REPLY, MPI2_POINTER PTR_MPI2_CONFIG_REPLY,
+  Mpi2ConfigReply_t, MPI2_POINTER pMpi2ConfigReply_t;
+
+
+
+/*****************************************************************************
+*
+*               C o n f i g u r a t i o n    P a g e s
+*
+*****************************************************************************/
+
+/****************************************************************************
+*   Manufacturing Config pages
+****************************************************************************/
+
+#define MPI2_MFGPAGE_VENDORID_LSI                   (0x1000)
+
+/* SAS */
+#define MPI2_MFGPAGE_DEVID_SAS2004                  (0x0070)
+#define MPI2_MFGPAGE_DEVID_SAS2008                  (0x0072)
+#define MPI2_MFGPAGE_DEVID_SAS2108_1                (0x0074)
+#define MPI2_MFGPAGE_DEVID_SAS2108_2                (0x0076)
+#define MPI2_MFGPAGE_DEVID_SAS2108_3                (0x0077)
+#define MPI2_MFGPAGE_DEVID_SAS2116_1                (0x0064)
+#define MPI2_MFGPAGE_DEVID_SAS2116_2                (0x0065)
+
+#define MPI2_MFGPAGE_DEVID_SAS2208_1                (0x0080)
+#define MPI2_MFGPAGE_DEVID_SAS2208_2                (0x0081)
+#define MPI2_MFGPAGE_DEVID_SAS2208_3                (0x0082)
+#define MPI2_MFGPAGE_DEVID_SAS2208_4                (0x0083)
+#define MPI2_MFGPAGE_DEVID_SAS2208_5                (0x0084)
+#define MPI2_MFGPAGE_DEVID_SAS2208_6                (0x0085)
+#define MPI2_MFGPAGE_DEVID_SAS2208_7                (0x0086)
+#define MPI2_MFGPAGE_DEVID_SAS2208_8                (0x0087)
+
+
+/* Manufacturing Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_0
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U8                      ChipName[16];               /* 0x04 */
+    U8                      ChipRevision[8];            /* 0x14 */
+    U8                      BoardName[16];              /* 0x1C */
+    U8                      BoardAssembly[16];          /* 0x2C */
+    U8                      BoardTracerNumber[16];      /* 0x3C */
+} MPI2_CONFIG_PAGE_MAN_0,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_0,
+  Mpi2ManufacturingPage0_t, MPI2_POINTER pMpi2ManufacturingPage0_t;
+
+#define MPI2_MANUFACTURING0_PAGEVERSION                (0x00)
+
+
+/* Manufacturing Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_1
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U8                      VPD[256];                   /* 0x04 */
+} MPI2_CONFIG_PAGE_MAN_1,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_1,
+  Mpi2ManufacturingPage1_t, MPI2_POINTER pMpi2ManufacturingPage1_t;
+
+#define MPI2_MANUFACTURING1_PAGEVERSION                (0x00)
+
+
+typedef struct _MPI2_CHIP_REVISION_ID
+{
+    U16 DeviceID;                                       /* 0x00 */
+    U8  PCIRevisionID;                                  /* 0x02 */
+    U8  Reserved;                                       /* 0x03 */
+} MPI2_CHIP_REVISION_ID, MPI2_POINTER PTR_MPI2_CHIP_REVISION_ID,
+  Mpi2ChipRevisionId_t, MPI2_POINTER pMpi2ChipRevisionId_t;
+
+
+/* Manufacturing Page 2 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength at runtime.
+ */
+#ifndef MPI2_MAN_PAGE_2_HW_SETTINGS_WORDS
+#define MPI2_MAN_PAGE_2_HW_SETTINGS_WORDS   (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_2
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    MPI2_CHIP_REVISION_ID   ChipId;                     /* 0x04 */
+    U32                     HwSettings[MPI2_MAN_PAGE_2_HW_SETTINGS_WORDS];/* 0x08 */
+} MPI2_CONFIG_PAGE_MAN_2,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_2,
+  Mpi2ManufacturingPage2_t, MPI2_POINTER pMpi2ManufacturingPage2_t;
+
+#define MPI2_MANUFACTURING2_PAGEVERSION                 (0x00)
+
+
+/* Manufacturing Page 3 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength at runtime.
+ */
+#ifndef MPI2_MAN_PAGE_3_INFO_WORDS
+#define MPI2_MAN_PAGE_3_INFO_WORDS          (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_3
+{
+    MPI2_CONFIG_PAGE_HEADER             Header;         /* 0x00 */
+    MPI2_CHIP_REVISION_ID               ChipId;         /* 0x04 */
+    U32                                 Info[MPI2_MAN_PAGE_3_INFO_WORDS];/* 0x08 */
+} MPI2_CONFIG_PAGE_MAN_3,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_3,
+  Mpi2ManufacturingPage3_t, MPI2_POINTER pMpi2ManufacturingPage3_t;
+
+#define MPI2_MANUFACTURING3_PAGEVERSION                 (0x00)
+
+
+/* Manufacturing Page 4 */
+
+typedef struct _MPI2_MANPAGE4_PWR_SAVE_SETTINGS
+{
+    U8                          PowerSaveFlags;                 /* 0x00 */
+    U8                          InternalOperationsSleepTime;    /* 0x01 */
+    U8                          InternalOperationsRunTime;      /* 0x02 */
+    U8                          HostIdleTime;                   /* 0x03 */
+} MPI2_MANPAGE4_PWR_SAVE_SETTINGS,
+  MPI2_POINTER PTR_MPI2_MANPAGE4_PWR_SAVE_SETTINGS,
+  Mpi2ManPage4PwrSaveSettings_t, MPI2_POINTER pMpi2ManPage4PwrSaveSettings_t;
+
+/* defines for the PowerSaveFlags field */
+#define MPI2_MANPAGE4_MASK_POWERSAVE_MODE               (0x03)
+#define MPI2_MANPAGE4_POWERSAVE_MODE_DISABLED           (0x00)
+#define MPI2_MANPAGE4_CUSTOM_POWERSAVE_MODE             (0x01)
+#define MPI2_MANPAGE4_FULL_POWERSAVE_MODE               (0x02)
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_4
+{
+    MPI2_CONFIG_PAGE_HEADER             Header;                 /* 0x00 */
+    U32                                 Reserved1;              /* 0x04 */
+    U32                                 Flags;                  /* 0x08 */
+    U8                                  InquirySize;            /* 0x0C */
+    U8                                  Reserved2;              /* 0x0D */
+    U16                                 Reserved3;              /* 0x0E */
+    U8                                  InquiryData[56];        /* 0x10 */
+    U32                                 RAID0VolumeSettings;    /* 0x48 */
+    U32                                 RAID1EVolumeSettings;   /* 0x4C */
+    U32                                 RAID1VolumeSettings;    /* 0x50 */
+    U32                                 RAID10VolumeSettings;   /* 0x54 */
+    U32                                 Reserved4;              /* 0x58 */
+    U32                                 Reserved5;              /* 0x5C */
+    MPI2_MANPAGE4_PWR_SAVE_SETTINGS     PowerSaveSettings;      /* 0x60 */
+    U8                                  MaxOCEDisks;            /* 0x64 */
+    U8                                  ResyncRate;             /* 0x65 */
+    U16                                 DataScrubDuration;      /* 0x66 */
+    U8                                  MaxHotSpares;           /* 0x68 */
+    U8                                  MaxPhysDisksPerVol;     /* 0x69 */
+    U8                                  MaxPhysDisks;           /* 0x6A */
+    U8                                  MaxVolumes;             /* 0x6B */
+} MPI2_CONFIG_PAGE_MAN_4,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_4,
+  Mpi2ManufacturingPage4_t, MPI2_POINTER pMpi2ManufacturingPage4_t;
+
+#define MPI2_MANUFACTURING4_PAGEVERSION                 (0x0A)
+
+/* Manufacturing Page 4 Flags field */
+#define MPI2_MANPAGE4_METADATA_SIZE_MASK                (0x00030000)
+#define MPI2_MANPAGE4_METADATA_512MB                    (0x00000000)
+
+#define MPI2_MANPAGE4_MIX_SSD_SAS_SATA                  (0x00008000)
+#define MPI2_MANPAGE4_MIX_SSD_AND_NON_SSD               (0x00004000)
+#define MPI2_MANPAGE4_HIDE_PHYSDISK_NON_IR              (0x00002000)
+
+#define MPI2_MANPAGE4_MASK_PHYSDISK_COERCION            (0x00001C00)
+#define MPI2_MANPAGE4_PHYSDISK_COERCION_1GB             (0x00000000)
+#define MPI2_MANPAGE4_PHYSDISK_128MB_COERCION           (0x00000400)
+#define MPI2_MANPAGE4_PHYSDISK_ADAPTIVE_COERCION        (0x00000800)
+#define MPI2_MANPAGE4_PHYSDISK_ZERO_COERCION            (0x00000C00)
+
+#define MPI2_MANPAGE4_MASK_BAD_BLOCK_MARKING            (0x00000300)
+#define MPI2_MANPAGE4_DEFAULT_BAD_BLOCK_MARKING         (0x00000000)
+#define MPI2_MANPAGE4_TABLE_BAD_BLOCK_MARKING           (0x00000100)
+#define MPI2_MANPAGE4_WRITE_LONG_BAD_BLOCK_MARKING      (0x00000200)
+
+#define MPI2_MANPAGE4_FORCE_OFFLINE_FAILOVER            (0x00000080)
+#define MPI2_MANPAGE4_RAID10_DISABLE                    (0x00000040)
+#define MPI2_MANPAGE4_RAID1E_DISABLE                    (0x00000020)
+#define MPI2_MANPAGE4_RAID1_DISABLE                     (0x00000010)
+#define MPI2_MANPAGE4_RAID0_DISABLE                     (0x00000008)
+#define MPI2_MANPAGE4_IR_MODEPAGE8_DISABLE              (0x00000004)
+#define MPI2_MANPAGE4_IM_RESYNC_CACHE_ENABLE            (0x00000002)
+#define MPI2_MANPAGE4_IR_NO_MIX_SAS_SATA                (0x00000001)
+
+
+/* Manufacturing Page 5 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_MAN_PAGE_5_PHY_ENTRIES
+#define MPI2_MAN_PAGE_5_PHY_ENTRIES         (1)
+#endif
+
+typedef struct _MPI2_MANUFACTURING5_ENTRY
+{
+    U64                                 WWID;           /* 0x00 */
+    U64                                 DeviceName;     /* 0x08 */
+} MPI2_MANUFACTURING5_ENTRY, MPI2_POINTER PTR_MPI2_MANUFACTURING5_ENTRY,
+  Mpi2Manufacturing5Entry_t, MPI2_POINTER pMpi2Manufacturing5Entry_t;
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_5
+{
+    MPI2_CONFIG_PAGE_HEADER             Header;         /* 0x00 */
+    U8                                  NumPhys;        /* 0x04 */
+    U8                                  Reserved1;      /* 0x05 */
+    U16                                 Reserved2;      /* 0x06 */
+    U32                                 Reserved3;      /* 0x08 */
+    U32                                 Reserved4;      /* 0x0C */
+    MPI2_MANUFACTURING5_ENTRY           Phy[MPI2_MAN_PAGE_5_PHY_ENTRIES];/* 0x08 */
+} MPI2_CONFIG_PAGE_MAN_5,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_5,
+  Mpi2ManufacturingPage5_t, MPI2_POINTER pMpi2ManufacturingPage5_t;
+
+#define MPI2_MANUFACTURING5_PAGEVERSION                 (0x03)
+
+
+/* Manufacturing Page 6 */
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_6
+{
+    MPI2_CONFIG_PAGE_HEADER         Header;             /* 0x00 */
+    U32                             ProductSpecificInfo;/* 0x04 */
+} MPI2_CONFIG_PAGE_MAN_6,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_6,
+  Mpi2ManufacturingPage6_t, MPI2_POINTER pMpi2ManufacturingPage6_t;
+
+#define MPI2_MANUFACTURING6_PAGEVERSION                 (0x00)
+
+
+/* Manufacturing Page 7 */
+
+typedef struct _MPI2_MANPAGE7_CONNECTOR_INFO
+{
+    U32                         Pinout;                 /* 0x00 */
+    U8                          Connector[16];          /* 0x04 */
+    U8                          Location;               /* 0x14 */
+    U8                          Reserved1;              /* 0x15 */
+    U16                         Slot;                   /* 0x16 */
+    U32                         Reserved2;              /* 0x18 */
+} MPI2_MANPAGE7_CONNECTOR_INFO, MPI2_POINTER PTR_MPI2_MANPAGE7_CONNECTOR_INFO,
+  Mpi2ManPage7ConnectorInfo_t, MPI2_POINTER pMpi2ManPage7ConnectorInfo_t;
+
+/* defines for the Pinout field */
+#define MPI2_MANPAGE7_PINOUT_SFF_8484_L4                (0x00080000)
+#define MPI2_MANPAGE7_PINOUT_SFF_8484_L3                (0x00040000)
+#define MPI2_MANPAGE7_PINOUT_SFF_8484_L2                (0x00020000)
+#define MPI2_MANPAGE7_PINOUT_SFF_8484_L1                (0x00010000)
+#define MPI2_MANPAGE7_PINOUT_SFF_8470_L4                (0x00000800)
+#define MPI2_MANPAGE7_PINOUT_SFF_8470_L3                (0x00000400)
+#define MPI2_MANPAGE7_PINOUT_SFF_8470_L2                (0x00000200)
+#define MPI2_MANPAGE7_PINOUT_SFF_8470_L1                (0x00000100)
+#define MPI2_MANPAGE7_PINOUT_SFF_8482                   (0x00000002)
+#define MPI2_MANPAGE7_PINOUT_CONNECTION_UNKNOWN         (0x00000001)
+
+/* defines for the Location field */
+#define MPI2_MANPAGE7_LOCATION_UNKNOWN                  (0x01)
+#define MPI2_MANPAGE7_LOCATION_INTERNAL                 (0x02)
+#define MPI2_MANPAGE7_LOCATION_EXTERNAL                 (0x04)
+#define MPI2_MANPAGE7_LOCATION_SWITCHABLE               (0x08)
+#define MPI2_MANPAGE7_LOCATION_AUTO                     (0x10)
+#define MPI2_MANPAGE7_LOCATION_NOT_PRESENT              (0x20)
+#define MPI2_MANPAGE7_LOCATION_NOT_CONNECTED            (0x80)
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check NumPhys at runtime.
+ */
+#ifndef MPI2_MANPAGE7_CONNECTOR_INFO_MAX
+#define MPI2_MANPAGE7_CONNECTOR_INFO_MAX  (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_7
+{
+    MPI2_CONFIG_PAGE_HEADER         Header;             /* 0x00 */
+    U32                             Reserved1;          /* 0x04 */
+    U32                             Reserved2;          /* 0x08 */
+    U32                             Flags;              /* 0x0C */
+    U8                              EnclosureName[16];  /* 0x10 */
+    U8                              NumPhys;            /* 0x20 */
+    U8                              Reserved3;          /* 0x21 */
+    U16                             Reserved4;          /* 0x22 */
+    MPI2_MANPAGE7_CONNECTOR_INFO    ConnectorInfo[MPI2_MANPAGE7_CONNECTOR_INFO_MAX]; /* 0x24 */
+} MPI2_CONFIG_PAGE_MAN_7,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_7,
+  Mpi2ManufacturingPage7_t, MPI2_POINTER pMpi2ManufacturingPage7_t;
+
+#define MPI2_MANUFACTURING7_PAGEVERSION                 (0x00)
+
+/* defines for the Flags field */
+#define MPI2_MANPAGE7_FLAG_USE_SLOT_INFO                (0x00000001)
+
+
+/*
+ * Generic structure to use for product-specific manufacturing pages
+ * (currently Manufacturing Page 8 through Manufacturing Page 31).
+ */
+
+typedef struct _MPI2_CONFIG_PAGE_MAN_PS
+{
+    MPI2_CONFIG_PAGE_HEADER         Header;             /* 0x00 */
+    U32                             ProductSpecificInfo;/* 0x04 */
+} MPI2_CONFIG_PAGE_MAN_PS,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_MAN_PS,
+  Mpi2ManufacturingPagePS_t, MPI2_POINTER pMpi2ManufacturingPagePS_t;
+
+#define MPI2_MANUFACTURING8_PAGEVERSION                 (0x00)
+#define MPI2_MANUFACTURING9_PAGEVERSION                 (0x00)
+#define MPI2_MANUFACTURING10_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING11_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING12_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING13_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING14_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING15_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING16_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING17_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING18_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING19_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING20_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING21_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING22_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING23_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING24_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING25_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING26_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING27_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING28_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING29_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING30_PAGEVERSION                (0x00)
+#define MPI2_MANUFACTURING31_PAGEVERSION                (0x00)
+
+
+/****************************************************************************
+*   IO Unit Config Pages
+****************************************************************************/
+
+/* IO Unit Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_IO_UNIT_0
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U64                     UniqueValue;                /* 0x04 */
+    MPI2_VERSION_UNION      NvdataVersionDefault;       /* 0x08 */
+    MPI2_VERSION_UNION      NvdataVersionPersistent;    /* 0x0A */
+} MPI2_CONFIG_PAGE_IO_UNIT_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IO_UNIT_0,
+  Mpi2IOUnitPage0_t, MPI2_POINTER pMpi2IOUnitPage0_t;
+
+#define MPI2_IOUNITPAGE0_PAGEVERSION                    (0x02)
+
+
+/* IO Unit Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_IO_UNIT_1
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U32                     Flags;                      /* 0x04 */
+} MPI2_CONFIG_PAGE_IO_UNIT_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IO_UNIT_1,
+  Mpi2IOUnitPage1_t, MPI2_POINTER pMpi2IOUnitPage1_t;
+
+#define MPI2_IOUNITPAGE1_PAGEVERSION                    (0x04)
+
+/* IO Unit Page 1 Flags defines */
+#define MPI2_IOUNITPAGE1_ENABLE_HOST_BASED_DISCOVERY    (0x00000800)
+#define MPI2_IOUNITPAGE1_MASK_SATA_WRITE_CACHE          (0x00000600)
+#define MPI2_IOUNITPAGE1_ENABLE_SATA_WRITE_CACHE        (0x00000000)
+#define MPI2_IOUNITPAGE1_DISABLE_SATA_WRITE_CACHE       (0x00000200)
+#define MPI2_IOUNITPAGE1_UNCHANGED_SATA_WRITE_CACHE     (0x00000400)
+#define MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE       (0x00000100)
+#define MPI2_IOUNITPAGE1_DISABLE_IR                     (0x00000040)
+#define MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING (0x00000020)
+#define MPI2_IOUNITPAGE1_IR_USE_STATIC_VOLUME_ID        (0x00000004)
+#define MPI2_IOUNITPAGE1_MULTI_PATHING                  (0x00000002)
+#define MPI2_IOUNITPAGE1_SINGLE_PATHING                 (0x00000000)
+
+
+/* IO Unit Page 3 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength at runtime.
+ */
+#ifndef MPI2_IO_UNIT_PAGE_3_GPIO_VAL_MAX
+#define MPI2_IO_UNIT_PAGE_3_GPIO_VAL_MAX    (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_IO_UNIT_3
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                                   /* 0x00 */
+    U8                      GPIOCount;                                /* 0x04 */
+    U8                      Reserved1;                                /* 0x05 */
+    U16                     Reserved2;                                /* 0x06 */
+    U16                     GPIOVal[MPI2_IO_UNIT_PAGE_3_GPIO_VAL_MAX];/* 0x08 */
+} MPI2_CONFIG_PAGE_IO_UNIT_3, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IO_UNIT_3,
+  Mpi2IOUnitPage3_t, MPI2_POINTER pMpi2IOUnitPage3_t;
+
+#define MPI2_IOUNITPAGE3_PAGEVERSION                    (0x01)
+
+/* defines for IO Unit Page 3 GPIOVal field */
+#define MPI2_IOUNITPAGE3_GPIO_FUNCTION_MASK             (0xFFFC)
+#define MPI2_IOUNITPAGE3_GPIO_FUNCTION_SHIFT            (2)
+#define MPI2_IOUNITPAGE3_GPIO_SETTING_OFF               (0x0000)
+#define MPI2_IOUNITPAGE3_GPIO_SETTING_ON                (0x0001)
+
+
+/* IO Unit Page 5 */
+
+/*
+ * Upper layer code (drivers, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength or NumDmaEngines at runtime.
+ */
+#ifndef MPI2_IOUNITPAGE5_DMAENGINE_ENTRIES
+#define MPI2_IOUNITPAGE5_DMAENGINE_ENTRIES      (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_IO_UNIT_5
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                                     /* 0x00 */
+    U64                     RaidAcceleratorBufferBaseAddress;           /* 0x04 */
+    U64                     RaidAcceleratorBufferSize;                  /* 0x0C */
+    U64                     RaidAcceleratorControlBaseAddress;          /* 0x14 */
+    U8                      RAControlSize;                              /* 0x1C */
+    U8                      NumDmaEngines;                              /* 0x1D */
+    U8                      RAMinControlSize;                           /* 0x1E */
+    U8                      RAMaxControlSize;                           /* 0x1F */
+    U32                     Reserved1;                                  /* 0x20 */
+    U32                     Reserved2;                                  /* 0x24 */
+    U32                     Reserved3;                                  /* 0x28 */
+    U32                     DmaEngineCapabilities[MPI2_IOUNITPAGE5_DMAENGINE_ENTRIES]; /* 0x2C */
+} MPI2_CONFIG_PAGE_IO_UNIT_5, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IO_UNIT_5,
+  Mpi2IOUnitPage5_t, MPI2_POINTER pMpi2IOUnitPage5_t;
+
+#define MPI2_IOUNITPAGE5_PAGEVERSION                    (0x00)
+
+/* defines for IO Unit Page 5 DmaEngineCapabilities field */
+#define MPI2_IOUNITPAGE5_DMA_CAP_MASK_MAX_REQUESTS      (0xFF00)
+#define MPI2_IOUNITPAGE5_DMA_CAP_SHIFT_MAX_REQUESTS     (16)
+
+#define MPI2_IOUNITPAGE5_DMA_CAP_EEDP                   (0x0008)
+#define MPI2_IOUNITPAGE5_DMA_CAP_PARITY_GENERATION      (0x0004)
+#define MPI2_IOUNITPAGE5_DMA_CAP_HASHING                (0x0002)
+#define MPI2_IOUNITPAGE5_DMA_CAP_ENCRYPTION             (0x0001)
+
+
+/* IO Unit Page 6 */
+
+typedef struct _MPI2_CONFIG_PAGE_IO_UNIT_6
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                                 /* 0x00 */
+    U16                     Flags;                                  /* 0x04 */
+    U8                      RAHostControlSize;                      /* 0x06 */
+    U8                      Reserved0;                              /* 0x07 */
+    U64                     RaidAcceleratorHostControlBaseAddress;  /* 0x08 */
+    U32                     Reserved1;                              /* 0x10 */
+    U32                     Reserved2;                              /* 0x14 */
+    U32                     Reserved3;                              /* 0x18 */
+} MPI2_CONFIG_PAGE_IO_UNIT_6, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IO_UNIT_6,
+  Mpi2IOUnitPage6_t, MPI2_POINTER pMpi2IOUnitPage6_t;
+
+#define MPI2_IOUNITPAGE6_PAGEVERSION                    (0x00)
+
+/* defines for IO Unit Page 6 Flags field */
+#define MPI2_IOUNITPAGE6_FLAGS_ENABLE_RAID_ACCELERATOR  (0x0001)
+
+
+/* IO Unit Page 7 */
+
+typedef struct _MPI2_CONFIG_PAGE_IO_UNIT_7
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                                 /* 0x00 */
+    U16                     Reserved1;                              /* 0x04 */
+    U8                      PCIeWidth;                              /* 0x06 */
+    U8                      PCIeSpeed;                              /* 0x07 */
+    U32                     ProcessorState;                         /* 0x08 */
+    U32                     Reserved2;                              /* 0x0C */
+    U16                     IOCTemperature;                         /* 0x10 */
+    U8                      IOCTemperatureUnits;                    /* 0x12 */
+    U8                      IOCSpeed;                               /* 0x13 */
+    U32                     Reserved3;                              /* 0x14 */
+} MPI2_CONFIG_PAGE_IO_UNIT_7, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IO_UNIT_7,
+  Mpi2IOUnitPage7_t, MPI2_POINTER pMpi2IOUnitPage7_t;
+
+#define MPI2_IOUNITPAGE7_PAGEVERSION                    (0x00)
+
+/* defines for IO Unit Page 7 PCIeWidth field */
+#define MPI2_IOUNITPAGE7_PCIE_WIDTH_X1              (0x01)
+#define MPI2_IOUNITPAGE7_PCIE_WIDTH_X2              (0x02)
+#define MPI2_IOUNITPAGE7_PCIE_WIDTH_X4              (0x04)
+#define MPI2_IOUNITPAGE7_PCIE_WIDTH_X8              (0x08)
+
+/* defines for IO Unit Page 7 PCIeSpeed field */
+#define MPI2_IOUNITPAGE7_PCIE_SPEED_2_5_GBPS        (0x00)
+#define MPI2_IOUNITPAGE7_PCIE_SPEED_5_0_GBPS        (0x01)
+#define MPI2_IOUNITPAGE7_PCIE_SPEED_8_0_GBPS        (0x02)
+
+/* defines for IO Unit Page 7 ProcessorState field */
+#define MPI2_IOUNITPAGE7_PSTATE_MASK_SECOND         (0x0000000F)
+#define MPI2_IOUNITPAGE7_PSTATE_SHIFT_SECOND        (0)
+
+#define MPI2_IOUNITPAGE7_PSTATE_NOT_PRESENT         (0x00)
+#define MPI2_IOUNITPAGE7_PSTATE_DISABLED            (0x01)
+#define MPI2_IOUNITPAGE7_PSTATE_ENABLED             (0x02)
+
+/* defines for IO Unit Page 7 IOCTemperatureUnits field */
+#define MPI2_IOUNITPAGE7_IOC_TEMP_NOT_PRESENT       (0x00)
+#define MPI2_IOUNITPAGE7_IOC_TEMP_FAHRENHEIT        (0x01)
+#define MPI2_IOUNITPAGE7_IOC_TEMP_CELSIUS           (0x02)
+
+/* defines for IO Unit Page 7 IOCSpeed field */
+#define MPI2_IOUNITPAGE7_IOC_SPEED_FULL             (0x01)
+#define MPI2_IOUNITPAGE7_IOC_SPEED_HALF             (0x02)
+#define MPI2_IOUNITPAGE7_IOC_SPEED_QUARTER          (0x04)
+#define MPI2_IOUNITPAGE7_IOC_SPEED_EIGHTH           (0x08)
+
+
+
+/****************************************************************************
+*   IOC Config Pages
+****************************************************************************/
+
+/* IOC Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_IOC_0
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U32                     Reserved1;                  /* 0x04 */
+    U32                     Reserved2;                  /* 0x08 */
+    U16                     VendorID;                   /* 0x0C */
+    U16                     DeviceID;                   /* 0x0E */
+    U8                      RevisionID;                 /* 0x10 */
+    U8                      Reserved3;                  /* 0x11 */
+    U16                     Reserved4;                  /* 0x12 */
+    U32                     ClassCode;                  /* 0x14 */
+    U16                     SubsystemVendorID;          /* 0x18 */
+    U16                     SubsystemID;                /* 0x1A */
+} MPI2_CONFIG_PAGE_IOC_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IOC_0,
+  Mpi2IOCPage0_t, MPI2_POINTER pMpi2IOCPage0_t;
+
+#define MPI2_IOCPAGE0_PAGEVERSION                       (0x02)
+
+
+/* IOC Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_IOC_1
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U32                     Flags;                      /* 0x04 */
+    U32                     CoalescingTimeout;          /* 0x08 */
+    U8                      CoalescingDepth;            /* 0x0C */
+    U8                      PCISlotNum;                 /* 0x0D */
+    U8                      PCIBusNum;                  /* 0x0E */
+    U8                      PCIDomainSegment;           /* 0x0F */
+    U32                     Reserved1;                  /* 0x10 */
+    U32                     Reserved2;                  /* 0x14 */
+} MPI2_CONFIG_PAGE_IOC_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IOC_1,
+  Mpi2IOCPage1_t, MPI2_POINTER pMpi2IOCPage1_t;
+
+#define MPI2_IOCPAGE1_PAGEVERSION                       (0x05)
+
+/* defines for IOC Page 1 Flags field */
+#define MPI2_IOCPAGE1_REPLY_COALESCING                  (0x00000001)
+
+#define MPI2_IOCPAGE1_PCISLOTNUM_UNKNOWN                (0xFF)
+#define MPI2_IOCPAGE1_PCIBUSNUM_UNKNOWN                 (0xFF)
+#define MPI2_IOCPAGE1_PCIDOMAIN_UNKNOWN                 (0xFF)
+
+/* IOC Page 6 */
+
+typedef struct _MPI2_CONFIG_PAGE_IOC_6
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                         /* 0x00 */
+    U32                     CapabilitiesFlags;              /* 0x04 */
+    U8                      MaxDrivesRAID0;                 /* 0x08 */
+    U8                      MaxDrivesRAID1;                 /* 0x09 */
+    U8                      MaxDrivesRAID1E;                /* 0x0A */
+    U8                      MaxDrivesRAID10;                /* 0x0B */
+    U8                      MinDrivesRAID0;                 /* 0x0C */
+    U8                      MinDrivesRAID1;                 /* 0x0D */
+    U8                      MinDrivesRAID1E;                /* 0x0E */
+    U8                      MinDrivesRAID10;                /* 0x0F */
+    U32                     Reserved1;                      /* 0x10 */
+    U8                      MaxGlobalHotSpares;             /* 0x14 */
+    U8                      MaxPhysDisks;                   /* 0x15 */
+    U8                      MaxVolumes;                     /* 0x16 */
+    U8                      MaxConfigs;                     /* 0x17 */
+    U8                      MaxOCEDisks;                    /* 0x18 */
+    U8                      Reserved2;                      /* 0x19 */
+    U16                     Reserved3;                      /* 0x1A */
+    U32                     SupportedStripeSizeMapRAID0;    /* 0x1C */
+    U32                     SupportedStripeSizeMapRAID1E;   /* 0x20 */
+    U32                     SupportedStripeSizeMapRAID10;   /* 0x24 */
+    U32                     Reserved4;                      /* 0x28 */
+    U32                     Reserved5;                      /* 0x2C */
+    U16                     DefaultMetadataSize;            /* 0x30 */
+    U16                     Reserved6;                      /* 0x32 */
+    U16                     MaxBadBlockTableEntries;        /* 0x34 */
+    U16                     Reserved7;                      /* 0x36 */
+    U32                     IRNvsramVersion;                /* 0x38 */
+} MPI2_CONFIG_PAGE_IOC_6, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IOC_6,
+  Mpi2IOCPage6_t, MPI2_POINTER pMpi2IOCPage6_t;
+
+#define MPI2_IOCPAGE6_PAGEVERSION                       (0x04)
+
+/* defines for IOC Page 6 CapabilitiesFlags */
+#define MPI2_IOCPAGE6_CAP_FLAGS_RAID10_SUPPORT          (0x00000010)
+#define MPI2_IOCPAGE6_CAP_FLAGS_RAID1_SUPPORT           (0x00000008)
+#define MPI2_IOCPAGE6_CAP_FLAGS_RAID1E_SUPPORT          (0x00000004)
+#define MPI2_IOCPAGE6_CAP_FLAGS_RAID0_SUPPORT           (0x00000002)
+#define MPI2_IOCPAGE6_CAP_FLAGS_GLOBAL_HOT_SPARE        (0x00000001)
+
+
+/* IOC Page 7 */
+
+#define MPI2_IOCPAGE7_EVENTMASK_WORDS       (4)
+
+typedef struct _MPI2_CONFIG_PAGE_IOC_7
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U32                     Reserved1;                  /* 0x04 */
+    U32                     EventMasks[MPI2_IOCPAGE7_EVENTMASK_WORDS];/* 0x08 */
+    U16                     SASBroadcastPrimitiveMasks; /* 0x18 */
+    U16                     Reserved2;                  /* 0x1A */
+    U32                     Reserved3;                  /* 0x1C */
+} MPI2_CONFIG_PAGE_IOC_7, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IOC_7,
+  Mpi2IOCPage7_t, MPI2_POINTER pMpi2IOCPage7_t;
+
+#define MPI2_IOCPAGE7_PAGEVERSION                       (0x01)
+
+
+/* IOC Page 8 */
+
+typedef struct _MPI2_CONFIG_PAGE_IOC_8
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U8                      NumDevsPerEnclosure;        /* 0x04 */
+    U8                      Reserved1;                  /* 0x05 */
+    U16                     Reserved2;                  /* 0x06 */
+    U16                     MaxPersistentEntries;       /* 0x08 */
+    U16                     MaxNumPhysicalMappedIDs;    /* 0x0A */
+    U16                     Flags;                      /* 0x0C */
+    U16                     Reserved3;                  /* 0x0E */
+    U16                     IRVolumeMappingFlags;       /* 0x10 */
+    U16                     Reserved4;                  /* 0x12 */
+    U32                     Reserved5;                  /* 0x14 */
+} MPI2_CONFIG_PAGE_IOC_8, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_IOC_8,
+  Mpi2IOCPage8_t, MPI2_POINTER pMpi2IOCPage8_t;
+
+#define MPI2_IOCPAGE8_PAGEVERSION                       (0x00)
+
+/* defines for IOC Page 8 Flags field */
+#define MPI2_IOCPAGE8_FLAGS_DA_START_SLOT_1             (0x00000020)
+#define MPI2_IOCPAGE8_FLAGS_RESERVED_TARGETID_0         (0x00000010)
+
+#define MPI2_IOCPAGE8_FLAGS_MASK_MAPPING_MODE           (0x0000000E)
+#define MPI2_IOCPAGE8_FLAGS_DEVICE_PERSISTENCE_MAPPING  (0x00000000)
+#define MPI2_IOCPAGE8_FLAGS_ENCLOSURE_SLOT_MAPPING      (0x00000002)
+
+#define MPI2_IOCPAGE8_FLAGS_DISABLE_PERSISTENT_MAPPING  (0x00000001)
+#define MPI2_IOCPAGE8_FLAGS_ENABLE_PERSISTENT_MAPPING   (0x00000000)
+
+/* defines for IOC Page 8 IRVolumeMappingFlags */
+#define MPI2_IOCPAGE8_IRFLAGS_MASK_VOLUME_MAPPING_MODE  (0x00000003)
+#define MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING        (0x00000000)
+#define MPI2_IOCPAGE8_IRFLAGS_HIGH_VOLUME_MAPPING       (0x00000001)
+
+
+/****************************************************************************
+*   BIOS Config Pages
+****************************************************************************/
+
+/* BIOS Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_BIOS_1
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U32                     BiosOptions;                /* 0x04 */
+    U32                     IOCSettings;                /* 0x08 */
+    U32                     Reserved1;                  /* 0x0C */
+    U32                     DeviceSettings;             /* 0x10 */
+    U16                     NumberOfDevices;            /* 0x14 */
+    U16                     Reserved2;                  /* 0x16 */
+    U16                     IOTimeoutBlockDevicesNonRM; /* 0x18 */
+    U16                     IOTimeoutSequential;        /* 0x1A */
+    U16                     IOTimeoutOther;             /* 0x1C */
+    U16                     IOTimeoutBlockDevicesRM;    /* 0x1E */
+} MPI2_CONFIG_PAGE_BIOS_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_BIOS_1,
+  Mpi2BiosPage1_t, MPI2_POINTER pMpi2BiosPage1_t;
+
+#define MPI2_BIOSPAGE1_PAGEVERSION                      (0x04)
+
+/* values for BIOS Page 1 BiosOptions field */
+#define MPI2_BIOSPAGE1_OPTIONS_DISABLE_BIOS             (0x00000001)
+
+/* values for BIOS Page 1 IOCSettings field */
+#define MPI2_BIOSPAGE1_IOCSET_MASK_BOOT_PREFERENCE      (0x00030000)
+#define MPI2_BIOSPAGE1_IOCSET_ENCLOSURE_SLOT_BOOT       (0x00000000)
+#define MPI2_BIOSPAGE1_IOCSET_SAS_ADDRESS_BOOT          (0x00010000)
+
+#define MPI2_BIOSPAGE1_IOCSET_MASK_RM_SETTING           (0x000000C0)
+#define MPI2_BIOSPAGE1_IOCSET_NONE_RM_SETTING           (0x00000000)
+#define MPI2_BIOSPAGE1_IOCSET_BOOT_RM_SETTING           (0x00000040)
+#define MPI2_BIOSPAGE1_IOCSET_MEDIA_RM_SETTING          (0x00000080)
+
+#define MPI2_BIOSPAGE1_IOCSET_MASK_ADAPTER_SUPPORT      (0x00000030)
+#define MPI2_BIOSPAGE1_IOCSET_NO_SUPPORT                (0x00000000)
+#define MPI2_BIOSPAGE1_IOCSET_BIOS_SUPPORT              (0x00000010)
+#define MPI2_BIOSPAGE1_IOCSET_OS_SUPPORT                (0x00000020)
+#define MPI2_BIOSPAGE1_IOCSET_ALL_SUPPORT               (0x00000030)
+
+#define MPI2_BIOSPAGE1_IOCSET_ALTERNATE_CHS             (0x00000008)
+
+/* values for BIOS Page 1 DeviceSettings field */
+#define MPI2_BIOSPAGE1_DEVSET_DISABLE_SMART_POLLING     (0x00000010)
+#define MPI2_BIOSPAGE1_DEVSET_DISABLE_SEQ_LUN           (0x00000008)
+#define MPI2_BIOSPAGE1_DEVSET_DISABLE_RM_LUN            (0x00000004)
+#define MPI2_BIOSPAGE1_DEVSET_DISABLE_NON_RM_LUN        (0x00000002)
+#define MPI2_BIOSPAGE1_DEVSET_DISABLE_OTHER_LUN         (0x00000001)
+
+
+/* BIOS Page 2 */
+
+typedef struct _MPI2_BOOT_DEVICE_ADAPTER_ORDER
+{
+    U32         Reserved1;                              /* 0x00 */
+    U32         Reserved2;                              /* 0x04 */
+    U32         Reserved3;                              /* 0x08 */
+    U32         Reserved4;                              /* 0x0C */
+    U32         Reserved5;                              /* 0x10 */
+    U32         Reserved6;                              /* 0x14 */
+} MPI2_BOOT_DEVICE_ADAPTER_ORDER,
+  MPI2_POINTER PTR_MPI2_BOOT_DEVICE_ADAPTER_ORDER,
+  Mpi2BootDeviceAdapterOrder_t, MPI2_POINTER pMpi2BootDeviceAdapterOrder_t;
+
+typedef struct _MPI2_BOOT_DEVICE_SAS_WWID
+{
+    U64         SASAddress;                             /* 0x00 */
+    U8          LUN[8];                                 /* 0x08 */
+    U32         Reserved1;                              /* 0x10 */
+    U32         Reserved2;                              /* 0x14 */
+} MPI2_BOOT_DEVICE_SAS_WWID, MPI2_POINTER PTR_MPI2_BOOT_DEVICE_SAS_WWID,
+  Mpi2BootDeviceSasWwid_t, MPI2_POINTER pMpi2BootDeviceSasWwid_t;
+
+typedef struct _MPI2_BOOT_DEVICE_ENCLOSURE_SLOT
+{
+    U64         EnclosureLogicalID;                     /* 0x00 */
+    U32         Reserved1;                              /* 0x08 */
+    U32         Reserved2;                              /* 0x0C */
+    U16         SlotNumber;                             /* 0x10 */
+    U16         Reserved3;                              /* 0x12 */
+    U32         Reserved4;                              /* 0x14 */
+} MPI2_BOOT_DEVICE_ENCLOSURE_SLOT,
+  MPI2_POINTER PTR_MPI2_BOOT_DEVICE_ENCLOSURE_SLOT,
+  Mpi2BootDeviceEnclosureSlot_t, MPI2_POINTER pMpi2BootDeviceEnclosureSlot_t;
+
+typedef struct _MPI2_BOOT_DEVICE_DEVICE_NAME
+{
+    U64         DeviceName;                             /* 0x00 */
+    U8          LUN[8];                                 /* 0x08 */
+    U32         Reserved1;                              /* 0x10 */
+    U32         Reserved2;                              /* 0x14 */
+} MPI2_BOOT_DEVICE_DEVICE_NAME, MPI2_POINTER PTR_MPI2_BOOT_DEVICE_DEVICE_NAME,
+  Mpi2BootDeviceDeviceName_t, MPI2_POINTER pMpi2BootDeviceDeviceName_t;
+
+typedef union _MPI2_MPI2_BIOSPAGE2_BOOT_DEVICE
+{
+    MPI2_BOOT_DEVICE_ADAPTER_ORDER  AdapterOrder;
+    MPI2_BOOT_DEVICE_SAS_WWID       SasWwid;
+    MPI2_BOOT_DEVICE_ENCLOSURE_SLOT EnclosureSlot;
+    MPI2_BOOT_DEVICE_DEVICE_NAME    DeviceName;
+} MPI2_BIOSPAGE2_BOOT_DEVICE, MPI2_POINTER PTR_MPI2_BIOSPAGE2_BOOT_DEVICE,
+  Mpi2BiosPage2BootDevice_t, MPI2_POINTER pMpi2BiosPage2BootDevice_t;
+
+typedef struct _MPI2_CONFIG_PAGE_BIOS_2
+{
+    MPI2_CONFIG_PAGE_HEADER     Header;                 /* 0x00 */
+    U32                         Reserved1;              /* 0x04 */
+    U32                         Reserved2;              /* 0x08 */
+    U32                         Reserved3;              /* 0x0C */
+    U32                         Reserved4;              /* 0x10 */
+    U32                         Reserved5;              /* 0x14 */
+    U32                         Reserved6;              /* 0x18 */
+    U8                          ReqBootDeviceForm;      /* 0x1C */
+    U8                          Reserved7;              /* 0x1D */
+    U16                         Reserved8;              /* 0x1E */
+    MPI2_BIOSPAGE2_BOOT_DEVICE  RequestedBootDevice;    /* 0x20 */
+    U8                          ReqAltBootDeviceForm;   /* 0x38 */
+    U8                          Reserved9;              /* 0x39 */
+    U16                         Reserved10;             /* 0x3A */
+    MPI2_BIOSPAGE2_BOOT_DEVICE  RequestedAltBootDevice; /* 0x3C */
+    U8                          CurrentBootDeviceForm;  /* 0x58 */
+    U8                          Reserved11;             /* 0x59 */
+    U16                         Reserved12;             /* 0x5A */
+    MPI2_BIOSPAGE2_BOOT_DEVICE  CurrentBootDevice;      /* 0x58 */
+} MPI2_CONFIG_PAGE_BIOS_2, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_BIOS_2,
+  Mpi2BiosPage2_t, MPI2_POINTER pMpi2BiosPage2_t;
+
+#define MPI2_BIOSPAGE2_PAGEVERSION                      (0x04)
+
+/* values for BIOS Page 2 BootDeviceForm fields */
+#define MPI2_BIOSPAGE2_FORM_MASK                        (0x0F)
+#define MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED         (0x00)
+#define MPI2_BIOSPAGE2_FORM_SAS_WWID                    (0x05)
+#define MPI2_BIOSPAGE2_FORM_ENCLOSURE_SLOT              (0x06)
+#define MPI2_BIOSPAGE2_FORM_DEVICE_NAME                 (0x07)
+
+
+/* BIOS Page 3 */
+
+typedef struct _MPI2_ADAPTER_INFO
+{
+    U8      PciBusNumber;                               /* 0x00 */
+    U8      PciDeviceAndFunctionNumber;                 /* 0x01 */
+    U16     AdapterFlags;                               /* 0x02 */
+} MPI2_ADAPTER_INFO, MPI2_POINTER PTR_MPI2_ADAPTER_INFO,
+  Mpi2AdapterInfo_t, MPI2_POINTER pMpi2AdapterInfo_t;
+
+#define MPI2_ADAPTER_INFO_FLAGS_EMBEDDED                (0x0001)
+#define MPI2_ADAPTER_INFO_FLAGS_INIT_STATUS             (0x0002)
+
+typedef struct _MPI2_CONFIG_PAGE_BIOS_3
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U32                     GlobalFlags;                /* 0x04 */
+    U32                     BiosVersion;                /* 0x08 */
+    MPI2_ADAPTER_INFO       AdapterOrder[4];            /* 0x0C */
+    U32                     Reserved1;                  /* 0x1C */
+} MPI2_CONFIG_PAGE_BIOS_3, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_BIOS_3,
+  Mpi2BiosPage3_t, MPI2_POINTER pMpi2BiosPage3_t;
+
+#define MPI2_BIOSPAGE3_PAGEVERSION                      (0x00)
+
+/* values for BIOS Page 3 GlobalFlags */
+#define MPI2_BIOSPAGE3_FLAGS_PAUSE_ON_ERROR             (0x00000002)
+#define MPI2_BIOSPAGE3_FLAGS_VERBOSE_ENABLE             (0x00000004)
+#define MPI2_BIOSPAGE3_FLAGS_HOOK_INT_40_DISABLE        (0x00000010)
+
+#define MPI2_BIOSPAGE3_FLAGS_DEV_LIST_DISPLAY_MASK      (0x000000E0)
+#define MPI2_BIOSPAGE3_FLAGS_INSTALLED_DEV_DISPLAY      (0x00000000)
+#define MPI2_BIOSPAGE3_FLAGS_ADAPTER_DISPLAY            (0x00000020)
+#define MPI2_BIOSPAGE3_FLAGS_ADAPTER_DEV_DISPLAY        (0x00000040)
+
+
+/* BIOS Page 4 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_BIOS_PAGE_4_PHY_ENTRIES
+#define MPI2_BIOS_PAGE_4_PHY_ENTRIES        (1)
+#endif
+
+typedef struct _MPI2_BIOS4_ENTRY
+{
+    U64                     ReassignmentWWID;       /* 0x00 */
+    U64                     ReassignmentDeviceName; /* 0x08 */
+} MPI2_BIOS4_ENTRY, MPI2_POINTER PTR_MPI2_BIOS4_ENTRY,
+  Mpi2MBios4Entry_t, MPI2_POINTER pMpi2Bios4Entry_t;
+
+typedef struct _MPI2_CONFIG_PAGE_BIOS_4
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                             /* 0x00 */
+    U8                      NumPhys;                            /* 0x04 */
+    U8                      Reserved1;                          /* 0x05 */
+    U16                     Reserved2;                          /* 0x06 */
+    MPI2_BIOS4_ENTRY        Phy[MPI2_BIOS_PAGE_4_PHY_ENTRIES];  /* 0x08 */
+} MPI2_CONFIG_PAGE_BIOS_4, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_BIOS_4,
+  Mpi2BiosPage4_t, MPI2_POINTER pMpi2BiosPage4_t;
+
+#define MPI2_BIOSPAGE4_PAGEVERSION                      (0x01)
+
+
+/****************************************************************************
+*   RAID Volume Config Pages
+****************************************************************************/
+
+/* RAID Volume Page 0 */
+
+typedef struct _MPI2_RAIDVOL0_PHYS_DISK
+{
+    U8                      RAIDSetNum;                 /* 0x00 */
+    U8                      PhysDiskMap;                /* 0x01 */
+    U8                      PhysDiskNum;                /* 0x02 */
+    U8                      Reserved;                   /* 0x03 */
+} MPI2_RAIDVOL0_PHYS_DISK, MPI2_POINTER PTR_MPI2_RAIDVOL0_PHYS_DISK,
+  Mpi2RaidVol0PhysDisk_t, MPI2_POINTER pMpi2RaidVol0PhysDisk_t;
+
+/* defines for the PhysDiskMap field */
+#define MPI2_RAIDVOL0_PHYSDISK_PRIMARY                  (0x01)
+#define MPI2_RAIDVOL0_PHYSDISK_SECONDARY                (0x02)
+
+typedef struct _MPI2_RAIDVOL0_SETTINGS
+{
+    U16                     Settings;                   /* 0x00 */
+    U8                      HotSparePool;               /* 0x01 */
+    U8                      Reserved;                   /* 0x02 */
+} MPI2_RAIDVOL0_SETTINGS, MPI2_POINTER PTR_MPI2_RAIDVOL0_SETTINGS,
+  Mpi2RaidVol0Settings_t, MPI2_POINTER pMpi2RaidVol0Settings_t;
+
+/* RAID Volume Page 0 HotSparePool defines, also used in RAID Physical Disk */
+#define MPI2_RAID_HOT_SPARE_POOL_0                      (0x01)
+#define MPI2_RAID_HOT_SPARE_POOL_1                      (0x02)
+#define MPI2_RAID_HOT_SPARE_POOL_2                      (0x04)
+#define MPI2_RAID_HOT_SPARE_POOL_3                      (0x08)
+#define MPI2_RAID_HOT_SPARE_POOL_4                      (0x10)
+#define MPI2_RAID_HOT_SPARE_POOL_5                      (0x20)
+#define MPI2_RAID_HOT_SPARE_POOL_6                      (0x40)
+#define MPI2_RAID_HOT_SPARE_POOL_7                      (0x80)
+
+/* RAID Volume Page 0 VolumeSettings defines */
+#define MPI2_RAIDVOL0_SETTING_USE_PRODUCT_ID_SUFFIX     (0x0008)
+#define MPI2_RAIDVOL0_SETTING_AUTO_CONFIG_HSWAP_DISABLE (0x0004)
+
+#define MPI2_RAIDVOL0_SETTING_MASK_WRITE_CACHING        (0x0003)
+#define MPI2_RAIDVOL0_SETTING_UNCHANGED                 (0x0000)
+#define MPI2_RAIDVOL0_SETTING_DISABLE_WRITE_CACHING     (0x0001)
+#define MPI2_RAIDVOL0_SETTING_ENABLE_WRITE_CACHING      (0x0002)
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength at runtime.
+ */
+#ifndef MPI2_RAID_VOL_PAGE_0_PHYSDISK_MAX
+#define MPI2_RAID_VOL_PAGE_0_PHYSDISK_MAX       (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_RAID_VOL_0
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U16                     DevHandle;                  /* 0x04 */
+    U8                      VolumeState;                /* 0x06 */
+    U8                      VolumeType;                 /* 0x07 */
+    U32                     VolumeStatusFlags;          /* 0x08 */
+    MPI2_RAIDVOL0_SETTINGS  VolumeSettings;             /* 0x0C */
+    U64                     MaxLBA;                     /* 0x10 */
+    U32                     StripeSize;                 /* 0x18 */
+    U16                     BlockSize;                  /* 0x1C */
+    U16                     Reserved1;                  /* 0x1E */
+    U8                      SupportedPhysDisks;         /* 0x20 */
+    U8                      ResyncRate;                 /* 0x21 */
+    U16                     DataScrubDuration;          /* 0x22 */
+    U8                      NumPhysDisks;               /* 0x24 */
+    U8                      Reserved2;                  /* 0x25 */
+    U8                      Reserved3;                  /* 0x26 */
+    U8                      InactiveStatus;             /* 0x27 */
+    MPI2_RAIDVOL0_PHYS_DISK PhysDisk[MPI2_RAID_VOL_PAGE_0_PHYSDISK_MAX]; /* 0x28 */
+} MPI2_CONFIG_PAGE_RAID_VOL_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_RAID_VOL_0,
+  Mpi2RaidVolPage0_t, MPI2_POINTER pMpi2RaidVolPage0_t;
+
+#define MPI2_RAIDVOLPAGE0_PAGEVERSION           (0x0A)
+
+/* values for RAID VolumeState */
+#define MPI2_RAID_VOL_STATE_MISSING                         (0x00)
+#define MPI2_RAID_VOL_STATE_FAILED                          (0x01)
+#define MPI2_RAID_VOL_STATE_INITIALIZING                    (0x02)
+#define MPI2_RAID_VOL_STATE_ONLINE                          (0x03)
+#define MPI2_RAID_VOL_STATE_DEGRADED                        (0x04)
+#define MPI2_RAID_VOL_STATE_OPTIMAL                         (0x05)
+
+/* values for RAID VolumeType */
+#define MPI2_RAID_VOL_TYPE_RAID0                            (0x00)
+#define MPI2_RAID_VOL_TYPE_RAID1E                           (0x01)
+#define MPI2_RAID_VOL_TYPE_RAID1                            (0x02)
+#define MPI2_RAID_VOL_TYPE_RAID10                           (0x05)
+#define MPI2_RAID_VOL_TYPE_UNKNOWN                          (0xFF)
+
+/* values for RAID Volume Page 0 VolumeStatusFlags field */
+#define MPI2_RAIDVOL0_STATUS_FLAG_PENDING_RESYNC            (0x02000000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_BACKG_INIT_PENDING        (0x01000000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_MDC_PENDING               (0x00800000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_USER_CONSIST_PENDING      (0x00400000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_MAKE_DATA_CONSISTENT      (0x00200000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_DATA_SCRUB                (0x00100000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_CONSISTENCY_CHECK         (0x00080000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_CAPACITY_EXPANSION        (0x00040000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_BACKGROUND_INIT           (0x00020000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_RESYNC_IN_PROGRESS        (0x00010000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_OCE_ALLOWED               (0x00000040)
+#define MPI2_RAIDVOL0_STATUS_FLAG_BGI_COMPLETE              (0x00000020)
+#define MPI2_RAIDVOL0_STATUS_FLAG_1E_OFFSET_MIRROR          (0x00000000)
+#define MPI2_RAIDVOL0_STATUS_FLAG_1E_ADJACENT_MIRROR        (0x00000010)
+#define MPI2_RAIDVOL0_STATUS_FLAG_BAD_BLOCK_TABLE_FULL      (0x00000008)
+#define MPI2_RAIDVOL0_STATUS_FLAG_VOLUME_INACTIVE           (0x00000004)
+#define MPI2_RAIDVOL0_STATUS_FLAG_QUIESCED                  (0x00000002)
+#define MPI2_RAIDVOL0_STATUS_FLAG_ENABLED                   (0x00000001)
+
+/* values for RAID Volume Page 0 SupportedPhysDisks field */
+#define MPI2_RAIDVOL0_SUPPORT_SOLID_STATE_DISKS             (0x08)
+#define MPI2_RAIDVOL0_SUPPORT_HARD_DISKS                    (0x04)
+#define MPI2_RAIDVOL0_SUPPORT_SAS_PROTOCOL                  (0x02)
+#define MPI2_RAIDVOL0_SUPPORT_SATA_PROTOCOL                 (0x01)
+
+/* values for RAID Volume Page 0 InactiveStatus field */
+#define MPI2_RAIDVOLPAGE0_UNKNOWN_INACTIVE                  (0x00)
+#define MPI2_RAIDVOLPAGE0_STALE_METADATA_INACTIVE           (0x01)
+#define MPI2_RAIDVOLPAGE0_FOREIGN_VOLUME_INACTIVE           (0x02)
+#define MPI2_RAIDVOLPAGE0_INSUFFICIENT_RESOURCE_INACTIVE    (0x03)
+#define MPI2_RAIDVOLPAGE0_CLONE_VOLUME_INACTIVE             (0x04)
+#define MPI2_RAIDVOLPAGE0_INSUFFICIENT_METADATA_INACTIVE    (0x05)
+#define MPI2_RAIDVOLPAGE0_PREVIOUSLY_DELETED                (0x06)
+
+
+/* RAID Volume Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_RAID_VOL_1
+{
+    MPI2_CONFIG_PAGE_HEADER Header;                     /* 0x00 */
+    U16                     DevHandle;                  /* 0x04 */
+    U16                     Reserved0;                  /* 0x06 */
+    U8                      GUID[24];                   /* 0x08 */
+    U8                      Name[16];                   /* 0x20 */
+    U64                     WWID;                       /* 0x30 */
+    U32                     Reserved1;                  /* 0x38 */
+    U32                     Reserved2;                  /* 0x3C */
+} MPI2_CONFIG_PAGE_RAID_VOL_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_RAID_VOL_1,
+  Mpi2RaidVolPage1_t, MPI2_POINTER pMpi2RaidVolPage1_t;
+
+#define MPI2_RAIDVOLPAGE1_PAGEVERSION           (0x03)
+
+
+/****************************************************************************
+*   RAID Physical Disk Config Pages
+****************************************************************************/
+
+/* RAID Physical Disk Page 0 */
+
+typedef struct _MPI2_RAIDPHYSDISK0_SETTINGS
+{
+    U16                     Reserved1;                  /* 0x00 */
+    U8                      HotSparePool;               /* 0x02 */
+    U8                      Reserved2;                  /* 0x03 */
+} MPI2_RAIDPHYSDISK0_SETTINGS, MPI2_POINTER PTR_MPI2_RAIDPHYSDISK0_SETTINGS,
+  Mpi2RaidPhysDisk0Settings_t, MPI2_POINTER pMpi2RaidPhysDisk0Settings_t;
+
+/* use MPI2_RAID_HOT_SPARE_POOL_ defines for the HotSparePool field */
+
+typedef struct _MPI2_RAIDPHYSDISK0_INQUIRY_DATA
+{
+    U8                      VendorID[8];                /* 0x00 */
+    U8                      ProductID[16];              /* 0x08 */
+    U8                      ProductRevLevel[4];         /* 0x18 */
+    U8                      SerialNum[32];              /* 0x1C */
+} MPI2_RAIDPHYSDISK0_INQUIRY_DATA,
+  MPI2_POINTER PTR_MPI2_RAIDPHYSDISK0_INQUIRY_DATA,
+  Mpi2RaidPhysDisk0InquiryData_t, MPI2_POINTER pMpi2RaidPhysDisk0InquiryData_t;
+
+typedef struct _MPI2_CONFIG_PAGE_RD_PDISK_0
+{
+    MPI2_CONFIG_PAGE_HEADER         Header;                     /* 0x00 */
+    U16                             DevHandle;                  /* 0x04 */
+    U8                              Reserved1;                  /* 0x06 */
+    U8                              PhysDiskNum;                /* 0x07 */
+    MPI2_RAIDPHYSDISK0_SETTINGS     PhysDiskSettings;           /* 0x08 */
+    U32                             Reserved2;                  /* 0x0C */
+    MPI2_RAIDPHYSDISK0_INQUIRY_DATA InquiryData;                /* 0x10 */
+    U32                             Reserved3;                  /* 0x4C */
+    U8                              PhysDiskState;              /* 0x50 */
+    U8                              OfflineReason;              /* 0x51 */
+    U8                              IncompatibleReason;         /* 0x52 */
+    U8                              PhysDiskAttributes;         /* 0x53 */
+    U32                             PhysDiskStatusFlags;        /* 0x54 */
+    U64                             DeviceMaxLBA;               /* 0x58 */
+    U64                             HostMaxLBA;                 /* 0x60 */
+    U64                             CoercedMaxLBA;              /* 0x68 */
+    U16                             BlockSize;                  /* 0x70 */
+    U16                             Reserved5;                  /* 0x72 */
+    U32                             Reserved6;                  /* 0x74 */
+} MPI2_CONFIG_PAGE_RD_PDISK_0,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_RD_PDISK_0,
+  Mpi2RaidPhysDiskPage0_t, MPI2_POINTER pMpi2RaidPhysDiskPage0_t;
+
+#define MPI2_RAIDPHYSDISKPAGE0_PAGEVERSION          (0x05)
+
+/* PhysDiskState defines */
+#define MPI2_RAID_PD_STATE_NOT_CONFIGURED               (0x00)
+#define MPI2_RAID_PD_STATE_NOT_COMPATIBLE               (0x01)
+#define MPI2_RAID_PD_STATE_OFFLINE                      (0x02)
+#define MPI2_RAID_PD_STATE_ONLINE                       (0x03)
+#define MPI2_RAID_PD_STATE_HOT_SPARE                    (0x04)
+#define MPI2_RAID_PD_STATE_DEGRADED                     (0x05)
+#define MPI2_RAID_PD_STATE_REBUILDING                   (0x06)
+#define MPI2_RAID_PD_STATE_OPTIMAL                      (0x07)
+
+/* OfflineReason defines */
+#define MPI2_PHYSDISK0_ONLINE                           (0x00)
+#define MPI2_PHYSDISK0_OFFLINE_MISSING                  (0x01)
+#define MPI2_PHYSDISK0_OFFLINE_FAILED                   (0x03)
+#define MPI2_PHYSDISK0_OFFLINE_INITIALIZING             (0x04)
+#define MPI2_PHYSDISK0_OFFLINE_REQUESTED                (0x05)
+#define MPI2_PHYSDISK0_OFFLINE_FAILED_REQUESTED         (0x06)
+#define MPI2_PHYSDISK0_OFFLINE_OTHER                    (0xFF)
+
+/* IncompatibleReason defines */
+#define MPI2_PHYSDISK0_COMPATIBLE                       (0x00)
+#define MPI2_PHYSDISK0_INCOMPATIBLE_PROTOCOL            (0x01)
+#define MPI2_PHYSDISK0_INCOMPATIBLE_BLOCKSIZE           (0x02)
+#define MPI2_PHYSDISK0_INCOMPATIBLE_MAX_LBA             (0x03)
+#define MPI2_PHYSDISK0_INCOMPATIBLE_SATA_EXTENDED_CMD   (0x04)
+#define MPI2_PHYSDISK0_INCOMPATIBLE_REMOVEABLE_MEDIA    (0x05)
+#define MPI2_PHYSDISK0_INCOMPATIBLE_UNKNOWN             (0xFF)
+
+/* PhysDiskAttributes defines */
+#define MPI2_PHYSDISK0_ATTRIB_SOLID_STATE_DRIVE         (0x08)
+#define MPI2_PHYSDISK0_ATTRIB_HARD_DISK_DRIVE           (0x04)
+#define MPI2_PHYSDISK0_ATTRIB_SAS_PROTOCOL              (0x02)
+#define MPI2_PHYSDISK0_ATTRIB_SATA_PROTOCOL             (0x01)
+
+/* PhysDiskStatusFlags defines */
+#define MPI2_PHYSDISK0_STATUS_FLAG_NOT_CERTIFIED        (0x00000040)
+#define MPI2_PHYSDISK0_STATUS_FLAG_OCE_TARGET           (0x00000020)
+#define MPI2_PHYSDISK0_STATUS_FLAG_WRITE_CACHE_ENABLED  (0x00000010)
+#define MPI2_PHYSDISK0_STATUS_FLAG_OPTIMAL_PREVIOUS     (0x00000000)
+#define MPI2_PHYSDISK0_STATUS_FLAG_NOT_OPTIMAL_PREVIOUS (0x00000008)
+#define MPI2_PHYSDISK0_STATUS_FLAG_INACTIVE_VOLUME      (0x00000004)
+#define MPI2_PHYSDISK0_STATUS_FLAG_QUIESCED             (0x00000002)
+#define MPI2_PHYSDISK0_STATUS_FLAG_OUT_OF_SYNC          (0x00000001)
+
+
+/* RAID Physical Disk Page 1 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.PageLength or NumPhysDiskPaths at runtime.
+ */
+#ifndef MPI2_RAID_PHYS_DISK1_PATH_MAX
+#define MPI2_RAID_PHYS_DISK1_PATH_MAX   (1)
+#endif
+
+typedef struct _MPI2_RAIDPHYSDISK1_PATH
+{
+    U16             DevHandle;          /* 0x00 */
+    U16             Reserved1;          /* 0x02 */
+    U64             WWID;               /* 0x04 */
+    U64             OwnerWWID;          /* 0x0C */
+    U8              OwnerIdentifier;    /* 0x14 */
+    U8              Reserved2;          /* 0x15 */
+    U16             Flags;              /* 0x16 */
+} MPI2_RAIDPHYSDISK1_PATH, MPI2_POINTER PTR_MPI2_RAIDPHYSDISK1_PATH,
+  Mpi2RaidPhysDisk1Path_t, MPI2_POINTER pMpi2RaidPhysDisk1Path_t;
+
+/* RAID Physical Disk Page 1 Physical Disk Path Flags field defines */
+#define MPI2_RAID_PHYSDISK1_FLAG_PRIMARY        (0x0004)
+#define MPI2_RAID_PHYSDISK1_FLAG_BROKEN         (0x0002)
+#define MPI2_RAID_PHYSDISK1_FLAG_INVALID        (0x0001)
+
+typedef struct _MPI2_CONFIG_PAGE_RD_PDISK_1
+{
+    MPI2_CONFIG_PAGE_HEADER         Header;                     /* 0x00 */
+    U8                              NumPhysDiskPaths;           /* 0x04 */
+    U8                              PhysDiskNum;                /* 0x05 */
+    U16                             Reserved1;                  /* 0x06 */
+    U32                             Reserved2;                  /* 0x08 */
+    MPI2_RAIDPHYSDISK1_PATH         PhysicalDiskPath[MPI2_RAID_PHYS_DISK1_PATH_MAX];/* 0x0C */
+} MPI2_CONFIG_PAGE_RD_PDISK_1,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_RD_PDISK_1,
+  Mpi2RaidPhysDiskPage1_t, MPI2_POINTER pMpi2RaidPhysDiskPage1_t;
+
+#define MPI2_RAIDPHYSDISKPAGE1_PAGEVERSION          (0x02)
+
+
+/****************************************************************************
+*   values for fields used by several types of SAS Config Pages
+****************************************************************************/
+
+/* values for NegotiatedLinkRates fields */
+#define MPI2_SAS_NEG_LINK_RATE_MASK_LOGICAL             (0xF0)
+#define MPI2_SAS_NEG_LINK_RATE_SHIFT_LOGICAL            (4)
+#define MPI2_SAS_NEG_LINK_RATE_MASK_PHYSICAL            (0x0F)
+/* link rates used for Negotiated Physical and Logical Link Rate */
+#define MPI2_SAS_NEG_LINK_RATE_UNKNOWN_LINK_RATE        (0x00)
+#define MPI2_SAS_NEG_LINK_RATE_PHY_DISABLED             (0x01)
+#define MPI2_SAS_NEG_LINK_RATE_NEGOTIATION_FAILED       (0x02)
+#define MPI2_SAS_NEG_LINK_RATE_SATA_OOB_COMPLETE        (0x03)
+#define MPI2_SAS_NEG_LINK_RATE_PORT_SELECTOR            (0x04)
+#define MPI2_SAS_NEG_LINK_RATE_SMP_RESET_IN_PROGRESS    (0x05)
+#define MPI2_SAS_NEG_LINK_RATE_1_5                      (0x08)
+#define MPI2_SAS_NEG_LINK_RATE_3_0                      (0x09)
+#define MPI2_SAS_NEG_LINK_RATE_6_0                      (0x0A)
+
+
+/* values for AttachedPhyInfo fields */
+#define MPI2_SAS_APHYINFO_INSIDE_ZPSDS_PERSISTENT       (0x00000040)
+#define MPI2_SAS_APHYINFO_REQUESTED_INSIDE_ZPSDS        (0x00000020)
+#define MPI2_SAS_APHYINFO_BREAK_REPLY_CAPABLE           (0x00000010)
+
+#define MPI2_SAS_APHYINFO_REASON_MASK                   (0x0000000F)
+#define MPI2_SAS_APHYINFO_REASON_UNKNOWN                (0x00000000)
+#define MPI2_SAS_APHYINFO_REASON_POWER_ON               (0x00000001)
+#define MPI2_SAS_APHYINFO_REASON_HARD_RESET             (0x00000002)
+#define MPI2_SAS_APHYINFO_REASON_SMP_PHY_CONTROL        (0x00000003)
+#define MPI2_SAS_APHYINFO_REASON_LOSS_OF_SYNC           (0x00000004)
+#define MPI2_SAS_APHYINFO_REASON_MULTIPLEXING_SEQ       (0x00000005)
+#define MPI2_SAS_APHYINFO_REASON_IT_NEXUS_LOSS_TIMER    (0x00000006)
+#define MPI2_SAS_APHYINFO_REASON_BREAK_TIMEOUT          (0x00000007)
+#define MPI2_SAS_APHYINFO_REASON_PHY_TEST_STOPPED       (0x00000008)
+
+
+/* values for PhyInfo fields */
+#define MPI2_SAS_PHYINFO_PHY_VACANT                     (0x80000000)
+
+#define MPI2_SAS_PHYINFO_PHY_POWER_CONDITION_MASK       (0x18000000)
+#define MPI2_SAS_PHYINFO_PHY_POWER_ACTIVE               (0x00000000)
+#define MPI2_SAS_PHYINFO_PHY_POWER_PARTIAL              (0x08000000)
+#define MPI2_SAS_PHYINFO_PHY_POWER_SLUMBER              (0x10000000)
+
+#define MPI2_SAS_PHYINFO_CHANGED_REQ_INSIDE_ZPSDS       (0x04000000)
+#define MPI2_SAS_PHYINFO_INSIDE_ZPSDS_PERSISTENT        (0x02000000)
+#define MPI2_SAS_PHYINFO_REQ_INSIDE_ZPSDS               (0x01000000)
+#define MPI2_SAS_PHYINFO_ZONE_GROUP_PERSISTENT          (0x00400000)
+#define MPI2_SAS_PHYINFO_INSIDE_ZPSDS                   (0x00200000)
+#define MPI2_SAS_PHYINFO_ZONING_ENABLED                 (0x00100000)
+
+#define MPI2_SAS_PHYINFO_REASON_MASK                    (0x000F0000)
+#define MPI2_SAS_PHYINFO_REASON_UNKNOWN                 (0x00000000)
+#define MPI2_SAS_PHYINFO_REASON_POWER_ON                (0x00010000)
+#define MPI2_SAS_PHYINFO_REASON_HARD_RESET              (0x00020000)
+#define MPI2_SAS_PHYINFO_REASON_SMP_PHY_CONTROL         (0x00030000)
+#define MPI2_SAS_PHYINFO_REASON_LOSS_OF_SYNC            (0x00040000)
+#define MPI2_SAS_PHYINFO_REASON_MULTIPLEXING_SEQ        (0x00050000)
+#define MPI2_SAS_PHYINFO_REASON_IT_NEXUS_LOSS_TIMER     (0x00060000)
+#define MPI2_SAS_PHYINFO_REASON_BREAK_TIMEOUT           (0x00070000)
+#define MPI2_SAS_PHYINFO_REASON_PHY_TEST_STOPPED        (0x00080000)
+
+#define MPI2_SAS_PHYINFO_MULTIPLEXING_SUPPORTED         (0x00008000)
+#define MPI2_SAS_PHYINFO_SATA_PORT_ACTIVE               (0x00004000)
+#define MPI2_SAS_PHYINFO_SATA_PORT_SELECTOR_PRESENT     (0x00002000)
+#define MPI2_SAS_PHYINFO_VIRTUAL_PHY                    (0x00001000)
+
+#define MPI2_SAS_PHYINFO_MASK_PARTIAL_PATHWAY_TIME      (0x00000F00)
+#define MPI2_SAS_PHYINFO_SHIFT_PARTIAL_PATHWAY_TIME     (8)
+
+#define MPI2_SAS_PHYINFO_MASK_ROUTING_ATTRIBUTE         (0x000000F0)
+#define MPI2_SAS_PHYINFO_DIRECT_ROUTING                 (0x00000000)
+#define MPI2_SAS_PHYINFO_SUBTRACTIVE_ROUTING            (0x00000010)
+#define MPI2_SAS_PHYINFO_TABLE_ROUTING                  (0x00000020)
+
+
+/* values for SAS ProgrammedLinkRate fields */
+#define MPI2_SAS_PRATE_MAX_RATE_MASK                    (0xF0)
+#define MPI2_SAS_PRATE_MAX_RATE_NOT_PROGRAMMABLE        (0x00)
+#define MPI2_SAS_PRATE_MAX_RATE_1_5                     (0x80)
+#define MPI2_SAS_PRATE_MAX_RATE_3_0                     (0x90)
+#define MPI2_SAS_PRATE_MAX_RATE_6_0                     (0xA0)
+#define MPI2_SAS_PRATE_MIN_RATE_MASK                    (0x0F)
+#define MPI2_SAS_PRATE_MIN_RATE_NOT_PROGRAMMABLE        (0x00)
+#define MPI2_SAS_PRATE_MIN_RATE_1_5                     (0x08)
+#define MPI2_SAS_PRATE_MIN_RATE_3_0                     (0x09)
+#define MPI2_SAS_PRATE_MIN_RATE_6_0                     (0x0A)
+
+
+/* values for SAS HwLinkRate fields */
+#define MPI2_SAS_HWRATE_MAX_RATE_MASK                   (0xF0)
+#define MPI2_SAS_HWRATE_MAX_RATE_1_5                    (0x80)
+#define MPI2_SAS_HWRATE_MAX_RATE_3_0                    (0x90)
+#define MPI2_SAS_HWRATE_MAX_RATE_6_0                    (0xA0)
+#define MPI2_SAS_HWRATE_MIN_RATE_MASK                   (0x0F)
+#define MPI2_SAS_HWRATE_MIN_RATE_1_5                    (0x08)
+#define MPI2_SAS_HWRATE_MIN_RATE_3_0                    (0x09)
+#define MPI2_SAS_HWRATE_MIN_RATE_6_0                    (0x0A)
+
+
+
+/****************************************************************************
+*   SAS IO Unit Config Pages
+****************************************************************************/
+
+/* SAS IO Unit Page 0 */
+
+typedef struct _MPI2_SAS_IO_UNIT0_PHY_DATA
+{
+    U8          Port;                   /* 0x00 */
+    U8          PortFlags;              /* 0x01 */
+    U8          PhyFlags;               /* 0x02 */
+    U8          NegotiatedLinkRate;     /* 0x03 */
+    U32         ControllerPhyDeviceInfo;/* 0x04 */
+    U16         AttachedDevHandle;      /* 0x08 */
+    U16         ControllerDevHandle;    /* 0x0A */
+    U32         DiscoveryStatus;        /* 0x0C */
+    U32         Reserved;               /* 0x10 */
+} MPI2_SAS_IO_UNIT0_PHY_DATA, MPI2_POINTER PTR_MPI2_SAS_IO_UNIT0_PHY_DATA,
+  Mpi2SasIOUnit0PhyData_t, MPI2_POINTER pMpi2SasIOUnit0PhyData_t;
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_SAS_IOUNIT0_PHY_MAX
+#define MPI2_SAS_IOUNIT0_PHY_MAX        (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_SASIOUNIT_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                             /* 0x00 */
+    U32                                 Reserved1;                          /* 0x08 */
+    U8                                  NumPhys;                            /* 0x0C */
+    U8                                  Reserved2;                          /* 0x0D */
+    U16                                 Reserved3;                          /* 0x0E */
+    MPI2_SAS_IO_UNIT0_PHY_DATA          PhyData[MPI2_SAS_IOUNIT0_PHY_MAX];  /* 0x10 */
+} MPI2_CONFIG_PAGE_SASIOUNIT_0,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SASIOUNIT_0,
+  Mpi2SasIOUnitPage0_t, MPI2_POINTER pMpi2SasIOUnitPage0_t;
+
+#define MPI2_SASIOUNITPAGE0_PAGEVERSION                     (0x05)
+
+/* values for SAS IO Unit Page 0 PortFlags */
+#define MPI2_SASIOUNIT0_PORTFLAGS_DISCOVERY_IN_PROGRESS     (0x08)
+#define MPI2_SASIOUNIT0_PORTFLAGS_AUTO_PORT_CONFIG          (0x01)
+
+/* values for SAS IO Unit Page 0 PhyFlags */
+#define MPI2_SASIOUNIT0_PHYFLAGS_ZONING_ENABLED             (0x10)
+#define MPI2_SASIOUNIT0_PHYFLAGS_PHY_DISABLED               (0x08)
+
+/* use MPI2_SAS_NEG_LINK_RATE_ defines for the NegotiatedLinkRate field */
+
+/* see mpi2_sas.h for values for SAS IO Unit Page 0 ControllerPhyDeviceInfo values */
+
+/* values for SAS IO Unit Page 0 DiscoveryStatus */
+#define MPI2_SASIOUNIT0_DS_MAX_ENCLOSURES_EXCEED            (0x80000000)
+#define MPI2_SASIOUNIT0_DS_MAX_EXPANDERS_EXCEED             (0x40000000)
+#define MPI2_SASIOUNIT0_DS_MAX_DEVICES_EXCEED               (0x20000000)
+#define MPI2_SASIOUNIT0_DS_MAX_TOPO_PHYS_EXCEED             (0x10000000)
+#define MPI2_SASIOUNIT0_DS_DOWNSTREAM_INITIATOR             (0x08000000)
+#define MPI2_SASIOUNIT0_DS_MULTI_SUBTRACTIVE_SUBTRACTIVE    (0x00008000)
+#define MPI2_SASIOUNIT0_DS_EXP_MULTI_SUBTRACTIVE            (0x00004000)
+#define MPI2_SASIOUNIT0_DS_MULTI_PORT_DOMAIN                (0x00002000)
+#define MPI2_SASIOUNIT0_DS_TABLE_TO_SUBTRACTIVE_LINK        (0x00001000)
+#define MPI2_SASIOUNIT0_DS_UNSUPPORTED_DEVICE               (0x00000800)
+#define MPI2_SASIOUNIT0_DS_TABLE_LINK                       (0x00000400)
+#define MPI2_SASIOUNIT0_DS_SUBTRACTIVE_LINK                 (0x00000200)
+#define MPI2_SASIOUNIT0_DS_SMP_CRC_ERROR                    (0x00000100)
+#define MPI2_SASIOUNIT0_DS_SMP_FUNCTION_FAILED              (0x00000080)
+#define MPI2_SASIOUNIT0_DS_INDEX_NOT_EXIST                  (0x00000040)
+#define MPI2_SASIOUNIT0_DS_OUT_ROUTE_ENTRIES                (0x00000020)
+#define MPI2_SASIOUNIT0_DS_SMP_TIMEOUT                      (0x00000010)
+#define MPI2_SASIOUNIT0_DS_MULTIPLE_PORTS                   (0x00000004)
+#define MPI2_SASIOUNIT0_DS_UNADDRESSABLE_DEVICE             (0x00000002)
+#define MPI2_SASIOUNIT0_DS_LOOP_DETECTED                    (0x00000001)
+
+
+/* SAS IO Unit Page 1 */
+
+typedef struct _MPI2_SAS_IO_UNIT1_PHY_DATA
+{
+    U8          Port;                       /* 0x00 */
+    U8          PortFlags;                  /* 0x01 */
+    U8          PhyFlags;                   /* 0x02 */
+    U8          MaxMinLinkRate;             /* 0x03 */
+    U32         ControllerPhyDeviceInfo;    /* 0x04 */
+    U16         MaxTargetPortConnectTime;   /* 0x08 */
+    U16         Reserved1;                  /* 0x0A */
+} MPI2_SAS_IO_UNIT1_PHY_DATA, MPI2_POINTER PTR_MPI2_SAS_IO_UNIT1_PHY_DATA,
+  Mpi2SasIOUnit1PhyData_t, MPI2_POINTER pMpi2SasIOUnit1PhyData_t;
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_SAS_IOUNIT1_PHY_MAX
+#define MPI2_SAS_IOUNIT1_PHY_MAX        (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_SASIOUNIT_1
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                             /* 0x00 */
+    U16                                 ControlFlags;                       /* 0x08 */
+    U16                                 SASNarrowMaxQueueDepth;             /* 0x0A */
+    U16                                 AdditionalControlFlags;             /* 0x0C */
+    U16                                 SASWideMaxQueueDepth;               /* 0x0E */
+    U8                                  NumPhys;                            /* 0x10 */
+    U8                                  SATAMaxQDepth;                      /* 0x11 */
+    U8                                  ReportDeviceMissingDelay;           /* 0x12 */
+    U8                                  IODeviceMissingDelay;               /* 0x13 */
+    MPI2_SAS_IO_UNIT1_PHY_DATA          PhyData[MPI2_SAS_IOUNIT1_PHY_MAX];  /* 0x14 */
+} MPI2_CONFIG_PAGE_SASIOUNIT_1,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SASIOUNIT_1,
+  Mpi2SasIOUnitPage1_t, MPI2_POINTER pMpi2SasIOUnitPage1_t;
+
+#define MPI2_SASIOUNITPAGE1_PAGEVERSION     (0x09)
+
+/* values for SAS IO Unit Page 1 ControlFlags */
+#define MPI2_SASIOUNIT1_CONTROL_DEVICE_SELF_TEST                    (0x8000)
+#define MPI2_SASIOUNIT1_CONTROL_SATA_3_0_MAX                        (0x4000)
+#define MPI2_SASIOUNIT1_CONTROL_SATA_1_5_MAX                        (0x2000)
+#define MPI2_SASIOUNIT1_CONTROL_SATA_SW_PRESERVE                    (0x1000)
+
+#define MPI2_SASIOUNIT1_CONTROL_MASK_DEV_SUPPORT                    (0x0600)
+#define MPI2_SASIOUNIT1_CONTROL_SHIFT_DEV_SUPPORT                   (9)
+#define MPI2_SASIOUNIT1_CONTROL_DEV_SUPPORT_BOTH                    (0x0)
+#define MPI2_SASIOUNIT1_CONTROL_DEV_SAS_SUPPORT                     (0x1)
+#define MPI2_SASIOUNIT1_CONTROL_DEV_SATA_SUPPORT                    (0x2)
+
+#define MPI2_SASIOUNIT1_CONTROL_SATA_48BIT_LBA_REQUIRED             (0x0080)
+#define MPI2_SASIOUNIT1_CONTROL_SATA_SMART_REQUIRED                 (0x0040)
+#define MPI2_SASIOUNIT1_CONTROL_SATA_NCQ_REQUIRED                   (0x0020)
+#define MPI2_SASIOUNIT1_CONTROL_SATA_FUA_REQUIRED                   (0x0010)
+#define MPI2_SASIOUNIT1_CONTROL_TABLE_SUBTRACTIVE_ILLEGAL           (0x0008)
+#define MPI2_SASIOUNIT1_CONTROL_SUBTRACTIVE_ILLEGAL                 (0x0004)
+#define MPI2_SASIOUNIT1_CONTROL_FIRST_LVL_DISC_ONLY                 (0x0002)
+#define MPI2_SASIOUNIT1_CONTROL_CLEAR_AFFILIATION                   (0x0001)
+
+/* values for SAS IO Unit Page 1 AdditionalControlFlags */
+#define MPI2_SASIOUNIT1_ACONTROL_MULTI_PORT_DOMAIN_ILLEGAL          (0x0080)
+#define MPI2_SASIOUNIT1_ACONTROL_SATA_ASYNCHROUNOUS_NOTIFICATION    (0x0040)
+#define MPI2_SASIOUNIT1_ACONTROL_INVALID_TOPOLOGY_CORRECTION        (0x0020)
+#define MPI2_SASIOUNIT1_ACONTROL_PORT_ENABLE_ONLY_SATA_LINK_RESET   (0x0010)
+#define MPI2_SASIOUNIT1_ACONTROL_OTHER_AFFILIATION_SATA_LINK_RESET  (0x0008)
+#define MPI2_SASIOUNIT1_ACONTROL_SELF_AFFILIATION_SATA_LINK_RESET   (0x0004)
+#define MPI2_SASIOUNIT1_ACONTROL_NO_AFFILIATION_SATA_LINK_RESET     (0x0002)
+#define MPI2_SASIOUNIT1_ACONTROL_ALLOW_TABLE_TO_TABLE               (0x0001)
+
+/* defines for SAS IO Unit Page 1 ReportDeviceMissingDelay */
+#define MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK                 (0x7F)
+#define MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16                      (0x80)
+
+/* values for SAS IO Unit Page 1 PortFlags */
+#define MPI2_SASIOUNIT1_PORT_FLAGS_AUTO_PORT_CONFIG                 (0x01)
+
+/* values for SAS IO Unit Page 1 PhyFlags */
+#define MPI2_SASIOUNIT1_PHYFLAGS_ZONING_ENABLE                      (0x10)
+#define MPI2_SASIOUNIT1_PHYFLAGS_PHY_DISABLE                        (0x08)
+
+/* values for SAS IO Unit Page 1 MaxMinLinkRate */
+#define MPI2_SASIOUNIT1_MAX_RATE_MASK                               (0xF0)
+#define MPI2_SASIOUNIT1_MAX_RATE_1_5                                (0x80)
+#define MPI2_SASIOUNIT1_MAX_RATE_3_0                                (0x90)
+#define MPI2_SASIOUNIT1_MAX_RATE_6_0                                (0xA0)
+#define MPI2_SASIOUNIT1_MIN_RATE_MASK                               (0x0F)
+#define MPI2_SASIOUNIT1_MIN_RATE_1_5                                (0x08)
+#define MPI2_SASIOUNIT1_MIN_RATE_3_0                                (0x09)
+#define MPI2_SASIOUNIT1_MIN_RATE_6_0                                (0x0A)
+
+/* see mpi2_sas.h for values for SAS IO Unit Page 1 ControllerPhyDeviceInfo values */
+
+
+/* SAS IO Unit Page 4 */
+
+typedef struct _MPI2_SAS_IOUNIT4_SPINUP_GROUP
+{
+    U8          MaxTargetSpinup;            /* 0x00 */
+    U8          SpinupDelay;                /* 0x01 */
+    U16         Reserved1;                  /* 0x02 */
+} MPI2_SAS_IOUNIT4_SPINUP_GROUP, MPI2_POINTER PTR_MPI2_SAS_IOUNIT4_SPINUP_GROUP,
+  Mpi2SasIOUnit4SpinupGroup_t, MPI2_POINTER pMpi2SasIOUnit4SpinupGroup_t;
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * four and check Header.ExtPageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_SAS_IOUNIT4_PHY_MAX
+#define MPI2_SAS_IOUNIT4_PHY_MAX        (4)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_SASIOUNIT_4
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                         /* 0x00 */
+    MPI2_SAS_IOUNIT4_SPINUP_GROUP       SpinupGroupParameters[4];       /* 0x08 */
+    U32                                 Reserved1;                      /* 0x18 */
+    U32                                 Reserved2;                      /* 0x1C */
+    U32                                 Reserved3;                      /* 0x20 */
+    U8                                  BootDeviceWaitTime;             /* 0x24 */
+    U8                                  Reserved4;                      /* 0x25 */
+    U16                                 Reserved5;                      /* 0x26 */
+    U8                                  NumPhys;                        /* 0x28 */
+    U8                                  PEInitialSpinupDelay;           /* 0x29 */
+    U8                                  PEReplyDelay;                   /* 0x2A */
+    U8                                  Flags;                          /* 0x2B */
+    U8                                  PHY[MPI2_SAS_IOUNIT4_PHY_MAX];  /* 0x2C */
+} MPI2_CONFIG_PAGE_SASIOUNIT_4,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SASIOUNIT_4,
+  Mpi2SasIOUnitPage4_t, MPI2_POINTER pMpi2SasIOUnitPage4_t;
+
+#define MPI2_SASIOUNITPAGE4_PAGEVERSION     (0x02)
+
+/* defines for Flags field */
+#define MPI2_SASIOUNIT4_FLAGS_AUTO_PORTENABLE               (0x01)
+
+/* defines for PHY field */
+#define MPI2_SASIOUNIT4_PHY_SPINUP_GROUP_MASK               (0x03)
+
+
+/* SAS IO Unit Page 5 */
+
+typedef struct _MPI2_SAS_IO_UNIT5_PHY_PM_SETTINGS
+{
+    U8          ControlFlags;               /* 0x00 */
+    U8          Reserved1;                  /* 0x01 */
+    U16         InactivityTimerExponent;    /* 0x02 */
+    U8          SATAPartialTimeout;         /* 0x04 */
+    U8          Reserved2;                  /* 0x05 */
+    U8          SATASlumberTimeout;         /* 0x06 */
+    U8          Reserved3;                  /* 0x07 */
+    U8          SASPartialTimeout;          /* 0x08 */
+    U8          Reserved4;                  /* 0x09 */
+    U8          SASSlumberTimeout;          /* 0x0A */
+    U8          Reserved5;                  /* 0x0B */
+} MPI2_SAS_IO_UNIT5_PHY_PM_SETTINGS,
+  MPI2_POINTER PTR_MPI2_SAS_IO_UNIT5_PHY_PM_SETTINGS,
+  Mpi2SasIOUnit5PhyPmSettings_t, MPI2_POINTER pMpi2SasIOUnit5PhyPmSettings_t;
+
+/* defines for ControlFlags field */
+#define MPI2_SASIOUNIT5_CONTROL_SAS_SLUMBER_ENABLE      (0x08)
+#define MPI2_SASIOUNIT5_CONTROL_SAS_PARTIAL_ENABLE      (0x04)
+#define MPI2_SASIOUNIT5_CONTROL_SATA_SLUMBER_ENABLE     (0x02)
+#define MPI2_SASIOUNIT5_CONTROL_SATA_PARTIAL_ENABLE     (0x01)
+
+/* defines for InactivityTimerExponent field */
+#define MPI2_SASIOUNIT5_ITE_MASK_SAS_SLUMBER            (0x7000)
+#define MPI2_SASIOUNIT5_ITE_SHIFT_SAS_SLUMBER           (12)
+#define MPI2_SASIOUNIT5_ITE_MASK_SAS_PARTIAL            (0x0700)
+#define MPI2_SASIOUNIT5_ITE_SHIFT_SAS_PARTIAL           (8)
+#define MPI2_SASIOUNIT5_ITE_MASK_SATA_SLUMBER           (0x0070)
+#define MPI2_SASIOUNIT5_ITE_SHIFT_SATA_SLUMBER          (4)
+#define MPI2_SASIOUNIT5_ITE_MASK_SATA_PARTIAL           (0x0007)
+#define MPI2_SASIOUNIT5_ITE_SHIFT_SATA_PARTIAL          (0)
+
+#define MPI2_SASIOUNIT5_ITE_TEN_SECONDS                 (7)
+#define MPI2_SASIOUNIT5_ITE_ONE_SECOND                  (6)
+#define MPI2_SASIOUNIT5_ITE_HUNDRED_MILLISECONDS        (5)
+#define MPI2_SASIOUNIT5_ITE_TEN_MILLISECONDS            (4)
+#define MPI2_SASIOUNIT5_ITE_ONE_MILLISECOND             (3)
+#define MPI2_SASIOUNIT5_ITE_HUNDRED_MICROSECONDS        (2)
+#define MPI2_SASIOUNIT5_ITE_TEN_MICROSECONDS            (1)
+#define MPI2_SASIOUNIT5_ITE_ONE_MICROSECOND             (0)
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_SAS_IOUNIT5_PHY_MAX
+#define MPI2_SAS_IOUNIT5_PHY_MAX        (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_SASIOUNIT_5
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                             /* 0x00 */
+    U8                                  NumPhys;                            /* 0x08 */
+    U8                                  Reserved1;                          /* 0x09 */
+    U16                                 Reserved2;                          /* 0x0A */
+    U32                                 Reserved3;                          /* 0x0C */
+    MPI2_SAS_IO_UNIT5_PHY_PM_SETTINGS   SASPhyPowerManagementSettings[MPI2_SAS_IOUNIT5_PHY_MAX];  /* 0x10 */
+} MPI2_CONFIG_PAGE_SASIOUNIT_5,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SASIOUNIT_5,
+  Mpi2SasIOUnitPage5_t, MPI2_POINTER pMpi2SasIOUnitPage5_t;
+
+#define MPI2_SASIOUNITPAGE5_PAGEVERSION     (0x00)
+
+
+
+
+/****************************************************************************
+*   SAS Expander Config Pages
+****************************************************************************/
+
+/* SAS Expander Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_EXPANDER_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U8                                  PhysicalPort;               /* 0x08 */
+    U8                                  ReportGenLength;            /* 0x09 */
+    U16                                 EnclosureHandle;            /* 0x0A */
+    U64                                 SASAddress;                 /* 0x0C */
+    U32                                 DiscoveryStatus;            /* 0x14 */
+    U16                                 DevHandle;                  /* 0x18 */
+    U16                                 ParentDevHandle;            /* 0x1A */
+    U16                                 ExpanderChangeCount;        /* 0x1C */
+    U16                                 ExpanderRouteIndexes;       /* 0x1E */
+    U8                                  NumPhys;                    /* 0x20 */
+    U8                                  SASLevel;                   /* 0x21 */
+    U16                                 Flags;                      /* 0x22 */
+    U16                                 STPBusInactivityTimeLimit;  /* 0x24 */
+    U16                                 STPMaxConnectTimeLimit;     /* 0x26 */
+    U16                                 STP_SMP_NexusLossTime;      /* 0x28 */
+    U16                                 MaxNumRoutedSasAddresses;   /* 0x2A */
+    U64                                 ActiveZoneManagerSASAddress;/* 0x2C */
+    U16                                 ZoneLockInactivityLimit;    /* 0x34 */
+    U16                                 Reserved1;                  /* 0x36 */
+    U8                                  TimeToReducedFunc;          /* 0x38 */
+    U8                                  InitialTimeToReducedFunc;   /* 0x39 */
+    U8                                  MaxReducedFuncTime;         /* 0x3A */
+    U8                                  Reserved2;                  /* 0x3B */
+} MPI2_CONFIG_PAGE_EXPANDER_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_EXPANDER_0,
+  Mpi2ExpanderPage0_t, MPI2_POINTER pMpi2ExpanderPage0_t;
+
+#define MPI2_SASEXPANDER0_PAGEVERSION       (0x06)
+
+/* values for SAS Expander Page 0 DiscoveryStatus field */
+#define MPI2_SAS_EXPANDER0_DS_MAX_ENCLOSURES_EXCEED         (0x80000000)
+#define MPI2_SAS_EXPANDER0_DS_MAX_EXPANDERS_EXCEED          (0x40000000)
+#define MPI2_SAS_EXPANDER0_DS_MAX_DEVICES_EXCEED            (0x20000000)
+#define MPI2_SAS_EXPANDER0_DS_MAX_TOPO_PHYS_EXCEED          (0x10000000)
+#define MPI2_SAS_EXPANDER0_DS_DOWNSTREAM_INITIATOR          (0x08000000)
+#define MPI2_SAS_EXPANDER0_DS_MULTI_SUBTRACTIVE_SUBTRACTIVE (0x00008000)
+#define MPI2_SAS_EXPANDER0_DS_EXP_MULTI_SUBTRACTIVE         (0x00004000)
+#define MPI2_SAS_EXPANDER0_DS_MULTI_PORT_DOMAIN             (0x00002000)
+#define MPI2_SAS_EXPANDER0_DS_TABLE_TO_SUBTRACTIVE_LINK     (0x00001000)
+#define MPI2_SAS_EXPANDER0_DS_UNSUPPORTED_DEVICE            (0x00000800)
+#define MPI2_SAS_EXPANDER0_DS_TABLE_LINK                    (0x00000400)
+#define MPI2_SAS_EXPANDER0_DS_SUBTRACTIVE_LINK              (0x00000200)
+#define MPI2_SAS_EXPANDER0_DS_SMP_CRC_ERROR                 (0x00000100)
+#define MPI2_SAS_EXPANDER0_DS_SMP_FUNCTION_FAILED           (0x00000080)
+#define MPI2_SAS_EXPANDER0_DS_INDEX_NOT_EXIST               (0x00000040)
+#define MPI2_SAS_EXPANDER0_DS_OUT_ROUTE_ENTRIES             (0x00000020)
+#define MPI2_SAS_EXPANDER0_DS_SMP_TIMEOUT                   (0x00000010)
+#define MPI2_SAS_EXPANDER0_DS_MULTIPLE_PORTS                (0x00000004)
+#define MPI2_SAS_EXPANDER0_DS_UNADDRESSABLE_DEVICE          (0x00000002)
+#define MPI2_SAS_EXPANDER0_DS_LOOP_DETECTED                 (0x00000001)
+
+/* values for SAS Expander Page 0 Flags field */
+#define MPI2_SAS_EXPANDER0_FLAGS_REDUCED_FUNCTIONALITY      (0x2000)
+#define MPI2_SAS_EXPANDER0_FLAGS_ZONE_LOCKED                (0x1000)
+#define MPI2_SAS_EXPANDER0_FLAGS_SUPPORTED_PHYSICAL_PRES    (0x0800)
+#define MPI2_SAS_EXPANDER0_FLAGS_ASSERTED_PHYSICAL_PRES     (0x0400)
+#define MPI2_SAS_EXPANDER0_FLAGS_ZONING_SUPPORT             (0x0200)
+#define MPI2_SAS_EXPANDER0_FLAGS_ENABLED_ZONING             (0x0100)
+#define MPI2_SAS_EXPANDER0_FLAGS_TABLE_TO_TABLE_SUPPORT     (0x0080)
+#define MPI2_SAS_EXPANDER0_FLAGS_CONNECTOR_END_DEVICE       (0x0010)
+#define MPI2_SAS_EXPANDER0_FLAGS_OTHERS_CONFIG              (0x0004)
+#define MPI2_SAS_EXPANDER0_FLAGS_CONFIG_IN_PROGRESS         (0x0002)
+#define MPI2_SAS_EXPANDER0_FLAGS_ROUTE_TABLE_CONFIG         (0x0001)
+
+
+/* SAS Expander Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_EXPANDER_1
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U8                                  PhysicalPort;               /* 0x08 */
+    U8                                  Reserved1;                  /* 0x09 */
+    U16                                 Reserved2;                  /* 0x0A */
+    U8                                  NumPhys;                    /* 0x0C */
+    U8                                  Phy;                        /* 0x0D */
+    U16                                 NumTableEntriesProgrammed;  /* 0x0E */
+    U8                                  ProgrammedLinkRate;         /* 0x10 */
+    U8                                  HwLinkRate;                 /* 0x11 */
+    U16                                 AttachedDevHandle;          /* 0x12 */
+    U32                                 PhyInfo;                    /* 0x14 */
+    U32                                 AttachedDeviceInfo;         /* 0x18 */
+    U16                                 ExpanderDevHandle;          /* 0x1C */
+    U8                                  ChangeCount;                /* 0x1E */
+    U8                                  NegotiatedLinkRate;         /* 0x1F */
+    U8                                  PhyIdentifier;              /* 0x20 */
+    U8                                  AttachedPhyIdentifier;      /* 0x21 */
+    U8                                  Reserved3;                  /* 0x22 */
+    U8                                  DiscoveryInfo;              /* 0x23 */
+    U32                                 AttachedPhyInfo;            /* 0x24 */
+    U8                                  ZoneGroup;                  /* 0x28 */
+    U8                                  SelfConfigStatus;           /* 0x29 */
+    U16                                 Reserved4;                  /* 0x2A */
+} MPI2_CONFIG_PAGE_EXPANDER_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_EXPANDER_1,
+  Mpi2ExpanderPage1_t, MPI2_POINTER pMpi2ExpanderPage1_t;
+
+#define MPI2_SASEXPANDER1_PAGEVERSION       (0x02)
+
+/* use MPI2_SAS_PRATE_ defines for the ProgrammedLinkRate field */
+
+/* use MPI2_SAS_HWRATE_ defines for the HwLinkRate field */
+
+/* use MPI2_SAS_PHYINFO_ for the PhyInfo field */
+
+/* see mpi2_sas.h for the MPI2_SAS_DEVICE_INFO_ defines used for the AttachedDeviceInfo field */
+
+/* use MPI2_SAS_NEG_LINK_RATE_ defines for the NegotiatedLinkRate field */
+
+/* use MPI2_SAS_APHYINFO_ defines for AttachedPhyInfo field */
+
+/* values for SAS Expander Page 1 DiscoveryInfo field */
+#define MPI2_SAS_EXPANDER1_DISCINFO_BAD_PHY_DISABLED    (0x04)
+#define MPI2_SAS_EXPANDER1_DISCINFO_LINK_STATUS_CHANGE  (0x02)
+#define MPI2_SAS_EXPANDER1_DISCINFO_NO_ROUTING_ENTRIES  (0x01)
+
+
+/****************************************************************************
+*   SAS Device Config Pages
+****************************************************************************/
+
+/* SAS Device Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_DEV_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                 /* 0x00 */
+    U16                                 Slot;                   /* 0x08 */
+    U16                                 EnclosureHandle;        /* 0x0A */
+    U64                                 SASAddress;             /* 0x0C */
+    U16                                 ParentDevHandle;        /* 0x14 */
+    U8                                  PhyNum;                 /* 0x16 */
+    U8                                  AccessStatus;           /* 0x17 */
+    U16                                 DevHandle;              /* 0x18 */
+    U8                                  AttachedPhyIdentifier;  /* 0x1A */
+    U8                                  ZoneGroup;              /* 0x1B */
+    U32                                 DeviceInfo;             /* 0x1C */
+    U16                                 Flags;                  /* 0x20 */
+    U8                                  PhysicalPort;           /* 0x22 */
+    U8                                  MaxPortConnections;     /* 0x23 */
+    U64                                 DeviceName;             /* 0x24 */
+    U8                                  PortGroups;             /* 0x2C */
+    U8                                  DmaGroup;               /* 0x2D */
+    U8                                  ControlGroup;           /* 0x2E */
+    U8                                  Reserved1;              /* 0x2F */
+    U32                                 Reserved2;              /* 0x30 */
+    U32                                 Reserved3;              /* 0x34 */
+} MPI2_CONFIG_PAGE_SAS_DEV_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_DEV_0,
+  Mpi2SasDevicePage0_t, MPI2_POINTER pMpi2SasDevicePage0_t;
+
+#define MPI2_SASDEVICE0_PAGEVERSION         (0x08)
+
+/* values for SAS Device Page 0 AccessStatus field */
+#define MPI2_SAS_DEVICE0_ASTATUS_NO_ERRORS                  (0x00)
+#define MPI2_SAS_DEVICE0_ASTATUS_SATA_INIT_FAILED           (0x01)
+#define MPI2_SAS_DEVICE0_ASTATUS_SATA_CAPABILITY_FAILED     (0x02)
+#define MPI2_SAS_DEVICE0_ASTATUS_SATA_AFFILIATION_CONFLICT  (0x03)
+#define MPI2_SAS_DEVICE0_ASTATUS_SATA_NEEDS_INITIALIZATION  (0x04)
+#define MPI2_SAS_DEVICE0_ASTATUS_ROUTE_NOT_ADDRESSABLE      (0x05)
+#define MPI2_SAS_DEVICE0_ASTATUS_SMP_ERROR_NOT_ADDRESSABLE  (0x06)
+#define MPI2_SAS_DEVICE0_ASTATUS_DEVICE_BLOCKED             (0x07)
+/* specific values for SATA Init failures */
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_UNKNOWN                (0x10)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_AFFILIATION_CONFLICT   (0x11)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_DIAG                   (0x12)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_IDENTIFICATION         (0x13)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_CHECK_POWER            (0x14)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_PIO_SN                 (0x15)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_MDMA_SN                (0x16)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_UDMA_SN                (0x17)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_ZONING_VIOLATION       (0x18)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_NOT_ADDRESSABLE        (0x19)
+#define MPI2_SAS_DEVICE0_ASTATUS_SIF_MAX                    (0x1F)
+
+/* see mpi2_sas.h for values for SAS Device Page 0 DeviceInfo values */
+
+/* values for SAS Device Page 0 Flags field */
+#define MPI2_SAS_DEVICE0_FLAGS_SLUMBER_PM_CAPABLE           (0x1000)
+#define MPI2_SAS_DEVICE0_FLAGS_PARTIAL_PM_CAPABLE           (0x0800)
+#define MPI2_SAS_DEVICE0_FLAGS_SATA_ASYNCHRONOUS_NOTIFY     (0x0400)
+#define MPI2_SAS_DEVICE0_FLAGS_SATA_SW_PRESERVE             (0x0200)
+#define MPI2_SAS_DEVICE0_FLAGS_UNSUPPORTED_DEVICE           (0x0100)
+#define MPI2_SAS_DEVICE0_FLAGS_SATA_48BIT_LBA_SUPPORTED     (0x0080)
+#define MPI2_SAS_DEVICE0_FLAGS_SATA_SMART_SUPPORTED         (0x0040)
+#define MPI2_SAS_DEVICE0_FLAGS_SATA_NCQ_SUPPORTED           (0x0020)
+#define MPI2_SAS_DEVICE0_FLAGS_SATA_FUA_SUPPORTED           (0x0010)
+#define MPI2_SAS_DEVICE0_FLAGS_PORT_SELECTOR_ATTACH         (0x0008)
+#define MPI2_SAS_DEVICE0_FLAGS_DEVICE_PRESENT               (0x0001)
+
+
+/* SAS Device Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_DEV_1
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                 /* 0x00 */
+    U32                                 Reserved1;              /* 0x08 */
+    U64                                 SASAddress;             /* 0x0C */
+    U32                                 Reserved2;              /* 0x14 */
+    U16                                 DevHandle;              /* 0x18 */
+    U16                                 Reserved3;              /* 0x1A */
+    U8                                  InitialRegDeviceFIS[20];/* 0x1C */
+} MPI2_CONFIG_PAGE_SAS_DEV_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_DEV_1,
+  Mpi2SasDevicePage1_t, MPI2_POINTER pMpi2SasDevicePage1_t;
+
+#define MPI2_SASDEVICE1_PAGEVERSION         (0x01)
+
+
+/****************************************************************************
+*   SAS PHY Config Pages
+****************************************************************************/
+
+/* SAS PHY Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_PHY_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                 /* 0x00 */
+    U16                                 OwnerDevHandle;         /* 0x08 */
+    U16                                 Reserved1;              /* 0x0A */
+    U16                                 AttachedDevHandle;      /* 0x0C */
+    U8                                  AttachedPhyIdentifier;  /* 0x0E */
+    U8                                  Reserved2;              /* 0x0F */
+    U32                                 AttachedPhyInfo;        /* 0x10 */
+    U8                                  ProgrammedLinkRate;     /* 0x14 */
+    U8                                  HwLinkRate;             /* 0x15 */
+    U8                                  ChangeCount;            /* 0x16 */
+    U8                                  Flags;                  /* 0x17 */
+    U32                                 PhyInfo;                /* 0x18 */
+    U8                                  NegotiatedLinkRate;     /* 0x1C */
+    U8                                  Reserved3;              /* 0x1D */
+    U16                                 Reserved4;              /* 0x1E */
+} MPI2_CONFIG_PAGE_SAS_PHY_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_PHY_0,
+  Mpi2SasPhyPage0_t, MPI2_POINTER pMpi2SasPhyPage0_t;
+
+#define MPI2_SASPHY0_PAGEVERSION            (0x03)
+
+/* use MPI2_SAS_PRATE_ defines for the ProgrammedLinkRate field */
+
+/* use MPI2_SAS_HWRATE_ defines for the HwLinkRate field */
+
+/* values for SAS PHY Page 0 Flags field */
+#define MPI2_SAS_PHY0_FLAGS_SGPIO_DIRECT_ATTACH_ENC             (0x01)
+
+/* use MPI2_SAS_APHYINFO_ defines for AttachedPhyInfo field */
+
+/* use MPI2_SAS_NEG_LINK_RATE_ defines for the NegotiatedLinkRate field */
+
+/* use MPI2_SAS_PHYINFO_ for the PhyInfo field */
+
+
+/* SAS PHY Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_PHY_1
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U32                                 Reserved1;                  /* 0x08 */
+    U32                                 InvalidDwordCount;          /* 0x0C */
+    U32                                 RunningDisparityErrorCount; /* 0x10 */
+    U32                                 LossDwordSynchCount;        /* 0x14 */
+    U32                                 PhyResetProblemCount;       /* 0x18 */
+} MPI2_CONFIG_PAGE_SAS_PHY_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_PHY_1,
+  Mpi2SasPhyPage1_t, MPI2_POINTER pMpi2SasPhyPage1_t;
+
+#define MPI2_SASPHY1_PAGEVERSION            (0x01)
+
+
+/* SAS PHY Page 2 */
+
+typedef struct _MPI2_SASPHY2_PHY_EVENT
+{
+    U8          PhyEventCode;       /* 0x00 */
+    U8          Reserved1;          /* 0x01 */
+    U16         Reserved2;          /* 0x02 */
+    U32         PhyEventInfo;       /* 0x04 */
+} MPI2_SASPHY2_PHY_EVENT, MPI2_POINTER PTR_MPI2_SASPHY2_PHY_EVENT,
+  Mpi2SasPhy2PhyEvent_t, MPI2_POINTER pMpi2SasPhy2PhyEvent_t;
+
+/* use MPI2_SASPHY3_EVENT_CODE_ for the PhyEventCode field */
+
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhyEvents at runtime.
+ */
+#ifndef MPI2_SASPHY2_PHY_EVENT_MAX
+#define MPI2_SASPHY2_PHY_EVENT_MAX      (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_PHY_2
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U32                                 Reserved1;                  /* 0x08 */
+    U8                                  NumPhyEvents;               /* 0x0C */
+    U8                                  Reserved2;                  /* 0x0D */
+    U16                                 Reserved3;                  /* 0x0E */
+    MPI2_SASPHY2_PHY_EVENT              PhyEvent[MPI2_SASPHY2_PHY_EVENT_MAX]; /* 0x10 */
+} MPI2_CONFIG_PAGE_SAS_PHY_2, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_PHY_2,
+  Mpi2SasPhyPage2_t, MPI2_POINTER pMpi2SasPhyPage2_t;
+
+#define MPI2_SASPHY2_PAGEVERSION            (0x00)
+
+
+/* SAS PHY Page 3 */
+
+typedef struct _MPI2_SASPHY3_PHY_EVENT_CONFIG
+{
+    U8          PhyEventCode;       /* 0x00 */
+    U8          Reserved1;          /* 0x01 */
+    U16         Reserved2;          /* 0x02 */
+    U8          CounterType;        /* 0x04 */
+    U8          ThresholdWindow;    /* 0x05 */
+    U8          TimeUnits;          /* 0x06 */
+    U8          Reserved3;          /* 0x07 */
+    U32         EventThreshold;     /* 0x08 */
+    U16         ThresholdFlags;     /* 0x0C */
+    U16         Reserved4;          /* 0x0E */
+} MPI2_SASPHY3_PHY_EVENT_CONFIG, MPI2_POINTER PTR_MPI2_SASPHY3_PHY_EVENT_CONFIG,
+  Mpi2SasPhy3PhyEventConfig_t, MPI2_POINTER pMpi2SasPhy3PhyEventConfig_t;
+
+/* values for PhyEventCode field */
+#define MPI2_SASPHY3_EVENT_CODE_NO_EVENT                    (0x00)
+#define MPI2_SASPHY3_EVENT_CODE_INVALID_DWORD               (0x01)
+#define MPI2_SASPHY3_EVENT_CODE_RUNNING_DISPARITY_ERROR     (0x02)
+#define MPI2_SASPHY3_EVENT_CODE_LOSS_DWORD_SYNC             (0x03)
+#define MPI2_SASPHY3_EVENT_CODE_PHY_RESET_PROBLEM           (0x04)
+#define MPI2_SASPHY3_EVENT_CODE_ELASTICITY_BUF_OVERFLOW     (0x05)
+#define MPI2_SASPHY3_EVENT_CODE_RX_ERROR                    (0x06)
+#define MPI2_SASPHY3_EVENT_CODE_RX_ADDR_FRAME_ERROR         (0x20)
+#define MPI2_SASPHY3_EVENT_CODE_TX_AC_OPEN_REJECT           (0x21)
+#define MPI2_SASPHY3_EVENT_CODE_RX_AC_OPEN_REJECT           (0x22)
+#define MPI2_SASPHY3_EVENT_CODE_TX_RC_OPEN_REJECT           (0x23)
+#define MPI2_SASPHY3_EVENT_CODE_RX_RC_OPEN_REJECT           (0x24)
+#define MPI2_SASPHY3_EVENT_CODE_RX_AIP_PARTIAL_WAITING_ON   (0x25)
+#define MPI2_SASPHY3_EVENT_CODE_RX_AIP_CONNECT_WAITING_ON   (0x26)
+#define MPI2_SASPHY3_EVENT_CODE_TX_BREAK                    (0x27)
+#define MPI2_SASPHY3_EVENT_CODE_RX_BREAK                    (0x28)
+#define MPI2_SASPHY3_EVENT_CODE_BREAK_TIMEOUT               (0x29)
+#define MPI2_SASPHY3_EVENT_CODE_CONNECTION                  (0x2A)
+#define MPI2_SASPHY3_EVENT_CODE_PEAKTX_PATHWAY_BLOCKED      (0x2B)
+#define MPI2_SASPHY3_EVENT_CODE_PEAKTX_ARB_WAIT_TIME        (0x2C)
+#define MPI2_SASPHY3_EVENT_CODE_PEAK_ARB_WAIT_TIME          (0x2D)
+#define MPI2_SASPHY3_EVENT_CODE_PEAK_CONNECT_TIME           (0x2E)
+#define MPI2_SASPHY3_EVENT_CODE_TX_SSP_FRAMES               (0x40)
+#define MPI2_SASPHY3_EVENT_CODE_RX_SSP_FRAMES               (0x41)
+#define MPI2_SASPHY3_EVENT_CODE_TX_SSP_ERROR_FRAMES         (0x42)
+#define MPI2_SASPHY3_EVENT_CODE_RX_SSP_ERROR_FRAMES         (0x43)
+#define MPI2_SASPHY3_EVENT_CODE_TX_CREDIT_BLOCKED           (0x44)
+#define MPI2_SASPHY3_EVENT_CODE_RX_CREDIT_BLOCKED           (0x45)
+#define MPI2_SASPHY3_EVENT_CODE_TX_SATA_FRAMES              (0x50)
+#define MPI2_SASPHY3_EVENT_CODE_RX_SATA_FRAMES              (0x51)
+#define MPI2_SASPHY3_EVENT_CODE_SATA_OVERFLOW               (0x52)
+#define MPI2_SASPHY3_EVENT_CODE_TX_SMP_FRAMES               (0x60)
+#define MPI2_SASPHY3_EVENT_CODE_RX_SMP_FRAMES               (0x61)
+#define MPI2_SASPHY3_EVENT_CODE_RX_SMP_ERROR_FRAMES         (0x63)
+#define MPI2_SASPHY3_EVENT_CODE_HOTPLUG_TIMEOUT             (0xD0)
+#define MPI2_SASPHY3_EVENT_CODE_MISALIGNED_MUX_PRIMITIVE    (0xD1)
+#define MPI2_SASPHY3_EVENT_CODE_RX_AIP                      (0xD2)
+
+/* values for the CounterType field */
+#define MPI2_SASPHY3_COUNTER_TYPE_WRAPPING                  (0x00)
+#define MPI2_SASPHY3_COUNTER_TYPE_SATURATING                (0x01)
+#define MPI2_SASPHY3_COUNTER_TYPE_PEAK_VALUE                (0x02)
+
+/* values for the TimeUnits field */
+#define MPI2_SASPHY3_TIME_UNITS_10_MICROSECONDS             (0x00)
+#define MPI2_SASPHY3_TIME_UNITS_100_MICROSECONDS            (0x01)
+#define MPI2_SASPHY3_TIME_UNITS_1_MILLISECOND               (0x02)
+#define MPI2_SASPHY3_TIME_UNITS_10_MILLISECONDS             (0x03)
+
+/* values for the ThresholdFlags field */
+#define MPI2_SASPHY3_TFLAGS_PHY_RESET                       (0x0002)
+#define MPI2_SASPHY3_TFLAGS_EVENT_NOTIFY                    (0x0001)
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhyEvents at runtime.
+ */
+#ifndef MPI2_SASPHY3_PHY_EVENT_MAX
+#define MPI2_SASPHY3_PHY_EVENT_MAX      (1)
+#endif
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_PHY_3
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U32                                 Reserved1;                  /* 0x08 */
+    U8                                  NumPhyEvents;               /* 0x0C */
+    U8                                  Reserved2;                  /* 0x0D */
+    U16                                 Reserved3;                  /* 0x0E */
+    MPI2_SASPHY3_PHY_EVENT_CONFIG       PhyEventConfig[MPI2_SASPHY3_PHY_EVENT_MAX]; /* 0x10 */
+} MPI2_CONFIG_PAGE_SAS_PHY_3, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_PHY_3,
+  Mpi2SasPhyPage3_t, MPI2_POINTER pMpi2SasPhyPage3_t;
+
+#define MPI2_SASPHY3_PAGEVERSION            (0x00)
+
+
+/* SAS PHY Page 4 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_PHY_4
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U16                                 Reserved1;                  /* 0x08 */
+    U8                                  Reserved2;                  /* 0x0A */
+    U8                                  Flags;                      /* 0x0B */
+    U8                                  InitialFrame[28];           /* 0x0C */
+} MPI2_CONFIG_PAGE_SAS_PHY_4, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_PHY_4,
+  Mpi2SasPhyPage4_t, MPI2_POINTER pMpi2SasPhyPage4_t;
+
+#define MPI2_SASPHY4_PAGEVERSION            (0x00)
+
+/* values for the Flags field */
+#define MPI2_SASPHY4_FLAGS_FRAME_VALID        (0x02)
+#define MPI2_SASPHY4_FLAGS_SATA_FRAME         (0x01)
+
+
+
+
+/****************************************************************************
+*   SAS Port Config Pages
+****************************************************************************/
+
+/* SAS Port Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_PORT_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U8                                  PortNumber;                 /* 0x08 */
+    U8                                  PhysicalPort;               /* 0x09 */
+    U8                                  PortWidth;                  /* 0x0A */
+    U8                                  PhysicalPortWidth;          /* 0x0B */
+    U8                                  ZoneGroup;                  /* 0x0C */
+    U8                                  Reserved1;                  /* 0x0D */
+    U16                                 Reserved2;                  /* 0x0E */
+    U64                                 SASAddress;                 /* 0x10 */
+    U32                                 DeviceInfo;                 /* 0x18 */
+    U32                                 Reserved3;                  /* 0x1C */
+    U32                                 Reserved4;                  /* 0x20 */
+} MPI2_CONFIG_PAGE_SAS_PORT_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_PORT_0,
+  Mpi2SasPortPage0_t, MPI2_POINTER pMpi2SasPortPage0_t;
+
+#define MPI2_SASPORT0_PAGEVERSION           (0x00)
+
+/* see mpi2_sas.h for values for SAS Port Page 0 DeviceInfo values */
+
+
+/****************************************************************************
+*   SAS Enclosure Config Pages
+****************************************************************************/
+
+/* SAS Enclosure Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_SAS_ENCLOSURE_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U32                                 Reserved1;                  /* 0x08 */
+    U64                                 EnclosureLogicalID;         /* 0x0C */
+    U16                                 Flags;                      /* 0x14 */
+    U16                                 EnclosureHandle;            /* 0x16 */
+    U16                                 NumSlots;                   /* 0x18 */
+    U16                                 StartSlot;                  /* 0x1A */
+    U16                                 Reserved2;                  /* 0x1C */
+    U16                                 SEPDevHandle;               /* 0x1E */
+    U32                                 Reserved3;                  /* 0x20 */
+    U32                                 Reserved4;                  /* 0x24 */
+} MPI2_CONFIG_PAGE_SAS_ENCLOSURE_0,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_SAS_ENCLOSURE_0,
+  Mpi2SasEnclosurePage0_t, MPI2_POINTER pMpi2SasEnclosurePage0_t;
+
+#define MPI2_SASENCLOSURE0_PAGEVERSION      (0x03)
+
+/* values for SAS Enclosure Page 0 Flags field */
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_MASK              (0x000F)
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_UNKNOWN           (0x0000)
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_IOC_SES           (0x0001)
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_IOC_SGPIO         (0x0002)
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_EXP_SGPIO         (0x0003)
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_SES_ENCLOSURE     (0x0004)
+#define MPI2_SAS_ENCLS0_FLAGS_MNG_IOC_GPIO          (0x0005)
+
+
+/****************************************************************************
+*   Log Config Page
+****************************************************************************/
+
+/* Log Page 0 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_LOG_0_NUM_LOG_ENTRIES
+#define MPI2_LOG_0_NUM_LOG_ENTRIES          (1)
+#endif
+
+#define MPI2_LOG_0_LOG_DATA_LENGTH          (0x1C)
+
+typedef struct _MPI2_LOG_0_ENTRY
+{
+    U64         TimeStamp;                          /* 0x00 */
+    U32         Reserved1;                          /* 0x08 */
+    U16         LogSequence;                        /* 0x0C */
+    U16         LogEntryQualifier;                  /* 0x0E */
+    U8          VP_ID;                              /* 0x10 */
+    U8          VF_ID;                              /* 0x11 */
+    U16         Reserved2;                          /* 0x12 */
+    U8          LogData[MPI2_LOG_0_LOG_DATA_LENGTH];/* 0x14 */
+} MPI2_LOG_0_ENTRY, MPI2_POINTER PTR_MPI2_LOG_0_ENTRY,
+  Mpi2Log0Entry_t, MPI2_POINTER pMpi2Log0Entry_t;
+
+/* values for Log Page 0 LogEntry LogEntryQualifier field */
+#define MPI2_LOG_0_ENTRY_QUAL_ENTRY_UNUSED          (0x0000)
+#define MPI2_LOG_0_ENTRY_QUAL_POWER_ON_RESET        (0x0001)
+#define MPI2_LOG_0_ENTRY_QUAL_TIMESTAMP_UPDATE      (0x0002)
+#define MPI2_LOG_0_ENTRY_QUAL_MIN_IMPLEMENT_SPEC    (0x8000)
+#define MPI2_LOG_0_ENTRY_QUAL_MAX_IMPLEMENT_SPEC    (0xFFFF)
+
+typedef struct _MPI2_CONFIG_PAGE_LOG_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U32                                 Reserved1;                  /* 0x08 */
+    U32                                 Reserved2;                  /* 0x0C */
+    U16                                 NumLogEntries;              /* 0x10 */
+    U16                                 Reserved3;                  /* 0x12 */
+    MPI2_LOG_0_ENTRY                    LogEntry[MPI2_LOG_0_NUM_LOG_ENTRIES]; /* 0x14 */
+} MPI2_CONFIG_PAGE_LOG_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_LOG_0,
+  Mpi2LogPage0_t, MPI2_POINTER pMpi2LogPage0_t;
+
+#define MPI2_LOG_0_PAGEVERSION              (0x02)
+
+
+/****************************************************************************
+*   RAID Config Page
+****************************************************************************/
+
+/* RAID Page 0 */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check Header.ExtPageLength or NumPhys at runtime.
+ */
+#ifndef MPI2_RAIDCONFIG0_MAX_ELEMENTS
+#define MPI2_RAIDCONFIG0_MAX_ELEMENTS       (1)
+#endif
+
+typedef struct _MPI2_RAIDCONFIG0_CONFIG_ELEMENT
+{
+    U16                     ElementFlags;               /* 0x00 */
+    U16                     VolDevHandle;               /* 0x02 */
+    U8                      HotSparePool;               /* 0x04 */
+    U8                      PhysDiskNum;                /* 0x05 */
+    U16                     PhysDiskDevHandle;          /* 0x06 */
+} MPI2_RAIDCONFIG0_CONFIG_ELEMENT,
+  MPI2_POINTER PTR_MPI2_RAIDCONFIG0_CONFIG_ELEMENT,
+  Mpi2RaidConfig0ConfigElement_t, MPI2_POINTER pMpi2RaidConfig0ConfigElement_t;
+
+/* values for the ElementFlags field */
+#define MPI2_RAIDCONFIG0_EFLAGS_MASK_ELEMENT_TYPE       (0x000F)
+#define MPI2_RAIDCONFIG0_EFLAGS_VOLUME_ELEMENT          (0x0000)
+#define MPI2_RAIDCONFIG0_EFLAGS_VOL_PHYS_DISK_ELEMENT   (0x0001)
+#define MPI2_RAIDCONFIG0_EFLAGS_HOT_SPARE_ELEMENT       (0x0002)
+#define MPI2_RAIDCONFIG0_EFLAGS_OCE_ELEMENT             (0x0003)
+
+
+typedef struct _MPI2_CONFIG_PAGE_RAID_CONFIGURATION_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    U8                                  NumHotSpares;               /* 0x08 */
+    U8                                  NumPhysDisks;               /* 0x09 */
+    U8                                  NumVolumes;                 /* 0x0A */
+    U8                                  ConfigNum;                  /* 0x0B */
+    U32                                 Flags;                      /* 0x0C */
+    U8                                  ConfigGUID[24];             /* 0x10 */
+    U32                                 Reserved1;                  /* 0x28 */
+    U8                                  NumElements;                /* 0x2C */
+    U8                                  Reserved2;                  /* 0x2D */
+    U16                                 Reserved3;                  /* 0x2E */
+    MPI2_RAIDCONFIG0_CONFIG_ELEMENT     ConfigElement[MPI2_RAIDCONFIG0_MAX_ELEMENTS]; /* 0x30 */
+} MPI2_CONFIG_PAGE_RAID_CONFIGURATION_0,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_RAID_CONFIGURATION_0,
+  Mpi2RaidConfigurationPage0_t, MPI2_POINTER pMpi2RaidConfigurationPage0_t;
+
+#define MPI2_RAIDCONFIG0_PAGEVERSION            (0x00)
+
+/* values for RAID Configuration Page 0 Flags field */
+#define MPI2_RAIDCONFIG0_FLAG_FOREIGN_CONFIG        (0x00000001)
+
+
+/****************************************************************************
+*   Driver Persistent Mapping Config Pages
+****************************************************************************/
+
+/* Driver Persistent Mapping Page 0 */
+
+typedef struct _MPI2_CONFIG_PAGE_DRIVER_MAP0_ENTRY
+{
+    U64                                 PhysicalIdentifier;         /* 0x00 */
+    U16                                 MappingInformation;         /* 0x08 */
+    U16                                 DeviceIndex;                /* 0x0A */
+    U32                                 PhysicalBitsMapping;        /* 0x0C */
+    U32                                 Reserved1;                  /* 0x10 */
+} MPI2_CONFIG_PAGE_DRIVER_MAP0_ENTRY,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_DRIVER_MAP0_ENTRY,
+  Mpi2DriverMap0Entry_t, MPI2_POINTER pMpi2DriverMap0Entry_t;
+
+typedef struct _MPI2_CONFIG_PAGE_DRIVER_MAPPING_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                     /* 0x00 */
+    MPI2_CONFIG_PAGE_DRIVER_MAP0_ENTRY  Entry;                      /* 0x08 */
+} MPI2_CONFIG_PAGE_DRIVER_MAPPING_0,
+  MPI2_POINTER PTR_MPI2_CONFIG_PAGE_DRIVER_MAPPING_0,
+  Mpi2DriverMappingPage0_t, MPI2_POINTER pMpi2DriverMappingPage0_t;
+
+#define MPI2_DRIVERMAPPING0_PAGEVERSION         (0x00)
+
+/* values for Driver Persistent Mapping Page 0 MappingInformation field */
+#define MPI2_DRVMAP0_MAPINFO_SLOT_MASK              (0x07F0)
+#define MPI2_DRVMAP0_MAPINFO_SLOT_SHIFT             (4)
+#define MPI2_DRVMAP0_MAPINFO_MISSING_MASK           (0x000F)
+
+
+/****************************************************************************
+*   Ethernet Config Pages
+****************************************************************************/
+
+/* Ethernet Page 0 */
+
+/* IP address (union of IPv4 and IPv6) */
+typedef union _MPI2_ETHERNET_IP_ADDR
+{
+    U32     IPv4Addr;
+    U32     IPv6Addr[4];
+} MPI2_ETHERNET_IP_ADDR, MPI2_POINTER PTR_MPI2_ETHERNET_IP_ADDR,
+  Mpi2EthernetIpAddr_t, MPI2_POINTER pMpi2EthernetIpAddr_t;
+
+#define MPI2_ETHERNET_HOST_NAME_LENGTH          (32)
+
+typedef struct _MPI2_CONFIG_PAGE_ETHERNET_0
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                 /* 0x00 */
+    U8                                  NumInterfaces;          /* 0x08 */
+    U8                                  Reserved0;              /* 0x09 */
+    U16                                 Reserved1;              /* 0x0A */
+    U32                                 Status;                 /* 0x0C */
+    U8                                  MediaState;             /* 0x10 */
+    U8                                  Reserved2;              /* 0x11 */
+    U16                                 Reserved3;              /* 0x12 */
+    U8                                  MacAddress[6];          /* 0x14 */
+    U8                                  Reserved4;              /* 0x1A */
+    U8                                  Reserved5;              /* 0x1B */
+    MPI2_ETHERNET_IP_ADDR               IpAddress;              /* 0x1C */
+    MPI2_ETHERNET_IP_ADDR               SubnetMask;             /* 0x2C */
+    MPI2_ETHERNET_IP_ADDR               GatewayIpAddress;       /* 0x3C */
+    MPI2_ETHERNET_IP_ADDR               DNS1IpAddress;          /* 0x4C */
+    MPI2_ETHERNET_IP_ADDR               DNS2IpAddress;          /* 0x5C */
+    MPI2_ETHERNET_IP_ADDR               DhcpIpAddress;          /* 0x6C */
+    U8                                  HostName[MPI2_ETHERNET_HOST_NAME_LENGTH];/* 0x7C */
+} MPI2_CONFIG_PAGE_ETHERNET_0, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_ETHERNET_0,
+  Mpi2EthernetPage0_t, MPI2_POINTER pMpi2EthernetPage0_t;
+
+#define MPI2_ETHERNETPAGE0_PAGEVERSION   (0x00)
+
+/* values for Ethernet Page 0 Status field */
+#define MPI2_ETHPG0_STATUS_IPV6_CAPABLE             (0x80000000)
+#define MPI2_ETHPG0_STATUS_IPV4_CAPABLE             (0x40000000)
+#define MPI2_ETHPG0_STATUS_CONSOLE_CONNECTED        (0x20000000)
+#define MPI2_ETHPG0_STATUS_DEFAULT_IF               (0x00000100)
+#define MPI2_ETHPG0_STATUS_FW_DWNLD_ENABLED         (0x00000080)
+#define MPI2_ETHPG0_STATUS_TELNET_ENABLED           (0x00000040)
+#define MPI2_ETHPG0_STATUS_SSH2_ENABLED             (0x00000020)
+#define MPI2_ETHPG0_STATUS_DHCP_CLIENT_ENABLED      (0x00000010)
+#define MPI2_ETHPG0_STATUS_IPV6_ENABLED             (0x00000008)
+#define MPI2_ETHPG0_STATUS_IPV4_ENABLED             (0x00000004)
+#define MPI2_ETHPG0_STATUS_IPV6_ADDRESSES           (0x00000002)
+#define MPI2_ETHPG0_STATUS_ETH_IF_ENABLED           (0x00000001)
+
+/* values for Ethernet Page 0 MediaState field */
+#define MPI2_ETHPG0_MS_DUPLEX_MASK                  (0x80)
+#define MPI2_ETHPG0_MS_HALF_DUPLEX                  (0x00)
+#define MPI2_ETHPG0_MS_FULL_DUPLEX                  (0x80)
+
+#define MPI2_ETHPG0_MS_CONNECT_SPEED_MASK           (0x07)
+#define MPI2_ETHPG0_MS_NOT_CONNECTED                (0x00)
+#define MPI2_ETHPG0_MS_10MBIT                       (0x01)
+#define MPI2_ETHPG0_MS_100MBIT                      (0x02)
+#define MPI2_ETHPG0_MS_1GBIT                        (0x03)
+
+
+/* Ethernet Page 1 */
+
+typedef struct _MPI2_CONFIG_PAGE_ETHERNET_1
+{
+    MPI2_CONFIG_EXTENDED_PAGE_HEADER    Header;                 /* 0x00 */
+    U32                                 Reserved0;              /* 0x08 */
+    U32                                 Flags;                  /* 0x0C */
+    U8                                  MediaState;             /* 0x10 */
+    U8                                  Reserved1;              /* 0x11 */
+    U16                                 Reserved2;              /* 0x12 */
+    U8                                  MacAddress[6];          /* 0x14 */
+    U8                                  Reserved3;              /* 0x1A */
+    U8                                  Reserved4;              /* 0x1B */
+    MPI2_ETHERNET_IP_ADDR               StaticIpAddress;        /* 0x1C */
+    MPI2_ETHERNET_IP_ADDR               StaticSubnetMask;       /* 0x2C */
+    MPI2_ETHERNET_IP_ADDR               StaticGatewayIpAddress; /* 0x3C */
+    MPI2_ETHERNET_IP_ADDR               StaticDNS1IpAddress;    /* 0x4C */
+    MPI2_ETHERNET_IP_ADDR               StaticDNS2IpAddress;    /* 0x5C */
+    U32                                 Reserved5;              /* 0x6C */
+    U32                                 Reserved6;              /* 0x70 */
+    U32                                 Reserved7;              /* 0x74 */
+    U32                                 Reserved8;              /* 0x78 */
+    U8                                  HostName[MPI2_ETHERNET_HOST_NAME_LENGTH];/* 0x7C */
+} MPI2_CONFIG_PAGE_ETHERNET_1, MPI2_POINTER PTR_MPI2_CONFIG_PAGE_ETHERNET_1,
+  Mpi2EthernetPage1_t, MPI2_POINTER pMpi2EthernetPage1_t;
+
+#define MPI2_ETHERNETPAGE1_PAGEVERSION   (0x00)
+
+/* values for Ethernet Page 1 Flags field */
+#define MPI2_ETHPG1_FLAG_SET_DEFAULT_IF             (0x00000100)
+#define MPI2_ETHPG1_FLAG_ENABLE_FW_DOWNLOAD         (0x00000080)
+#define MPI2_ETHPG1_FLAG_ENABLE_TELNET              (0x00000040)
+#define MPI2_ETHPG1_FLAG_ENABLE_SSH2                (0x00000020)
+#define MPI2_ETHPG1_FLAG_ENABLE_DHCP_CLIENT         (0x00000010)
+#define MPI2_ETHPG1_FLAG_ENABLE_IPV6                (0x00000008)
+#define MPI2_ETHPG1_FLAG_ENABLE_IPV4                (0x00000004)
+#define MPI2_ETHPG1_FLAG_USE_IPV6_ADDRESSES         (0x00000002)
+#define MPI2_ETHPG1_FLAG_ENABLE_ETH_IF              (0x00000001)
+
+/* values for Ethernet Page 1 MediaState field */
+#define MPI2_ETHPG1_MS_DUPLEX_MASK                  (0x80)
+#define MPI2_ETHPG1_MS_HALF_DUPLEX                  (0x00)
+#define MPI2_ETHPG1_MS_FULL_DUPLEX                  (0x80)
+
+#define MPI2_ETHPG1_MS_DATA_RATE_MASK               (0x07)
+#define MPI2_ETHPG1_MS_DATA_RATE_AUTO               (0x00)
+#define MPI2_ETHPG1_MS_DATA_RATE_10MBIT             (0x01)
+#define MPI2_ETHPG1_MS_DATA_RATE_100MBIT            (0x02)
+#define MPI2_ETHPG1_MS_DATA_RATE_1GBIT              (0x03)
+
+
+#endif
+
diff --git a/sys/dev/mps/mpi/mpi2_hbd.h b/sys/dev/mps/mpi/mpi2_hbd.h
new file mode 100644
index 00000000000..d14e352c22a
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_hbd.h
@@ -0,0 +1,114 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_hbd.h
+ *          Title:  MPI Host Based Discovery messages and structures
+ *  Creation Date:  October 21, 2009
+ *
+ *  mpi2_hbd.h Version:  02.00.00
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  10-28-09  02.00.00  Initial version.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_HBD_H
+#define MPI2_HBD_H
+
+/****************************************************************************
+*  Host Based Discovery Action messages
+****************************************************************************/
+
+/* Host Based Discovery Action Request Message */
+typedef struct _MPI2_HBD_ACTION_REQUEST
+{
+    U8                      Operation;          /* 0x00 */
+    U8                      Reserved1;          /* 0x01 */
+    U8                      ChainOffset;        /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     DevHandle;          /* 0x04 */
+    U8                      Reserved2;          /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved3;          /* 0x0A */
+    U32                     Reserved4;          /* 0x0C */
+    U64                     SASAddress;         /* 0x10 */
+    U32                     Reserved5;          /* 0x18 */
+    U32                     HbdDeviceInfo;      /* 0x1C */
+    U16                     ParentDevHandle;    /* 0x20 */
+    U16                     MaxQDepth;          /* 0x22 */
+    U8                      FirstPhyIdentifier; /* 0x24 */
+    U8                      Port;               /* 0x25 */
+    U8                      MaxConnections;     /* 0x26 */
+    U8                      MaxRate;            /* 0x27 */
+    U8                      PortGroups;         /* 0x28 */
+    U8                      DmaGroup;           /* 0x29 */
+    U8                      ControlGroup;       /* 0x2A */
+    U8                      Reserved6;          /* 0x2B */
+    U16                     InitialAWT;         /* 0x2C */
+    U16                     Reserved7;          /* 0x2E */
+    U32                     Reserved8;          /* 0x30 */
+} MPI2_HBD_ACTION_REQUEST, MPI2_POINTER PTR_MPI2_HBD_ACTION_REQUEST,
+  Mpi2HbdActionRequest_t, MPI2_POINTER pMpi2HbdActionRequest_t;
+
+/* values for the Operation field */
+#define MPI2_HBD_OP_ADD_DEVICE                  (0x01)
+#define MPI2_HBD_OP_REMOVE_DEVICE               (0x02)
+#define MPI2_HBD_OP_UPDATE_DEVICE               (0x03)
+
+/* values for the HbdDeviceInfo field */
+#define MPI2_HBD_DEVICE_INFO_VIRTUAL_DEVICE     (0x00004000)
+#define MPI2_HBD_DEVICE_INFO_ATAPI_DEVICE       (0x00002000)
+#define MPI2_HBD_DEVICE_INFO_DIRECT_ATTACH      (0x00000800)
+#define MPI2_HBD_DEVICE_INFO_SSP_TARGET         (0x00000400)
+#define MPI2_HBD_DEVICE_INFO_STP_TARGET         (0x00000200)
+#define MPI2_HBD_DEVICE_INFO_SMP_TARGET         (0x00000100)
+#define MPI2_HBD_DEVICE_INFO_SATA_DEVICE        (0x00000080)
+#define MPI2_HBD_DEVICE_INFO_SSP_INITIATOR      (0x00000040)
+#define MPI2_HBD_DEVICE_INFO_STP_INITIATOR      (0x00000020)
+#define MPI2_HBD_DEVICE_INFO_SMP_INITIATOR      (0x00000010)
+#define MPI2_HBD_DEVICE_INFO_SATA_HOST          (0x00000008)
+
+#define MPI2_HBD_DEVICE_INFO_MASK_DEVICE_TYPE   (0x00000007)
+#define MPI2_HBD_DEVICE_INFO_NO_DEVICE          (0x00000000)
+#define MPI2_HBD_DEVICE_INFO_END_DEVICE         (0x00000001)
+#define MPI2_HBD_DEVICE_INFO_EDGE_EXPANDER      (0x00000002)
+#define MPI2_HBD_DEVICE_INFO_FANOUT_EXPANDER    (0x00000003)
+
+/* values for the MaxRate field */
+#define MPI2_HBD_MAX_RATE_MASK                  (0x0F)
+#define MPI2_HBD_MAX_RATE_1_5                   (0x08)
+#define MPI2_HBD_MAX_RATE_3_0                   (0x09)
+#define MPI2_HBD_MAX_RATE_6_0                   (0x0A)
+
+
+/* Host Based Discovery Action Reply Message */
+typedef struct _MPI2_HBD_ACTION_REPLY
+{
+    U8                      Operation;          /* 0x00 */
+    U8                      Reserved1;          /* 0x01 */
+    U8                      MsgLength;          /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     DevHandle;          /* 0x04 */
+    U8                      Reserved2;          /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved3;          /* 0x0A */
+    U16                     Reserved4;          /* 0x0C */
+    U16                     IOCStatus;          /* 0x0E */
+    U32                     IOCLogInfo;         /* 0x10 */
+} MPI2_HBD_ACTION_REPLY, MPI2_POINTER PTR_MPI2_HBD_ACTION_REPLY,
+  Mpi2HbdActionReply_t, MPI2_POINTER pMpi2HbdActionReply_t;
+
+
+#endif
+
+
diff --git a/sys/dev/mps/mpi/mpi2_history.txt b/sys/dev/mps/mpi/mpi2_history.txt
new file mode 100644
index 00000000000..d70df0dc71d
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_history.txt
@@ -0,0 +1,382 @@
+/* $FreeBSD$ */
+ ==============================
+ Fusion-MPT MPI 2.0 Header File Change History
+ ==============================
+
+ Copyright (c) 2000-2009 LSI Corporation.
+
+ ---------------------------------------
+ Header Set Release Version:    02.00.14
+ Header Set Release Date:       10-28-09
+ ---------------------------------------
+
+ Filename               Current version     Prior version
+ ----------             ---------------     -------------
+ mpi2.h                 02.00.14            02.00.13
+ mpi2_cnfg.h            02.00.13            02.00.12
+ mpi2_init.h            02.00.08            02.00.07
+ mpi2_ioc.h             02.00.13            02.00.12
+ mpi2_raid.h            02.00.04            02.00.04
+ mpi2_sas.h             02.00.03            02.00.02
+ mpi2_targ.h            02.00.03            02.00.03
+ mpi2_tool.h            02.00.04            02.00.04
+ mpi2_type.h            02.00.00            02.00.00
+ mpi2_ra.h              02.00.00            02.00.00
+ mpi2_hbd.h             02.00.00
+ mpi2_history.txt       02.00.14            02.00.13
+
+
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+
+mpi2.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-04-07  02.00.01  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  06-26-07  02.00.02  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  08-31-07  02.00.03  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Moved ReplyPostHostIndex register to offset 0x6C of the
+ *                      MPI2_SYSTEM_INTERFACE_REGS and modified the define for
+ *                      MPI2_REPLY_POST_HOST_INDEX_OFFSET.
+ *                      Added union of request descriptors.
+ *                      Added union of reply descriptors.
+ *  10-31-07  02.00.04  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Added define for MPI2_VERSION_02_00.
+ *                      Fixed the size of the FunctionDependent5 field in the
+ *                      MPI2_DEFAULT_REPLY structure.
+ *  12-18-07  02.00.05  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Removed the MPI-defined Fault Codes and extended the
+ *                      product specific codes up to 0xEFFF.
+ *                      Added a sixth key value for the WriteSequence register
+ *                      and changed the flush value to 0x0.
+ *                      Added message function codes for Diagnostic Buffer Post
+ *                      and Diagnsotic Release.
+ *                      New IOCStatus define: MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED
+ *                      Moved MPI2_VERSION_UNION from mpi2_ioc.h.
+ *  02-29-08  02.00.06  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  03-03-08  02.00.07  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  05-21-08  02.00.08  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Added #defines for marking a reply descriptor as unused.
+ *  06-27-08  02.00.09  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  10-02-08  02.00.10  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Moved LUN field defines from mpi2_init.h.
+ *  01-19-09  02.00.11  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  05-06-09  02.00.12  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      In all request and reply descriptors, replaced VF_ID
+ *                      field with MSIxIndex field.
+ *                      Removed DevHandle field from
+ *                      MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR and made those
+ *                      bytes reserved.
+ *                      Added RAID Accelerator functionality.
+ *  07-30-09  02.00.13  Bumped MPI2_HEADER_VERSION_UNIT.
+ *  10-28-09  02.00.14  Bumped MPI2_HEADER_VERSION_UNIT.
+ *                      Added MSI-x index mask and shift for Reply Post Host
+ *                      Index register.
+ *                      Added function code for Host Based Discovery Action.
+ *  --------------------------------------------------------------------------
+
+mpi2_cnfg.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-04-07  02.00.01  Added defines for SAS IO Unit Page 2 PhyFlags.
+ *                      Added Manufacturing Page 11.
+ *                      Added MPI2_SAS_EXPANDER0_FLAGS_CONNECTOR_END_DEVICE
+ *                      define.
+ *  06-26-07  02.00.02  Adding generic structure for product-specific
+ *                      Manufacturing pages: MPI2_CONFIG_PAGE_MANUFACTURING_PS.
+ *                      Rework of BIOS Page 2 configuration page.
+ *                      Fixed MPI2_BIOSPAGE2_BOOT_DEVICE to be a union of the
+ *                      forms.
+ *                      Added configuration pages IOC Page 8 and Driver
+ *                      Persistent Mapping Page 0.
+ *  08-31-07  02.00.03  Modified configuration pages dealing with Integrated
+ *                      RAID (Manufacturing Page 4, RAID Volume Pages 0 and 1,
+ *                      RAID Physical Disk Pages 0 and 1, RAID Configuration
+ *                      Page 0).
+ *                      Added new value for AccessStatus field of SAS Device
+ *                      Page 0 (_SATA_NEEDS_INITIALIZATION).
+ *  10-31-07  02.00.04  Added missing SEPDevHandle field to
+ *                      MPI2_CONFIG_PAGE_SAS_ENCLOSURE_0.
+ *  12-18-07  02.00.05  Modified IO Unit Page 0 to use 32-bit version fields for
+ *                      NVDATA.
+ *                      Modified IOC Page 7 to use masks and added field for
+ *                      SASBroadcastPrimitiveMasks.
+ *                      Added MPI2_CONFIG_PAGE_BIOS_4.
+ *                      Added MPI2_CONFIG_PAGE_LOG_0.
+ *  02-29-08  02.00.06  Modified various names to make them 32-character unique.
+ *                      Added SAS Device IDs.
+ *                      Updated Integrated RAID configuration pages including
+ *                      Manufacturing Page 4, IOC Page 6, and RAID Configuration
+ *                      Page 0.
+ *  05-21-08  02.00.07  Added define MPI2_MANPAGE4_MIX_SSD_SAS_SATA.
+ *                      Added define MPI2_MANPAGE4_PHYSDISK_128MB_COERCION.
+ *                      Fixed define MPI2_IOCPAGE8_FLAGS_ENCLOSURE_SLOT_MAPPING.
+ *                      Added missing MaxNumRoutedSasAddresses field to
+ *                      MPI2_CONFIG_PAGE_EXPANDER_0.
+ *                      Added SAS Port Page 0.
+ *                      Modified structure layout for
+ *                      MPI2_CONFIG_PAGE_DRIVER_MAPPING_0.
+ *  06-27-08  02.00.08  Changed MPI2_CONFIG_PAGE_RD_PDISK_1 to use
+ *                      MPI2_RAID_PHYS_DISK1_PATH_MAX to size the array.
+ *  10-02-08  02.00.09  Changed MPI2_RAID_PGAD_CONFIGNUM_MASK from 0x0000FFFF
+ *                      to 0x000000FF.
+ *                      Added two new values for the Physical Disk Coercion Size
+ *                      bits in the Flags field of Manufacturing Page 4.
+ *                      Added product-specific Manufacturing pages 16 to 31.
+ *                      Modified Flags bits for controlling write cache on SATA
+ *                      drives in IO Unit Page 1.
+ *                      Added new bit to AdditionalControlFlags of SAS IO Unit
+ *                      Page 1 to control Invalid Topology Correction.
+ *                      Added SupportedPhysDisks field to RAID Volume Page 1 and
+ *                      added related defines.
+ *                      Added additional defines for RAID Volume Page 0
+ *                      VolumeStatusFlags field.
+ *                      Modified meaning of RAID Volume Page 0 VolumeSettings
+ *                      define for auto-configure of hot-swap drives.
+ *                      Added PhysDiskAttributes field (and related defines) to
+ *                      RAID Physical Disk Page 0.
+ *                      Added MPI2_SAS_PHYINFO_PHY_VACANT define.
+ *                      Added three new DiscoveryStatus bits for SAS IO Unit
+ *                      Page 0 and SAS Expander Page 0.
+ *                      Removed multiplexing information from SAS IO Unit pages.
+ *                      Added BootDeviceWaitTime field to SAS IO Unit Page 4.
+ *                      Removed Zone Address Resolved bit from PhyInfo and from
+ *                      Expander Page 0 Flags field.
+ *                      Added two new AccessStatus values to SAS Device Page 0
+ *                      for indicating routing problems. Added 3 reserved words
+ *                      to this page.
+ *  01-19-09  02.00.10  Fixed defines for GPIOVal field of IO Unit Page 3.
+ *                      Inserted missing reserved field into structure for IOC
+ *                      Page 6.
+ *                      Added more pending task bits to RAID Volume Page 0
+ *                      VolumeStatusFlags defines.
+ *                      Added MPI2_PHYSDISK0_STATUS_FLAG_NOT_CERTIFIED define.
+ *                      Added a new DiscoveryStatus bit for SAS IO Unit Page 0
+ *                      and SAS Expander Page 0 to flag a downstream initiator
+ *                      when in simplified routing mode.
+ *                      Removed SATA Init Failure defines for DiscoveryStatus
+ *                      fields of SAS IO Unit Page 0 and SAS Expander Page 0.
+ *                      Added MPI2_SAS_DEVICE0_ASTATUS_DEVICE_BLOCKED define.
+ *                      Added PortGroups, DmaGroup, and ControlGroup fields to
+ *                      SAS Device Page 0.
+ *  05-06-09  02.00.11  Added structures and defines for IO Unit Page 5 and IO
+ *                      Unit Page 6.
+ *                      Added expander reduced functionality data to SAS
+ *                      Expander Page 0.
+ *                      Added SAS PHY Page 2 and SAS PHY Page 3.
+ *  07-30-09  02.00.12  Added IO Unit Page 7.
+ *                      Added new device ids.
+ *                      Added SAS IO Unit Page 5.
+ *                      Added partial and slumber power management capable flags
+ *                      to SAS Device Page 0 Flags field.
+ *                      Added PhyInfo defines for power condition.
+ *                      Added Ethernet configuration pages.
+ *  10-28-09  02.00.13  Added MPI2_IOUNITPAGE1_ENABLE_HOST_BASED_DISCOVERY.
+ *                      Added SAS PHY Page 4 structure and defines.
+ *  --------------------------------------------------------------------------
+
+mpi2_init.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  10-31-07  02.00.01  Fixed name for pMpi2SCSITaskManagementRequest_t.
+ *  12-18-07  02.00.02  Modified Task Management Target Reset Method defines.
+ *  02-29-08  02.00.03  Added Query Task Set and Query Unit Attention.
+ *  03-03-08  02.00.04  Fixed name of struct _MPI2_SCSI_TASK_MANAGE_REPLY.
+ *  05-21-08  02.00.05  Fixed typo in name of Mpi2SepRequest_t.
+ *  10-02-08  02.00.06  Removed Untagged and No Disconnect values from SCSI IO
+ *                      Control field Task Attribute flags.
+ *                      Moved LUN field defines to mpi2.h becasue they are
+ *                      common to many structures.
+ *  05-06-09  02.00.07  Changed task management type of Query Unit Attention to
+ *                      Query Asynchronous Event.
+ *                      Defined two new bits in the SlotStatus field of the SCSI
+ *                      Enclosure Processor Request and Reply.
+ *  10-28-09  02.00.08  Added defines for decoding the ResponseInfo bytes for
+ *                      both SCSI IO Error Reply and SCSI Task Management Reply.
+ *                      Added ResponseInfo field to MPI2_SCSI_TASK_MANAGE_REPLY.
+ *                      Added MPI2_SCSITASKMGMT_RSP_TM_OVERLAPPED_TAG define.
+ *  --------------------------------------------------------------------------
+
+mpi2_ioc.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-04-07  02.00.01  In IOCFacts Reply structure, renamed MaxDevices to
+ *                      MaxTargets.
+ *                      Added TotalImageSize field to FWDownload Request.
+ *                      Added reserved words to FWUpload Request.
+ *  06-26-07  02.00.02  Added IR Configuration Change List Event.
+ *  08-31-07  02.00.03  Removed SystemReplyQueueDepth field from the IOCInit
+ *                      request and replaced it with
+ *                      ReplyDescriptorPostQueueDepth and ReplyFreeQueueDepth.
+ *                      Replaced the MinReplyQueueDepth field of the IOCFacts
+ *                      reply with MaxReplyDescriptorPostQueueDepth.
+ *                      Added MPI2_RDPQ_DEPTH_MIN define to specify the minimum
+ *                      depth for the Reply Descriptor Post Queue.
+ *                      Added SASAddress field to Initiator Device Table
+ *                      Overflow Event data.
+ *  10-31-07  02.00.04  Added ReasonCode MPI2_EVENT_SAS_INIT_RC_NOT_RESPONDING
+ *                      for SAS Initiator Device Status Change Event data.
+ *                      Modified Reason Code defines for SAS Topology Change
+ *                      List Event data, including adding a bit for PHY Vacant
+ *                      status, and adding a mask for the Reason Code.
+ *                      Added define for
+ *                      MPI2_EVENT_SAS_TOPO_ES_DELAY_NOT_RESPONDING.
+ *                      Added define for MPI2_EXT_IMAGE_TYPE_MEGARAID.
+ *  12-18-07  02.00.05  Added Boot Status defines for the IOCExceptions field of
+ *                      the IOCFacts Reply.
+ *                      Removed MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER define.
+ *                      Moved MPI2_VERSION_UNION to mpi2.h.
+ *                      Changed MPI2_EVENT_NOTIFICATION_REQUEST to use masks
+ *                      instead of enables, and added SASBroadcastPrimitiveMasks
+ *                      field.
+ *                      Added Log Entry Added Event and related structure.
+ *  02-29-08  02.00.06  Added define MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID.
+ *                      Removed define MPI2_IOCFACTS_PROTOCOL_SMP_TARGET.
+ *                      Added MaxVolumes and MaxPersistentEntries fields to
+ *                      IOCFacts reply.
+ *                      Added ProtocalFlags and IOCCapabilities fields to
+ *                      MPI2_FW_IMAGE_HEADER.
+ *                      Removed MPI2_PORTENABLE_FLAGS_ENABLE_SINGLE_PORT.
+ *  03-03-08  02.00.07  Fixed MPI2_FW_IMAGE_HEADER by changing Reserved26 to
+ *                      a U16 (from a U32).
+ *                      Removed extra 's' from EventMasks name.
+ *  06-27-08  02.00.08  Fixed an offset in a comment.
+ *  10-02-08  02.00.09  Removed SystemReplyFrameSize from MPI2_IOC_INIT_REQUEST.
+ *                      Removed CurReplyFrameSize from MPI2_IOC_FACTS_REPLY and
+ *                      renamed MinReplyFrameSize to ReplyFrameSize.
+ *                      Added MPI2_IOCFACTS_EXCEPT_IR_FOREIGN_CONFIG_MAX.
+ *                      Added two new RAIDOperation values for Integrated RAID
+ *                      Operations Status Event data.
+ *                      Added four new IR Configuration Change List Event data
+ *                      ReasonCode values.
+ *                      Added two new ReasonCode defines for SAS Device Status
+ *                      Change Event data.
+ *                      Added three new DiscoveryStatus bits for the SAS
+ *                      Discovery event data.
+ *                      Added Multiplexing Status Change bit to the PhyStatus
+ *                      field of the SAS Topology Change List event data.
+ *                      Removed define for MPI2_INIT_IMAGE_BOOTFLAGS_XMEMCOPY.
+ *                      BootFlags are now product-specific.
+ *                      Added defines for the indivdual signature bytes
+ *                      for MPI2_INIT_IMAGE_FOOTER.
+ *  01-19-09  02.00.10  Added MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY define.
+ *                      Added MPI2_EVENT_SAS_DISC_DS_DOWNSTREAM_INITIATOR
+ *                      define.
+ *                      Added MPI2_EVENT_SAS_DEV_STAT_RC_SATA_INIT_FAILURE
+ *                      define.
+ *                      Removed MPI2_EVENT_SAS_DISC_DS_SATA_INIT_FAILURE define.
+ *  05-06-09  02.00.11  Added MPI2_IOCFACTS_CAPABILITY_RAID_ACCELERATOR define.
+ *                      Added MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX define.
+ *                      Added two new reason codes for SAS Device Status Change
+ *                      Event.
+ *                      Added new event: SAS PHY Counter.
+ *  07-30-09  02.00.12  Added GPIO Interrupt event define and structure.
+ *                      Added MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER define.
+ *                      Added new product id family for 2208.
+ *  10-28-09  02.00.13  Added HostMSIxVectors field to MPI2_IOC_INIT_REQUEST.
+ *                      Added MaxMSIxVectors field to MPI2_IOC_FACTS_REPLY.
+ *                      Added MinDevHandle field to MPI2_IOC_FACTS_REPLY.
+ *                      Added MPI2_IOCFACTS_CAPABILITY_HOST_BASED_DISCOVERY.
+ *                      Added MPI2_EVENT_HOST_BASED_DISCOVERY_PHY define.
+ *                      Added MPI2_EVENT_SAS_TOPO_ES_NO_EXPANDER define.
+ *                      Added Host Based Discovery Phy Event data.
+ *                      Added defines for ProductID Product field
+ *                      (MPI2_FW_HEADER_PID_).
+ *                      Modified values for SAS ProductID Family
+ *                      (MPI2_FW_HEADER_PID_FAMILY_).
+ *  --------------------------------------------------------------------------
+
+mpi2_raid.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  08-31-07  02.00.01  Modifications to RAID Action request and reply,
+ *                      including the Actions and ActionData.
+ *  02-29-08  02.00.02  Added MPI2_RAID_ACTION_ADATA_DISABL_FULL_REBUILD.
+ *  05-21-08  02.00.03  Added MPI2_RAID_VOL_CREATION_NUM_PHYSDISKS so that
+ *                      the PhysDisk array in MPI2_RAID_VOLUME_CREATION_STRUCT
+ *                      can be sized by the build environment.
+ *  07-30-09  02.00.04  Added proper define for the Use Default Settings bit of
+ *                      VolumeCreationFlags and marked the old one as obsolete.
+ *  --------------------------------------------------------------------------
+
+mpi2_sas.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-26-07  02.00.01  Added Clear All Persistent Operation to SAS IO Unit
+ *                      Control Request.
+ *  10-02-08  02.00.02  Added Set IOC Parameter Operation to SAS IO Unit Control
+ *                      Request.
+ *  10-28-09  02.00.03  Changed the type of SGL in MPI2_SATA_PASSTHROUGH_REQUEST
+ *                      to MPI2_SGE_IO_UNION since it supports chained SGLs.
+ *  --------------------------------------------------------------------------
+
+mpi2_targ.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  08-31-07  02.00.01  Added Command Buffer Data Location Address Space bits to
+ *                      BufferPostFlags field of CommandBufferPostBase Request.
+ *  02-29-08  02.00.02  Modified various names to make them 32-character unique.
+ *  10-02-08  02.00.03  Removed NextCmdBufferOffset from
+ *                      MPI2_TARGET_CMD_BUF_POST_BASE_REQUEST.
+ *                      Target Status Send Request only takes a single SGE for
+ *                      response data.
+ *  --------------------------------------------------------------------------
+
+mpi2_tool.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  12-18-07  02.00.01  Added Diagnostic Buffer Post and Diagnostic Release
+ *                      structures and defines.
+ *  02-29-08  02.00.02  Modified various names to make them 32-character unique.
+ *  05-06-09  02.00.03  Added ISTWI Read Write Tool and Diagnostic CLI Tool.
+ *  07-30-09  02.00.04  Added ExtendedType field to DiagnosticBufferPost request
+ *                      and reply messages.
+ *                      Added MPI2_DIAG_BUF_TYPE_EXTENDED.
+ *                      Incremented MPI2_DIAG_BUF_TYPE_COUNT.
+ *  --------------------------------------------------------------------------
+
+mpi2_type.h
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  --------------------------------------------------------------------------
+
+mpi2_ra.h
+ *  05-06-09  02.00.00  Initial version.
+ *  --------------------------------------------------------------------------
+
+mpi2_hbd.h
+ *  10-28-09  02.00.00  Initial version.
+ *  --------------------------------------------------------------------------
+
+
+mpi2_history.txt         Parts list history
+
+Filename     02.00.14  02.00.13  02.00.12
+----------   --------  --------  --------
+mpi2.h       02.00.14  02.00.13  02.00.12
+mpi2_cnfg.h  02.00.13  02.00.12  02.00.11
+mpi2_init.h  02.00.08  02.00.07  02.00.07
+mpi2_ioc.h   02.00.13  02.00.12  02.00.11
+mpi2_raid.h  02.00.04  02.00.04  02.00.03
+mpi2_sas.h   02.00.03  02.00.02  02.00.02
+mpi2_targ.h  02.00.03  02.00.03  02.00.03
+mpi2_tool.h  02.00.04  02.00.04  02.00.03
+mpi2_type.h  02.00.00  02.00.00  02.00.00
+mpi2_ra.h    02.00.00  02.00.00  02.00.00
+mpi2_hbd.h   02.00.00
+
+Filename     02.00.11  02.00.10  02.00.09  02.00.08  02.00.07  02.00.06
+----------   --------  --------  --------  --------  --------  --------
+mpi2.h       02.00.11  02.00.10  02.00.09  02.00.08  02.00.07  02.00.06
+mpi2_cnfg.h  02.00.10  02.00.09  02.00.08  02.00.07  02.00.06  02.00.06
+mpi2_init.h  02.00.06  02.00.06  02.00.05  02.00.05  02.00.04  02.00.03
+mpi2_ioc.h   02.00.10  02.00.09  02.00.08  02.00.07  02.00.07  02.00.06
+mpi2_raid.h  02.00.03  02.00.03  02.00.03  02.00.03  02.00.02  02.00.02
+mpi2_sas.h   02.00.02  02.00.02  02.00.01  02.00.01  02.00.01  02.00.01
+mpi2_targ.h  02.00.03  02.00.03  02.00.02  02.00.02  02.00.02  02.00.02
+mpi2_tool.h  02.00.02  02.00.02  02.00.02  02.00.02  02.00.02  02.00.02
+mpi2_type.h  02.00.00  02.00.00  02.00.00  02.00.00  02.00.00  02.00.00
+
+Filename     02.00.05  02.00.04  02.00.03  02.00.02  02.00.01  02.00.00
+----------   --------  --------  --------  --------  --------  --------
+mpi2.h       02.00.05  02.00.04  02.00.03  02.00.02  02.00.01  02.00.00
+mpi2_cnfg.h  02.00.05  02.00.04  02.00.03  02.00.02  02.00.01  02.00.00
+mpi2_init.h  02.00.02  02.00.01  02.00.00  02.00.00  02.00.00  02.00.00
+mpi2_ioc.h   02.00.05  02.00.04  02.00.03  02.00.02  02.00.01  02.00.00
+mpi2_raid.h  02.00.01  02.00.01  02.00.01  02.00.00  02.00.00  02.00.00
+mpi2_sas.h   02.00.01  02.00.01  02.00.01  02.00.01  02.00.00  02.00.00
+mpi2_targ.h  02.00.01  02.00.01  02.00.01  02.00.00  02.00.00  02.00.00
+mpi2_tool.h  02.00.01  02.00.00  02.00.00  02.00.00  02.00.00  02.00.00
+mpi2_type.h  02.00.00  02.00.00  02.00.00  02.00.00  02.00.00  02.00.00
+
diff --git a/sys/dev/mps/mpi/mpi2_init.h b/sys/dev/mps/mpi/mpi2_init.h
new file mode 100644
index 00000000000..8d2b1f98d88
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_init.h
@@ -0,0 +1,454 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_init.h
+ *          Title:  MPI SCSI initiator mode messages and structures
+ *  Creation Date:  June 23, 2006
+ *
+ *    mpi2_init.h Version:  02.00.08
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  10-31-07  02.00.01  Fixed name for pMpi2SCSITaskManagementRequest_t.
+ *  12-18-07  02.00.02  Modified Task Management Target Reset Method defines.
+ *  02-29-08  02.00.03  Added Query Task Set and Query Unit Attention.
+ *  03-03-08  02.00.04  Fixed name of struct _MPI2_SCSI_TASK_MANAGE_REPLY.
+ *  05-21-08  02.00.05  Fixed typo in name of Mpi2SepRequest_t.
+ *  10-02-08  02.00.06  Removed Untagged and No Disconnect values from SCSI IO
+ *                      Control field Task Attribute flags.
+ *                      Moved LUN field defines to mpi2.h becasue they are
+ *                      common to many structures.
+ *  05-06-09  02.00.07  Changed task management type of Query Unit Attention to
+ *                      Query Asynchronous Event.
+ *                      Defined two new bits in the SlotStatus field of the SCSI
+ *                      Enclosure Processor Request and Reply.
+ *  10-28-09  02.00.08  Added defines for decoding the ResponseInfo bytes for
+ *                      both SCSI IO Error Reply and SCSI Task Management Reply.
+ *                      Added ResponseInfo field to MPI2_SCSI_TASK_MANAGE_REPLY.
+ *                      Added MPI2_SCSITASKMGMT_RSP_TM_OVERLAPPED_TAG define.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_INIT_H
+#define MPI2_INIT_H
+
+/*****************************************************************************
+*
+*               SCSI Initiator Messages
+*
+*****************************************************************************/
+
+/****************************************************************************
+*  SCSI IO messages and associated structures
+****************************************************************************/
+
+typedef struct
+{
+    U8                      CDB[20];                    /* 0x00 */
+    U32                     PrimaryReferenceTag;        /* 0x14 */
+    U16                     PrimaryApplicationTag;      /* 0x18 */
+    U16                     PrimaryApplicationTagMask;  /* 0x1A */
+    U32                     TransferLength;             /* 0x1C */
+} MPI2_SCSI_IO_CDB_EEDP32, MPI2_POINTER PTR_MPI2_SCSI_IO_CDB_EEDP32,
+  Mpi2ScsiIoCdbEedp32_t, MPI2_POINTER pMpi2ScsiIoCdbEedp32_t;
+
+/* TBD: I don't think this is needed for MPI2/Gen2 */
+#if 0
+typedef struct
+{
+    U8                      CDB[16];                    /* 0x00 */
+    U32                     DataLength;                 /* 0x10 */
+    U32                     PrimaryReferenceTag;        /* 0x14 */
+    U16                     PrimaryApplicationTag;      /* 0x18 */
+    U16                     PrimaryApplicationTagMask;  /* 0x1A */
+    U32                     TransferLength;             /* 0x1C */
+} MPI2_SCSI_IO32_CDB_EEDP16, MPI2_POINTER PTR_MPI2_SCSI_IO32_CDB_EEDP16,
+  Mpi2ScsiIo32CdbEedp16_t, MPI2_POINTER pMpi2ScsiIo32CdbEedp16_t;
+#endif
+
+typedef union
+{
+    U8                      CDB32[32];
+    MPI2_SCSI_IO_CDB_EEDP32 EEDP32;
+    MPI2_SGE_SIMPLE_UNION   SGE;
+} MPI2_SCSI_IO_CDB_UNION, MPI2_POINTER PTR_MPI2_SCSI_IO_CDB_UNION,
+  Mpi2ScsiIoCdb_t, MPI2_POINTER pMpi2ScsiIoCdb_t;
+
+/* SCSI IO Request Message */
+typedef struct _MPI2_SCSI_IO_REQUEST
+{
+    U16                     DevHandle;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved1;                      /* 0x04 */
+    U8                      Reserved2;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved3;                      /* 0x0A */
+    U32                     SenseBufferLowAddress;          /* 0x0C */
+    U16                     SGLFlags;                       /* 0x10 */
+    U8                      SenseBufferLength;              /* 0x12 */
+    U8                      Reserved4;                      /* 0x13 */
+    U8                      SGLOffset0;                     /* 0x14 */
+    U8                      SGLOffset1;                     /* 0x15 */
+    U8                      SGLOffset2;                     /* 0x16 */
+    U8                      SGLOffset3;                     /* 0x17 */
+    U32                     SkipCount;                      /* 0x18 */
+    U32                     DataLength;                     /* 0x1C */
+    U32                     BidirectionalDataLength;        /* 0x20 */
+    U16                     IoFlags;                        /* 0x24 */
+    U16                     EEDPFlags;                      /* 0x26 */
+    U32                     EEDPBlockSize;                  /* 0x28 */
+    U32                     SecondaryReferenceTag;          /* 0x2C */
+    U16                     SecondaryApplicationTag;        /* 0x30 */
+    U16                     ApplicationTagTranslationMask;  /* 0x32 */
+    U8                      LUN[8];                         /* 0x34 */
+    U32                     Control;                        /* 0x3C */
+    MPI2_SCSI_IO_CDB_UNION  CDB;                            /* 0x40 */
+    MPI2_SGE_IO_UNION       SGL;                            /* 0x60 */
+} MPI2_SCSI_IO_REQUEST, MPI2_POINTER PTR_MPI2_SCSI_IO_REQUEST,
+  Mpi2SCSIIORequest_t, MPI2_POINTER pMpi2SCSIIORequest_t;
+
+/* SCSI IO MsgFlags bits */
+
+/* MsgFlags for SenseBufferAddressSpace */
+#define MPI2_SCSIIO_MSGFLAGS_MASK_SENSE_ADDR        (0x0C)
+#define MPI2_SCSIIO_MSGFLAGS_SYSTEM_SENSE_ADDR      (0x00)
+#define MPI2_SCSIIO_MSGFLAGS_IOCDDR_SENSE_ADDR      (0x04)
+#define MPI2_SCSIIO_MSGFLAGS_IOCPLB_SENSE_ADDR      (0x08)
+#define MPI2_SCSIIO_MSGFLAGS_IOCPLBNTA_SENSE_ADDR   (0x0C)
+
+/* SCSI IO SGLFlags bits */
+
+/* base values for Data Location Address Space */
+#define MPI2_SCSIIO_SGLFLAGS_ADDR_MASK              (0x0C)
+#define MPI2_SCSIIO_SGLFLAGS_SYSTEM_ADDR            (0x00)
+#define MPI2_SCSIIO_SGLFLAGS_IOCDDR_ADDR            (0x04)
+#define MPI2_SCSIIO_SGLFLAGS_IOCPLB_ADDR            (0x08)
+#define MPI2_SCSIIO_SGLFLAGS_IOCPLBNTA_ADDR         (0x0C)
+
+/* base values for Type */
+#define MPI2_SCSIIO_SGLFLAGS_TYPE_MASK              (0x03)
+#define MPI2_SCSIIO_SGLFLAGS_TYPE_MPI               (0x00)
+#define MPI2_SCSIIO_SGLFLAGS_TYPE_IEEE32            (0x01)
+#define MPI2_SCSIIO_SGLFLAGS_TYPE_IEEE64            (0x02)
+
+/* shift values for each sub-field */
+#define MPI2_SCSIIO_SGLFLAGS_SGL3_SHIFT             (12)
+#define MPI2_SCSIIO_SGLFLAGS_SGL2_SHIFT             (8)
+#define MPI2_SCSIIO_SGLFLAGS_SGL1_SHIFT             (4)
+#define MPI2_SCSIIO_SGLFLAGS_SGL0_SHIFT             (0)
+
+/* SCSI IO IoFlags bits */
+
+/* Large CDB Address Space */
+#define MPI2_SCSIIO_CDB_ADDR_MASK                   (0x6000)
+#define MPI2_SCSIIO_CDB_ADDR_SYSTEM                 (0x0000)
+#define MPI2_SCSIIO_CDB_ADDR_IOCDDR                 (0x2000)
+#define MPI2_SCSIIO_CDB_ADDR_IOCPLB                 (0x4000)
+#define MPI2_SCSIIO_CDB_ADDR_IOCPLBNTA              (0x6000)
+
+#define MPI2_SCSIIO_IOFLAGS_LARGE_CDB               (0x1000)
+#define MPI2_SCSIIO_IOFLAGS_BIDIRECTIONAL           (0x0800)
+#define MPI2_SCSIIO_IOFLAGS_MULTICAST               (0x0400)
+#define MPI2_SCSIIO_IOFLAGS_CMD_DETERMINES_DATA_DIR (0x0200)
+#define MPI2_SCSIIO_IOFLAGS_CDBLENGTH_MASK          (0x01FF)
+
+/* SCSI IO EEDPFlags bits */
+
+#define MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG        (0x8000)
+#define MPI2_SCSIIO_EEDPFLAGS_INC_SEC_REFTAG        (0x4000)
+#define MPI2_SCSIIO_EEDPFLAGS_INC_PRI_APPTAG        (0x2000)
+#define MPI2_SCSIIO_EEDPFLAGS_INC_SEC_APPTAG        (0x1000)
+
+#define MPI2_SCSIIO_EEDPFLAGS_CHECK_REFTAG          (0x0400)
+#define MPI2_SCSIIO_EEDPFLAGS_CHECK_APPTAG          (0x0200)
+#define MPI2_SCSIIO_EEDPFLAGS_CHECK_GUARD           (0x0100)
+
+#define MPI2_SCSIIO_EEDPFLAGS_PASSTHRU_REFTAG       (0x0008)
+
+#define MPI2_SCSIIO_EEDPFLAGS_MASK_OP               (0x0007)
+#define MPI2_SCSIIO_EEDPFLAGS_NOOP_OP               (0x0000)
+#define MPI2_SCSIIO_EEDPFLAGS_CHECK_OP              (0x0001)
+#define MPI2_SCSIIO_EEDPFLAGS_STRIP_OP              (0x0002)
+#define MPI2_SCSIIO_EEDPFLAGS_CHECK_REMOVE_OP       (0x0003)
+#define MPI2_SCSIIO_EEDPFLAGS_INSERT_OP             (0x0004)
+#define MPI2_SCSIIO_EEDPFLAGS_REPLACE_OP            (0x0006)
+#define MPI2_SCSIIO_EEDPFLAGS_CHECK_REGEN_OP        (0x0007)
+
+/* SCSI IO LUN fields: use MPI2_LUN_ from mpi2.h */
+
+/* SCSI IO Control bits */
+#define MPI2_SCSIIO_CONTROL_ADDCDBLEN_MASK      (0xFC000000)
+#define MPI2_SCSIIO_CONTROL_ADDCDBLEN_SHIFT     (26)
+
+#define MPI2_SCSIIO_CONTROL_DATADIRECTION_MASK  (0x03000000)
+#define MPI2_SCSIIO_CONTROL_NODATATRANSFER      (0x00000000)
+#define MPI2_SCSIIO_CONTROL_WRITE               (0x01000000)
+#define MPI2_SCSIIO_CONTROL_READ                (0x02000000)
+#define MPI2_SCSIIO_CONTROL_BIDIRECTIONAL       (0x03000000)
+
+#define MPI2_SCSIIO_CONTROL_TASKPRI_MASK        (0x00007800)
+#define MPI2_SCSIIO_CONTROL_TASKPRI_SHIFT       (11)
+
+#define MPI2_SCSIIO_CONTROL_TASKATTRIBUTE_MASK  (0x00000700)
+#define MPI2_SCSIIO_CONTROL_SIMPLEQ             (0x00000000)
+#define MPI2_SCSIIO_CONTROL_HEADOFQ             (0x00000100)
+#define MPI2_SCSIIO_CONTROL_ORDEREDQ            (0x00000200)
+#define MPI2_SCSIIO_CONTROL_ACAQ                (0x00000400)
+
+#define MPI2_SCSIIO_CONTROL_TLR_MASK            (0x000000C0)
+#define MPI2_SCSIIO_CONTROL_NO_TLR              (0x00000000)
+#define MPI2_SCSIIO_CONTROL_TLR_ON              (0x00000040)
+#define MPI2_SCSIIO_CONTROL_TLR_OFF             (0x00000080)
+
+
+/* SCSI IO Error Reply Message */
+typedef struct _MPI2_SCSI_IO_REPLY
+{
+    U16                     DevHandle;                      /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved1;                      /* 0x04 */
+    U8                      Reserved2;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved3;                      /* 0x0A */
+    U8                      SCSIStatus;                     /* 0x0C */
+    U8                      SCSIState;                      /* 0x0D */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+    U32                     TransferCount;                  /* 0x14 */
+    U32                     SenseCount;                     /* 0x18 */
+    U32                     ResponseInfo;                   /* 0x1C */
+    U16                     TaskTag;                        /* 0x20 */
+    U16                     Reserved4;                      /* 0x22 */
+    U32                     BidirectionalTransferCount;     /* 0x24 */
+    U32                     Reserved5;                      /* 0x28 */
+    U32                     Reserved6;                      /* 0x2C */
+} MPI2_SCSI_IO_REPLY, MPI2_POINTER PTR_MPI2_SCSI_IO_REPLY,
+  Mpi2SCSIIOReply_t, MPI2_POINTER pMpi2SCSIIOReply_t;
+
+/* SCSI IO Reply SCSIStatus values (SAM-4 status codes) */
+
+#define MPI2_SCSI_STATUS_GOOD                   (0x00)
+#define MPI2_SCSI_STATUS_CHECK_CONDITION        (0x02)
+#define MPI2_SCSI_STATUS_CONDITION_MET          (0x04)
+#define MPI2_SCSI_STATUS_BUSY                   (0x08)
+#define MPI2_SCSI_STATUS_INTERMEDIATE           (0x10)
+#define MPI2_SCSI_STATUS_INTERMEDIATE_CONDMET   (0x14)
+#define MPI2_SCSI_STATUS_RESERVATION_CONFLICT   (0x18)
+#define MPI2_SCSI_STATUS_COMMAND_TERMINATED     (0x22) /* obsolete */
+#define MPI2_SCSI_STATUS_TASK_SET_FULL          (0x28)
+#define MPI2_SCSI_STATUS_ACA_ACTIVE             (0x30)
+#define MPI2_SCSI_STATUS_TASK_ABORTED           (0x40)
+
+/* SCSI IO Reply SCSIState flags */
+
+#define MPI2_SCSI_STATE_RESPONSE_INFO_VALID     (0x10)
+#define MPI2_SCSI_STATE_TERMINATED              (0x08)
+#define MPI2_SCSI_STATE_NO_SCSI_STATUS          (0x04)
+#define MPI2_SCSI_STATE_AUTOSENSE_FAILED        (0x02)
+#define MPI2_SCSI_STATE_AUTOSENSE_VALID         (0x01)
+
+/* masks and shifts for the ResponseInfo field */
+
+#define MPI2_SCSI_RI_MASK_REASONCODE            (0x000000FF)
+#define MPI2_SCSI_RI_SHIFT_REASONCODE           (0)
+
+#define MPI2_SCSI_TASKTAG_UNKNOWN               (0xFFFF)
+
+
+/****************************************************************************
+*  SCSI Task Management messages
+****************************************************************************/
+
+/* SCSI Task Management Request Message */
+typedef struct _MPI2_SCSI_TASK_MANAGE_REQUEST
+{
+    U16                     DevHandle;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U8                      Reserved1;                      /* 0x04 */
+    U8                      TaskType;                       /* 0x05 */
+    U8                      Reserved2;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved3;                      /* 0x0A */
+    U8                      LUN[8];                         /* 0x0C */
+    U32                     Reserved4[7];                   /* 0x14 */
+    U16                     TaskMID;                        /* 0x30 */
+    U16                     Reserved5;                      /* 0x32 */
+} MPI2_SCSI_TASK_MANAGE_REQUEST,
+  MPI2_POINTER PTR_MPI2_SCSI_TASK_MANAGE_REQUEST,
+  Mpi2SCSITaskManagementRequest_t,
+  MPI2_POINTER pMpi2SCSITaskManagementRequest_t;
+
+/* TaskType values */
+
+#define MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK           (0x01)
+#define MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET        (0x02)
+#define MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET         (0x03)
+#define MPI2_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET   (0x05)
+#define MPI2_SCSITASKMGMT_TASKTYPE_CLEAR_TASK_SET       (0x06)
+#define MPI2_SCSITASKMGMT_TASKTYPE_QUERY_TASK           (0x07)
+#define MPI2_SCSITASKMGMT_TASKTYPE_CLR_ACA              (0x08)
+#define MPI2_SCSITASKMGMT_TASKTYPE_QRY_TASK_SET         (0x09)
+#define MPI2_SCSITASKMGMT_TASKTYPE_QRY_ASYNC_EVENT      (0x0A)
+
+/* obsolete TaskType name */
+#define MPI2_SCSITASKMGMT_TASKTYPE_QRY_UNIT_ATTENTION   (MPI2_SCSITASKMGMT_TASKTYPE_QRY_ASYNC_EVENT)
+
+/* MsgFlags bits */
+
+#define MPI2_SCSITASKMGMT_MSGFLAGS_MASK_TARGET_RESET    (0x18)
+#define MPI2_SCSITASKMGMT_MSGFLAGS_LINK_RESET           (0x00)
+#define MPI2_SCSITASKMGMT_MSGFLAGS_NEXUS_RESET_SRST     (0x08)
+#define MPI2_SCSITASKMGMT_MSGFLAGS_SAS_HARD_LINK_RESET  (0x10)
+
+#define MPI2_SCSITASKMGMT_MSGFLAGS_DO_NOT_SEND_TASK_IU  (0x01)
+
+
+
+/* SCSI Task Management Reply Message */
+typedef struct _MPI2_SCSI_TASK_MANAGE_REPLY
+{
+    U16                     DevHandle;                      /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U8                      ResponseCode;                   /* 0x04 */
+    U8                      TaskType;                       /* 0x05 */
+    U8                      Reserved1;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved2;                      /* 0x0A */
+    U16                     Reserved3;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+    U32                     TerminationCount;               /* 0x14 */
+    U32                     ResponseInfo;                   /* 0x18 */
+} MPI2_SCSI_TASK_MANAGE_REPLY,
+  MPI2_POINTER PTR_MPI2_SCSI_TASK_MANAGE_REPLY,
+  Mpi2SCSITaskManagementReply_t, MPI2_POINTER pMpi2SCSIManagementReply_t;
+
+/* ResponseCode values */
+
+#define MPI2_SCSITASKMGMT_RSP_TM_COMPLETE               (0x00)
+#define MPI2_SCSITASKMGMT_RSP_INVALID_FRAME             (0x02)
+#define MPI2_SCSITASKMGMT_RSP_TM_NOT_SUPPORTED          (0x04)
+#define MPI2_SCSITASKMGMT_RSP_TM_FAILED                 (0x05)
+#define MPI2_SCSITASKMGMT_RSP_TM_SUCCEEDED              (0x08)
+#define MPI2_SCSITASKMGMT_RSP_TM_INVALID_LUN            (0x09)
+#define MPI2_SCSITASKMGMT_RSP_TM_OVERLAPPED_TAG         (0x0A)
+#define MPI2_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC          (0x80)
+
+/* masks and shifts for the ResponseInfo field */
+
+#define MPI2_SCSITASKMGMT_RI_MASK_REASONCODE            (0x000000FF)
+#define MPI2_SCSITASKMGMT_RI_SHIFT_REASONCODE           (0)
+#define MPI2_SCSITASKMGMT_RI_MASK_ARI2                  (0x0000FF00)
+#define MPI2_SCSITASKMGMT_RI_SHIFT_ARI2                 (8)
+#define MPI2_SCSITASKMGMT_RI_MASK_ARI1                  (0x00FF0000)
+#define MPI2_SCSITASKMGMT_RI_SHIFT_ARI1                 (16)
+#define MPI2_SCSITASKMGMT_RI_MASK_ARI0                  (0xFF000000)
+#define MPI2_SCSITASKMGMT_RI_SHIFT_ARI0                 (24)
+
+
+/****************************************************************************
+*  SCSI Enclosure Processor messages
+****************************************************************************/
+
+/* SCSI Enclosure Processor Request Message */
+typedef struct _MPI2_SEP_REQUEST
+{
+    U16                     DevHandle;          /* 0x00 */
+    U8                      ChainOffset;        /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U8                      Action;             /* 0x04 */
+    U8                      Flags;              /* 0x05 */
+    U8                      Reserved1;          /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved2;          /* 0x0A */
+    U32                     SlotStatus;         /* 0x0C */
+    U32                     Reserved3;          /* 0x10 */
+    U32                     Reserved4;          /* 0x14 */
+    U32                     Reserved5;          /* 0x18 */
+    U16                     Slot;               /* 0x1C */
+    U16                     EnclosureHandle;    /* 0x1E */
+} MPI2_SEP_REQUEST, MPI2_POINTER PTR_MPI2_SEP_REQUEST,
+  Mpi2SepRequest_t, MPI2_POINTER pMpi2SepRequest_t;
+
+/* Action defines */
+#define MPI2_SEP_REQ_ACTION_WRITE_STATUS                (0x00)
+#define MPI2_SEP_REQ_ACTION_READ_STATUS                 (0x01)
+
+/* Flags defines */
+#define MPI2_SEP_REQ_FLAGS_DEVHANDLE_ADDRESS            (0x00)
+#define MPI2_SEP_REQ_FLAGS_ENCLOSURE_SLOT_ADDRESS       (0x01)
+
+/* SlotStatus defines */
+#define MPI2_SEP_REQ_SLOTSTATUS_REQUEST_REMOVE          (0x00040000)
+#define MPI2_SEP_REQ_SLOTSTATUS_IDENTIFY_REQUEST        (0x00020000)
+#define MPI2_SEP_REQ_SLOTSTATUS_REBUILD_STOPPED         (0x00000200)
+#define MPI2_SEP_REQ_SLOTSTATUS_HOT_SPARE               (0x00000100)
+#define MPI2_SEP_REQ_SLOTSTATUS_UNCONFIGURED            (0x00000080)
+#define MPI2_SEP_REQ_SLOTSTATUS_PREDICTED_FAULT         (0x00000040)
+#define MPI2_SEP_REQ_SLOTSTATUS_IN_CRITICAL_ARRAY       (0x00000010)
+#define MPI2_SEP_REQ_SLOTSTATUS_IN_FAILED_ARRAY         (0x00000008)
+#define MPI2_SEP_REQ_SLOTSTATUS_DEV_REBUILDING          (0x00000004)
+#define MPI2_SEP_REQ_SLOTSTATUS_DEV_FAULTY              (0x00000002)
+#define MPI2_SEP_REQ_SLOTSTATUS_NO_ERROR                (0x00000001)
+
+
+/* SCSI Enclosure Processor Reply Message */
+typedef struct _MPI2_SEP_REPLY
+{
+    U16                     DevHandle;          /* 0x00 */
+    U8                      MsgLength;          /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U8                      Action;             /* 0x04 */
+    U8                      Flags;              /* 0x05 */
+    U8                      Reserved1;          /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved2;          /* 0x0A */
+    U16                     Reserved3;          /* 0x0C */
+    U16                     IOCStatus;          /* 0x0E */
+    U32                     IOCLogInfo;         /* 0x10 */
+    U32                     SlotStatus;         /* 0x14 */
+    U32                     Reserved4;          /* 0x18 */
+    U16                     Slot;               /* 0x1C */
+    U16                     EnclosureHandle;    /* 0x1E */
+} MPI2_SEP_REPLY, MPI2_POINTER PTR_MPI2_SEP_REPLY,
+  Mpi2SepReply_t, MPI2_POINTER pMpi2SepReply_t;
+
+/* SlotStatus defines */
+#define MPI2_SEP_REPLY_SLOTSTATUS_REMOVE_READY          (0x00040000)
+#define MPI2_SEP_REPLY_SLOTSTATUS_IDENTIFY_REQUEST      (0x00020000)
+#define MPI2_SEP_REPLY_SLOTSTATUS_REBUILD_STOPPED       (0x00000200)
+#define MPI2_SEP_REPLY_SLOTSTATUS_HOT_SPARE             (0x00000100)
+#define MPI2_SEP_REPLY_SLOTSTATUS_UNCONFIGURED          (0x00000080)
+#define MPI2_SEP_REPLY_SLOTSTATUS_PREDICTED_FAULT       (0x00000040)
+#define MPI2_SEP_REPLY_SLOTSTATUS_IN_CRITICAL_ARRAY     (0x00000010)
+#define MPI2_SEP_REPLY_SLOTSTATUS_IN_FAILED_ARRAY       (0x00000008)
+#define MPI2_SEP_REPLY_SLOTSTATUS_DEV_REBUILDING        (0x00000004)
+#define MPI2_SEP_REPLY_SLOTSTATUS_DEV_FAULTY            (0x00000002)
+#define MPI2_SEP_REPLY_SLOTSTATUS_NO_ERROR              (0x00000001)
+
+
+#endif
+
+
diff --git a/sys/dev/mps/mpi/mpi2_ioc.h b/sys/dev/mps/mpi/mpi2_ioc.h
new file mode 100644
index 00000000000..24a56625ef3
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_ioc.h
@@ -0,0 +1,1414 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_ioc.h
+ *          Title:  MPI IOC, Port, Event, FW Download, and FW Upload messages
+ *  Creation Date:  October 11, 2006
+ *
+ *  mpi2_ioc.h Version:  02.00.13
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-04-07  02.00.01  In IOCFacts Reply structure, renamed MaxDevices to
+ *                      MaxTargets.
+ *                      Added TotalImageSize field to FWDownload Request.
+ *                      Added reserved words to FWUpload Request.
+ *  06-26-07  02.00.02  Added IR Configuration Change List Event.
+ *  08-31-07  02.00.03  Removed SystemReplyQueueDepth field from the IOCInit
+ *                      request and replaced it with
+ *                      ReplyDescriptorPostQueueDepth and ReplyFreeQueueDepth.
+ *                      Replaced the MinReplyQueueDepth field of the IOCFacts
+ *                      reply with MaxReplyDescriptorPostQueueDepth.
+ *                      Added MPI2_RDPQ_DEPTH_MIN define to specify the minimum
+ *                      depth for the Reply Descriptor Post Queue.
+ *                      Added SASAddress field to Initiator Device Table
+ *                      Overflow Event data.
+ *  10-31-07  02.00.04  Added ReasonCode MPI2_EVENT_SAS_INIT_RC_NOT_RESPONDING
+ *                      for SAS Initiator Device Status Change Event data.
+ *                      Modified Reason Code defines for SAS Topology Change
+ *                      List Event data, including adding a bit for PHY Vacant
+ *                      status, and adding a mask for the Reason Code.
+ *                      Added define for
+ *                      MPI2_EVENT_SAS_TOPO_ES_DELAY_NOT_RESPONDING.
+ *                      Added define for MPI2_EXT_IMAGE_TYPE_MEGARAID.
+ *  12-18-07  02.00.05  Added Boot Status defines for the IOCExceptions field of
+ *                      the IOCFacts Reply.
+ *                      Removed MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER define.
+ *                      Moved MPI2_VERSION_UNION to mpi2.h.
+ *                      Changed MPI2_EVENT_NOTIFICATION_REQUEST to use masks
+ *                      instead of enables, and added SASBroadcastPrimitiveMasks
+ *                      field.
+ *                      Added Log Entry Added Event and related structure.
+ *  02-29-08  02.00.06  Added define MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID.
+ *                      Removed define MPI2_IOCFACTS_PROTOCOL_SMP_TARGET.
+ *                      Added MaxVolumes and MaxPersistentEntries fields to
+ *                      IOCFacts reply.
+ *                      Added ProtocalFlags and IOCCapabilities fields to
+ *                      MPI2_FW_IMAGE_HEADER.
+ *                      Removed MPI2_PORTENABLE_FLAGS_ENABLE_SINGLE_PORT.
+ *  03-03-08  02.00.07  Fixed MPI2_FW_IMAGE_HEADER by changing Reserved26 to
+ *                      a U16 (from a U32).
+ *                      Removed extra 's' from EventMasks name.
+ *  06-27-08  02.00.08  Fixed an offset in a comment.
+ *  10-02-08  02.00.09  Removed SystemReplyFrameSize from MPI2_IOC_INIT_REQUEST.
+ *                      Removed CurReplyFrameSize from MPI2_IOC_FACTS_REPLY and
+ *                      renamed MinReplyFrameSize to ReplyFrameSize.
+ *                      Added MPI2_IOCFACTS_EXCEPT_IR_FOREIGN_CONFIG_MAX.
+ *                      Added two new RAIDOperation values for Integrated RAID
+ *                      Operations Status Event data.
+ *                      Added four new IR Configuration Change List Event data
+ *                      ReasonCode values.
+ *                      Added two new ReasonCode defines for SAS Device Status
+ *                      Change Event data.
+ *                      Added three new DiscoveryStatus bits for the SAS
+ *                      Discovery event data.
+ *                      Added Multiplexing Status Change bit to the PhyStatus
+ *                      field of the SAS Topology Change List event data.
+ *                      Removed define for MPI2_INIT_IMAGE_BOOTFLAGS_XMEMCOPY.
+ *                      BootFlags are now product-specific.
+ *                      Added defines for the indivdual signature bytes
+ *                      for MPI2_INIT_IMAGE_FOOTER.
+ *  01-19-09  02.00.10  Added MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY define.
+ *                      Added MPI2_EVENT_SAS_DISC_DS_DOWNSTREAM_INITIATOR
+ *                      define.
+ *                      Added MPI2_EVENT_SAS_DEV_STAT_RC_SATA_INIT_FAILURE
+ *                      define.
+ *                      Removed MPI2_EVENT_SAS_DISC_DS_SATA_INIT_FAILURE define.
+ *  05-06-09  02.00.11  Added MPI2_IOCFACTS_CAPABILITY_RAID_ACCELERATOR define.
+ *                      Added MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX define.
+ *                      Added two new reason codes for SAS Device Status Change
+ *                      Event.
+ *                      Added new event: SAS PHY Counter.
+ *  07-30-09  02.00.12  Added GPIO Interrupt event define and structure.
+ *                      Added MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER define.
+ *                      Added new product id family for 2208.
+ *  10-28-09  02.00.13  Added HostMSIxVectors field to MPI2_IOC_INIT_REQUEST.
+ *                      Added MaxMSIxVectors field to MPI2_IOC_FACTS_REPLY.
+ *                      Added MinDevHandle field to MPI2_IOC_FACTS_REPLY.
+ *                      Added MPI2_IOCFACTS_CAPABILITY_HOST_BASED_DISCOVERY.
+ *                      Added MPI2_EVENT_HOST_BASED_DISCOVERY_PHY define.
+ *                      Added MPI2_EVENT_SAS_TOPO_ES_NO_EXPANDER define.
+ *                      Added Host Based Discovery Phy Event data.
+ *                      Added defines for ProductID Product field
+ *                      (MPI2_FW_HEADER_PID_).
+ *                      Modified values for SAS ProductID Family
+ *                      (MPI2_FW_HEADER_PID_FAMILY_).
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_IOC_H
+#define MPI2_IOC_H
+
+/*****************************************************************************
+*
+*               IOC Messages
+*
+*****************************************************************************/
+
+/****************************************************************************
+*  IOCInit message
+****************************************************************************/
+
+/* IOCInit Request message */
+typedef struct _MPI2_IOC_INIT_REQUEST
+{
+    U8                      WhoInit;                        /* 0x00 */
+    U8                      Reserved1;                      /* 0x01 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+    U16                     MsgVersion;                     /* 0x0C */
+    U16                     HeaderVersion;                  /* 0x0E */
+    U32                     Reserved5;                      /* 0x10 */
+    U16                     Reserved6;                      /* 0x14 */
+    U8                      Reserved7;                      /* 0x16 */
+    U8                      HostMSIxVectors;                /* 0x17 */
+    U16                     Reserved8;                      /* 0x18 */
+    U16                     SystemRequestFrameSize;         /* 0x1A */
+    U16                     ReplyDescriptorPostQueueDepth;  /* 0x1C */
+    U16                     ReplyFreeQueueDepth;            /* 0x1E */
+    U32                     SenseBufferAddressHigh;         /* 0x20 */
+    U32                     SystemReplyAddressHigh;         /* 0x24 */
+    U64                     SystemRequestFrameBaseAddress;  /* 0x28 */
+    U64                     ReplyDescriptorPostQueueAddress;/* 0x30 */
+    U64                     ReplyFreeQueueAddress;          /* 0x38 */
+    U64                     TimeStamp;                      /* 0x40 */
+} MPI2_IOC_INIT_REQUEST, MPI2_POINTER PTR_MPI2_IOC_INIT_REQUEST,
+  Mpi2IOCInitRequest_t, MPI2_POINTER pMpi2IOCInitRequest_t;
+
+/* WhoInit values */
+#define MPI2_WHOINIT_NOT_INITIALIZED            (0x00)
+#define MPI2_WHOINIT_SYSTEM_BIOS                (0x01)
+#define MPI2_WHOINIT_ROM_BIOS                   (0x02)
+#define MPI2_WHOINIT_PCI_PEER                   (0x03)
+#define MPI2_WHOINIT_HOST_DRIVER                (0x04)
+#define MPI2_WHOINIT_MANUFACTURER               (0x05)
+
+/* MsgVersion */
+#define MPI2_IOCINIT_MSGVERSION_MAJOR_MASK      (0xFF00)
+#define MPI2_IOCINIT_MSGVERSION_MAJOR_SHIFT     (8)
+#define MPI2_IOCINIT_MSGVERSION_MINOR_MASK      (0x00FF)
+#define MPI2_IOCINIT_MSGVERSION_MINOR_SHIFT     (0)
+
+/* HeaderVersion */
+#define MPI2_IOCINIT_HDRVERSION_UNIT_MASK       (0xFF00)
+#define MPI2_IOCINIT_HDRVERSION_UNIT_SHIFT      (8)
+#define MPI2_IOCINIT_HDRVERSION_DEV_MASK        (0x00FF)
+#define MPI2_IOCINIT_HDRVERSION_DEV_SHIFT       (0)
+
+/* minimum depth for the Reply Descriptor Post Queue */
+#define MPI2_RDPQ_DEPTH_MIN                     (16)
+
+
+/* IOCInit Reply message */
+typedef struct _MPI2_IOC_INIT_REPLY
+{
+    U8                      WhoInit;                        /* 0x00 */
+    U8                      Reserved1;                      /* 0x01 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+    U16                     Reserved5;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+} MPI2_IOC_INIT_REPLY, MPI2_POINTER PTR_MPI2_IOC_INIT_REPLY,
+  Mpi2IOCInitReply_t, MPI2_POINTER pMpi2IOCInitReply_t;
+
+
+/****************************************************************************
+*  IOCFacts message
+****************************************************************************/
+
+/* IOCFacts Request message */
+typedef struct _MPI2_IOC_FACTS_REQUEST
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+} MPI2_IOC_FACTS_REQUEST, MPI2_POINTER PTR_MPI2_IOC_FACTS_REQUEST,
+  Mpi2IOCFactsRequest_t, MPI2_POINTER pMpi2IOCFactsRequest_t;
+
+
+/* IOCFacts Reply message */
+typedef struct _MPI2_IOC_FACTS_REPLY
+{
+    U16                     MsgVersion;                     /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     HeaderVersion;                  /* 0x04 */
+    U8                      IOCNumber;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved1;                      /* 0x0A */
+    U16                     IOCExceptions;                  /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+    U8                      MaxChainDepth;                  /* 0x14 */
+    U8                      WhoInit;                        /* 0x15 */
+    U8                      NumberOfPorts;                  /* 0x16 */
+    U8                      MaxMSIxVectors;                 /* 0x17 */
+    U16                     RequestCredit;                  /* 0x18 */
+    U16                     ProductID;                      /* 0x1A */
+    U32                     IOCCapabilities;                /* 0x1C */
+    MPI2_VERSION_UNION      FWVersion;                      /* 0x20 */
+    U16                     IOCRequestFrameSize;            /* 0x24 */
+    U16                     Reserved3;                      /* 0x26 */
+    U16                     MaxInitiators;                  /* 0x28 */
+    U16                     MaxTargets;                     /* 0x2A */
+    U16                     MaxSasExpanders;                /* 0x2C */
+    U16                     MaxEnclosures;                  /* 0x2E */
+    U16                     ProtocolFlags;                  /* 0x30 */
+    U16                     HighPriorityCredit;             /* 0x32 */
+    U16                     MaxReplyDescriptorPostQueueDepth; /* 0x34 */
+    U8                      ReplyFrameSize;                 /* 0x36 */
+    U8                      MaxVolumes;                     /* 0x37 */
+    U16                     MaxDevHandle;                   /* 0x38 */
+    U16                     MaxPersistentEntries;           /* 0x3A */
+    U16                     MinDevHandle;                   /* 0x3C */
+    U16                     Reserved4;                      /* 0x3E */
+} MPI2_IOC_FACTS_REPLY, MPI2_POINTER PTR_MPI2_IOC_FACTS_REPLY,
+  Mpi2IOCFactsReply_t, MPI2_POINTER pMpi2IOCFactsReply_t;
+
+/* MsgVersion */
+#define MPI2_IOCFACTS_MSGVERSION_MAJOR_MASK             (0xFF00)
+#define MPI2_IOCFACTS_MSGVERSION_MAJOR_SHIFT            (8)
+#define MPI2_IOCFACTS_MSGVERSION_MINOR_MASK             (0x00FF)
+#define MPI2_IOCFACTS_MSGVERSION_MINOR_SHIFT            (0)
+
+/* HeaderVersion */
+#define MPI2_IOCFACTS_HDRVERSION_UNIT_MASK              (0xFF00)
+#define MPI2_IOCFACTS_HDRVERSION_UNIT_SHIFT             (8)
+#define MPI2_IOCFACTS_HDRVERSION_DEV_MASK               (0x00FF)
+#define MPI2_IOCFACTS_HDRVERSION_DEV_SHIFT              (0)
+
+/* IOCExceptions */
+#define MPI2_IOCFACTS_EXCEPT_IR_FOREIGN_CONFIG_MAX      (0x0100)
+
+#define MPI2_IOCFACTS_EXCEPT_BOOTSTAT_MASK              (0x00E0)
+#define MPI2_IOCFACTS_EXCEPT_BOOTSTAT_GOOD              (0x0000)
+#define MPI2_IOCFACTS_EXCEPT_BOOTSTAT_BACKUP            (0x0020)
+#define MPI2_IOCFACTS_EXCEPT_BOOTSTAT_RESTORED          (0x0040)
+#define MPI2_IOCFACTS_EXCEPT_BOOTSTAT_CORRUPT_BACKUP    (0x0060)
+
+#define MPI2_IOCFACTS_EXCEPT_METADATA_UNSUPPORTED       (0x0010)
+#define MPI2_IOCFACTS_EXCEPT_MANUFACT_CHECKSUM_FAIL     (0x0008)
+#define MPI2_IOCFACTS_EXCEPT_FW_CHECKSUM_FAIL           (0x0004)
+#define MPI2_IOCFACTS_EXCEPT_RAID_CONFIG_INVALID        (0x0002)
+#define MPI2_IOCFACTS_EXCEPT_CONFIG_CHECKSUM_FAIL       (0x0001)
+
+/* defines for WhoInit field are after the IOCInit Request */
+
+/* ProductID field uses MPI2_FW_HEADER_PID_ */
+
+/* IOCCapabilities */
+#define MPI2_IOCFACTS_CAPABILITY_HOST_BASED_DISCOVERY   (0x00010000)
+#define MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX            (0x00008000)
+#define MPI2_IOCFACTS_CAPABILITY_RAID_ACCELERATOR       (0x00004000)
+#define MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY           (0x00002000)
+#define MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID        (0x00001000)
+#define MPI2_IOCFACTS_CAPABILITY_TLR                    (0x00000800)
+#define MPI2_IOCFACTS_CAPABILITY_MULTICAST              (0x00000100)
+#define MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET   (0x00000080)
+#define MPI2_IOCFACTS_CAPABILITY_EEDP                   (0x00000040)
+#define MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER        (0x00000020)
+#define MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER        (0x00000010)
+#define MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER      (0x00000008)
+#define MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING (0x00000004)
+
+/* ProtocolFlags */
+#define MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET              (0x0001)
+#define MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR           (0x0002)
+
+
+/****************************************************************************
+*  PortFacts message
+****************************************************************************/
+
+/* PortFacts Request message */
+typedef struct _MPI2_PORT_FACTS_REQUEST
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      PortNumber;                     /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved3;                      /* 0x0A */
+} MPI2_PORT_FACTS_REQUEST, MPI2_POINTER PTR_MPI2_PORT_FACTS_REQUEST,
+  Mpi2PortFactsRequest_t, MPI2_POINTER pMpi2PortFactsRequest_t;
+
+/* PortFacts Reply message */
+typedef struct _MPI2_PORT_FACTS_REPLY
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      PortNumber;                     /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved3;                      /* 0x0A */
+    U16                     Reserved4;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+    U8                      Reserved5;                      /* 0x14 */
+    U8                      PortType;                       /* 0x15 */
+    U16                     Reserved6;                      /* 0x16 */
+    U16                     MaxPostedCmdBuffers;            /* 0x18 */
+    U16                     Reserved7;                      /* 0x1A */
+} MPI2_PORT_FACTS_REPLY, MPI2_POINTER PTR_MPI2_PORT_FACTS_REPLY,
+  Mpi2PortFactsReply_t, MPI2_POINTER pMpi2PortFactsReply_t;
+
+/* PortType values */
+#define MPI2_PORTFACTS_PORTTYPE_INACTIVE            (0x00)
+#define MPI2_PORTFACTS_PORTTYPE_FC                  (0x10)
+#define MPI2_PORTFACTS_PORTTYPE_ISCSI               (0x20)
+#define MPI2_PORTFACTS_PORTTYPE_SAS_PHYSICAL        (0x30)
+#define MPI2_PORTFACTS_PORTTYPE_SAS_VIRTUAL         (0x31)
+
+
+/****************************************************************************
+*  PortEnable message
+****************************************************************************/
+
+/* PortEnable Request message */
+typedef struct _MPI2_PORT_ENABLE_REQUEST
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U8                      Reserved2;                      /* 0x04 */
+    U8                      PortFlags;                      /* 0x05 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+} MPI2_PORT_ENABLE_REQUEST, MPI2_POINTER PTR_MPI2_PORT_ENABLE_REQUEST,
+  Mpi2PortEnableRequest_t, MPI2_POINTER pMpi2PortEnableRequest_t;
+
+
+/* PortEnable Reply message */
+typedef struct _MPI2_PORT_ENABLE_REPLY
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U8                      Reserved2;                      /* 0x04 */
+    U8                      PortFlags;                      /* 0x05 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+    U16                     Reserved5;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+} MPI2_PORT_ENABLE_REPLY, MPI2_POINTER PTR_MPI2_PORT_ENABLE_REPLY,
+  Mpi2PortEnableReply_t, MPI2_POINTER pMpi2PortEnableReply_t;
+
+
+/****************************************************************************
+*  EventNotification message
+****************************************************************************/
+
+/* EventNotification Request message */
+#define MPI2_EVENT_NOTIFY_EVENTMASK_WORDS           (4)
+
+typedef struct _MPI2_EVENT_NOTIFICATION_REQUEST
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+    U32                     Reserved5;                      /* 0x0C */
+    U32                     Reserved6;                      /* 0x10 */
+    U32                     EventMasks[MPI2_EVENT_NOTIFY_EVENTMASK_WORDS];/* 0x14 */
+    U16                     SASBroadcastPrimitiveMasks;     /* 0x24 */
+    U16                     Reserved7;                      /* 0x26 */
+    U32                     Reserved8;                      /* 0x28 */
+} MPI2_EVENT_NOTIFICATION_REQUEST,
+  MPI2_POINTER PTR_MPI2_EVENT_NOTIFICATION_REQUEST,
+  Mpi2EventNotificationRequest_t, MPI2_POINTER pMpi2EventNotificationRequest_t;
+
+
+/* EventNotification Reply message */
+typedef struct _MPI2_EVENT_NOTIFICATION_REPLY
+{
+    U16                     EventDataLength;                /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved1;                      /* 0x04 */
+    U8                      AckRequired;                    /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved2;                      /* 0x0A */
+    U16                     Reserved3;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+    U16                     Event;                          /* 0x14 */
+    U16                     Reserved4;                      /* 0x16 */
+    U32                     EventContext;                   /* 0x18 */
+    U32                     EventData[1];                   /* 0x1C */
+} MPI2_EVENT_NOTIFICATION_REPLY, MPI2_POINTER PTR_MPI2_EVENT_NOTIFICATION_REPLY,
+  Mpi2EventNotificationReply_t, MPI2_POINTER pMpi2EventNotificationReply_t;
+
+/* AckRequired */
+#define MPI2_EVENT_NOTIFICATION_ACK_NOT_REQUIRED    (0x00)
+#define MPI2_EVENT_NOTIFICATION_ACK_REQUIRED        (0x01)
+
+/* Event */
+#define MPI2_EVENT_LOG_DATA                         (0x0001)
+#define MPI2_EVENT_STATE_CHANGE                     (0x0002)
+#define MPI2_EVENT_HARD_RESET_RECEIVED              (0x0005)
+#define MPI2_EVENT_EVENT_CHANGE                     (0x000A)
+#define MPI2_EVENT_TASK_SET_FULL                    (0x000E)
+#define MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE         (0x000F)
+#define MPI2_EVENT_IR_OPERATION_STATUS              (0x0014)
+#define MPI2_EVENT_SAS_DISCOVERY                    (0x0016)
+#define MPI2_EVENT_SAS_BROADCAST_PRIMITIVE          (0x0017)
+#define MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE    (0x0018)
+#define MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW          (0x0019)
+#define MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST         (0x001C)
+#define MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE    (0x001D)
+#define MPI2_EVENT_IR_VOLUME                        (0x001E)
+#define MPI2_EVENT_IR_PHYSICAL_DISK                 (0x001F)
+#define MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST     (0x0020)
+#define MPI2_EVENT_LOG_ENTRY_ADDED                  (0x0021)
+#define MPI2_EVENT_SAS_PHY_COUNTER                  (0x0022)
+#define MPI2_EVENT_GPIO_INTERRUPT                   (0x0023)
+#define MPI2_EVENT_HOST_BASED_DISCOVERY_PHY         (0x0024)
+
+
+/* Log Entry Added Event data */
+
+/* the following structure matches MPI2_LOG_0_ENTRY in mpi2_cnfg.h */
+#define MPI2_EVENT_DATA_LOG_DATA_LENGTH             (0x1C)
+
+typedef struct _MPI2_EVENT_DATA_LOG_ENTRY_ADDED
+{
+    U64         TimeStamp;                          /* 0x00 */
+    U32         Reserved1;                          /* 0x08 */
+    U16         LogSequence;                        /* 0x0C */
+    U16         LogEntryQualifier;                  /* 0x0E */
+    U8          VP_ID;                              /* 0x10 */
+    U8          VF_ID;                              /* 0x11 */
+    U16         Reserved2;                          /* 0x12 */
+    U8          LogData[MPI2_EVENT_DATA_LOG_DATA_LENGTH];/* 0x14 */
+} MPI2_EVENT_DATA_LOG_ENTRY_ADDED,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_LOG_ENTRY_ADDED,
+  Mpi2EventDataLogEntryAdded_t, MPI2_POINTER pMpi2EventDataLogEntryAdded_t;
+
+/* GPIO Interrupt Event data */
+
+typedef struct _MPI2_EVENT_DATA_GPIO_INTERRUPT
+{
+    U8          GPIONum;                            /* 0x00 */
+    U8          Reserved1;                          /* 0x01 */
+    U16         Reserved2;                          /* 0x02 */
+} MPI2_EVENT_DATA_GPIO_INTERRUPT,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_GPIO_INTERRUPT,
+  Mpi2EventDataGpioInterrupt_t, MPI2_POINTER pMpi2EventDataGpioInterrupt_t;
+
+/* Hard Reset Received Event data */
+
+typedef struct _MPI2_EVENT_DATA_HARD_RESET_RECEIVED
+{
+    U8                      Reserved1;                      /* 0x00 */
+    U8                      Port;                           /* 0x01 */
+    U16                     Reserved2;                      /* 0x02 */
+} MPI2_EVENT_DATA_HARD_RESET_RECEIVED,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_HARD_RESET_RECEIVED,
+  Mpi2EventDataHardResetReceived_t,
+  MPI2_POINTER pMpi2EventDataHardResetReceived_t;
+
+/* Task Set Full Event data */
+
+typedef struct _MPI2_EVENT_DATA_TASK_SET_FULL
+{
+    U16                     DevHandle;                      /* 0x00 */
+    U16                     CurrentDepth;                   /* 0x02 */
+} MPI2_EVENT_DATA_TASK_SET_FULL, MPI2_POINTER PTR_MPI2_EVENT_DATA_TASK_SET_FULL,
+  Mpi2EventDataTaskSetFull_t, MPI2_POINTER pMpi2EventDataTaskSetFull_t;
+
+
+/* SAS Device Status Change Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_DEVICE_STATUS_CHANGE
+{
+    U16                     TaskTag;                        /* 0x00 */
+    U8                      ReasonCode;                     /* 0x02 */
+    U8                      Reserved1;                      /* 0x03 */
+    U8                      ASC;                            /* 0x04 */
+    U8                      ASCQ;                           /* 0x05 */
+    U16                     DevHandle;                      /* 0x06 */
+    U32                     Reserved2;                      /* 0x08 */
+    U64                     SASAddress;                     /* 0x0C */
+    U8                      LUN[8];                         /* 0x14 */
+} MPI2_EVENT_DATA_SAS_DEVICE_STATUS_CHANGE,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_DEVICE_STATUS_CHANGE,
+  Mpi2EventDataSasDeviceStatusChange_t,
+  MPI2_POINTER pMpi2EventDataSasDeviceStatusChange_t;
+
+/* SAS Device Status Change Event data ReasonCode values */
+#define MPI2_EVENT_SAS_DEV_STAT_RC_SMART_DATA                           (0x05)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_UNSUPPORTED                          (0x07)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_INTERNAL_DEVICE_RESET                (0x08)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_TASK_ABORT_INTERNAL                  (0x09)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_ABORT_TASK_SET_INTERNAL              (0x0A)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_CLEAR_TASK_SET_INTERNAL              (0x0B)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_QUERY_TASK_INTERNAL                  (0x0C)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_ASYNC_NOTIFICATION                   (0x0D)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_CMP_INTERNAL_DEV_RESET               (0x0E)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_CMP_TASK_ABORT_INTERNAL              (0x0F)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_SATA_INIT_FAILURE                    (0x10)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_EXPANDER_REDUCED_FUNCTIONALITY       (0x11)
+#define MPI2_EVENT_SAS_DEV_STAT_RC_CMP_EXPANDER_REDUCED_FUNCTIONALITY   (0x12)
+
+
+/* Integrated RAID Operation Status Event data */
+
+typedef struct _MPI2_EVENT_DATA_IR_OPERATION_STATUS
+{
+    U16                     VolDevHandle;               /* 0x00 */
+    U16                     Reserved1;                  /* 0x02 */
+    U8                      RAIDOperation;              /* 0x04 */
+    U8                      PercentComplete;            /* 0x05 */
+    U16                     Reserved2;                  /* 0x06 */
+    U32                     Resereved3;                 /* 0x08 */
+} MPI2_EVENT_DATA_IR_OPERATION_STATUS,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_IR_OPERATION_STATUS,
+  Mpi2EventDataIrOperationStatus_t,
+  MPI2_POINTER pMpi2EventDataIrOperationStatus_t;
+
+/* Integrated RAID Operation Status Event data RAIDOperation values */
+#define MPI2_EVENT_IR_RAIDOP_RESYNC                     (0x00)
+#define MPI2_EVENT_IR_RAIDOP_ONLINE_CAP_EXPANSION       (0x01)
+#define MPI2_EVENT_IR_RAIDOP_CONSISTENCY_CHECK          (0x02)
+#define MPI2_EVENT_IR_RAIDOP_BACKGROUND_INIT            (0x03)
+#define MPI2_EVENT_IR_RAIDOP_MAKE_DATA_CONSISTENT       (0x04)
+
+
+/* Integrated RAID Volume Event data */
+
+typedef struct _MPI2_EVENT_DATA_IR_VOLUME
+{
+    U16                     VolDevHandle;               /* 0x00 */
+    U8                      ReasonCode;                 /* 0x02 */
+    U8                      Reserved1;                  /* 0x03 */
+    U32                     NewValue;                   /* 0x04 */
+    U32                     PreviousValue;              /* 0x08 */
+} MPI2_EVENT_DATA_IR_VOLUME, MPI2_POINTER PTR_MPI2_EVENT_DATA_IR_VOLUME,
+  Mpi2EventDataIrVolume_t, MPI2_POINTER pMpi2EventDataIrVolume_t;
+
+/* Integrated RAID Volume Event data ReasonCode values */
+#define MPI2_EVENT_IR_VOLUME_RC_SETTINGS_CHANGED        (0x01)
+#define MPI2_EVENT_IR_VOLUME_RC_STATUS_FLAGS_CHANGED    (0x02)
+#define MPI2_EVENT_IR_VOLUME_RC_STATE_CHANGED           (0x03)
+
+
+/* Integrated RAID Physical Disk Event data */
+
+typedef struct _MPI2_EVENT_DATA_IR_PHYSICAL_DISK
+{
+    U16                     Reserved1;                  /* 0x00 */
+    U8                      ReasonCode;                 /* 0x02 */
+    U8                      PhysDiskNum;                /* 0x03 */
+    U16                     PhysDiskDevHandle;          /* 0x04 */
+    U16                     Reserved2;                  /* 0x06 */
+    U16                     Slot;                       /* 0x08 */
+    U16                     EnclosureHandle;            /* 0x0A */
+    U32                     NewValue;                   /* 0x0C */
+    U32                     PreviousValue;              /* 0x10 */
+} MPI2_EVENT_DATA_IR_PHYSICAL_DISK,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_IR_PHYSICAL_DISK,
+  Mpi2EventDataIrPhysicalDisk_t, MPI2_POINTER pMpi2EventDataIrPhysicalDisk_t;
+
+/* Integrated RAID Physical Disk Event data ReasonCode values */
+#define MPI2_EVENT_IR_PHYSDISK_RC_SETTINGS_CHANGED      (0x01)
+#define MPI2_EVENT_IR_PHYSDISK_RC_STATUS_FLAGS_CHANGED  (0x02)
+#define MPI2_EVENT_IR_PHYSDISK_RC_STATE_CHANGED         (0x03)
+
+
+/* Integrated RAID Configuration Change List Event data */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check NumElements at runtime.
+ */
+#ifndef MPI2_EVENT_IR_CONFIG_ELEMENT_COUNT
+#define MPI2_EVENT_IR_CONFIG_ELEMENT_COUNT          (1)
+#endif
+
+typedef struct _MPI2_EVENT_IR_CONFIG_ELEMENT
+{
+    U16                     ElementFlags;               /* 0x00 */
+    U16                     VolDevHandle;               /* 0x02 */
+    U8                      ReasonCode;                 /* 0x04 */
+    U8                      PhysDiskNum;                /* 0x05 */
+    U16                     PhysDiskDevHandle;          /* 0x06 */
+} MPI2_EVENT_IR_CONFIG_ELEMENT, MPI2_POINTER PTR_MPI2_EVENT_IR_CONFIG_ELEMENT,
+  Mpi2EventIrConfigElement_t, MPI2_POINTER pMpi2EventIrConfigElement_t;
+
+/* IR Configuration Change List Event data ElementFlags values */
+#define MPI2_EVENT_IR_CHANGE_EFLAGS_ELEMENT_TYPE_MASK   (0x000F)
+#define MPI2_EVENT_IR_CHANGE_EFLAGS_VOLUME_ELEMENT      (0x0000)
+#define MPI2_EVENT_IR_CHANGE_EFLAGS_VOLPHYSDISK_ELEMENT (0x0001)
+#define MPI2_EVENT_IR_CHANGE_EFLAGS_HOTSPARE_ELEMENT    (0x0002)
+
+/* IR Configuration Change List Event data ReasonCode values */
+#define MPI2_EVENT_IR_CHANGE_RC_ADDED                   (0x01)
+#define MPI2_EVENT_IR_CHANGE_RC_REMOVED                 (0x02)
+#define MPI2_EVENT_IR_CHANGE_RC_NO_CHANGE               (0x03)
+#define MPI2_EVENT_IR_CHANGE_RC_HIDE                    (0x04)
+#define MPI2_EVENT_IR_CHANGE_RC_UNHIDE                  (0x05)
+#define MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED          (0x06)
+#define MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED          (0x07)
+#define MPI2_EVENT_IR_CHANGE_RC_PD_CREATED              (0x08)
+#define MPI2_EVENT_IR_CHANGE_RC_PD_DELETED              (0x09)
+
+typedef struct _MPI2_EVENT_DATA_IR_CONFIG_CHANGE_LIST
+{
+    U8                              NumElements;        /* 0x00 */
+    U8                              Reserved1;          /* 0x01 */
+    U8                              Reserved2;          /* 0x02 */
+    U8                              ConfigNum;          /* 0x03 */
+    U32                             Flags;              /* 0x04 */
+    MPI2_EVENT_IR_CONFIG_ELEMENT    ConfigElement[MPI2_EVENT_IR_CONFIG_ELEMENT_COUNT];    /* 0x08 */
+} MPI2_EVENT_DATA_IR_CONFIG_CHANGE_LIST,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_IR_CONFIG_CHANGE_LIST,
+  Mpi2EventDataIrConfigChangeList_t,
+  MPI2_POINTER pMpi2EventDataIrConfigChangeList_t;
+
+/* IR Configuration Change List Event data Flags values */
+#define MPI2_EVENT_IR_CHANGE_FLAGS_FOREIGN_CONFIG   (0x00000001)
+
+
+/* SAS Discovery Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_DISCOVERY
+{
+    U8                      Flags;                      /* 0x00 */
+    U8                      ReasonCode;                 /* 0x01 */
+    U8                      PhysicalPort;               /* 0x02 */
+    U8                      Reserved1;                  /* 0x03 */
+    U32                     DiscoveryStatus;            /* 0x04 */
+} MPI2_EVENT_DATA_SAS_DISCOVERY,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_DISCOVERY,
+  Mpi2EventDataSasDiscovery_t, MPI2_POINTER pMpi2EventDataSasDiscovery_t;
+
+/* SAS Discovery Event data Flags values */
+#define MPI2_EVENT_SAS_DISC_DEVICE_CHANGE                   (0x02)
+#define MPI2_EVENT_SAS_DISC_IN_PROGRESS                     (0x01)
+
+/* SAS Discovery Event data ReasonCode values */
+#define MPI2_EVENT_SAS_DISC_RC_STARTED                      (0x01)
+#define MPI2_EVENT_SAS_DISC_RC_COMPLETED                    (0x02)
+
+/* SAS Discovery Event data DiscoveryStatus values */
+#define MPI2_EVENT_SAS_DISC_DS_MAX_ENCLOSURES_EXCEED            (0x80000000)
+#define MPI2_EVENT_SAS_DISC_DS_MAX_EXPANDERS_EXCEED             (0x40000000)
+#define MPI2_EVENT_SAS_DISC_DS_MAX_DEVICES_EXCEED               (0x20000000)
+#define MPI2_EVENT_SAS_DISC_DS_MAX_TOPO_PHYS_EXCEED             (0x10000000)
+#define MPI2_EVENT_SAS_DISC_DS_DOWNSTREAM_INITIATOR             (0x08000000)
+#define MPI2_EVENT_SAS_DISC_DS_MULTI_SUBTRACTIVE_SUBTRACTIVE    (0x00008000)
+#define MPI2_EVENT_SAS_DISC_DS_EXP_MULTI_SUBTRACTIVE            (0x00004000)
+#define MPI2_EVENT_SAS_DISC_DS_MULTI_PORT_DOMAIN                (0x00002000)
+#define MPI2_EVENT_SAS_DISC_DS_TABLE_TO_SUBTRACTIVE_LINK        (0x00001000)
+#define MPI2_EVENT_SAS_DISC_DS_UNSUPPORTED_DEVICE               (0x00000800)
+#define MPI2_EVENT_SAS_DISC_DS_TABLE_LINK                       (0x00000400)
+#define MPI2_EVENT_SAS_DISC_DS_SUBTRACTIVE_LINK                 (0x00000200)
+#define MPI2_EVENT_SAS_DISC_DS_SMP_CRC_ERROR                    (0x00000100)
+#define MPI2_EVENT_SAS_DISC_DS_SMP_FUNCTION_FAILED              (0x00000080)
+#define MPI2_EVENT_SAS_DISC_DS_INDEX_NOT_EXIST                  (0x00000040)
+#define MPI2_EVENT_SAS_DISC_DS_OUT_ROUTE_ENTRIES                (0x00000020)
+#define MPI2_EVENT_SAS_DISC_DS_SMP_TIMEOUT                      (0x00000010)
+#define MPI2_EVENT_SAS_DISC_DS_MULTIPLE_PORTS                   (0x00000004)
+#define MPI2_EVENT_SAS_DISC_DS_UNADDRESSABLE_DEVICE             (0x00000002)
+#define MPI2_EVENT_SAS_DISC_DS_LOOP_DETECTED                    (0x00000001)
+
+
+/* SAS Broadcast Primitive Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_BROADCAST_PRIMITIVE
+{
+    U8                      PhyNum;                     /* 0x00 */
+    U8                      Port;                       /* 0x01 */
+    U8                      PortWidth;                  /* 0x02 */
+    U8                      Primitive;                  /* 0x03 */
+} MPI2_EVENT_DATA_SAS_BROADCAST_PRIMITIVE,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_BROADCAST_PRIMITIVE,
+  Mpi2EventDataSasBroadcastPrimitive_t,
+  MPI2_POINTER pMpi2EventDataSasBroadcastPrimitive_t;
+
+/* defines for the Primitive field */
+#define MPI2_EVENT_PRIMITIVE_CHANGE                         (0x01)
+#define MPI2_EVENT_PRIMITIVE_SES                            (0x02)
+#define MPI2_EVENT_PRIMITIVE_EXPANDER                       (0x03)
+#define MPI2_EVENT_PRIMITIVE_ASYNCHRONOUS_EVENT             (0x04)
+#define MPI2_EVENT_PRIMITIVE_RESERVED3                      (0x05)
+#define MPI2_EVENT_PRIMITIVE_RESERVED4                      (0x06)
+#define MPI2_EVENT_PRIMITIVE_CHANGE0_RESERVED               (0x07)
+#define MPI2_EVENT_PRIMITIVE_CHANGE1_RESERVED               (0x08)
+
+
+/* SAS Initiator Device Status Change Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_INIT_DEV_STATUS_CHANGE
+{
+    U8                      ReasonCode;                 /* 0x00 */
+    U8                      PhysicalPort;               /* 0x01 */
+    U16                     DevHandle;                  /* 0x02 */
+    U64                     SASAddress;                 /* 0x04 */
+} MPI2_EVENT_DATA_SAS_INIT_DEV_STATUS_CHANGE,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_INIT_DEV_STATUS_CHANGE,
+  Mpi2EventDataSasInitDevStatusChange_t,
+  MPI2_POINTER pMpi2EventDataSasInitDevStatusChange_t;
+
+/* SAS Initiator Device Status Change event ReasonCode values */
+#define MPI2_EVENT_SAS_INIT_RC_ADDED                (0x01)
+#define MPI2_EVENT_SAS_INIT_RC_NOT_RESPONDING       (0x02)
+
+
+/* SAS Initiator Device Table Overflow Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_INIT_TABLE_OVERFLOW
+{
+    U16                     MaxInit;                    /* 0x00 */
+    U16                     CurrentInit;                /* 0x02 */
+    U64                     SASAddress;                 /* 0x04 */
+} MPI2_EVENT_DATA_SAS_INIT_TABLE_OVERFLOW,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_INIT_TABLE_OVERFLOW,
+  Mpi2EventDataSasInitTableOverflow_t,
+  MPI2_POINTER pMpi2EventDataSasInitTableOverflow_t;
+
+
+/* SAS Topology Change List Event data */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check NumEntries at runtime.
+ */
+#ifndef MPI2_EVENT_SAS_TOPO_PHY_COUNT
+#define MPI2_EVENT_SAS_TOPO_PHY_COUNT           (1)
+#endif
+
+typedef struct _MPI2_EVENT_SAS_TOPO_PHY_ENTRY
+{
+    U16                     AttachedDevHandle;          /* 0x00 */
+    U8                      LinkRate;                   /* 0x02 */
+    U8                      PhyStatus;                  /* 0x03 */
+} MPI2_EVENT_SAS_TOPO_PHY_ENTRY, MPI2_POINTER PTR_MPI2_EVENT_SAS_TOPO_PHY_ENTRY,
+  Mpi2EventSasTopoPhyEntry_t, MPI2_POINTER pMpi2EventSasTopoPhyEntry_t;
+
+typedef struct _MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST
+{
+    U16                             EnclosureHandle;            /* 0x00 */
+    U16                             ExpanderDevHandle;          /* 0x02 */
+    U8                              NumPhys;                    /* 0x04 */
+    U8                              Reserved1;                  /* 0x05 */
+    U16                             Reserved2;                  /* 0x06 */
+    U8                              NumEntries;                 /* 0x08 */
+    U8                              StartPhyNum;                /* 0x09 */
+    U8                              ExpStatus;                  /* 0x0A */
+    U8                              PhysicalPort;               /* 0x0B */
+    MPI2_EVENT_SAS_TOPO_PHY_ENTRY   PHY[MPI2_EVENT_SAS_TOPO_PHY_COUNT]; /* 0x0C*/
+} MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST,
+  Mpi2EventDataSasTopologyChangeList_t,
+  MPI2_POINTER pMpi2EventDataSasTopologyChangeList_t;
+
+/* values for the ExpStatus field */
+#define MPI2_EVENT_SAS_TOPO_ES_NO_EXPANDER                  (0x00)
+#define MPI2_EVENT_SAS_TOPO_ES_ADDED                        (0x01)
+#define MPI2_EVENT_SAS_TOPO_ES_NOT_RESPONDING               (0x02)
+#define MPI2_EVENT_SAS_TOPO_ES_RESPONDING                   (0x03)
+#define MPI2_EVENT_SAS_TOPO_ES_DELAY_NOT_RESPONDING         (0x04)
+
+/* defines for the LinkRate field */
+#define MPI2_EVENT_SAS_TOPO_LR_CURRENT_MASK                 (0xF0)
+#define MPI2_EVENT_SAS_TOPO_LR_CURRENT_SHIFT                (4)
+#define MPI2_EVENT_SAS_TOPO_LR_PREV_MASK                    (0x0F)
+#define MPI2_EVENT_SAS_TOPO_LR_PREV_SHIFT                   (0)
+
+#define MPI2_EVENT_SAS_TOPO_LR_UNKNOWN_LINK_RATE            (0x00)
+#define MPI2_EVENT_SAS_TOPO_LR_PHY_DISABLED                 (0x01)
+#define MPI2_EVENT_SAS_TOPO_LR_NEGOTIATION_FAILED           (0x02)
+#define MPI2_EVENT_SAS_TOPO_LR_SATA_OOB_COMPLETE            (0x03)
+#define MPI2_EVENT_SAS_TOPO_LR_PORT_SELECTOR                (0x04)
+#define MPI2_EVENT_SAS_TOPO_LR_SMP_RESET_IN_PROGRESS        (0x05)
+#define MPI2_EVENT_SAS_TOPO_LR_RATE_1_5                     (0x08)
+#define MPI2_EVENT_SAS_TOPO_LR_RATE_3_0                     (0x09)
+#define MPI2_EVENT_SAS_TOPO_LR_RATE_6_0                     (0x0A)
+
+/* values for the PhyStatus field */
+#define MPI2_EVENT_SAS_TOPO_PHYSTATUS_VACANT                (0x80)
+#define MPI2_EVENT_SAS_TOPO_PS_MULTIPLEX_CHANGE             (0x10)
+/* values for the PhyStatus ReasonCode sub-field */
+#define MPI2_EVENT_SAS_TOPO_RC_MASK                         (0x0F)
+#define MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED                   (0x01)
+#define MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING          (0x02)
+#define MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED                  (0x03)
+#define MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE                    (0x04)
+#define MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING         (0x05)
+
+
+/* SAS Enclosure Device Status Change Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_ENCL_DEV_STATUS_CHANGE
+{
+    U16                     EnclosureHandle;            /* 0x00 */
+    U8                      ReasonCode;                 /* 0x02 */
+    U8                      PhysicalPort;               /* 0x03 */
+    U64                     EnclosureLogicalID;         /* 0x04 */
+    U16                     NumSlots;                   /* 0x0C */
+    U16                     StartSlot;                  /* 0x0E */
+    U32                     PhyBits;                    /* 0x10 */
+} MPI2_EVENT_DATA_SAS_ENCL_DEV_STATUS_CHANGE,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_ENCL_DEV_STATUS_CHANGE,
+  Mpi2EventDataSasEnclDevStatusChange_t,
+  MPI2_POINTER pMpi2EventDataSasEnclDevStatusChange_t;
+
+/* SAS Enclosure Device Status Change event ReasonCode values */
+#define MPI2_EVENT_SAS_ENCL_RC_ADDED                (0x01)
+#define MPI2_EVENT_SAS_ENCL_RC_NOT_RESPONDING       (0x02)
+
+
+/* SAS PHY Counter Event data */
+
+typedef struct _MPI2_EVENT_DATA_SAS_PHY_COUNTER
+{
+    U64         TimeStamp;          /* 0x00 */
+    U32         Reserved1;          /* 0x08 */
+    U8          PhyEventCode;       /* 0x0C */
+    U8          PhyNum;             /* 0x0D */
+    U16         Reserved2;          /* 0x0E */
+    U32         PhyEventInfo;       /* 0x10 */
+    U8          CounterType;        /* 0x14 */
+    U8          ThresholdWindow;    /* 0x15 */
+    U8          TimeUnits;          /* 0x16 */
+    U8          Reserved3;          /* 0x17 */
+    U32         EventThreshold;     /* 0x18 */
+    U16         ThresholdFlags;     /* 0x1C */
+    U16         Reserved4;          /* 0x1E */
+} MPI2_EVENT_DATA_SAS_PHY_COUNTER,
+  MPI2_POINTER PTR_MPI2_EVENT_DATA_SAS_PHY_COUNTER,
+  Mpi2EventDataSasPhyCounter_t, MPI2_POINTER pMpi2EventDataSasPhyCounter_t;
+
+/* use MPI2_SASPHY3_EVENT_CODE_ values from mpi2_cnfg.h for the PhyEventCode field */
+
+/* use MPI2_SASPHY3_COUNTER_TYPE_ values from mpi2_cnfg.h for the CounterType field */
+
+/* use MPI2_SASPHY3_TIME_UNITS_ values from mpi2_cnfg.h for the TimeUnits field */
+
+/* use MPI2_SASPHY3_TFLAGS_ values from mpi2_cnfg.h for the ThresholdFlags field */
+
+
+/* Host Based Discovery Phy Event data */
+
+typedef struct _MPI2_EVENT_HBD_PHY_SAS
+{
+    U8          Flags;                      /* 0x00 */
+    U8          NegotiatedLinkRate;         /* 0x01 */
+    U8          PhyNum;                     /* 0x02 */
+    U8          PhysicalPort;               /* 0x03 */
+    U32         Reserved1;                  /* 0x04 */
+    U8          InitialFrame[28];           /* 0x08 */
+} MPI2_EVENT_HBD_PHY_SAS, MPI2_POINTER PTR_MPI2_EVENT_HBD_PHY_SAS,
+  Mpi2EventHbdPhySas_t, MPI2_POINTER pMpi2EventHbdPhySas_t;
+
+/* values for the Flags field */
+#define MPI2_EVENT_HBD_SAS_FLAGS_FRAME_VALID        (0x02)
+#define MPI2_EVENT_HBD_SAS_FLAGS_SATA_FRAME         (0x01)
+
+/* use MPI2_SAS_NEG_LINK_RATE_ defines from mpi2_cnfg.h for the NegotiatedLinkRate field */
+
+typedef union _MPI2_EVENT_HBD_DESCRIPTOR
+{
+    MPI2_EVENT_HBD_PHY_SAS      Sas;
+} MPI2_EVENT_HBD_DESCRIPTOR, MPI2_POINTER PTR_MPI2_EVENT_HBD_DESCRIPTOR,
+  Mpi2EventHbdDescriptor_t, MPI2_POINTER pMpi2EventHbdDescriptor_t;
+
+typedef struct _MPI2_EVENT_DATA_HBD_PHY
+{
+    U8                          DescriptorType;     /* 0x00 */
+    U8                          Reserved1;          /* 0x01 */
+    U16                         Reserved2;          /* 0x02 */
+    U32                         Reserved3;          /* 0x04 */
+    MPI2_EVENT_HBD_DESCRIPTOR   Descriptor;         /* 0x08 */
+} MPI2_EVENT_DATA_HBD_PHY, MPI2_POINTER PTR_MPI2_EVENT_DATA_HBD_PHY,
+  Mpi2EventDataHbdPhy_t, MPI2_POINTER pMpi2EventDataMpi2EventDataHbdPhy_t;
+
+/* values for the DescriptorType field */
+#define MPI2_EVENT_HBD_DT_SAS               (0x01)
+
+
+
+/****************************************************************************
+*  EventAck message
+****************************************************************************/
+
+/* EventAck Request message */
+typedef struct _MPI2_EVENT_ACK_REQUEST
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+    U16                     Event;                          /* 0x0C */
+    U16                     Reserved5;                      /* 0x0E */
+    U32                     EventContext;                   /* 0x10 */
+} MPI2_EVENT_ACK_REQUEST, MPI2_POINTER PTR_MPI2_EVENT_ACK_REQUEST,
+  Mpi2EventAckRequest_t, MPI2_POINTER pMpi2EventAckRequest_t;
+
+
+/* EventAck Reply message */
+typedef struct _MPI2_EVENT_ACK_REPLY
+{
+    U16                     Reserved1;                      /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved2;                      /* 0x04 */
+    U8                      Reserved3;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved4;                      /* 0x0A */
+    U16                     Reserved5;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+} MPI2_EVENT_ACK_REPLY, MPI2_POINTER PTR_MPI2_EVENT_ACK_REPLY,
+  Mpi2EventAckReply_t, MPI2_POINTER pMpi2EventAckReply_t;
+
+
+/****************************************************************************
+*  FWDownload message
+****************************************************************************/
+
+/* FWDownload Request message */
+typedef struct _MPI2_FW_DOWNLOAD_REQUEST
+{
+    U8                      ImageType;                  /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U32                     TotalImageSize;             /* 0x0C */
+    U32                     Reserved5;                  /* 0x10 */
+    MPI2_MPI_SGE_UNION      SGL;                        /* 0x14 */
+} MPI2_FW_DOWNLOAD_REQUEST, MPI2_POINTER PTR_MPI2_FW_DOWNLOAD_REQUEST,
+  Mpi2FWDownloadRequest, MPI2_POINTER pMpi2FWDownloadRequest;
+
+#define MPI2_FW_DOWNLOAD_MSGFLGS_LAST_SEGMENT   (0x01)
+
+#define MPI2_FW_DOWNLOAD_ITYPE_FW                   (0x01)
+#define MPI2_FW_DOWNLOAD_ITYPE_BIOS                 (0x02)
+#define MPI2_FW_DOWNLOAD_ITYPE_MANUFACTURING        (0x06)
+#define MPI2_FW_DOWNLOAD_ITYPE_CONFIG_1             (0x07)
+#define MPI2_FW_DOWNLOAD_ITYPE_CONFIG_2             (0x08)
+#define MPI2_FW_DOWNLOAD_ITYPE_MEGARAID             (0x09)
+#define MPI2_FW_DOWNLOAD_ITYPE_COMMON_BOOT_BLOCK    (0x0B)
+
+/* FWDownload TransactionContext Element */
+typedef struct _MPI2_FW_DOWNLOAD_TCSGE
+{
+    U8                      Reserved1;                  /* 0x00 */
+    U8                      ContextSize;                /* 0x01 */
+    U8                      DetailsLength;              /* 0x02 */
+    U8                      Flags;                      /* 0x03 */
+    U32                     Reserved2;                  /* 0x04 */
+    U32                     ImageOffset;                /* 0x08 */
+    U32                     ImageSize;                  /* 0x0C */
+} MPI2_FW_DOWNLOAD_TCSGE, MPI2_POINTER PTR_MPI2_FW_DOWNLOAD_TCSGE,
+  Mpi2FWDownloadTCSGE_t, MPI2_POINTER pMpi2FWDownloadTCSGE_t;
+
+/* FWDownload Reply message */
+typedef struct _MPI2_FW_DOWNLOAD_REPLY
+{
+    U8                      ImageType;                  /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+} MPI2_FW_DOWNLOAD_REPLY, MPI2_POINTER PTR_MPI2_FW_DOWNLOAD_REPLY,
+  Mpi2FWDownloadReply_t, MPI2_POINTER pMpi2FWDownloadReply_t;
+
+
+/****************************************************************************
+*  FWUpload message
+****************************************************************************/
+
+/* FWUpload Request message */
+typedef struct _MPI2_FW_UPLOAD_REQUEST
+{
+    U8                      ImageType;                  /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U32                     Reserved5;                  /* 0x0C */
+    U32                     Reserved6;                  /* 0x10 */
+    MPI2_MPI_SGE_UNION      SGL;                        /* 0x14 */
+} MPI2_FW_UPLOAD_REQUEST, MPI2_POINTER PTR_MPI2_FW_UPLOAD_REQUEST,
+  Mpi2FWUploadRequest_t, MPI2_POINTER pMpi2FWUploadRequest_t;
+
+#define MPI2_FW_UPLOAD_ITYPE_FW_CURRENT         (0x00)
+#define MPI2_FW_UPLOAD_ITYPE_FW_FLASH           (0x01)
+#define MPI2_FW_UPLOAD_ITYPE_BIOS_FLASH         (0x02)
+#define MPI2_FW_UPLOAD_ITYPE_FW_BACKUP          (0x05)
+#define MPI2_FW_UPLOAD_ITYPE_MANUFACTURING      (0x06)
+#define MPI2_FW_UPLOAD_ITYPE_CONFIG_1           (0x07)
+#define MPI2_FW_UPLOAD_ITYPE_CONFIG_2           (0x08)
+#define MPI2_FW_UPLOAD_ITYPE_MEGARAID           (0x09)
+#define MPI2_FW_UPLOAD_ITYPE_COMPLETE           (0x0A)
+#define MPI2_FW_UPLOAD_ITYPE_COMMON_BOOT_BLOCK  (0x0B)
+
+typedef struct _MPI2_FW_UPLOAD_TCSGE
+{
+    U8                      Reserved1;                  /* 0x00 */
+    U8                      ContextSize;                /* 0x01 */
+    U8                      DetailsLength;              /* 0x02 */
+    U8                      Flags;                      /* 0x03 */
+    U32                     Reserved2;                  /* 0x04 */
+    U32                     ImageOffset;                /* 0x08 */
+    U32                     ImageSize;                  /* 0x0C */
+} MPI2_FW_UPLOAD_TCSGE, MPI2_POINTER PTR_MPI2_FW_UPLOAD_TCSGE,
+  Mpi2FWUploadTCSGE_t, MPI2_POINTER pMpi2FWUploadTCSGE_t;
+
+/* FWUpload Reply message */
+typedef struct _MPI2_FW_UPLOAD_REPLY
+{
+    U8                      ImageType;                  /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    U32                     ActualImageSize;            /* 0x14 */
+} MPI2_FW_UPLOAD_REPLY, MPI2_POINTER PTR_MPI2_FW_UPLOAD_REPLY,
+  Mpi2FWUploadReply_t, MPI2_POINTER pMPi2FWUploadReply_t;
+
+
+/* FW Image Header */
+typedef struct _MPI2_FW_IMAGE_HEADER
+{
+    U32                     Signature;                  /* 0x00 */
+    U32                     Signature0;                 /* 0x04 */
+    U32                     Signature1;                 /* 0x08 */
+    U32                     Signature2;                 /* 0x0C */
+    MPI2_VERSION_UNION      MPIVersion;                 /* 0x10 */
+    MPI2_VERSION_UNION      FWVersion;                  /* 0x14 */
+    MPI2_VERSION_UNION      NVDATAVersion;              /* 0x18 */
+    MPI2_VERSION_UNION      PackageVersion;             /* 0x1C */
+    U16                     VendorID;                   /* 0x20 */
+    U16                     ProductID;                  /* 0x22 */
+    U16                     ProtocolFlags;              /* 0x24 */
+    U16                     Reserved26;                 /* 0x26 */
+    U32                     IOCCapabilities;            /* 0x28 */
+    U32                     ImageSize;                  /* 0x2C */
+    U32                     NextImageHeaderOffset;      /* 0x30 */
+    U32                     Checksum;                   /* 0x34 */
+    U32                     Reserved38;                 /* 0x38 */
+    U32                     Reserved3C;                 /* 0x3C */
+    U32                     Reserved40;                 /* 0x40 */
+    U32                     Reserved44;                 /* 0x44 */
+    U32                     Reserved48;                 /* 0x48 */
+    U32                     Reserved4C;                 /* 0x4C */
+    U32                     Reserved50;                 /* 0x50 */
+    U32                     Reserved54;                 /* 0x54 */
+    U32                     Reserved58;                 /* 0x58 */
+    U32                     Reserved5C;                 /* 0x5C */
+    U32                     Reserved60;                 /* 0x60 */
+    U32                     FirmwareVersionNameWhat;    /* 0x64 */
+    U8                      FirmwareVersionName[32];    /* 0x68 */
+    U32                     VendorNameWhat;             /* 0x88 */
+    U8                      VendorName[32];             /* 0x8C */
+    U32                     PackageNameWhat;            /* 0x88 */
+    U8                      PackageName[32];            /* 0x8C */
+    U32                     ReservedD0;                 /* 0xD0 */
+    U32                     ReservedD4;                 /* 0xD4 */
+    U32                     ReservedD8;                 /* 0xD8 */
+    U32                     ReservedDC;                 /* 0xDC */
+    U32                     ReservedE0;                 /* 0xE0 */
+    U32                     ReservedE4;                 /* 0xE4 */
+    U32                     ReservedE8;                 /* 0xE8 */
+    U32                     ReservedEC;                 /* 0xEC */
+    U32                     ReservedF0;                 /* 0xF0 */
+    U32                     ReservedF4;                 /* 0xF4 */
+    U32                     ReservedF8;                 /* 0xF8 */
+    U32                     ReservedFC;                 /* 0xFC */
+} MPI2_FW_IMAGE_HEADER, MPI2_POINTER PTR_MPI2_FW_IMAGE_HEADER,
+  Mpi2FWImageHeader_t, MPI2_POINTER pMpi2FWImageHeader_t;
+
+/* Signature field */
+#define MPI2_FW_HEADER_SIGNATURE_OFFSET         (0x00)
+#define MPI2_FW_HEADER_SIGNATURE_MASK           (0xFF000000)
+#define MPI2_FW_HEADER_SIGNATURE                (0xEA000000)
+
+/* Signature0 field */
+#define MPI2_FW_HEADER_SIGNATURE0_OFFSET        (0x04)
+#define MPI2_FW_HEADER_SIGNATURE0               (0x5AFAA55A)
+
+/* Signature1 field */
+#define MPI2_FW_HEADER_SIGNATURE1_OFFSET        (0x08)
+#define MPI2_FW_HEADER_SIGNATURE1               (0xA55AFAA5)
+
+/* Signature2 field */
+#define MPI2_FW_HEADER_SIGNATURE2_OFFSET        (0x0C)
+#define MPI2_FW_HEADER_SIGNATURE2               (0x5AA55AFA)
+
+
+/* defines for using the ProductID field */
+#define MPI2_FW_HEADER_PID_TYPE_MASK            (0xF000)
+#define MPI2_FW_HEADER_PID_TYPE_SAS             (0x2000)
+
+#define MPI2_FW_HEADER_PID_PROD_MASK                    (0x0F00)
+#define MPI2_FW_HEADER_PID_PROD_A                       (0x0000)
+#define MPI2_FW_HEADER_PID_PROD_MASK                    (0x0F00)
+#define MPI2_FW_HEADER_PID_PROD_TARGET_INITIATOR_SCSI   (0x0200)
+#define MPI2_FW_HEADER_PID_PROD_IR_SCSI                 (0x0700)
+
+
+#define MPI2_FW_HEADER_PID_FAMILY_MASK          (0x00FF)
+/* SAS */
+#define MPI2_FW_HEADER_PID_FAMILY_2108_SAS      (0x0013)
+#define MPI2_FW_HEADER_PID_FAMILY_2208_SAS      (0x0014)
+
+/* use MPI2_IOCFACTS_PROTOCOL_ defines for ProtocolFlags field */
+
+/* use MPI2_IOCFACTS_CAPABILITY_ defines for IOCCapabilities field */
+
+
+#define MPI2_FW_HEADER_IMAGESIZE_OFFSET         (0x2C)
+#define MPI2_FW_HEADER_NEXTIMAGE_OFFSET         (0x30)
+#define MPI2_FW_HEADER_VERNMHWAT_OFFSET         (0x64)
+
+#define MPI2_FW_HEADER_WHAT_SIGNATURE           (0x29232840)
+
+#define MPI2_FW_HEADER_SIZE                     (0x100)
+
+
+/* Extended Image Header */
+typedef struct _MPI2_EXT_IMAGE_HEADER
+
+{
+    U8                      ImageType;                  /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U16                     Reserved2;                  /* 0x02 */
+    U32                     Checksum;                   /* 0x04 */
+    U32                     ImageSize;                  /* 0x08 */
+    U32                     NextImageHeaderOffset;      /* 0x0C */
+    U32                     PackageVersion;             /* 0x10 */
+    U32                     Reserved3;                  /* 0x14 */
+    U32                     Reserved4;                  /* 0x18 */
+    U32                     Reserved5;                  /* 0x1C */
+    U8                      IdentifyString[32];         /* 0x20 */
+} MPI2_EXT_IMAGE_HEADER, MPI2_POINTER PTR_MPI2_EXT_IMAGE_HEADER,
+  Mpi2ExtImageHeader_t, MPI2_POINTER pMpi2ExtImageHeader_t;
+
+/* useful offsets */
+#define MPI2_EXT_IMAGE_IMAGETYPE_OFFSET         (0x00)
+#define MPI2_EXT_IMAGE_IMAGESIZE_OFFSET         (0x08)
+#define MPI2_EXT_IMAGE_NEXTIMAGE_OFFSET         (0x0C)
+
+#define MPI2_EXT_IMAGE_HEADER_SIZE              (0x40)
+
+/* defines for the ImageType field */
+#define MPI2_EXT_IMAGE_TYPE_UNSPECIFIED         (0x00)
+#define MPI2_EXT_IMAGE_TYPE_FW                  (0x01)
+#define MPI2_EXT_IMAGE_TYPE_NVDATA              (0x03)
+#define MPI2_EXT_IMAGE_TYPE_BOOTLOADER          (0x04)
+#define MPI2_EXT_IMAGE_TYPE_INITIALIZATION      (0x05)
+#define MPI2_EXT_IMAGE_TYPE_FLASH_LAYOUT        (0x06)
+#define MPI2_EXT_IMAGE_TYPE_SUPPORTED_DEVICES   (0x07)
+#define MPI2_EXT_IMAGE_TYPE_MEGARAID            (0x08)
+
+#define MPI2_EXT_IMAGE_TYPE_MAX                 (MPI2_EXT_IMAGE_TYPE_MEGARAID)
+
+
+
+/* FLASH Layout Extended Image Data */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check RegionsPerLayout at runtime.
+ */
+#ifndef MPI2_FLASH_NUMBER_OF_REGIONS
+#define MPI2_FLASH_NUMBER_OF_REGIONS        (1)
+#endif
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check NumberOfLayouts at runtime.
+ */
+#ifndef MPI2_FLASH_NUMBER_OF_LAYOUTS
+#define MPI2_FLASH_NUMBER_OF_LAYOUTS        (1)
+#endif
+
+typedef struct _MPI2_FLASH_REGION
+{
+    U8                      RegionType;                 /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U16                     Reserved2;                  /* 0x02 */
+    U32                     RegionOffset;               /* 0x04 */
+    U32                     RegionSize;                 /* 0x08 */
+    U32                     Reserved3;                  /* 0x0C */
+} MPI2_FLASH_REGION, MPI2_POINTER PTR_MPI2_FLASH_REGION,
+  Mpi2FlashRegion_t, MPI2_POINTER pMpi2FlashRegion_t;
+
+typedef struct _MPI2_FLASH_LAYOUT
+{
+    U32                     FlashSize;                  /* 0x00 */
+    U32                     Reserved1;                  /* 0x04 */
+    U32                     Reserved2;                  /* 0x08 */
+    U32                     Reserved3;                  /* 0x0C */
+    MPI2_FLASH_REGION       Region[MPI2_FLASH_NUMBER_OF_REGIONS];/* 0x10 */
+} MPI2_FLASH_LAYOUT, MPI2_POINTER PTR_MPI2_FLASH_LAYOUT,
+  Mpi2FlashLayout_t, MPI2_POINTER pMpi2FlashLayout_t;
+
+typedef struct _MPI2_FLASH_LAYOUT_DATA
+{
+    U8                      ImageRevision;              /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      SizeOfRegion;               /* 0x02 */
+    U8                      Reserved2;                  /* 0x03 */
+    U16                     NumberOfLayouts;            /* 0x04 */
+    U16                     RegionsPerLayout;           /* 0x06 */
+    U16                     MinimumSectorAlignment;     /* 0x08 */
+    U16                     Reserved3;                  /* 0x0A */
+    U32                     Reserved4;                  /* 0x0C */
+    MPI2_FLASH_LAYOUT       Layout[MPI2_FLASH_NUMBER_OF_LAYOUTS];/* 0x10 */
+} MPI2_FLASH_LAYOUT_DATA, MPI2_POINTER PTR_MPI2_FLASH_LAYOUT_DATA,
+  Mpi2FlashLayoutData_t, MPI2_POINTER pMpi2FlashLayoutData_t;
+
+/* defines for the RegionType field */
+#define MPI2_FLASH_REGION_UNUSED                (0x00)
+#define MPI2_FLASH_REGION_FIRMWARE              (0x01)
+#define MPI2_FLASH_REGION_BIOS                  (0x02)
+#define MPI2_FLASH_REGION_NVDATA                (0x03)
+#define MPI2_FLASH_REGION_FIRMWARE_BACKUP       (0x05)
+#define MPI2_FLASH_REGION_MFG_INFORMATION       (0x06)
+#define MPI2_FLASH_REGION_CONFIG_1              (0x07)
+#define MPI2_FLASH_REGION_CONFIG_2              (0x08)
+#define MPI2_FLASH_REGION_MEGARAID              (0x09)
+#define MPI2_FLASH_REGION_INIT                  (0x0A)
+
+/* ImageRevision */
+#define MPI2_FLASH_LAYOUT_IMAGE_REVISION        (0x00)
+
+
+
+/* Supported Devices Extended Image Data */
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set to
+ * one and check NumberOfDevices at runtime.
+ */
+#ifndef MPI2_SUPPORTED_DEVICES_IMAGE_NUM_DEVICES
+#define MPI2_SUPPORTED_DEVICES_IMAGE_NUM_DEVICES    (1)
+#endif
+
+typedef struct _MPI2_SUPPORTED_DEVICE
+{
+    U16                     DeviceID;                   /* 0x00 */
+    U16                     VendorID;                   /* 0x02 */
+    U16                     DeviceIDMask;               /* 0x04 */
+    U16                     Reserved1;                  /* 0x06 */
+    U8                      LowPCIRev;                  /* 0x08 */
+    U8                      HighPCIRev;                 /* 0x09 */
+    U16                     Reserved2;                  /* 0x0A */
+    U32                     Reserved3;                  /* 0x0C */
+} MPI2_SUPPORTED_DEVICE, MPI2_POINTER PTR_MPI2_SUPPORTED_DEVICE,
+  Mpi2SupportedDevice_t, MPI2_POINTER pMpi2SupportedDevice_t;
+
+typedef struct _MPI2_SUPPORTED_DEVICES_DATA
+{
+    U8                      ImageRevision;              /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      NumberOfDevices;            /* 0x02 */
+    U8                      Reserved2;                  /* 0x03 */
+    U32                     Reserved3;                  /* 0x04 */
+    MPI2_SUPPORTED_DEVICE   SupportedDevice[MPI2_SUPPORTED_DEVICES_IMAGE_NUM_DEVICES]; /* 0x08 */
+} MPI2_SUPPORTED_DEVICES_DATA, MPI2_POINTER PTR_MPI2_SUPPORTED_DEVICES_DATA,
+  Mpi2SupportedDevicesData_t, MPI2_POINTER pMpi2SupportedDevicesData_t;
+
+/* ImageRevision */
+#define MPI2_SUPPORTED_DEVICES_IMAGE_REVISION   (0x00)
+
+
+/* Init Extended Image Data */
+
+typedef struct _MPI2_INIT_IMAGE_FOOTER
+
+{
+    U32                     BootFlags;                  /* 0x00 */
+    U32                     ImageSize;                  /* 0x04 */
+    U32                     Signature0;                 /* 0x08 */
+    U32                     Signature1;                 /* 0x0C */
+    U32                     Signature2;                 /* 0x10 */
+    U32                     ResetVector;                /* 0x14 */
+} MPI2_INIT_IMAGE_FOOTER, MPI2_POINTER PTR_MPI2_INIT_IMAGE_FOOTER,
+  Mpi2InitImageFooter_t, MPI2_POINTER pMpi2InitImageFooter_t;
+
+/* defines for the BootFlags field */
+#define MPI2_INIT_IMAGE_BOOTFLAGS_OFFSET        (0x00)
+
+/* defines for the ImageSize field */
+#define MPI2_INIT_IMAGE_IMAGESIZE_OFFSET        (0x04)
+
+/* defines for the Signature0 field */
+#define MPI2_INIT_IMAGE_SIGNATURE0_OFFSET       (0x08)
+#define MPI2_INIT_IMAGE_SIGNATURE0              (0x5AA55AEA)
+
+/* defines for the Signature1 field */
+#define MPI2_INIT_IMAGE_SIGNATURE1_OFFSET       (0x0C)
+#define MPI2_INIT_IMAGE_SIGNATURE1              (0xA55AEAA5)
+
+/* defines for the Signature2 field */
+#define MPI2_INIT_IMAGE_SIGNATURE2_OFFSET       (0x10)
+#define MPI2_INIT_IMAGE_SIGNATURE2              (0x5AEAA55A)
+
+/* Signature fields as individual bytes */
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_0        (0xEA)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_1        (0x5A)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_2        (0xA5)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_3        (0x5A)
+
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_4        (0xA5)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_5        (0xEA)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_6        (0x5A)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_7        (0xA5)
+
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_8        (0x5A)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_9        (0xA5)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_A        (0xEA)
+#define MPI2_INIT_IMAGE_SIGNATURE_BYTE_B        (0x5A)
+
+/* defines for the ResetVector field */
+#define MPI2_INIT_IMAGE_RESETVECTOR_OFFSET      (0x14)
+
+
+#endif
+
diff --git a/sys/dev/mps/mpi/mpi2_ra.h b/sys/dev/mps/mpi/mpi2_ra.h
new file mode 100644
index 00000000000..18b0b3d8015
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_ra.h
@@ -0,0 +1,86 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_ra.h
+ *          Title:  MPI RAID Accelerator messages and structures
+ *  Creation Date:  April 13, 2009
+ *
+ *  mpi2_ra.h Version:  02.00.00
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  05-06-09  02.00.00  Initial version.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_RA_H
+#define MPI2_RA_H
+
+/* generic structure for RAID Accelerator Control Block */
+typedef struct _MPI2_RAID_ACCELERATOR_CONTROL_BLOCK
+{
+    U32                 Reserved[8];                /* 0x00 */
+    U32                 RaidAcceleratorCDB[1];      /* 0x20 */
+} MPI2_RAID_ACCELERATOR_CONTROL_BLOCK,
+  MPI2_POINTER PTR_MPI2_RAID_ACCELERATOR_CONTROL_BLOCK,
+  Mpi2RAIDAcceleratorControlBlock_t,
+  MPI2_POINTER pMpi2RAIDAcceleratorControlBlock_t;
+
+
+/******************************************************************************
+*
+*        RAID Accelerator Messages
+*
+*******************************************************************************/
+
+/* RAID Accelerator Request Message */
+typedef struct _MPI2_RAID_ACCELERATOR_REQUEST
+{
+    U16                     Reserved0;                          /* 0x00 */
+    U8                      ChainOffset;                        /* 0x02 */
+    U8                      Function;                           /* 0x03 */
+    U16                     Reserved1;                          /* 0x04 */
+    U8                      Reserved2;                          /* 0x06 */
+    U8                      MsgFlags;                           /* 0x07 */
+    U8                      VP_ID;                              /* 0x08 */
+    U8                      VF_ID;                              /* 0x09 */
+    U16                     Reserved3;                          /* 0x0A */
+    U64                     RaidAcceleratorControlBlockAddress; /* 0x0C */
+    U8                      DmaEngineNumber;                    /* 0x14 */
+    U8                      Reserved4;                          /* 0x15 */
+    U16                     Reserved5;                          /* 0x16 */
+    U32                     Reserved6;                          /* 0x18 */
+    U32                     Reserved7;                          /* 0x1C */
+    U32                     Reserved8;                          /* 0x20 */
+} MPI2_RAID_ACCELERATOR_REQUEST, MPI2_POINTER PTR_MPI2_RAID_ACCELERATOR_REQUEST,
+  Mpi2RAIDAcceleratorRequest_t, MPI2_POINTER pMpi2RAIDAcceleratorRequest_t;
+
+
+/* RAID Accelerator Error Reply Message */
+typedef struct _MPI2_RAID_ACCELERATOR_REPLY
+{
+    U16                     Reserved0;                      /* 0x00 */
+    U8                      MsgLength;                      /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     Reserved1;                      /* 0x04 */
+    U8                      Reserved2;                      /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved3;                      /* 0x0A */
+    U16                     Reserved4;                      /* 0x0C */
+    U16                     IOCStatus;                      /* 0x0E */
+    U32                     IOCLogInfo;                     /* 0x10 */
+    U32                     ProductSpecificData[3];         /* 0x14 */
+} MPI2_RAID_ACCELERATOR_REPLY, MPI2_POINTER PTR_MPI2_RAID_ACCELERATOR_REPLY,
+  Mpi2RAIDAcceleratorReply_t, MPI2_POINTER pMpi2RAIDAcceleratorReply_t;
+
+
+#endif
+
+
diff --git a/sys/dev/mps/mpi/mpi2_raid.h b/sys/dev/mps/mpi/mpi2_raid.h
new file mode 100644
index 00000000000..f65302817ce
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_raid.h
@@ -0,0 +1,302 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2008 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_raid.h
+ *          Title:  MPI Integrated RAID messages and structures
+ *  Creation Date:  April 26, 2007
+ *
+ *    mpi2_raid.h Version:  02.00.04
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  08-31-07  02.00.01  Modifications to RAID Action request and reply,
+ *                      including the Actions and ActionData.
+ *  02-29-08  02.00.02  Added MPI2_RAID_ACTION_ADATA_DISABL_FULL_REBUILD.
+ *  05-21-08  02.00.03  Added MPI2_RAID_VOL_CREATION_NUM_PHYSDISKS so that
+ *                      the PhysDisk array in MPI2_RAID_VOLUME_CREATION_STRUCT
+ *                      can be sized by the build environment.
+ *  07-30-09  02.00.04  Added proper define for the Use Default Settings bit of
+ *                      VolumeCreationFlags and marked the old one as obsolete.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_RAID_H
+#define MPI2_RAID_H
+
+/*****************************************************************************
+*
+*               Integrated RAID Messages
+*
+*****************************************************************************/
+
+/****************************************************************************
+*  RAID Action messages
+****************************************************************************/
+
+/* ActionDataWord defines for use with MPI2_RAID_ACTION_DELETE_VOLUME action */
+#define MPI2_RAID_ACTION_ADATA_KEEP_LBA0            (0x00000000)
+#define MPI2_RAID_ACTION_ADATA_ZERO_LBA0            (0x00000001)
+
+/* use MPI2_RAIDVOL0_SETTING_ defines from mpi2_cnfg.h for MPI2_RAID_ACTION_CHANGE_VOL_WRITE_CACHE action */
+
+/* ActionDataWord defines for use with MPI2_RAID_ACTION_DISABLE_ALL_VOLUMES action */
+#define MPI2_RAID_ACTION_ADATA_DISABL_FULL_REBUILD  (0x00000001)
+
+/* ActionDataWord for MPI2_RAID_ACTION_SET_RAID_FUNCTION_RATE Action */
+typedef struct _MPI2_RAID_ACTION_RATE_DATA
+{
+    U8              RateToChange;               /* 0x00 */
+    U8              RateOrMode;                 /* 0x01 */
+    U16             DataScrubDuration;          /* 0x02 */
+} MPI2_RAID_ACTION_RATE_DATA, MPI2_POINTER PTR_MPI2_RAID_ACTION_RATE_DATA,
+  Mpi2RaidActionRateData_t, MPI2_POINTER pMpi2RaidActionRateData_t;
+
+#define MPI2_RAID_ACTION_SET_RATE_RESYNC            (0x00)
+#define MPI2_RAID_ACTION_SET_RATE_DATA_SCRUB        (0x01)
+#define MPI2_RAID_ACTION_SET_RATE_POWERSAVE_MODE    (0x02)
+
+/* ActionDataWord for MPI2_RAID_ACTION_START_RAID_FUNCTION Action */
+typedef struct _MPI2_RAID_ACTION_START_RAID_FUNCTION
+{
+    U8              RAIDFunction;                       /* 0x00 */
+    U8              Flags;                              /* 0x01 */
+    U16             Reserved1;                          /* 0x02 */
+} MPI2_RAID_ACTION_START_RAID_FUNCTION,
+  MPI2_POINTER PTR_MPI2_RAID_ACTION_START_RAID_FUNCTION,
+  Mpi2RaidActionStartRaidFunction_t,
+  MPI2_POINTER pMpi2RaidActionStartRaidFunction_t;
+
+/* defines for the RAIDFunction field */
+#define MPI2_RAID_ACTION_START_BACKGROUND_INIT      (0x00)
+#define MPI2_RAID_ACTION_START_ONLINE_CAP_EXPANSION (0x01)
+#define MPI2_RAID_ACTION_START_CONSISTENCY_CHECK    (0x02)
+
+/* defines for the Flags field */
+#define MPI2_RAID_ACTION_START_NEW                  (0x00)
+#define MPI2_RAID_ACTION_START_RESUME               (0x01)
+
+/* ActionDataWord for MPI2_RAID_ACTION_STOP_RAID_FUNCTION Action */
+typedef struct _MPI2_RAID_ACTION_STOP_RAID_FUNCTION
+{
+    U8              RAIDFunction;                       /* 0x00 */
+    U8              Flags;                              /* 0x01 */
+    U16             Reserved1;                          /* 0x02 */
+} MPI2_RAID_ACTION_STOP_RAID_FUNCTION,
+  MPI2_POINTER PTR_MPI2_RAID_ACTION_STOP_RAID_FUNCTION,
+  Mpi2RaidActionStopRaidFunction_t,
+  MPI2_POINTER pMpi2RaidActionStopRaidFunction_t;
+
+/* defines for the RAIDFunction field */
+#define MPI2_RAID_ACTION_STOP_BACKGROUND_INIT       (0x00)
+#define MPI2_RAID_ACTION_STOP_ONLINE_CAP_EXPANSION  (0x01)
+#define MPI2_RAID_ACTION_STOP_CONSISTENCY_CHECK     (0x02)
+
+/* defines for the Flags field */
+#define MPI2_RAID_ACTION_STOP_ABORT                 (0x00)
+#define MPI2_RAID_ACTION_STOP_PAUSE                 (0x01)
+
+/* ActionDataWord for MPI2_RAID_ACTION_CREATE_HOT_SPARE Action */
+typedef struct _MPI2_RAID_ACTION_HOT_SPARE
+{
+    U8              HotSparePool;               /* 0x00 */
+    U8              Reserved1;                  /* 0x01 */
+    U16             DevHandle;                  /* 0x02 */
+} MPI2_RAID_ACTION_HOT_SPARE, MPI2_POINTER PTR_MPI2_RAID_ACTION_HOT_SPARE,
+  Mpi2RaidActionHotSpare_t, MPI2_POINTER pMpi2RaidActionHotSpare_t;
+
+/* ActionDataWord for MPI2_RAID_ACTION_DEVICE_FW_UPDATE_MODE Action */
+typedef struct _MPI2_RAID_ACTION_FW_UPDATE_MODE
+{
+    U8              Flags;                              /* 0x00 */
+    U8              DeviceFirmwareUpdateModeTimeout;    /* 0x01 */
+    U16             Reserved1;                          /* 0x02 */
+} MPI2_RAID_ACTION_FW_UPDATE_MODE,
+  MPI2_POINTER PTR_MPI2_RAID_ACTION_FW_UPDATE_MODE,
+  Mpi2RaidActionFwUpdateMode_t, MPI2_POINTER pMpi2RaidActionFwUpdateMode_t;
+
+/* ActionDataWord defines for use with MPI2_RAID_ACTION_DEVICE_FW_UPDATE_MODE action */
+#define MPI2_RAID_ACTION_ADATA_DISABLE_FW_UPDATE        (0x00)
+#define MPI2_RAID_ACTION_ADATA_ENABLE_FW_UPDATE         (0x01)
+
+typedef union _MPI2_RAID_ACTION_DATA
+{
+    U32                                     Word;
+    MPI2_RAID_ACTION_RATE_DATA              Rates;
+    MPI2_RAID_ACTION_START_RAID_FUNCTION    StartRaidFunction;
+    MPI2_RAID_ACTION_STOP_RAID_FUNCTION     StopRaidFunction;
+    MPI2_RAID_ACTION_HOT_SPARE              HotSpare;
+    MPI2_RAID_ACTION_FW_UPDATE_MODE         FwUpdateMode;
+} MPI2_RAID_ACTION_DATA, MPI2_POINTER PTR_MPI2_RAID_ACTION_DATA,
+  Mpi2RaidActionData_t, MPI2_POINTER pMpi2RaidActionData_t;
+
+
+/* RAID Action Request Message */
+typedef struct _MPI2_RAID_ACTION_REQUEST
+{
+    U8                      Action;                         /* 0x00 */
+    U8                      Reserved1;                      /* 0x01 */
+    U8                      ChainOffset;                    /* 0x02 */
+    U8                      Function;                       /* 0x03 */
+    U16                     VolDevHandle;                   /* 0x04 */
+    U8                      PhysDiskNum;                    /* 0x06 */
+    U8                      MsgFlags;                       /* 0x07 */
+    U8                      VP_ID;                          /* 0x08 */
+    U8                      VF_ID;                          /* 0x09 */
+    U16                     Reserved2;                      /* 0x0A */
+    U32                     Reserved3;                      /* 0x0C */
+    MPI2_RAID_ACTION_DATA   ActionDataWord;                 /* 0x10 */
+    MPI2_SGE_SIMPLE_UNION   ActionDataSGE;                  /* 0x14 */
+} MPI2_RAID_ACTION_REQUEST, MPI2_POINTER PTR_MPI2_RAID_ACTION_REQUEST,
+  Mpi2RaidActionRequest_t, MPI2_POINTER pMpi2RaidActionRequest_t;
+
+/* RAID Action request Action values */
+
+#define MPI2_RAID_ACTION_INDICATOR_STRUCT           (0x01)
+#define MPI2_RAID_ACTION_CREATE_VOLUME              (0x02)
+#define MPI2_RAID_ACTION_DELETE_VOLUME              (0x03)
+#define MPI2_RAID_ACTION_DISABLE_ALL_VOLUMES        (0x04)
+#define MPI2_RAID_ACTION_ENABLE_ALL_VOLUMES         (0x05)
+#define MPI2_RAID_ACTION_PHYSDISK_OFFLINE           (0x0A)
+#define MPI2_RAID_ACTION_PHYSDISK_ONLINE            (0x0B)
+#define MPI2_RAID_ACTION_FAIL_PHYSDISK              (0x0F)
+#define MPI2_RAID_ACTION_ACTIVATE_VOLUME            (0x11)
+#define MPI2_RAID_ACTION_DEVICE_FW_UPDATE_MODE      (0x15)
+#define MPI2_RAID_ACTION_CHANGE_VOL_WRITE_CACHE     (0x17)
+#define MPI2_RAID_ACTION_SET_VOLUME_NAME            (0x18)
+#define MPI2_RAID_ACTION_SET_RAID_FUNCTION_RATE     (0x19)
+#define MPI2_RAID_ACTION_ENABLE_FAILED_VOLUME       (0x1C)
+#define MPI2_RAID_ACTION_CREATE_HOT_SPARE           (0x1D)
+#define MPI2_RAID_ACTION_DELETE_HOT_SPARE           (0x1E)
+#define MPI2_RAID_ACTION_SYSTEM_SHUTDOWN_INITIATED  (0x20)
+#define MPI2_RAID_ACTION_START_RAID_FUNCTION        (0x21)
+#define MPI2_RAID_ACTION_STOP_RAID_FUNCTION         (0x22)
+
+
+/* RAID Volume Creation Structure */
+
+/*
+ * The following define can be customized for the targeted product.
+ */
+#ifndef MPI2_RAID_VOL_CREATION_NUM_PHYSDISKS
+#define MPI2_RAID_VOL_CREATION_NUM_PHYSDISKS        (1)
+#endif
+
+typedef struct _MPI2_RAID_VOLUME_PHYSDISK
+{
+    U8                      RAIDSetNum;                     /* 0x00 */
+    U8                      PhysDiskMap;                    /* 0x01 */
+    U16                     PhysDiskDevHandle;              /* 0x02 */
+} MPI2_RAID_VOLUME_PHYSDISK, MPI2_POINTER PTR_MPI2_RAID_VOLUME_PHYSDISK,
+  Mpi2RaidVolumePhysDisk_t, MPI2_POINTER pMpi2RaidVolumePhysDisk_t;
+
+/* defines for the PhysDiskMap field */
+#define MPI2_RAIDACTION_PHYSDISK_PRIMARY            (0x01)
+#define MPI2_RAIDACTION_PHYSDISK_SECONDARY          (0x02)
+
+typedef struct _MPI2_RAID_VOLUME_CREATION_STRUCT
+{
+    U8                          NumPhysDisks;               /* 0x00 */
+    U8                          VolumeType;                 /* 0x01 */
+    U16                         Reserved1;                  /* 0x02 */
+    U32                         VolumeCreationFlags;        /* 0x04 */
+    U32                         VolumeSettings;             /* 0x08 */
+    U8                          Reserved2;                  /* 0x0C */
+    U8                          ResyncRate;                 /* 0x0D */
+    U16                         DataScrubDuration;          /* 0x0E */
+    U64                         VolumeMaxLBA;               /* 0x10 */
+    U32                         StripeSize;                 /* 0x18 */
+    U8                          Name[16];                   /* 0x1C */
+    MPI2_RAID_VOLUME_PHYSDISK   PhysDisk[MPI2_RAID_VOL_CREATION_NUM_PHYSDISKS];/* 0x2C */
+} MPI2_RAID_VOLUME_CREATION_STRUCT,
+  MPI2_POINTER PTR_MPI2_RAID_VOLUME_CREATION_STRUCT,
+  Mpi2RaidVolumeCreationStruct_t, MPI2_POINTER pMpi2RaidVolumeCreationStruct_t;
+
+/* use MPI2_RAID_VOL_TYPE_ defines from mpi2_cnfg.h for VolumeType */
+
+/* defines for the VolumeCreationFlags field */
+#define MPI2_RAID_VOL_CREATION_DEFAULT_SETTINGS     (0x80000000)
+#define MPI2_RAID_VOL_CREATION_BACKGROUND_INIT      (0x00000004)
+#define MPI2_RAID_VOL_CREATION_LOW_LEVEL_INIT       (0x00000002)
+#define MPI2_RAID_VOL_CREATION_MIGRATE_DATA         (0x00000001)
+/* The following is an obsolete define.
+ * It must be shifted left 24 bits in order to set the proper bit.
+ */
+#define MPI2_RAID_VOL_CREATION_USE_DEFAULT_SETTINGS (0x80)
+
+
+/* RAID Online Capacity Expansion Structure */
+
+typedef struct _MPI2_RAID_ONLINE_CAPACITY_EXPANSION
+{
+    U32                     Flags;                          /* 0x00 */
+    U16                     DevHandle0;                     /* 0x04 */
+    U16                     Reserved1;                      /* 0x06 */
+    U16                     DevHandle1;                     /* 0x08 */
+    U16                     Reserved2;                      /* 0x0A */
+} MPI2_RAID_ONLINE_CAPACITY_EXPANSION,
+  MPI2_POINTER PTR_MPI2_RAID_ONLINE_CAPACITY_EXPANSION,
+  Mpi2RaidOnlineCapacityExpansion_t,
+  MPI2_POINTER pMpi2RaidOnlineCapacityExpansion_t;
+
+
+/* RAID Volume Indicator Structure */
+
+typedef struct _MPI2_RAID_VOL_INDICATOR
+{
+    U64                     TotalBlocks;                    /* 0x00 */
+    U64                     BlocksRemaining;                /* 0x08 */
+    U32                     Flags;                          /* 0x10 */
+} MPI2_RAID_VOL_INDICATOR, MPI2_POINTER PTR_MPI2_RAID_VOL_INDICATOR,
+  Mpi2RaidVolIndicator_t, MPI2_POINTER pMpi2RaidVolIndicator_t;
+
+/* defines for RAID Volume Indicator Flags field */
+#define MPI2_RAID_VOL_FLAGS_OP_MASK                 (0x0000000F)
+#define MPI2_RAID_VOL_FLAGS_OP_BACKGROUND_INIT      (0x00000000)
+#define MPI2_RAID_VOL_FLAGS_OP_ONLINE_CAP_EXPANSION (0x00000001)
+#define MPI2_RAID_VOL_FLAGS_OP_CONSISTENCY_CHECK    (0x00000002)
+#define MPI2_RAID_VOL_FLAGS_OP_RESYNC               (0x00000003)
+
+
+/* RAID Action Reply ActionData union */
+typedef union _MPI2_RAID_ACTION_REPLY_DATA
+{
+    U32                     Word[5];
+    MPI2_RAID_VOL_INDICATOR RaidVolumeIndicator;
+    U16                     VolDevHandle;
+    U8                      VolumeState;
+    U8                      PhysDiskNum;
+} MPI2_RAID_ACTION_REPLY_DATA, MPI2_POINTER PTR_MPI2_RAID_ACTION_REPLY_DATA,
+  Mpi2RaidActionReplyData_t, MPI2_POINTER pMpi2RaidActionReplyData_t;
+
+/* use MPI2_RAIDVOL0_SETTING_ defines from mpi2_cnfg.h for MPI2_RAID_ACTION_CHANGE_VOL_WRITE_CACHE action */
+
+
+/* RAID Action Reply Message */
+typedef struct _MPI2_RAID_ACTION_REPLY
+{
+    U8                          Action;                     /* 0x00 */
+    U8                          Reserved1;                  /* 0x01 */
+    U8                          MsgLength;                  /* 0x02 */
+    U8                          Function;                   /* 0x03 */
+    U16                         VolDevHandle;               /* 0x04 */
+    U8                          PhysDiskNum;                /* 0x06 */
+    U8                          MsgFlags;                   /* 0x07 */
+    U8                          VP_ID;                      /* 0x08 */
+    U8                          VF_ID;                      /* 0x09 */
+    U16                         Reserved2;                  /* 0x0A */
+    U16                         Reserved3;                  /* 0x0C */
+    U16                         IOCStatus;                  /* 0x0E */
+    U32                         IOCLogInfo;                 /* 0x10 */
+    MPI2_RAID_ACTION_REPLY_DATA ActionData;                 /* 0x14 */
+} MPI2_RAID_ACTION_REPLY, MPI2_POINTER PTR_MPI2_RAID_ACTION_REPLY,
+  Mpi2RaidActionReply_t, MPI2_POINTER pMpi2RaidActionReply_t;
+
+
+#endif
+
diff --git a/sys/dev/mps/mpi/mpi2_sas.h b/sys/dev/mps/mpi/mpi2_sas.h
new file mode 100644
index 00000000000..ef64a7307df
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_sas.h
@@ -0,0 +1,285 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2007 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_sas.h
+ *          Title:  MPI Serial Attached SCSI structures and definitions
+ *  Creation Date:  February 9, 2007
+ *
+ *  mpi2.h Version:  02.00.03
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  06-26-07  02.00.01  Added Clear All Persistent Operation to SAS IO Unit
+ *                      Control Request.
+ *  10-02-08  02.00.02  Added Set IOC Parameter Operation to SAS IO Unit Control
+ *                      Request.
+ *  10-28-09  02.00.03  Changed the type of SGL in MPI2_SATA_PASSTHROUGH_REQUEST
+ *                      to MPI2_SGE_IO_UNION since it supports chained SGLs.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_SAS_H
+#define MPI2_SAS_H
+
+/*
+ * Values for SASStatus.
+ */
+#define MPI2_SASSTATUS_SUCCESS                          (0x00)
+#define MPI2_SASSTATUS_UNKNOWN_ERROR                    (0x01)
+#define MPI2_SASSTATUS_INVALID_FRAME                    (0x02)
+#define MPI2_SASSTATUS_UTC_BAD_DEST                     (0x03)
+#define MPI2_SASSTATUS_UTC_BREAK_RECEIVED               (0x04)
+#define MPI2_SASSTATUS_UTC_CONNECT_RATE_NOT_SUPPORTED   (0x05)
+#define MPI2_SASSTATUS_UTC_PORT_LAYER_REQUEST           (0x06)
+#define MPI2_SASSTATUS_UTC_PROTOCOL_NOT_SUPPORTED       (0x07)
+#define MPI2_SASSTATUS_UTC_STP_RESOURCES_BUSY           (0x08)
+#define MPI2_SASSTATUS_UTC_WRONG_DESTINATION            (0x09)
+#define MPI2_SASSTATUS_SHORT_INFORMATION_UNIT           (0x0A)
+#define MPI2_SASSTATUS_LONG_INFORMATION_UNIT            (0x0B)
+#define MPI2_SASSTATUS_XFER_RDY_INCORRECT_WRITE_DATA    (0x0C)
+#define MPI2_SASSTATUS_XFER_RDY_REQUEST_OFFSET_ERROR    (0x0D)
+#define MPI2_SASSTATUS_XFER_RDY_NOT_EXPECTED            (0x0E)
+#define MPI2_SASSTATUS_DATA_INCORRECT_DATA_LENGTH       (0x0F)
+#define MPI2_SASSTATUS_DATA_TOO_MUCH_READ_DATA          (0x10)
+#define MPI2_SASSTATUS_DATA_OFFSET_ERROR                (0x11)
+#define MPI2_SASSTATUS_SDSF_NAK_RECEIVED                (0x12)
+#define MPI2_SASSTATUS_SDSF_CONNECTION_FAILED           (0x13)
+#define MPI2_SASSTATUS_INITIATOR_RESPONSE_TIMEOUT       (0x14)
+
+
+/*
+ * Values for the SAS DeviceInfo field used in SAS Device Status Change Event
+ * data and SAS Configuration pages.
+ */
+#define MPI2_SAS_DEVICE_INFO_SEP                (0x00004000)
+#define MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE       (0x00002000)
+#define MPI2_SAS_DEVICE_INFO_LSI_DEVICE         (0x00001000)
+#define MPI2_SAS_DEVICE_INFO_DIRECT_ATTACH      (0x00000800)
+#define MPI2_SAS_DEVICE_INFO_SSP_TARGET         (0x00000400)
+#define MPI2_SAS_DEVICE_INFO_STP_TARGET         (0x00000200)
+#define MPI2_SAS_DEVICE_INFO_SMP_TARGET         (0x00000100)
+#define MPI2_SAS_DEVICE_INFO_SATA_DEVICE        (0x00000080)
+#define MPI2_SAS_DEVICE_INFO_SSP_INITIATOR      (0x00000040)
+#define MPI2_SAS_DEVICE_INFO_STP_INITIATOR      (0x00000020)
+#define MPI2_SAS_DEVICE_INFO_SMP_INITIATOR      (0x00000010)
+#define MPI2_SAS_DEVICE_INFO_SATA_HOST          (0x00000008)
+
+#define MPI2_SAS_DEVICE_INFO_MASK_DEVICE_TYPE   (0x00000007)
+#define MPI2_SAS_DEVICE_INFO_NO_DEVICE          (0x00000000)
+#define MPI2_SAS_DEVICE_INFO_END_DEVICE         (0x00000001)
+#define MPI2_SAS_DEVICE_INFO_EDGE_EXPANDER      (0x00000002)
+#define MPI2_SAS_DEVICE_INFO_FANOUT_EXPANDER    (0x00000003)
+
+
+/*****************************************************************************
+*
+*        SAS Messages
+*
+*****************************************************************************/
+
+/****************************************************************************
+*  SMP Passthrough messages
+****************************************************************************/
+
+/* SMP Passthrough Request Message */
+typedef struct _MPI2_SMP_PASSTHROUGH_REQUEST
+{
+    U8                      PassthroughFlags;   /* 0x00 */
+    U8                      PhysicalPort;       /* 0x01 */
+    U8                      ChainOffset;        /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     RequestDataLength;  /* 0x04 */
+    U8                      SGLFlags;           /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved1;          /* 0x0A */
+    U32                     Reserved2;          /* 0x0C */
+    U64                     SASAddress;         /* 0x10 */
+    U32                     Reserved3;          /* 0x18 */
+    U32                     Reserved4;          /* 0x1C */
+    MPI2_SIMPLE_SGE_UNION   SGL;                /* 0x20 */
+} MPI2_SMP_PASSTHROUGH_REQUEST, MPI2_POINTER PTR_MPI2_SMP_PASSTHROUGH_REQUEST,
+  Mpi2SmpPassthroughRequest_t, MPI2_POINTER pMpi2SmpPassthroughRequest_t;
+
+/* values for PassthroughFlags field */
+#define MPI2_SMP_PT_REQ_PT_FLAGS_IMMEDIATE      (0x80)
+
+/* values for SGLFlags field are in the SGL section of mpi2.h */
+
+
+/* SMP Passthrough Reply Message */
+typedef struct _MPI2_SMP_PASSTHROUGH_REPLY
+{
+    U8                      PassthroughFlags;   /* 0x00 */
+    U8                      PhysicalPort;       /* 0x01 */
+    U8                      MsgLength;          /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     ResponseDataLength; /* 0x04 */
+    U8                      SGLFlags;           /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved1;          /* 0x0A */
+    U8                      Reserved2;          /* 0x0C */
+    U8                      SASStatus;          /* 0x0D */
+    U16                     IOCStatus;          /* 0x0E */
+    U32                     IOCLogInfo;         /* 0x10 */
+    U32                     Reserved3;          /* 0x14 */
+    U8                      ResponseData[4];    /* 0x18 */
+} MPI2_SMP_PASSTHROUGH_REPLY, MPI2_POINTER PTR_MPI2_SMP_PASSTHROUGH_REPLY,
+  Mpi2SmpPassthroughReply_t, MPI2_POINTER pMpi2SmpPassthroughReply_t;
+
+/* values for PassthroughFlags field */
+#define MPI2_SMP_PT_REPLY_PT_FLAGS_IMMEDIATE    (0x80)
+
+/* values for SASStatus field are at the top of this file */
+
+
+/****************************************************************************
+*  SATA Passthrough messages
+****************************************************************************/
+
+/* SATA Passthrough Request Message */
+typedef struct _MPI2_SATA_PASSTHROUGH_REQUEST
+{
+    U16                     DevHandle;          /* 0x00 */
+    U8                      ChainOffset;        /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     PassthroughFlags;   /* 0x04 */
+    U8                      SGLFlags;           /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved1;          /* 0x0A */
+    U32                     Reserved2;          /* 0x0C */
+    U32                     Reserved3;          /* 0x10 */
+    U32                     Reserved4;          /* 0x14 */
+    U32                     DataLength;         /* 0x18 */
+    U8                      CommandFIS[20];     /* 0x1C */
+    MPI2_SGE_IO_UNION       SGL;                /* 0x20 */
+} MPI2_SATA_PASSTHROUGH_REQUEST, MPI2_POINTER PTR_MPI2_SATA_PASSTHROUGH_REQUEST,
+  Mpi2SataPassthroughRequest_t, MPI2_POINTER pMpi2SataPassthroughRequest_t;
+
+/* values for PassthroughFlags field */
+#define MPI2_SATA_PT_REQ_PT_FLAGS_EXECUTE_DIAG      (0x0100)
+#define MPI2_SATA_PT_REQ_PT_FLAGS_DMA               (0x0020)
+#define MPI2_SATA_PT_REQ_PT_FLAGS_PIO               (0x0010)
+#define MPI2_SATA_PT_REQ_PT_FLAGS_UNSPECIFIED_VU    (0x0004)
+#define MPI2_SATA_PT_REQ_PT_FLAGS_WRITE             (0x0002)
+#define MPI2_SATA_PT_REQ_PT_FLAGS_READ              (0x0001)
+
+/* values for SGLFlags field are in the SGL section of mpi2.h */
+
+
+/* SATA Passthrough Reply Message */
+typedef struct _MPI2_SATA_PASSTHROUGH_REPLY
+{
+    U16                     DevHandle;          /* 0x00 */
+    U8                      MsgLength;          /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     PassthroughFlags;   /* 0x04 */
+    U8                      SGLFlags;           /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved1;          /* 0x0A */
+    U8                      Reserved2;          /* 0x0C */
+    U8                      SASStatus;          /* 0x0D */
+    U16                     IOCStatus;          /* 0x0E */
+    U32                     IOCLogInfo;         /* 0x10 */
+    U8                      StatusFIS[20];      /* 0x14 */
+    U32                     StatusControlRegisters; /* 0x28 */
+    U32                     TransferCount;      /* 0x2C */
+} MPI2_SATA_PASSTHROUGH_REPLY, MPI2_POINTER PTR_MPI2_SATA_PASSTHROUGH_REPLY,
+  Mpi2SataPassthroughReply_t, MPI2_POINTER pMpi2SataPassthroughReply_t;
+
+/* values for SASStatus field are at the top of this file */
+
+
+/****************************************************************************
+*  SAS IO Unit Control messages
+****************************************************************************/
+
+/* SAS IO Unit Control Request Message */
+typedef struct _MPI2_SAS_IOUNIT_CONTROL_REQUEST
+{
+    U8                      Operation;          /* 0x00 */
+    U8                      Reserved1;          /* 0x01 */
+    U8                      ChainOffset;        /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     DevHandle;          /* 0x04 */
+    U8                      IOCParameter;       /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved3;          /* 0x0A */
+    U16                     Reserved4;          /* 0x0C */
+    U8                      PhyNum;             /* 0x0E */
+    U8                      PrimFlags;          /* 0x0F */
+    U32                     Primitive;          /* 0x10 */
+    U8                      LookupMethod;       /* 0x14 */
+    U8                      Reserved5;          /* 0x15 */
+    U16                     SlotNumber;         /* 0x16 */
+    U64                     LookupAddress;      /* 0x18 */
+    U32                     IOCParameterValue;  /* 0x20 */
+    U32                     Reserved7;          /* 0x24 */
+    U32                     Reserved8;          /* 0x28 */
+} MPI2_SAS_IOUNIT_CONTROL_REQUEST,
+  MPI2_POINTER PTR_MPI2_SAS_IOUNIT_CONTROL_REQUEST,
+  Mpi2SasIoUnitControlRequest_t, MPI2_POINTER pMpi2SasIoUnitControlRequest_t;
+
+/* values for the Operation field */
+#define MPI2_SAS_OP_CLEAR_ALL_PERSISTENT        (0x02)
+#define MPI2_SAS_OP_PHY_LINK_RESET              (0x06)
+#define MPI2_SAS_OP_PHY_HARD_RESET              (0x07)
+#define MPI2_SAS_OP_PHY_CLEAR_ERROR_LOG         (0x08)
+#define MPI2_SAS_OP_SEND_PRIMITIVE              (0x0A)
+#define MPI2_SAS_OP_FORCE_FULL_DISCOVERY        (0x0B)
+#define MPI2_SAS_OP_TRANSMIT_PORT_SELECT_SIGNAL (0x0C)
+#define MPI2_SAS_OP_REMOVE_DEVICE               (0x0D)
+#define MPI2_SAS_OP_LOOKUP_MAPPING              (0x0E)
+#define MPI2_SAS_OP_SET_IOC_PARAMETER           (0x0F)
+#define MPI2_SAS_OP_PRODUCT_SPECIFIC_MIN        (0x80)
+
+/* values for the PrimFlags field */
+#define MPI2_SAS_PRIMFLAGS_SINGLE               (0x08)
+#define MPI2_SAS_PRIMFLAGS_TRIPLE               (0x02)
+#define MPI2_SAS_PRIMFLAGS_REDUNDANT            (0x01)
+
+/* values for the LookupMethod field */
+#define MPI2_SAS_LOOKUP_METHOD_SAS_ADDRESS          (0x01)
+#define MPI2_SAS_LOOKUP_METHOD_SAS_ENCLOSURE_SLOT   (0x02)
+#define MPI2_SAS_LOOKUP_METHOD_SAS_DEVICE_NAME      (0x03)
+
+
+/* SAS IO Unit Control Reply Message */
+typedef struct _MPI2_SAS_IOUNIT_CONTROL_REPLY
+{
+    U8                      Operation;          /* 0x00 */
+    U8                      Reserved1;          /* 0x01 */
+    U8                      MsgLength;          /* 0x02 */
+    U8                      Function;           /* 0x03 */
+    U16                     DevHandle;          /* 0x04 */
+    U8                      IOCParameter;       /* 0x06 */
+    U8                      MsgFlags;           /* 0x07 */
+    U8                      VP_ID;              /* 0x08 */
+    U8                      VF_ID;              /* 0x09 */
+    U16                     Reserved3;          /* 0x0A */
+    U16                     Reserved4;          /* 0x0C */
+    U16                     IOCStatus;          /* 0x0E */
+    U32                     IOCLogInfo;         /* 0x10 */
+} MPI2_SAS_IOUNIT_CONTROL_REPLY,
+  MPI2_POINTER PTR_MPI2_SAS_IOUNIT_CONTROL_REPLY,
+  Mpi2SasIoUnitControlReply_t, MPI2_POINTER pMpi2SasIoUnitControlReply_t;
+
+
+#endif
+
+
diff --git a/sys/dev/mps/mpi/mpi2_targ.h b/sys/dev/mps/mpi/mpi2_targ.h
new file mode 100644
index 00000000000..50f38d0c2b2
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_targ.h
@@ -0,0 +1,441 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2008 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_targ.h
+ *          Title:  MPI Target mode messages and structures
+ *  Creation Date:  September 8, 2006
+ *
+ *    mpi2_targ.h Version: 02.00.03
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  08-31-07  02.00.01  Added Command Buffer Data Location Address Space bits to
+ *                      BufferPostFlags field of CommandBufferPostBase Request.
+ *  02-29-08  02.00.02  Modified various names to make them 32-character unique.
+ *  10-02-08  02.00.03  Removed NextCmdBufferOffset from
+ *                      MPI2_TARGET_CMD_BUF_POST_BASE_REQUEST.
+ *                      Target Status Send Request only takes a single SGE for
+ *                      response data.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_TARG_H
+#define MPI2_TARG_H
+
+
+/******************************************************************************
+*
+*        SCSI Target Messages
+*
+*******************************************************************************/
+
+/****************************************************************************
+*  Target Command Buffer Post Base Request
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_CMD_BUF_POST_BASE_REQUEST
+{
+    U8                      BufferPostFlags;        /* 0x00 */
+    U8                      Reserved1;              /* 0x01 */
+    U8                      ChainOffset;            /* 0x02 */
+    U8                      Function;               /* 0x03 */
+    U16                     TotalCmdBuffers;        /* 0x04 */
+    U8                      Reserved;               /* 0x06 */
+    U8                      MsgFlags;               /* 0x07 */
+    U8                      VP_ID;                  /* 0x08 */
+    U8                      VF_ID;                  /* 0x09 */
+    U16                     Reserved2;              /* 0x0A */
+    U32                     Reserved3;              /* 0x0C */
+    U16                     CmdBufferLength;        /* 0x10 */
+    U16                     Reserved4;              /* 0x12 */
+    U32                     BaseAddressLow;         /* 0x14 */
+    U32                     BaseAddressHigh;        /* 0x18 */
+} MPI2_TARGET_CMD_BUF_POST_BASE_REQUEST,
+  MPI2_POINTER PTR_MPI2_TARGET_CMD_BUF_POST_BASE_REQUEST,
+  Mpi2TargetCmdBufferPostBaseRequest_t,
+  MPI2_POINTER pMpi2TargetCmdBufferPostBaseRequest_t;
+
+/* values for the BufferPostflags field */
+#define MPI2_CMD_BUF_POST_BASE_ADDRESS_SPACE_MASK            (0x0C)
+#define MPI2_CMD_BUF_POST_BASE_SYSTEM_ADDRESS_SPACE          (0x00)
+#define MPI2_CMD_BUF_POST_BASE_IOCDDR_ADDRESS_SPACE          (0x04)
+#define MPI2_CMD_BUF_POST_BASE_IOCPLB_ADDRESS_SPACE          (0x08)
+#define MPI2_CMD_BUF_POST_BASE_IOCPLBNTA_ADDRESS_SPACE       (0x0C)
+
+#define MPI2_CMD_BUF_POST_BASE_FLAGS_AUTO_POST_ALL           (0x01)
+
+
+/****************************************************************************
+*  Target Command Buffer Post List Request
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_CMD_BUF_POST_LIST_REQUEST
+{
+    U16                     Reserved;               /* 0x00 */
+    U8                      ChainOffset;            /* 0x02 */
+    U8                      Function;               /* 0x03 */
+    U16                     CmdBufferCount;         /* 0x04 */
+    U8                      Reserved1;              /* 0x06 */
+    U8                      MsgFlags;               /* 0x07 */
+    U8                      VP_ID;                  /* 0x08 */
+    U8                      VF_ID;                  /* 0x09 */
+    U16                     Reserved2;              /* 0x0A */
+    U32                     Reserved3;              /* 0x0C */
+    U16                     IoIndex[2];             /* 0x10 */
+} MPI2_TARGET_CMD_BUF_POST_LIST_REQUEST,
+  MPI2_POINTER PTR_MPI2_TARGET_CMD_BUF_POST_LIST_REQUEST,
+  Mpi2TargetCmdBufferPostListRequest_t,
+  MPI2_POINTER pMpi2TargetCmdBufferPostListRequest_t;
+
+/****************************************************************************
+*  Target Command Buffer Post Base List Reply
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_BUF_POST_BASE_LIST_REPLY
+{
+    U8                      Flags;                  /* 0x00 */
+    U8                      Reserved;               /* 0x01 */
+    U8                      MsgLength;              /* 0x02 */
+    U8                      Function;               /* 0x03 */
+    U16                     Reserved1;              /* 0x04 */
+    U8                      Reserved2;              /* 0x06 */
+    U8                      MsgFlags;               /* 0x07 */
+    U8                      VP_ID;                  /* 0x08 */
+    U8                      VF_ID;                  /* 0x09 */
+    U16                     Reserved3;              /* 0x0A */
+    U16                     Reserved4;              /* 0x0C */
+    U16                     IOCStatus;              /* 0x0E */
+    U32                     IOCLogInfo;             /* 0x10 */
+    U16                     IoIndex;                /* 0x14 */
+    U16                     Reserved5;              /* 0x16 */
+    U32                     Reserved6;              /* 0x18 */
+} MPI2_TARGET_BUF_POST_BASE_LIST_REPLY,
+  MPI2_POINTER PTR_MPI2_TARGET_BUF_POST_BASE_LIST_REPLY,
+  Mpi2TargetCmdBufferPostBaseListReply_t,
+  MPI2_POINTER pMpi2TargetCmdBufferPostBaseListReply_t;
+
+/* Flags defines */
+#define MPI2_CMD_BUF_POST_REPLY_IOINDEX_VALID       (0x01)
+
+
+/****************************************************************************
+*  Command Buffer Formats (with 16 byte CDB)
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_SSP_CMD_BUFFER
+{
+    U8      FrameType;                                  /* 0x00 */
+    U8      Reserved1;                                  /* 0x01 */
+    U16     InitiatorConnectionTag;                     /* 0x02 */
+    U32     HashedSourceSASAddress;                     /* 0x04 */
+    U16     Reserved2;                                  /* 0x08 */
+    U16     Flags;                                      /* 0x0A */
+    U32     Reserved3;                                  /* 0x0C */
+    U16     Tag;                                        /* 0x10 */
+    U16     TargetPortTransferTag;                      /* 0x12 */
+    U32     DataOffset;                                 /* 0x14 */
+    /* COMMAND information unit starts here */
+    U8      LogicalUnitNumber[8];                       /* 0x18 */
+    U8      Reserved4;                                  /* 0x20 */
+    U8      TaskAttribute; /* lower 3 bits */           /* 0x21 */
+    U8      Reserved5;                                  /* 0x22 */
+    U8      AdditionalCDBLength; /* upper 5 bits */     /* 0x23 */
+    U8      CDB[16];                                    /* 0x24 */
+    /* Additional CDB bytes extend past the CDB field */
+} MPI2_TARGET_SSP_CMD_BUFFER, MPI2_POINTER PTR_MPI2_TARGET_SSP_CMD_BUFFER,
+  Mpi2TargetSspCmdBuffer, MPI2_POINTER pMp2iTargetSspCmdBuffer;
+
+typedef struct _MPI2_TARGET_SSP_TASK_BUFFER
+{
+    U8      FrameType;                                  /* 0x00 */
+    U8      Reserved1;                                  /* 0x01 */
+    U16     InitiatorConnectionTag;                     /* 0x02 */
+    U32     HashedSourceSASAddress;                     /* 0x04 */
+    U16     Reserved2;                                  /* 0x08 */
+    U16     Flags;                                      /* 0x0A */
+    U32     Reserved3;                                  /* 0x0C */
+    U16     Tag;                                        /* 0x10 */
+    U16     TargetPortTransferTag;                      /* 0x12 */
+    U32     DataOffset;                                 /* 0x14 */
+    /* TASK information unit starts here */
+    U8      LogicalUnitNumber[8];                       /* 0x18 */
+    U16     Reserved4;                                  /* 0x20 */
+    U8      TaskManagementFunction;                     /* 0x22 */
+    U8      Reserved5;                                  /* 0x23 */
+    U16     ManagedTaskTag;                             /* 0x24 */
+    U16     Reserved6;                                  /* 0x26 */
+    U32     Reserved7;                                  /* 0x28 */
+    U32     Reserved8;                                  /* 0x2C */
+    U32     Reserved9;                                  /* 0x30 */
+} MPI2_TARGET_SSP_TASK_BUFFER, MPI2_POINTER PTR_MPI2_TARGET_SSP_TASK_BUFFER,
+  Mpi2TargetSspTaskBuffer, MPI2_POINTER pMpi2TargetSspTaskBuffer;
+
+/* mask and shift for HashedSourceSASAddress field */
+#define MPI2_TARGET_HASHED_SAS_ADDRESS_MASK     (0xFFFFFF00)
+#define MPI2_TARGET_HASHED_SAS_ADDRESS_SHIFT    (8)
+
+
+/****************************************************************************
+*   Target Assist Request
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_ASSIST_REQUEST
+{
+    U8                  Reserved1;                          /* 0x00 */
+    U8                  TargetAssistFlags;                  /* 0x01 */
+    U8                  ChainOffset;                        /* 0x02 */
+    U8                  Function;                           /* 0x03 */
+    U16                 QueueTag;                           /* 0x04 */
+    U8                  Reserved2;                          /* 0x06 */
+    U8                  MsgFlags;                           /* 0x07 */
+    U8                  VP_ID;                              /* 0x08 */
+    U8                  VF_ID;                              /* 0x09 */
+    U16                 Reserved3;                          /* 0x0A */
+    U16                 IoIndex;                            /* 0x0C */
+    U16                 InitiatorConnectionTag;             /* 0x0E */
+    U16                 SGLFlags;                           /* 0x10 */
+    U8                  SequenceNumber;                     /* 0x12 */
+    U8                  Reserved4;                          /* 0x13 */
+    U8                  SGLOffset0;                         /* 0x14 */
+    U8                  SGLOffset1;                         /* 0x15 */
+    U8                  SGLOffset2;                         /* 0x16 */
+    U8                  SGLOffset3;                         /* 0x17 */
+    U32                 SkipCount;                          /* 0x18 */
+    U32                 DataLength;                         /* 0x1C */
+    U32                 BidirectionalDataLength;            /* 0x20 */
+    U16                 IoFlags;                            /* 0x24 */
+    U16                 EEDPFlags;                          /* 0x26 */
+    U32                 EEDPBlockSize;                      /* 0x28 */
+    U32                 SecondaryReferenceTag;              /* 0x2C */
+    U16                 SecondaryApplicationTag;            /* 0x30 */
+    U16                 ApplicationTagTranslationMask;      /* 0x32 */
+    U32                 PrimaryReferenceTag;                /* 0x34 */
+    U16                 PrimaryApplicationTag;              /* 0x38 */
+    U16                 PrimaryApplicationTagMask;          /* 0x3A */
+    U32                 RelativeOffset;                     /* 0x3C */
+    U32                 Reserved5;                          /* 0x40 */
+    U32                 Reserved6;                          /* 0x44 */
+    U32                 Reserved7;                          /* 0x48 */
+    U32                 Reserved8;                          /* 0x4C */
+    MPI2_SGE_IO_UNION   SGL[1];                             /* 0x50 */
+} MPI2_TARGET_ASSIST_REQUEST, MPI2_POINTER PTR_MPI2_TARGET_ASSIST_REQUEST,
+  Mpi2TargetAssistRequest_t, MPI2_POINTER pMpi2TargetAssistRequest_t;
+
+/* Target Assist TargetAssistFlags bits */
+
+#define MPI2_TARGET_ASSIST_FLAGS_REPOST_CMD_BUFFER      (0x80)
+#define MPI2_TARGET_ASSIST_FLAGS_TLR                    (0x10)
+#define MPI2_TARGET_ASSIST_FLAGS_RETRANSMIT             (0x04)
+#define MPI2_TARGET_ASSIST_FLAGS_AUTO_STATUS            (0x02)
+#define MPI2_TARGET_ASSIST_FLAGS_DATA_DIRECTION         (0x01)
+
+/* Target Assist SGLFlags bits */
+
+/* base values for Data Location Address Space */
+#define MPI2_TARGET_ASSIST_SGLFLAGS_ADDR_MASK           (0x0C)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_SYSTEM_ADDR         (0x00)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_IOCDDR_ADDR         (0x04)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_IOCPLB_ADDR         (0x08)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_PLBNTA_ADDR         (0x0C)
+
+/* base values for Type */
+#define MPI2_TARGET_ASSIST_SGLFLAGS_TYPE_MASK           (0x03)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_MPI_TYPE            (0x00)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_32IEEE_TYPE         (0x01)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_64IEEE_TYPE         (0x02)
+
+/* shift values for each sub-field */
+#define MPI2_TARGET_ASSIST_SGLFLAGS_SGL3_SHIFT          (12)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_SGL2_SHIFT          (8)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_SGL1_SHIFT          (4)
+#define MPI2_TARGET_ASSIST_SGLFLAGS_SGL0_SHIFT          (0)
+
+/* Target Assist IoFlags bits */
+
+#define MPI2_TARGET_ASSIST_IOFLAGS_BIDIRECTIONAL        (0x0800)
+#define MPI2_TARGET_ASSIST_IOFLAGS_MULTICAST            (0x0400)
+#define MPI2_TARGET_ASSIST_IOFLAGS_RECEIVE_FIRST        (0x0200)
+
+/* Target Assist EEDPFlags bits */
+
+#define MPI2_TA_EEDPFLAGS_INC_PRI_REFTAG            (0x8000)
+#define MPI2_TA_EEDPFLAGS_INC_SEC_REFTAG            (0x4000)
+#define MPI2_TA_EEDPFLAGS_INC_PRI_APPTAG            (0x2000)
+#define MPI2_TA_EEDPFLAGS_INC_SEC_APPTAG            (0x1000)
+
+#define MPI2_TA_EEDPFLAGS_CHECK_REFTAG              (0x0400)
+#define MPI2_TA_EEDPFLAGS_CHECK_APPTAG              (0x0200)
+#define MPI2_TA_EEDPFLAGS_CHECK_GUARD               (0x0100)
+
+#define MPI2_TA_EEDPFLAGS_PASSTHRU_REFTAG           (0x0008)
+
+#define MPI2_TA_EEDPFLAGS_MASK_OP                   (0x0007)
+#define MPI2_TA_EEDPFLAGS_NOOP_OP                   (0x0000)
+#define MPI2_TA_EEDPFLAGS_CHECK_OP                  (0x0001)
+#define MPI2_TA_EEDPFLAGS_STRIP_OP                  (0x0002)
+#define MPI2_TA_EEDPFLAGS_CHECK_REMOVE_OP           (0x0003)
+#define MPI2_TA_EEDPFLAGS_INSERT_OP                 (0x0004)
+#define MPI2_TA_EEDPFLAGS_REPLACE_OP                (0x0006)
+#define MPI2_TA_EEDPFLAGS_CHECK_REGEN_OP            (0x0007)
+
+
+/****************************************************************************
+*  Target Status Send Request
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_STATUS_SEND_REQUEST
+{
+    U8                      Reserved1;                  /* 0x00 */
+    U8                      StatusFlags;                /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     QueueTag;                   /* 0x04 */
+    U8                      Reserved2;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved3;                  /* 0x0A */
+    U16                     IoIndex;                    /* 0x0C */
+    U16                     InitiatorConnectionTag;     /* 0x0E */
+    U16                     SGLFlags;                   /* 0x10 */
+    U16                     Reserved4;                  /* 0x12 */
+    U8                      SGLOffset0;                 /* 0x14 */
+    U8                      Reserved5;                  /* 0x15 */
+    U16                     Reserved6;                  /* 0x16 */
+    U32                     Reserved7;                  /* 0x18 */
+    U32                     Reserved8;                  /* 0x1C */
+    MPI2_SIMPLE_SGE_UNION   StatusDataSGE;              /* 0x20 */
+} MPI2_TARGET_STATUS_SEND_REQUEST,
+  MPI2_POINTER PTR_MPI2_TARGET_STATUS_SEND_REQUEST,
+  Mpi2TargetStatusSendRequest_t, MPI2_POINTER pMpi2TargetStatusSendRequest_t;
+
+/* Target Status Send StatusFlags bits */
+
+#define MPI2_TSS_FLAGS_REPOST_CMD_BUFFER            (0x80)
+#define MPI2_TSS_FLAGS_RETRANSMIT                   (0x04)
+#define MPI2_TSS_FLAGS_AUTO_GOOD_STATUS             (0x01)
+
+/* Target Status Send SGLFlags bits */
+/* Data Location Address Space */
+#define MPI2_TSS_SGLFLAGS_ADDR_MASK                 (0x0C)
+#define MPI2_TSS_SGLFLAGS_SYSTEM_ADDR               (0x00)
+#define MPI2_TSS_SGLFLAGS_IOCDDR_ADDR               (0x04)
+#define MPI2_TSS_SGLFLAGS_IOCPLB_ADDR               (0x08)
+#define MPI2_TSS_SGLFLAGS_IOCPLBNTA_ADDR            (0x0C)
+/* Type */
+#define MPI2_TSS_SGLFLAGS_TYPE_MASK                 (0x03)
+#define MPI2_TSS_SGLFLAGS_MPI_TYPE                  (0x00)
+#define MPI2_TSS_SGLFLAGS_IEEE32_TYPE               (0x01)
+#define MPI2_TSS_SGLFLAGS_IEEE64_TYPE               (0x02)
+
+
+
+/*
+ * NOTE: The SSP status IU is big-endian. When used on a little-endian system,
+ * this structure properly orders the bytes.
+ */
+typedef struct _MPI2_TARGET_SSP_RSP_IU
+{
+    U32     Reserved0[6]; /* reserved for SSP header */ /* 0x00 */
+    /* start of RESPONSE information unit */
+    U32     Reserved1;                                  /* 0x18 */
+    U32     Reserved2;                                  /* 0x1C */
+    U16     Reserved3;                                  /* 0x20 */
+    U8      DataPres; /* lower 2 bits */                /* 0x22 */
+    U8      Status;                                     /* 0x23 */
+    U32     Reserved4;                                  /* 0x24 */
+    U32     SenseDataLength;                            /* 0x28 */
+    U32     ResponseDataLength;                         /* 0x2C */
+    U8      ResponseSenseData[4];                       /* 0x30 */
+} MPI2_TARGET_SSP_RSP_IU, MPI2_POINTER PTR_MPI2_TARGET_SSP_RSP_IU,
+  Mpi2TargetSspRspIu_t, MPI2_POINTER pMpi2TargetSspRspIu_t;
+
+
+/****************************************************************************
+*  Target Standard Reply - used with Target Assist or Target Status Send
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_STANDARD_REPLY
+{
+    U16                     Reserved;                   /* 0x00 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved1;                  /* 0x04 */
+    U8                      Reserved2;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved3;                  /* 0x0A */
+    U16                     Reserved4;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    U16                     IoIndex;                    /* 0x14 */
+    U16                     Reserved5;                  /* 0x16 */
+    U32                     TransferCount;              /* 0x18 */
+    U32                     BidirectionalTransferCount; /* 0x1C */
+} MPI2_TARGET_STANDARD_REPLY, MPI2_POINTER PTR_MPI2_TARGET_STANDARD_REPLY,
+  Mpi2TargetErrorReply_t, MPI2_POINTER pMpi2TargetErrorReply_t;
+
+
+/****************************************************************************
+*  Target Mode Abort Request
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_MODE_ABORT_REQUEST
+{
+    U8                      AbortType;                  /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     IoIndexToAbort;             /* 0x0C */
+    U16                     Reserved6;                  /* 0x0E */
+    U32                     MidToAbort;                 /* 0x10 */
+} MPI2_TARGET_MODE_ABORT, MPI2_POINTER PTR_MPI2_TARGET_MODE_ABORT,
+  Mpi2TargetModeAbort_t, MPI2_POINTER pMpi2TargetModeAbort_t;
+
+/* Target Mode Abort AbortType values */
+
+#define MPI2_TARGET_MODE_ABORT_ALL_CMD_BUFFERS      (0x00)
+#define MPI2_TARGET_MODE_ABORT_ALL_IO               (0x01)
+#define MPI2_TARGET_MODE_ABORT_EXACT_IO             (0x02)
+#define MPI2_TARGET_MODE_ABORT_EXACT_IO_REQUEST     (0x03)
+#define MPI2_TARGET_MODE_ABORT_IO_REQUEST_AND_IO    (0x04)
+
+
+/****************************************************************************
+*  Target Mode Abort Reply
+****************************************************************************/
+
+typedef struct _MPI2_TARGET_MODE_ABORT_REPLY
+{
+    U16                     Reserved;                   /* 0x00 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved1;                  /* 0x04 */
+    U8                      Reserved2;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved3;                  /* 0x0A */
+    U16                     Reserved4;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    U32                     AbortCount;                 /* 0x14 */
+} MPI2_TARGET_MODE_ABORT_REPLY, MPI2_POINTER PTR_MPI2_TARGET_MODE_ABORT_REPLY,
+  Mpi2TargetModeAbortReply_t, MPI2_POINTER pMpi2TargetModeAbortReply_t;
+
+
+#endif
+
diff --git a/sys/dev/mps/mpi/mpi2_tool.h b/sys/dev/mps/mpi/mpi2_tool.h
new file mode 100644
index 00000000000..f782507302d
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_tool.h
@@ -0,0 +1,391 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2009 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_tool.h
+ *          Title:  MPI diagnostic tool structures and definitions
+ *  Creation Date:  March 26, 2007
+ *
+ *    mpi2_tool.h Version:  02.00.04
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  12-18-07  02.00.01  Added Diagnostic Buffer Post and Diagnostic Release
+ *                      structures and defines.
+ *  02-29-08  02.00.02  Modified various names to make them 32-character unique.
+ *  05-06-09  02.00.03  Added ISTWI Read Write Tool and Diagnostic CLI Tool.
+ *  07-30-09  02.00.04  Added ExtendedType field to DiagnosticBufferPost request
+ *                      and reply messages.
+ *                      Added MPI2_DIAG_BUF_TYPE_EXTENDED.
+ *                      Incremented MPI2_DIAG_BUF_TYPE_COUNT.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_TOOL_H
+#define MPI2_TOOL_H
+
+/*****************************************************************************
+*
+*               Toolbox Messages
+*
+*****************************************************************************/
+
+/* defines for the Tools */
+#define MPI2_TOOLBOX_CLEAN_TOOL                     (0x00)
+#define MPI2_TOOLBOX_MEMORY_MOVE_TOOL               (0x01)
+#define MPI2_TOOLBOX_ISTWI_READ_WRITE_TOOL          (0x03)
+#define MPI2_TOOLBOX_BEACON_TOOL                    (0x05)
+#define MPI2_TOOLBOX_DIAGNOSTIC_CLI_TOOL            (0x06)
+
+
+/****************************************************************************
+*  Toolbox reply
+****************************************************************************/
+
+typedef struct _MPI2_TOOLBOX_REPLY
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+} MPI2_TOOLBOX_REPLY, MPI2_POINTER PTR_MPI2_TOOLBOX_REPLY,
+  Mpi2ToolboxReply_t, MPI2_POINTER pMpi2ToolboxReply_t;
+
+
+/****************************************************************************
+*  Toolbox Clean Tool request
+****************************************************************************/
+
+typedef struct _MPI2_TOOLBOX_CLEAN_REQUEST
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U32                     Flags;                      /* 0x0C */
+   } MPI2_TOOLBOX_CLEAN_REQUEST, MPI2_POINTER PTR_MPI2_TOOLBOX_CLEAN_REQUEST,
+  Mpi2ToolboxCleanRequest_t, MPI2_POINTER pMpi2ToolboxCleanRequest_t;
+
+/* values for the Flags field */
+#define MPI2_TOOLBOX_CLEAN_BOOT_SERVICES            (0x80000000)
+#define MPI2_TOOLBOX_CLEAN_PERSIST_MANUFACT_PAGES   (0x40000000)
+#define MPI2_TOOLBOX_CLEAN_OTHER_PERSIST_PAGES      (0x20000000)
+#define MPI2_TOOLBOX_CLEAN_FW_CURRENT               (0x10000000)
+#define MPI2_TOOLBOX_CLEAN_FW_BACKUP                (0x08000000)
+#define MPI2_TOOLBOX_CLEAN_MEGARAID                 (0x02000000)
+#define MPI2_TOOLBOX_CLEAN_INITIALIZATION           (0x01000000)
+#define MPI2_TOOLBOX_CLEAN_FLASH                    (0x00000004)
+#define MPI2_TOOLBOX_CLEAN_SEEPROM                  (0x00000002)
+#define MPI2_TOOLBOX_CLEAN_NVSRAM                   (0x00000001)
+
+
+/****************************************************************************
+*  Toolbox Memory Move request
+****************************************************************************/
+
+typedef struct _MPI2_TOOLBOX_MEM_MOVE_REQUEST
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    MPI2_SGE_SIMPLE_UNION   SGL;                        /* 0x0C */
+} MPI2_TOOLBOX_MEM_MOVE_REQUEST, MPI2_POINTER PTR_MPI2_TOOLBOX_MEM_MOVE_REQUEST,
+  Mpi2ToolboxMemMoveRequest_t, MPI2_POINTER pMpi2ToolboxMemMoveRequest_t;
+
+
+/****************************************************************************
+*  Toolbox ISTWI Read Write Tool
+****************************************************************************/
+
+/* Toolbox ISTWI Read Write Tool request message */
+typedef struct _MPI2_TOOLBOX_ISTWI_READ_WRITE_REQUEST
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U32                     Reserved5;                  /* 0x0C */
+    U32                     Reserved6;                  /* 0x10 */
+    U8                      DevIndex;                   /* 0x14 */
+    U8                      Action;                     /* 0x15 */
+    U8                      SGLFlags;                   /* 0x16 */
+    U8                      Reserved7;                  /* 0x17 */
+    U16                     TxDataLength;               /* 0x18 */
+    U16                     RxDataLength;               /* 0x1A */
+    U32                     Reserved8;                  /* 0x1C */
+    U32                     Reserved9;                  /* 0x20 */
+    U32                     Reserved10;                 /* 0x24 */
+    U32                     Reserved11;                 /* 0x28 */
+    U32                     Reserved12;                 /* 0x2C */
+    MPI2_SGE_SIMPLE_UNION   SGL;                        /* 0x30 */
+} MPI2_TOOLBOX_ISTWI_READ_WRITE_REQUEST,
+  MPI2_POINTER PTR_MPI2_TOOLBOX_ISTWI_READ_WRITE_REQUEST,
+  Mpi2ToolboxIstwiReadWriteRequest_t,
+  MPI2_POINTER pMpi2ToolboxIstwiReadWriteRequest_t;
+
+/* values for the Action field */
+#define MPI2_TOOL_ISTWI_ACTION_READ_DATA            (0x01)
+#define MPI2_TOOL_ISTWI_ACTION_WRITE_DATA           (0x02)
+#define MPI2_TOOL_ISTWI_ACTION_SEQUENCE             (0x03)
+#define MPI2_TOOL_ISTWI_ACTION_RESERVE_BUS          (0x10)
+#define MPI2_TOOL_ISTWI_ACTION_RELEASE_BUS          (0x11)
+#define MPI2_TOOL_ISTWI_ACTION_RESET                (0x12)
+
+/* values for SGLFlags field are in the SGL section of mpi2.h */
+
+
+/* Toolbox ISTWI Read Write Tool reply message */
+typedef struct _MPI2_TOOLBOX_ISTWI_REPLY
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    U8                      DevIndex;                   /* 0x14 */
+    U8                      Action;                     /* 0x15 */
+    U8                      IstwiStatus;                /* 0x16 */
+    U8                      Reserved6;                  /* 0x17 */
+    U16                     TxDataCount;                /* 0x18 */
+    U16                     RxDataCount;                /* 0x1A */
+} MPI2_TOOLBOX_ISTWI_REPLY, MPI2_POINTER PTR_MPI2_TOOLBOX_ISTWI_REPLY,
+  Mpi2ToolboxIstwiReply_t, MPI2_POINTER pMpi2ToolboxIstwiReply_t;
+
+
+/****************************************************************************
+*  Toolbox Beacon Tool request
+****************************************************************************/
+
+typedef struct _MPI2_TOOLBOX_BEACON_REQUEST
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U8                      Reserved5;                  /* 0x0C */
+    U8                      PhysicalPort;               /* 0x0D */
+    U8                      Reserved6;                  /* 0x0E */
+    U8                      Flags;                      /* 0x0F */
+} MPI2_TOOLBOX_BEACON_REQUEST, MPI2_POINTER PTR_MPI2_TOOLBOX_BEACON_REQUEST,
+  Mpi2ToolboxBeaconRequest_t, MPI2_POINTER pMpi2ToolboxBeaconRequest_t;
+
+/* values for the Flags field */
+#define MPI2_TOOLBOX_FLAGS_BEACONMODE_OFF       (0x00)
+#define MPI2_TOOLBOX_FLAGS_BEACONMODE_ON        (0x01)
+
+
+/****************************************************************************
+*  Toolbox Diagnostic CLI Tool
+****************************************************************************/
+
+#define MPI2_TOOLBOX_DIAG_CLI_CMD_LENGTH    (0x5C)
+
+/* Toolbox Diagnostic CLI Tool request message */
+typedef struct _MPI2_TOOLBOX_DIAGNOSTIC_CLI_REQUEST
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U8                      SGLFlags;                   /* 0x0C */
+    U8                      Reserved5;                  /* 0x0D */
+    U16                     Reserved6;                  /* 0x0E */
+    U32                     DataLength;                 /* 0x10 */
+    U8                      DiagnosticCliCommand[MPI2_TOOLBOX_DIAG_CLI_CMD_LENGTH]; /* 0x14 */
+    MPI2_SGE_SIMPLE_UNION   SGL;                        /* 0x70 */
+} MPI2_TOOLBOX_DIAGNOSTIC_CLI_REQUEST,
+  MPI2_POINTER PTR_MPI2_TOOLBOX_DIAGNOSTIC_CLI_REQUEST,
+  Mpi2ToolboxDiagnosticCliRequest_t,
+  MPI2_POINTER pMpi2ToolboxDiagnosticCliRequest_t;
+
+/* values for SGLFlags field are in the SGL section of mpi2.h */
+
+
+/* Toolbox Diagnostic CLI Tool reply message */
+typedef struct _MPI2_TOOLBOX_DIAGNOSTIC_CLI_REPLY
+{
+    U8                      Tool;                       /* 0x00 */
+    U8                      Reserved1;                  /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    U32                     ReturnedDataLength;         /* 0x14 */
+} MPI2_TOOLBOX_DIAGNOSTIC_CLI_REPLY,
+  MPI2_POINTER PTR_MPI2_TOOLBOX_DIAG_CLI_REPLY,
+  Mpi2ToolboxDiagnosticCliReply_t,
+  MPI2_POINTER pMpi2ToolboxDiagnosticCliReply_t;
+
+
+/*****************************************************************************
+*
+*       Diagnostic Buffer Messages
+*
+*****************************************************************************/
+
+
+/****************************************************************************
+*  Diagnostic Buffer Post request
+****************************************************************************/
+
+typedef struct _MPI2_DIAG_BUFFER_POST_REQUEST
+{
+    U8                      ExtendedType;               /* 0x00 */
+    U8                      BufferType;                 /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U64                     BufferAddress;              /* 0x0C */
+    U32                     BufferLength;               /* 0x14 */
+    U32                     Reserved5;                  /* 0x18 */
+    U32                     Reserved6;                  /* 0x1C */
+    U32                     Flags;                      /* 0x20 */
+    U32                     ProductSpecific[23];        /* 0x24 */
+} MPI2_DIAG_BUFFER_POST_REQUEST, MPI2_POINTER PTR_MPI2_DIAG_BUFFER_POST_REQUEST,
+  Mpi2DiagBufferPostRequest_t, MPI2_POINTER pMpi2DiagBufferPostRequest_t;
+
+/* values for the ExtendedType field */
+#define MPI2_DIAG_EXTENDED_TYPE_UTILIZATION         (0x02)
+
+/* values for the BufferType field */
+#define MPI2_DIAG_BUF_TYPE_TRACE                    (0x00)
+#define MPI2_DIAG_BUF_TYPE_SNAPSHOT                 (0x01)
+#define MPI2_DIAG_BUF_TYPE_EXTENDED                 (0x02)
+/* count of the number of buffer types */
+#define MPI2_DIAG_BUF_TYPE_COUNT                    (0x03)
+
+
+/****************************************************************************
+*  Diagnostic Buffer Post reply
+****************************************************************************/
+
+typedef struct _MPI2_DIAG_BUFFER_POST_REPLY
+{
+    U8                      ExtendedType;               /* 0x00 */
+    U8                      BufferType;                 /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+    U32                     TransferLength;             /* 0x14 */
+} MPI2_DIAG_BUFFER_POST_REPLY, MPI2_POINTER PTR_MPI2_DIAG_BUFFER_POST_REPLY,
+  Mpi2DiagBufferPostReply_t, MPI2_POINTER pMpi2DiagBufferPostReply_t;
+
+
+/****************************************************************************
+*  Diagnostic Release request
+****************************************************************************/
+
+typedef struct _MPI2_DIAG_RELEASE_REQUEST
+{
+    U8                      Reserved1;                  /* 0x00 */
+    U8                      BufferType;                 /* 0x01 */
+    U8                      ChainOffset;                /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+} MPI2_DIAG_RELEASE_REQUEST, MPI2_POINTER PTR_MPI2_DIAG_RELEASE_REQUEST,
+  Mpi2DiagReleaseRequest_t, MPI2_POINTER pMpi2DiagReleaseRequest_t;
+
+
+/****************************************************************************
+*  Diagnostic Buffer Post reply
+****************************************************************************/
+
+typedef struct _MPI2_DIAG_RELEASE_REPLY
+{
+    U8                      Reserved1;                  /* 0x00 */
+    U8                      BufferType;                 /* 0x01 */
+    U8                      MsgLength;                  /* 0x02 */
+    U8                      Function;                   /* 0x03 */
+    U16                     Reserved2;                  /* 0x04 */
+    U8                      Reserved3;                  /* 0x06 */
+    U8                      MsgFlags;                   /* 0x07 */
+    U8                      VP_ID;                      /* 0x08 */
+    U8                      VF_ID;                      /* 0x09 */
+    U16                     Reserved4;                  /* 0x0A */
+    U16                     Reserved5;                  /* 0x0C */
+    U16                     IOCStatus;                  /* 0x0E */
+    U32                     IOCLogInfo;                 /* 0x10 */
+} MPI2_DIAG_RELEASE_REPLY, MPI2_POINTER PTR_MPI2_DIAG_RELEASE_REPLY,
+  Mpi2DiagReleaseReply_t, MPI2_POINTER pMpi2DiagReleaseReply_t;
+
+
+#endif
+
diff --git a/sys/dev/mps/mpi/mpi2_type.h b/sys/dev/mps/mpi/mpi2_type.h
new file mode 100644
index 00000000000..9effe68e28c
--- /dev/null
+++ b/sys/dev/mps/mpi/mpi2_type.h
@@ -0,0 +1,99 @@
+/* $FreeBSD$ */
+/*
+ *  Copyright (c) 2000-2007 LSI Corporation.
+ *
+ *
+ *           Name:  mpi2_type.h
+ *          Title:  MPI basic type definitions
+ *  Creation Date:  August 16, 2006
+ *
+ *    mpi2_type.h Version:  02.00.00
+ *
+ *  Version History
+ *  ---------------
+ *
+ *  Date      Version   Description
+ *  --------  --------  ------------------------------------------------------
+ *  04-30-07  02.00.00  Corresponds to Fusion-MPT MPI Specification Rev A.
+ *  --------------------------------------------------------------------------
+ */
+
+#ifndef MPI2_TYPE_H
+#define MPI2_TYPE_H
+
+
+/*******************************************************************************
+ * Define MPI2_POINTER if it hasn't already been defined. By default
+ * MPI2_POINTER is defined to be a near pointer. MPI2_POINTER can be defined as
+ * a far pointer by defining MPI2_POINTER as "far *" before this header file is
+ * included.
+ */
+#ifndef MPI2_POINTER
+#define MPI2_POINTER     *
+#endif
+
+/* the basic types may have already been included by mpi_type.h */
+#ifndef MPI_TYPE_H
+/*****************************************************************************
+*
+*               Basic Types
+*
+*****************************************************************************/
+
+typedef signed   char   S8;
+typedef unsigned char   U8;
+typedef signed   short  S16;
+typedef unsigned short  U16;
+
+#ifdef	__FreeBSD__
+
+typedef int32_t  S32;
+typedef uint32_t U32;
+
+#else
+
+#if defined(unix) || defined(__arm) || defined(ALPHA) || defined(__PPC__) || defined(__ppc)
+
+    typedef signed   int   S32;
+    typedef unsigned int   U32;
+
+#else
+
+    typedef signed   long  S32;
+    typedef unsigned long  U32;
+
+#endif
+#endif
+
+typedef struct _S64
+{
+    U32          Low;
+    S32          High;
+} S64;
+
+typedef struct _U64
+{
+    U32          Low;
+    U32          High;
+} U64;
+
+
+/*****************************************************************************
+*
+*               Pointer Types
+*
+*****************************************************************************/
+
+typedef S8      *PS8;
+typedef U8      *PU8;
+typedef S16     *PS16;
+typedef U16     *PU16;
+typedef S32     *PS32;
+typedef U32     *PU32;
+typedef S64     *PS64;
+typedef U64     *PU64;
+
+#endif
+
+#endif
+
diff --git a/sys/dev/mps/mps.c b/sys/dev/mps/mps.c
new file mode 100644
index 00000000000..d0129e95edf
--- /dev/null
+++ b/sys/dev/mps/mps.c
@@ -0,0 +1,1605 @@
+/*-
+ * Copyright (c) 2009 Yahoo! Inc.
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+/* Communications core for LSI MPT2 */
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+static void mps_startup(void *arg);
+static void mps_startup_complete(struct mps_softc *sc, struct mps_command *cm);
+static int mps_send_iocinit(struct mps_softc *sc);
+static int mps_attach_log(struct mps_softc *sc);
+static void mps_dispatch_event(struct mps_softc *sc, uintptr_t data, MPI2_EVENT_NOTIFICATION_REPLY *reply);
+static void mps_config_complete(struct mps_softc *sc, struct mps_command *cm);
+static void mps_periodic(void *);
+
+SYSCTL_NODE(_hw, OID_AUTO, mps, CTLFLAG_RD, 0, "MPS Driver Parameters");
+
+MALLOC_DEFINE(M_MPT2, "mps", "mpt2 driver memory");
+
+/*
+ * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
+ * any state and back to its initialization state machine.
+ */
+static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
+
+static int
+mps_hard_reset(struct mps_softc *sc)
+{
+	uint32_t reg;
+	int i, error, tries = 0;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	/* Clear any pending interrupts */
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+
+	/* Push the magic sequence */
+	error = ETIMEDOUT;
+	while (tries++ < 20) {
+		for (i = 0; i < sizeof(mpt2_reset_magic); i++)
+			mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
+			    mpt2_reset_magic[i]);
+
+		DELAY(100 * 1000);
+
+		reg = mps_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
+		if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
+			error = 0;
+			break;
+		}
+	}
+	if (error)
+		return (error);
+
+	/* Send the actual reset.  XXX need to refresh the reg? */
+	mps_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET,
+	    reg | MPI2_DIAG_RESET_ADAPTER);
+
+	/* Wait up to 300 seconds in 50ms intervals */
+	error = ETIMEDOUT;
+	for (i = 0; i < 60000; i++) {
+		DELAY(50000);
+		reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
+		if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
+			error = 0;
+			break;
+		}
+	}
+	if (error)
+		return (error);
+
+	mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
+
+	return (0);
+}
+
+static int
+mps_soft_reset(struct mps_softc *sc)
+{
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
+	    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
+	    MPI2_DOORBELL_FUNCTION_SHIFT);
+	DELAY(50000);
+
+	return (0);
+}
+
+static int
+mps_transition_ready(struct mps_softc *sc)
+{
+	uint32_t reg, state;
+	int error, tries = 0;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	error = 0;
+	while (tries++ < 5) {
+		reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
+		mps_dprint(sc, MPS_INFO, "Doorbell= 0x%x\n", reg);
+
+		/*
+		 * Ensure the IOC is ready to talk.  If it's not, try
+		 * resetting it.
+		 */
+		if (reg & MPI2_DOORBELL_USED) {
+			mps_hard_reset(sc);
+			DELAY(50000);
+			continue;
+		}
+
+		/* Is the adapter owned by another peer? */
+		if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
+		    (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
+			device_printf(sc->mps_dev, "IOC is under the control "
+			    "of another peer host, aborting initialization.\n");
+			return (ENXIO);
+		}
+		
+		state = reg & MPI2_IOC_STATE_MASK;
+		if (state == MPI2_IOC_STATE_READY) {
+			/* Ready to go! */
+			error = 0;
+			break;
+		} else if (state == MPI2_IOC_STATE_FAULT) {
+			mps_dprint(sc, MPS_INFO, "IOC in fault state 0x%x\n",
+			    state & MPI2_DOORBELL_FAULT_CODE_MASK);
+			mps_hard_reset(sc);
+		} else if (state == MPI2_IOC_STATE_OPERATIONAL) {
+			/* Need to take ownership */
+			mps_soft_reset(sc);
+		} else if (state == MPI2_IOC_STATE_RESET) {
+			/* Wait a bit, IOC might be in transition */
+			mps_dprint(sc, MPS_FAULT,
+			    "IOC in unexpected reset state\n");
+		} else {
+			mps_dprint(sc, MPS_FAULT,
+			    "IOC in unknown state 0x%x\n", state);
+			error = EINVAL;
+			break;
+		}
+	
+		/* Wait 50ms for things to settle down. */
+		DELAY(50000);
+	}
+
+	if (error)
+		device_printf(sc->mps_dev, "Cannot transition IOC to ready\n");
+
+	return (error);
+}
+
+static int
+mps_transition_operational(struct mps_softc *sc)
+{
+	uint32_t reg, state;
+	int error;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	error = 0;
+	reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
+	mps_dprint(sc, MPS_INFO, "Doorbell= 0x%x\n", reg);
+
+	state = reg & MPI2_IOC_STATE_MASK;
+	if (state != MPI2_IOC_STATE_READY) {
+		if ((error = mps_transition_ready(sc)) != 0)
+			return (error);
+	}
+
+	error = mps_send_iocinit(sc);
+	return (error);
+}
+
+/* Wait for the chip to ACK a word that we've put into its FIFO */
+static int
+mps_wait_db_ack(struct mps_softc *sc)
+{
+	int retry;
+
+	for (retry = 0; retry < MPS_DB_MAX_WAIT; retry++) {
+		if ((mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
+		    MPI2_HIS_SYS2IOC_DB_STATUS) == 0)
+			return (0);
+		DELAY(2000);
+	}
+	return (ETIMEDOUT);
+}
+
+/* Wait for the chip to signal that the next word in its FIFO can be fetched */
+static int
+mps_wait_db_int(struct mps_softc *sc)
+{
+	int retry;
+
+	for (retry = 0; retry < MPS_DB_MAX_WAIT; retry++) {
+		if ((mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
+		    MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
+			return (0);
+		DELAY(2000);
+	}
+	return (ETIMEDOUT);
+}
+
+/* Step through the synchronous command state machine, i.e. "Doorbell mode" */
+static int
+mps_request_sync(struct mps_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
+    int req_sz, int reply_sz, int timeout)
+{
+	uint32_t *data32;
+	uint16_t *data16;
+	int i, count, ioc_sz, residual;
+
+	/* Step 1 */
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+
+	/* Step 2 */
+	if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
+		return (EBUSY);
+
+	/* Step 3
+	 * Announce that a message is coming through the doorbell.  Messages
+	 * are pushed at 32bit words, so round up if needed.
+	 */
+	count = (req_sz + 3) / 4;
+	mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
+	    (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
+	    (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
+
+	/* Step 4 */
+	if (mps_wait_db_int(sc) ||
+	    (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
+		mps_dprint(sc, MPS_FAULT, "Doorbell failed to activate\n");
+		return (ENXIO);
+	}
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+	if (mps_wait_db_ack(sc) != 0) {
+		mps_dprint(sc, MPS_FAULT, "Doorbell handshake failed\n");
+		return (ENXIO);
+	}
+
+	/* Step 5 */
+	/* Clock out the message data synchronously in 32-bit dwords*/
+	data32 = (uint32_t *)req;
+	for (i = 0; i < count; i++) {
+		mps_regwrite(sc, MPI2_DOORBELL_OFFSET, data32[i]);
+		if (mps_wait_db_ack(sc) != 0) {
+			mps_dprint(sc, MPS_FAULT,
+			    "Timeout while writing doorbell\n");
+			return (ENXIO);
+		}
+	}
+
+	/* Step 6 */
+	/* Clock in the reply in 16-bit words.  The total length of the
+	 * message is always in the 4th byte, so clock out the first 2 words
+	 * manually, then loop the rest.
+	 */
+	data16 = (uint16_t *)reply;
+	if (mps_wait_db_int(sc) != 0) {
+		mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 0\n");
+		return (ENXIO);
+	}
+	data16[0] =
+	    mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+	if (mps_wait_db_int(sc) != 0) {
+		mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 1\n");
+		return (ENXIO);
+	}
+	data16[1] =
+	    mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+
+	/* Number of 32bit words in the message */
+	ioc_sz = reply->MsgLength;
+
+	/*
+	 * Figure out how many 16bit words to clock in without overrunning.
+	 * The precision loss with dividing reply_sz can safely be
+	 * ignored because the messages can only be multiples of 32bits.
+	 */
+	residual = 0;
+	count = MIN((reply_sz / 4), ioc_sz) * 2;
+	if (count < ioc_sz * 2) {
+		residual = ioc_sz * 2 - count;
+		mps_dprint(sc, MPS_FAULT, "Driver error, throwing away %d "
+		    "residual message words\n", residual);
+	}
+
+	for (i = 2; i < count; i++) {
+		if (mps_wait_db_int(sc) != 0) {
+			mps_dprint(sc, MPS_FAULT,
+			    "Timeout reading doorbell %d\n", i);
+			return (ENXIO);
+		}
+		data16[i] = mps_regread(sc, MPI2_DOORBELL_OFFSET) &
+		    MPI2_DOORBELL_DATA_MASK;
+		mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+	}
+
+	/*
+	 * Pull out residual words that won't fit into the provided buffer.
+	 * This keeps the chip from hanging due to a driver programming
+	 * error.
+	 */
+	while (residual--) {
+		if (mps_wait_db_int(sc) != 0) {
+			mps_dprint(sc, MPS_FAULT,
+			    "Timeout reading doorbell\n");
+			return (ENXIO);
+		}
+		(void)mps_regread(sc, MPI2_DOORBELL_OFFSET);
+		mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+	}
+
+	/* Step 7 */
+	if (mps_wait_db_int(sc) != 0) {
+		mps_dprint(sc, MPS_FAULT, "Timeout waiting to exit doorbell\n");
+		return (ENXIO);
+	}
+	if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
+		mps_dprint(sc, MPS_FAULT, "Warning, doorbell still active\n");
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
+
+	return (0);
+}
+
+static void
+mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm)
+{
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
+	    cm->cm_desc.Words.Low);
+	mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
+	    cm->cm_desc.Words.High);
+}
+
+int
+mps_request_polled(struct mps_softc *sc, struct mps_command *cm)
+{
+	int error, timeout = 0;
+
+	error = 0;
+
+	cm->cm_flags |= MPS_CM_FLAGS_POLLED;
+	cm->cm_complete = NULL;
+	mps_map_command(sc, cm);
+
+	while ((cm->cm_flags & MPS_CM_FLAGS_COMPLETE) == 0) {
+		mps_intr(sc);
+		DELAY(50 * 1000);
+		if (timeout++ > 1000) {
+			mps_dprint(sc, MPS_FAULT, "polling failed\n");
+			error = ETIMEDOUT;
+			break;
+		}
+	}
+
+	return (error);
+}
+
+/*
+ * Just the FACTS, ma'am.
+ */
+static int
+mps_get_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
+{
+	MPI2_DEFAULT_REPLY *reply;
+	MPI2_IOC_FACTS_REQUEST request;
+	int error, req_sz, reply_sz;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
+	reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
+	reply = (MPI2_DEFAULT_REPLY *)facts;
+
+	bzero(&request, req_sz);
+	request.Function = MPI2_FUNCTION_IOC_FACTS;
+	error = mps_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
+
+	return (error);
+}
+
+static int
+mps_get_portfacts(struct mps_softc *sc, MPI2_PORT_FACTS_REPLY *facts, int port)
+{
+	MPI2_PORT_FACTS_REQUEST *request;
+	MPI2_PORT_FACTS_REPLY *reply;
+	struct mps_command *cm;
+	int error;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	if ((cm = mps_alloc_command(sc)) == NULL)
+		return (EBUSY);
+	request = (MPI2_PORT_FACTS_REQUEST *)cm->cm_req;
+	request->Function = MPI2_FUNCTION_PORT_FACTS;
+	request->PortNumber = port;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+	cm->cm_data = NULL;
+	error = mps_request_polled(sc, cm);
+	reply = (MPI2_PORT_FACTS_REPLY *)cm->cm_reply;
+	if ((reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
+		error = ENXIO;
+	bcopy(reply, facts, sizeof(MPI2_PORT_FACTS_REPLY));
+	mps_free_command(sc, cm);
+
+	return (error);
+}
+
+static int
+mps_send_iocinit(struct mps_softc *sc)
+{
+	MPI2_IOC_INIT_REQUEST	init;
+	MPI2_DEFAULT_REPLY	reply;
+	int req_sz, reply_sz, error;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
+	reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
+	bzero(&init, req_sz);
+	bzero(&reply, reply_sz);
+
+	/*
+	 * Fill in the init block.  Note that most addresses are
+	 * deliberately in the lower 32bits of memory.  This is a micro-
+	 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
+	 */
+	init.Function = MPI2_FUNCTION_IOC_INIT;
+	init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
+	init.MsgVersion = MPI2_VERSION;
+	init.HeaderVersion = MPI2_HEADER_VERSION;
+	init.SystemRequestFrameSize = sc->facts->IOCRequestFrameSize;
+	init.ReplyDescriptorPostQueueDepth = sc->pqdepth;
+	init.ReplyFreeQueueDepth = sc->fqdepth;
+	init.SenseBufferAddressHigh = 0;
+	init.SystemReplyAddressHigh = 0;
+	init.SystemRequestFrameBaseAddress.High = 0;
+	init.SystemRequestFrameBaseAddress.Low = (uint32_t)sc->req_busaddr;
+	init.ReplyDescriptorPostQueueAddress.High = 0;
+	init.ReplyDescriptorPostQueueAddress.Low = (uint32_t)sc->post_busaddr;
+	init.ReplyFreeQueueAddress.High = 0;
+	init.ReplyFreeQueueAddress.Low = (uint32_t)sc->free_busaddr;
+	init.TimeStamp.High = 0;
+	init.TimeStamp.Low = (uint32_t)time_uptime;
+
+	error = mps_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
+	if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
+		error = ENXIO;
+
+	mps_dprint(sc, MPS_INFO, "IOCInit status= 0x%x\n", reply.IOCStatus);
+	return (error);
+}
+
+static int
+mps_send_portenable(struct mps_softc *sc)
+{
+	MPI2_PORT_ENABLE_REQUEST *request;
+	struct mps_command *cm;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	if ((cm = mps_alloc_command(sc)) == NULL)
+		return (EBUSY);
+	request = (MPI2_PORT_ENABLE_REQUEST *)cm->cm_req;
+	request->Function = MPI2_FUNCTION_PORT_ENABLE;
+	request->MsgFlags = 0;
+	request->VP_ID = 0;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+	cm->cm_complete = mps_startup_complete;
+
+	mps_enqueue_request(sc, cm);
+	return (0);
+}
+
+static int
+mps_send_mur(struct mps_softc *sc)
+{
+
+	/* Placeholder */
+	return (0);
+}
+
+void
+mps_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
+{
+	bus_addr_t *addr;
+
+	addr = arg;
+	*addr = segs[0].ds_addr;
+}
+
+static int
+mps_alloc_queues(struct mps_softc *sc)
+{
+	bus_addr_t queues_busaddr;
+	uint8_t *queues;
+	int qsize, fqsize, pqsize;
+
+	/*
+	 * The reply free queue contains 4 byte entries in multiples of 16 and
+	 * aligned on a 16 byte boundary. There must always be an unused entry.
+	 * This queue supplies fresh reply frames for the firmware to use.
+	 *
+	 * The reply descriptor post queue contains 8 byte entries in
+	 * multiples of 16 and aligned on a 16 byte boundary.  This queue
+	 * contains filled-in reply frames sent from the firmware to the host.
+	 *
+	 * These two queues are allocated together for simplicity.
+	 */
+	sc->fqdepth = roundup2((sc->num_replies + 1), 16);
+	sc->pqdepth = roundup2((sc->num_replies + 1), 16);
+	fqsize= sc->fqdepth * 4;
+	pqsize = sc->pqdepth * 8;
+	qsize = fqsize + pqsize;
+
+        if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
+				16, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+                                qsize,			/* maxsize */
+                                1,			/* nsegments */
+                                qsize,			/* maxsegsize */
+                                0,			/* flags */
+                                NULL, NULL,		/* lockfunc, lockarg */
+                                &sc->queues_dmat)) {
+		device_printf(sc->mps_dev, "Cannot allocate queues DMA tag\n");
+		return (ENOMEM);
+        }
+        if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
+	    &sc->queues_map)) {
+		device_printf(sc->mps_dev, "Cannot allocate queues memory\n");
+		return (ENOMEM);
+        }
+        bzero(queues, qsize);
+        bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
+	    mps_memaddr_cb, &queues_busaddr, 0);
+
+	sc->free_queue = (uint32_t *)queues;
+	sc->free_busaddr = queues_busaddr;
+	sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
+	sc->post_busaddr = queues_busaddr + fqsize;
+
+	return (0);
+}
+
+static int
+mps_alloc_replies(struct mps_softc *sc)
+{
+	int rsize;
+
+	rsize = sc->facts->ReplyFrameSize * sc->num_replies * 4; 
+        if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
+				4, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+                                rsize,			/* maxsize */
+                                1,			/* nsegments */
+                                rsize,			/* maxsegsize */
+                                0,			/* flags */
+                                NULL, NULL,		/* lockfunc, lockarg */
+                                &sc->reply_dmat)) {
+		device_printf(sc->mps_dev, "Cannot allocate replies DMA tag\n");
+		return (ENOMEM);
+        }
+        if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
+	    BUS_DMA_NOWAIT, &sc->reply_map)) {
+		device_printf(sc->mps_dev, "Cannot allocate replies memory\n");
+		return (ENOMEM);
+        }
+        bzero(sc->reply_frames, rsize);
+        bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
+	    mps_memaddr_cb, &sc->reply_busaddr, 0);
+
+	return (0);
+}
+
+static int
+mps_alloc_requests(struct mps_softc *sc)
+{
+	struct mps_command *cm;
+	struct mps_chain *chain;
+	int i, rsize, nsegs;
+
+	rsize = sc->facts->IOCRequestFrameSize * sc->num_reqs * 4;
+        if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
+				16, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+                                rsize,			/* maxsize */
+                                1,			/* nsegments */
+                                rsize,			/* maxsegsize */
+                                0,			/* flags */
+                                NULL, NULL,		/* lockfunc, lockarg */
+                                &sc->req_dmat)) {
+		device_printf(sc->mps_dev, "Cannot allocate request DMA tag\n");
+		return (ENOMEM);
+        }
+        if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
+	    BUS_DMA_NOWAIT, &sc->req_map)) {
+		device_printf(sc->mps_dev, "Cannot allocate request memory\n");
+		return (ENOMEM);
+        }
+        bzero(sc->req_frames, rsize);
+        bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
+	    mps_memaddr_cb, &sc->req_busaddr, 0);
+
+	rsize = sc->facts->IOCRequestFrameSize * MPS_CHAIN_FRAMES * 4;
+        if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
+				16, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+                                rsize,			/* maxsize */
+                                1,			/* nsegments */
+                                rsize,			/* maxsegsize */
+                                0,			/* flags */
+                                NULL, NULL,		/* lockfunc, lockarg */
+                                &sc->chain_dmat)) {
+		device_printf(sc->mps_dev, "Cannot allocate chain DMA tag\n");
+		return (ENOMEM);
+        }
+        if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
+	    BUS_DMA_NOWAIT, &sc->chain_map)) {
+		device_printf(sc->mps_dev, "Cannot allocate chain memory\n");
+		return (ENOMEM);
+        }
+        bzero(sc->chain_frames, rsize);
+        bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
+	    mps_memaddr_cb, &sc->chain_busaddr, 0);
+
+	rsize = MPS_SENSE_LEN * sc->num_reqs;
+        if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
+				1, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+                                rsize,			/* maxsize */
+                                1,			/* nsegments */
+                                rsize,			/* maxsegsize */
+                                0,			/* flags */
+                                NULL, NULL,		/* lockfunc, lockarg */
+                                &sc->sense_dmat)) {
+		device_printf(sc->mps_dev, "Cannot allocate sense DMA tag\n");
+		return (ENOMEM);
+        }
+        if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
+	    BUS_DMA_NOWAIT, &sc->sense_map)) {
+		device_printf(sc->mps_dev, "Cannot allocate sense memory\n");
+		return (ENOMEM);
+        }
+        bzero(sc->sense_frames, rsize);
+        bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
+	    mps_memaddr_cb, &sc->sense_busaddr, 0);
+
+	sc->chains = malloc(sizeof(struct mps_chain) * MPS_CHAIN_FRAMES,
+	    M_MPT2, M_WAITOK | M_ZERO);
+	for (i = 0; i < MPS_CHAIN_FRAMES; i++) {
+		chain = &sc->chains[i];
+		chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
+		    i * sc->facts->IOCRequestFrameSize * 4);
+		chain->chain_busaddr = sc->chain_busaddr +
+		    i * sc->facts->IOCRequestFrameSize * 4;
+		mps_free_chain(sc, chain);
+	}
+
+	/* XXX Need to pick a more precise value */
+	nsegs = (MAXPHYS / PAGE_SIZE) + 1;
+        if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
+				1, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR,	/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+                                BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
+                                nsegs,			/* nsegments */
+                                BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
+                                BUS_DMA_ALLOCNOW,	/* flags */
+                                busdma_lock_mutex,	/* lockfunc */
+				&sc->mps_mtx,		/* lockarg */
+                                &sc->buffer_dmat)) {
+		device_printf(sc->mps_dev, "Cannot allocate sense DMA tag\n");
+		return (ENOMEM);
+        }
+
+	/*
+	 * SMID 0 cannot be used as a free command per the firmware spec.
+	 * Just drop that command instead of risking accounting bugs.
+	 */
+	sc->commands = malloc(sizeof(struct mps_command) * sc->num_reqs,
+	    M_MPT2, M_WAITOK | M_ZERO);
+	for (i = 1; i < sc->num_reqs; i++) {
+		cm = &sc->commands[i];
+		cm->cm_req = sc->req_frames +
+		    i * sc->facts->IOCRequestFrameSize * 4;
+		cm->cm_req_busaddr = sc->req_busaddr +
+		    i * sc->facts->IOCRequestFrameSize * 4;
+		cm->cm_sense = &sc->sense_frames[i];
+		cm->cm_sense_busaddr = sc->sense_busaddr + i * MPS_SENSE_LEN;
+		cm->cm_desc.Default.SMID = i;
+		cm->cm_sc = sc;
+		TAILQ_INIT(&cm->cm_chain_list);
+		callout_init(&cm->cm_callout, 1 /*MPSAFE*/);
+
+		/* XXX Is a failure here a critical problem? */
+		if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap) == 0)
+			mps_free_command(sc, cm);
+		else {
+			sc->num_reqs = i;
+			break;
+		}
+	}
+
+	return (0);
+}
+
+static int
+mps_init_queues(struct mps_softc *sc)
+{
+	int i;
+
+	memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
+
+	if (sc->num_replies >= sc->fqdepth)
+		return (EINVAL);
+
+	for (i = 0; i < sc->num_replies; i++)
+		sc->free_queue[i] = sc->reply_busaddr + i * sc->facts->ReplyFrameSize * 4;
+	sc->replyfreeindex = sc->num_replies;
+
+	return (0);
+}
+
+int
+mps_attach(struct mps_softc *sc)
+{
+	int i, error;
+	char tmpstr[80], tmpstr2[80];
+
+	/*
+	 * Grab any tunable-set debug level so that tracing works as early
+	 * as possible.
+	 */
+	snprintf(tmpstr, sizeof(tmpstr), "hw.mps.%d.debug_level",
+	    device_get_unit(sc->mps_dev));
+	TUNABLE_INT_FETCH(tmpstr, &sc->mps_debug);
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	mtx_init(&sc->mps_mtx, "MPT2SAS lock", NULL, MTX_DEF);
+	callout_init_mtx(&sc->periodic, &sc->mps_mtx, 0);
+	TAILQ_INIT(&sc->event_list);
+
+	/*
+	 * Setup the sysctl variable so the user can change the debug level
+	 * on the fly.
+	 */
+	snprintf(tmpstr, sizeof(tmpstr), "MPS controller %d",
+	    device_get_unit(sc->mps_dev));
+	snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mps_dev));
+
+	sysctl_ctx_init(&sc->sysctl_ctx);
+	sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
+	    SYSCTL_STATIC_CHILDREN(_hw_mps), OID_AUTO, tmpstr2, CTLFLAG_RD,
+	    0, tmpstr);
+	if (sc->sysctl_tree == NULL)
+		return (ENOMEM);
+
+	SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
+	    OID_AUTO, "debug_level", CTLFLAG_RW, &sc->mps_debug, 0,
+	    "mps debug level");
+
+	if ((error = mps_transition_ready(sc)) != 0)
+		return (error);
+
+	sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPT2,
+	    M_ZERO|M_NOWAIT);
+	if ((error = mps_get_iocfacts(sc, sc->facts)) != 0)
+		return (error);
+
+	mps_print_iocfacts(sc, sc->facts);
+
+	mps_printf(sc, "Firmware: %02d.%02d.%02d.%02d\n",
+	    sc->facts->FWVersion.Struct.Major,
+	    sc->facts->FWVersion.Struct.Minor,
+	    sc->facts->FWVersion.Struct.Unit,
+	    sc->facts->FWVersion.Struct.Dev);
+	mps_printf(sc, "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
+	    "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
+	    "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
+	    "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc");
+
+	/*
+	 * If the chip doesn't support event replay then a hard reset will be
+	 * required to trigger a full discovery.  Do the reset here then
+	 * retransition to Ready.  A hard reset might have already been done,
+	 * but it doesn't hurt to do it again.
+	 */
+	if ((sc->facts->IOCCapabilities &
+	    MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0) {
+		mps_hard_reset(sc);
+		if ((error = mps_transition_ready(sc)) != 0)
+			return (error);
+	}
+
+	/*
+	 * Size the queues. Since the reply queues always need one free entry,
+	 * we'll just deduct one reply message here.
+	 */
+	sc->num_reqs = MIN(MPS_REQ_FRAMES, sc->facts->RequestCredit);
+	sc->num_replies = MIN(MPS_REPLY_FRAMES + MPS_EVT_REPLY_FRAMES,
+	    sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
+	TAILQ_INIT(&sc->req_list);
+	TAILQ_INIT(&sc->chain_list);
+
+	if (((error = mps_alloc_queues(sc)) != 0) ||
+	    ((error = mps_alloc_replies(sc)) != 0) ||
+	    ((error = mps_alloc_requests(sc)) != 0)) {
+		mps_free(sc);
+		return (error);
+	}
+
+	if (((error = mps_init_queues(sc)) != 0) ||
+	    ((error = mps_transition_operational(sc)) != 0)) {
+		mps_free(sc);
+		return (error);
+	}
+
+	/*
+	 * Finish the queue initialization.
+	 * These are set here instead of in mps_init_queues() because the
+	 * IOC resets these values during the state transition in
+	 * mps_transition_operational().  The free index is set to 1
+	 * because the corresponding index in the IOC is set to 0, and the
+	 * IOC treats the queues as full if both are set to the same value.
+	 * Hence the reason that the queue can't hold all of the possible
+	 * replies.
+	 */
+	sc->replypostindex = 0;
+	sc->replycurindex = 0;
+	mps_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
+	mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
+
+	sc->pfacts = malloc(sizeof(MPI2_PORT_FACTS_REPLY) *
+	    sc->facts->NumberOfPorts, M_MPT2, M_ZERO|M_WAITOK);
+	for (i = 0; i < sc->facts->NumberOfPorts; i++) {
+		if ((error = mps_get_portfacts(sc, &sc->pfacts[i], i)) != 0) {
+			mps_free(sc);
+			return (error);
+		}
+		mps_print_portfacts(sc, &sc->pfacts[i]);
+	}
+
+	/* Attach the subsystems so they can prepare their event masks. */
+	/* XXX Should be dynamic so that IM/IR and user modules can attach */
+	if (((error = mps_attach_log(sc)) != 0) ||
+	    ((error = mps_attach_sas(sc)) != 0)) {
+		mps_free(sc);
+		return (error);
+	}
+
+	if ((error = mps_pci_setup_interrupts(sc)) != 0) {
+		mps_free(sc);
+		return (error);
+	}
+
+	/* Start the periodic watchdog check on the IOC Doorbell */
+	mps_periodic(sc);
+
+	/*
+	 * The portenable will kick off discovery events that will drive the
+	 * rest of the initialization process.  The CAM/SAS module will
+	 * hold up the boot sequence until discovery is complete.
+	 */
+	sc->mps_ich.ich_func = mps_startup;
+	sc->mps_ich.ich_arg = sc;
+	if (config_intrhook_establish(&sc->mps_ich) != 0) {
+		mps_dprint(sc, MPS_FAULT, "Cannot establish MPS config hook\n");
+		error = EINVAL;
+	}
+
+	return (error);
+}
+
+static void
+mps_startup(void *arg)
+{
+	struct mps_softc *sc;
+
+	sc = (struct mps_softc *)arg;
+
+	mps_lock(sc);
+	mps_unmask_intr(sc);
+	mps_send_portenable(sc);
+	mps_unlock(sc);
+}
+
+/* Periodic watchdog.  Is called with the driver lock already held. */
+static void
+mps_periodic(void *arg)
+{
+	struct mps_softc *sc;
+	uint32_t db;
+
+	sc = (struct mps_softc *)arg;
+	if (sc->mps_flags & MPS_FLAGS_SHUTDOWN)
+		return;
+
+	db = mps_regread(sc, MPI2_DOORBELL_OFFSET);
+	if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
+		device_printf(sc->mps_dev, "IOC Fault 0x%08x, Resetting\n", db);
+		/* XXX Need to broaden this to re-initialize the chip */
+		mps_hard_reset(sc);
+		db = mps_regread(sc, MPI2_DOORBELL_OFFSET);
+		if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
+			device_printf(sc->mps_dev, "Second IOC Fault 0x%08x, "
+			    "Giving up!\n", db);
+			return;
+		}
+	}
+
+	callout_reset(&sc->periodic, MPS_PERIODIC_DELAY * hz, mps_periodic, sc);
+}
+
+static void
+mps_startup_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_PORT_ENABLE_REPLY *reply;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	reply = (MPI2_PORT_ENABLE_REPLY *)cm->cm_reply;
+	if ((reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
+		mps_dprint(sc, MPS_FAULT, "Portenable failed\n");
+
+	mps_free_command(sc, cm);
+	config_intrhook_disestablish(&sc->mps_ich);
+
+}
+
+static void
+mps_log_evt_handler(struct mps_softc *sc, uintptr_t data,
+    MPI2_EVENT_NOTIFICATION_REPLY *event)
+{
+	MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
+
+	mps_print_event(sc, event);
+
+	switch (event->Event) {
+	case MPI2_EVENT_LOG_DATA:
+		device_printf(sc->mps_dev, "MPI2_EVENT_LOG_DATA:\n");
+		hexdump(event->EventData, event->EventDataLength, NULL, 0);
+		break;
+	case MPI2_EVENT_LOG_ENTRY_ADDED:
+		entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
+		mps_dprint(sc, MPS_INFO, "MPI2_EVENT_LOG_ENTRY_ADDED event "
+		    "0x%x Sequence %d:\n", entry->LogEntryQualifier,
+		     entry->LogSequence);
+		break;
+	default:
+		break;
+	}
+	return;
+}
+
+static int
+mps_attach_log(struct mps_softc *sc)
+{
+	uint8_t events[16];
+
+	bzero(events, 16);
+	setbit(events, MPI2_EVENT_LOG_DATA);
+	setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
+
+	mps_register_events(sc, events, mps_log_evt_handler, NULL,
+	    &sc->mps_log_eh);
+
+	return (0);
+}
+
+static int
+mps_detach_log(struct mps_softc *sc)
+{
+
+	if (sc->mps_log_eh != NULL)
+		mps_deregister_events(sc, sc->mps_log_eh);
+	return (0);
+}
+
+/*
+ * Free all of the driver resources and detach submodules.  Should be called
+ * without the lock held.
+ */
+int
+mps_free(struct mps_softc *sc)
+{
+	struct mps_command *cm;
+	int i, error;
+
+	/* Turn off the watchdog */
+	mps_lock(sc);
+	sc->mps_flags |= MPS_FLAGS_SHUTDOWN;
+	mps_unlock(sc);
+	/* Lock must not be held for this */
+	callout_drain(&sc->periodic);
+
+	if (((error = mps_detach_log(sc)) != 0) ||
+	    ((error = mps_detach_sas(sc)) != 0))
+		return (error);
+
+	/* Put the IOC back in the READY state. */
+	mps_lock(sc);
+	if ((error = mps_send_mur(sc)) != 0) {
+		mps_unlock(sc);
+		return (error);
+	}
+	mps_unlock(sc);
+
+	if (sc->facts != NULL)
+		free(sc->facts, M_MPT2);
+
+	if (sc->pfacts != NULL)
+		free(sc->pfacts, M_MPT2);
+
+	if (sc->post_busaddr != 0)
+		bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
+	if (sc->post_queue != NULL)
+		bus_dmamem_free(sc->queues_dmat, sc->post_queue,
+		    sc->queues_map);
+	if (sc->queues_dmat != NULL)
+		bus_dma_tag_destroy(sc->queues_dmat);
+
+	if (sc->chain_busaddr != 0)
+		bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
+	if (sc->chain_frames != NULL)
+		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,sc->chain_map);
+	if (sc->chain_dmat != NULL)
+		bus_dma_tag_destroy(sc->chain_dmat);
+
+	if (sc->sense_busaddr != 0)
+		bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
+	if (sc->sense_frames != NULL)
+		bus_dmamem_free(sc->sense_dmat, sc->sense_frames,sc->sense_map);
+	if (sc->sense_dmat != NULL)
+		bus_dma_tag_destroy(sc->sense_dmat);
+
+	if (sc->reply_busaddr != 0)
+		bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
+	if (sc->reply_frames != NULL)
+		bus_dmamem_free(sc->reply_dmat, sc->reply_frames,sc->reply_map);
+	if (sc->reply_dmat != NULL)
+		bus_dma_tag_destroy(sc->reply_dmat);
+
+	if (sc->req_busaddr != 0)
+		bus_dmamap_unload(sc->req_dmat, sc->req_map);
+	if (sc->req_frames != NULL)
+		bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
+	if (sc->req_dmat != NULL)
+		bus_dma_tag_destroy(sc->req_dmat);
+
+	if (sc->chains != NULL)
+		free(sc->chains, M_MPT2);
+	if (sc->commands != NULL) {
+		for (i = 1; i < sc->num_reqs; i++) {
+			cm = &sc->commands[i];
+			bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
+		}
+		free(sc->commands, M_MPT2);
+	}
+	if (sc->buffer_dmat != NULL)
+		bus_dma_tag_destroy(sc->buffer_dmat);
+
+	if (sc->sysctl_tree != NULL)
+		sysctl_ctx_free(&sc->sysctl_ctx);
+
+	mtx_destroy(&sc->mps_mtx);
+
+	return (0);
+}
+
+void
+mps_intr(void *data)
+{
+	struct mps_softc *sc;
+	uint32_t status;
+
+	sc = (struct mps_softc *)data;
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	/*
+	 * Check interrupt status register to flush the bus.  This is
+	 * needed for both INTx interrupts and driver-driven polling
+	 */
+	status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
+	if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
+		return;
+
+	mps_lock(sc);
+	mps_intr_locked(data);
+	mps_unlock(sc);
+	return;
+}
+
+/*
+ * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
+ * chip.  Hopefully this theory is correct.
+ */
+void
+mps_intr_msi(void *data)
+{
+	struct mps_softc *sc;
+
+	sc = (struct mps_softc *)data;
+	mps_lock(sc);
+	mps_intr_locked(data);
+	mps_unlock(sc);
+	return;
+}
+
+/*
+ * The locking is overly broad and simplistic, but easy to deal with for now.
+ */
+void
+mps_intr_locked(void *data)
+{
+	MPI2_REPLY_DESCRIPTORS_UNION *desc;
+	struct mps_softc *sc;
+	struct mps_command *cm = NULL;
+	uint8_t flags;
+	u_int pq;
+
+	sc = (struct mps_softc *)data;
+
+	pq = sc->replypostindex;
+
+	for ( ;; ) {
+		cm = NULL;
+		desc = &sc->post_queue[pq];
+		flags = desc->Default.ReplyFlags &
+		    MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
+		if (flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
+			break;
+
+		switch (flags) {
+		case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
+			cm = &sc->commands[desc->SCSIIOSuccess.SMID];
+			cm->cm_reply = NULL;
+			break;
+		case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
+		{
+			uint32_t baddr;
+			uint8_t *reply;
+
+			reply = sc->reply_frames +
+			    sc->replycurindex * sc->facts->ReplyFrameSize * 4;
+			baddr = desc->AddressReply.ReplyFrameAddress;
+			if (desc->AddressReply.SMID == 0) {
+				mps_dispatch_event(sc, baddr,
+				   (MPI2_EVENT_NOTIFICATION_REPLY *) reply);
+			} else {
+				cm = &sc->commands[desc->AddressReply.SMID];
+				cm->cm_reply = reply;
+				cm->cm_reply_data =
+				    desc->AddressReply.ReplyFrameAddress;
+			}
+			if (++sc->replycurindex >= sc->fqdepth)
+				sc->replycurindex = 0;
+			break;
+		}
+		case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
+		case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
+		case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
+		default:
+			/* Unhandled */
+			device_printf(sc->mps_dev, "Unhandled reply 0x%x\n",
+			    desc->Default.ReplyFlags);
+			cm = NULL;
+			break;
+		}
+
+		if (cm != NULL) {
+			if (cm->cm_flags & MPS_CM_FLAGS_POLLED)
+				cm->cm_flags |= MPS_CM_FLAGS_COMPLETE;
+
+			if (cm->cm_complete != NULL)
+				cm->cm_complete(sc, cm);
+
+			if (cm->cm_flags & MPS_CM_FLAGS_WAKEUP)
+				wakeup(cm);
+		}
+
+		desc->Words.Low = 0xffffffff;
+		desc->Words.High = 0xffffffff;
+		if (++pq >= sc->pqdepth)
+			pq = 0;
+	}
+
+	if (pq != sc->replypostindex) {
+		mps_dprint(sc, MPS_INFO, "writing postindex %d\n", pq);
+		mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, pq);
+		sc->replypostindex = pq;
+	}
+
+	return;
+}
+
+static void
+mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
+    MPI2_EVENT_NOTIFICATION_REPLY *reply)
+{
+	struct mps_event_handle *eh;
+	int event, handled = 0;;
+
+	event = reply->Event;
+	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
+		if (isset(eh->mask, event)) {
+			eh->callback(sc, data, reply);
+			handled++;
+		}
+	}
+
+	if (handled == 0)
+		device_printf(sc->mps_dev, "Unhandled event 0x%x\n", event);
+}
+
+/*
+ * For both register_events and update_events, the caller supplies a bitmap
+ * of events that it _wants_.  These functions then turn that into a bitmask
+ * suitable for the controller.
+ */
+int
+mps_register_events(struct mps_softc *sc, uint8_t *mask,
+    mps_evt_callback_t *cb, void *data, struct mps_event_handle **handle)
+{
+	struct mps_event_handle *eh;
+	int error = 0;
+
+	eh = malloc(sizeof(struct mps_event_handle), M_MPT2, M_WAITOK|M_ZERO);
+	eh->callback = cb;
+	eh->data = data;
+	TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
+	if (mask != NULL)
+		error = mps_update_events(sc, eh, mask);
+	*handle = eh;
+
+	return (error);
+}
+
+int
+mps_update_events(struct mps_softc *sc, struct mps_event_handle *handle,
+    uint8_t *mask)
+{
+	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
+	MPI2_EVENT_NOTIFICATION_REPLY *reply;
+	struct mps_command *cm;
+	struct mps_event_handle *eh;
+	int error, i;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	if ((mask != NULL) && (handle != NULL))
+		bcopy(mask, &handle->mask[0], 16);
+	memset(sc->event_mask, 0xff, 16);
+
+	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
+		for (i = 0; i < 16; i++)
+			sc->event_mask[i] &= ~eh->mask[i];
+	}
+
+	if ((cm = mps_alloc_command(sc)) == NULL)
+		return (EBUSY);
+	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
+	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
+	evtreq->MsgFlags = 0;
+	evtreq->SASBroadcastPrimitiveMasks = 0;
+#ifdef MPS_DEBUG_ALL_EVENTS
+	{
+		u_char fullmask[16];
+		memset(fullmask, 0x00, 16);
+		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
+	}
+#else
+		bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
+#endif
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+	cm->cm_data = NULL;
+
+	error = mps_request_polled(sc, cm);
+	reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
+	if ((reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
+		error = ENXIO;
+	mps_print_event(sc, reply);
+
+	mps_free_command(sc, cm);
+	return (error);
+}
+
+int
+mps_deregister_events(struct mps_softc *sc, struct mps_event_handle *handle)
+{
+
+	TAILQ_REMOVE(&sc->event_list, handle, eh_list);
+	free(handle, M_MPT2);
+	return (mps_update_events(sc, NULL, NULL));
+}
+
+static void
+mps_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
+{
+	MPI2_SGE_SIMPLE64 *sge;
+	MPI2_SGE_CHAIN32 *sgc;
+	struct mps_softc *sc;
+	struct mps_command *cm;
+	struct mps_chain *chain;
+	u_int i, segsleft, sglspace, dir, flags, sflags;
+
+	cm = (struct mps_command *)arg;
+	sc = cm->cm_sc;
+
+        segsleft = nsegs;
+        sglspace = cm->cm_sglsize;
+        sge = (MPI2_SGE_SIMPLE64 *)&cm->cm_sge->MpiSimple;
+
+	/*
+	 * Set up DMA direction flags.  Note no support for
+	 * bi-directional transactions.
+	 */
+        sflags = MPI2_SGE_FLAGS_ADDRESS_SIZE;
+        if (cm->cm_flags & MPS_CM_FLAGS_DATAOUT) {
+                sflags |= MPI2_SGE_FLAGS_DIRECTION;
+		dir = BUS_DMASYNC_PREWRITE;
+	} else
+		dir = BUS_DMASYNC_PREREAD;
+
+	/*
+	 * case 1: 1 more segment, enough room for it
+	 * case 2: 2 more segments, enough room for both
+	 * case 3: >=2 more segments, only enough room for 1 and a chain
+	 * case 4: >=1 more segment, enough room for only a chain
+	 * case 5: >=1 more segment, no room for anything (error)
+	 */
+
+	for (i = 0; i < nsegs; i++) {
+
+		/* Case 5 Error.  This should never happen. */
+		if (sglspace < MPS_SGC_SIZE) {
+			panic("MPS: Need SGE Error Code\n");
+		}
+
+		/*
+		 * Case 4, Fill in a chain element, allocate a chain,
+		 * fill in one SGE element, continue.
+		 */
+		if ((sglspace >= MPS_SGC_SIZE) && (sglspace < MPS_SGE64_SIZE)) {
+			chain = mps_alloc_chain(sc);
+			if (chain == NULL) {
+				/* Resource shortage, roll back! */
+				printf("out of chain frames\n");
+				return;
+			}
+
+			/*
+			 * Note: a double-linked list is used to make it
+			 * easier to walk for debugging.
+			 */
+			TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain,chain_link);
+
+			sgc = (MPI2_SGE_CHAIN32 *)sge;
+			sgc->Length = 128;
+			sgc->NextChainOffset = 0;
+			sgc->Flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT;
+			sgc->Address = chain->chain_busaddr;
+
+			sge = (MPI2_SGE_SIMPLE64 *)&chain->chain->MpiSimple;
+			sglspace = 128;
+		}
+
+		flags = MPI2_SGE_FLAGS_SIMPLE_ELEMENT;
+		sge->FlagsLength = segs[i].ds_len |
+		   ((sflags | flags) << MPI2_SGE_FLAGS_SHIFT);
+		mps_from_u64(segs[i].ds_addr, &sge->Address);
+
+		/* Case 1, Fill in one SGE element and break */
+		if (segsleft == 1)
+			break;
+
+		sglspace -= MPS_SGE64_SIZE;
+		segsleft--;
+
+		/* Case 3, prepare for a chain on the next loop */
+		if ((segsleft > 0) && (sglspace < MPS_SGE64_SIZE))
+			sge->FlagsLength |= 
+			    (MPI2_SGE_FLAGS_LAST_ELEMENT <<
+			    MPI2_SGE_FLAGS_SHIFT);
+
+		/* Advance to the next element to be filled in. */
+		sge++;
+	}
+
+	/* Last element of the last segment of the entire buffer */
+	flags = MPI2_SGE_FLAGS_LAST_ELEMENT |
+	    MPI2_SGE_FLAGS_END_OF_BUFFER |
+	    MPI2_SGE_FLAGS_END_OF_LIST;
+	sge->FlagsLength |= (flags << MPI2_SGE_FLAGS_SHIFT);
+
+	bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
+	mps_enqueue_request(sc, cm);
+
+	return;
+}
+
+int
+mps_map_command(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SGE_SIMPLE32 *sge;
+	int error = 0;
+
+	if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
+		error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
+		    cm->cm_data, cm->cm_length, mps_data_cb, cm, 0);
+	} else {
+		/* Add a zero-length element as needed */
+		if (cm->cm_sge != NULL) {
+			sge = (MPI2_SGE_SIMPLE32 *)cm->cm_sge;
+			sge->FlagsLength = (MPI2_SGE_FLAGS_LAST_ELEMENT |
+			    MPI2_SGE_FLAGS_END_OF_BUFFER |
+			    MPI2_SGE_FLAGS_END_OF_LIST |
+			    MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
+			    MPI2_SGE_FLAGS_SHIFT;
+			sge->Address = 0;
+		}
+		mps_enqueue_request(sc, cm);	
+	}
+
+	return (error);
+}
+
+/*
+ * The MPT driver had a verbose interface for config pages.  In this driver,
+ * reduce it to much simplier terms, similar to the Linux driver.
+ */
+int
+mps_read_config_page(struct mps_softc *sc, struct mps_config_params *params)
+{
+	MPI2_CONFIG_REQUEST *req;
+	struct mps_command *cm;
+	int error;
+
+	if (sc->mps_flags & MPS_FLAGS_BUSY) {
+		return (EBUSY);
+	}
+
+	cm = mps_alloc_command(sc);
+	if (cm == NULL) {
+		return (EBUSY);
+	}
+
+	req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
+	req->Function = MPI2_FUNCTION_CONFIG;
+	req->Action = params->action;
+	req->SGLFlags = 0;
+	req->ChainOffset = 0;
+	req->PageAddress = params->page_address;
+	if (params->hdr.Ext.ExtPageType != 0) {
+		MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
+
+		hdr = ¶ms->hdr.Ext;
+		req->ExtPageType = hdr->ExtPageType;
+		req->ExtPageLength = hdr->ExtPageLength;
+		req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
+		req->Header.PageLength = 0; /* Must be set to zero */
+		req->Header.PageNumber = hdr->PageNumber;
+		req->Header.PageVersion = hdr->PageVersion;
+	} else {
+		MPI2_CONFIG_PAGE_HEADER *hdr;
+
+		hdr = ¶ms->hdr.Struct;
+		req->Header.PageType = hdr->PageType;
+		req->Header.PageNumber = hdr->PageNumber;
+		req->Header.PageLength = hdr->PageLength;
+		req->Header.PageVersion = hdr->PageVersion;
+	}
+
+	cm->cm_data = params->buffer;
+	cm->cm_length = params->length;
+	cm->cm_sge = &req->PageBufferSGE;
+	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
+	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+
+	if (params->callback != NULL) {
+		cm->cm_complete = mps_config_complete;
+		cm->cm_complete_data = params;
+		return (mps_map_command(sc, cm));
+	} else {
+		cm->cm_complete = NULL;
+		cm->cm_flags |= MPS_CM_FLAGS_WAKEUP;
+		if ((error = mps_map_command(sc, cm)) != 0)
+			return (error);
+		msleep(cm, &sc->mps_mtx, 0, "mpswait", 0);
+		mps_config_complete(sc, cm);
+	}
+
+	return (0);
+}
+
+int
+mps_write_config_page(struct mps_softc *sc, struct mps_config_params *params)
+{
+	return (EINVAL);
+}
+
+static void
+mps_config_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_CONFIG_REPLY *reply;
+	struct mps_config_params *params;
+
+	params = cm->cm_complete_data;
+
+	if (cm->cm_data != NULL) {
+		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
+		    BUS_DMASYNC_POSTREAD);
+		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
+	}
+
+	reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
+	params->status = reply->IOCStatus;
+	if (params->hdr.Ext.ExtPageType != 0) {
+		params->hdr.Ext.ExtPageType = reply->ExtPageType;
+		params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
+	} else {
+		params->hdr.Struct.PageType = reply->Header.PageType;
+		params->hdr.Struct.PageNumber = reply->Header.PageNumber;
+		params->hdr.Struct.PageLength = reply->Header.PageLength;
+		params->hdr.Struct.PageVersion = reply->Header.PageVersion;
+	}
+
+	mps_free_command(sc, cm);
+	if (params->callback != NULL)
+		params->callback(sc, params);
+
+	return;
+}
diff --git a/sys/dev/mps/mps_ioctl.h b/sys/dev/mps/mps_ioctl.h
new file mode 100644
index 00000000000..7b80498278a
--- /dev/null
+++ b/sys/dev/mps/mps_ioctl.h
@@ -0,0 +1,146 @@
+/*-
+ * Copyright (c) 2008 Yahoo!, Inc.
+ * All rights reserved.
+ * Written by: John Baldwin 
+ *
+ * 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. Neither the name of the author nor the names of any co-contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ *
+ * LSI MPT-Fusion Host Adapter FreeBSD userland interface
+ *
+ * $FreeBSD$
+ */
+
+#ifndef _MPS_IOCTL_H_
+#define	_MPS_IOCTL_H_
+
+#include 
+#include 
+#include 
+#include 
+
+/*
+ * For the read header requests, the header should include the page
+ * type or extended page type, page number, and page version.  The
+ * buffer and length are unused.  The completed header is returned in
+ * the 'header' member.
+ *
+ * For the read page and write page requests, 'buf' should point to a
+ * buffer of 'len' bytes which holds the entire page (including the
+ * header).
+ *
+ * All requests specify the page address in 'page_address'.
+ */
+struct mps_cfg_page_req {	
+	MPI2_CONFIG_PAGE_HEADER header;
+	uint32_t page_address;
+	void	*buf;
+	int	len;
+	uint16_t ioc_status;
+};
+
+struct mps_ext_cfg_page_req {
+	MPI2_CONFIG_EXTENDED_PAGE_HEADER header;
+	uint32_t page_address;
+	void	*buf;
+	int	len;
+	uint16_t ioc_status;
+};
+
+struct mps_raid_action {
+	uint8_t action;
+	uint8_t volume_bus;
+	uint8_t volume_id;
+	uint8_t phys_disk_num;
+	uint32_t action_data_word;
+	void *buf;
+	int len;
+	uint32_t volume_status;
+	uint32_t action_data[4];
+	uint16_t action_status;
+	uint16_t ioc_status;
+	uint8_t write;
+};
+
+struct mps_usr_command {
+	void *req;
+	uint32_t req_len;
+	void *rpl;
+	uint32_t rpl_len;
+	void *buf;
+	int len;
+	uint32_t flags;
+};
+
+#define MPSIO_MPS_COMMAND_FLAG_VERBOSE 0x01
+#define MPSIO_MPS_COMMAND_FLAG_DEBUG 0x02
+#define	MPSIO_READ_CFG_HEADER	_IOWR('M', 200, struct mps_cfg_page_req)
+#define	MPSIO_READ_CFG_PAGE	_IOWR('M', 201, struct mps_cfg_page_req)
+#define	MPSIO_READ_EXT_CFG_HEADER _IOWR('M', 202, struct mps_ext_cfg_page_req)
+#define	MPSIO_READ_EXT_CFG_PAGE	_IOWR('M', 203, struct mps_ext_cfg_page_req)
+#define	MPSIO_WRITE_CFG_PAGE	_IOWR('M', 204, struct mps_cfg_page_req)
+#define	MPSIO_RAID_ACTION	_IOWR('M', 205, struct mps_raid_action)
+#define	MPSIO_MPS_COMMAND	_IOWR('M', 210, struct mps_usr_command)
+
+#if defined(__amd64__)
+struct mps_cfg_page_req32 {
+	MPI2_CONFIG_PAGE_HEADER header;
+	uint32_t page_address;
+	uint32_t buf;
+	int	len;	
+	uint16_t ioc_status;
+};
+
+struct mps_ext_cfg_page_req32 {
+	MPI2_CONFIG_EXTENDED_PAGE_HEADER header;
+	uint32_t page_address;
+	uint32_t buf;
+	int	len;
+	uint16_t ioc_status;
+};
+
+struct mps_raid_action32 {
+	uint8_t action;
+	uint8_t volume_bus;
+	uint8_t volume_id;
+	uint8_t phys_disk_num;
+	uint32_t action_data_word;
+	uint32_t buf;
+	int len;
+	uint32_t volume_status;
+	uint32_t action_data[4];
+	uint16_t action_status;
+	uint16_t ioc_status;
+	uint8_t write;
+};
+
+#define	MPSIO_READ_CFG_HEADER32	_IOWR('M', 100, struct mps_cfg_page_req32)
+#define	MPSIO_READ_CFG_PAGE32	_IOWR('M', 101, struct mps_cfg_page_req32)
+#define	MPSIO_READ_EXT_CFG_HEADER32 _IOWR('M', 102, struct mps_ext_cfg_page_req32)
+#define	MPSIO_READ_EXT_CFG_PAGE32 _IOWR('M', 103, struct mps_ext_cfg_page_req32)
+#define	MPSIO_WRITE_CFG_PAGE32	_IOWR('M', 104, struct mps_cfg_page_req32)
+#define	MPSIO_RAID_ACTION32	_IOWR('M', 105, struct mps_raid_action32)
+#endif
+
+#endif /* !_MPS_IOCTL_H_ */
diff --git a/sys/dev/mps/mps_pci.c b/sys/dev/mps/mps_pci.c
new file mode 100644
index 00000000000..2b33ba857d8
--- /dev/null
+++ b/sys/dev/mps/mps_pci.c
@@ -0,0 +1,364 @@
+/*-
+ * Copyright (c) 2009 Yahoo! Inc.
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+/* PCI/PCI-X/PCIe bus interface for the LSI MPT2 controllers */
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+static int	mps_pci_probe(device_t);
+static int	mps_pci_attach(device_t);
+static int	mps_pci_detach(device_t);
+static int	mps_pci_suspend(device_t);
+static int	mps_pci_resume(device_t);
+static void	mps_pci_free(struct mps_softc *);
+static int	mps_alloc_msix(struct mps_softc *sc, int msgs);
+static int	mps_alloc_msi(struct mps_softc *sc, int msgs);
+
+int mps_disable_msix = 0;
+TUNABLE_INT("hw.mps.disable_msix", &mps_disable_msix);
+SYSCTL_INT(_hw_mps, OID_AUTO, disable_msix, CTLFLAG_RD, &mps_disable_msix, 0,
+    "Disable MSIX interrupts\n");
+int mps_disable_msi = 0;
+TUNABLE_INT("hw.mps.disable_msi", &mps_disable_msi);
+SYSCTL_INT(_hw_mps, OID_AUTO, disable_msi, CTLFLAG_RD, &mps_disable_msi, 0,
+    "Disable MSI interrupts\n");
+
+static device_method_t mps_methods[] = {
+	DEVMETHOD(device_probe,		mps_pci_probe),
+	DEVMETHOD(device_attach,	mps_pci_attach),
+	DEVMETHOD(device_detach,	mps_pci_detach),
+	DEVMETHOD(device_suspend,	mps_pci_suspend),
+	DEVMETHOD(device_resume,	mps_pci_resume),
+	DEVMETHOD(bus_print_child,	bus_generic_print_child),
+	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
+	{ 0, 0 }
+};
+
+static driver_t mps_pci_driver = {
+	"mps",
+	mps_methods,
+	sizeof(struct mps_softc)
+};
+
+static devclass_t	mps_devclass;
+DRIVER_MODULE(mps, pci, mps_pci_driver, mps_devclass, 0, 0);
+
+struct mps_ident {
+	uint16_t	vendor;
+	uint16_t	device;
+	uint16_t	subvendor;
+	uint16_t	subdevice;
+	u_int		flags;
+	const char	*desc;
+} mps_identifiers[] = {
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2004,
+	    0xffff, 0xffff, 0, "LSI SAS2004" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2008,
+	    0xffff, 0xffff, 0, "LSI SAS2008" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2108_1,
+	    0xffff, 0xffff, 0, "LSI SAS2108" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2108_2,
+	    0xffff, 0xffff, 0, "LSI SAS2108" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2108_3,
+	    0xffff, 0xffff, 0, "LSI SAS2108" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2116_1,
+	    0xffff, 0xffff, 0, "LSI SAS2116" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2116_2,
+	    0xffff, 0xffff, 0, "LSI SAS2116" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_1,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_2,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_3,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_4,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_5,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_6,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_7,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ MPI2_MFGPAGE_VENDORID_LSI, MPI2_MFGPAGE_DEVID_SAS2208_8,
+	    0xffff, 0xffff, 0, "LSI SAS2208" },
+	{ 0, 0, 0, 0, 0, NULL }
+};
+
+static struct mps_ident *
+mps_find_ident(device_t dev)
+{
+	struct mps_ident *m;
+
+	for (m = mps_identifiers; m->vendor != 0; m++) {
+		if (m->vendor != pci_get_vendor(dev))
+			continue;
+		if (m->device != pci_get_device(dev))
+			continue;
+		if ((m->subvendor != 0xffff) &&
+		    (m->subvendor != pci_get_subvendor(dev)))
+			continue;
+		if ((m->subdevice != 0xffff) &&
+		    (m->subdevice != pci_get_subdevice(dev)))
+			continue;
+		return (m);
+	}
+
+	return (NULL);
+}
+
+static int
+mps_pci_probe(device_t dev)
+{
+	struct mps_ident *id;
+
+	if ((id = mps_find_ident(dev)) != NULL) {
+		device_set_desc(dev, id->desc);
+		return (BUS_PROBE_DEFAULT);
+	}
+	return (ENXIO);
+}
+
+static int
+mps_pci_attach(device_t dev)
+{
+	struct mps_softc *sc;
+	struct mps_ident *m;
+	uint16_t command;
+	int error;
+
+	sc = device_get_softc(dev);
+	bzero(sc, sizeof(*sc));
+	sc->mps_dev = dev;
+	m = mps_find_ident(dev);
+	sc->mps_flags = m->flags;
+
+	/* Twiddle basic PCI config bits for a sanity check */
+	command = pci_read_config(dev, PCIR_COMMAND, 2);
+	command |= PCIM_CMD_BUSMASTEREN;
+	pci_write_config(dev, PCIR_COMMAND, command, 2);
+	command = pci_read_config(dev, PCIR_COMMAND, 2);
+	if ((command & PCIM_CMD_BUSMASTEREN) == 0) {
+		device_printf(dev, "Cannot enable PCI busmaster\n");
+		return (ENXIO);
+	}
+	if ((command & PCIM_CMD_MEMEN) == 0) {
+		device_printf(dev, "PCI memory window not available\n");
+		return (ENXIO);
+	}
+
+	/* Allocate the System Interface Register Set */
+	sc->mps_regs_rid = PCIR_BAR(1);
+	if ((sc->mps_regs_resource = bus_alloc_resource_any(dev,
+	    SYS_RES_MEMORY, &sc->mps_regs_rid, RF_ACTIVE)) == NULL) {
+		device_printf(dev, "Cannot allocate PCI registers\n");
+		return (ENXIO);
+	}
+	sc->mps_btag = rman_get_bustag(sc->mps_regs_resource);
+	sc->mps_bhandle = rman_get_bushandle(sc->mps_regs_resource);
+
+	/* Allocate the parent DMA tag */
+	if (bus_dma_tag_create( NULL,			/* parent */
+				1, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR,	/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+				BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
+				BUS_SPACE_UNRESTRICTED,	/* nsegments */
+				BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
+				0,			/* flags */
+				NULL, NULL,		/* lockfunc, lockarg */
+				&sc->mps_parent_dmat)) {
+		device_printf(dev, "Cannot allocate parent DMA tag\n");
+		mps_pci_free(sc);
+		return (ENOMEM);
+	}
+
+	if ((error = mps_attach(sc)) != 0)
+		mps_pci_free(sc);
+
+	return (error);
+}
+
+int
+mps_pci_setup_interrupts(struct mps_softc *sc)
+{
+	device_t dev;
+	int i, error, msgs;
+
+	dev = sc->mps_dev;
+	error = ENXIO;
+	if ((mps_disable_msix == 0) &&
+	    ((msgs = pci_msix_count(dev)) >= MPS_MSI_COUNT))
+		error = mps_alloc_msix(sc, MPS_MSI_COUNT);
+	if ((error != 0) && (mps_disable_msi == 0) &&
+	    ((msgs = pci_msi_count(dev)) >= MPS_MSI_COUNT))
+		error = mps_alloc_msi(sc, MPS_MSI_COUNT);
+
+	if (error != 0) {
+		sc->mps_flags |= MPS_FLAGS_INTX;
+		sc->mps_irq_rid[0] = 0;
+		sc->mps_irq[0] = bus_alloc_resource_any(dev, SYS_RES_IRQ,
+		    &sc->mps_irq_rid[0],  RF_SHAREABLE | RF_ACTIVE);
+		if (sc->mps_irq[0] == NULL) {
+			device_printf(dev, "Cannot allocate INTx interrupt\n");
+			return (ENXIO);
+		}
+		error = bus_setup_intr(dev, sc->mps_irq[0],
+		    INTR_TYPE_BIO | INTR_MPSAFE, NULL, mps_intr, sc,
+		    &sc->mps_intrhand[0]);
+		if (error)
+			device_printf(dev, "Cannot setup INTx interrupt\n");
+	} else {
+		sc->mps_flags |= MPS_FLAGS_MSI;
+		for (i = 0; i < MPS_MSI_COUNT; i++) {
+			sc->mps_irq_rid[i] = i + 1;
+			sc->mps_irq[i] = bus_alloc_resource_any(dev,
+			    SYS_RES_IRQ, &sc->mps_irq_rid[i], RF_ACTIVE);
+			if (sc->mps_irq[i] == NULL) {
+				device_printf(dev,
+				    "Cannot allocate MSI interrupt\n");
+				return (ENXIO);
+			}
+			error = bus_setup_intr(dev, sc->mps_irq[i],
+			    INTR_TYPE_BIO | INTR_MPSAFE, NULL, mps_intr_msi,
+			    sc, &sc->mps_intrhand[i]);
+			if (error) {
+				device_printf(dev,
+				    "Cannot setup MSI interrupt %d\n", i);
+				break;
+			}
+		}
+	}
+
+	return (error);
+}
+
+static int
+mps_pci_detach(device_t dev)
+{
+	struct mps_softc *sc;
+	int error;
+
+	sc = device_get_softc(dev);
+
+	if ((error = mps_free(sc)) != 0)
+		return (error);
+
+	mps_pci_free(sc);
+	return (0);
+}
+
+static void
+mps_pci_free(struct mps_softc *sc)
+{
+	int i;
+
+	if (sc->mps_parent_dmat != NULL) {
+		bus_dma_tag_destroy(sc->mps_parent_dmat);
+	}
+
+	if (sc->mps_flags & MPS_FLAGS_MSI) {
+		for (i = 0; i < MPS_MSI_COUNT; i++) {
+			if (sc->mps_irq[i] != NULL) {
+				bus_teardown_intr(sc->mps_dev, sc->mps_irq[i],
+				    sc->mps_intrhand[i]);
+				bus_release_resource(sc->mps_dev, SYS_RES_IRQ,
+				    sc->mps_irq_rid[i], sc->mps_irq[i]);
+			}
+		}
+		pci_release_msi(sc->mps_dev);
+	}
+
+	if (sc->mps_flags & MPS_FLAGS_INTX) {
+		bus_teardown_intr(sc->mps_dev, sc->mps_irq[0],
+		    sc->mps_intrhand[0]);
+		bus_release_resource(sc->mps_dev, SYS_RES_IRQ,
+		    sc->mps_irq_rid[0], sc->mps_irq[0]);
+	}
+
+	if (sc->mps_regs_resource != NULL) {
+		bus_release_resource(sc->mps_dev, SYS_RES_MEMORY,
+		    sc->mps_regs_rid, sc->mps_regs_resource);
+	}
+
+	return;
+}
+
+static int
+mps_pci_suspend(device_t dev)
+{
+	return (EINVAL);
+}
+
+static int
+mps_pci_resume(device_t dev)
+{
+	return (EINVAL);
+}
+
+static int
+mps_alloc_msix(struct mps_softc *sc, int msgs)
+{
+	int error;
+
+	error = pci_alloc_msix(sc->mps_dev, &msgs);
+	return (error);
+}
+
+static int
+mps_alloc_msi(struct mps_softc *sc, int msgs)
+{
+	int error;
+
+	error = pci_alloc_msi(sc->mps_dev, &msgs);
+	return (error);
+}
+
diff --git a/sys/dev/mps/mps_sas.c b/sys/dev/mps/mps_sas.c
new file mode 100644
index 00000000000..fd7e21d1f25
--- /dev/null
+++ b/sys/dev/mps/mps_sas.c
@@ -0,0 +1,1411 @@
+/*-
+ * Copyright (c) 2009 Yahoo! Inc.
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+/* Communications core for LSI MPT2 */
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+struct mpssas_target {
+	uint16_t	handle;
+	uint8_t		linkrate;
+	uint64_t	devname;
+	uint32_t	devinfo;
+	uint16_t	encl_handle;
+	uint16_t	encl_slot;
+	int		flags;
+#define MPSSAS_TARGET_INABORT	(1 << 0)
+#define MPSSAS_TARGET_INRESET	(1 << 1)
+#define MPSSAS_TARGET_INCHIPRESET (1 << 2)
+#define MPSSAS_TARGET_INRECOVERY 0x7
+	uint16_t	tid;
+};
+
+struct mpssas_softc {
+	struct mps_softc	*sc;
+	u_int			flags;
+#define MPSSAS_IN_DISCOVERY	(1 << 0)
+#define MPSSAS_IN_STARTUP	(1 << 1)
+#define MPSSAS_DISCOVERY_TIMEOUT_PENDING	(1 << 2)
+#define MPSSAS_QUEUE_FROZEN	(1 << 3)
+	struct mpssas_target	*targets;
+	struct cam_devq		*devq;
+	struct cam_sim		*sim;
+	struct cam_path		*path;
+	struct intr_config_hook	sas_ich;
+	struct callout		discovery_callout;
+	u_int			discovery_timeouts;
+	struct mps_event_handle	*mpssas_eh;
+};
+
+struct mpssas_devprobe {
+	struct mps_config_params	params;
+	u_int			state;
+#define MPSSAS_PROBE_DEV1	0x01
+#define MPSSAS_PROBE_DEV2	0x02
+#define MPSSAS_PROBE_PHY	0x03
+#define MPSSAS_PROBE_EXP	0x04
+#define MPSSAS_PROBE_PHY2	0x05
+#define MPSSAS_PROBE_EXP2	0x06
+	struct mpssas_target	target;
+};
+
+#define MPSSAS_DISCOVERY_TIMEOUT	20
+#define MPSSAS_MAX_DISCOVERY_TIMEOUTS	10 /* 200 seconds */
+
+MALLOC_DEFINE(M_MPSSAS, "MPSSAS", "MPS SAS memory");
+
+static struct mpssas_target * mpssas_alloc_target(struct mpssas_softc *,
+    struct mpssas_target *);
+static struct mpssas_target * mpssas_find_target(struct mpssas_softc *, int,
+     uint16_t);
+static void mpssas_announce_device(struct mpssas_softc *,
+     struct mpssas_target *);
+static void mpssas_startup(void *data);
+static void mpssas_discovery_end(struct mpssas_softc *sassc);
+static void mpssas_discovery_timeout(void *data);
+static void mpssas_prepare_remove(struct mpssas_softc *,
+    MPI2_EVENT_SAS_TOPO_PHY_ENTRY *);
+static void mpssas_remove_device(struct mps_softc *, struct mps_command *);
+static void mpssas_remove_complete(struct mps_softc *, struct mps_command *);
+static void mpssas_action(struct cam_sim *sim, union ccb *ccb);
+static void mpssas_poll(struct cam_sim *sim);
+static void mpssas_probe_device(struct mps_softc *sc, uint16_t handle);
+static void mpssas_probe_device_complete(struct mps_softc *sc,
+     struct mps_config_params *params);
+static void mpssas_scsiio_timeout(void *data);
+static void mpssas_abort_complete(struct mps_softc *sc, struct mps_command *cm);
+static void mpssas_recovery(struct mps_softc *, struct mps_command *);
+static void mpssas_action_scsiio(struct mpssas_softc *, union ccb *);
+static void mpssas_scsiio_complete(struct mps_softc *, struct mps_command *);
+static int mpssas_resetdev(struct mpssas_softc *, struct mps_command *);
+static void mpssas_action_resetdev(struct mpssas_softc *, union ccb *);
+static void mpssas_resetdev_complete(struct mps_softc *, struct mps_command *);
+static void mpssas_freeze_device(struct mpssas_softc *, struct mpssas_target *);
+static void mpssas_unfreeze_device(struct mpssas_softc *, struct mpssas_target *) __unused;
+
+static struct mpssas_target *
+mpssas_alloc_target(struct mpssas_softc *sassc, struct mpssas_target *probe)
+{
+	struct mpssas_target *target;
+	int start;
+
+	mps_dprint(sassc->sc, MPS_TRACE, "%s\n", __func__);
+
+	/*
+	 * If it's not a sata or sas target, CAM won't be able to see it.  Put
+	 * it into a high-numbered slot so that it's accessible but not
+	 * interrupting the target numbering sequence of real drives.
+	 */
+	if ((probe->devinfo & (MPI2_SAS_DEVICE_INFO_SSP_TARGET |
+	    MPI2_SAS_DEVICE_INFO_STP_TARGET | MPI2_SAS_DEVICE_INFO_SATA_DEVICE))
+	    == 0) {
+		start = 200;
+	} else {
+		/*
+		 * Use the enclosure number and slot number as a hint for target
+		 * numbering.  If that doesn't produce a sane result, search the
+		 * entire space.
+		 */
+#if 0
+		start = probe->encl_handle * 16 + probe->encl_slot;
+#else
+		start = probe->encl_slot;
+#endif
+		if (start >= sassc->sc->facts->MaxTargets)
+			start = 0;
+	}
+
+	target = mpssas_find_target(sassc, start, 0);
+
+	/*
+	 * Nothing found on the first pass, try a second pass that searches the
+	 * entire space.
+	 */
+	if (target == NULL)
+		target = mpssas_find_target(sassc, 0, 0);
+
+	return (target);
+}
+
+static struct mpssas_target *
+mpssas_find_target(struct mpssas_softc *sassc, int start, uint16_t handle)
+{
+	struct mpssas_target *target;
+	int i;
+
+	for (i = start; i < sassc->sc->facts->MaxTargets; i++) {
+		target = &sassc->targets[i];
+		if (target->handle == handle)
+			return (target);
+	}
+
+	return (NULL);
+}
+
+/*
+ * Start the probe sequence for a given device handle.  This will not
+ * block.
+ */
+static void
+mpssas_probe_device(struct mps_softc *sc, uint16_t handle)
+{
+	struct mpssas_devprobe *probe;
+	struct mps_config_params *params;
+	MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
+	int error;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	probe = malloc(sizeof(*probe), M_MPSSAS, M_NOWAIT | M_ZERO);
+	if (probe == NULL) {
+		mps_dprint(sc, MPS_FAULT, "Out of memory starting probe\n");
+		return;
+	}
+	params = &probe->params;
+	hdr = ¶ms->hdr.Ext;
+
+	params->action = MPI2_CONFIG_ACTION_PAGE_HEADER;
+	params->page_address = MPI2_SAS_DEVICE_PGAD_FORM_HANDLE | handle;
+	hdr->ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_DEVICE;
+	hdr->ExtPageLength = 0;
+	hdr->PageNumber = 0;
+	hdr->PageVersion = 0;
+	params->buffer = NULL;
+	params->length = 0;
+	params->callback = mpssas_probe_device_complete;
+	params->cbdata = probe;
+	probe->target.handle = handle;
+	probe->state = MPSSAS_PROBE_DEV1;
+
+	if ((error = mps_read_config_page(sc, params)) != 0) {
+		free(probe, M_MPSSAS);
+		mps_dprint(sc, MPS_FAULT, "Failure starting device probe\n");
+		return;
+	}
+}
+
+static void
+mpssas_probe_device_complete(struct mps_softc *sc,
+    struct mps_config_params *params)
+{
+	MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
+	struct mpssas_devprobe *probe;
+	int error;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	hdr = ¶ms->hdr.Ext;
+	probe = params->cbdata;
+
+	switch (probe->state) {
+	case MPSSAS_PROBE_DEV1:
+	case MPSSAS_PROBE_PHY:
+	case MPSSAS_PROBE_EXP:
+		if (params->status != MPI2_IOCSTATUS_SUCCESS) {
+			mps_dprint(sc, MPS_FAULT,
+			    "Probe Failure 0x%x state %d\n", params->status,
+			    probe->state);
+			free(probe, M_MPSSAS);
+			return;
+		}
+		params->action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT;
+		params->length = hdr->ExtPageLength * 4;
+		params->buffer = malloc(params->length, M_MPSSAS,
+		    M_ZERO|M_NOWAIT);
+		if (params->buffer == NULL) {
+			mps_dprint(sc, MPS_FAULT, "Out of memory at state "
+			   "0x%x, size 0x%x\n", probe->state, params->length);
+			free(probe, M_MPSSAS);
+			return;
+		}
+		if (probe->state == MPSSAS_PROBE_DEV1)
+			probe->state = MPSSAS_PROBE_DEV2;
+		else if (probe->state == MPSSAS_PROBE_PHY)
+			probe->state = MPSSAS_PROBE_PHY2;
+		else if (probe->state == MPSSAS_PROBE_EXP)
+			probe->state = MPSSAS_PROBE_EXP2;
+		error = mps_read_config_page(sc, params);
+		break;
+	case MPSSAS_PROBE_DEV2:
+	{
+		MPI2_CONFIG_PAGE_SAS_DEV_0 *buf;
+
+		if (params->status != MPI2_IOCSTATUS_SUCCESS) {
+			mps_dprint(sc, MPS_FAULT,
+			    "Probe Failure 0x%x state %d\n", params->status,
+			    probe->state);
+			free(params->buffer, M_MPSSAS);
+			free(probe, M_MPSSAS);
+			return;
+		}
+		buf = params->buffer;
+		mps_print_sasdev0(sc, buf);
+
+		probe->target.devname = mps_to_u64(&buf->DeviceName);
+		probe->target.devinfo = buf->DeviceInfo;
+		probe->target.encl_handle = buf->EnclosureHandle;
+		probe->target.encl_slot = buf->Slot;
+
+		if (buf->DeviceInfo & MPI2_SAS_DEVICE_INFO_DIRECT_ATTACH) {
+			params->page_address =
+			    MPI2_SAS_PHY_PGAD_FORM_PHY_NUMBER | buf->PhyNum;
+			hdr->ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_PHY;
+			hdr->PageNumber = 0;
+			probe->state = MPSSAS_PROBE_PHY;
+		} else {
+			params->page_address =
+			    MPI2_SAS_EXPAND_PGAD_FORM_HNDL_PHY_NUM |
+			    buf->ParentDevHandle | (buf->PhyNum << 16);
+			hdr->ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_EXPANDER;
+			hdr->PageNumber = 1;
+			probe->state = MPSSAS_PROBE_EXP;
+		}
+		params->action = MPI2_CONFIG_ACTION_PAGE_HEADER;
+		hdr->ExtPageLength = 0;
+		hdr->PageVersion = 0;
+		params->buffer = NULL;
+		params->length = 0;
+		free(buf, M_MPSSAS);
+		error = mps_read_config_page(sc, params);
+		break;
+	}
+	case MPSSAS_PROBE_PHY2:
+	case MPSSAS_PROBE_EXP2:
+	{
+		MPI2_CONFIG_PAGE_SAS_PHY_0 *phy;
+		MPI2_CONFIG_PAGE_EXPANDER_1 *exp;
+		struct mpssas_softc *sassc;
+		struct mpssas_target *targ;
+		char devstring[80];
+		uint16_t handle;
+
+		if (params->status != MPI2_IOCSTATUS_SUCCESS) {
+			mps_dprint(sc, MPS_FAULT,
+			    "Probe Failure 0x%x state %d\n", params->status,
+			    probe->state);
+			free(params->buffer, M_MPSSAS);
+			free(probe, M_MPSSAS);
+			return;
+		}
+
+		if (probe->state == MPSSAS_PROBE_PHY2) {
+			phy = params->buffer;
+			mps_print_sasphy0(sc, phy);
+			probe->target.linkrate = phy->NegotiatedLinkRate & 0xf;
+		} else {
+			exp = params->buffer;
+			mps_print_expander1(sc, exp);
+			probe->target.linkrate = exp->NegotiatedLinkRate & 0xf;
+		}
+		free(params->buffer, M_MPSSAS);
+
+		sassc = sc->sassc;
+		handle = probe->target.handle;
+		if ((targ = mpssas_find_target(sassc, 0, handle)) != NULL) {
+			mps_printf(sc, "Ignoring dup device handle 0x%04x\n",
+			    handle);
+			free(probe, M_MPSSAS);
+			return;
+		}
+		if ((targ = mpssas_alloc_target(sassc, &probe->target)) == NULL) {
+			mps_printf(sc, "Target table overflow, handle 0x%04x\n",
+			    handle);
+			free(probe, M_MPSSAS);
+			return;
+		}
+
+		*targ = probe->target;	/* Copy the attributes */
+		targ->tid = targ - sassc->targets;
+		mps_describe_devinfo(targ->devinfo, devstring, 80);
+		if (bootverbose)
+			mps_printf(sc, "Found device <%s> <%s> <0x%04x> "
+			    "<%d/%d>\n", devstring,
+			    mps_describe_table(mps_linkrate_names,
+			    targ->linkrate), targ->handle, targ->encl_handle,
+			    targ->encl_slot);
+
+		free(probe, M_MPSSAS);
+		mpssas_announce_device(sassc, targ);
+		break;
+	}
+	default:
+		printf("what?\n");
+	}
+}
+
+/*
+ * The MPT2 firmware performs debounce on the link to avoid transient link errors
+ * and false removals.  When it does decide that link has been lost and a device
+ * need to go away, it expects that the host will perform a target reset and then
+ * an op remove.  The reset has the side-effect of aborting any outstanding
+ * requests for the device, which is required for the op-remove to succeed.  It's
+ * not clear if the host should check for the device coming back alive after the
+ * reset.
+ */
+static void
+mpssas_prepare_remove(struct mpssas_softc *sassc, MPI2_EVENT_SAS_TOPO_PHY_ENTRY *phy)
+{
+	MPI2_SCSI_TASK_MANAGE_REQUEST *req;
+	struct mps_softc *sc;
+	struct mps_command *cm;
+	struct mpssas_target *targ = NULL;
+	uint16_t handle;
+
+	mps_dprint(sassc->sc, MPS_TRACE, "%s\n", __func__);
+
+	handle = phy->AttachedDevHandle;
+	targ = mpssas_find_target(sassc, 0, handle);
+	if (targ == NULL)
+		/* We don't know about this device? */
+		return;
+
+	sc = sassc->sc;
+	cm = mps_alloc_command(sc);
+	if (cm == NULL) {
+		mps_printf(sc, "comand alloc failure in mpssas_prepare_remove\n");
+		return;
+	}
+
+	req = (MPI2_SCSI_TASK_MANAGE_REQUEST *)cm->cm_req;
+	req->DevHandle = targ->handle;
+	req->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
+	req->TaskType = MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
+
+	/* SAS Hard Link Reset / SATA Link Reset */
+	req->MsgFlags = MPI2_SCSITASKMGMT_MSGFLAGS_LINK_RESET;
+
+	cm->cm_data = NULL;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+	cm->cm_complete = mpssas_remove_device;
+	cm->cm_targ = targ;
+	mps_map_command(sc, cm);
+}
+
+static void
+mpssas_remove_device(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SCSI_TASK_MANAGE_REPLY *reply;
+	MPI2_SAS_IOUNIT_CONTROL_REQUEST *req;
+	struct mpssas_target *targ;
+	uint16_t handle;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	reply = (MPI2_SCSI_TASK_MANAGE_REPLY *)cm->cm_reply;
+	handle = cm->cm_targ->handle;
+	if (reply->IOCStatus != MPI2_IOCSTATUS_SUCCESS) {
+		mps_printf(sc, "Failure 0x%x reseting device 0x%04x\n", 
+		   reply->IOCStatus, handle);
+		mps_free_command(sc, cm);
+		return;
+	}
+
+	mps_printf(sc, "Reset aborted %d commands\n", reply->TerminationCount);
+	mps_free_reply(sc, cm->cm_reply_data);
+
+	/* Reuse the existing command */
+	req = (MPI2_SAS_IOUNIT_CONTROL_REQUEST *)cm->cm_req;
+	req->Function = MPI2_FUNCTION_SAS_IO_UNIT_CONTROL;
+	req->Operation = MPI2_SAS_OP_REMOVE_DEVICE;
+	req->DevHandle = handle;
+	cm->cm_data = NULL;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+	cm->cm_flags &= ~MPS_CM_FLAGS_COMPLETE;
+	cm->cm_complete = mpssas_remove_complete;
+
+	mps_map_command(sc, cm);
+
+	mps_dprint(sc, MPS_INFO, "clearing target handle 0x%04x\n", handle);
+	targ = mpssas_find_target(sc->sassc, 0, handle);
+	if (targ != NULL) {
+		targ->handle = 0x0;
+		mpssas_announce_device(sc->sassc, targ);
+	}
+}
+
+static void
+mpssas_remove_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SAS_IOUNIT_CONTROL_REPLY *reply;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	reply = (MPI2_SAS_IOUNIT_CONTROL_REPLY *)cm->cm_reply;
+
+	mps_printf(sc, "mpssas_remove_complete on target 0x%04x,"
+	   " IOCStatus= 0x%x\n", cm->cm_targ->tid, reply->IOCStatus);
+
+	mps_free_command(sc, cm);
+}
+
+static void
+mpssas_evt_handler(struct mps_softc *sc, uintptr_t data,
+    MPI2_EVENT_NOTIFICATION_REPLY *event)
+{
+	struct mpssas_softc *sassc;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	sassc = sc->sassc;
+	mps_print_evt_sas(sc, event);
+
+	switch (event->Event) {
+	case MPI2_EVENT_SAS_DISCOVERY:
+	{
+		MPI2_EVENT_DATA_SAS_DISCOVERY *data;
+
+		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)&event->EventData;
+
+		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_STARTED)
+			mps_dprint(sc, MPS_TRACE,"SAS discovery start event\n");
+		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_COMPLETED) {
+			mps_dprint(sc, MPS_TRACE, "SAS discovery end event\n");
+			sassc->flags &= ~MPSSAS_IN_DISCOVERY;
+			mpssas_discovery_end(sassc);
+		}
+		break;
+	}
+	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
+	{
+		MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *data;
+		MPI2_EVENT_SAS_TOPO_PHY_ENTRY *phy;
+		int i;
+
+		data = (MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *)
+		    &event->EventData;
+
+		if (data->ExpStatus == MPI2_EVENT_SAS_TOPO_ES_ADDED) {
+			if (bootverbose)
+				printf("Expander found at enclosure %d\n",
+				    data->EnclosureHandle);
+			mpssas_probe_device(sc, data->ExpanderDevHandle);
+		}
+
+		for (i = 0; i < data->NumEntries; i++) {
+			phy = &data->PHY[i];
+			switch (phy->PhyStatus & MPI2_EVENT_SAS_TOPO_RC_MASK) {
+			case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
+				mpssas_probe_device(sc, phy->AttachedDevHandle);
+				break;
+			case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
+				mpssas_prepare_remove(sassc, phy);
+				break;
+			case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
+			case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
+			case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
+			default:
+				break;
+			}
+		}
+
+		break;
+	}
+	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
+		break;
+	default:
+		break;
+	}
+
+	mps_free_reply(sc, data);
+}
+
+static int
+mpssas_register_events(struct mps_softc *sc)
+{
+	uint8_t events[16];
+
+	bzero(events, 16);
+	setbit(events, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
+	setbit(events, MPI2_EVENT_SAS_DISCOVERY);
+	setbit(events, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
+	setbit(events, MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE);
+	setbit(events, MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW);
+	setbit(events, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
+	setbit(events, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
+
+	mps_register_events(sc, events, mpssas_evt_handler, NULL,
+	    &sc->sassc->mpssas_eh);
+
+	return (0);
+}
+
+int
+mps_attach_sas(struct mps_softc *sc)
+{
+	struct mpssas_softc *sassc;
+	int error = 0;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	sassc = malloc(sizeof(struct mpssas_softc), M_MPT2, M_WAITOK|M_ZERO);
+	sassc->targets = malloc(sizeof(struct mpssas_target) *
+	    sc->facts->MaxTargets, M_MPT2, M_WAITOK|M_ZERO);
+	sc->sassc = sassc;
+	sassc->sc = sc;
+
+	if ((sassc->devq = cam_simq_alloc(sc->num_reqs)) == NULL) {
+		mps_dprint(sc, MPS_FAULT, "Cannot allocate SIMQ\n");
+		error = ENOMEM;
+		goto out;
+	}
+
+	sassc->sim = cam_sim_alloc(mpssas_action, mpssas_poll, "mps", sassc,
+	    device_get_unit(sc->mps_dev), &sc->mps_mtx, sc->num_reqs, sc->num_reqs,
+	    sassc->devq);
+	if (sassc->sim == NULL) {
+		mps_dprint(sc, MPS_FAULT, "Cannot allocate SIM\n");
+		error = EINVAL;
+		goto out;
+	}
+
+	/*
+	 * XXX There should be a bus for every port on the adapter, but since
+	 * we're just going to fake the topology for now, we'll pretend that
+	 * everything is just a target on a single bus.
+	 */
+	mps_lock(sc);
+	if ((error = xpt_bus_register(sassc->sim, sc->mps_dev, 0)) != 0) {
+		mps_dprint(sc, MPS_FAULT, "Error %d registering SCSI bus\n",
+		    error);
+		mps_unlock(sc);
+		goto out;
+	}
+
+	/*
+	 * Assume that discovery events will start right away.  Freezing
+	 * the simq will prevent the CAM boottime scanner from running
+	 * before discovery is complete.
+	 */
+	sassc->flags = MPSSAS_IN_STARTUP | MPSSAS_IN_DISCOVERY;
+	xpt_freeze_simq(sassc->sim, 1);
+
+	mps_unlock(sc);
+
+	callout_init(&sassc->discovery_callout, 1 /*mpsafe*/);
+	sassc->discovery_timeouts = 0;
+
+	mpssas_register_events(sc);
+out:
+	if (error)
+		mps_detach_sas(sc);
+	return (error);
+}
+
+int
+mps_detach_sas(struct mps_softc *sc)
+{
+	struct mpssas_softc *sassc;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	if (sc->sassc == NULL)
+		return (0);
+
+	sassc = sc->sassc;
+
+	/* Make sure CAM doesn't wedge if we had to bail out early. */
+	mps_lock(sc);
+	if (sassc->flags & MPSSAS_IN_STARTUP)
+		xpt_release_simq(sassc->sim, 1);
+	mps_unlock(sc);
+
+	if (sassc->mpssas_eh != NULL)
+		mps_deregister_events(sc, sassc->mpssas_eh);
+
+	mps_lock(sc);
+
+	if (sassc->sim != NULL) {
+		xpt_bus_deregister(cam_sim_path(sassc->sim));
+		cam_sim_free(sassc->sim, FALSE);
+	}
+	mps_unlock(sc);
+
+	if (sassc->devq != NULL)
+		cam_simq_free(sassc->devq);
+
+	free(sassc->targets, M_MPT2);
+	free(sassc, M_MPT2);
+	sc->sassc = NULL;
+
+	return (0);
+}
+
+static void
+mpssas_discovery_end(struct mpssas_softc *sassc)
+{
+	struct mps_softc *sc = sassc->sc;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	if (sassc->flags & MPSSAS_DISCOVERY_TIMEOUT_PENDING)
+		callout_stop(&sassc->discovery_callout);
+
+	if ((sassc->flags & MPSSAS_IN_STARTUP) != 0) {
+		mps_dprint(sc, MPS_INFO,
+		    "mpssas_discovery_end: removing confighook\n");
+		sassc->flags &= ~MPSSAS_IN_STARTUP;
+		xpt_release_simq(sassc->sim, 1);
+	}
+#if 0
+	mpssas_announce_device(sassc, NULL);
+#endif
+
+}
+
+static void
+mpssas_announce_device(struct mpssas_softc *sassc, struct mpssas_target *targ)
+{
+	union ccb *ccb;
+	int bus, tid, lun;
+
+	/*
+	 * Force a rescan, a hackish way to announce devices.
+	 * XXX Doing a scan on an individual device is hackish in that it
+	 *     won't scan the LUNs.
+	 * XXX Does it matter if any of this fails?
+	 */
+	bus = cam_sim_path(sassc->sim);
+	if (targ != NULL) {
+		tid = targ->tid;
+		lun = 0;
+	} else {
+		tid = CAM_TARGET_WILDCARD;
+		lun = CAM_LUN_WILDCARD;
+	}
+	ccb = xpt_alloc_ccb_nowait();
+	if (ccb == NULL)
+		return;
+	if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, bus, tid,
+	    CAM_LUN_WILDCARD) != CAM_REQ_CMP) { 
+		xpt_free_ccb(ccb);
+		return;
+	}
+	mps_dprint(sassc->sc, MPS_INFO, "Triggering rescan of %d:%d:-1\n",
+	    bus, tid);
+	xpt_rescan(ccb);
+}
+
+static void
+mpssas_startup(void *data)
+{
+	struct mpssas_softc *sassc = data;
+
+	mps_dprint(sassc->sc, MPS_TRACE, "%s\n", __func__);
+
+	mps_lock(sassc->sc);
+	if ((sassc->flags & MPSSAS_IN_DISCOVERY) == 0) {
+		mpssas_discovery_end(sassc);
+	} else {
+		if (sassc->discovery_timeouts < MPSSAS_MAX_DISCOVERY_TIMEOUTS) {
+			sassc->flags |= MPSSAS_DISCOVERY_TIMEOUT_PENDING;
+			callout_reset(&sassc->discovery_callout,
+			    MPSSAS_DISCOVERY_TIMEOUT * hz,
+			    mpssas_discovery_timeout, sassc);
+			sassc->discovery_timeouts++;
+		} else {
+			mps_dprint(sassc->sc, MPS_FAULT,
+			    "Discovery timed out, continuing.\n");
+			sassc->flags &= ~MPSSAS_IN_DISCOVERY;
+			mpssas_discovery_end(sassc);
+		}
+	}
+	mps_unlock(sassc->sc);
+
+	return;
+}
+
+static void
+mpssas_discovery_timeout(void *data)
+{
+	struct mpssas_softc *sassc = data;
+	struct mps_softc *sc;
+
+	sc = sassc->sc;
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	mps_lock(sc);
+	mps_printf(sc,
+	    "Timeout waiting for discovery, interrupts may not be working!\n");
+	sassc->flags &= ~MPSSAS_DISCOVERY_TIMEOUT_PENDING;
+
+	/* Poll the hardware for events in case interrupts aren't working */
+	mps_intr_locked(sc);
+	mps_unlock(sc);
+
+	/* Check the status of discovery and re-arm the timeout if needed */
+	mpssas_startup(sassc);
+}
+
+static void
+mpssas_action(struct cam_sim *sim, union ccb *ccb)
+{
+	struct mpssas_softc *sassc;
+
+	sassc = cam_sim_softc(sim);
+
+	mps_dprint(sassc->sc, MPS_TRACE, "%s func 0x%x\n", __func__,
+	    ccb->ccb_h.func_code);
+
+	switch (ccb->ccb_h.func_code) {
+	case XPT_PATH_INQ:
+	{
+		struct ccb_pathinq *cpi = &ccb->cpi;
+
+		cpi->version_num = 1;
+		cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
+		cpi->target_sprt = 0;
+		cpi->hba_misc = PIM_NOBUSRESET;
+		cpi->hba_eng_cnt = 0;
+		cpi->max_target = sassc->sc->facts->MaxTargets - 1;
+		cpi->max_lun = 0;
+		cpi->initiator_id = 255;
+		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
+		strncpy(cpi->hba_vid, "LSILogic", HBA_IDLEN);
+		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
+		cpi->unit_number = cam_sim_unit(sim);
+		cpi->bus_id = cam_sim_bus(sim);
+		cpi->base_transfer_speed = 150000;
+		cpi->transport = XPORT_SAS;
+		cpi->transport_version = 0;
+		cpi->protocol = PROTO_SCSI;
+		cpi->protocol_version = SCSI_REV_SPC;
+		cpi->ccb_h.status = CAM_REQ_CMP;
+		break;
+	}
+	case XPT_GET_TRAN_SETTINGS:
+	{
+		struct ccb_trans_settings	*cts;
+		struct ccb_trans_settings_sas	*sas;
+		struct ccb_trans_settings_scsi	*scsi;
+		struct mpssas_target *targ;
+
+		cts = &ccb->cts;
+		sas = &cts->xport_specific.sas;
+		scsi = &cts->proto_specific.scsi;
+
+		targ = &sassc->targets[cts->ccb_h.target_id];
+		if (targ->handle == 0x0) {
+			cts->ccb_h.status = CAM_TID_INVALID;
+			break;
+		}
+
+		cts->protocol_version = SCSI_REV_SPC2;
+		cts->transport = XPORT_SAS;
+		cts->transport_version = 0;
+
+		sas->valid = CTS_SAS_VALID_SPEED;
+		switch (targ->linkrate) {
+		case 0x08:
+			sas->bitrate = 150000;
+			break;
+		case 0x09:
+			sas->bitrate = 300000;
+			break;
+		case 0x0a:
+			sas->bitrate = 600000;
+			break;
+		default:
+			sas->valid = 0;
+		}
+
+		cts->protocol = PROTO_SCSI;
+		scsi->valid = CTS_SCSI_VALID_TQ;
+		scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
+
+		cts->ccb_h.status = CAM_REQ_CMP;
+		break;
+	}
+	case XPT_CALC_GEOMETRY:
+		cam_calc_geometry(&ccb->ccg, /*extended*/1);
+		ccb->ccb_h.status = CAM_REQ_CMP;
+		break;
+	case XPT_RESET_DEV:
+		mpssas_action_resetdev(sassc, ccb);
+		return;
+	case XPT_RESET_BUS:
+	case XPT_ABORT:
+	case XPT_TERM_IO:
+		ccb->ccb_h.status = CAM_REQ_CMP;
+		break;
+	case XPT_SCSI_IO:
+		mpssas_action_scsiio(sassc, ccb);
+		return;
+	default:
+		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
+		break;
+	}
+	xpt_done(ccb);
+
+}
+
+#if 0
+static void
+mpssas_resettimeout_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SCSI_TASK_MANAGE_REPLY *resp;
+	uint16_t code;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	resp = (MPI2_SCSI_TASK_MANAGE_REPLY *)cm->cm_reply;
+	code = resp->ResponseCode;
+
+	mps_free_command(sc, cm);
+	mpssas_unfreeze_device(sassc, targ);
+
+	if (code != MPI2_SCSITASKMGMT_RSP_TM_COMPLETE) {
+		mps_reset_controller(sc);
+	}
+
+	return;
+}
+#endif
+
+static void
+mpssas_scsiio_timeout(void *data)
+{
+	union ccb *ccb;
+	struct mps_softc *sc;
+	struct mps_command *cm;
+	struct mpssas_target *targ;
+
+	cm = (struct mps_command *)data;
+	sc = cm->cm_sc;
+
+	/*
+	 * Run the interrupt handler to make sure it's not pending.  This
+	 * isn't perfect because the command could have already completed
+	 * and been re-used, though this is unlikely.
+	 */
+	mps_lock(sc);
+	mps_intr_locked(sc);
+	if (cm->cm_state == MPS_CM_STATE_FREE) {
+		mps_unlock(sc);
+		return;
+	}
+
+	ccb = cm->cm_complete_data;
+	targ = cm->cm_targ;
+	if (targ == 0x00)
+		/* Driver bug */
+		targ = &sc->sassc->targets[ccb->ccb_h.target_id];
+
+	xpt_print(ccb->ccb_h.path, "SCSI command timeout on device handle "
+		  "0x%04x SMID %d\n", targ->handle, cm->cm_desc.Default.SMID);
+
+	/* Inform CAM about the timeout and that recovery is starting. */
+#if 0
+	if ((targ->flags & MPSSAS_TARGET_INRECOVERY) == 0) {
+		mpssas_freeze_device(sc->sassc, targ);
+		ccb->ccb_h.status = CAM_CMD_TIMEOUT;
+		xpt_done(ccb);
+	}
+#endif
+	mpssas_freeze_device(sc->sassc, targ);
+	ccb->ccb_h.status = CAM_CMD_TIMEOUT;
+
+	/*
+	 * recycle the command into recovery so that there's no risk of
+	 * command allocation failure.
+	 */
+	cm->cm_state = MPS_CM_STATE_TIMEDOUT;
+	mpssas_recovery(sc, cm);
+	mps_unlock(sc);
+}
+
+static void
+mpssas_abort_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SCSI_TASK_MANAGE_REQUEST *req;
+
+	req = (MPI2_SCSI_TASK_MANAGE_REQUEST *)cm->cm_req;
+
+	mps_printf(sc, "%s: abort request on handle %#04x SMID %d "
+		   "complete\n", __func__, req->DevHandle, req->TaskMID);
+
+	mps_free_command(sc, cm);
+}
+
+static void
+mpssas_recovery(struct mps_softc *sc, struct mps_command *abort_cm)
+{
+	struct mps_command *cm;
+	MPI2_SCSI_TASK_MANAGE_REQUEST *req, *orig_req;
+	int error;
+
+	cm = mps_alloc_command(sc);
+	if (cm == NULL) {
+		mps_printf(sc, "%s: command allocation failure\n", __func__);
+		return;
+	}
+
+	cm->cm_targ = abort_cm->cm_targ;
+	cm->cm_complete = mpssas_abort_complete;
+
+	req = (MPI2_SCSI_TASK_MANAGE_REQUEST *)cm->cm_req;
+	orig_req = (MPI2_SCSI_TASK_MANAGE_REQUEST *)abort_cm->cm_req;
+	req->DevHandle = abort_cm->cm_targ->handle;
+	req->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
+	req->TaskType = MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK;
+	memcpy(req->LUN, orig_req->LUN, sizeof(req->LUN));
+	req->TaskMID = abort_cm->cm_desc.Default.SMID;
+
+	cm->cm_data = NULL;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+
+	error = mps_map_command(sc, cm);
+
+	if (error != 0) {
+		mps_printf(sc, "%s: error mapping abort request!\n", __func__);
+	}
+#if 0
+	error = mpssas_reset(sc, targ, &resetcm);
+	if ((error != 0) && (error != EBUSY)) {
+		mps_printf(sc, "Error resetting device!\n");
+		mps_unlock(sc);
+		return;
+	}
+
+	targ->flags |= MPSSAS_TARGET_INRESET;
+
+	cm->cm_complete = mpssas_resettimeout_complete;
+	cm->cm_complete_data = cm;
+	mps_map_command(sassc->sc, cm);
+#endif
+}
+
+static void
+mpssas_action_scsiio(struct mpssas_softc *sassc, union ccb *ccb)
+{
+	MPI2_SCSI_IO_REQUEST *req;
+	struct ccb_scsiio *csio;
+	struct mps_softc *sc;
+	struct mpssas_target *targ;
+	struct mps_command *cm;
+
+	mps_dprint(sassc->sc, MPS_TRACE, "%s\n", __func__);
+
+	sc = sassc->sc;
+
+	csio = &ccb->csio;
+	targ = &sassc->targets[csio->ccb_h.target_id];
+	if (targ->handle == 0x0) {
+		csio->ccb_h.status = CAM_SEL_TIMEOUT;
+		xpt_done(ccb);
+		return;
+	}
+
+	cm = mps_alloc_command(sc);
+	if (cm == NULL) {
+		if ((sassc->flags & MPSSAS_QUEUE_FROZEN) == 0) {
+			xpt_freeze_simq(sassc->sim, 1);
+			sassc->flags |= MPSSAS_QUEUE_FROZEN;
+		}
+		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
+		ccb->ccb_h.status |= CAM_REQUEUE_REQ;
+		xpt_done(ccb);
+		return;
+	}
+
+	req = (MPI2_SCSI_IO_REQUEST *)cm->cm_req;
+	req->DevHandle = targ->handle;
+	req->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
+	req->MsgFlags = 0;
+	req->SenseBufferLowAddress = cm->cm_sense_busaddr;
+	req->SenseBufferLength = MPS_SENSE_LEN;
+	req->SGLFlags = 0;
+	req->ChainOffset = 0;
+	req->SGLOffset0 = 24;	/* 32bit word offset to the SGL */
+	req->SGLOffset1= 0;
+	req->SGLOffset2= 0;
+	req->SGLOffset3= 0;
+	req->SkipCount = 0;
+	req->DataLength = csio->dxfer_len;
+	req->BidirectionalDataLength = 0;
+	req->IoFlags = csio->cdb_len;
+	req->EEDPFlags = 0;
+
+	/* Note: BiDirectional transfers are not supported */
+	switch (csio->ccb_h.flags & CAM_DIR_MASK) {
+	case CAM_DIR_IN:
+		req->Control = MPI2_SCSIIO_CONTROL_READ;
+		cm->cm_flags |= MPS_CM_FLAGS_DATAIN;
+		break;
+	case CAM_DIR_OUT:
+		req->Control = MPI2_SCSIIO_CONTROL_WRITE;
+		cm->cm_flags |= MPS_CM_FLAGS_DATAOUT;
+		break;
+	case CAM_DIR_NONE:
+	default:
+		req->Control = MPI2_SCSIIO_CONTROL_NODATATRANSFER;
+		break;
+	}
+
+	/*
+	 * It looks like the hardware doesn't require an explicit tag
+	 * number for each transaction.  SAM Task Management not supported
+	 * at the moment.
+	 */
+	switch (csio->tag_action) {
+	case MSG_HEAD_OF_Q_TAG:
+		req->Control |= MPI2_SCSIIO_CONTROL_HEADOFQ;
+		break;
+	case MSG_ORDERED_Q_TAG:
+		req->Control |= MPI2_SCSIIO_CONTROL_ORDEREDQ;
+		break;
+	case MSG_ACA_TASK:
+		req->Control |= MPI2_SCSIIO_CONTROL_ACAQ;
+		break;
+	case CAM_TAG_ACTION_NONE:
+	case MSG_SIMPLE_Q_TAG:
+	default:
+		req->Control |= MPI2_SCSIIO_CONTROL_SIMPLEQ;
+		break;
+	}
+
+	/* XXX Need to handle multi-level LUNs */
+	if (csio->ccb_h.target_lun > 255) {
+		mps_free_command(sc, cm);
+		ccb->ccb_h.status = CAM_LUN_INVALID;
+		xpt_done(ccb);
+		return;
+	}
+	req->LUN[1] = csio->ccb_h.target_lun;
+
+	if (csio->ccb_h.flags & CAM_CDB_POINTER)
+		bcopy(csio->cdb_io.cdb_ptr, &req->CDB.CDB32[0], csio->cdb_len);
+	else
+		bcopy(csio->cdb_io.cdb_bytes, &req->CDB.CDB32[0],csio->cdb_len);
+	req->IoFlags = csio->cdb_len;
+
+	cm->cm_data = csio->data_ptr;
+	cm->cm_length = csio->dxfer_len;
+	cm->cm_sge = &req->SGL;
+	cm->cm_sglsize = (32 - 24) * 4;
+	cm->cm_desc.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
+	cm->cm_desc.SCSIIO.DevHandle = targ->handle;
+	cm->cm_complete = mpssas_scsiio_complete;
+	cm->cm_complete_data = ccb;
+	cm->cm_targ = targ;
+
+	callout_reset(&cm->cm_callout, (ccb->ccb_h.timeout * hz) / 1000,
+	   mpssas_scsiio_timeout, cm);
+
+	mps_map_command(sc, cm);
+	return;
+}
+
+static void
+mpssas_scsiio_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SCSI_IO_REPLY *rep;
+	union ccb *ccb;
+	struct mpssas_softc *sassc;
+	u_int sense_len;
+	int dir = 0;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	callout_stop(&cm->cm_callout);
+
+	sassc = sc->sassc;
+	ccb = cm->cm_complete_data;
+	rep = (MPI2_SCSI_IO_REPLY *)cm->cm_reply;
+
+	if (cm->cm_data != NULL) {
+		if (cm->cm_flags & MPS_CM_FLAGS_DATAIN)
+			dir = BUS_DMASYNC_POSTREAD;
+		else if (cm->cm_flags & MPS_CM_FLAGS_DATAOUT)
+			dir = BUS_DMASYNC_POSTWRITE;;
+		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
+		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
+	}
+
+	if (sassc->flags & MPSSAS_QUEUE_FROZEN) {
+		ccb->ccb_h.flags |= CAM_RELEASE_SIMQ;
+		sassc->flags &= ~MPSSAS_QUEUE_FROZEN;
+	}
+
+	/* Take the fast path to completion */
+	if (cm->cm_reply == NULL) {
+		ccb->ccb_h.status = CAM_REQ_CMP;
+		ccb->csio.scsi_status = SCSI_STATUS_OK;
+		mps_free_command(sc, cm);
+		xpt_done(ccb);
+		return;
+	}
+
+	mps_dprint(sc, MPS_INFO, "(%d:%d:%d) IOCStatus= 0x%x, "
+	    "ScsiStatus= 0x%x, SCSIState= 0x%x TransferCount= 0x%x\n",
+	    xpt_path_path_id(ccb->ccb_h.path),
+	    xpt_path_target_id(ccb->ccb_h.path),
+	    xpt_path_lun_id(ccb->ccb_h.path), rep->IOCStatus,
+	    rep->SCSIStatus, rep->SCSIState, rep->TransferCount);
+
+	switch (rep->IOCStatus & MPI2_IOCSTATUS_MASK) {
+	case MPI2_IOCSTATUS_BUSY:
+	case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
+		/*
+		 * The controller is overloaded, try waiting a bit for it
+		 * to free up.
+		 */
+		ccb->ccb_h.status = CAM_BUSY;
+		break;
+	case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
+		ccb->csio.resid = cm->cm_length - rep->TransferCount;
+		/* FALLTHROUGH */
+	case MPI2_IOCSTATUS_SUCCESS:
+	case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
+		ccb->ccb_h.status = CAM_REQ_CMP;
+		break;
+	case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
+		/*
+		 * XXX any way to report this?
+		 */
+		ccb->csio.resid = 0;
+		ccb->ccb_h.status = CAM_REQ_CMP;
+		break;
+	case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
+	case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
+		ccb->ccb_h.status = CAM_DEV_NOT_THERE;
+		break;
+	case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
+		/*
+		 * This is one of the responses that comes back when an I/O
+		 * has been aborted.  If it is because of a timeout that we
+		 * initiated, just set the status to CAM_CMD_TIMEOUT.
+		 * Otherwise set it to CAM_REQ_ABORTED.  The effect on the
+		 * command is the same (it gets retried, subject to the
+		 * retry counter), the only difference is what gets printed
+		 * on the console.
+		 */
+		if (cm->cm_state == MPS_CM_STATE_TIMEDOUT)
+			ccb->ccb_h.status = CAM_CMD_TIMEOUT;
+		else
+			ccb->ccb_h.status = CAM_REQ_ABORTED;
+		break;
+	case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
+	case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
+		ccb->ccb_h.status = CAM_REQ_ABORTED;
+		break;
+	case MPI2_IOCSTATUS_INVALID_SGL:
+		mps_print_scsiio_cmd(sc, cm);
+		ccb->ccb_h.status = CAM_UNREC_HBA_ERROR;
+		break;
+	case MPI2_IOCSTATUS_INVALID_FUNCTION:
+	case MPI2_IOCSTATUS_INTERNAL_ERROR:
+	case MPI2_IOCSTATUS_INVALID_VPID:
+	case MPI2_IOCSTATUS_INVALID_FIELD:
+	case MPI2_IOCSTATUS_INVALID_STATE:
+	case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
+	case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
+	case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
+	case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
+	case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
+	default:
+		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
+	}
+
+
+	if ((rep->SCSIState & MPI2_SCSI_STATE_NO_SCSI_STATUS) == 0) {
+		ccb->csio.scsi_status = rep->SCSIStatus;
+
+		switch (rep->SCSIStatus) {
+		case MPI2_SCSI_STATUS_TASK_SET_FULL:
+		case MPI2_SCSI_STATUS_CHECK_CONDITION:
+			ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
+			break;
+		case MPI2_SCSI_STATUS_COMMAND_TERMINATED:
+		case MPI2_SCSI_STATUS_TASK_ABORTED:
+			ccb->ccb_h.status = CAM_REQ_ABORTED;
+			break;
+		case MPI2_SCSI_STATUS_GOOD:
+		default:
+			break;
+		}
+	}
+
+	if (rep->SCSIState & MPI2_SCSI_STATE_AUTOSENSE_VALID) {
+		sense_len = MIN(rep->SenseCount,
+		    sizeof(struct scsi_sense_data));
+		if (sense_len < rep->SenseCount)
+			ccb->csio.sense_resid = rep->SenseCount - sense_len;
+		bcopy(cm->cm_sense, &ccb->csio.sense_data, sense_len);
+		ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
+	}
+
+	if (rep->SCSIState & MPI2_SCSI_STATE_AUTOSENSE_FAILED)
+		ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
+
+	if (rep->SCSIState & MPI2_SCSI_STATE_RESPONSE_INFO_VALID)
+		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
+
+	mps_free_command(sc, cm);
+	xpt_done(ccb);
+}
+
+static void
+mpssas_action_resetdev(struct mpssas_softc *sassc, union ccb *ccb)
+{
+	struct mps_softc *sc;
+	struct mps_command *cm;
+	struct mpssas_target *targ;
+	int error;
+
+	sc = sassc->sc;
+	targ = &sassc->targets[ccb->ccb_h.target_id];
+
+	if (targ->flags & MPSSAS_TARGET_INRECOVERY) {
+		ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
+		xpt_done(ccb);
+		return;
+	}
+
+	cm = mps_alloc_command(sc);
+	if (cm == NULL) {
+		mps_printf(sc, "mpssas_action_resetdev: cannot alloc command\n");
+		ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
+		xpt_done(ccb);
+		return;
+	}
+
+	cm->cm_targ = targ;
+	cm->cm_complete = mpssas_resetdev_complete;
+	cm->cm_complete_data = ccb;
+
+	error = mpssas_resetdev(sassc, cm);
+	if (error) {
+		ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
+		xpt_done(ccb);
+		return;
+	}
+}
+
+static int
+mpssas_resetdev(struct mpssas_softc *sassc, struct mps_command *cm)
+{
+	MPI2_SCSI_TASK_MANAGE_REQUEST *req;
+	struct mps_softc *sc;
+	int error;
+
+	mps_dprint(sassc->sc, MPS_TRACE, "%s\n", __func__);
+
+	sc = sassc->sc;
+
+	req = (MPI2_SCSI_TASK_MANAGE_REQUEST *)cm->cm_req;
+	req->DevHandle = cm->cm_targ->handle;
+	req->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
+	req->TaskType = MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
+
+	/* SAS Hard Link Reset / SATA Link Reset */
+	req->MsgFlags = MPI2_SCSITASKMGMT_MSGFLAGS_LINK_RESET;
+
+	cm->cm_data = NULL;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+
+	error = mps_map_command(sassc->sc, cm);
+	return (error);
+}
+
+static void
+mpssas_resetdev_complete(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SCSI_TASK_MANAGE_REPLY *resp;
+	union ccb *ccb;
+
+	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
+
+	resp = (MPI2_SCSI_TASK_MANAGE_REPLY *)cm->cm_reply;
+	ccb = cm->cm_complete_data;
+
+	printf("resetdev complete IOCStatus= 0x%x ResponseCode= 0x%x\n",
+	    resp->IOCStatus, resp->ResponseCode);
+
+	if (resp->ResponseCode == MPI2_SCSITASKMGMT_RSP_TM_COMPLETE)
+		ccb->ccb_h.status = CAM_REQ_CMP;
+	else
+		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
+
+	mps_free_command(sc, cm);
+	xpt_done(ccb);
+}
+
+static void
+mpssas_poll(struct cam_sim *sim)
+{
+	struct mpssas_softc *sassc;
+
+	sassc = cam_sim_softc(sim);
+	mps_intr_locked(sassc->sc);
+}
+
+static void
+mpssas_freeze_device(struct mpssas_softc *sassc, struct mpssas_target *targ)
+{
+}
+
+static void
+mpssas_unfreeze_device(struct mpssas_softc *sassc, struct mpssas_target *targ)
+{
+}
+
diff --git a/sys/dev/mps/mps_table.c b/sys/dev/mps/mps_table.c
new file mode 100644
index 00000000000..55110a182e6
--- /dev/null
+++ b/sys/dev/mps/mps_table.c
@@ -0,0 +1,493 @@
+/*-
+ * Copyright (c) 2009 Yahoo! Inc.
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+/* Debugging tables for MPT2 */
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+char *
+mps_describe_table(struct mps_table_lookup *table, u_int code)
+{
+	int i;
+
+	for (i = 0; table[i].string != NULL; i++) {
+		if (table[i].code == code)
+			return(table[i].string);
+	}
+	return(table[i+1].string);
+}
+
+struct mps_table_lookup mps_event_names[] = {
+	{"LogData",			0x01},
+	{"StateChange",			0x02},
+	{"HardResetReceived",		0x05},
+	{"EventChange",			0x0a},
+	{"TaskSetFull",			0x0e},
+	{"SasDeviceStatusChange",	0x0f},
+	{"IrOperationStatus",		0x14},
+	{"SasDiscovery",		0x16},
+	{"SasBroadcastPrimitive",	0x17},
+	{"SasInitDeviceStatusChange",	0x18},
+	{"SasInitTableOverflow",	0x19},
+	{"SasTopologyChangeList",	0x1c},
+	{"SasEnclDeviceStatusChange",	0x1d},
+	{"IrVolume",			0x1e},
+	{"IrPhysicalDisk",		0x1f},
+	{"IrConfigurationChangeList",	0x20},
+	{"LogEntryAdded",		0x21},
+	{"SasPhyCounter",		0x22},
+	{"GpioInterrupt",		0x23},
+	{"HbdPhyEvent",			0x24},
+	{NULL, 0},
+	{"Unknown Event", 0}
+};
+
+struct mps_table_lookup mps_phystatus_names[] = {
+	{"NewTargetAdded",		0x01},
+	{"TargetGone",			0x02},
+	{"PHYLinkStatusChange",		0x03},
+	{"PHYLinkStatusUnchanged",	0x04},
+	{"TargetMissing",		0x05},
+	{NULL, 0},
+	{"Unknown Status", 0}
+};
+
+struct mps_table_lookup mps_linkrate_names[] = {
+	{"PHY disabled",		0x01},
+	{"Speed Negotiation Failed",	0x02},
+	{"SATA OOB Complete",		0x03},
+	{"SATA Port Selector",		0x04},
+	{"SMP Reset in Progress",	0x05},
+	{"1.5Gbps",			0x08},
+	{"3.0Gbps",			0x09},
+	{"6.0Gbps",			0x0a},
+	{NULL, 0},
+	{"LinkRate Unknown",		0x00}
+};
+
+struct mps_table_lookup mps_sasdev0_devtype[] = {
+	{"End Device",			0x01},
+	{"Edge Expander",		0x02},
+	{"Fanout Expander",		0x03},
+	{NULL, 0},
+	{"No Device",			0x00}
+};
+
+struct mps_table_lookup mps_phyinfo_reason_names[] = {
+	{"Power On",			0x01},
+	{"Hard Reset",			0x02},
+	{"SMP Phy Control Link Reset",	0x03},
+	{"Loss DWORD Sync",		0x04},
+	{"Multiplex Sequence",		0x05},
+	{"I-T Nexus Loss Timer",	0x06},
+	{"Break Timeout Timer",		0x07},
+	{"PHY Test Function",		0x08},
+	{NULL, 0},
+	{"Unknown Reason",		0x00}
+};
+
+struct mps_table_lookup mps_whoinit_names[] = {
+	{"System BIOS",			0x01},
+	{"ROM BIOS",			0x02},
+	{"PCI Peer",			0x03},
+	{"Host Driver",			0x04},
+	{"Manufacturing",		0x05},
+	{NULL, 0},
+	{"Not Initialized",		0x00}
+};
+
+struct mps_table_lookup mps_sasdisc_reason[] = {
+	{"Discovery Started",		0x01},
+	{"Discovery Complete",		0x02},
+	{NULL, 0},
+	{"Unknown",			0x00}
+};
+
+struct mps_table_lookup mps_sastopo_exp[] = {
+	{"Added",			0x01},
+	{"Not Responding",		0x02},
+	{"Responding",			0x03},
+	{"Delay Not Responding",	0x04},
+	{NULL, 0},
+	{"Unknown",			0x00}
+};
+
+struct mps_table_lookup mps_sasdev_reason[] = {
+	{"SMART Data",			0x05},
+	{"Unsupported",			0x07},
+	{"Internal Device Reset",	0x08},
+	{"Task Abort Internal",		0x09},
+	{"Abort Task Set Internal",	0x0a},
+	{"Clear Task Set Internal",	0x0b},
+	{"Query Task Internal",		0x0c},
+	{"Async Notification",		0x0d},
+	{"Cmp Internal Device Reset",	0x0e},
+	{"Cmp Task Abort Internal",	0x0f},
+	{"Sata Init Failure",		0x10},
+	{NULL, 0},
+	{"Unknown",			0x00}
+};
+
+void
+mps_describe_devinfo(uint32_t devinfo, char *string, int len)
+{
+	snprintf(string, len, "%b,%s", devinfo,
+	    "\20" "\4SataHost" "\5SmpInit" "\6StpInit" "\7SspInit"
+	    "\10SataDev" "\11SmpTarg" "\12StpTarg" "\13SspTarg" "\14Direct"
+	    "\15LsiDev" "\16AtapiDev" "\17SepDev",
+	    mps_describe_table(mps_sasdev0_devtype, devinfo & 0x03));
+}
+
+void
+mps_print_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
+{
+
+	MPS_PRINTFIELD_START(sc, "IOCFacts");
+	MPS_PRINTFIELD(sc, facts, MsgVersion, 0x%x);
+	MPS_PRINTFIELD(sc, facts, HeaderVersion, 0x%x);
+	MPS_PRINTFIELD(sc, facts, IOCNumber, %d);
+	MPS_PRINTFIELD(sc, facts, IOCExceptions, 0x%x);
+	MPS_PRINTFIELD(sc, facts, MaxChainDepth, %d);
+	mps_dprint_field(sc, MPS_INFO, "WhoInit: %s\n",
+	    mps_describe_table(mps_whoinit_names, facts->WhoInit));
+	MPS_PRINTFIELD(sc, facts, NumberOfPorts, %d);
+	MPS_PRINTFIELD(sc, facts, RequestCredit, %d);
+	MPS_PRINTFIELD(sc, facts, ProductID, 0x%x);
+	mps_dprint_field(sc, MPS_INFO, "IOCCapabilities: %b\n",
+	    facts->IOCCapabilities, "\20" "\3ScsiTaskFull" "\4DiagTrace"
+	    "\5SnapBuf" "\6ExtBuf" "\7EEDP" "\10BiDirTarg" "\11Multicast"
+	    "\14TransRetry" "\15IR" "\16EventReplay" "\17RaidAccel"
+	    "\20MSIXIndex" "\21HostDisc");
+	mps_dprint_field(sc, MPS_INFO, "FWVersion= %d-%d-%d-%d\n",
+	    facts->FWVersion.Struct.Major,
+	    facts->FWVersion.Struct.Minor,
+	    facts->FWVersion.Struct.Unit,
+	    facts->FWVersion.Struct.Dev);
+	MPS_PRINTFIELD(sc, facts, IOCRequestFrameSize, %d);
+	MPS_PRINTFIELD(sc, facts, MaxInitiators, %d);
+	MPS_PRINTFIELD(sc, facts, MaxTargets, %d);
+	MPS_PRINTFIELD(sc, facts, MaxSasExpanders, %d);
+	MPS_PRINTFIELD(sc, facts, MaxEnclosures, %d);
+	mps_dprint_field(sc, MPS_INFO, "ProtocolFlags: %b\n",
+	    facts->ProtocolFlags, "\20" "\1ScsiTarg" "\2ScsiInit");
+	MPS_PRINTFIELD(sc, facts, HighPriorityCredit, %d);
+	MPS_PRINTFIELD(sc, facts, MaxReplyDescriptorPostQueueDepth, %d);
+	MPS_PRINTFIELD(sc, facts, ReplyFrameSize, %d);
+	MPS_PRINTFIELD(sc, facts, MaxVolumes, %d);
+	MPS_PRINTFIELD(sc, facts, MaxDevHandle, %d);
+	MPS_PRINTFIELD(sc, facts, MaxPersistentEntries, %d);
+}
+
+void
+mps_print_portfacts(struct mps_softc *sc, MPI2_PORT_FACTS_REPLY *facts)
+{
+
+	MPS_PRINTFIELD_START(sc, "PortFacts");
+	MPS_PRINTFIELD(sc, facts, PortNumber, %d);
+	MPS_PRINTFIELD(sc, facts, PortType, 0x%x);
+	MPS_PRINTFIELD(sc, facts, MaxPostedCmdBuffers, %d);
+}
+
+void
+mps_print_event(struct mps_softc *sc, MPI2_EVENT_NOTIFICATION_REPLY *event)
+{
+
+	MPS_EVENTFIELD_START(sc, "EventReply");
+	MPS_EVENTFIELD(sc, event, EventDataLength, %d);
+	MPS_EVENTFIELD(sc, event, AckRequired, %d);
+	mps_dprint_field(sc, MPS_EVENT, "Event: %s (0x%x)\n",
+	    mps_describe_table(mps_event_names, event->Event), event->Event);
+	MPS_EVENTFIELD(sc, event, EventContext, 0x%x);
+}
+
+void
+mps_print_sasdev0(struct mps_softc *sc, MPI2_CONFIG_PAGE_SAS_DEV_0 *buf)
+{
+	MPS_PRINTFIELD_START(sc, "SAS Device Page 0");
+	MPS_PRINTFIELD(sc, buf, Slot, %d);
+	MPS_PRINTFIELD(sc, buf, EnclosureHandle, 0x%x);
+	mps_dprint_field(sc, MPS_INFO, "SASAddress: 0x%jx\n",
+	    mps_to_u64(&buf->SASAddress));
+	MPS_PRINTFIELD(sc, buf, ParentDevHandle, 0x%x);
+	MPS_PRINTFIELD(sc, buf, PhyNum, %d);
+	MPS_PRINTFIELD(sc, buf, AccessStatus, 0x%x);
+	MPS_PRINTFIELD(sc, buf, DevHandle, 0x%x);
+	MPS_PRINTFIELD(sc, buf, AttachedPhyIdentifier, 0x%x);
+	MPS_PRINTFIELD(sc, buf, ZoneGroup, %d);
+	mps_dprint_field(sc, MPS_INFO, "DeviceInfo: %b,%s\n", buf->DeviceInfo,
+	    "\20" "\4SataHost" "\5SmpInit" "\6StpInit" "\7SspInit"
+	    "\10SataDev" "\11SmpTarg" "\12StpTarg" "\13SspTarg" "\14Direct"
+	    "\15LsiDev" "\16AtapiDev" "\17SepDev",
+	    mps_describe_table(mps_sasdev0_devtype, buf->DeviceInfo & 0x03));
+	MPS_PRINTFIELD(sc, buf, Flags, 0x%x);
+	MPS_PRINTFIELD(sc, buf, PhysicalPort, %d);
+	MPS_PRINTFIELD(sc, buf, MaxPortConnections, %d);
+	mps_dprint_field(sc, MPS_INFO, "DeviceName: 0x%jx\n",
+	    mps_to_u64(&buf->DeviceName));
+	MPS_PRINTFIELD(sc, buf, PortGroups, %d);
+	MPS_PRINTFIELD(sc, buf, DmaGroup, %d);
+	MPS_PRINTFIELD(sc, buf, ControlGroup, %d);
+}
+
+void
+mps_print_evt_sas(struct mps_softc *sc, MPI2_EVENT_NOTIFICATION_REPLY *event)
+{
+
+	mps_print_event(sc, event);
+
+	switch(event->Event) {
+	case MPI2_EVENT_SAS_DISCOVERY:
+	{
+		MPI2_EVENT_DATA_SAS_DISCOVERY *data;
+
+		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)&event->EventData;
+		mps_dprint_field(sc, MPS_EVENT, "Flags: %b\n", data->Flags,
+		    "\20" "\1InProgress" "\2DeviceChange");
+		mps_dprint_field(sc, MPS_EVENT, "ReasonCode: %s\n",
+		    mps_describe_table(mps_sasdisc_reason, data->ReasonCode));
+		MPS_EVENTFIELD(sc, data, PhysicalPort, %d);
+		mps_dprint_field(sc, MPS_EVENT, "DiscoveryStatus: %b\n",
+		    data->DiscoveryStatus,  "\20"
+		    "\1Loop" "\2UnaddressableDev" "\3DupSasAddr" "\5SmpTimeout"
+		    "\6ExpRouteFull" "\7RouteIndexError" "\10SmpFailed"
+		    "\11SmpCrcError" "\12SubSubLink" "\13TableTableLink"
+		    "\14UnsupDevice" "\15TableSubLink" "\16MultiDomain"
+		    "\17MultiSub" "\20MultiSubSub" "\34DownstreamInit"
+		    "\35MaxPhys" "\36MaxTargs" "\37MaxExpanders"
+		    "\40MaxEnclosures");
+		break;
+	}
+	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
+	{
+		MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *data;
+		MPI2_EVENT_SAS_TOPO_PHY_ENTRY *phy;
+		int i, phynum;
+
+		data = (MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *)
+		    &event->EventData;
+		MPS_EVENTFIELD(sc, data, EnclosureHandle, 0x%x);
+		MPS_EVENTFIELD(sc, data, ExpanderDevHandle, 0x%x);
+		MPS_EVENTFIELD(sc, data, NumPhys, %d);
+		MPS_EVENTFIELD(sc, data, NumEntries, %d);
+		MPS_EVENTFIELD(sc, data, StartPhyNum, %d);
+		mps_dprint_field(sc, MPS_EVENT, "ExpStatus: %s (0x%x)\n",
+		    mps_describe_table(mps_sastopo_exp, data->ExpStatus),
+		    data->ExpStatus);
+		MPS_EVENTFIELD(sc, data, PhysicalPort, %d);
+		for (i = 0; i < data->NumEntries; i++) {
+			phy = &data->PHY[i];
+			phynum = data->StartPhyNum + i;
+			mps_dprint_field(sc, MPS_EVENT,
+			    "PHY[%d].AttachedDevHandle: 0x%04x\n", phynum,
+			    phy->AttachedDevHandle);
+			mps_dprint_field(sc, MPS_EVENT,
+			    "PHY[%d].LinkRate: %s (0x%x)\n", phynum,
+			    mps_describe_table(mps_linkrate_names,
+			    (phy->LinkRate >> 4) & 0xf), phy->LinkRate);
+			mps_dprint_field(sc,MPS_EVENT,"PHY[%d].PhyStatus: %s\n",
+			    phynum, mps_describe_table(mps_phystatus_names,
+			    phy->PhyStatus));
+		}
+		break;
+	}
+	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
+	{
+		MPI2_EVENT_DATA_SAS_ENCL_DEV_STATUS_CHANGE *data;
+
+		data = (MPI2_EVENT_DATA_SAS_ENCL_DEV_STATUS_CHANGE *)
+		    &event->EventData;
+		MPS_EVENTFIELD(sc, data, EnclosureHandle, 0x%x);
+		mps_dprint_field(sc, MPS_EVENT, "ReasonCode: %s\n",
+		    mps_describe_table(mps_sastopo_exp, data->ReasonCode));
+		MPS_EVENTFIELD(sc, data, PhysicalPort, %d);
+		MPS_EVENTFIELD(sc, data, NumSlots, %d);
+		MPS_EVENTFIELD(sc, data, StartSlot, %d);
+		MPS_EVENTFIELD(sc, data, PhyBits, 0x%x);
+		break;
+	}
+	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
+	{
+		MPI2_EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *data;
+
+		data = (MPI2_EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *)
+		    &event->EventData;
+		MPS_EVENTFIELD(sc, data, TaskTag, 0x%x);
+		mps_dprint_field(sc, MPS_EVENT, "ReasonCode: %s\n",
+		    mps_describe_table(mps_sasdev_reason, data->ReasonCode));
+		MPS_EVENTFIELD(sc, data, ASC, 0x%x);
+		MPS_EVENTFIELD(sc, data, ASCQ, 0x%x);
+		MPS_EVENTFIELD(sc, data, DevHandle, 0x%x);
+		mps_dprint_field(sc, MPS_EVENT, "SASAddress: 0x%jx\n",
+		    mps_to_u64(&data->SASAddress));
+	}
+	default:
+		break;
+	}
+}
+
+void
+mps_print_expander1(struct mps_softc *sc, MPI2_CONFIG_PAGE_EXPANDER_1 *buf)
+{
+	MPS_PRINTFIELD_START(sc, "SAS Expander Page 1 #%d", buf->Phy);
+	MPS_PRINTFIELD(sc, buf, PhysicalPort, %d);
+	MPS_PRINTFIELD(sc, buf, NumPhys, %d);
+	MPS_PRINTFIELD(sc, buf, Phy, %d);
+	MPS_PRINTFIELD(sc, buf, NumTableEntriesProgrammed, %d);
+	mps_dprint_field(sc, MPS_INFO, "ProgrammedLinkRate: %s (0x%x)\n",
+	    mps_describe_table(mps_linkrate_names,
+	    (buf->ProgrammedLinkRate >> 4) & 0xf), buf->ProgrammedLinkRate);
+	mps_dprint_field(sc, MPS_INFO, "HwLinkRate: %s (0x%x)\n",
+	    mps_describe_table(mps_linkrate_names,
+	    (buf->HwLinkRate >> 4) & 0xf), buf->HwLinkRate);
+	MPS_PRINTFIELD(sc, buf, AttachedDevHandle, 0x%04x);
+	mps_dprint_field(sc, MPS_INFO, "PhyInfo Reason: %s (0x%x)\n",
+	    mps_describe_table(mps_phyinfo_reason_names,
+	    (buf->PhyInfo >> 16) & 0xf), buf->PhyInfo);
+	mps_dprint_field(sc, MPS_INFO, "AttachedDeviceInfo: %b,%s\n",
+	    buf->AttachedDeviceInfo, "\20" "\4SATAhost" "\5SMPinit" "\6STPinit"
+	    "\7SSPinit" "\10SATAdev" "\11SMPtarg" "\12STPtarg" "\13SSPtarg"
+	    "\14Direct" "\15LSIdev" "\16ATAPIdev" "\17SEPdev",
+	    mps_describe_table(mps_sasdev0_devtype,
+	    buf->AttachedDeviceInfo & 0x03));
+	MPS_PRINTFIELD(sc, buf, ExpanderDevHandle, 0x%04x);
+	MPS_PRINTFIELD(sc, buf, ChangeCount, %d);
+	mps_dprint_field(sc, MPS_INFO, "NegotiatedLinkRate: %s (0x%x)\n",
+	    mps_describe_table(mps_linkrate_names,
+	    buf->NegotiatedLinkRate & 0xf), buf->NegotiatedLinkRate);
+	MPS_PRINTFIELD(sc, buf, PhyIdentifier, %d);
+	MPS_PRINTFIELD(sc, buf, AttachedPhyIdentifier, %d);
+	MPS_PRINTFIELD(sc, buf, DiscoveryInfo, 0x%x);
+	MPS_PRINTFIELD(sc, buf, AttachedPhyInfo, 0x%x);
+	mps_dprint_field(sc, MPS_INFO, "AttachedPhyInfo Reason: %s (0x%x)\n",
+	    mps_describe_table(mps_phyinfo_reason_names,
+	    buf->AttachedPhyInfo & 0xf), buf->AttachedPhyInfo);
+	MPS_PRINTFIELD(sc, buf, ZoneGroup, %d);
+	MPS_PRINTFIELD(sc, buf, SelfConfigStatus, 0x%x);
+}
+
+void
+mps_print_sasphy0(struct mps_softc *sc, MPI2_CONFIG_PAGE_SAS_PHY_0 *buf)
+{
+	MPS_PRINTFIELD_START(sc, "SAS PHY Page 0");
+	MPS_PRINTFIELD(sc, buf, OwnerDevHandle, 0x%04x);
+	MPS_PRINTFIELD(sc, buf, AttachedDevHandle, 0x%04x);
+	MPS_PRINTFIELD(sc, buf, AttachedPhyIdentifier, %d);
+	mps_dprint_field(sc, MPS_INFO, "AttachedPhyInfo Reason: %s (0x%x)\n",
+	    mps_describe_table(mps_phyinfo_reason_names,
+	    buf->AttachedPhyInfo & 0xf), buf->AttachedPhyInfo);
+	mps_dprint_field(sc, MPS_INFO, "ProgrammedLinkRate: %s (0x%x)\n",
+	    mps_describe_table(mps_linkrate_names,
+	    (buf->ProgrammedLinkRate >> 4) & 0xf), buf->ProgrammedLinkRate);
+	mps_dprint_field(sc, MPS_INFO, "HwLinkRate: %s (0x%x)\n",
+	    mps_describe_table(mps_linkrate_names,
+	    (buf->HwLinkRate >> 4) & 0xf), buf->HwLinkRate);
+	MPS_PRINTFIELD(sc, buf, ChangeCount, %d);
+	MPS_PRINTFIELD(sc, buf, Flags, 0x%x);
+	mps_dprint_field(sc, MPS_INFO, "PhyInfo Reason: %s (0x%x)\n",
+	    mps_describe_table(mps_phyinfo_reason_names,
+	    (buf->PhyInfo >> 16) & 0xf), buf->PhyInfo);
+	mps_dprint_field(sc, MPS_INFO, "NegotiatedLinkRate: %s (0x%x)\n",
+	    mps_describe_table(mps_linkrate_names,
+	    buf->NegotiatedLinkRate & 0xf), buf->NegotiatedLinkRate);
+}
+
+void
+mps_print_sgl(struct mps_softc *sc, struct mps_command *cm, int offset)
+{
+	MPI2_SGE_SIMPLE64 *sge;
+	MPI2_SGE_CHAIN32 *sgc;
+	MPI2_REQUEST_HEADER *req;
+	struct mps_chain *chain = NULL;
+	char *frame;
+	u_int i = 0, flags;
+
+	req = (MPI2_REQUEST_HEADER *)cm->cm_req;
+	frame = (char *)cm->cm_req;
+	sge = (MPI2_SGE_SIMPLE64 *)&frame[offset * 4];
+	printf("SGL for command %p\n", cm);
+
+	while (frame != NULL) {
+		flags = sge->FlagsLength >> MPI2_SGE_FLAGS_SHIFT;
+		printf("seg%d flags=0x%x len=0x%x addr=0x%jx\n", i, flags,
+		    sge->FlagsLength & 0xffffff, mps_to_u64(&sge->Address));
+		if (flags & (MPI2_SGE_FLAGS_END_OF_LIST |
+		    MPI2_SGE_FLAGS_END_OF_BUFFER))
+			break;
+		sge++;
+		i++;
+		if (flags & MPI2_SGE_FLAGS_LAST_ELEMENT) {
+			sgc = (MPI2_SGE_CHAIN32 *)sge;
+			printf("chain flags=0x%x len=0x%x Offset=0x%x "
+			    "Address=0x%x\n", sgc->Flags, sgc->Length,
+			    sgc->NextChainOffset, sgc->Address);
+			if (chain == NULL)
+				chain = TAILQ_FIRST(&cm->cm_chain_list);
+			else
+				chain = TAILQ_NEXT(chain, chain_link);
+			frame = (char *)chain->chain;
+			sge = (MPI2_SGE_SIMPLE64 *)frame;
+			hexdump(frame, 128, NULL, 0);
+		}
+	}
+}
+
+void
+mps_print_scsiio_cmd(struct mps_softc *sc, struct mps_command *cm)
+{
+	MPI2_SCSI_IO_REQUEST *req;
+
+	req = (MPI2_SCSI_IO_REQUEST *)cm->cm_req;
+	mps_print_sgl(sc, cm, req->SGLOffset0);
+}
+
diff --git a/sys/dev/mps/mps_table.h b/sys/dev/mps/mps_table.h
new file mode 100644
index 00000000000..88aa2c38546
--- /dev/null
+++ b/sys/dev/mps/mps_table.h
@@ -0,0 +1,53 @@
+/*-
+ * Copyright (c) 2009 Yahoo! Inc.
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ *
+ * $FreeBSD$
+ */
+
+#ifndef _MPS_TABLE_H
+#define _MPS_TABLE_H
+
+struct mps_table_lookup {
+	char	*string;
+	u_int	code;
+};
+
+char * mps_describe_table(struct mps_table_lookup *table, u_int code);
+void mps_describe_devinfo(uint32_t devinfo, char *string, int len);
+
+extern struct mps_table_lookup mps_event_names[];
+extern struct mps_table_lookup mps_phystatus_names[];
+extern struct mps_table_lookup mps_linkrate_names[];
+
+void mps_print_iocfacts(struct mps_softc *, MPI2_IOC_FACTS_REPLY *);
+void mps_print_portfacts(struct mps_softc *, MPI2_PORT_FACTS_REPLY *);
+void mps_print_event(struct mps_softc *, MPI2_EVENT_NOTIFICATION_REPLY *);
+void mps_print_sasdev0(struct mps_softc *, MPI2_CONFIG_PAGE_SAS_DEV_0 *);
+void mps_print_evt_sas(struct mps_softc *, MPI2_EVENT_NOTIFICATION_REPLY *);
+void mps_print_expander1(struct mps_softc *, MPI2_CONFIG_PAGE_EXPANDER_1 *);
+void mps_print_sasphy0(struct mps_softc *, MPI2_CONFIG_PAGE_SAS_PHY_0 *);
+void mps_print_sgl(struct mps_softc *, struct mps_command *, int);
+void mps_print_scsiio_cmd(struct mps_softc *, struct mps_command *);
+#endif
diff --git a/sys/dev/mps/mps_user.c b/sys/dev/mps/mps_user.c
new file mode 100644
index 00000000000..9fa091dce1f
--- /dev/null
+++ b/sys/dev/mps/mps_user.c
@@ -0,0 +1,583 @@
+/*-
+ * Copyright (c) 2008 Yahoo!, Inc.
+ * All rights reserved.
+ * Written by: John Baldwin 
+ *
+ * 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. Neither the name of the author nor the names of any co-contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ *
+ * LSI MPS-Fusion Host Adapter FreeBSD userland interface
+ */
+
+#include 
+__FBSDID("$FreeBSD$");
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+static d_open_t		mps_open;
+static d_close_t	mps_close;
+static d_ioctl_t	mps_ioctl;
+
+static struct cdevsw mps_cdevsw = {
+	.d_version =	D_VERSION,
+	.d_flags =	0,
+	.d_open =	mps_open,
+	.d_close =	mps_close,
+	.d_ioctl =	mps_ioctl,
+	.d_name =	"mps",
+};
+
+static MALLOC_DEFINE(M_MPSUSER, "mps_user", "Buffers for mps(4) ioctls");
+
+int
+mps_attach_user(struct mps_softc *sc)
+{
+	int unit;
+
+	unit = device_get_unit(sc->mps_dev);
+	sc->mps_cdev = make_dev(&mps_cdevsw, unit, UID_ROOT, GID_OPERATOR, 0640,
+	    "mps%d", unit);
+	if (sc->mps_cdev == NULL) {
+		return (ENOMEM);
+	}
+	sc->mps_cdev->si_drv1 = sc;
+	return (0);
+}
+
+void
+mps_detach_user(struct mps_softc *sc)
+{
+
+	/* XXX: do a purge of pending requests? */
+	destroy_dev(sc->mps_cdev);
+
+}
+
+static int
+mps_open(struct cdev *dev, int flags, int fmt, struct thread *td)
+{
+
+	return (0);
+}
+
+static int
+mps_close(struct cdev *dev, int flags, int fmt, struct thread *td)
+{
+
+	return (0);
+}
+
+static int
+mps_user_read_cfg_header(struct mps_softc *sc,
+    struct mps_cfg_page_req *page_req)
+{
+	MPI2_CONFIG_PAGE_HEADER *hdr;
+	struct mps_config_params params;
+	int	    error;
+
+	hdr = ¶ms.hdr.Struct;
+	params.action = MPI2_CONFIG_ACTION_PAGE_HEADER;
+	params.page_address = le32toh(page_req->page_address);
+	hdr->PageVersion = 0;
+	hdr->PageLength = 0;
+	hdr->PageNumber = page_req->header.PageNumber;
+	hdr->PageType = page_req->header.PageType;
+	params.buffer = NULL;
+	params.length = 0;
+	params.callback = NULL;
+
+	if ((error = mps_read_config_page(sc, ¶ms)) != 0) {
+		/*
+		 * Leave the request. Without resetting the chip, it's
+		 * still owned by it and we'll just get into trouble
+		 * freeing it now. Mark it as abandoned so that if it
+		 * shows up later it can be freed.
+		 */
+		mps_printf(sc, "read_cfg_header timed out\n");
+		return (ETIMEDOUT);
+	}
+
+	page_req->ioc_status = htole16(params.status);
+	if ((page_req->ioc_status & MPI2_IOCSTATUS_MASK) ==
+	    MPI2_IOCSTATUS_SUCCESS) {
+		bcopy(hdr, &page_req->header, sizeof(page_req->header));
+	}
+
+	return (0);
+}
+
+static int
+mps_user_read_cfg_page(struct mps_softc *sc, struct mps_cfg_page_req *page_req,
+    void *buf)
+{
+	MPI2_CONFIG_PAGE_HEADER *reqhdr, *hdr;
+	struct mps_config_params params;
+	int	      error;
+
+	reqhdr = buf;
+	hdr = ¶ms.hdr.Struct;
+	hdr->PageVersion = reqhdr->PageVersion;
+	hdr->PageLength = reqhdr->PageLength;
+	hdr->PageNumber = reqhdr->PageNumber;
+	hdr->PageType = reqhdr->PageType & MPI2_CONFIG_PAGETYPE_MASK;
+	params.action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT;
+	params.page_address = le32toh(page_req->page_address);
+	params.buffer = buf;
+	params.length = le32toh(page_req->len);
+	params.callback = NULL;
+
+	if ((error = mps_read_config_page(sc, ¶ms)) != 0) {
+		mps_printf(sc, "mps_user_read_cfg_page timed out\n");
+		return (ETIMEDOUT);
+	}
+
+	page_req->ioc_status = htole16(params.status);
+	return (0);
+}
+
+static int
+mps_user_read_extcfg_header(struct mps_softc *sc,
+    struct mps_ext_cfg_page_req *ext_page_req)
+{
+	MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
+	struct mps_config_params params;
+	int	    error;
+
+	hdr = ¶ms.hdr.Ext;
+	params.action = MPI2_CONFIG_ACTION_PAGE_HEADER;
+	hdr->PageVersion = ext_page_req->header.PageVersion;
+	hdr->ExtPageLength = 0;
+	hdr->PageNumber = ext_page_req->header.PageNumber;
+	hdr->ExtPageType = ext_page_req->header.ExtPageType;
+	params.page_address = le32toh(ext_page_req->page_address);
+	if ((error = mps_read_config_page(sc, ¶ms)) != 0) {
+		/*
+		 * Leave the request. Without resetting the chip, it's
+		 * still owned by it and we'll just get into trouble
+		 * freeing it now. Mark it as abandoned so that if it
+		 * shows up later it can be freed.
+		 */
+		mps_printf(sc, "mps_user_read_extcfg_header timed out\n");
+		return (ETIMEDOUT);
+	}
+
+	ext_page_req->ioc_status = htole16(params.status);
+	if ((ext_page_req->ioc_status & MPI2_IOCSTATUS_MASK) ==
+	    MPI2_IOCSTATUS_SUCCESS) {
+		ext_page_req->header.PageVersion = hdr->PageVersion;
+		ext_page_req->header.PageNumber = hdr->PageNumber;
+		ext_page_req->header.PageType = hdr->PageType;
+		ext_page_req->header.ExtPageLength = hdr->ExtPageLength;
+		ext_page_req->header.ExtPageType = hdr->ExtPageType;
+	}
+
+	return (0);
+}
+
+static int
+mps_user_read_extcfg_page(struct mps_softc *sc,
+    struct mps_ext_cfg_page_req *ext_page_req, void *buf)
+{
+	MPI2_CONFIG_EXTENDED_PAGE_HEADER *reqhdr, *hdr;
+	struct mps_config_params params;
+	int error;
+
+	reqhdr = buf;
+	hdr = ¶ms.hdr.Ext;
+	params.action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT;
+	params.page_address = le32toh(ext_page_req->page_address);
+	hdr->PageVersion = reqhdr->PageVersion;
+	hdr->PageNumber = reqhdr->PageNumber;
+	hdr->ExtPageType = reqhdr->ExtPageType;
+	hdr->ExtPageLength = reqhdr->ExtPageLength;
+	params.buffer = buf;
+	params.length = le32toh(ext_page_req->len);
+	params.callback = NULL;
+
+	if ((error = mps_read_config_page(sc, ¶ms)) != 0) {
+		mps_printf(sc, "mps_user_read_extcfg_page timed out\n");
+		return (ETIMEDOUT);
+	}
+
+	ext_page_req->ioc_status = htole16(params.status);
+	return (0);
+}
+
+static int
+mps_user_write_cfg_page(struct mps_softc *sc,
+    struct mps_cfg_page_req *page_req, void *buf)
+{
+	MPI2_CONFIG_PAGE_HEADER *reqhdr, *hdr;
+	struct mps_config_params params;
+	u_int	      hdr_attr;
+	int	      error;
+
+	reqhdr = buf;
+	hdr = ¶ms.hdr.Struct;
+	hdr_attr = reqhdr->PageType & MPI2_CONFIG_PAGEATTR_MASK;
+	if (hdr_attr != MPI2_CONFIG_PAGEATTR_CHANGEABLE &&
+	    hdr_attr != MPI2_CONFIG_PAGEATTR_PERSISTENT) {
+		mps_printf(sc, "page type 0x%x not changeable\n",
+			reqhdr->PageType & MPI2_CONFIG_PAGETYPE_MASK);
+		return (EINVAL);
+	}
+
+	/*
+	 * There isn't any point in restoring stripped out attributes
+	 * if you then mask them going down to issue the request.
+	 */
+
+	hdr->PageVersion = reqhdr->PageVersion;
+	hdr->PageLength = reqhdr->PageLength;
+	hdr->PageNumber = reqhdr->PageNumber;
+	hdr->PageType = reqhdr->PageType;
+	params.action = MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT;
+	params.page_address = le32toh(page_req->page_address);
+	params.buffer = buf;
+	params.length = le32toh(page_req->len);
+	params.callback = NULL;
+
+	if ((error = mps_write_config_page(sc, ¶ms)) != 0) {
+		mps_printf(sc, "mps_write_cfg_page timed out\n");
+		return (ETIMEDOUT);
+	}
+
+	page_req->ioc_status = htole16(params.status);
+	return (0);
+}
+
+struct mps_user_func {
+	U8 Func;
+	U8 SgOff;
+} mps_user_func_list[] = {
+	{ MPI2_FUNCTION_IOC_FACTS,	0 },
+	{ MPI2_FUNCTION_PORT_FACTS,	0 },
+	{ MPI2_FUNCTION_FW_DOWNLOAD, 	offsetof(Mpi2FWDownloadRequest,SGL)},
+	{ MPI2_FUNCTION_FW_UPLOAD,	offsetof(Mpi2FWUploadRequest_t,SGL)},
+	{ MPI2_FUNCTION_SATA_PASSTHROUGH,offsetof(Mpi2SataPassthroughRequest_t,SGL)},
+	{ MPI2_FUNCTION_SMP_PASSTHROUGH, offsetof(Mpi2SmpPassthroughRequest_t,SGL)},
+	{ MPI2_FUNCTION_CONFIG,		offsetof(Mpi2ConfigRequest_t,PageBufferSGE)},
+	{ MPI2_FUNCTION_SAS_IO_UNIT_CONTROL,	0 },
+};	
+
+static int
+mps_user_verify_request(MPI2_REQUEST_HEADER *hdr, MPI2_SGE_IO_UNION **psgl)
+{
+	int i, err = EINVAL;
+
+	for (i = 0; i < sizeof(mps_user_func_list) /
+	    sizeof(mps_user_func_list[0]); i++ ) {
+		struct mps_user_func *func = &mps_user_func_list[i];
+		
+		if (hdr->Function == func->Func) {
+			if (psgl != NULL) {
+				if (func->SgOff != 0)
+					*psgl = (PTR_MPI2_SGE_IO_UNION)
+					    ((char*)hdr + func->SgOff);
+				else
+					*psgl = NULL;
+				err = 0;
+				break;
+			}
+		}
+	}	
+
+	return err;
+}	
+
+static int
+mps_user_command(struct mps_softc *sc, struct mps_usr_command *cmd)
+{
+	MPI2_REQUEST_HEADER *hdr;	
+	MPI2_DEFAULT_REPLY *rpl;
+	MPI2_SGE_IO_UNION *sgl;	
+	void *buf;
+	struct mps_command *cm;
+	int err = 0;
+	int sz;
+
+	mps_lock(sc);
+	cm = mps_alloc_command(sc);
+
+	if (cm == NULL) {
+		mps_printf(sc, "mps_user_command: no mps requests\n");
+		err = ENOMEM;
+		goto Ret;
+	}
+	mps_unlock(sc);
+
+	hdr = (MPI2_REQUEST_HEADER *)cm->cm_req;
+
+	mps_dprint(sc, MPS_INFO, "mps_user_command: req %p %d  rpl %p %d\n",
+		    cmd->req, cmd->req_len, cmd->rpl, cmd->rpl_len );
+
+	copyin(cmd->req, hdr, cmd->req_len);
+
+	mps_dprint(sc, MPS_INFO, "mps_user_command: Function %02X  "
+	    "MsgFlags %02X\n", hdr->Function, hdr->MsgFlags );
+
+	err = mps_user_verify_request(hdr, &sgl);
+	if (err != 0) {
+		mps_printf(sc, "mps_user_command: unsupported function 0x%X\n",
+		    hdr->Function );
+		goto RetFree;
+	}
+
+	if (cmd->len > 0) {
+		buf = malloc(cmd->len, M_MPSUSER, M_WAITOK|M_ZERO);
+		cm->cm_data = buf;
+		cm->cm_length = cmd->len;
+	} else {
+		buf = NULL;
+		cm->cm_data = NULL;
+		cm->cm_length = 0;
+	}
+
+	cm->cm_sge = sgl;
+	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
+	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_WAKEUP;
+	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
+
+	mps_lock(sc);
+	err = mps_map_command(sc, cm);
+
+	if (err != 0) {
+		mps_printf(sc, "mps_user_command: request timed out\n");
+		goto Ret;
+	}
+	msleep(cm, &sc->mps_mtx, 0, "mpsuser", 0); /* 30 seconds */
+
+	rpl = (MPI2_DEFAULT_REPLY *)cm->cm_reply;
+	sz = rpl->MsgLength * 4;
+	
+	if (sz > cmd->rpl_len) {
+		mps_printf(sc,
+		    "mps_user_command: reply buffer too small %d required %d\n",
+		    cmd->rpl_len, sz );
+		err = EINVAL;
+		sz = cmd->rpl_len;
+	}	
+
+	mps_unlock(sc);
+	copyout(rpl, cmd->rpl, sz);
+	if (buf != NULL) {
+		copyout(buf, cmd->buf, cmd->len);
+		free(buf, M_MPSUSER);
+	}
+	mps_lock(sc);
+
+	mps_dprint(sc, MPS_INFO, "mps_user_command: reply size %d\n", sz );
+
+RetFree:	   
+	mps_free_command(sc, cm);
+
+Ret:
+	mps_unlock(sc);
+	return err;
+}	
+
+#ifdef __amd64__
+#define	PTRIN(p)		((void *)(uintptr_t)(p))
+#define PTROUT(v)		((u_int32_t)(uintptr_t)(v))
+#endif
+
+static int
+mps_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag,
+    struct thread *td)
+{
+	struct mps_softc *sc;
+	struct mps_cfg_page_req *page_req;
+	struct mps_ext_cfg_page_req *ext_page_req;
+	void *mps_page;
+#ifdef __amd64__
+	struct mps_cfg_page_req32 *page_req32;
+	struct mps_cfg_page_req page_req_swab;
+	struct mps_ext_cfg_page_req32 *ext_page_req32;
+	struct mps_ext_cfg_page_req ext_page_req_swab;
+#endif
+	int error;
+
+	mps_page = NULL;
+	sc = dev->si_drv1;
+	page_req = (void *)arg;
+	ext_page_req = (void *)arg;
+
+#ifdef __amd64__
+	/* Convert 32-bit structs to native ones. */
+	page_req32 = (void *)arg;
+	ext_page_req32 = (void *)arg;
+	switch (cmd) {
+	case MPSIO_READ_CFG_HEADER32:
+	case MPSIO_READ_CFG_PAGE32:
+	case MPSIO_WRITE_CFG_PAGE32:
+		page_req = &page_req_swab;
+		page_req->header = page_req32->header;
+		page_req->page_address = page_req32->page_address;
+		page_req->buf = PTRIN(page_req32->buf);
+		page_req->len = page_req32->len;
+		page_req->ioc_status = page_req32->ioc_status;
+		break;
+	case MPSIO_READ_EXT_CFG_HEADER32:
+	case MPSIO_READ_EXT_CFG_PAGE32:
+		ext_page_req = &ext_page_req_swab;
+		ext_page_req->header = ext_page_req32->header;
+		ext_page_req->page_address = ext_page_req32->page_address;
+		ext_page_req->buf = PTRIN(ext_page_req32->buf);
+		ext_page_req->len = ext_page_req32->len;
+		ext_page_req->ioc_status = ext_page_req32->ioc_status;
+		break;
+	default:
+		return (ENOIOCTL);
+	}
+#endif
+
+	switch (cmd) {
+#ifdef __amd64__
+	case MPSIO_READ_CFG_HEADER32:
+#endif
+	case MPSIO_READ_CFG_HEADER:
+		mps_lock(sc);
+		error = mps_user_read_cfg_header(sc, page_req);
+		mps_unlock(sc);
+		break;
+#ifdef __amd64__
+	case MPSIO_READ_CFG_PAGE32:
+#endif
+	case MPSIO_READ_CFG_PAGE:
+		mps_page = malloc(page_req->len, M_MPSUSER, M_WAITOK | M_ZERO);
+		error = copyin(page_req->buf, mps_page,
+		    sizeof(MPI2_CONFIG_PAGE_HEADER));
+		if (error)
+			break;
+		mps_lock(sc);
+		error = mps_user_read_cfg_page(sc, page_req, mps_page);
+		mps_unlock(sc);
+		if (error)
+			break;
+		error = copyout(mps_page, page_req->buf, page_req->len);
+		break;
+#ifdef __amd64__
+	case MPSIO_READ_EXT_CFG_HEADER32:
+#endif
+	case MPSIO_READ_EXT_CFG_HEADER:
+		mps_lock(sc);
+		error = mps_user_read_extcfg_header(sc, ext_page_req);
+		mps_unlock(sc);
+		break;
+#ifdef __amd64__
+	case MPSIO_READ_EXT_CFG_PAGE32:
+#endif
+	case MPSIO_READ_EXT_CFG_PAGE:
+		mps_page = malloc(ext_page_req->len, M_MPSUSER, M_WAITOK|M_ZERO);
+		error = copyin(ext_page_req->buf, mps_page,
+		    sizeof(MPI2_CONFIG_EXTENDED_PAGE_HEADER));
+		if (error)
+			break;
+		mps_lock(sc);
+		error = mps_user_read_extcfg_page(sc, ext_page_req, mps_page);
+		mps_unlock(sc);
+		if (error)
+			break;
+		error = copyout(mps_page, ext_page_req->buf, ext_page_req->len);
+		break;
+#ifdef __amd64__
+	case MPSIO_WRITE_CFG_PAGE32:
+#endif
+	case MPSIO_WRITE_CFG_PAGE:
+		mps_page = malloc(page_req->len, M_MPSUSER, M_WAITOK|M_ZERO);
+		error = copyin(page_req->buf, mps_page, page_req->len);
+		if (error)
+			break;
+		mps_lock(sc);
+		error = mps_user_write_cfg_page(sc, page_req, mps_page);
+		mps_unlock(sc);
+		break;
+	case MPSIO_MPS_COMMAND:
+		error = mps_user_command(sc, (struct mps_usr_command *)arg);
+		break;
+	default:
+		error = ENOIOCTL;
+		break;
+	}
+
+	if (mps_page != NULL)
+		free(mps_page, M_MPSUSER);
+
+	if (error)
+		return (error);
+
+#ifdef __amd64__
+	/* Convert native structs to 32-bit ones. */
+	switch (cmd) {
+	case MPSIO_READ_CFG_HEADER32:
+	case MPSIO_READ_CFG_PAGE32:
+	case MPSIO_WRITE_CFG_PAGE32:
+		page_req32->header = page_req->header;
+		page_req32->page_address = page_req->page_address;
+		page_req32->buf = PTROUT(page_req->buf);
+		page_req32->len = page_req->len;
+		page_req32->ioc_status = page_req->ioc_status;
+		break;
+	case MPSIO_READ_EXT_CFG_HEADER32:
+	case MPSIO_READ_EXT_CFG_PAGE32:		
+		ext_page_req32->header = ext_page_req->header;
+		ext_page_req32->page_address = ext_page_req->page_address;
+		ext_page_req32->buf = PTROUT(ext_page_req->buf);
+		ext_page_req32->len = ext_page_req->len;
+		ext_page_req32->ioc_status = ext_page_req->ioc_status;
+		break;
+	default:
+		return (ENOIOCTL);
+	}
+#endif
+
+	return (0);
+}
diff --git a/sys/dev/mps/mpsvar.h b/sys/dev/mps/mpsvar.h
new file mode 100644
index 00000000000..47489b97a10
--- /dev/null
+++ b/sys/dev/mps/mpsvar.h
@@ -0,0 +1,370 @@
+/*-
+ * Copyright (c) 2009 Yahoo! Inc.
+ * 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+ * 
+ * $FreeBSD$
+ */
+
+#ifndef _MPSVAR_H
+#define _MPSVAR_H
+
+#define MPS_DB_MAX_WAIT		2500
+
+#define MPS_REQ_FRAMES		1024
+#define MPS_EVT_REPLY_FRAMES	32
+#define MPS_REPLY_FRAMES	MPS_REQ_FRAMES
+#define MPS_CHAIN_FRAMES	1024
+#define MPS_SENSE_LEN		SSD_FULL_SIZE
+#define MPS_MSI_COUNT		1
+#define MPS_SGE64_SIZE		12
+#define MPS_SGE32_SIZE		8
+#define MPS_SGC_SIZE		8
+
+#define MPS_PERIODIC_DELAY	1	/* 1 second heartbeat/watchdog check */
+
+struct mps_softc;
+struct mps_command;
+struct mpssas_softc;
+struct mpssas_target;
+
+MALLOC_DECLARE(M_MPT2);
+
+typedef void mps_evt_callback_t(struct mps_softc *, uintptr_t,
+    MPI2_EVENT_NOTIFICATION_REPLY *reply);
+typedef void mps_command_callback_t(struct mps_softc *, struct mps_command *cm);
+
+struct mps_chain {
+	TAILQ_ENTRY(mps_chain)		chain_link;
+	MPI2_SGE_IO_UNION		*chain;
+	uint32_t			chain_busaddr;
+};
+
+struct mps_command {
+	TAILQ_ENTRY(mps_command)	cm_link;
+	struct mps_softc		*cm_sc;
+	void				*cm_data;
+	u_int				cm_length;
+	u_int				cm_sglsize;
+	MPI2_SGE_IO_UNION		*cm_sge;
+	uint8_t				*cm_req;
+	uint8_t				*cm_reply;
+	uint32_t			cm_reply_data;
+	mps_command_callback_t		*cm_complete;
+	void				*cm_complete_data;
+	struct mpssas_target		*cm_targ;
+	MPI2_REQUEST_DESCRIPTOR_UNION	cm_desc;
+	u_int				cm_flags;
+#define MPS_CM_FLAGS_POLLED		(1 << 0)
+#define MPS_CM_FLAGS_COMPLETE		(1 << 1)
+#define MPS_CM_FLAGS_SGE_SIMPLE		(1 << 2)
+#define MPS_CM_FLAGS_DATAOUT		(1 << 3)
+#define MPS_CM_FLAGS_DATAIN		(1 << 4)
+#define MPS_CM_FLAGS_WAKEUP		(1 << 5)
+	u_int				cm_state;
+#define MPS_CM_STATE_FREE		0
+#define MPS_CM_STATE_BUSY		1
+#define MPS_CM_STATE_TIMEDOUT		2
+	bus_dmamap_t			cm_dmamap;
+	struct scsi_sense_data		*cm_sense;
+	TAILQ_HEAD(, mps_chain)		cm_chain_list;
+	uint32_t			cm_req_busaddr;
+	uint32_t			cm_sense_busaddr;
+	struct callout			cm_callout;
+};
+
+struct mps_event_handle {
+	TAILQ_ENTRY(mps_event_handle)	eh_list;
+	mps_evt_callback_t		*callback;
+	void				*data;
+	uint8_t				mask[16];
+};
+
+struct mps_softc {
+	device_t			mps_dev;
+	struct cdev			*mps_cdev;
+	u_int				mps_flags;
+#define MPS_FLAGS_INTX		(1 << 0)
+#define MPS_FLAGS_MSI		(1 << 1)
+#define MPS_FLAGS_BUSY		(1 << 2)
+#define MPS_FLAGS_SHUTDOWN	(1 << 3)
+	u_int				mps_debug;
+	struct sysctl_ctx_list		sysctl_ctx;
+	struct sysctl_oid		*sysctl_tree;
+	struct mps_command		*commands;
+	struct mps_chain		*chains;
+	struct callout			periodic;
+
+	struct mpssas_softc		*sassc;
+
+	TAILQ_HEAD(, mps_command)	req_list;
+	TAILQ_HEAD(, mps_chain)		chain_list;
+	int				replypostindex;
+	int				replyfreeindex;
+	int				replycurindex;
+
+	struct resource			*mps_regs_resource;
+	bus_space_handle_t		mps_bhandle;
+	bus_space_tag_t			mps_btag;
+	int				mps_regs_rid;
+
+	bus_dma_tag_t			mps_parent_dmat;
+	bus_dma_tag_t			buffer_dmat;
+
+	MPI2_IOC_FACTS_REPLY		*facts;
+	MPI2_PORT_FACTS_REPLY		*pfacts;
+	int				num_reqs;
+	int				num_replies;
+	int				fqdepth;	/* Free queue */
+	int				pqdepth;	/* Post queue */
+
+	uint8_t				event_mask[16];
+	TAILQ_HEAD(, mps_event_handle)	event_list;
+	struct mps_event_handle		*mps_log_eh;
+
+	struct mtx			mps_mtx;
+	struct intr_config_hook		mps_ich;
+	struct resource			*mps_irq[MPS_MSI_COUNT];
+	void				*mps_intrhand[MPS_MSI_COUNT];
+	int				mps_irq_rid[MPS_MSI_COUNT];
+
+	uint8_t				*req_frames;
+	bus_addr_t			req_busaddr;
+	bus_dma_tag_t			req_dmat;
+	bus_dmamap_t			req_map;
+
+	uint8_t				*reply_frames;
+	bus_addr_t			reply_busaddr;
+	bus_dma_tag_t			reply_dmat;
+	bus_dmamap_t			reply_map;
+
+	struct scsi_sense_data		*sense_frames;
+	bus_addr_t			sense_busaddr;
+	bus_dma_tag_t			sense_dmat;
+	bus_dmamap_t			sense_map;
+
+	uint8_t				*chain_frames;
+	bus_addr_t			chain_busaddr;
+	bus_dma_tag_t			chain_dmat;
+	bus_dmamap_t			chain_map;
+
+	MPI2_REPLY_DESCRIPTORS_UNION	*post_queue;
+	bus_addr_t			post_busaddr;
+	uint32_t			*free_queue;
+	bus_addr_t			free_busaddr;
+	bus_dma_tag_t			queues_dmat;
+	bus_dmamap_t			queues_map;
+};
+
+struct mps_config_params {
+	MPI2_CONFIG_EXT_PAGE_HEADER_UNION	hdr;
+	u_int		action;
+	u_int		page_address;	/* Attributes, not a phys address */
+	u_int		status;
+	void		*buffer;
+	u_int		length;
+	int		timeout;
+	void		(*callback)(struct mps_softc *, struct mps_config_params *);
+	void		*cbdata;
+};
+
+static __inline uint32_t
+mps_regread(struct mps_softc *sc, uint32_t offset)
+{
+	return (bus_space_read_4(sc->mps_btag, sc->mps_bhandle, offset));
+}
+
+static __inline void
+mps_regwrite(struct mps_softc *sc, uint32_t offset, uint32_t val)
+{
+	bus_space_write_4(sc->mps_btag, sc->mps_bhandle, offset, val);
+}
+
+static __inline void
+mps_free_reply(struct mps_softc *sc, uint32_t busaddr)
+{
+
+	if (++sc->replyfreeindex >= sc->fqdepth)
+		sc->replyfreeindex = 0;
+	sc->free_queue[sc->replyfreeindex] = busaddr;
+	mps_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
+}
+
+static __inline struct mps_chain *
+mps_alloc_chain(struct mps_softc *sc)
+{
+	struct mps_chain *chain;
+
+	if ((chain = TAILQ_FIRST(&sc->chain_list)) != NULL)
+		TAILQ_REMOVE(&sc->chain_list, chain, chain_link);
+	return (chain);
+}
+
+static __inline void
+mps_free_chain(struct mps_softc *sc, struct mps_chain *chain)
+{
+#if 0
+	bzero(chain->chain, 128);
+#endif
+	TAILQ_INSERT_TAIL(&sc->chain_list, chain, chain_link);
+}
+
+static __inline void
+mps_free_command(struct mps_softc *sc, struct mps_command *cm)
+{
+	struct mps_chain *chain, *chain_temp;
+
+	if (cm->cm_reply != NULL)
+		mps_free_reply(sc, cm->cm_reply_data);
+	cm->cm_flags = 0;
+	cm->cm_complete = NULL;
+	cm->cm_complete_data = NULL;
+	cm->cm_targ = 0;
+	cm->cm_state = MPS_CM_STATE_FREE;
+	TAILQ_FOREACH_SAFE(chain, &cm->cm_chain_list, chain_link, chain_temp) {
+		TAILQ_REMOVE(&cm->cm_chain_list, chain, chain_link);
+		mps_free_chain(sc, chain);
+	}
+	TAILQ_INSERT_TAIL(&sc->req_list, cm, cm_link);
+}
+
+static __inline struct mps_command *
+mps_alloc_command(struct mps_softc *sc)
+{
+	struct mps_command *cm;
+
+	cm = TAILQ_FIRST(&sc->req_list);
+	if (cm == NULL)
+		return (NULL);
+
+	TAILQ_REMOVE(&sc->req_list, cm, cm_link);
+	KASSERT(cm->cm_state == MPS_CM_STATE_FREE, ("mps: Allocating busy command\n"));
+	cm->cm_state = MPS_CM_STATE_BUSY;
+	return (cm);
+}
+
+static __inline void
+mps_lock(struct mps_softc *sc)
+{
+	mtx_lock(&sc->mps_mtx);
+}
+
+static __inline void
+mps_unlock(struct mps_softc *sc)
+{
+	mtx_unlock(&sc->mps_mtx);
+}
+
+#define MPS_INFO	(1 << 0)
+#define MPS_TRACE	(1 << 1)
+#define MPS_FAULT	(1 << 2)
+#define MPS_EVENT	(1 << 3)
+#define MPS_LOG		(1 << 4)
+
+#define mps_printf(sc, args...)				\
+	device_printf((sc)->mps_dev, ##args)
+
+#define mps_dprint(sc, level, msg, args...)		\
+do {							\
+	if (sc->mps_debug & level)			\
+		device_printf(sc->mps_dev, msg, ##args);	\
+} while (0)
+
+#define mps_dprint_field(sc, level, msg, args...)		\
+do {								\
+	if (sc->mps_debug & level)				\
+		printf("\t" msg, ##args);			\
+} while (0)
+
+#define MPS_PRINTFIELD_START(sc, tag...)	\
+	mps_dprint((sc), MPS_INFO, ##tag);	\
+	mps_dprint_field((sc), MPS_INFO, ":\n")
+#define MPS_PRINTFIELD_END(sc, tag)		\
+	mps_dprint((sc), MPS_INFO, tag "\n")
+#define MPS_PRINTFIELD(sc, facts, attr, fmt)	\
+	mps_dprint_field((sc), MPS_INFO, #attr ": " #fmt "\n", (facts)->attr)
+
+#define MPS_EVENTFIELD_START(sc, tag...)	\
+	mps_dprint((sc), MPS_EVENT, ##tag);	\
+	mps_dprint_field((sc), MPS_EVENT, ":\n")
+#define MPS_EVENTFIELD(sc, facts, attr, fmt)	\
+	mps_dprint_field((sc), MPS_EVENT, #attr ": " #fmt "\n", (facts)->attr)
+
+static __inline void
+mps_from_u64(uint64_t data, U64 *mps)
+{
+	(mps)->High = (uint32_t)((data) >> 32);
+	(mps)->Low = (uint32_t)((data) & 0xffffffff);
+}
+
+static __inline uint64_t
+mps_to_u64(U64 *data)
+{
+
+	return (((uint64_t)data->High << 32) | data->Low);
+}
+
+static __inline void
+mps_mask_intr(struct mps_softc *sc)
+{
+	uint32_t mask;
+
+	mask = mps_regread(sc, MPI2_HOST_INTERRUPT_MASK_OFFSET);
+	mask |= MPI2_HIM_REPLY_INT_MASK;
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_MASK_OFFSET, mask);
+}
+
+static __inline void
+mps_unmask_intr(struct mps_softc *sc)
+{
+	uint32_t mask;
+
+	mask = mps_regread(sc, MPI2_HOST_INTERRUPT_MASK_OFFSET);
+	mask &= ~MPI2_HIM_REPLY_INT_MASK;
+	mps_regwrite(sc, MPI2_HOST_INTERRUPT_MASK_OFFSET, mask);
+}
+
+int mps_pci_setup_interrupts(struct mps_softc *);
+int mps_attach(struct mps_softc *sc);
+int mps_free(struct mps_softc *sc);
+void mps_intr(void *);
+void mps_intr_msi(void *);
+void mps_intr_locked(void *);
+int mps_register_events(struct mps_softc *, uint8_t *, mps_evt_callback_t *,
+    void *, struct mps_event_handle **);
+int mps_update_events(struct mps_softc *, struct mps_event_handle *, uint8_t *);
+int mps_deregister_events(struct mps_softc *, struct mps_event_handle *);
+int mps_request_polled(struct mps_softc *sc, struct mps_command *cm);
+int mps_attach_sas(struct mps_softc *sc);
+int mps_detach_sas(struct mps_softc *sc);
+int mps_map_command(struct mps_softc *sc, struct mps_command *cm);
+int mps_read_config_page(struct mps_softc *, struct mps_config_params *);
+int mps_write_config_page(struct mps_softc *, struct mps_config_params *);
+void mps_memaddr_cb(void *, bus_dma_segment_t *, int , int );
+int mps_attach_user(struct mps_softc *);
+void mps_detach_user(struct mps_softc *);
+
+SYSCTL_DECL(_hw_mps);
+
+#endif
+
diff --git a/sys/modules/Makefile b/sys/modules/Makefile
index 80850bd4ec2..452cc8f907f 100644
--- a/sys/modules/Makefile
+++ b/sys/modules/Makefile
@@ -185,6 +185,7 @@ SUBDIR=	${_3dfx} \
 	${_mly} \
 	mmc \
 	mmcsd \
+	mps \
 	mpt \
 	mqueue \
 	msdosfs \
diff --git a/sys/modules/mps/Makefile b/sys/modules/mps/Makefile
new file mode 100644
index 00000000000..f8f520b6d7c
--- /dev/null
+++ b/sys/modules/mps/Makefile
@@ -0,0 +1,13 @@
+# $FreeBSD$
+
+.PATH: ${.CURDIR}/../../dev/mps
+
+KMOD=	mps
+SRCS=	mps_pci.c mps.c mps_sas.c mps_table.c mps_user.c
+SRCS+=	opt_mps.h opt_cam.h
+SRCS+=	device_if.h bus_if.h pci_if.h
+
+#CFLAGS += -DMPS_DEBUG
+DEBUG += -g
+
+.include 

From 9a1d11500003d4b4df561d1b3369a127db072fff Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Fri, 10 Sep 2010 16:19:58 +0000
Subject: [PATCH 0617/1624] Add the DTRACE variable that points to the
 executable.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/sys.mk | 1 +
 1 file changed, 1 insertion(+)

diff --git a/share/mk/sys.mk b/share/mk/sys.mk
index dbd7fa08866..fae3f3e5f50 100644
--- a/share/mk/sys.mk
+++ b/share/mk/sys.mk
@@ -69,6 +69,7 @@ CTFFLAGS	?=	-L VERSION
 
 CTFCONVERT	?=	ctfconvert
 CTFMERGE	?=	ctfmerge
+DTRACE		?=	dtrace
 .if defined(CFLAGS) && (${CFLAGS:M-g} != "")
 CTFFLAGS	+=	-g
 .else

From c2c48445bad6ac76cacf4859f41dd2b93143fa6b Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Fri, 10 Sep 2010 16:21:09 +0000
Subject: [PATCH 0618/1624] Check the existence of a 'beforelinking' target and
 make the resulting program or library depend on that before doing the final
 linking. This will be needed by DTrace.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/bsd.lib.mk  |  4 ++++
 share/mk/bsd.prog.mk | 10 +++++++++-
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/share/mk/bsd.lib.mk b/share/mk/bsd.lib.mk
index ecb91bfd288..4da0a2fe45e 100644
--- a/share/mk/bsd.lib.mk
+++ b/share/mk/bsd.lib.mk
@@ -198,7 +198,11 @@ SOBJS+=		${OBJS:.o=.So}
 .if defined(SHLIB_NAME)
 _LIBS+=		${SHLIB_NAME}
 
+.if target(beforelinking)
+${SHLIB_NAME}: ${SOBJS} beforelinking
+.else
 ${SHLIB_NAME}: ${SOBJS}
+.endif
 	@${ECHO} building shared library ${SHLIB_NAME}
 	@rm -f ${.TARGET} ${SHLIB_LINK}
 .if defined(SHLIB_LINK)
diff --git a/share/mk/bsd.prog.mk b/share/mk/bsd.prog.mk
index f483a7eac52..06a89d8e0dc 100644
--- a/share/mk/bsd.prog.mk
+++ b/share/mk/bsd.prog.mk
@@ -60,7 +60,11 @@ LDADD+=	-lobjc -lpthread
 
 OBJS+=  ${SRCS:N*.h:R:S/$/.o/g}
 
-${PROG}: ${OBJS}
+.if target(beforelinking)
+${PROG}: ${OBJS} beforelinking
+.else
+${PROG}: ${OBJS} beforelinking
+.endif
 .if defined(PROG_CXX)
 	${CXX} ${CXXFLAGS} ${LDFLAGS} -o ${.TARGET} ${OBJS} ${LDADD}
 .else
@@ -86,7 +90,11 @@ SRCS=	${PROG}.c
 # - it's useful to keep objects around for crunching.
 OBJS=	${PROG}.o
 
+.if target(beforelinking)
+${PROG}: ${OBJS} beforelinking
+.else
 ${PROG}: ${OBJS}
+.endif
 .if defined(PROG_CXX)
 	${CXX} ${CXXFLAGS} ${LDFLAGS} -o ${.TARGET} ${OBJS} ${LDADD}
 .else

From 6a4e245b76e19c5a09b70face2ea9f9e34347469 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Fri, 10 Sep 2010 16:27:09 +0000
Subject: [PATCH 0619/1624] Add bsd.dtrace.mk. This allows userland programs
 and libraries to define USDT probes on a provider.d file and then use this
 new make infrastructure to build the corresponding header file and object
 file.

This will only take effect when the user defines WITH_DTRACE when building.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/Makefile      |  3 ++-
 share/mk/bsd.dtrace.mk | 55 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 share/mk/bsd.dtrace.mk

diff --git a/share/mk/Makefile b/share/mk/Makefile
index f070d714eed..f0a7cdfe4f2 100644
--- a/share/mk/Makefile
+++ b/share/mk/Makefile
@@ -3,7 +3,8 @@
 
 FILES=	bsd.README
 FILES+=	bsd.arch.inc.mk
-FILES+=	bsd.compat.mk bsd.cpu.mk bsd.dep.mk bsd.doc.mk bsd.endian.mk
+FILES+=	bsd.compat.mk bsd.cpu.mk bsd.dep.mk bsd.doc.mk bsd.dtrace.mk
+FILES+=	bsd.endian.mk
 FILES+=	bsd.files.mk bsd.incs.mk bsd.info.mk bsd.init.mk
 FILES+=	bsd.kmod.mk
 FILES+=	bsd.lib.mk bsd.libnames.mk bsd.links.mk bsd.man.mk bsd.nls.mk
diff --git a/share/mk/bsd.dtrace.mk b/share/mk/bsd.dtrace.mk
new file mode 100644
index 00000000000..bc4d9067990
--- /dev/null
+++ b/share/mk/bsd.dtrace.mk
@@ -0,0 +1,55 @@
+# $FreeBSD$
+#
+# Copyright (c) 2010 The FreeBSD Foundation 
+# All rights reserved. 
+# 
+# This software was developed by Rui Paulo under sponsorship from the
+# FreeBSD Foundation. 
+#  
+# 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. 
+# 
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. 
+# 
+#
+# The only variable that you should define on your Makefile is 'DTRACEOBJS'.
+#
+
+.if defined(WITH_DTRACE)
+
+CFLAGS+=-DWITH_DTRACE
+DTRACEHEADERS=${DTRACEOBJS:S/o$/h/}
+DTRACESRCS=${DTRACEOBJS:S/o$/d/}
+CLEANFILES+=${DTRACEOBJS} ${DTRACEHEADERS}
+.if defined(PROG)
+_DTRACELINKING:=${OBJS}
+OBJS+=${DTRACEOBJS}
+.else
+_DTRACELINKING:=${SOBJS}
+SOBJS+=${DTRACEOBJS}
+.endif
+DPADD+=${LIBELF}
+LDADD+=-lelf
+
+beforedepend:
+	${DTRACE} -C -h -s ${DTRACESRCS}
+beforelinking:
+	${DTRACE} -G -s ${DTRACESRCS} ${_DTRACELINKING}
+
+.endif

From 4d369413e19e5195fe4babcb74980c4cff21df03 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 10 Sep 2010 16:42:16 +0000
Subject: [PATCH 0620/1624] Replace sbuf_overflowed() with sbuf_error(), which
 returns any error code associated with overflow or with the drain function. 
 While this function is not expected to be used often, it produces more
 information in the form of an errno that sbuf_overflowed() did.

---
 share/man/man9/Makefile                       |  2 +-
 share/man/man9/sbuf.9                         | 19 ++++---
 .../opensolaris/uts/common/fs/zfs/zfs_fm.c    | 10 ++--
 sys/compat/linux/linux_ioctl.c                |  4 +-
 sys/kern/kern_sig.c                           |  2 +-
 sys/kern/subr_sbuf.c                          | 53 +++++++++----------
 sys/net/if.c                                  |  4 +-
 sys/security/audit/audit_bsm_klib.c           |  2 +-
 sys/sys/sbuf.h                                |  3 +-
 9 files changed, 51 insertions(+), 48 deletions(-)

diff --git a/share/man/man9/Makefile b/share/man/man9/Makefile
index 6abafe19e09..194eba47137 100644
--- a/share/man/man9/Makefile
+++ b/share/man/man9/Makefile
@@ -1025,10 +1025,10 @@ MLINKS+=sbuf.9 sbuf_bcat.9 \
 	sbuf.9 sbuf_data.9 \
 	sbuf.9 sbuf_delete.9 \
 	sbuf.9 sbuf_done.9 \
+	sbuf.9 sbuf_error.9 \
 	sbuf.9 sbuf_finish.9 \
 	sbuf.9 sbuf_len.9 \
 	sbuf.9 sbuf_new.9 \
-	sbuf.9 sbuf_overflowed.9 \
 	sbuf.9 sbuf_printf.9 \
 	sbuf.9 sbuf_putc.9 \
 	sbuf.9 sbuf_set_drain.9 \
diff --git a/share/man/man9/sbuf.9 b/share/man/man9/sbuf.9
index 7389064544f..0b6aa908d07 100644
--- a/share/man/man9/sbuf.9
+++ b/share/man/man9/sbuf.9
@@ -45,7 +45,7 @@
 .Nm sbuf_putc ,
 .Nm sbuf_set_drain ,
 .Nm sbuf_trim ,
-.Nm sbuf_overflowed ,
+.Nm sbuf_error ,
 .Nm sbuf_finish ,
 .Nm sbuf_data ,
 .Nm sbuf_len ,
@@ -88,7 +88,7 @@
 .Ft int
 .Fn sbuf_trim "struct sbuf *s"
 .Ft int
-.Fn sbuf_overflowed "struct sbuf *s"
+.Fn sbuf_error "struct sbuf *s"
 .Ft int
 .Fn sbuf_finish "struct sbuf *s"
 .Ft char *
@@ -332,10 +332,15 @@ function removes trailing whitespace from the
 .Fa sbuf .
 .Pp
 The
-.Fn sbuf_overflowed
-function returns a non-zero value if the
+.Fn sbuf_error
+function returns any error value that the
+.Fa sbuf
+may have accumulated, either from the drain function, or ENOMEM if the
 .Fa sbuf
 overflowed.
+This function is generally not needed and instead the error code from
+.Fn sbuf_finish
+is the preferred way to discover whether an sbuf had an error.
 .Pp
 The
 .Fn sbuf_finish
@@ -437,9 +442,9 @@ functions
 all return \-1 if the buffer overflowed, and zero otherwise.
 .Pp
 The
-.Fn sbuf_overflowed
-function
-returns a non-zero value if the buffer overflowed, and zero otherwise.
+.Fn sbuf_error
+function returns a non-zero value if the buffer has an overflow or
+drain error, and zero otherwise.
 .Pp
 The
 .Fn sbuf_data
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_fm.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_fm.c
index 63ae13ac856..cf2f90db69d 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_fm.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_fm.c
@@ -101,6 +101,7 @@ zfs_ereport_post(const char *subclass, spa_t *spa, vdev_t *vd, zio_t *zio,
 	char buf[1024];
 	struct sbuf sb;
 	struct timespec ts;
+	int error;
 
 	/*
 	 * If we are doing a spa_tryimport(), ignore errors.
@@ -315,9 +316,9 @@ zfs_ereport_post(const char *subclass, spa_t *spa, vdev_t *vd, zio_t *zio,
 	}
 	mutex_exit(&spa->spa_errlist_lock);
 
-	sbuf_finish(&sb);
+	error = sbuf_finish(&sb);
 	devctl_notify("ZFS", spa->spa_name, subclass, sbuf_data(&sb));
-	if (sbuf_overflowed(&sb))
+	if (error != 0)
 		printf("ZFS WARNING: sbuf overflowed\n");
 	sbuf_delete(&sb);
 #endif
@@ -331,6 +332,7 @@ zfs_post_common(spa_t *spa, vdev_t *vd, const char *name)
 	char class[64];
 	struct sbuf sb;
 	struct timespec ts;
+	int error;
 
 	nanotime(&ts);
 
@@ -346,10 +348,10 @@ zfs_post_common(spa_t *spa, vdev_t *vd, const char *name)
 	if (vd)
 		sbuf_printf(&sb, " %s=%ju", FM_EREPORT_PAYLOAD_ZFS_VDEV_GUID,
 		    vd->vdev_guid);
-	sbuf_finish(&sb);
+	error = sbuf_finish(&sb);
 	ZFS_LOG(1, "%s", sbuf_data(&sb));
 	devctl_notify("ZFS", spa->spa_name, class, sbuf_data(&sb));
-	if (sbuf_overflowed(&sb))
+	if (error != 0)
 		printf("ZFS WARNING: sbuf overflowed\n");
 	sbuf_delete(&sb);
 #endif
diff --git a/sys/compat/linux/linux_ioctl.c b/sys/compat/linux/linux_ioctl.c
index b6de86a3c01..07a281e2926 100644
--- a/sys/compat/linux/linux_ioctl.c
+++ b/sys/compat/linux/linux_ioctl.c
@@ -2220,7 +2220,7 @@ again:
 				addrs++;
 			}
 
-			if (!sbuf_overflowed(sb))
+			if (sbuf_error(sb) == 0)
 				valid_len = sbuf_len(sb);
 		}
 		if (addrs == 0) {
@@ -2228,7 +2228,7 @@ again:
 			sbuf_bcat(sb, &ifr, sizeof(ifr));
 			max_len += sizeof(ifr);
 
-			if (!sbuf_overflowed(sb))
+			if (sbuf_error(sb) == 0)
 				valid_len = sbuf_len(sb);
 		}
 	}
diff --git a/sys/kern/kern_sig.c b/sys/kern/kern_sig.c
index f54d59e59f2..d315ff1a401 100644
--- a/sys/kern/kern_sig.c
+++ b/sys/kern/kern_sig.c
@@ -3093,7 +3093,7 @@ expand_name(const char *name, uid_t uid, pid_t pid, struct thread *td,
 		sbuf_printf(&sb, GZ_SUFFIX);
 	}
 #endif
-	if (sbuf_overflowed(&sb)) {
+	if (sbuf_error(&sb) != 0) {
 		log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
 		    "long\n", (long)pid, name, (u_long)uid);
 nomem:
diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 58964fb1d85..4535337486b 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -66,7 +66,6 @@ static MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
 #define	SBUF_ISDYNAMIC(s)	((s)->s_flags & SBUF_DYNAMIC)
 #define	SBUF_ISDYNSTRUCT(s)	((s)->s_flags & SBUF_DYNSTRUCT)
 #define	SBUF_ISFINISHED(s)	((s)->s_flags & SBUF_FINISHED)
-#define	SBUF_HASOVERFLOWED(s)	((s)->s_flags & SBUF_OVERFLOWED)
 #define	SBUF_HASROOM(s)		((s)->s_len < (s)->s_size - 1)
 #define	SBUF_FREESPACE(s)	((s)->s_size - (s)->s_len - 1)
 #define	SBUF_CANEXTEND(s)	((s)->s_flags & SBUF_AUTOEXTEND)
@@ -247,7 +246,6 @@ sbuf_clear(struct sbuf *s)
 	/* don't care if it's finished or not */
 
 	SBUF_CLEARFLAG(s, SBUF_FINISHED);
-	SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
 	s->s_error = 0;
 	s->s_len = 0;
 }
@@ -299,10 +297,10 @@ sbuf_drain(struct sbuf *s)
 	int len;
 
 	KASSERT(s->s_len > 0, ("Shouldn't drain empty sbuf %p", s));
+	KASSERT(s->s_error == 0, ("Called %s with error on %p", __func__, s));
 	len = s->s_drain_func(s->s_drain_arg, s->s_buf, s->s_len);
 	if (len < 0) {
 		s->s_error = -len;
-		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
 		return (s->s_error);
 	}
 	KASSERT(len > 0 && len <= s->s_len,
@@ -334,7 +332,7 @@ sbuf_put_byte(int c, struct sbuf *s)
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return;
 	if (SBUF_FREESPACE(s) <= 0) {
 		/* 
@@ -344,8 +342,8 @@ sbuf_put_byte(int c, struct sbuf *s)
 		if (s->s_drain_func != NULL)
 			(void)sbuf_drain(s);
 		else if (sbuf_extend(s, 1) < 0)
-			SBUF_SETFLAG(s, SBUF_OVERFLOWED);
-		if (SBUF_HASOVERFLOWED(s))
+			s->s_error = ENOMEM;
+		if (s->s_error != 0)
 			return;
 	}
 	s->s_buf[s->s_len++] = c;
@@ -375,11 +373,11 @@ sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 	for (; str < end; str++) {
 		sbuf_put_byte(*str, s);
-		if (SBUF_HASOVERFLOWED(s))
+		if (s->s_error != 0)
 			return (-1);
  	}
 	return (0);
@@ -398,7 +396,7 @@ sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
 	KASSERT(s->s_drain_func == NULL,
 	    ("Nonsensical copyin to sbuf %p with a drain", s));
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 	if (len == 0)
 		return (0);
@@ -439,12 +437,12 @@ sbuf_cat(struct sbuf *s, const char *str)
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 
 	while (*str != '\0') {
 		sbuf_put_byte(*str, s);
-		if (SBUF_HASOVERFLOWED(s))
+		if (s->s_error != 0)
 			return (-1);
 	}
 	return (0);
@@ -464,7 +462,7 @@ sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
 	KASSERT(s->s_drain_func == NULL,
 	    ("Nonsensical copyin to sbuf %p with a drain", s));
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 
 	if (len == 0)
@@ -476,7 +474,7 @@ sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
 	}
 	switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
 	case ENAMETOOLONG:
-		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
+		s->s_error = ENOMEM;
 		/* fall through */
 	case 0:
 		s->s_len += done - 1;
@@ -518,7 +516,7 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 	    ("%s called with a NULL format string", __func__));
 
 	(void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 	return (0);
 }
@@ -535,7 +533,7 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 	KASSERT(fmt != NULL,
 	    ("%s called with a NULL format string", __func__));
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 
 	/*
@@ -578,12 +576,12 @@ sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
 		len = SBUF_FREESPACE(s);
 	s->s_len += len;
 	if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
-		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
+		s->s_error = ENOMEM;
 
 	KASSERT(s->s_len < s->s_size,
 	    ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 	return (0);
 }
@@ -612,7 +610,7 @@ sbuf_putc(struct sbuf *s, int c)
 {
 
 	sbuf_putc_func(c, s);
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 	return (0);
 }
@@ -629,7 +627,7 @@ sbuf_trim(struct sbuf *s)
 	KASSERT(s->s_drain_func == NULL,
 	    ("%s makes no sense on sbuf %p with drain", __func__, s));
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 
 	while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1]))
@@ -639,13 +637,13 @@ sbuf_trim(struct sbuf *s)
 }
 
 /*
- * Check if an sbuf overflowed
+ * Check if an sbuf has an error.
  */
 int
-sbuf_overflowed(struct sbuf *s)
+sbuf_error(struct sbuf *s)
 {
 
-	return (SBUF_HASOVERFLOWED(s));
+	return (s->s_error);
 }
 
 /*
@@ -654,19 +652,18 @@ sbuf_overflowed(struct sbuf *s)
 int
 sbuf_finish(struct sbuf *s)
 {
-	int error = 0;
+	int error;
 
 	assert_sbuf_integrity(s);
 	assert_sbuf_state(s, 0);
 
+	error = s->s_error;
 	if (s->s_drain_func != NULL) {
-		error = s->s_error;
 		while (s->s_len > 0 && error == 0)
 			error = sbuf_drain(s);
-	} else if (SBUF_HASOVERFLOWED(s))
-		error = ENOMEM;
+	}
 	s->s_buf[s->s_len] = '\0';
-	SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
+	s->s_error = 0;
 	SBUF_SETFLAG(s, SBUF_FINISHED);
 #ifdef _KERNEL
 	return (error);
@@ -703,7 +700,7 @@ sbuf_len(struct sbuf *s)
 	KASSERT(s->s_drain_func == NULL,
 	    ("%s makes no sense on sbuf %p with drain", __func__, s));
 
-	if (SBUF_HASOVERFLOWED(s))
+	if (s->s_error != 0)
 		return (-1);
 	return (s->s_len);
 }
diff --git a/sys/net/if.c b/sys/net/if.c
index c387dbf498f..bd54acf28c2 100644
--- a/sys/net/if.c
+++ b/sys/net/if.c
@@ -2726,7 +2726,7 @@ again:
 				max_len += sa->sa_len;
 			}
 
-			if (!sbuf_overflowed(sb))
+			if (sbuf_error(sb) == 0)
 				valid_len = sbuf_len(sb);
 		}
 		IF_ADDR_UNLOCK(ifp);
@@ -2735,7 +2735,7 @@ again:
 			sbuf_bcat(sb, &ifr, sizeof(ifr));
 			max_len += sizeof(ifr);
 
-			if (!sbuf_overflowed(sb))
+			if (sbuf_error(sb) == 0)
 				valid_len = sbuf_len(sb);
 		}
 	}
diff --git a/sys/security/audit/audit_bsm_klib.c b/sys/security/audit/audit_bsm_klib.c
index c8d40356cfe..f26f86cabc9 100644
--- a/sys/security/audit/audit_bsm_klib.c
+++ b/sys/security/audit/audit_bsm_klib.c
@@ -548,7 +548,7 @@ audit_canon_path(struct thread *td, char *path, char *cpath)
 	 * the supplied buffer being overflowed.  Check to see if this is the
 	 * case.
 	 */
-	if (sbuf_overflowed(&sbf) != 0) {
+	if (sbuf_error(&sbf) != 0) {
 		cpath[0] = '\0';
 		return;
 	}
diff --git a/sys/sys/sbuf.h b/sys/sys/sbuf.h
index be3d80c5240..eeb38140da5 100644
--- a/sys/sys/sbuf.h
+++ b/sys/sys/sbuf.h
@@ -51,7 +51,6 @@ struct sbuf {
 #define	SBUF_USRFLAGMSK	0x0000ffff	/* mask of flags the user may specify */
 #define	SBUF_DYNAMIC	0x00010000	/* s_buf must be freed */
 #define	SBUF_FINISHED	0x00020000	/* set by sbuf_finish() */
-#define	SBUF_OVERFLOWED	0x00040000	/* sbuf overflowed */
 #define	SBUF_DYNSTRUCT	0x00080000	/* sbuf must be freed */
 	int		 s_flags;	/* flags */
 };
@@ -76,7 +75,7 @@ int		 sbuf_vprintf(struct sbuf *, const char *, __va_list)
 int		 sbuf_putc(struct sbuf *, int);
 void		 sbuf_set_drain(struct sbuf *, sbuf_drain_func *, void *);
 int		 sbuf_trim(struct sbuf *);
-int		 sbuf_overflowed(struct sbuf *);
+int		 sbuf_error(struct sbuf *);
 int		 sbuf_finish(struct sbuf *);
 char		*sbuf_data(struct sbuf *);
 int		 sbuf_len(struct sbuf *);

From 9feea9c1f41f12d8c656962ed9cb19b0082e30ac Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Fri, 10 Sep 2010 17:00:48 +0000
Subject: [PATCH 0621/1624] Fix typo in previous commit.

---
 share/mk/bsd.prog.mk | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/share/mk/bsd.prog.mk b/share/mk/bsd.prog.mk
index 06a89d8e0dc..9489e349ef0 100644
--- a/share/mk/bsd.prog.mk
+++ b/share/mk/bsd.prog.mk
@@ -63,7 +63,7 @@ OBJS+=  ${SRCS:N*.h:R:S/$/.o/g}
 .if target(beforelinking)
 ${PROG}: ${OBJS} beforelinking
 .else
-${PROG}: ${OBJS} beforelinking
+${PROG}: ${OBJS}
 .endif
 .if defined(PROG_CXX)
 	${CXX} ${CXXFLAGS} ${LDFLAGS} -o ${.TARGET} ${OBJS} ${LDADD}

From 51ccb83a3923175922a8abde93fb985e719f71e2 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Fri, 10 Sep 2010 17:44:11 +0000
Subject: [PATCH 0622/1624] Fix bugs introduced in the previous rev: * add a
 phatom target for the DTRACEOBJS * when invoking DTrace, don't add DTRACEOBJS
 to the command line.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/bsd.dtrace.mk | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/share/mk/bsd.dtrace.mk b/share/mk/bsd.dtrace.mk
index bc4d9067990..bebe969ccf1 100644
--- a/share/mk/bsd.dtrace.mk
+++ b/share/mk/bsd.dtrace.mk
@@ -37,19 +37,23 @@ CFLAGS+=-DWITH_DTRACE
 DTRACEHEADERS=${DTRACEOBJS:S/o$/h/}
 DTRACESRCS=${DTRACEOBJS:S/o$/d/}
 CLEANFILES+=${DTRACEOBJS} ${DTRACEHEADERS}
-.if defined(PROG)
-_DTRACELINKING:=${OBJS}
-OBJS+=${DTRACEOBJS}
-.else
-_DTRACELINKING:=${SOBJS}
-SOBJS+=${DTRACEOBJS}
-.endif
+
 DPADD+=${LIBELF}
 LDADD+=-lelf
 
+.if defined(PROG)
+_DTRACELINKING=${OBJS}
+OBJS+=${DTRACEOBJS}
+.else
+_DTRACELINKING=${SOBJS}
+SOBJS+=${DTRACEOBJS}
+.endif
+
+${DTRACEOBJS}:
+
 beforedepend:
 	${DTRACE} -C -h -s ${DTRACESRCS}
 beforelinking:
-	${DTRACE} -G -s ${DTRACESRCS} ${_DTRACELINKING}
+	${DTRACE} -G -s ${DTRACESRCS} ${_DTRACELINKING:S/${DTRACEOBJS}//}
 
 .endif

From 0b57f2cd45a90954ff8f20968c70476909a29fd5 Mon Sep 17 00:00:00 2001
From: "David E. O'Brien" 
Date: Fri, 10 Sep 2010 18:19:38 +0000
Subject: [PATCH 0623/1624] Add real dependancies on the uuencoded firmwares.
 Now when one does 'make kernel ; make kernel' the second invocation only
 does:  `kernel.ko' is up to date. rather than reproduce all the .fw files and
 relink the kernel.

---
 sys/conf/files | 38 +++++++++++++++++++-------------------
 1 file changed, 19 insertions(+), 19 deletions(-)

diff --git a/sys/conf/files b/sys/conf/files
index a08d6bd6ed2..f84e668bbfb 100644
--- a/sys/conf/files
+++ b/sys/conf/files
@@ -1064,7 +1064,7 @@ ipw_bss.fwo			optional ipwbssfw | ipwfw		\
 	no-implicit-rule						\
 	clean		"ipw_bss.fwo"
 ipw_bss.fw			optional ipwbssfw | ipwfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ipw/ipw2100-1.3.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ipw/ipw2100-1.3.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"ipw_bss.fw"
@@ -1078,7 +1078,7 @@ ipw_ibss.fwo			optional ipwibssfw | ipwfw		\
 	no-implicit-rule						\
 	clean		"ipw_ibss.fwo"
 ipw_ibss.fw			optional ipwibssfw | ipwfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ipw/ipw2100-1.3-i.fw.uu"	\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ipw/ipw2100-1.3-i.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"ipw_ibss.fw"
@@ -1092,7 +1092,7 @@ ipw_monitor.fwo			optional ipwmonitorfw | ipwfw		\
 	no-implicit-rule						\
 	clean		"ipw_monitor.fwo"
 ipw_monitor.fw			optional ipwmonitorfw | ipwfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ipw/ipw2100-1.3-p.fw.uu"	\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ipw/ipw2100-1.3-p.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"ipw_monitor.fw"
@@ -1120,7 +1120,7 @@ iwi_bss.fwo			optional iwibssfw | iwifw		\
 	no-implicit-rule						\
 	clean		"iwi_bss.fwo"
 iwi_bss.fw			optional iwibssfw | iwifw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwi/ipw2200-bss.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwi/ipw2200-bss.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwi_bss.fw"
@@ -1134,7 +1134,7 @@ iwi_ibss.fwo			optional iwiibssfw | iwifw		\
 	no-implicit-rule						\
 	clean		"iwi_ibss.fwo"
 iwi_ibss.fw			optional iwiibssfw | iwifw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwi/ipw2200-ibss.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwi/ipw2200-ibss.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwi_ibss.fw"
@@ -1148,7 +1148,7 @@ iwi_monitor.fwo			optional iwimonitorfw | iwifw		\
 	no-implicit-rule						\
 	clean		"iwi_monitor.fwo"
 iwi_monitor.fw			optional iwimonitorfw | iwifw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwi/ipw2200-sniffer.fw.uu"	\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwi/ipw2200-sniffer.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwi_monitor.fw"
@@ -1163,7 +1163,7 @@ iwn1000fw.fwo			optional iwn1000fw | iwnfw		\
 	no-implicit-rule						\
 	clean		"iwn1000fw.fwo"
 iwn1000.fw			optional iwn1000fw | iwnfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwn/iwlwifi-1000-128.50.3.1.fw.uu" \
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwn/iwlwifi-1000-128.50.3.1.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwn1000.fw"
@@ -1177,7 +1177,7 @@ iwn4965fw.fwo			optional iwn4965fw | iwnfw		\
 	no-implicit-rule						\
 	clean		"iwn4965fw.fwo"
 iwn4965.fw			optional iwn4965fw | iwnfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwn/iwlwifi-4965-228.61.2.24.fw.uu" \
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwn/iwlwifi-4965-228.61.2.24.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwn4965.fw"
@@ -1191,7 +1191,7 @@ iwn5000fw.fwo		optional iwn5000fw | iwnfw			\
 	no-implicit-rule						\
 	clean		"iwn5000fw.fwo"
 iwn5000.fw			optional iwn5000fw | iwnfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwn/iwlwifi-5000-8.24.2.12.fw.uu" \
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwn/iwlwifi-5000-8.24.2.12.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"iwn5000.fw"
@@ -1205,7 +1205,7 @@ iwn5150fw.fwo			optional iwn5150fw | iwnfw		\
 	no-implicit-rule						\
 	clean		"iwn5150fw.fwo"
 iwn5150.fw			optional iwn5150fw | iwnfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwn/iwlwifi-5150-8.24.2.2.fw.uu"\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwn/iwlwifi-5150-8.24.2.2.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwn5150.fw"
@@ -1219,7 +1219,7 @@ iwn6000fw.fwo			optional iwn6000fw | iwnfw		\
 	no-implicit-rule						\
 	clean		"iwn6000fw.fwo"
 iwn6000.fw			optional iwn6000fw | iwnfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwn/iwlwifi-6000-9.221.4.1.fw.uu" \
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwn/iwlwifi-6000-9.221.4.1.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwn6000.fw"
@@ -1233,7 +1233,7 @@ iwn6050fw.fwo			optional iwn6050fw | iwnfw		\
 	no-implicit-rule						\
 	clean		"iwn6050fw.fwo"
 iwn6050.fw			optional iwn6050fw | iwnfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/iwn/iwlwifi-6050-9.201.4.1.fw.uu" \
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/iwn/iwlwifi-6050-9.201.4.1.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"iwn6000.fw"
@@ -1356,7 +1356,7 @@ mw88W8363.fwo		optional mwlfw					\
 	no-implicit-rule						\
 	clean		"mw88W8363.fwo"
 mw88W8363.fw		optional mwlfw					\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/mwl/mw88W8363.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/mwl/mw88W8363.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"mw88W8363.fw"
@@ -1366,7 +1366,7 @@ mwlboot.fwo		optional mwlfw					\
 	no-implicit-rule						\
 	clean		"mwlboot.fwo"
 mwlboot.fw		optional mwlfw					\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/mwl/mwlboot.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/mwl/mwlboot.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"mwlboot.fw"
@@ -1471,7 +1471,7 @@ rt2561fw.fwo			optional rt2561fw | ralfw		\
 	no-implicit-rule						\
 	clean		"rt2561fw.fwo"
 rt2561.fw			optional rt2561fw | ralfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ral/rt2561.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ral/rt2561.fw.uu" \
 	no-obj no-implicit-rule						\
 	clean		"rt2561.fw"
@@ -1485,7 +1485,7 @@ rt2561sfw.fwo			optional rt2561sfw | ralfw		\
 	no-implicit-rule						\
 	clean		"rt2561sfw.fwo"
 rt2561s.fw			optional rt2561sfw | ralfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ral/rt2561s.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ral/rt2561s.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"rt2561s.fw"
@@ -1499,7 +1499,7 @@ rt2661fw.fwo			optional rt2661fw | ralfw		\
 	no-implicit-rule						\
 	clean		"rt2661fw.fwo"
 rt2661.fw			optional rt2661fw | ralfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ral/rt2661.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ral/rt2661.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"rt2661.fw"
@@ -1513,7 +1513,7 @@ rt2860fw.fwo			optional rt2860fw | ralfw		\
 	no-implicit-rule						\
 	clean		"rt2860fw.fwo"
 rt2860.fw			optional rt2860fw | ralfw		\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/ral/rt2860.fw.uu"		\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/ral/rt2860.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"rt2860.fw"
@@ -1873,7 +1873,7 @@ wpifw.fwo			optional wpifw				\
 	no-implicit-rule						\
 	clean		"wpifw.fwo"
 wpi.fw			optional wpifw					\
-	dependency	".PHONY"					\
+	dependency	"$S/contrib/dev/wpi/iwlwifi-3945-2.14.4.fw.uu"	\
 	compile-with	"uudecode -o ${.TARGET} $S/contrib/dev/wpi/iwlwifi-3945-2.14.4.fw.uu"	\
 	no-obj no-implicit-rule						\
 	clean		"wpi.fw"

From 85451f90f1cc1ed46fdad6eba3a4cb22ad8290fb Mon Sep 17 00:00:00 2001
From: Colin Percival 
Date: Fri, 10 Sep 2010 19:20:52 +0000
Subject: [PATCH 0624/1624] Remind the user that he needs to run
 'freebsd-update install' to install new bits after downloading them using
 'freebsd-update upgrade'.

Submitted by:	bapt
MFC after:	1 month
---
 usr.sbin/freebsd-update/freebsd-update.sh | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/usr.sbin/freebsd-update/freebsd-update.sh b/usr.sbin/freebsd-update/freebsd-update.sh
index e1453c67d6d..0539eb3c0ae 100644
--- a/usr.sbin/freebsd-update/freebsd-update.sh
+++ b/usr.sbin/freebsd-update/freebsd-update.sh
@@ -2528,6 +2528,10 @@ upgrade_run () {
 	# Leave a note behind to tell the "install" command that the kernel
 	# needs to be installed before the world.
 	touch ${BDHASH}-install/kernelfirst
+
+	# Remind the user that they need to run "freebsd-update install"
+	# to install the downloaded bits, in case they didn't RTFM.
+	echo "To install the downloaded upgrades, run \"$0 install\"."
 }
 
 # Make sure that all the file hashes mentioned in $@ have corresponding

From adbcc9964d3218bfae0b81b2dce753d95cbae076 Mon Sep 17 00:00:00 2001
From: Colin Percival 
Date: Fri, 10 Sep 2010 19:23:59 +0000
Subject: [PATCH 0625/1624] Add warning about freebsd-update upgrade needing
 lots of disk space.

Submitted by:	jpaetzel
MFC after:	1 month
---
 usr.sbin/freebsd-update/freebsd-update.8 | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/usr.sbin/freebsd-update/freebsd-update.8 b/usr.sbin/freebsd-update/freebsd-update.8
index 6741f422ca9..87f786a2c81 100644
--- a/usr.sbin/freebsd-update/freebsd-update.8
+++ b/usr.sbin/freebsd-update/freebsd-update.8
@@ -128,6 +128,11 @@ Fetch files necessary for upgrading to a new release.
 Before using this command, make sure that you read the
 announcement and release notes for the new release in
 case there are any special steps needed for upgrading.
+Note that this command may require up to 500 MB of space in
+.Ar workdir
+depending on which components of the
+.Fx
+base system are installed.
 .It Cm install
 Install the most recently fetched updates or upgrade.
 .It Cm rollback

From 211f2ba07f7e02e9742848a2c0bf13bf4b472658 Mon Sep 17 00:00:00 2001
From: Colin Percival 
Date: Fri, 10 Sep 2010 20:20:28 +0000
Subject: [PATCH 0626/1624] "freebsd-update fetch -r NEWRELEASE" is meaningless
 and probably a typo for "freebsd-update upgrade -r NEWRELEASE".  Error out
 and suggest what the user probably meant.

Submitted by:	James Seward
MFC after:	1 month
---
 usr.sbin/freebsd-update/freebsd-update.sh | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/usr.sbin/freebsd-update/freebsd-update.sh b/usr.sbin/freebsd-update/freebsd-update.sh
index 0539eb3c0ae..b5420776423 100644
--- a/usr.sbin/freebsd-update/freebsd-update.sh
+++ b/usr.sbin/freebsd-update/freebsd-update.sh
@@ -572,7 +572,7 @@ fetch_setup_verboselevel () {
 # running *-p[0-9]+, strip off the last part; if the
 # user is running -SECURITY, call it -RELEASE.  Chdir
 # into the working directory.
-fetch_check_params () {
+fetchupgrade_check_params () {
 	export HTTP_USER_AGENT="freebsd-update (${COMMAND}, `uname -r`)"
 
 	_SERVERNAME_z=\
@@ -655,9 +655,21 @@ fetch_check_params () {
 	BDHASH=`echo ${BASEDIR} | sha256 -q`
 }
 
+# Perform sanity checks etc. before fetching updates.
+fetch_check_params () {
+	fetchupgrade_check_params
+
+	if ! [ -z "${TARGETRELEASE}" ]; then
+		echo -n "`basename $0`: "
+		echo -n "-r option is meaningless with 'fetch' command.  "
+		echo "(Did you mean 'upgrade' instead?)"
+		exit 1
+	fi
+}
+
 # Perform sanity checks etc. before fetching upgrades.
 upgrade_check_params () {
-	fetch_check_params
+	fetchupgrade_check_params
 
 	# Unless set otherwise, we're upgrading to the same kernel config.
 	NKERNCONF=${KERNCONF}

From 87eb4065762d0dac3f85c9c7b398d6da523875c4 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Fri, 10 Sep 2010 20:42:41 +0000
Subject: [PATCH 0627/1624] Mark the sbuf_overflowed(9) manpage as obsolete
 since it has been renamed.

Noticed by:	jhb
---
 ObsoleteFiles.inc | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/ObsoleteFiles.inc b/ObsoleteFiles.inc
index 1e9c9d68adf..dfb69d17001 100644
--- a/ObsoleteFiles.inc
+++ b/ObsoleteFiles.inc
@@ -14,6 +14,8 @@
 # The file is partitioned: OLD_FILES first, then OLD_LIBS and OLD_DIRS last.
 #
 
+# 20100910: renamed sbuf_overflowed to sbuf_error
+OLD_FILES+=usr/share/man/man9/sbuf_overflowed.9.gz
 # 20100815: retired last traces of chooseproc(9)
 OLD_FILES+=usr/share/man/man9/chooseproc.9.gz
 # 20100806: removal of unused libcompat routines

From f337198db0c11d6a3881793da22ca529aa0c13b3 Mon Sep 17 00:00:00 2001
From: Jamie Gritton 
Date: Fri, 10 Sep 2010 21:45:42 +0000
Subject: [PATCH 0628/1624] Don't exit kern_jail_set without freeing options
 when enforce_statfs has an illegal value.

MFC after:	3 days
---
 sys/kern/kern_jail.c | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)

diff --git a/sys/kern/kern_jail.c b/sys/kern/kern_jail.c
index ded2379acbf..4882e8e83eb 100644
--- a/sys/kern/kern_jail.c
+++ b/sys/kern/kern_jail.c
@@ -584,12 +584,15 @@ kern_jail_set(struct thread *td, struct uio *optuio, int flags)
 		gotchildmax = 1;
 
 	error = vfs_copyopt(opts, "enforce_statfs", &enforce, sizeof(enforce));
-	gotenforce = (error == 0);
-	if (gotenforce) {
-		if (enforce < 0 || enforce > 2)
-			return (EINVAL);
-	} else if (error != ENOENT)
+	if (error == ENOENT)
+		gotenforce = 0;
+	else if (error != 0)
 		goto done_free;
+	else if (enforce < 0 || enforce > 2) {
+		error = EINVAL;
+		goto done_free;
+	} else
+		gotenforce = 1;
 
 	pr_flags = ch_flags = 0;
 	for (fi = 0; fi < sizeof(pr_flag_names) / sizeof(pr_flag_names[0]);

From cbd5df1c0430ce05e67b2b76e793b3d155d9ce01 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Fri, 10 Sep 2010 23:15:05 +0000
Subject: [PATCH 0629/1624] Add EINVAL to list of possible return values for
 cpuset_getaffinity(2).

PR:		149978
Submitted by:	gcooper
Patch by:	gcooper
Approved by:	keramida (mentor)
MFC after:	1 week
---
 lib/libc/sys/cpuset_getaffinity.2 | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/lib/libc/sys/cpuset_getaffinity.2 b/lib/libc/sys/cpuset_getaffinity.2
index c8b272f0aef..26d72ef7985 100644
--- a/lib/libc/sys/cpuset_getaffinity.2
+++ b/lib/libc/sys/cpuset_getaffinity.2
@@ -121,6 +121,12 @@ The
 or
 .Fa which
 argument was not a valid value.
+.It Bq Er EINVAL
+The
+.Fa mask
+argument specified when calling
+.Fn cpuset_setaffinity
+was not a valid value.
 .It Bq Er EDEADLK
 The
 .Fn cpuset_setaffinity

From 37fe68325050134b4f984a039de880935b72dcf6 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Fri, 10 Sep 2010 23:18:45 +0000
Subject: [PATCH 0630/1624] Fix the NFSVNO_CMPFH() macro in the experimental
 NFS server so that it works correctly for ZFS file handles. It is possible to
 have two ZFS file handles that differ only in the bytes in the fid_reserved
 field of the generic "struct fid" and comparing the bytes in fid_data didn't
 catch this case. This patch changes the macro to compare all bytes of "struct
 fid".

Tested by:	gull at gull.us
MFC after:	2 weeks
---
 sys/fs/nfs/nfsdport.h | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/sys/fs/nfs/nfsdport.h b/sys/fs/nfs/nfsdport.h
index 42dbe082f98..fdba9169987 100644
--- a/sys/fs/nfs/nfsdport.h
+++ b/sys/fs/nfs/nfsdport.h
@@ -70,8 +70,7 @@ struct nfsexstuff {
 #define	NFSVNO_CMPFH(f1, f2)						\
     ((f1)->fh_fsid.val[0] == (f2)->fh_fsid.val[0] &&			\
      (f1)->fh_fsid.val[1] == (f2)->fh_fsid.val[1] &&			\
-     !bcmp((f1)->fh_fid.fid_data, (f2)->fh_fid.fid_data,		\
-            (f1)->fh_fid.fid_len))
+     bcmp(&(f1)->fh_fid, &(f2)->fh_fid, sizeof(struct fid)) == 0)
 
 #define	NFSLOCKHASH(f) 							\
 	(&nfslockhash[(*((u_int32_t *)((f)->fh_fid.fid_data))) % NFSLOCKHASHSIZE])

From 9d839c44c148f91b74373015284f435a490717c0 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Fri, 10 Sep 2010 23:22:01 +0000
Subject: [PATCH 0631/1624] Add RETURN VALUES section to
 devclass_get_maxunit(9).

PR:		149979
Submitted by:	gcooper
Patch by:	gcooper
Approved by:	keramida (mentor)
MFC after:	1 week
---
 share/man/man9/devclass_get_maxunit.9 | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/share/man/man9/devclass_get_maxunit.9 b/share/man/man9/devclass_get_maxunit.9
index c1fa694cbf8..63b8490ebfc 100644
--- a/share/man/man9/devclass_get_maxunit.9
+++ b/share/man/man9/devclass_get_maxunit.9
@@ -43,6 +43,19 @@
 Returns the next unit number to be allocated to device instances in the
 .Dv devclass .
 This is one greater than the highest currently allocated unit.
+.Sh RETURN VALUES
+The
+.Fn devclass_get_maxunit
+function returns -1 if
+.Fa dc
+is 
+.Dv NULL;
+otherwise it returns the next unit
+number in
+.Fa dc's
+devclass.
+.Sh ERRORS
+None.
 .Sh SEE ALSO
 .Xr devclass 9 ,
 .Xr device 9

From 1569ab8c492d45f438b8240d52d163a1eb13e629 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Fri, 10 Sep 2010 23:24:55 +0000
Subject: [PATCH 0632/1624] Note O_SYNC and O_NOFOLLOW flags in dbopen(3) since
 r190497.

PR:		150030
Submitted by:	Janne Snabb snabb at epipe com
Patch by:	Janne Snabb
Approved by:	keramida (mentor)
MFC after:	1 week
---
 lib/libc/db/man/dbopen.3 | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/libc/db/man/dbopen.3 b/lib/libc/db/man/dbopen.3
index 7ef7ae79afe..7a9f548bfd2 100644
--- a/lib/libc/db/man/dbopen.3
+++ b/lib/libc/db/man/dbopen.3
@@ -78,8 +78,8 @@ arguments
 are as specified to the
 .Xr open 2
 routine, however, only the
-.Dv O_CREAT , O_EXCL , O_EXLOCK , O_NONBLOCK ,
-.Dv O_RDONLY , O_RDWR , O_SHLOCK
+.Dv O_CREAT , O_EXCL , O_EXLOCK , O_NOFOLLOW , O_NONBLOCK ,
+.Dv O_RDONLY , O_RDWR , O_SHLOCK , O_SYNC
 and
 .Dv O_TRUNC
 flags are meaningful.

From 2c6d0e01f8bb5e96fea9e80c7f21f8a005cc2d97 Mon Sep 17 00:00:00 2001
From: Rick Macklem 
Date: Fri, 10 Sep 2010 23:49:33 +0000
Subject: [PATCH 0633/1624] This patch applies one of the two fixes suggested
 by zack.kirsch at isilon.com for a race between nfsrv_freeopen() and
 nfsrv_getlockfile() in the experimental NFS server that he found during
 testing. Although nfsrv_freeopen() holds a sleep lock on the lock file
 structure when called with cansleep != 0, nfsrv_getlockfile() could still
 search the list, once it acquired the NFSLOCKSTATE() mutex. I believe that
 acquiring the mutex in nfsrv_freeopen() fixes the race.

MFC after:	2 weeks
---
 sys/fs/nfsserver/nfs_nfsdstate.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/sys/fs/nfsserver/nfs_nfsdstate.c b/sys/fs/nfsserver/nfs_nfsdstate.c
index a53175154d0..df9f0540420 100644
--- a/sys/fs/nfsserver/nfs_nfsdstate.c
+++ b/sys/fs/nfsserver/nfs_nfsdstate.c
@@ -1085,8 +1085,11 @@ nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
 	 * associated with the open.
 	 * If there are locks associated with the open, the
 	 * nfslockfile structure can be freed via nfsrv_freelockowner().
-	 * (That is why the call must be here instead of after the loop.)
+	 * Acquire the state mutex to avoid races with calls to
+	 * nfsrv_getlockfile().
 	 */
+	if (cansleep != 0)
+		NFSLOCKSTATE();
 	if (lfp != NULL && LIST_EMPTY(&lfp->lf_open) &&
 	    LIST_EMPTY(&lfp->lf_deleg) && LIST_EMPTY(&lfp->lf_lock) &&
 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
@@ -1096,6 +1099,8 @@ nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
 		ret = 1;
 	} else
 		ret = 0;
+	if (cansleep != 0)
+		NFSUNLOCKSTATE();
 	FREE((caddr_t)stp, M_NFSDSTATE);
 	newnfsstats.srvopens--;
 	nfsrv_openpluslock--;

From 707c2fb95043be2f67e9795a1f10a8be0c229e69 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 11 Sep 2010 04:45:51 +0000
Subject: [PATCH 0634/1624] Update PowerPC event timer code to use new event
 timers infrastructure.

Reviewed by:	nwitehorn
Tested by:	andreast
H/W donated by:	Gheorghe Ardelean
---
 sys/conf/files.powerpc             |   1 +
 sys/powerpc/aim/clock.c            | 178 ++++++++++++++++++++---------
 sys/powerpc/aim/interrupt.c        |   6 +-
 sys/powerpc/aim/machdep.c          |   3 +-
 sys/powerpc/booke/clock.c          | 173 +++++++++++++++++++---------
 sys/powerpc/booke/interrupt.c      |   4 +
 sys/powerpc/booke/platform_bare.c  |   2 +-
 sys/powerpc/include/intr_machdep.h |   2 +
 sys/powerpc/include/md_var.h       |   2 -
 sys/powerpc/include/smp.h          |   1 +
 sys/powerpc/powerpc/intr_machdep.c |  20 +++-
 sys/powerpc/powerpc/mp_machdep.c   |  12 +-
 12 files changed, 286 insertions(+), 118 deletions(-)

diff --git a/sys/conf/files.powerpc b/sys/conf/files.powerpc
index 409554f0e04..1a4a8ffaa4c 100644
--- a/sys/conf/files.powerpc
+++ b/sys/conf/files.powerpc
@@ -52,6 +52,7 @@ dev/syscons/scvtb.c		optional	sc
 dev/tsec/if_tsec.c		optional	tsec
 dev/tsec/if_tsec_fdt.c		optional	tsec fdt
 dev/uart/uart_cpu_powerpc.c	optional	uart aim
+kern/kern_clocksource.c		standard
 kern/syscalls.c			optional	ktr
 libkern/ashldi3.c		optional	powerpc
 libkern/ashrdi3.c		optional	powerpc
diff --git a/sys/powerpc/aim/clock.c b/sys/powerpc/aim/clock.c
index 92f0c66d306..eb3337cae9e 100644
--- a/sys/powerpc/aim/clock.c
+++ b/sys/powerpc/aim/clock.c
@@ -65,107 +65,195 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 
 #include 
 
 #include 
 #include 
+#include 
 #include 
 #include 
 
 /*
  * Initially we assume a processor with a bus frequency of 12.5 MHz.
  */
-u_long			ns_per_tick = 80;
+static int		initialized = 0;
+static u_long		ns_per_tick = 80;
 static u_long		ticks_per_sec = 12500000;
-static long		ticks_per_intr;
+static u_long		*decr_counts[MAXCPU];
 
+static int		decr_et_start(struct eventtimer *et,
+    struct bintime *first, struct bintime *period);
+static int		decr_et_stop(struct eventtimer *et);
 static timecounter_get_t	decr_get_timecount;
 
-static struct timecounter	decr_timecounter = {
+struct decr_state {
+	int	mode;	/* 0 - off, 1 - periodic, 2 - one-shot. */
+	int32_t	div;	/* Periodic divisor. */
+};
+static DPCPU_DEFINE(struct decr_state, decr_state);
+
+static struct eventtimer	decr_et;
+static struct timecounter	decr_tc = {
 	decr_get_timecount,	/* get_timecount */
 	0,			/* no poll_pps */
 	~0u,			/* counter_mask */
 	0,			/* frequency */
-	"decrementer"		/* name */
+	"timebase"		/* name */
 };
 
+/*
+ * Decrementor interrupt handler.
+ */
 void
 decr_intr(struct trapframe *frame)
 {
-	int32_t		tick, nticks;
+	struct decr_state *s = DPCPU_PTR(decr_state);
+	int		nticks = 0;
+	int32_t		val;
 
-	/*
-	 * Check whether we are initialized.
-	 */
-	if (!ticks_per_intr)
+	if (!initialized)
 		return;
 
-	/*
-	 * Based on the actual time delay since the last decrementer reload,
-	 * we arrange for earlier interrupt next time.
-	 */
-	__asm ("mfdec %0" : "=r"(tick));
-	for (nticks = 0; tick < 0; nticks++)
-		tick += ticks_per_intr;
-	mtdec(tick);
+	(*decr_counts[curcpu])++;
+
+	if (s->mode == 1) {
+		/*
+		 * Based on the actual time delay since the last decrementer
+		 * reload, we arrange for earlier interrupt next time.
+		 */
+		__asm ("mfdec %0" : "=r"(val));
+		while (val < 0) {
+			val += s->div;
+			nticks++;
+		}
+		mtdec(val);
+	} else if (s->mode == 2) {
+		nticks = 1;
+		decr_et_stop(NULL);
+	}
 
 	while (nticks-- > 0) {
-		if (PCPU_GET(cpuid) == 0)
-			hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
-		else
-			hardclock_cpu(TRAPF_USERMODE(frame));
-
-		statclock(TRAPF_USERMODE(frame));
-		if (profprocs != 0)
-			profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
+		if (decr_et.et_active)
+			decr_et.et_event_cb(&decr_et, decr_et.et_arg);
 	}
 }
 
+/*
+ * BSP early initialization.
+ */
 void
 decr_init(void)
 {
 	struct cpuref cpu;
-	register_t msr;
+	char buf[32];
 
 	/*
 	 * Check the BSP's timebase frequency. Sometimes we can't find the BSP, so fall
 	 * back to the first CPU in this case.
 	 */
-
 	if (platform_smp_get_bsp(&cpu) != 0)
 		platform_smp_first_cpu(&cpu);
-
 	ticks_per_sec = platform_timebase_freq(&cpu);
-
-	msr = mfmsr();
-	mtmsr(msr & ~PSL_EE);
-
 	ns_per_tick = 1000000000 / ticks_per_sec;
-	ticks_per_intr = ticks_per_sec / hz;
-	mtdec(ticks_per_intr);
 
 	set_cputicker(mftb, ticks_per_sec, 0);
-
-	mtmsr(msr);
+	snprintf(buf, sizeof(buf), "cpu%d:decrementer", curcpu);
+	intrcnt_add(buf, &decr_counts[curcpu]);
+	decr_et_stop(NULL);
+	initialized = 1;
 }
 
 #ifdef SMP
+/*
+ * AP early initialization.
+ */
 void
 decr_ap_init(void)
 {
+	char buf[32];
 
+	snprintf(buf, sizeof(buf), "cpu%d:decrementer", curcpu);
+	intrcnt_add(buf, &decr_counts[curcpu]);
+	decr_et_stop(NULL);
 }
 #endif
 
+/*
+ * Final initialization.
+ */
 void
 decr_tc_init(void)
 {
-	decr_timecounter.tc_frequency = ticks_per_sec;
-	tc_init(&decr_timecounter);
+
+	decr_tc.tc_frequency = ticks_per_sec;
+	tc_init(&decr_tc);
+	decr_et.et_name = "decrementer";
+	decr_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
+	    ET_FLAGS_PERCPU;
+	decr_et.et_quality = 1000;
+	decr_et.et_frequency = ticks_per_sec;
+	decr_et.et_min_period.sec = 0;
+	decr_et.et_min_period.frac =
+	    ((0x00000002LLU << 32) / ticks_per_sec) << 32;
+	decr_et.et_max_period.sec = 0x7fffffffLLU / ticks_per_sec;
+	decr_et.et_max_period.frac =
+	    ((0x7fffffffLLU << 32) / ticks_per_sec) << 32;
+	decr_et.et_start = decr_et_start;
+	decr_et.et_stop = decr_et_stop;
+	decr_et.et_priv = NULL;
+	et_register(&decr_et);
 }
 
+/*
+ * Event timer start method.
+ */
+static int
+decr_et_start(struct eventtimer *et,
+    struct bintime *first, struct bintime *period)
+{
+	struct decr_state *s = DPCPU_PTR(decr_state);
+	uint32_t fdiv;
+
+	if (period != NULL) {
+		s->mode = 1;
+		s->div = (decr_et.et_frequency * (period->frac >> 32)) >> 32;
+		if (period->sec != 0)
+			s->div += decr_et.et_frequency * period->sec;
+	} else {
+		s->mode = 2;
+		s->div = 0x7fffffff;
+	}
+	if (first != NULL) {
+		fdiv = (decr_et.et_frequency * (first->frac >> 32)) >> 32;
+		if (first->sec != 0)
+			fdiv += decr_et.et_frequency * first->sec;
+	} else
+		fdiv = s->div;
+
+	mtdec(fdiv);
+	return (0);
+}
+
+/*
+ * Event timer stop method.
+ */
+static int
+decr_et_stop(struct eventtimer *et)
+{
+	struct decr_state *s = DPCPU_PTR(decr_state);
+
+	s->mode = 0;
+	s->div = 0x7fffffff;
+	mtdec(s->div);
+	return (0);
+}
+
+/*
+ * Timecounter get method.
+ */
 static unsigned
 decr_get_timecount(struct timecounter *tc)
 {
@@ -189,17 +277,3 @@ DELAY(int n)
 		tb = mftb();
 }
 
-/*
- * Nothing to do.
- */
-void
-cpu_startprofclock(void)
-{
-
-	/* Do nothing */
-}
-
-void
-cpu_stopprofclock(void)
-{
-}
diff --git a/sys/powerpc/aim/interrupt.c b/sys/powerpc/aim/interrupt.c
index 5f92d243368..b06fb92e233 100644
--- a/sys/powerpc/aim/interrupt.c
+++ b/sys/powerpc/aim/interrupt.c
@@ -72,6 +72,7 @@ void
 powerpc_interrupt(struct trapframe *framep)
 {
 	struct thread *td;
+	struct trapframe *oldframe;
 	register_t ee;
 
 	td = curthread;
@@ -88,8 +89,11 @@ powerpc_interrupt(struct trapframe *framep)
 	case EXC_DECR:
 		critical_enter();
 		atomic_add_int(&td->td_intr_nesting_level, 1);
+		oldframe = td->td_intr_frame;
+		td->td_intr_frame = framep;
 		decr_intr(framep);
-		atomic_subtract_int(&td->td_intr_nesting_level, 1);	
+		td->td_intr_frame = oldframe;
+		atomic_subtract_int(&td->td_intr_nesting_level, 1);
 		critical_exit();
 		break;
 
diff --git a/sys/powerpc/aim/machdep.c b/sys/powerpc/aim/machdep.c
index fe3939d1f37..3290fa67441 100644
--- a/sys/powerpc/aim/machdep.c
+++ b/sys/powerpc/aim/machdep.c
@@ -609,8 +609,7 @@ cpu_initclocks(void)
 {
 
 	decr_tc_init();
-	stathz = hz;
-	profhz = hz;
+	cpu_initclocks_bsp();
 }
 
 /*
diff --git a/sys/powerpc/booke/clock.c b/sys/powerpc/booke/clock.c
index 5b9979a8145..a50a504fa69 100644
--- a/sys/powerpc/booke/clock.c
+++ b/sys/powerpc/booke/clock.c
@@ -63,12 +63,14 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
+#include 
 #include 
-#include 
 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -78,33 +80,46 @@ __FBSDID("$FreeBSD$");
 /*
  * Initially we assume a processor with a bus frequency of 12.5 MHz.
  */
-u_int tickspending;
-u_long ns_per_tick = 80;
-static u_long ticks_per_sec = 12500000;
-static long ticks_per_intr;
+static int		initialized = 0;
+static u_long		ns_per_tick = 80;
+static u_long		ticks_per_sec = 12500000;
+static u_long		*decr_counts[MAXCPU];
 
 #define	DIFF19041970	2082844800
 
+static int		decr_et_start(struct eventtimer *et,
+    struct bintime *first, struct bintime *period);
+static int		decr_et_stop(struct eventtimer *et);
 static timecounter_get_t decr_get_timecount;
 
+struct decr_state {
+	int	mode;	/* 0 - off, 1 - periodic, 2 - one-shot. */
+	int32_t	div;	/* Periodic divisor. */
+};
+static DPCPU_DEFINE(struct decr_state, decr_state);
+
+static struct eventtimer	decr_et;
 static struct timecounter	decr_timecounter = {
 	decr_get_timecount,	/* get_timecount */
 	0,			/* no poll_pps */
 	~0u,			/* counter_mask */
 	0,			/* frequency */
-	"decrementer"		/* name */
+	"timebase"		/* name */
 };
 
+/*
+ * Decrementor interrupt handler.
+ */
 void
 decr_intr(struct trapframe *frame)
 {
+	struct decr_state *s = DPCPU_PTR(decr_state);
 
-	/*
-	 * Check whether we are initialized.
-	 */
-	if (!ticks_per_intr)
+	if (!initialized)
 		return;
 
+	(*decr_counts[curcpu])++;
+
 	/*
 	 * Interrupt handler must reset DIS to avoid getting another
 	 * interrupt once EE is enabled.
@@ -113,14 +128,11 @@ decr_intr(struct trapframe *frame)
 
 	CTR1(KTR_INTR, "%s: DEC interrupt", __func__);
 
-	if (PCPU_GET(cpuid) == 0)
-		hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
-	else
-		hardclock_cpu(TRAPF_USERMODE(frame));
+	if (s->mode == 2)
+		decr_et_stop(NULL);
 
-	statclock(TRAPF_USERMODE(frame));
-	if (profprocs != 0)
-		profclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
+	if (decr_et.et_active)
+		decr_et.et_event_cb(&decr_et, decr_et.et_arg);
 }
 
 void
@@ -128,57 +140,129 @@ cpu_initclocks(void)
 {
 
 	decr_tc_init();
-	stathz = hz;
-	profhz = hz;
+	cpu_initclocks_bsp();
 }
 
+/*
+ * BSP early initialization.
+ */
 void
 decr_init(void)
 {
 	struct cpuref cpu;
-	unsigned int msr;
+	char buf[32];
 
 	if (platform_smp_get_bsp(&cpu) != 0)
 		platform_smp_first_cpu(&cpu);
 	ticks_per_sec = platform_timebase_freq(&cpu);
-
-	msr = mfmsr();
-	mtmsr(msr & ~(PSL_EE));
-
 	ns_per_tick = 1000000000 / ticks_per_sec;
-	ticks_per_intr = ticks_per_sec / hz;
-
-	mtdec(ticks_per_intr);
-
-	mtspr(SPR_DECAR, ticks_per_intr);
-	mtspr(SPR_TCR, mfspr(SPR_TCR) | TCR_DIE | TCR_ARE);
 
 	set_cputicker(mftb, ticks_per_sec, 0);
-
-	mtmsr(msr);
+	snprintf(buf, sizeof(buf), "cpu%d:decrementer", curcpu);
+	intrcnt_add(buf, &decr_counts[curcpu]);
+	decr_et_stop(NULL);
+	initialized = 1;
 }
 
 #ifdef SMP
+/*
+ * AP early initialization.
+ */
 void
 decr_ap_init(void)
 {
+	char buf[32];
 
-	/* Set auto-reload value and enable DEC interrupts in TCR */
-	mtspr(SPR_DECAR, ticks_per_intr);
-	mtspr(SPR_TCR, mfspr(SPR_TCR) | TCR_DIE | TCR_ARE);
-
-	CTR2(KTR_INTR, "%s: set TCR=%p", __func__, mfspr(SPR_TCR));
+	snprintf(buf, sizeof(buf), "cpu%d:decrementer", curcpu);
+	intrcnt_add(buf, &decr_counts[curcpu]);
+	decr_et_stop(NULL);
 }
 #endif
 
+/*
+ * Final initialization.
+ */
 void
 decr_tc_init(void)
 {
 
 	decr_timecounter.tc_frequency = ticks_per_sec;
 	tc_init(&decr_timecounter);
+	decr_et.et_name = "decrementer";
+	decr_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
+	    ET_FLAGS_PERCPU;
+	decr_et.et_quality = 1000;
+	decr_et.et_frequency = ticks_per_sec;
+	decr_et.et_min_period.sec = 0;
+	decr_et.et_min_period.frac =
+	    ((0x00000002LLU << 32) / ticks_per_sec) << 32;
+	decr_et.et_max_period.sec = 0xfffffffeLLU / ticks_per_sec;
+	decr_et.et_max_period.frac =
+	    ((0xfffffffeLLU << 32) / ticks_per_sec) << 32;
+	decr_et.et_start = decr_et_start;
+	decr_et.et_stop = decr_et_stop;
+	decr_et.et_priv = NULL;
+	et_register(&decr_et);
 }
 
+/*
+ * Event timer start method.
+ */
+static int
+decr_et_start(struct eventtimer *et,
+    struct bintime *first, struct bintime *period)
+{
+	struct decr_state *s = DPCPU_PTR(decr_state);
+	uint32_t fdiv, tcr;
+
+	if (period != NULL) {
+		s->mode = 1;
+		s->div = (decr_et.et_frequency * (period->frac >> 32)) >> 32;
+		if (period->sec != 0)
+			s->div += decr_et.et_frequency * period->sec;
+	} else {
+		s->mode = 2;
+		s->div = 0xffffffff;
+	}
+	if (first != NULL) {
+		fdiv = (decr_et.et_frequency * (first->frac >> 32)) >> 32;
+		if (first->sec != 0)
+			fdiv += decr_et.et_frequency * first->sec;
+	} else
+		fdiv = s->div;
+
+	tcr = mfspr(SPR_TCR);
+	tcr |= TCR_DIE;
+	if (s->mode == 1) {
+		mtspr(SPR_DECAR, s->div);
+		tcr |= TCR_ARE;
+	} else
+		tcr &= ~TCR_ARE;
+	mtdec(fdiv);
+	mtspr(SPR_TCR, tcr);
+	return (0);
+}
+
+/*
+ * Event timer stop method.
+ */
+static int
+decr_et_stop(struct eventtimer *et)
+{
+	struct decr_state *s = DPCPU_PTR(decr_state);
+	uint32_t tcr;
+
+	s->mode = 0;
+	s->div = 0xffffffff;
+	tcr = mfspr(SPR_TCR);
+	tcr &= ~(TCR_DIE | TCR_ARE);
+	mtspr(SPR_TCR, tcr);
+	return (0);
+}
+
+/*
+ * Timecounter get method.
+ */
 static unsigned
 decr_get_timecount(struct timecounter *tc)
 {
@@ -203,18 +287,3 @@ DELAY(int n)
 	} while (now < end || (now > start && end < start));
 }
 
-/*
- * Nothing to do.
- */
-void
-cpu_startprofclock(void)
-{
-
-	/* Do nothing */
-}
-
-void
-cpu_stopprofclock(void)
-{
-
-}
diff --git a/sys/powerpc/booke/interrupt.c b/sys/powerpc/booke/interrupt.c
index 1626a8fbd27..c0bdee1e96c 100644
--- a/sys/powerpc/booke/interrupt.c
+++ b/sys/powerpc/booke/interrupt.c
@@ -116,11 +116,15 @@ void
 powerpc_decr_interrupt(struct trapframe *framep)
 {
 	struct thread *td;
+	struct trapframe *oldframe;
 
 	td = PCPU_GET(curthread);
 	critical_enter();
 	atomic_add_int(&td->td_intr_nesting_level, 1);
+	oldframe = td->td_intr_frame;
+	td->td_intr_frame = framep;
 	decr_intr(framep);
+	td->td_intr_frame = oldframe;
 	atomic_subtract_int(&td->td_intr_nesting_level, 1);
 	critical_exit();
 	framep->srr1 &= ~PSL_WE;
diff --git a/sys/powerpc/booke/platform_bare.c b/sys/powerpc/booke/platform_bare.c
index bdfcbfc41b0..c569d751f0b 100644
--- a/sys/powerpc/booke/platform_bare.c
+++ b/sys/powerpc/booke/platform_bare.c
@@ -82,7 +82,7 @@ static platform_method_t bare_methods[] = {
 	PLATFORMMETHOD(platform_smp_get_bsp,	bare_smp_get_bsp),
 	PLATFORMMETHOD(platform_smp_start_cpu,	bare_smp_start_cpu),
 
-	PLATFORMMETHOD(platform_reset,		e500_reset);
+	PLATFORMMETHOD(platform_reset,		e500_reset),
 
 	{ 0, 0 }
 };
diff --git a/sys/powerpc/include/intr_machdep.h b/sys/powerpc/include/intr_machdep.h
index 5a0e04ad812..67d7e796f9b 100644
--- a/sys/powerpc/include/intr_machdep.h
+++ b/sys/powerpc/include/intr_machdep.h
@@ -48,6 +48,8 @@ struct trapframe;
 
 driver_filter_t powerpc_ipi_handler;
 
+void	intrcnt_add(const char *name, u_long **countp);
+
 void	powerpc_register_pic(device_t, u_int);
 int	powerpc_ign_lookup(uint32_t pic_id);
 
diff --git a/sys/powerpc/include/md_var.h b/sys/powerpc/include/md_var.h
index 65c952a027f..a90967a3e41 100644
--- a/sys/powerpc/include/md_var.h
+++ b/sys/powerpc/include/md_var.h
@@ -47,8 +47,6 @@ extern	int	busdma_swi_pending;
 extern	vm_offset_t	kstack0;
 extern	vm_offset_t	kstack0_phys;
 
-extern	u_long	ns_per_tick;
-
 extern	int powerpc_pow_enabled;
 extern	int cacheline_size;
 extern  int hw_direct_map;
diff --git a/sys/powerpc/include/smp.h b/sys/powerpc/include/smp.h
index 64d13dbdd7b..cf952788c68 100644
--- a/sys/powerpc/include/smp.h
+++ b/sys/powerpc/include/smp.h
@@ -36,6 +36,7 @@
 #define	IPI_RENDEZVOUS		2
 #define	IPI_STOP		3
 #define	IPI_STOP_HARD		3
+#define	IPI_HARDCLOCK		4
 
 #ifndef LOCORE
 
diff --git a/sys/powerpc/powerpc/intr_machdep.c b/sys/powerpc/powerpc/intr_machdep.c
index 5a0ff8cadf5..4b2dbbe9550 100644
--- a/sys/powerpc/powerpc/intr_machdep.c
+++ b/sys/powerpc/powerpc/intr_machdep.c
@@ -95,6 +95,7 @@ struct powerpc_intr {
 	device_t pic;
 	u_int	intline;
 	u_int	vector;
+	u_int	cntindex;
 	cpumask_t cpu;
 	enum intr_trigger trig;
 	enum intr_polarity pol;
@@ -106,6 +107,7 @@ struct pic {
 	int ipi_irq;
 };
 
+static u_int intrcnt_index = 0;
 static struct mtx intr_table_lock;
 static struct powerpc_intr *powerpc_intrs[INTR_VECTORS];
 static struct pic piclist[MAX_PICS];
@@ -152,6 +154,16 @@ intrcnt_setname(const char *name, int index)
 	    MAXCOMLEN, name);
 }
 
+void
+intrcnt_add(const char *name, u_long **countp)
+{
+	int idx;
+
+	idx = atomic_fetchadd_int(&intrcnt_index, 1);
+	*countp = &intrcnt[idx];
+	intrcnt_setname(name, idx);
+}
+
 static struct powerpc_intr *
 intr_lookup(u_int irq)
 {
@@ -200,8 +212,10 @@ intr_lookup(u_int irq)
 
 	if (iscan == NULL && i->vector != -1) {
 		powerpc_intrs[i->vector] = i;
+		i->cntindex = atomic_fetchadd_int(&intrcnt_index, 1);
+		i->cntp = &intrcnt[i->cntindex];
 		sprintf(intrname, "irq%u:", i->irq);
-		intrcnt_setname(intrname, i->vector);
+		intrcnt_setname(intrname, i->cntindex);
 		nvectors++;
 	}
 	mtx_unlock(&intr_table_lock);
@@ -384,8 +398,6 @@ powerpc_setup_intr(const char *name, u_int irq, driver_filter_t filter,
 		if (error)
 			return (error);
 
-		i->cntp = &intrcnt[i->vector];
-
 		enable = 1;
 	}
 
@@ -393,7 +405,7 @@ powerpc_setup_intr(const char *name, u_int irq, driver_filter_t filter,
 	    intr_priority(flags), flags, cookiep);
 
 	mtx_lock(&intr_table_lock);
-	intrcnt_setname(i->event->ie_fullname, i->vector);
+	intrcnt_setname(i->event->ie_fullname, i->cntindex);
 	mtx_unlock(&intr_table_lock);
 
 	if (!cold) {
diff --git a/sys/powerpc/powerpc/mp_machdep.c b/sys/powerpc/powerpc/mp_machdep.c
index 46f02956c16..a8336389f45 100644
--- a/sys/powerpc/powerpc/mp_machdep.c
+++ b/sys/powerpc/powerpc/mp_machdep.c
@@ -59,7 +59,6 @@ extern struct pcpu __pcpu[MAXCPU];
 
 volatile static int ap_awake;
 volatile static u_int ap_letgo;
-volatile static uint32_t ap_decr;
 volatile static u_quad_t ap_timebase;
 static u_int ipi_msg_cnt[32];
 static struct mtx ap_boot_mtx;
@@ -79,9 +78,8 @@ machdep_ap_bootstrap(void)
 		;
 
 	/* Initialize DEC and TB, sync with the BSP values */
-	decr_ap_init();
 	mttb(ap_timebase);
-	__asm __volatile("mtdec %0" :: "r"(ap_decr));
+	decr_ap_init();
 
 	/* Serialize console output and AP count increment */
 	mtx_lock_spin(&ap_boot_mtx);
@@ -96,6 +94,9 @@ machdep_ap_bootstrap(void)
 	/* Let the DEC and external interrupts go */
 	mtmsr(mfmsr() | PSL_EE);
 
+	/* Start per-CPU event timers. */
+	cpu_initclocks_ap();
+
 	/* Announce ourselves awake, and enter the scheduler */
 	sched_throw(NULL);
 }
@@ -243,7 +244,6 @@ cpu_mp_unleash(void *dummy)
 	ap_awake = 1;
 
 	/* Provide our current DEC and TB values for APs */
-	__asm __volatile("mfdec %0" : "=r"(ap_decr));
 	ap_timebase = mftb() + 10;
 	__asm __volatile("msync; isync");
 	
@@ -313,6 +313,10 @@ powerpc_ipi_handler(void *arg)
 			atomic_clear_int(&stopped_cpus, self);
 			CTR1(KTR_SMP, "%s: IPI_STOP (restart)", __func__);
 			break;
+		case IPI_HARDCLOCK:
+			CTR1(KTR_SMP, "%s: IPI_HARDCLOCK", __func__);
+			hardclockintr(curthread->td_intr_frame);
+			break;
 		}
 	}
 

From b722ad008b31b4687a88097babe2318072317988 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 11 Sep 2010 07:08:22 +0000
Subject: [PATCH 0635/1624] Merge some SCHED_ULE features to SCHED_4BSD: -
 Teach SCHED_4BSD to inform cpu_idle() about high sleep/wakeup rate to choose
 optimized handler. In case of x86 it is MONITOR/MWAIT. Also it will be needed
 to bypass forthcoming idle tick skipping logic to not consume resources on
 events rescheduling when it won't give any benefits. - Teach SCHED_4BSD to
 wake up idle CPUs without using IPI. In case of x86, when MONITOR/MWAIT is
 active, it require just single memory write. This doubles performance on some
 heavily switching test loads.

---
 sys/kern/sched_4bsd.c | 32 ++++++++++++++++++++++++++++----
 1 file changed, 28 insertions(+), 4 deletions(-)

diff --git a/sys/kern/sched_4bsd.c b/sys/kern/sched_4bsd.c
index e579198adc6..780dc6d1760 100644
--- a/sys/kern/sched_4bsd.c
+++ b/sys/kern/sched_4bsd.c
@@ -157,6 +157,12 @@ static struct runq runq_pcpu[MAXCPU];
 long runq_length[MAXCPU];
 #endif
 
+struct pcpuidlestat {
+	u_int idlecalls;
+	u_int oldidlecalls;
+};
+static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
+
 static void
 setup_runqs(void)
 {
@@ -684,6 +690,7 @@ sched_rr_interval(void)
 void
 sched_clock(struct thread *td)
 {
+	struct pcpuidlestat *stat;
 	struct td_sched *ts;
 
 	THREAD_LOCK_ASSERT(td, MA_OWNED);
@@ -703,6 +710,10 @@ sched_clock(struct thread *td)
 	if (!TD_IS_IDLETHREAD(td) &&
 	    ticks - PCPU_GET(switchticks) >= sched_quantum)
 		td->td_flags |= TDF_NEEDRESCHED;
+
+	stat = DPCPU_PTR(idlestat);
+	stat->oldidlecalls = stat->idlecalls;
+	stat->idlecalls = 0;
 }
 
 /*
@@ -1137,7 +1148,15 @@ forward_wakeup(int cpunum)
 	}
 	if (map) {
 		forward_wakeups_delivered++;
-		ipi_selected(map, IPI_AST);
+		SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
+			id = pc->pc_cpumask;
+			if ((map & id) == 0)
+				continue;
+			if (cpu_idle_wakeup(pc->pc_cpuid))
+				map &= ~id;
+		}
+		if (map)
+			ipi_selected(map, IPI_AST);
 		return (1);
 	}
 	if (cpunum == NOCPU)
@@ -1154,7 +1173,8 @@ kick_other_cpu(int pri, int cpuid)
 	pcpu = pcpu_find(cpuid);
 	if (idle_cpus_mask & pcpu->pc_cpumask) {
 		forward_wakeups_delivered++;
-		ipi_cpu(cpuid, IPI_AST);
+		if (!cpu_idle_wakeup(cpuid))
+			ipi_cpu(cpuid, IPI_AST);
 		return;
 	}
 
@@ -1537,12 +1557,16 @@ sched_tick(void)
 void
 sched_idletd(void *dummy)
 {
+	struct pcpuidlestat *stat;
 
+	stat = DPCPU_PTR(idlestat);
 	for (;;) {
 		mtx_assert(&Giant, MA_NOTOWNED);
 
-		while (sched_runnable() == 0)
-			cpu_idle(0);
+		while (sched_runnable() == 0) {
+			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
+			stat->idlecalls++;
+		}
 
 		mtx_lock_spin(&sched_lock);
 		mi_switch(SW_VOL | SWT_IDLE, NULL);

From dc5b8c2ee73020fa02cba8fa0ebf1cf8a261edab Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 11 Sep 2010 07:24:10 +0000
Subject: [PATCH 0636/1624] Sparc64 uses dummy cpu_idle() method. It's CPUs
 never sleeping. Tell scheduler that it doesn't need to use IPI to "wake up"
 CPU.

---
 sys/sparc64/sparc64/machdep.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sparc64/sparc64/machdep.c b/sys/sparc64/sparc64/machdep.c
index 70abf63e47d..90da7c62be3 100644
--- a/sys/sparc64/sparc64/machdep.c
+++ b/sys/sparc64/sparc64/machdep.c
@@ -959,7 +959,7 @@ int
 cpu_idle_wakeup(int cpu)
 {
 
-	return (0);
+	return (1);
 }
 
 int

From f5aadc99a63f868547d6d44d11104a815a83871f Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Sat, 11 Sep 2010 08:09:14 +0000
Subject: [PATCH 0637/1624] make acpi_hp device a child of acpi_wmi

to properly reflect dependency between the devices/drivers

PR:		kern/147858
Suggested by:	jhb
Tested by:	Maciej Suszko 
MFC after:	1 week
---
 sys/dev/acpi_support/acpi_hp.c  | 28 +++-------------------------
 sys/dev/acpi_support/acpi_wmi.c |  9 +++++++++
 2 files changed, 12 insertions(+), 25 deletions(-)

diff --git a/sys/dev/acpi_support/acpi_hp.c b/sys/dev/acpi_support/acpi_hp.c
index a52905d2492..edc04b75b40 100644
--- a/sys/dev/acpi_support/acpi_hp.c
+++ b/sys/dev/acpi_support/acpi_hp.c
@@ -49,7 +49,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -336,7 +335,7 @@ static driver_t	acpi_hp_driver = {
 
 static devclass_t acpi_hp_devclass;
 
-DRIVER_MODULE(acpi_hp, acpi, acpi_hp_driver, acpi_hp_devclass,
+DRIVER_MODULE(acpi_hp, acpi_wmi, acpi_hp_driver, acpi_hp_devclass,
 		0, 0);
 MODULE_DEPEND(acpi_hp, acpi_wmi, 1, 1, 1);
 MODULE_DEPEND(acpi_hp, acpi, 1, 1, 1);
@@ -453,16 +452,7 @@ acpi_hp_identify(driver_t *driver, device_t parent)
 	if (device_find_child(parent, "acpi_hp", -1) != NULL)
 		return;
 
-	/* Make sure acpi_wmi driver is present. */
-	if (devclass_find("acpi_wmi") == NULL)
-		return;
-
-	/*
-	 * Add our device with late order, so that it is hopefully
-	 * probed after acpi_wmi.
-	 * XXX User proper constant instead of UINT_MAX for order.
-	 */
-	if (BUS_ADD_CHILD(parent, UINT_MAX, "acpi_hp", -1) == NULL)
+	if (BUS_ADD_CHILD(parent, 0, "acpi_hp", -1) == NULL)
 		device_printf(parent, "add acpi_hp child failed\n");
 }
 
@@ -470,11 +460,7 @@ static int
 acpi_hp_probe(device_t dev)
 {
 
-	/* Skip auto-enumerated devices from ACPI namespace. */
-	if (acpi_get_handle(dev) != NULL)
-		return (ENXIO);
 	device_set_desc(dev, "HP ACPI-WMI Mapping");
-
 	return (0);
 }
 
@@ -482,7 +468,6 @@ static int
 acpi_hp_attach(device_t dev)
 {
 	struct acpi_hp_softc	*sc;
-	devclass_t		wmi_devclass;
 	int			arg;
 
 	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
@@ -505,14 +490,7 @@ acpi_hp_attach(device_t dev)
 	sc->verbose = 0;
 	memset(sc->cmi_order, 0, sizeof(sc->cmi_order));
 
-	if (!(wmi_devclass = devclass_find("acpi_wmi"))) {
-		device_printf(dev, "Couldn't find acpi_wmi devclass\n");
-		return (EINVAL);
-	}
-	if (!(sc->wmi_dev = devclass_get_device(wmi_devclass, 0))) {
-		device_printf(dev, "Couldn't find acpi_wmi device\n");
-		return (EINVAL);
-	}
+	sc->wmi_dev = device_get_parent(dev);
 	if (!ACPI_WMI_PROVIDES_GUID_STRING(sc->wmi_dev,
 	    ACPI_HP_WMI_BIOS_GUID)) {
 		device_printf(dev,
diff --git a/sys/dev/acpi_support/acpi_wmi.c b/sys/dev/acpi_support/acpi_wmi.c
index 9da790c5fda..cf70ab09172 100644
--- a/sys/dev/acpi_support/acpi_wmi.c
+++ b/sys/dev/acpi_support/acpi_wmi.c
@@ -173,6 +173,10 @@ static device_method_t acpi_wmi_methods[] = {
 	DEVMETHOD(device_attach, acpi_wmi_attach),
 	DEVMETHOD(device_detach, acpi_wmi_detach),
 
+	/* bus interface */
+	DEVMETHOD(bus_add_child,	bus_generic_add_child),
+	DEVMETHOD(bus_print_child,	bus_generic_print_child),
+
 	/* acpi_wmi interface */
 	DEVMETHOD(acpi_wmi_provides_guid_string,
 		    acpi_wmi_provides_guid_string_method),
@@ -269,6 +273,11 @@ acpi_wmi_attach(device_t dev)
 	}
 	ACPI_SERIAL_END(acpi_wmi);
 
+	if (ret == 0) {
+		bus_generic_probe(dev);
+		ret = bus_generic_attach(dev);
+	}
+
 	return (ret);
 }
 

From a60c2f1c0e725e8e2cf921ad669b25af739c45ce Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Sat, 11 Sep 2010 08:15:18 +0000
Subject: [PATCH 0638/1624] kill() does queue signal now.

---
 share/man/man3/siginfo.3 | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/share/man/man3/siginfo.3 b/share/man/man3/siginfo.3
index 2783d98da29..9452b08647e 100644
--- a/share/man/man3/siginfo.3
+++ b/share/man/man3/siginfo.3
@@ -272,10 +272,6 @@ the ID of the message queue which generated the signal
 Currently, the kernel never generates the
 .Dv SIGPOLL
 signal.
-Also, the
-.Xr kill 2
-system call does not queue signals, so you will not get code
-.Dv SI_USER .
 .Dv SIGCHLD
 signal is queued when a process changed its status or exited.
 .Tn POSIX

From b9b58ffa2690ccfec600ffb425d4c18caa7413e4 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Sat, 11 Sep 2010 09:26:36 +0000
Subject: [PATCH 0639/1624] Make a link for pthread_timedjoin_np.

---
 share/man/man3/Makefile | 1 +
 1 file changed, 1 insertion(+)

diff --git a/share/man/man3/Makefile b/share/man/man3/Makefile
index 9e536a05b65..cc9a3f3403d 100644
--- a/share/man/man3/Makefile
+++ b/share/man/man3/Makefile
@@ -277,6 +277,7 @@ PTHREAD_MLINKS+=pthread_spin_init.3 pthread_spin_destroy.3 \
 PTHREAD_MLINKS+=pthread_switch_add_np.3 pthread_switch_delete_np.3
 PTHREAD_MLINKS+=pthread_testcancel.3 pthread_setcancelstate.3 \
 		pthread_testcancel.3 pthread_setcanceltype.3
+PTHREAD_MLINKS+=pthread_join.3 pthread_timedjoin_np.3
 .endif
 
 .include 

From 6774542431e2f37f3b919b90a83e0c783525fdc8 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 11 Sep 2010 09:53:33 +0000
Subject: [PATCH 0640/1624] Fix the build after r212453. IPI_STATCLOCK
 declaration is still needed for build, though not really used.

Submitted by:	andreast
---
 sys/powerpc/include/smp.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/powerpc/include/smp.h b/sys/powerpc/include/smp.h
index cf952788c68..c78af741f70 100644
--- a/sys/powerpc/include/smp.h
+++ b/sys/powerpc/include/smp.h
@@ -37,6 +37,7 @@
 #define	IPI_STOP		3
 #define	IPI_STOP_HARD		3
 #define	IPI_HARDCLOCK		4
+#define	IPI_STATCLOCK		5
 
 #ifndef LOCORE
 

From 004699f14f34b51eeef9ff9525dbac36182de5cb Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 11 Sep 2010 10:11:59 +0000
Subject: [PATCH 0641/1624] Add a comment describing where to include
 bsd.dtrace.mk.

Sponsored by:	The FreeBSD Foundation
---
 share/mk/bsd.dtrace.mk | 1 +
 1 file changed, 1 insertion(+)

diff --git a/share/mk/bsd.dtrace.mk b/share/mk/bsd.dtrace.mk
index bebe969ccf1..518de30ff33 100644
--- a/share/mk/bsd.dtrace.mk
+++ b/share/mk/bsd.dtrace.mk
@@ -29,6 +29,7 @@
 # 
 #
 # The only variable that you should define on your Makefile is 'DTRACEOBJS'.
+# You must include this file before bsd.lib.mk or bsd.prog.mk.
 #
 
 .if defined(WITH_DTRACE)

From dba0ac63fbdc2da1410a659b6dd2d917a7ad1d23 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 11 Sep 2010 10:16:15 +0000
Subject: [PATCH 0642/1624] Disable debug by default.

Sponsored by:	The FreeBSD Foundation
---
 cddl/contrib/opensolaris/lib/libdtrace/common/drti.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c b/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c
index bce80383849..7a14dd38d31 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/drti.c
@@ -64,7 +64,7 @@ static int gen;			/* DOF helper generation */
 #if defined(sun)
 extern dof_hdr_t __SUNW_dof;	/* DOF defined in the .SUNW_dof section */
 #endif
-static boolean_t dof_init_debug = B_TRUE;	/* From DTRACE_DOF_INIT_DEBUG */
+static boolean_t dof_init_debug = B_FALSE;	/* From DTRACE_DOF_INIT_DEBUG */
 
 static void
 dprintf(int debug, const char *fmt, ...)

From 5512804bb8fe7606fcc50062327c11622c79b6ca Mon Sep 17 00:00:00 2001
From: Rebecca Cran 
Date: Sat, 11 Sep 2010 10:49:56 +0000
Subject: [PATCH 0643/1624] Revert changes of 'assure' to 'ensure' made in
 r211936.

Approved by: rrs (mentor)
---
 bin/test/test.1                      | 2 +-
 lib/libc/net/sctp_send.3             | 4 ++--
 lib/libc/net/sctp_sendmsg.3          | 4 ++--
 lib/libc/stdio/printf.3              | 2 +-
 lib/libc/stdlib/malloc.3             | 4 ++--
 secure/lib/libcrypto/man/BIO_s_bio.3 | 2 +-
 share/man/man4/ata.4                 | 2 +-
 share/man/man4/ng_hci.4              | 2 +-
 8 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/bin/test/test.1 b/bin/test/test.1
index 8cf43d0a405..5815b1255de 100644
--- a/bin/test/test.1
+++ b/bin/test/test.1
@@ -302,7 +302,7 @@ manual page.
 The
 .Nm
 grammar is inherently ambiguous.
-In order to ensure a degree of consistency,
+In order to assure a degree of consistency,
 the cases described in the
 .St -p1003.2 ,
 section D11.2/4.62.4, standard
diff --git a/lib/libc/net/sctp_send.3 b/lib/libc/net/sctp_send.3
index 8d860dfb318..9acb616be5b 100644
--- a/lib/libc/net/sctp_send.3
+++ b/lib/libc/net/sctp_send.3
@@ -191,7 +191,7 @@ If that many milliseconds elapse
 and the peer has not acknowledged the data, the data will be
 skipped and no longer transmitted.
 Note that this policy does
-not even ensure that the data will ever be sent.
+not even assure that the data will ever be sent.
 In times of a congestion
 with large amounts of data being queued, the 
 .Fa sinfo->sinfo_timetolive
@@ -218,7 +218,7 @@ policy transforms the
 .Fa sinfo->sinfo_timetolive 
 into a number of retransmissions to allow.
 This policy
-always ensures that at a minimum one send attempt is
+always assures that at a minimum one send attempt is
 made of the data.
 After which no more than 
 .Fa sinfo->sinfo_timetolive
diff --git a/lib/libc/net/sctp_sendmsg.3 b/lib/libc/net/sctp_sendmsg.3
index 10155580195..ddd88b43c9f 100644
--- a/lib/libc/net/sctp_sendmsg.3
+++ b/lib/libc/net/sctp_sendmsg.3
@@ -203,7 +203,7 @@ If that many milliseconds elapse
 and the peer has not acknowledged the data, the data will be
 skipped and no longer transmitted.
 Note that this policy does
-not even ensure that the data will ever be sent.
+not even assure that the data will ever be sent.
 In times of a congestion
 with large amounts of data being queued, the 
 .Fa timetolive
@@ -230,7 +230,7 @@ policy transforms the
 .Fa timetolive 
 into a number of retransmissions to allow.
 This policy
-always ensures that at a minimum one send attempt is
+always assures that at a minimum one send attempt is
 made of the data.
 After which no more than 
 .Fa timetolive
diff --git a/lib/libc/stdio/printf.3 b/lib/libc/stdio/printf.3
index a0d2613da66..90a8ed8b02e 100644
--- a/lib/libc/stdio/printf.3
+++ b/lib/libc/stdio/printf.3
@@ -849,7 +849,7 @@ and
 .Fn vsprintf
 assume an infinitely long string,
 callers must be careful not to overflow the actual space;
-this is often hard to ensure.
+this is often hard to assure.
 For safety, programmers should use the
 .Fn snprintf
 interface instead.
diff --git a/lib/libc/stdlib/malloc.3 b/lib/libc/stdlib/malloc.3
index 90781a10961..2f21b6a5294 100644
--- a/lib/libc/stdlib/malloc.3
+++ b/lib/libc/stdlib/malloc.3
@@ -266,7 +266,7 @@ options are enabled, the allocator prefers anonymous mappings over the DSS,
 but allocation only fails if memory cannot be acquired via either method.
 If neither option is enabled, then the
 .Dq M
-option is implicitly enabled in order to ensure that there is a method for
+option is implicitly enabled in order to assure that there is a method for
 acquiring memory.
 .It N
 Double/halve the number of arenas.
@@ -437,7 +437,7 @@ rounded up to the nearest multiple of the chunk size.
 .Pp
 Allocations are packed tightly together, which can be an issue for
 multi-threaded applications.
-If you need to ensure that allocations do not suffer from cacheline sharing,
+If you need to assure that allocations do not suffer from cacheline sharing,
 round your allocation requests up to the nearest multiple of the cacheline
 size.
 .Sh DEBUGGING MALLOC PROBLEMS
diff --git a/secure/lib/libcrypto/man/BIO_s_bio.3 b/secure/lib/libcrypto/man/BIO_s_bio.3
index 956f3f6d13e..34345d112a8 100644
--- a/secure/lib/libcrypto/man/BIO_s_bio.3
+++ b/secure/lib/libcrypto/man/BIO_s_bio.3
@@ -317,7 +317,7 @@ find out, how many bytes must be written into the buffer before the
 .IX Header "WARNING"
 As the data is buffered, \fISSL_operation()\fR may return with a \s-1ERROR_SSL_WANT_READ\s0
 condition, but there is still data in the write buffer. An application must
-not rely on the error value of \fISSL_operation()\fR but must ensure that the
+not rely on the error value of \fISSL_operation()\fR but must assure that the
 write buffer is always flushed first. Otherwise a deadlock may occur as
 the peer might be waiting for the data before being able to continue.
 .SH "SEE ALSO"
diff --git a/share/man/man4/ata.4 b/share/man/man4/ata.4
index 22de1a96d97..ba67991dd2a 100644
--- a/share/man/man4/ata.4
+++ b/share/man/man4/ata.4
@@ -243,7 +243,7 @@ based systems
 Please remember that in order to use UDMA4/ATA66 and above modes you
 .Em must
 use 80 conductor cables.
-Please ensure that ribbon cables are no longer than 45cm.
+Please assure that ribbon cables are no longer than 45cm.
 In case of rounded ATA cables, the length depends on the
 quality of the cables.
 SATA cables can be up to 1m long according to the specification.
diff --git a/share/man/man4/ng_hci.4 b/share/man/man4/ng_hci.4
index 5d8dab3e9a8..28de180c242 100644
--- a/share/man/man4/ng_hci.4
+++ b/share/man/man4/ng_hci.4
@@ -108,7 +108,7 @@ piconet.
 Both asynchronous and isochronous services are supported.
 Between a master and a slave only a single ACL link can exist.
 For most ACL packets,
-packet retransmission is applied to ensure data integrity.
+packet retransmission is applied to assure data integrity.
 .Sh HOST CONTROLLER INTERFACE (HCI)
 The HCI provides a command interface to the baseband controller and link
 manager, and access to hardware status and control registers.

From eae81e9501f81fe562e1e807e9d27caa3e4bfe70 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sat, 11 Sep 2010 12:58:31 +0000
Subject: [PATCH 0644/1624] Avoid a LOR (sleepable after non-sleepable) in
 fasttrap_tracepoint_enable().

Sponsored by:	The FreeBSD Foundation
---
 sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
index b819f3b0720..38c2c7a6215 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
@@ -591,7 +591,9 @@ fasttrap_tracepoint_enable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
 	 * Before we make any modifications, make sure we've imposed a barrier
 	 * on the generation in which this probe was last modified.
 	 */
+	PROC_UNLOCK(p);
 	fasttrap_mod_barrier(probe->ftp_gen);
+	PROC_LOCK(p);
 
 	bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
 

From 9a24dc07606e7e0b9f1fde92c8d94fa405a9043b Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sat, 11 Sep 2010 13:06:06 +0000
Subject: [PATCH 0645/1624] Protect mnt_syncer with the sync_mtx. This prevents
 a (rare) vnode leak when mount and update are executed in parallel.

Encapsulate syncer vnode deallocation into the helper function
vfs_deallocate_syncvnode(), to not externalize sync_mtx from vfs_subr.c.

Found and reviewed by:	jh (previous version of the patch)
Tested by:	pho
MFC after:	3 weeks
---
 sys/kern/vfs_mount.c | 17 ++++++-----------
 sys/kern/vfs_subr.c  | 31 +++++++++++++++++++++++++++----
 sys/sys/mount.h      |  1 +
 3 files changed, 34 insertions(+), 15 deletions(-)

diff --git a/sys/kern/vfs_mount.c b/sys/kern/vfs_mount.c
index 325426688fa..7bd10b42978 100644
--- a/sys/kern/vfs_mount.c
+++ b/sys/kern/vfs_mount.c
@@ -1031,14 +1031,10 @@ vfs_domount_update(
 	 */
 	mp->mnt_optnew = NULL;
 
-	if ((mp->mnt_flag & MNT_RDONLY) == 0) {
-		if (mp->mnt_syncer == NULL)
-			vfs_allocate_syncvnode(mp);
-	} else {
-		if (mp->mnt_syncer != NULL)
-			vrele(mp->mnt_syncer);
-		mp->mnt_syncer = NULL;
-	}
+	if ((mp->mnt_flag & MNT_RDONLY) == 0)
+		vfs_allocate_syncvnode(mp);
+	else
+		vfs_deallocate_syncvnode(mp);
 end:
 	vfs_unbusy(mp);
 	VI_LOCK(vp);
@@ -1318,8 +1314,7 @@ dounmount(mp, flags, td)
 	mp->mnt_kern_flag &= ~MNTK_ASYNC;
 	MNT_IUNLOCK(mp);
 	cache_purgevfs(mp);	/* remove cache entries for this file sys */
-	if (mp->mnt_syncer != NULL)
-		vrele(mp->mnt_syncer);
+	vfs_deallocate_syncvnode(mp);
 	/*
 	 * For forced unmounts, move process cdir/rdir refs on the fs root
 	 * vnode to the covered vnode.  For non-forced unmounts we want
@@ -1358,7 +1353,7 @@ dounmount(mp, flags, td)
 		}
 		MNT_ILOCK(mp);
 		mp->mnt_kern_flag &= ~MNTK_NOINSMNTQ;
-		if ((mp->mnt_flag & MNT_RDONLY) == 0 && mp->mnt_syncer == NULL) {
+		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
 			MNT_IUNLOCK(mp);
 			vfs_allocate_syncvnode(mp);
 			MNT_ILOCK(mp);
diff --git a/sys/kern/vfs_subr.c b/sys/kern/vfs_subr.c
index d770b988ef1..6b90888a7b2 100644
--- a/sys/kern/vfs_subr.c
+++ b/sys/kern/vfs_subr.c
@@ -3405,9 +3405,31 @@ vfs_allocate_syncvnode(struct mount *mp)
 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
 	mtx_lock(&sync_mtx);
 	sync_vnode_count++;
+	if (mp->mnt_syncer == NULL) {
+		mp->mnt_syncer = vp;
+		vp = NULL;
+	}
 	mtx_unlock(&sync_mtx);
 	BO_UNLOCK(bo);
-	mp->mnt_syncer = vp;
+	if (vp != NULL) {
+		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
+		vgone(vp);
+		vput(vp);
+	}
+}
+
+void
+vfs_deallocate_syncvnode(struct mount *mp)
+{
+	struct vnode *vp;
+
+	mtx_lock(&sync_mtx);
+	vp = mp->mnt_syncer;
+	if (vp != NULL)
+		mp->mnt_syncer = NULL;
+	mtx_unlock(&sync_mtx);
+	if (vp != NULL)
+		vrele(vp);
 }
 
 /*
@@ -3488,15 +3510,16 @@ sync_reclaim(struct vop_reclaim_args *ap)
 
 	bo = &vp->v_bufobj;
 	BO_LOCK(bo);
-	vp->v_mount->mnt_syncer = NULL;
+	mtx_lock(&sync_mtx);
+	if (vp->v_mount->mnt_syncer == vp)
+		vp->v_mount->mnt_syncer = NULL;
 	if (bo->bo_flag & BO_ONWORKLST) {
-		mtx_lock(&sync_mtx);
 		LIST_REMOVE(bo, bo_synclist);
 		syncer_worklist_len--;
 		sync_vnode_count--;
-		mtx_unlock(&sync_mtx);
 		bo->bo_flag &= ~BO_ONWORKLST;
 	}
+	mtx_unlock(&sync_mtx);
 	BO_UNLOCK(bo);
 
 	return (0);
diff --git a/sys/sys/mount.h b/sys/sys/mount.h
index 85f16ff2802..f68e95dbac9 100644
--- a/sys/sys/mount.h
+++ b/sys/sys/mount.h
@@ -731,6 +731,7 @@ int	vfs_busy(struct mount *, int);
 int	vfs_export			 /* process mount export info */
 	    (struct mount *, struct export_args *);
 void	vfs_allocate_syncvnode(struct mount *);
+void	vfs_deallocate_syncvnode(struct mount *);
 int	vfs_donmount(struct thread *td, int fsflags, struct uio *fsoptions);
 void	vfs_getnewfsid(struct mount *);
 struct cdev *vfs_getrootfsid(struct mount *);

From 011d162dd330f5506cd12f2a64b819e118ce7ff4 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sat, 11 Sep 2010 14:15:50 +0000
Subject: [PATCH 0646/1624] sh: Apply variable assignments left-to-right in
 bltinlookup().

Example:
  HOME=foo HOME=bar cd
---
 bin/sh/var.c                                    | 6 +++++-
 tools/regression/bin/sh/execution/var-assign1.0 | 3 +++
 2 files changed, 8 insertions(+), 1 deletion(-)
 create mode 100644 tools/regression/bin/sh/execution/var-assign1.0

diff --git a/bin/sh/var.c b/bin/sh/var.c
index 6f4acae1ba5..8ff64262bf9 100644
--- a/bin/sh/var.c
+++ b/bin/sh/var.c
@@ -431,11 +431,15 @@ bltinlookup(const char *name, int doall)
 {
 	struct strlist *sp;
 	struct var *v;
+	char *result;
 
+	result = NULL;
 	for (sp = cmdenviron ; sp ; sp = sp->next) {
 		if (varequal(sp->text, name))
-			return strchr(sp->text, '=') + 1;
+			result = strchr(sp->text, '=') + 1;
 	}
+	if (result != NULL)
+		return result;
 	for (v = *hashvar(name) ; v ; v = v->next) {
 		if (varequal(v->text, name)) {
 			if ((v->flags & VUNSET)
diff --git a/tools/regression/bin/sh/execution/var-assign1.0 b/tools/regression/bin/sh/execution/var-assign1.0
new file mode 100644
index 00000000000..26e54249c1c
--- /dev/null
+++ b/tools/regression/bin/sh/execution/var-assign1.0
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+[ "$(HOME=/etc HOME=/ cd && pwd)" = / ]

From 8f2dc7de675462b3162872659737eac309afc83c Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sat, 11 Sep 2010 15:07:40 +0000
Subject: [PATCH 0647/1624] sh: Fix exit status if return is used within a loop
 condition.

---
 bin/sh/eval.c                              | 2 ++
 tools/regression/bin/sh/builtins/return6.4 | 3 +++
 tools/regression/bin/sh/builtins/return7.4 | 6 ++++++
 3 files changed, 11 insertions(+)
 create mode 100644 tools/regression/bin/sh/builtins/return6.4
 create mode 100644 tools/regression/bin/sh/builtins/return7.4

diff --git a/bin/sh/eval.c b/bin/sh/eval.c
index 21a0b60bd09..29923c7f098 100644
--- a/bin/sh/eval.c
+++ b/bin/sh/eval.c
@@ -305,6 +305,8 @@ skipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
 			}
 			if (evalskip == SKIPBREAK && --skipcount <= 0)
 				evalskip = 0;
+			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
+				status = exitstatus;
 			break;
 		}
 		if (n->type == NWHILE) {
diff --git a/tools/regression/bin/sh/builtins/return6.4 b/tools/regression/bin/sh/builtins/return6.4
new file mode 100644
index 00000000000..e4d8e0d641a
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/return6.4
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+while return 4; do exit 3; done
diff --git a/tools/regression/bin/sh/builtins/return7.4 b/tools/regression/bin/sh/builtins/return7.4
new file mode 100644
index 00000000000..2047373473a
--- /dev/null
+++ b/tools/regression/bin/sh/builtins/return7.4
@@ -0,0 +1,6 @@
+# $FreeBSD$
+
+f() {
+	while return 4; do exit 3; done
+}
+f

From cdb25d827efda15643a73b0b15f1b724b6e83429 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Sat, 11 Sep 2010 18:55:00 +0000
Subject: [PATCH 0648/1624] Change OF_interpret() to also take an array of
 cell_t (missed in r209801).

Reviewed by:	nwhitehorn
---
 sys/dev/ofw/ofw_fdt.c      |  4 ++--
 sys/dev/ofw/ofw_if.m       |  2 +-
 sys/dev/ofw/ofw_standard.c | 10 ++++------
 sys/dev/ofw/openfirm.c     |  2 +-
 sys/powerpc/ofw/ofw_real.c |  7 +++----
 5 files changed, 11 insertions(+), 14 deletions(-)

diff --git a/sys/dev/ofw/ofw_fdt.c b/sys/dev/ofw/ofw_fdt.c
index 0ec0830dee3..d67b2e5602d 100644
--- a/sys/dev/ofw/ofw_fdt.c
+++ b/sys/dev/ofw/ofw_fdt.c
@@ -66,7 +66,7 @@ static ssize_t ofw_fdt_canon(ofw_t, const char *, char *, size_t);
 static phandle_t ofw_fdt_finddevice(ofw_t, const char *);
 static ssize_t ofw_fdt_instance_to_path(ofw_t, ihandle_t, char *, size_t);
 static ssize_t ofw_fdt_package_to_path(ofw_t, phandle_t, char *, size_t);
-static int ofw_fdt_interpret(ofw_t, const char *, int, unsigned long *);
+static int ofw_fdt_interpret(ofw_t, const char *, int, cell_t *);
 
 static ofw_method_t ofw_fdt_methods[] = {
 	OFWMETHOD(ofw_init,			ofw_fdt_init),
@@ -435,7 +435,7 @@ ofw_fdt_fixup(ofw_t ofw)
 }
 
 static int
-ofw_fdt_interpret(ofw_t ofw, const char *cmd, int nret, unsigned long *retvals)
+ofw_fdt_interpret(ofw_t ofw, const char *cmd, int nret, cell_t *retvals)
 {
 	int rv;
 
diff --git a/sys/dev/ofw/ofw_if.m b/sys/dev/ofw/ofw_if.m
index eff85a21c81..6017a69e7bd 100644
--- a/sys/dev/ofw/ofw_if.m
+++ b/sys/dev/ofw/ofw_if.m
@@ -244,7 +244,7 @@ METHOD int interpret {
 	ofw_t		_ofw;
 	const char	*_cmd;
 	int		_nreturns;
-	unsigned long	*_returns;
+	cell_t		*_returns;
 };
 
 # Device I/O Functions (optional)
diff --git a/sys/dev/ofw/ofw_standard.c b/sys/dev/ofw/ofw_standard.c
index e3f8bcc87fa..b514a94f335 100644
--- a/sys/dev/ofw/ofw_standard.c
+++ b/sys/dev/ofw/ofw_standard.c
@@ -73,7 +73,7 @@ __FBSDID("$FreeBSD$");
 static int ofw_std_init(ofw_t ofw, void *openfirm);
 static int ofw_std_test(ofw_t ofw, const char *name);
 static int ofw_std_interpret(ofw_t ofw, const char *cmd, int nreturns,
-    unsigned long *returns);
+    cell_t *returns);
 static phandle_t ofw_std_peer(ofw_t ofw, phandle_t node);
 static phandle_t ofw_std_child(ofw_t ofw, phandle_t node);
 static phandle_t ofw_std_parent(ofw_t ofw, phandle_t node);
@@ -94,8 +94,7 @@ static ssize_t ofw_std_instance_to_path(ofw_t ofw, ihandle_t instance,
 static ssize_t ofw_std_package_to_path(ofw_t ofw, phandle_t package, char *buf,
     size_t len);
 static int ofw_std_call_method(ofw_t ofw, ihandle_t instance,
-    const char *method, int nargs, int nreturns,
-    cell_t *args_and_returns);
+    const char *method, int nargs, int nreturns, cell_t *args_and_returns);
 static ihandle_t ofw_std_open(ofw_t ofw, const char *device);
 static void ofw_std_close(ofw_t ofw, ihandle_t instance);
 static ssize_t ofw_std_read(ofw_t ofw, ihandle_t instance, void *addr,
@@ -185,8 +184,7 @@ ofw_std_test(ofw_t ofw, const char *name)
 }
 
 static int
-ofw_std_interpret(ofw_t ofw, const char *cmd, int nreturns,
-    unsigned long *returns)
+ofw_std_interpret(ofw_t ofw, const char *cmd, int nreturns, cell_t *returns)
 {
 	struct {
 		cell_t name;
@@ -529,7 +527,7 @@ ofw_std_call_method(ofw_t ofw, ihandle_t instance, const char *method,
 		2,
 		1,
 	};
-	cell_t *cp, *ap;
+	cell_t *ap, *cp;
 	int n;
 
 	if (nargs > 6)
diff --git a/sys/dev/ofw/openfirm.c b/sys/dev/ofw/openfirm.c
index 241ce8a6369..8424fc20375 100644
--- a/sys/dev/ofw/openfirm.c
+++ b/sys/dev/ofw/openfirm.c
@@ -165,7 +165,7 @@ int
 OF_interpret(const char *cmd, int nreturns, ...)
 {
 	va_list ap;
-	unsigned long slots[16];
+	cell_t slots[16];
 	int i = 0;
 	int status;
 
diff --git a/sys/powerpc/ofw/ofw_real.c b/sys/powerpc/ofw/ofw_real.c
index 8eb86b47a59..963e96cbd0c 100644
--- a/sys/powerpc/ofw/ofw_real.c
+++ b/sys/powerpc/ofw/ofw_real.c
@@ -101,7 +101,7 @@ static ssize_t ofw_real_package_to_path(ofw_t, phandle_t package, char *buf,
 static int ofw_real_call_method(ofw_t, ihandle_t instance, const char *method, 
     int nargs, int nreturns, cell_t *args_and_returns);
 static int ofw_real_interpret(ofw_t ofw, const char *cmd, int nreturns,
-    unsigned long *returns);
+    cell_t *returns);
 static ihandle_t ofw_real_open(ofw_t, const char *device);
 static void ofw_real_close(ofw_t, ihandle_t instance);
 static ssize_t ofw_real_read(ofw_t, ihandle_t instance, void *addr, size_t len);
@@ -756,7 +756,7 @@ ofw_real_call_method(ofw_t ofw, ihandle_t instance, const char *method,
 		cell_t instance;
 		cell_t args_n_results[12];
 	} args;
-	cell_t *cp, *ap;
+	cell_t *ap, *cp;
 	int n;
 
 	args.name = (cell_t)(uintptr_t)"call-method";
@@ -791,8 +791,7 @@ ofw_real_call_method(ofw_t ofw, ihandle_t instance, const char *method,
 }
 
 static int
-ofw_real_interpret(ofw_t ofw, const char *cmd, int nreturns,
-    unsigned long *returns)
+ofw_real_interpret(ofw_t ofw, const char *cmd, int nreturns, cell_t *returns)
 {
 	vm_offset_t argsptr;
 	struct {

From eb262be33391d4dddbe108412c1e45acf8bc7c5c Mon Sep 17 00:00:00 2001
From: Alexander Kabaev 
Date: Sat, 11 Sep 2010 19:42:50 +0000
Subject: [PATCH 0649/1624] Add missing pointer increment to sbuf_cat.

---
 sys/kern/subr_sbuf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 4535337486b..0d083b4b33e 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -441,7 +441,7 @@ sbuf_cat(struct sbuf *s, const char *str)
 		return (-1);
 
 	while (*str != '\0') {
-		sbuf_put_byte(*str, s);
+		sbuf_put_byte(*str++, s);
 		if (s->s_error != 0)
 			return (-1);
 	}

From 90baf564d21e0cb968501250e5f2b495b43cba2e Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sat, 11 Sep 2010 20:18:15 +0000
Subject: [PATCH 0650/1624] Do not print "frequency 0 Hz", when frequency is
 unknown.

---
 sys/kern/kern_et.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/sys/kern/kern_et.c b/sys/kern/kern_et.c
index 6a56b1d4e80..17b9c676422 100644
--- a/sys/kern/kern_et.c
+++ b/sys/kern/kern_et.c
@@ -52,9 +52,15 @@ et_register(struct eventtimer *et)
 	struct eventtimer *tmp, *next;
 
 	if (et->et_quality >= 0 || bootverbose) {
-		printf("Event timer \"%s\" frequency %ju Hz quality %d\n",
-		    et->et_name, (uintmax_t)et->et_frequency,
-		    et->et_quality);
+		if (et->et_frequency == 0) {
+			printf("Event timer \"%s\" quality %d\n",
+			    et->et_name, et->et_quality);
+		} else {
+			printf("Event timer \"%s\" "
+			    "frequency %ju Hz quality %d\n",
+			    et->et_name, (uintmax_t)et->et_frequency,
+			    et->et_quality);
+		}
 	}
 	et->et_sysctl = SYSCTL_ADD_NODE(NULL,
 	    SYSCTL_STATIC_CHILDREN(_kern_eventtimer_et), OID_AUTO, et->et_name,

From 37e81ca522e2c863c595bd4ddd3490eb21643d6a Mon Sep 17 00:00:00 2001
From: Weongyo Jeong 
Date: Sat, 11 Sep 2010 21:49:28 +0000
Subject: [PATCH 0651/1624] Mentions cases when bwi(4) driver should be used
 that it only wrote about chipset type instead of card names because it's not
 easy to sort names what cards use these chipsets.

Pointed by:	imp
---
 share/man/man4/bwn.4 | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/share/man/man4/bwn.4 b/share/man/man4/bwn.4
index 23514f58a59..856012eb241 100644
--- a/share/man/man4/bwn.4
+++ b/share/man/man4/bwn.4
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd September 6, 2010
+.Dd September 11, 2010
 .Dt BWN 4
 .Os
 .Sh NAME
@@ -92,6 +92,13 @@ driver supports Broadcom BCM43xx based wireless devices, including:
 .It "TRENDnet TEW-401PCplus	BCM4306	CardBus	b/g"
 .It "US Robotics 5411	BCM4318	CardBus	b/g"
 .El
+.Pp
+However if the device chipset is one of BCM4301, BCM4303 and BCM4306 rev 2,
+uses
+.Xr bwi 4
+instead of
+.Xr bwn 4
+because the vendor dropped the firmware support.
 .Sh EXAMPLES
 Join an existing BSS network (i.e., connect to an access point):
 .Pp

From 1a18ae7010acb0bacb134d9f47614cf31228e35a Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Sat, 11 Sep 2010 22:09:16 +0000
Subject: [PATCH 0652/1624] ATAPI DMA does not seem to work completely reliably
 on Shasta controllers, especially in conjunction with ATA_CAM, so disable it
 for now.

---
 sys/powerpc/powermac/ata_kauai.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/sys/powerpc/powermac/ata_kauai.c b/sys/powerpc/powermac/ata_kauai.c
index fd45061e5a6..3ad2a48ee2a 100644
--- a/sys/powerpc/powermac/ata_kauai.c
+++ b/sys/powerpc/powermac/ata_kauai.c
@@ -217,8 +217,10 @@ ata_kauai_probe(device_t dev)
 	ch = &sc->sc_ch.sc_ch;
 
 	compatstring = ofw_bus_get_compat(dev);
-	if (compatstring != NULL && strcmp(compatstring,"shasta-ata") == 0)
+	if (compatstring != NULL && strcmp(compatstring,"shasta-ata") == 0) {
+		ch->flags |= ATA_NO_ATAPI_DMA;
 		sc->shasta = 1;
+	}
 
 	/* Pre-K2 controllers apparently need this hack */
 	if (!sc->shasta &&

From 6184f8d60ea8188f2b4ab77a1460fdfc5bdd69cf Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Sun, 12 Sep 2010 11:11:53 +0000
Subject: [PATCH 0653/1624] Instead of storing last event timestamp, store the
 next event timestamp. It corrects handling of the first event offset in
 emulated periodic mode.

---
 sys/dev/acpica/acpi_hpet.c | 47 +++++++++++++++++++++++---------------
 1 file changed, 28 insertions(+), 19 deletions(-)

diff --git a/sys/dev/acpica/acpi_hpet.c b/sys/dev/acpica/acpi_hpet.c
index 656a395f40d..bc8cd852aef 100644
--- a/sys/dev/acpica/acpi_hpet.c
+++ b/sys/dev/acpica/acpi_hpet.c
@@ -98,7 +98,7 @@ struct hpet_softc {
 		uint32_t		caps;
 		uint32_t		vectors;
 		uint32_t		div;
-		uint32_t		last;
+		uint32_t		next;
 		char			name[8];
 	} 			t[32];
 	int			num_timers;
@@ -149,7 +149,7 @@ hpet_start(struct eventtimer *et,
 	struct hpet_timer *mt = (struct hpet_timer *)et->et_priv;
 	struct hpet_timer *t;
 	struct hpet_softc *sc = mt->sc;
-	uint32_t fdiv, cmp;
+	uint32_t fdiv, now;
 
 	t = (mt->pcpu_master < 0) ? mt : &sc->t[mt->pcpu_slaves[curcpu]];
 	if (period != NULL) {
@@ -170,24 +170,28 @@ hpet_start(struct eventtimer *et,
 	if (t->irq < 0)
 		bus_write_4(sc->mem_res, HPET_ISR, 1 << t->num);
 	t->caps |= HPET_TCNF_INT_ENB;
-	t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+	now = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
 restart:
-	cmp = t->last + fdiv;
+	t->next = now + fdiv;
 	if (t->mode == 1 && (t->caps & HPET_TCAP_PER_INT)) {
 		t->caps |= HPET_TCNF_TYPE;
 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
 		    t->caps | HPET_TCNF_VAL_SET);
-		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num), cmp);
-		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num), t->div);
+		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
+		    t->next);
+		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
+		    t->div);
 	} else {
 		t->caps &= ~HPET_TCNF_TYPE;
-		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num), t->caps);
-		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num), cmp);
+		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
+		    t->caps);
+		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
+		    t->next);
 	}
 	if (fdiv < 5000) {
 		bus_read_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num));
-		t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
-		if ((int32_t)(t->last - cmp) >= 0) {
+		now = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+		if ((int32_t)(now - t->next) >= 0) {
 			fdiv *= 2;
 			goto restart;
 		}
@@ -217,6 +221,8 @@ hpet_intr_single(void *arg)
 	struct hpet_softc *sc = t->sc;
 	uint32_t now;
 
+	if (t->mode == 0)
+		return (FILTER_STRAY);
 	/* Check that per-CPU timer interrupt reached right CPU. */
 	if (t->pcpu_cpu >= 0 && t->pcpu_cpu != curcpu) {
 		if ((++t->pcpu_misrouted) % 32 == 0) {
@@ -231,20 +237,21 @@ hpet_intr_single(void *arg)
 		 */
 		if ((t->mode == 1 && (t->caps & HPET_TCAP_PER_INT) == 0) ||
 		    t->mode == 2) {
-			t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+			t->next = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER) +
+			    sc->freq / 8;
 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
-			    t->last + sc->freq / 8);
+			    t->next);
 		}
 		return (FILTER_HANDLED);
 	}
 	if (t->mode == 1 &&
 	    (t->caps & HPET_TCAP_PER_INT) == 0) {
-		t->last += t->div;
+		t->next += t->div;
 		now = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
-		if ((int32_t)(now - (t->last + t->div / 2)) > 0)
-			t->last = now - t->div / 2;
+		if ((int32_t)((now + t->div / 2) - t->next) > 0)
+			t->next = now + t->div / 2;
 		bus_write_4(sc->mem_res,
-		    HPET_TIMER_COMPARATOR(t->num), t->last + t->div);
+		    HPET_TIMER_COMPARATOR(t->num), t->next);
 	} else if (t->mode == 2)
 		t->mode = 0;
 	mt = (t->pcpu_master < 0) ? t : &sc->t[t->pcpu_master];
@@ -713,19 +720,21 @@ hpet_resume(device_t dev)
 #endif
 		if (t->mode == 0)
 			continue;
-		t->last = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
+		t->next = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
 		if (t->mode == 1 && (t->caps & HPET_TCAP_PER_INT)) {
 			t->caps |= HPET_TCNF_TYPE;
+			t->next += t->div;
 			bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
 			    t->caps | HPET_TCNF_VAL_SET);
 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
-			    t->last + t->div);
+			    t->next);
 			bus_read_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num));
 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
 			    t->div);
 		} else {
+			t->next += sc->freq / 1024;
 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
-			    t->last + sc->freq / 1024);
+			    t->next);
 		}
 		bus_write_4(sc->mem_res, HPET_ISR, 1 << t->num);
 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num), t->caps);

From 416d1e6f23ba692c99df1b8b2e138f70b12a49b9 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Sun, 12 Sep 2010 14:04:05 +0000
Subject: [PATCH 0654/1624] Bump dates in dbopen(3) and cpuset_getaffinity(2)
 from r212441 and r212438, repectively.

Approved by:	keramida (mentor)
MFC after:	1 week
---
 lib/libc/db/man/dbopen.3          | 2 +-
 lib/libc/sys/cpuset_getaffinity.2 | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/libc/db/man/dbopen.3 b/lib/libc/db/man/dbopen.3
index 7a9f548bfd2..13481dd7ecc 100644
--- a/lib/libc/db/man/dbopen.3
+++ b/lib/libc/db/man/dbopen.3
@@ -28,7 +28,7 @@
 .\"	@(#)dbopen.3	8.5 (Berkeley) 1/2/94
 .\" $FreeBSD$
 .\"
-.Dd January 2, 1994
+.Dd September 10, 2010
 .Dt DBOPEN 3
 .Os
 .Sh NAME
diff --git a/lib/libc/sys/cpuset_getaffinity.2 b/lib/libc/sys/cpuset_getaffinity.2
index 26d72ef7985..5c75b92a7dc 100644
--- a/lib/libc/sys/cpuset_getaffinity.2
+++ b/lib/libc/sys/cpuset_getaffinity.2
@@ -25,7 +25,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd January 8, 2010
+.Dd September 10, 2010
 .Dt CPUSET 2
 .Os
 .Sh NAME

From f3f98585783f1615c24cd2b2b2a442ddc833c2a3 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Sun, 12 Sep 2010 14:04:54 +0000
Subject: [PATCH 0655/1624] Bump date from r212440.

Approved by:	keramida (mentor)
MFC after:	1 week
---
 share/man/man9/devclass_get_maxunit.9 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/share/man/man9/devclass_get_maxunit.9 b/share/man/man9/devclass_get_maxunit.9
index 63b8490ebfc..ff18c9f232e 100644
--- a/share/man/man9/devclass_get_maxunit.9
+++ b/share/man/man9/devclass_get_maxunit.9
@@ -28,7 +28,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd April 3, 2005
+.Dd September 10, 2005
 .Dt DEVCLASS_GET_MAXUNIT 9
 .Os
 .Sh NAME

From 47047e3418f4965db9bd2dcd7caf1d61c02fa3a6 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 12 Sep 2010 14:12:16 +0000
Subject: [PATCH 0656/1624] Revamp locking a bit. This fixes three problems: *
 processes now can't go away while we are inserting probes (fixes a panic) *
 if a trap happens, we won't be holding the process lock (fixes a hang) * fix
 a LOR between the process lock and the fasttrap bucket list lock

Thanks to kib for pointing some problems.
Sponsored by:	The FreeBSD Foundation
---
 .../opensolaris/uts/common/dtrace/fasttrap.c  | 35 ++++++++++++-------
 .../uts/intel/dtrace/fasttrap_isa.c           |  9 ++---
 2 files changed, 26 insertions(+), 18 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
index 38c2c7a6215..4599a3238b0 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/dtrace/fasttrap.c
@@ -460,11 +460,13 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 		/*
 		 * dtrace_helpers_duplicate() allocates memory.
 		 */
+		_PHOLD(cp);
 		PROC_UNLOCK(p);
 		PROC_UNLOCK(cp);
 		dtrace_helpers_duplicate(p, cp);
 		PROC_LOCK(cp);
 		PROC_LOCK(p);
+		_PRELE(cp);
 	}
 	/*
 	 * This check is purposely here instead of in kern_fork.c because,
@@ -494,6 +496,8 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 	mtx_lock_spin(&cp->p_slock);
 	sprlock_proc(cp);
 	mtx_unlock_spin(&cp->p_slock);
+#else
+	_PHOLD(cp);
 #endif
 
 	/*
@@ -527,6 +531,8 @@ fasttrap_fork(proc_t *p, proc_t *cp)
 #if defined(sun)
 	mutex_enter(&cp->p_lock);
 	sprunlock(cp);
+#else
+	_PRELE(cp);
 #endif
 }
 
@@ -542,6 +548,7 @@ fasttrap_exec_exit(proc_t *p)
 	ASSERT(p == curproc);
 #endif
 	PROC_LOCK_ASSERT(p, MA_OWNED);
+	_PHOLD(p);
 	PROC_UNLOCK(p);
 
 	/*
@@ -554,6 +561,7 @@ fasttrap_exec_exit(proc_t *p)
 		dtrace_helpers_destroy(p);
 #endif
 	PROC_LOCK(p);
+	_PRELE(p);
 }
 
 
@@ -591,9 +599,7 @@ fasttrap_tracepoint_enable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
 	 * Before we make any modifications, make sure we've imposed a barrier
 	 * on the generation in which this probe was last modified.
 	 */
-	PROC_UNLOCK(p);
 	fasttrap_mod_barrier(probe->ftp_gen);
-	PROC_LOCK(p);
 
 	bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
 
@@ -695,8 +701,6 @@ again:
 		 */
 #if defined(sun)
 		ASSERT(p->p_proc_flag & P_PR_LOCK);
-#else
-		PROC_LOCK_ASSERT(p, MA_OWNED);
 #endif
 		p->p_dtrace_count++;
 
@@ -889,8 +893,6 @@ fasttrap_tracepoint_disable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
 		 */
 #if defined(sun)
 		ASSERT(p->p_proc_flag & P_PR_LOCK);
-#else
-		PROC_LOCK_ASSERT(p, MA_OWNED);
 #endif
 		p->p_dtrace_count--;
 	}
@@ -1044,9 +1046,14 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 	 * the chance to execute the trap instruction we're about to place
 	 * in their process's text.
 	 */
+#ifdef __FreeBSD__
+	/*
+	 * pfind() returns a locked process.
+	 */
+	_PHOLD(p);
 	PROC_UNLOCK(p);
+#endif
 	fasttrap_enable_callbacks();
-	PROC_LOCK(p);
 
 	/*
 	 * Enable all the tracepoints and add this probe's id to each
@@ -1077,7 +1084,7 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 			mutex_enter(&p->p_lock);
 			sprunlock(p);
 #else
-			PROC_UNLOCK(p);
+			PRELE(p);
 #endif
 
 			/*
@@ -1092,7 +1099,7 @@ fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
 	mutex_enter(&p->p_lock);
 	sprunlock(p);
 #else
-	PROC_UNLOCK(p);
+	PRELE(p);
 #endif
 
 	probe->ftp_enabled = 1;
@@ -1121,6 +1128,10 @@ fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
 		mutex_exit(&provider->ftp_mtx);
 		return;
 	}
+#ifdef __FreeBSD__
+	_PHOLD(p);
+	PROC_UNLOCK(p);
+#endif
 
 	/*
 	 * Disable all the associated tracepoints (for fully enabled probes).
@@ -1152,13 +1163,13 @@ fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
 			whack = provider->ftp_marked = 1;
 		mutex_exit(&provider->ftp_mtx);
 	}
-#if !defined(sun)
-	PROC_UNLOCK(p);
-#endif
 
 	if (whack)
 		fasttrap_pid_cleanup();
 
+#ifdef __FreeBSD__
+	PRELE(p);
+#endif
 	if (!probe->ftp_enabled)
 		return;
 
diff --git a/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c b/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
index dba77ce5d0c..85d9649f674 100644
--- a/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
+++ b/sys/cddl/contrib/opensolaris/uts/intel/dtrace/fasttrap_isa.c
@@ -74,15 +74,12 @@ proc_ops(int op, proc_t *p, void *kaddr, off_t uaddr, size_t len)
 	uio.uio_segflg = UIO_SYSSPACE;
 	uio.uio_td = curthread;
 	uio.uio_rw = op;
-	_PHOLD(p);
-	PROC_UNLOCK(p);
+	PHOLD(p);
 	if (proc_rwmem(p, &uio) < 0) {
-		PROC_LOCK(p);
-		_PRELE(p);
+		PRELE(p);
 		return (-1);
 	}
-	PROC_LOCK(p);
-	_PRELE(p);
+	PRELE(p);
 
 	return (0);
 }

From 7879263397dd5f904770ec2446920dea4199e504 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Sun, 12 Sep 2010 15:59:14 +0000
Subject: [PATCH 0657/1624] Give a chance to the target binary to run the ctors
 by waiting until it has reached main(). This allows plockstat to work.

Sponsored by:	The FreeBSD Foundation
---
 cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c
index a8070e602ef..962da1a884b 100644
--- a/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c
+++ b/cddl/contrib/opensolaris/lib/libdtrace/common/dt_open.c
@@ -1103,7 +1103,7 @@ alloc:
 #if defined(sun)
 	dtp->dt_prcmode = DT_PROC_STOP_PREINIT;
 #else
-	dtp->dt_prcmode = DT_PROC_STOP_POSTINIT;
+	dtp->dt_prcmode = DT_PROC_STOP_MAIN;
 #endif
 	dtp->dt_linkmode = DT_LINK_KERNEL;
 	dtp->dt_linktype = DT_LTYP_ELF;

From 89f81c964662f6934ef86f94f46507bb7f944d18 Mon Sep 17 00:00:00 2001
From: Ivan Voras 
Date: Sun, 12 Sep 2010 16:28:26 +0000
Subject: [PATCH 0658/1624] List low-level Blowfish ECB module in the SRCS. It
 looks like it was dropped by accident (and it would be inconvenient to
 implement it otherwise because it uses internal non-published headers).

MFC after:	1 week
---
 sys/modules/crypto/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/modules/crypto/Makefile b/sys/modules/crypto/Makefile
index be801db598d..bf7c566f133 100644
--- a/sys/modules/crypto/Makefile
+++ b/sys/modules/crypto/Makefile
@@ -12,7 +12,7 @@ KMOD	= crypto
 SRCS	= crypto.c cryptodev_if.c
 SRCS	+= criov.c cryptosoft.c xform.c
 SRCS	+= cast.c deflate.c rmd160.c rijndael-alg-fst.c rijndael-api.c
-SRCS	+= skipjack.c bf_enc.c bf_skey.c
+SRCS	+= skipjack.c bf_enc.c bf_ecb.c bf_skey.c
 SRCS	+= des_ecb.c des_enc.c des_setkey.c
 SRCS	+= sha1.c sha2.c
 SRCS	+= opt_param.h cryptodev_if.h bus_if.h device_if.h

From d48dde6f68072916eb115b65cb71353edbb19e7e Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Sun, 12 Sep 2010 17:04:51 +0000
Subject: [PATCH 0659/1624] Check for undefined weak symbols during PLT binding
 on powerpc64, and do not attempt to copy NULL function descriptors. This
 fixes LD_BIND_NOW on powerpc64 after r211706.

Reviewed by:	kib
---
 libexec/rtld-elf/powerpc64/reloc.c | 9 +++++++--
 libexec/rtld-elf/rtld.c            | 2 +-
 libexec/rtld-elf/rtld.h            | 1 +
 3 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/libexec/rtld-elf/powerpc64/reloc.c b/libexec/rtld-elf/powerpc64/reloc.c
index b35be180652..d2430e741d8 100644
--- a/libexec/rtld-elf/powerpc64/reloc.c
+++ b/libexec/rtld-elf/powerpc64/reloc.c
@@ -405,8 +405,13 @@ reloc_jmpslots(Obj_Entry *obj)
 		    (void *)target, basename(defobj->path));
 #endif
 
-		reloc_jmpslot(where, target, defobj, obj,
-		    (const Elf_Rel *) rela);
+		if (def == &sym_zero) {
+			/* Zero undefined weak symbols */
+			bzero(where, sizeof(struct funcdesc));
+		} else {
+			reloc_jmpslot(where, target, defobj, obj,
+			    (const Elf_Rel *) rela);
+		}
 	}
 
 	obj->jmpslots_done = true;
diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
index a1b95ae612c..8bc8692a922 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -183,7 +183,7 @@ static Objlist list_main =	/* Objects loaded at program startup */
 static Objlist list_fini =	/* Objects needing fini() calls */
   STAILQ_HEAD_INITIALIZER(list_fini);
 
-static Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
+Elf_Sym sym_zero;		/* For resolving undefined weak refs. */
 
 #define GDB_STATE(s,m)	r_debug.r_state = s; r_debug_state(&r_debug,m);
 
diff --git a/libexec/rtld-elf/rtld.h b/libexec/rtld-elf/rtld.h
index 875e84bc7e6..6bae2f034b7 100644
--- a/libexec/rtld-elf/rtld.h
+++ b/libexec/rtld-elf/rtld.h
@@ -261,6 +261,7 @@ extern void *xcalloc(size_t);
 extern void *xmalloc(size_t);
 extern char *xstrdup(const char *);
 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
+extern Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
 
 extern void dump_relocations (Obj_Entry *);
 extern void dump_obj_relocations (Obj_Entry *);

From 92d01db21c32c0b650a8b73562f48c12047e2465 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Sun, 12 Sep 2010 17:50:07 +0000
Subject: [PATCH 0660/1624] Rewording and typo fixes in newfs(8).

PR:		150490
Submitted by:	Eitan Adler 
Additional fixes by:	Warren Block , keramida
Approved by:	keramida (mentor)
MFC after:	1 week
---
 sbin/newfs/newfs.8 | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/sbin/newfs/newfs.8 b/sbin/newfs/newfs.8
index ec9bcd8c71a..f49a730ff50 100644
--- a/sbin/newfs/newfs.8
+++ b/sbin/newfs/newfs.8
@@ -79,10 +79,10 @@ The following options define the general layout policies:
 Erase the content of the disk before making the filesystem.
 The reserved area in front of the superblock (for bootcode) will not be erased.
 .Pp
-This is a relevant option for flash based storage devices that use
-wear levelling algorithms.
+This option is only relevant for flash based storage devices that use
+wear-leveling algorithms.
 .Pp
-NB: Erasing may take as long time as writing every sector on the disk.
+Erasing may take a long time as it writes to every sector on the disk.
 .It Fl J
 Enable journaling on the new file system via gjournal.
 See

From 702dafe6ab6b8836875ba43cecca06ec35f1216e Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sun, 12 Sep 2010 17:53:31 +0000
Subject: [PATCH 0661/1624] Fix typo.

MFC after:	3 days
---
 sys/sys/elf_common.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/elf_common.h b/sys/sys/elf_common.h
index 5d43634d132..79323049fb7 100644
--- a/sys/sys/elf_common.h
+++ b/sys/sys/elf_common.h
@@ -388,7 +388,7 @@ typedef struct {
 #define	DT_ENCODING	32	/* Values greater than or equal to DT_ENCODING
 				   and less than DT_LOOS follow the rules for
 				   the interpretation of the d_un union
-				   as follows: even == 'd_ptr', even == 'd_val'
+				   as follows: even == 'd_ptr', odd == 'd_val'
 				   or none */
 #define	DT_PREINIT_ARRAY 32	/* Address of the array of pointers to
 				   pre-initialization functions. */

From 8d89b8f2a2b5eac660bd700af5196a2ece94b8fc Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Sun, 12 Sep 2010 17:53:36 +0000
Subject: [PATCH 0662/1624] I believe the majority of Gregorian calendars would
 agree the current year is 2010, not 2005.

Approved by:	keramida (mentor)
Pointy hat to:	gjb
MFC after:	1 week
---
 share/man/man9/devclass_get_maxunit.9 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/share/man/man9/devclass_get_maxunit.9 b/share/man/man9/devclass_get_maxunit.9
index ff18c9f232e..fc2bc25b8da 100644
--- a/share/man/man9/devclass_get_maxunit.9
+++ b/share/man/man9/devclass_get_maxunit.9
@@ -28,7 +28,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd September 10, 2005
+.Dd September 10, 2010
 .Dt DEVCLASS_GET_MAXUNIT 9
 .Os
 .Sh NAME

From 12debc81fc3dd3a0af11c57fa2d33604802cad80 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sun, 12 Sep 2010 17:55:56 +0000
Subject: [PATCH 0663/1624] Add DF_1_LOADFLTR.

MFC after:	3 days
---
 sys/sys/elf_common.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/sys/elf_common.h b/sys/sys/elf_common.h
index 79323049fb7..1e1154f3896 100644
--- a/sys/sys/elf_common.h
+++ b/sys/sys/elf_common.h
@@ -471,6 +471,7 @@ typedef struct {
 #define	DF_1_BIND_NOW	0x00000001	/* Same as DF_BIND_NOW */
 #define	DF_1_GLOBAL	0x00000002	/* Set the RTLD_GLOBAL for object */
 #define	DF_1_NODELETE	0x00000008	/* Set the RTLD_NODELETE for object */
+#define	DF_1_LOADFLTR	0x00000010	/* Immediate loading of filtees */
 #define	DF_1_NOOPEN     0x00000040	/* Do not allow loading on dlopen() */
 #define	DF_1_ORIGIN	0x00000080	/* Process $ORIGIN */
 

From a458eaa039f041c8bf534a73ee1f340c56237085 Mon Sep 17 00:00:00 2001
From: Qing Li 
Date: Sun, 12 Sep 2010 18:04:47 +0000
Subject: [PATCH 0664/1624] Adding an address on an interface also requires the
 loopback route to that address be installed.

PR:		kern/150481
Submitted by:	Ingo Flaschberger 
MFC after:	5 days
---
 sys/netinet/raw_ip.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sys/netinet/raw_ip.c b/sys/netinet/raw_ip.c
index d6b426c9a48..c91d4a9da9f 100644
--- a/sys/netinet/raw_ip.c
+++ b/sys/netinet/raw_ip.c
@@ -741,6 +741,8 @@ rip_ctlinput(int cmd, struct sockaddr *sa, void *vip)
 		if (err == 0)
 			ia->ia_flags |= IFA_ROUTE;
 		err = ifa_add_loopback_route((struct ifaddr *)ia, sa);
+		if (err == 0)
+			ia->ia_flags |= IFA_RTSELF;
 		ifa_free(&ia->ia_ifa);
 		break;
 	}

From ab7d0151f9f429f912b9a48e0e53dc9158106399 Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Sun, 12 Sep 2010 18:53:44 +0000
Subject: [PATCH 0665/1624] In backup_kernel(), support backing up
 subdirectories and handle files with spaces correctly.

Approved by:	cperciva
MFC after:	1 month
---
 usr.sbin/freebsd-update/freebsd-update.sh | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/usr.sbin/freebsd-update/freebsd-update.sh b/usr.sbin/freebsd-update/freebsd-update.sh
index b5420776423..441d257a98f 100644
--- a/usr.sbin/freebsd-update/freebsd-update.sh
+++ b/usr.sbin/freebsd-update/freebsd-update.sh
@@ -2638,11 +2638,13 @@ backup_kernel () {
 	# "not ours", backup_kernel_finddir would have exited, so
 	# deleting the directory content is as safe as we can make it.
 	if [ -d $BACKUPKERNELDIR ]; then
-		rm -f $BACKUPKERNELDIR/*
+		rm -fr $BACKUPKERNELDIR
 	fi
 
-	# Create directory for backup if it doesn't exist.
+	# Create directories for backup.
 	mkdir -p $BACKUPKERNELDIR
+	mtree -cdn -p "${KERNELDIR}" | \
+	    mtree -Ue -p "${BACKUPKERNELDIR}" > /dev/null
 
 	# Mark the directory as having been created by freebsd-update.
 	touch $BACKUPKERNELDIR/.freebsd-update
@@ -2663,9 +2665,8 @@ backup_kernel () {
 	fi
 
 	# Backup all the kernel files using hardlinks.
-	find $KERNELDIR -type f $FINDFILTER | \
-		sed -Ee "s,($KERNELDIR)/?(.*),\1/\2 ${BACKUPKERNELDIR}/\2," | \
-		xargs -n 2 cp -pl
+	(cd $KERNELDIR && find . -type f $FINDFILTER -exec \
+	    cp -pl '{}' ${BACKUPKERNELDIR}/'{}' \;)
 
 	# Re-enable patchname expansion.
 	set +f

From 57bfe0a9f8c5710f149bcb5511413036d9324df3 Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Sun, 12 Sep 2010 19:06:08 +0000
Subject: [PATCH 0666/1624] Do not fork nfsiod directly from the vop methods.
 This causes LORs between vnode lock and several locks needed during fork,
 like fd lock.

Instead, schedule the task to be executed in the taskqueue context. We
still waiting for the fork to finish, but the context of the thread
executing the task does not make real LORs with our vnode lock.

Submitted by:	pluknet at gmail com
Reviewed by:	jhb
Tested by:	pho
MFC after:	3 weeks
---
 sys/nfsclient/nfs.h        |  2 ++
 sys/nfsclient/nfs_nfsiod.c | 41 ++++++++++++++++++++++++++++++++++++--
 sys/nfsclient/nfs_subs.c   |  7 +++++++
 3 files changed, 48 insertions(+), 2 deletions(-)

diff --git a/sys/nfsclient/nfs.h b/sys/nfsclient/nfs.h
index 6f6e0d33ad5..da61175c4dd 100644
--- a/sys/nfsclient/nfs.h
+++ b/sys/nfsclient/nfs.h
@@ -125,6 +125,7 @@ extern struct uma_zone *nfsmount_zone;
 
 extern struct nfsstats nfsstats;
 extern struct mtx nfs_iod_mtx;
+extern struct task nfs_nfsiodnew_task;
 
 extern int nfs_numasync;
 extern unsigned int nfs_iodmax;
@@ -253,6 +254,7 @@ int	nfs_commit(struct vnode *vp, u_quad_t offset, int cnt,
 	    struct ucred *cred, struct thread *td);
 int	nfs_readdirrpc(struct vnode *, struct uio *, struct ucred *);
 int	nfs_nfsiodnew(int);
+void	nfs_nfsiodnew_tq(__unused void *, int);
 int	nfs_asyncio(struct nfsmount *, struct buf *, struct ucred *, struct thread *);
 int	nfs_doio(struct vnode *, struct buf *, struct ucred *, struct thread *);
 void	nfs_doio_directwrite (struct buf *);
diff --git a/sys/nfsclient/nfs_nfsiod.c b/sys/nfsclient/nfs_nfsiod.c
index d192848f067..5e2fbcc13ad 100644
--- a/sys/nfsclient/nfs_nfsiod.c
+++ b/sys/nfsclient/nfs_nfsiod.c
@@ -59,6 +59,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -75,6 +76,16 @@ static MALLOC_DEFINE(M_NFSSVC, "nfsclient_srvsock", "Nfs server structure");
 
 static void	nfssvc_iod(void *);
 
+struct nfsiod_str {
+	STAILQ_ENTRY(nfsiod_str) ni_links;
+	int *ni_inst;
+	int ni_iod;
+	int ni_error;
+	int ni_done;
+};
+static STAILQ_HEAD(, nfsiod_str) nfsiodhead =
+    STAILQ_HEAD_INITIALIZER(nfsiodhead);
+
 static int nfs_asyncdaemon[NFS_MAXASYNCDAEMON];
 
 SYSCTL_DECL(_vfs_nfs);
@@ -159,11 +170,30 @@ SYSCTL_PROC(_vfs_nfs, OID_AUTO, iodmax, CTLTYPE_UINT | CTLFLAG_RW, 0,
     sizeof (nfs_iodmax), sysctl_iodmax, "IU",
     "Max number of nfsiod kthreads");
 
+void
+nfs_nfsiodnew_tq(__unused void *arg, int pending)
+{
+	struct nfsiod_str *nip;
+
+	mtx_lock(&nfs_iod_mtx);
+	while ((nip = STAILQ_FIRST(&nfsiodhead)) != NULL) {
+		STAILQ_REMOVE_HEAD(&nfsiodhead, ni_links);
+		mtx_unlock(&nfs_iod_mtx);
+		nip->ni_error = kproc_create(nfssvc_iod, nip->ni_inst, NULL,
+		    RFHIGHPID, 0, "nfsiod %d", nip->ni_iod);
+		nip->ni_done = 1;
+		mtx_lock(&nfs_iod_mtx);
+		wakeup(nip);
+	}
+	mtx_unlock(&nfs_iod_mtx);
+}
+
 int
 nfs_nfsiodnew(int set_iodwant)
 {
 	int error, i;
 	int newiod;
+	struct nfsiod_str *nip;
 
 	if (nfs_numasync >= nfs_iodmax)
 		return (-1);
@@ -179,9 +209,16 @@ nfs_nfsiodnew(int set_iodwant)
 	if (set_iodwant > 0)
 		nfs_iodwant[i] = NFSIOD_CREATED_FOR_NFS_ASYNCIO;
 	mtx_unlock(&nfs_iod_mtx);
-	error = kproc_create(nfssvc_iod, nfs_asyncdaemon + i, NULL, RFHIGHPID,
-	    0, "nfsiod %d", newiod);
+	nip = malloc(sizeof(*nip), M_TEMP, M_WAITOK | M_ZERO);
+	nip->ni_inst = nfs_asyncdaemon + i;
+	nip->ni_iod = newiod;
 	mtx_lock(&nfs_iod_mtx);
+	STAILQ_INSERT_TAIL(&nfsiodhead, nip, ni_links);
+	taskqueue_enqueue(taskqueue_thread, &nfs_nfsiodnew_task);
+	while (!nip->ni_done)
+		mtx_sleep(nip, &nfs_iod_mtx, 0, "niwt", 0);
+	error = nip->ni_error;
+	free(nip, M_TEMP);
 	if (error) {
 		if (set_iodwant > 0)
 			nfs_iodwant[i] = NFSIOD_NOT_AVAILABLE;
diff --git a/sys/nfsclient/nfs_subs.c b/sys/nfsclient/nfs_subs.c
index 0ab5fa28c2e..7c9941fdd17 100644
--- a/sys/nfsclient/nfs_subs.c
+++ b/sys/nfsclient/nfs_subs.c
@@ -59,6 +59,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -117,6 +118,7 @@ int		nfs_pbuf_freecnt = -1;	/* start out unlimited */
 
 struct nfs_bufq	nfs_bufq;
 static struct mtx nfs_xid_mtx;
+struct task	nfs_nfsiodnew_task;
 
 /*
  * and the reverse mapping from generic to Version 2 procedure numbers
@@ -354,6 +356,7 @@ nfs_init(struct vfsconf *vfsp)
 	 */
 	mtx_init(&nfs_iod_mtx, "NFS iod lock", NULL, MTX_DEF);
 	mtx_init(&nfs_xid_mtx, "NFS xid lock", NULL, MTX_DEF);
+	TASK_INIT(&nfs_nfsiodnew_task, 0, nfs_nfsiodnew_tq, NULL);
 
 	nfs_pbuf_freecnt = nswbuf / 2 + 1;
 
@@ -368,9 +371,13 @@ nfs_uninit(struct vfsconf *vfsp)
 	/*
 	 * Tell all nfsiod processes to exit. Clear nfs_iodmax, and wakeup
 	 * any sleeping nfsiods so they check nfs_iodmax and exit.
+	 * Drain nfsiodnew task before we wait for them to finish.
 	 */
 	mtx_lock(&nfs_iod_mtx);
 	nfs_iodmax = 0;
+	mtx_unlock(&nfs_iod_mtx);
+	taskqueue_drain(taskqueue_thread, &nfs_nfsiodnew_task);
+	mtx_lock(&nfs_iod_mtx);
 	for (i = 0; i < nfs_numasync; i++)
 		if (nfs_iodwant[i] == NFSIOD_AVAILABLE)
 			wakeup(&nfs_iodwant[i]);

From 68710d7d2f852c6f90ca8a8d2e1c04bac4f0f6ba Mon Sep 17 00:00:00 2001
From: Olivier Houchard 
Date: Sun, 12 Sep 2010 20:46:32 +0000
Subject: [PATCH 0667/1624] In pmap_remove_all(), do not decrease
 pm_stats.wired_count if the mapping was wired, as it's been done later in
 pmap_nuke_pv().

Submitted by:	Mark Tinguely
---
 sys/arm/arm/pmap.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/arm/arm/pmap.c b/sys/arm/arm/pmap.c
index 3bcbbe0c98b..f33a692e730 100644
--- a/sys/arm/arm/pmap.c
+++ b/sys/arm/arm/pmap.c
@@ -3158,8 +3158,6 @@ pmap_remove_all(vm_page_t m)
 			*ptep = 0;
 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
 			pmap_free_l2_bucket(pv->pv_pmap, l2b, 1);
-			if (pv->pv_flags & PVF_WIRED)
-				pv->pv_pmap->pm_stats.wired_count--;
 			pv->pv_pmap->pm_stats.resident_count--;
 			flags |= pv->pv_flags;
 		}

From 2b11dfee8e281074ca3d67abca126429f0aee792 Mon Sep 17 00:00:00 2001
From: Jilles Tjoelker 
Date: Sun, 12 Sep 2010 22:00:31 +0000
Subject: [PATCH 0668/1624] sh: Add __dead2 to two functions that do not
 return.

Apart from helping static analyzers, this also appears to reduce the size of
the binary slightly.
---
 bin/sh/parser.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/bin/sh/parser.c b/bin/sh/parser.c
index 69d3e6f2d9f..02012ef1f1a 100644
--- a/bin/sh/parser.c
+++ b/bin/sh/parser.c
@@ -118,8 +118,8 @@ STATIC int readtoken(void);
 STATIC int xxreadtoken(void);
 STATIC int readtoken1(int, char const *, char *, int);
 STATIC int noexpand(char *);
-STATIC void synexpect(int);
-STATIC void synerror(const char *);
+STATIC void synexpect(int) __dead2;
+STATIC void synerror(const char *) __dead2;
 STATIC void setprompt(int);
 
 

From cb015705d81a572c8ba8fad8a8f4f3f1ca2da6a7 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 00:57:48 +0000
Subject: [PATCH 0669/1624] Use TARGET_CPUARCH instead of TARGET_ARCH here. 
 Define TARGET_CPUARCH based on TARGET_ARCH.  Use TARGET_ARCH still for a
 powerpc64 test. Futureproof for coming mipsel/mipseb and arm/armeb rename.

---
 usr.sbin/crunch/crunchide/Makefile | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/usr.sbin/crunch/crunchide/Makefile b/usr.sbin/crunch/crunchide/Makefile
index 3e173e48608..34e5674420a 100644
--- a/usr.sbin/crunch/crunchide/Makefile
+++ b/usr.sbin/crunch/crunchide/Makefile
@@ -3,6 +3,14 @@
 PROG=   crunchide
 SRCS=	crunchide.c
 
+# These assignments duplicate much of the functionality of
+# MACHINE_CPUARCH, but there's no easy way to export make functions...
+
+.if defined(TARGET_ARCH)
+TARGET_CPUARCH=${TARGET_ARCH:C/mipse[bl]/mips/:C/armeb/arm/}
+.else
+TARGET_CPUARCH=${MACHINE_CPUARCH}
+.endif
 TARGET_ARCH?=	${MACHINE_ARCH}
 
 .if ${TARGET_ARCH} == i386 && ${MACHINE_ARCH} == i386
@@ -10,8 +18,9 @@ CFLAGS+=-DNLIST_AOUT
 SRCS+=	exec_aout.c
 .endif
 
-.if ${TARGET_ARCH} == ia64 || ${TARGET_ARCH} == powerpc64 || \
-    ${TARGET_ARCH} == sparc64 || ${TARGET_ARCH} == amd64
+# nb: TARGET_ARCH for powerpc64 is correct here
+.if ${TARGET_CPUARCH} == ia64 || ${TARGET_ARCH} == powerpc64 || \
+    ${TARGET_CPUARCH} == sparc64 || ${TARGET_CPUARCH} == amd64
 CFLAGS+=-DNLIST_ELF64
 SRCS+=	exec_elf64.c
 exec_elf64.o: exec_elf32.c

From 1136c95ff4a877b262a1d12331afe5b15011c00d Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 01:00:48 +0000
Subject: [PATCH 0670/1624] Move to using TARGET_CPUARCH instead of
 TARGET_ARCH.

---
 usr.bin/xlint/Makefile.inc | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/usr.bin/xlint/Makefile.inc b/usr.bin/xlint/Makefile.inc
index 0c1b97a5cdf..f4956ab25e5 100644
--- a/usr.bin/xlint/Makefile.inc
+++ b/usr.bin/xlint/Makefile.inc
@@ -5,8 +5,16 @@ WARNS?=		0
 
 .PATH:		${.CURDIR}/../common
 
+# These assignments duplicate much of the functionality of
+# MACHINE_CPUARCH, but there's no easy way to export make functions...
+
+.if defined(TARGET_ARCH)
+TARGET_CPUARCH=${TARGET_ARCH:C/mipse[bl]/mips/:C/armeb/arm/}
+.else
+TARGET_CPUARCH=${MACHINE_CPUARCH}
+.endif
 TARGET_ARCH?=	${MACHINE_ARCH}
-CFLAGS+=	-I${.CURDIR}/../arch/${TARGET_ARCH}
+CFLAGS+=	-I${.CURDIR}/../arch/${TARGET_CPUARCH}
 CFLAGS+=	-I${.CURDIR}/../common
 
 OBJECT_FMT=	ELF

From 9cbda5febfa066ff1d9ce80b1ba78f1fcb5bce32 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 01:20:53 +0000
Subject: [PATCH 0671/1624] merge powerpc and powerpc64 now that we use
 TARGET_CPUARCH

---
 usr.bin/xlint/arch/powerpc/targparam.h   | 11 +++++
 usr.bin/xlint/arch/powerpc64/targparam.h | 55 ------------------------
 2 files changed, 11 insertions(+), 55 deletions(-)
 delete mode 100644 usr.bin/xlint/arch/powerpc64/targparam.h

diff --git a/usr.bin/xlint/arch/powerpc/targparam.h b/usr.bin/xlint/arch/powerpc/targparam.h
index d49eb764388..2316f30983b 100644
--- a/usr.bin/xlint/arch/powerpc/targparam.h
+++ b/usr.bin/xlint/arch/powerpc/targparam.h
@@ -29,13 +29,19 @@
  * 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.
+ *
+ * $FreeBSD$
  */
 
 /*
  * Machine-dependent target parameters for lint1.
  */
 
+#ifdef __powerpc64__
+#include "lp64.h"
+#else
 #include "ilp32.h"
+#endif
 
 /*    
  * Should be set to 1 if the difference of two pointers is of type long
@@ -43,8 +49,13 @@
  * kept in sync with the compiler!
  */     
 
+#ifdef __powerpc64__
+#define	PTRDIFF_IS_LONG		1
+#define	SIZEOF_IS_ULONG		1
+#else
 #define	PTRDIFF_IS_LONG		0
 #define	SIZEOF_IS_ULONG		0
+#endif
 
 #define	FLOAT_SIZE		(4 * CHAR_BIT)
 #define	DOUBLE_SIZE		(8 * CHAR_BIT)
diff --git a/usr.bin/xlint/arch/powerpc64/targparam.h b/usr.bin/xlint/arch/powerpc64/targparam.h
deleted file mode 100644
index 09bfd3e2b3c..00000000000
--- a/usr.bin/xlint/arch/powerpc64/targparam.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*	$NetBSD: targparam.h,v 1.1 2002/01/18 20:39:20 thorpej Exp $	*/
-
-/*
- * Copyright (c) 1994, 1995 Jochen Pohl
- * 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 Jochen Pohl for
- *	The NetBSD Project.
- * 4. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
- *
- * $FreeBSD$
- */
-
-/*
- * Machine-dependent target parameters for lint1.
- */
-
-#include "lp64.h"
-
-/*    
- * Should be set to 1 if the difference of two pointers is of type long
- * or the value of sizeof is of type unsigned long.  Note this MUST be
- * kept in sync with the compiler!
- */     
-
-#define	PTRDIFF_IS_LONG		1
-#define	SIZEOF_IS_ULONG		1
-
-#define	FLOAT_SIZE		(4 * CHAR_BIT)
-#define	DOUBLE_SIZE		(8 * CHAR_BIT)
-#define	LDOUBLE_SIZE		(8 * CHAR_BIT)
-
-#define	ENUM_SIZE		(4 * CHAR_BIT)

From 9768ccae056d693c0ab571a02d16d57ce8785c88 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 01:29:51 +0000
Subject: [PATCH 0672/1624] Merge from tbemd: Add directory names directly and
 sort at the end. Include bsd.arch.inc.mk so we can, in the future, more
 easily make arch dependent changes in /bin (unlikely, but is needed for
 symmetry).

---
 bin/Makefile | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/bin/Makefile b/bin/Makefile
index 3114e670097..e5052cad51a 100644
--- a/bin/Makefile
+++ b/bin/Makefile
@@ -8,7 +8,6 @@ SUBDIR= cat \
 	chio \
 	chmod \
 	cp \
-	${_csh} \
 	date \
 	dd \
 	df \
@@ -29,10 +28,8 @@ SUBDIR= cat \
 	ps \
 	pwait \
 	pwd \
-	${_rcp} \
 	realpath \
 	rm \
-	${_rmail} \
 	rmdir \
 	setfacl \
 	sh \
@@ -43,15 +40,19 @@ SUBDIR= cat \
 	uuidgen
 
 .if ${MK_RCMDS} != "no"
-_rcp=	rcp
+SUBDIR+=	rcp
 .endif
 
 .if ${MK_SENDMAIL} != "no"
-_rmail=	rmail
+SUBDIR+=	rmail
 .endif
 
 .if ${MK_TCSH} != "no"
-_csh=	csh
+SUBDIR+=	csh
 .endif
 
+.include 
+
+SUBDIR:=	${SUBDIR:O}
+
 .include 

From 10f3ae5899a263635b5354c6f50362161c15740d Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 01:43:10 +0000
Subject: [PATCH 0673/1624] Merge from tbemd, with a small amount of rework:
 For all libthr contexts, use ${MACHINE_CPUARCH} for all libc contexts, use
 ${MACHINE_ARCH} if it exists, otherwise use ${MACHINE_CPUARCH} Move some
 common code up a layer (the .PATH statement was the same in all the arch
 submakefiles).

# Hope she hasn't busted powerpc64 with this...
---
 lib/libthr/Makefile                  | 4 +++-
 lib/libthr/arch/amd64/Makefile.inc   | 2 --
 lib/libthr/arch/arm/Makefile.inc     | 2 --
 lib/libthr/arch/i386/Makefile.inc    | 2 --
 lib/libthr/arch/ia64/Makefile.inc    | 2 --
 lib/libthr/arch/mips/Makefile.inc    | 2 --
 lib/libthr/arch/powerpc/Makefile.inc | 2 --
 lib/libthr/arch/sparc64/Makefile.inc | 2 --
 lib/libthr/support/Makefile.inc      | 9 ++++++++-
 9 files changed, 11 insertions(+), 16 deletions(-)

diff --git a/lib/libthr/Makefile b/lib/libthr/Makefile
index 6a10ce3ce80..e64a412f56b 100644
--- a/lib/libthr/Makefile
+++ b/lib/libthr/Makefile
@@ -22,7 +22,7 @@ CFLAGS+=-I${.CURDIR}/../libc/include -I${.CURDIR}/thread \
 CFLAGS+=-I${.CURDIR}/arch/${MACHINE_CPUARCH}/include
 CFLAGS+=-I${.CURDIR}/sys
 CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf
-CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf/${MACHINE_ARCH}
+CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf/${MACHINE_CPUARCH}
 CFLAGS+=-I${.CURDIR}/../libthread_db
 CFLAGS+=-Winline
 LDFLAGS+=-Wl,-znodelete
@@ -38,6 +38,8 @@ CFLAGS+=-D_PTHREADS_INVARIANTS
 
 PRECIOUSLIB=
 
+.PATH: ${.CURDIR}/arch/${MACHINE_CPUARCH}/${MACHINE_CPUARCH}
+
 .include "${.CURDIR}/arch/${MACHINE_CPUARCH}/Makefile.inc"
 .include "${.CURDIR}/sys/Makefile.inc"
 .include "${.CURDIR}/thread/Makefile.inc"
diff --git a/lib/libthr/arch/amd64/Makefile.inc b/lib/libthr/arch/amd64/Makefile.inc
index f62999f9c88..e6d99ec0f57 100644
--- a/lib/libthr/arch/amd64/Makefile.inc
+++ b/lib/libthr/arch/amd64/Makefile.inc
@@ -1,5 +1,3 @@
 #$FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
 SRCS+=	pthread_md.c _umtx_op_err.S
diff --git a/lib/libthr/arch/arm/Makefile.inc b/lib/libthr/arch/arm/Makefile.inc
index b6a4acd6f60..2ee224772e2 100644
--- a/lib/libthr/arch/arm/Makefile.inc
+++ b/lib/libthr/arch/arm/Makefile.inc
@@ -1,5 +1,3 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
 SRCS+=	pthread_md.c
diff --git a/lib/libthr/arch/i386/Makefile.inc b/lib/libthr/arch/i386/Makefile.inc
index 35e93a250ec..01290d5ddac 100644
--- a/lib/libthr/arch/i386/Makefile.inc
+++ b/lib/libthr/arch/i386/Makefile.inc
@@ -1,5 +1,3 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
 SRCS+=	pthread_md.c _umtx_op_err.S
diff --git a/lib/libthr/arch/ia64/Makefile.inc b/lib/libthr/arch/ia64/Makefile.inc
index 160cdf64577..795aa9992d5 100644
--- a/lib/libthr/arch/ia64/Makefile.inc
+++ b/lib/libthr/arch/ia64/Makefile.inc
@@ -1,5 +1,3 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
 SRCS+= _umtx_op_err.S pthread_md.c
diff --git a/lib/libthr/arch/mips/Makefile.inc b/lib/libthr/arch/mips/Makefile.inc
index b6a4acd6f60..2ee224772e2 100644
--- a/lib/libthr/arch/mips/Makefile.inc
+++ b/lib/libthr/arch/mips/Makefile.inc
@@ -1,5 +1,3 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
 SRCS+=	pthread_md.c
diff --git a/lib/libthr/arch/powerpc/Makefile.inc b/lib/libthr/arch/powerpc/Makefile.inc
index e4dffef84cf..2ee224772e2 100644
--- a/lib/libthr/arch/powerpc/Makefile.inc
+++ b/lib/libthr/arch/powerpc/Makefile.inc
@@ -1,5 +1,3 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_CPUARCH}/${MACHINE_CPUARCH}
-
 SRCS+=	pthread_md.c
diff --git a/lib/libthr/arch/sparc64/Makefile.inc b/lib/libthr/arch/sparc64/Makefile.inc
index b6a4acd6f60..2ee224772e2 100644
--- a/lib/libthr/arch/sparc64/Makefile.inc
+++ b/lib/libthr/arch/sparc64/Makefile.inc
@@ -1,5 +1,3 @@
 # $FreeBSD$
 
-.PATH: ${.CURDIR}/arch/${MACHINE_ARCH}/${MACHINE_ARCH}
-
 SRCS+=	pthread_md.c
diff --git a/lib/libthr/support/Makefile.inc b/lib/libthr/support/Makefile.inc
index bcf4393a2f5..35a15f85926 100644
--- a/lib/libthr/support/Makefile.inc
+++ b/lib/libthr/support/Makefile.inc
@@ -1,9 +1,16 @@
 # $FreeBSD$
 
 .PATH: ${.CURDIR}/support ${.CURDIR}/../libc/gen ${.CURDIR}/../libc/string
-.PATH: ${.CURDIR}/../libc/${MACHINE_ARCH}/sys
 
+# libc must search machine_arch, then machine_cpuarch, but libthr has all its
+# code implemented in machine_cpuarch.  Cope.
+.if exists(${.CURDIR}/../libc/${MACHINE_ARCH}/sys)
+.PATH: ${.CURDIR}/../libc/${MACHINE_ARCH}/sys
 CFLAGS+= -I${.CURDIR}/../libc/${MACHINE_ARCH}
+.else
+.PATH: ${.CURDIR}/../libc/${MACHINE_CPUARCH}/sys
+CFLAGS+= -I${.CURDIR}/../libc/${MACHINE_CPUARCH}
+.endif
 
 SYSCALLS= thr_new
 

From c885004b9e847ea33dd646d54b1d951d1eeb6904 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 01:44:07 +0000
Subject: [PATCH 0674/1624] Include FreeBSD svn tag

---
 lib/libz/minigzip.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/lib/libz/minigzip.c b/lib/libz/minigzip.c
index 9825ccc3a71..f78176eb707 100644
--- a/lib/libz/minigzip.c
+++ b/lib/libz/minigzip.c
@@ -13,6 +13,8 @@
  * or in pipe mode.
  */
 
+#include 
+__FBSDID("$FreeBSD$");
 /* @(#) $Id$ */
 
 #include "zlib.h"

From 165721e3b142a1eb2f9a25624a5fc8e31f6485ea Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 01:44:56 +0000
Subject: [PATCH 0675/1624] MFtbemd: Move to using MACHINE_CPUARCH, now that it
 is safe.

---
 lib/msun/Makefile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/msun/Makefile b/lib/msun/Makefile
index 5a31f5cd918..1c5869e8483 100644
--- a/lib/msun/Makefile
+++ b/lib/msun/Makefile
@@ -12,12 +12,12 @@
 #
 #
 
-.if ${MACHINE_ARCH} == "i386"
+.if ${MACHINE_CPUARCH} == "i386"
 ARCH_SUBDIR= i387
 .elif ${MACHINE_ARCH} == "powerpc64"
 ARCH_SUBDIR= powerpc
 .else
-ARCH_SUBDIR= ${MACHINE_ARCH}
+ARCH_SUBDIR= ${MACHINE_CPUARCH}
 .endif
 
 .include "${ARCH_SUBDIR}/Makefile.inc"

From 5545f7f9b46d595476f7ec168cbcfa81d219ec5a Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 02:02:20 +0000
Subject: [PATCH 0676/1624] Use :T:Micc here like everywhere else we test icc

---
 sys/conf/kern.pre.mk | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/conf/kern.pre.mk b/sys/conf/kern.pre.mk
index d4bdc1f54b2..4dd8918d7da 100644
--- a/sys/conf/kern.pre.mk
+++ b/sys/conf/kern.pre.mk
@@ -42,7 +42,7 @@ COPTFLAGS+= -fno-strict-aliasing
 . endif
 .endif
 .if !defined(NO_CPU_COPTFLAGS)
-. if ${CC} == "icc"
+. if ${CC:T:Micc} == "icc"
 COPTFLAGS+= ${_ICC_CPUCFLAGS:C/(-x[^M^K^W]+)[MKW]+|-x[MKW]+/\1/}
 . else
 COPTFLAGS+= ${_CPUCFLAGS}

From 146fce53d858e49e5945a66a039b6b8f50ffb399 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 02:05:42 +0000
Subject: [PATCH 0677/1624] MFtbemd: use MACHINE_CPUARCH

---
 sys/modules/scc/Makefile         | 2 +-
 sys/modules/sound/sound/Makefile | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/modules/scc/Makefile b/sys/modules/scc/Makefile
index c1678b76f72..8a40e0b0007 100644
--- a/sys/modules/scc/Makefile
+++ b/sys/modules/scc/Makefile
@@ -5,7 +5,7 @@
 .if ${MACHINE} == "sparc64"
 scc_bfe= scc_bfe_ebus.c scc_bfe_sbus.c
 .endif
-.if ${MACHINE_ARCH} == "powerpc"
+.if ${MACHINE_CPUARCH} == "powerpc"
 scc_bfe= scc_bfe_macio.c scc_bfe_quicc.c
 .endif
 
diff --git a/sys/modules/sound/sound/Makefile b/sys/modules/sound/sound/Makefile
index 78f91d44553..42cfc24f011 100644
--- a/sys/modules/sound/sound/Makefile
+++ b/sys/modules/sound/sound/Makefile
@@ -44,7 +44,7 @@ CLEANFILES+=	feeder_eq_gen.h feeder_rate_gen.h snd_fxdiv_gen.h
 
 EXPORT_SYMS=	YES	# XXX evaluate
 
-.if ${MACHINE_ARCH} == "sparc64" || ${MACHINE_ARCH} == "powerpc"
+.if ${MACHINE_CPUARCH} == "sparc64" || ${MACHINE_CPUARCH} == "powerpc"
 # Create an empty opt_isa.h in order to keep kmod.mk from linking in an
 # existing one from KERNBUILDDIR which possibly has DEV_ISA defined so
 # sound.ko is always built without isadma support.

From 519b7ecc1b2ceecfc70bd75523816e740aa1c7ad Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 02:21:07 +0000
Subject: [PATCH 0678/1624] Merge from tbemd: use Makefile.arch to control
 building.

Reviewed by:	arch@ (many times, no objection)
---
 usr.sbin/Makefile         | 414 +++++++-----------------------
 usr.sbin/Makefile.amd64   |  30 +++
 usr.sbin/Makefile.arm     |   5 +
 usr.sbin/Makefile.i386    |  42 +++
 usr.sbin/Makefile.ia64    |   9 +
 usr.sbin/Makefile.mips    |   6 +
 usr.sbin/Makefile.orig    | 528 ++++++++++++++++++++++++++++++++++++++
 usr.sbin/Makefile.powerpc |   5 +
 usr.sbin/Makefile.sparc64 |   8 +
 9 files changed, 728 insertions(+), 319 deletions(-)
 create mode 100644 usr.sbin/Makefile.amd64
 create mode 100644 usr.sbin/Makefile.arm
 create mode 100644 usr.sbin/Makefile.i386
 create mode 100644 usr.sbin/Makefile.ia64
 create mode 100644 usr.sbin/Makefile.mips
 create mode 100644 usr.sbin/Makefile.orig
 create mode 100644 usr.sbin/Makefile.powerpc
 create mode 100644 usr.sbin/Makefile.sparc64

diff --git a/usr.sbin/Makefile b/usr.sbin/Makefile
index 3012da0fb37..eabe867defc 100644
--- a/usr.sbin/Makefile
+++ b/usr.sbin/Makefile
@@ -3,27 +3,9 @@
 
 .include 
 
-SUBDIR=	${_ac} \
-	${_accton} \
-	${_acpi} \
-	adduser \
-	${_amd} \
-	${_ancontrol} \
-	${_apm} \
-	${_apmd} \
+SUBDIR= adduser \
 	arp \
-	${_asf} \
-	${_atm} \
-	${_audit} \
-	${_auditd} \
-	${_auditreduce} \
-	${_authpf} \
-	${_bluetooth} \
-	${_boot0cfg} \
-	${_boot98cfg} \
 	bootparamd \
-	${_bsnmpd} \
-	${_btxld} \
 	burncd \
 	cdcontrol \
 	chkgrp \
@@ -31,153 +13,71 @@ SUBDIR=	${_ac} \
 	chroot \
 	ckdist \
 	clear_locks \
-	${_config} \
-	${_cpucontrol} \
 	crashinfo \
 	cron \
-	${_crunch} \
-	${_ctm} \
 	daemon \
 	dconschat \
 	devinfo \
 	digictl \
 	diskinfo \
-	${_dnssec-dsfromkey} \
-	${_dnssec-keyfromlabel} \
-	${_dnssec-keygen} \
-	${_dnssec-signzone} \
 	dumpcis \
-	${_editmap} \
-	${_edquota} \
-	${_eeprom} \
 	extattr \
 	extattrctl \
-	${_faithd} \
-	${_fdcontrol} \
-	${_fdformat} \
-	${_fdread} \
-	${_fdwrite} \
 	fifolog \
-	${_flowctl} \
-	${_freebsd-update} \
-	${_ftp-proxy} \
 	fwcontrol \
 	getfmac \
 	getpmac \
 	gstat \
-	${_gssd} \
 	i2c \
 	ifmcstat \
 	inetd \
 	iostat \
-	${_ip6addrctl} \
-	${_ipfwpcap} \
-	${_IPXrouted} \
-	${_jail} \
-	${_jexec} \
-	${_jls} \
-	${_kbdcontrol} \
-	${_kbdmap} \
-	${_keyserv} \
-	${_kgmon} \
-	${_kgzip} \
 	kldxref \
 	lastlogin \
-	${_lmcconfig} \
-	${_lpr} \
-	${_lptcontrol} \
-	${_mailstats} \
 	mailwrapper \
 	makefs \
-	${_makemap} \
-	${_manctl} \
+	manctl \
 	memcontrol \
 	mergemaster \
 	mfiutil \
 	mixer \
-	${_mld6query} \
 	mlxcontrol \
 	mountd \
-	${_mount_nwfs} \
 	mount_portalfs \
-	${_mount_smbfs} \
-	${_moused} \
-	${_mptable} \
 	mptutil \
 	mtest \
 	mtree \
-	${_named} \
-	${_named-checkconf} \
-	${_named-checkzone} \
-	${_named.reload} \
-	${_ndiscvt} \
-	${_ndp} \
 	newsyslog \
 	nfscbd \
 	nfsd \
 	nfsdumpstate \
 	nfsrevoke \
 	nfsuserd \
-	${_ngctl} \
-	${_nghook} \
 	nologin \
-	${_nscd} \
-	${_ntp} \
-	${_nvram} \
-	${_ofwdump} \
 	pc-sysinstall \
 	pciconf \
 	periodic \
-	${_pkg_install} \
-	${_pmcannotate} \
-	${_pmccontrol} \
-	${_pmcstat} \
-	${_pnpinfo} \
-	${_portsnap} \
 	powerd \
-	${_ppp} \
-	${_pppctl} \
-	${_praliases} \
-	${_praudit} \
 	procctl \
 	pstat \
 	pw \
 	pwd_mkdb \
 	quot \
-	${_quotaon} \
 	rarpd \
-	${_repquota} \
-	${_rip6query} \
 	rmt \
-	${_rndc} \
-	${_rndc-confgen} \
-	${_route6d} \
 	rpcbind \
 	rpc.lockd \
 	rpc.statd \
 	rpc.umntall \
-	${_rpc.yppasswdd} \
-	${_rpc.ypupdated} \
-	${_rpc.ypxfrd} \
-	${_rrenumd} \
-	${_rtadvd} \
 	rtprio \
-	${_rtsold} \
-	${_rwhod} \
-	${_sa} \
-	${_sade} \
-	${_sendmail} \
 	service \
 	services_mkdb \
 	setfib \
 	setfmac \
 	setpmac \
-	${_sicontrol} \
 	smbmsg \
 	snapinfo \
-	${_spkrtest} \
 	spray \
-	${_sysinstall} \
 	syslogd \
 	tcpdchk \
 	tcpdmatch \
@@ -185,344 +85,220 @@ SUBDIR=	${_ac} \
 	tcpdump \
 	timed \
 	traceroute \
-	${_traceroute6} \
 	trpt \
 	tzsetup \
-	${_uathload} \
 	ugidfw \
-	${_uhsoctl} \
-	${_usbdevs} \
-	${_usbconfig} \
-	${_vidcontrol} \
 	vipw \
 	wake \
 	watch \
 	watchdogd \
-	${_wlandebug} \
-	${_wlconfig} \
-	${_wpa} \
-	${_ypbind} \
-	${_yp_mkdb} \
-	${_yppoll} \
-	${_yppush} \
-	${_ypserv} \
-	${_ypset} \
-	zic \
-	${_zzz}
+	zic
 
 # NB: keep these sorted by MK_* knobs
 
 .if ${MK_ACCT} != "no"
-_ac=		ac
-_accton=	accton
-_sa=		sa
+SUBDIR+=	ac
+SUBDIR+=	accton
+SUBDIR+=	sa
 .endif
 
 .if ${MK_AMD} != "no"
-_amd=		amd
+SUBDIR+=	amd
 .endif
 
 .if ${MK_AUDIT} != "no"
-_audit=		audit
-_auditd=	auditd
-_auditreduce=	auditreduce
-_praudit=	praudit
+SUBDIR+=	audit
+SUBDIR+=	auditd
+SUBDIR+=	auditreduce
+SUBDIR+=	praudit
 .endif
 
 .if ${MK_AUTHPF} != "no"
-_authpf=	authpf
+SUBDIR+=	authpf
 .endif
 
 .if ${MK_BIND_DNSSEC} != "no" && ${MK_OPENSSL} != "no"
-_dnssec-dsfromkey=	dnssec-dsfromkey
-_dnssec-keyfromlabel=	dnssec-keyfromlabel
-_dnssec-keygen=		dnssec-keygen
-_dnssec-signzone=	dnssec-signzone
+SUBDIR+=	dnssec-dsfromkey
+SUBDIR+=	dnssec-keyfromlabel
+SUBDIR+=	dnssec-keygen
+SUBDIR+=	dnssec-signzone
 .endif
 .if ${MK_BIND_NAMED} != "no"
-_named=			named
-_named-checkconf=	named-checkconf
-_named-checkzone=	named-checkzone
-_named.reload=		named.reload
-_rndc=			rndc
-_rndc-confgen=		rndc-confgen
+SUBDIR+=	named
+SUBDIR+=	named-checkconf
+SUBDIR+=	named-checkzone
+SUBDIR+=	named.reload
+SUBDIR+=	rndc
+SUBDIR+=	rndc-confgen
 .endif
 
 .if ${MK_BLUETOOTH} != "no"
-_bluetooth=	bluetooth
+SUBDIR+=	bluetooth
 .endif
 
 .if ${MK_BSNMP} != "no"
-_bsnmpd=	bsnmpd
+SUBDIR+=	bsnmpd
 .endif
 
 .if ${MK_CTM} != "no"
-_ctm=		ctm
+SUBDIR+=	ctm
 .endif
 
 .if ${MK_FLOPPY} != "no"
-_fdcontrol=	fdcontrol
-_fdformat=	fdformat
-_fdread=	fdread
-_fdwrite=	fdwrite
+SUBDIR+=	fdcontrol
+SUBDIR+=	fdformat
+SUBDIR+=	fdread
+SUBDIR+=	fdwrite
 .endif
 
 .if ${MK_FREEBSD_UPDATE} != "no"
-_freebsd-update= freebsd-update
+SUBDIR+=	freebsd-update
 .endif
 
 .if ${MK_GSSAPI} != no
-_gssd=		gssd
+SUBDIR+=	gssd
 .endif
 
 .if ${MK_INET6} != "no"
-_faithd=	faithd
-_ip6addrctl=	ip6addrctl
-_mld6query=	mld6query
-_ndp=		ndp
-_rip6query=	rip6query
-_route6d=	route6d
-_rrenumd=	rrenumd
-_rtadvd=	rtadvd
-_rtsold=	rtsold
-_traceroute6=	traceroute6
+SUBDIR+=	faithd
+SUBDIR+=	ip6addrctl
+SUBDIR+=	mld6query
+SUBDIR+=	ndp
+SUBDIR+=	rip6query
+SUBDIR+=	route6d
+SUBDIR+=	rrenumd
+SUBDIR+=	rtadvd
+SUBDIR+=	rtsold
+SUBDIR+=	traceroute6
 .endif
 
 .if ${MK_IPFW} != "no"
-_ipfwpcap=	ipfwpcap
+SUBDIR+=	ipfwpcap
 .endif
 
 .if ${MK_IPX} != "no"
-_IPXrouted=	IPXrouted
+SUBDIR+=	IPXrouted
 .endif
 
 .if ${MK_JAIL} != "no"
-_jail=		jail
-_jexec=		jexec
-_jls=		jls
+SUBDIR+=	jail
+SUBDIR+=	jexec
+SUBDIR+=	jls
 .endif
 
 # XXX MK_SYSCONS
 .if ${MK_LEGACY_CONSOLE} != "no"
-_kbdcontrol=	kbdcontrol
-_kbdmap=	kbdmap
-_moused=	moused
-_vidcontrol=	vidcontrol
+SUBDIR+=	kbdcontrol
+SUBDIR+=	kbdmap
+SUBDIR+=	moused
+SUBDIR+=	vidcontrol
 .endif
 
 .if ${MK_LIBTHR} != "no" || ${MK_LIBPTHREAD} != "no"
 .if ${MK_PPP} != "no"
-_pppctl=	pppctl
+SUBDIR+=	pppctl
 .endif
 .if ${MK_NS_CACHING} != "no"
-_nscd=		nscd
+SUBDIR+=	nscd
 .endif
 .endif
 
 .if ${MK_LPR} != "no"
-_lpr=		lpr
+SUBDIR+=	lpr
 .endif
 
 .if ${MK_MAN_UTILS} != "no"
-_manctl=	manctl
+SUBDIR+=	manctl
 .endif
 
 .if ${MK_NETGRAPH} != "no"
-_flowctl=	flowctl
-_lmcconfig=	lmcconfig
-_ngctl=		ngctl
-_nghook=	nghook
+SUBDIR+=	flowctl
+SUBDIR+=	lmcconfig
+SUBDIR+=	ngctl
+SUBDIR+=	nghook
 .endif
 
 .if ${MK_NIS} != "no"
-_rpc.yppasswdd=	rpc.yppasswdd
-_rpc.ypupdated=	rpc.ypupdated
-_rpc.ypxfrd=	rpc.ypxfrd
-_ypbind=	ypbind
-_yp_mkdb=	yp_mkdb
-_yppoll=	yppoll
-_yppush=	yppush
-_ypserv=	ypserv
-_ypset=		ypset
+SUBDIR+=	rpc.yppasswdd
+SUBDIR+=	rpc.ypupdated
+SUBDIR+=	rpc.ypxfrd
+SUBDIR+=	ypbind
+SUBDIR+=	yp_mkdb
+SUBDIR+=	yppoll
+SUBDIR+=	yppush
+SUBDIR+=	ypserv
+SUBDIR+=	ypset
 .endif
 
 .if ${MK_NTP} != "no"
-_ntp=		ntp
+SUBDIR+=	ntp
 .endif
 
 .if ${MK_OPENSSL} != "no"
-_keyserv=	keyserv
+SUBDIR+=	keyserv
 .endif
 
 .if ${MK_PF} != "no"
-_ftp-proxy=	ftp-proxy
+SUBDIR+=	ftp-proxy
 .endif
 
 .if ${MK_PKGTOOLS} != "no"
-_pkg_install=	pkg_install
+SUBDIR+=	pkg_install
 .endif
 
 # XXX MK_TOOLCHAIN?
 .if ${MK_PMC} != "no"
-_pmcannotate=	pmcannotate
-_pmccontrol=	pmccontrol
-_pmcstat=	pmcstat
+SUBDIR+=	pmcannotate
+SUBDIR+=	pmccontrol
+SUBDIR+=	pmcstat
 .endif
 
 .if ${MK_PORTSNAP} != "no"
-_portsnap=	portsnap
+SUBDIR+=	portsnap
 .endif
 
 .if ${MK_PPP} != "no"
-_ppp=		ppp
-#_pppctl handled below
+SUBDIR+=	ppp
 .endif
 
 .if ${MK_QUOTAS} != "no"
-_edquota=	edquota
-_quotaon=	quotaon
-_repquota=	repquota
+SUBDIR+=	edquota
+SUBDIR+=	quotaon
+SUBDIR+=	repquota
 .endif
 
 .if ${MK_RCMDS} != "no"
-_rwhod=		rwhod
+SUBDIR+=	rwhod
 .endif
 
 .if ${MK_SENDMAIL} != "no"
-_editmap=	editmap
-_mailstats=	mailstats
-_makemap=	makemap
-_praliases=	praliases
-_sendmail=	sendmail
+SUBDIR+=	editmap
+SUBDIR+=	mailstats
+SUBDIR+=	makemap
+SUBDIR+=	praliases
+SUBDIR+=	sendmail
 .endif
 
-.if ${MK_SYSINSTALL} != "no"
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386" || \
-    ${MACHINE_ARCH} == "sparc64"
-_sade=		sade
-.endif
-.if ${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
-_sysinstall=	sysinstall
-.endif
-.endif
+SUBDIR+=	sysinstall
 
 .if ${MK_TOOLCHAIN} != "no"
-_config=	config
-_crunch=	crunch
+SUBDIR+=	config
+SUBDIR+=	crunch
 .endif
 
 .if ${MK_USB} != "no"
-.if ${MACHINE_ARCH} != "ia64" && \
-   !(${MACHINE_ARCH} == "mips" && defined(TARGET_ABI) && ${TARGET_ABI} == "n64")
-_uathload=	uathload
-.endif
-_uhsoctl=	uhsoctl
-#_usbdevs=	usbdevs
-_usbconfig=	usbconfig
+SUBDIR+=	uhsoctl
+SUBDIR+=	usbconfig
 .endif
 
 .if ${MK_WIRELESS} != "no"
-_ancontrol=	ancontrol
-_wlandebug=	wlandebug
-_wpa=		wpa
+SUBDIR+=	ancontrol
+SUBDIR+=	wlandebug
+SUBDIR+=	wpa
 .endif
 
-.if ${MACHINE_ARCH} == "arm"
-_kgmon=		kgmon
-.endif
+.include 
 
-.if ${MACHINE_ARCH} == "i386"
-.if ${MK_APM} != "no"
-_apm=		apm
-_apmd=		apmd
-.endif
-_asf=		asf
-.if ${MK_TOOLCHAIN} != "no"
-_btxld=		btxld
-.endif
-_cpucontrol=	cpucontrol
-_kgmon=		kgmon
-_kgzip=		kgzip
-_lptcontrol=	lptcontrol
-.if ${MK_NCP} != "no"
-_mount_nwfs=	mount_nwfs
-.endif
-_mount_smbfs=	mount_smbfs
-_mptable=	mptable
-.if ${MK_NDIS} != "no"
-_ndiscvt=	ndiscvt
-.endif
-_pnpinfo=	pnpinfo
-_sicontrol=	sicontrol
-_spkrtest=	spkrtest
-_zzz=		zzz
-.if ${MACHINE} == "i386"
-.if ${MK_ACPI} != "no"
-_acpi=		acpi
-.endif
-_boot0cfg=	boot0cfg
-.if ${MK_WIRELESS} != "no"
-_wlconfig=	wlconfig
-.endif
-.elif ${MACHINE} == "pc98"
-_boot98cfg=	boot98cfg
-.endif
-.endif
-
-# kgzip: builds, but missing support files
-# mptable: broken (not 64 bit clean)
-# pnpinfo: crashes (not really useful anyway)
-.if ${MACHINE_ARCH} == "amd64"
-.if ${MK_ACPI} != "no"
-_acpi=		acpi
-.endif
-.if ${MK_APM} != "no"
-_apm=		apm
-.endif
-_asf=		asf
-_boot0cfg=	boot0cfg
-.if ${MK_TOOLCHAIN} != "no"
-_btxld=		btxld
-.endif
-_cpucontrol=	cpucontrol
-_kgmon=		kgmon
-_lptcontrol=	lptcontrol
-.if ${MK_NCP} != "no"
-_mount_nwfs=	mount_nwfs
-.endif
-_mount_smbfs=	mount_smbfs
-_mptable=	mptable
-.if ${MK_NDIS} != "no"
-_ndiscvt=	ndiscvt
-.endif
-_sicontrol=	sicontrol
-_spkrtest=	spkrtest
-_zzz=		zzz
-.endif
-
-.if ${MACHINE_ARCH} == "arm"
-_ofwdump=	ofwdump
-.endif
-
-.if ${MACHINE_ARCH} == "ia64"
-.if ${MK_ACPI} != "no"
-_acpi=		acpi
-.endif
-_kgmon=		kgmon
-_mount_smbfs=	mount_smbfs
-_zzz=		zzz
-.endif
-
-.if ${MACHINE_CPUARCH} == "powerpc"
-_mount_smbfs=	mount_smbfs
-_nvram=		nvram
-_ofwdump=	ofwdump
-.endif
-
-.if ${MACHINE_ARCH} == "sparc64"
-_eeprom=	eeprom
-_mount_smbfs=	mount_smbfs
-_ofwdump=	ofwdump
-.endif
+SUBDIR:=	${SUBDIR:O}
 
 .include 
diff --git a/usr.sbin/Makefile.amd64 b/usr.sbin/Makefile.amd64
new file mode 100644
index 00000000000..61f94c4bf25
--- /dev/null
+++ b/usr.sbin/Makefile.amd64
@@ -0,0 +1,30 @@
+# $FreeBSD$
+
+# kgzip: builds, but missing support files
+# mptable: broken (not 64 bit clean)
+# pnpinfo: crashes (not really useful anyway)
+.if ${MK_ACPI} != "no"
+SUBDIR+=	acpi
+.endif
+.if ${MK_APM} != "no"
+SUBDIR+=	apm
+.endif
+SUBDIR+=	asf
+SUBDIR+=	boot0cfg
+.if ${MK_TOOLCHAIN} != "no"
+SUBDIR+=	btxld
+.endif
+SUBDIR+=	cpucontrol
+SUBDIR+=	kgmon
+SUBDIR+=	lptcontrol
+.if ${MK_NCP} != "no"
+SUBDIR+=	mount_nwfs
+.endif
+SUBDIR+=	mount_smbfs
+SUBDIR+=	mptable
+.if ${MK_NDIS} != "no"
+SUBDIR+=	ndiscvt
+.endif
+SUBDIR+=	sicontrol
+SUBDIR+=	spkrtest
+SUBDIR+=	zzz
diff --git a/usr.sbin/Makefile.arm b/usr.sbin/Makefile.arm
new file mode 100644
index 00000000000..f19c7175cd5
--- /dev/null
+++ b/usr.sbin/Makefile.arm
@@ -0,0 +1,5 @@
+# $FreeBSD$
+
+SUBDIR+=	ofwdump
+SUBDIR+=	kgmon
+SUBDIR:=	${SUBDIR:Nsysinstall}
diff --git a/usr.sbin/Makefile.i386 b/usr.sbin/Makefile.i386
new file mode 100644
index 00000000000..f7870dc714b
--- /dev/null
+++ b/usr.sbin/Makefile.i386
@@ -0,0 +1,42 @@
+# $FreeBSD$
+
+.if ${MK_APM} != "no"
+SUBDIR+=	apm
+SUBDIR+=	apmd
+.endif
+SUBDIR+=	asf
+.if ${MK_TOOLCHAIN} != "no"
+SUBDIR+=	btxld
+.endif
+SUBDIR+=	cpucontrol
+SUBDIR+=	kgmon
+SUBDIR+=	kgzip
+SUBDIR+=	lptcontrol
+.if ${MK_NCP} != "no"
+SUBDIR+=	mount_nwfs
+.endif
+SUBDIR+=	mount_smbfs
+SUBDIR+=	mptable
+.if ${MK_NDIS} != "no"
+SUBDIR+=	ndiscvt
+.endif
+SUBDIR+=	pnpinfo
+.if ${MK_SYSINSTALL} != "no"
+SUBDIR+=	sade
+.endif
+SUBDIR+=	sicontrol
+SUBDIR+=	spkrtest
+SUBDIR+=	zzz
+
+# Differentiate between FreeBSD/i386 and FreeBSD/pc98
+.if ${MACHINE} == "i386"
+.if ${MK_ACPI} != "no"
+SUBDIR+=	acpi
+.endif
+SUBDIR+=	boot0cfg
+.if ${MK_WIRELESS} != "no"
+SUBDIR+=	wlconfig
+.endif
+.elif ${MACHINE} == "pc98"
+SUBDIR+=	boot98cfg
+.endif
diff --git a/usr.sbin/Makefile.ia64 b/usr.sbin/Makefile.ia64
new file mode 100644
index 00000000000..0a897b40b31
--- /dev/null
+++ b/usr.sbin/Makefile.ia64
@@ -0,0 +1,9 @@
+# $FreeBSD$
+
+.if ${MK_ACPI} != "no"
+SUBDIR+=	acpi
+.endif
+SUBDIR+=	kgmon
+SUBDIR+=	mount_smbfs
+SUBDIR:=	${SUBDIR:Nuathload}
+SUBDIR+=	zzz
diff --git a/usr.sbin/Makefile.mips b/usr.sbin/Makefile.mips
new file mode 100644
index 00000000000..4d30e12d70a
--- /dev/null
+++ b/usr.sbin/Makefile.mips
@@ -0,0 +1,6 @@
+# $FreeBSD$
+
+SUBDIR:=	${SUBDIR:Nsysinstall}
+.if defined(TARGET_ABI) && ${TARGET_ABI} == "n64"
+SUBDIR:=	${SUBDIR:Nuathload}
+.endif
diff --git a/usr.sbin/Makefile.orig b/usr.sbin/Makefile.orig
new file mode 100644
index 00000000000..3012da0fb37
--- /dev/null
+++ b/usr.sbin/Makefile.orig
@@ -0,0 +1,528 @@
+#	From: @(#)Makefile	5.20 (Berkeley) 6/12/93
+# $FreeBSD$
+
+.include 
+
+SUBDIR=	${_ac} \
+	${_accton} \
+	${_acpi} \
+	adduser \
+	${_amd} \
+	${_ancontrol} \
+	${_apm} \
+	${_apmd} \
+	arp \
+	${_asf} \
+	${_atm} \
+	${_audit} \
+	${_auditd} \
+	${_auditreduce} \
+	${_authpf} \
+	${_bluetooth} \
+	${_boot0cfg} \
+	${_boot98cfg} \
+	bootparamd \
+	${_bsnmpd} \
+	${_btxld} \
+	burncd \
+	cdcontrol \
+	chkgrp \
+	chown \
+	chroot \
+	ckdist \
+	clear_locks \
+	${_config} \
+	${_cpucontrol} \
+	crashinfo \
+	cron \
+	${_crunch} \
+	${_ctm} \
+	daemon \
+	dconschat \
+	devinfo \
+	digictl \
+	diskinfo \
+	${_dnssec-dsfromkey} \
+	${_dnssec-keyfromlabel} \
+	${_dnssec-keygen} \
+	${_dnssec-signzone} \
+	dumpcis \
+	${_editmap} \
+	${_edquota} \
+	${_eeprom} \
+	extattr \
+	extattrctl \
+	${_faithd} \
+	${_fdcontrol} \
+	${_fdformat} \
+	${_fdread} \
+	${_fdwrite} \
+	fifolog \
+	${_flowctl} \
+	${_freebsd-update} \
+	${_ftp-proxy} \
+	fwcontrol \
+	getfmac \
+	getpmac \
+	gstat \
+	${_gssd} \
+	i2c \
+	ifmcstat \
+	inetd \
+	iostat \
+	${_ip6addrctl} \
+	${_ipfwpcap} \
+	${_IPXrouted} \
+	${_jail} \
+	${_jexec} \
+	${_jls} \
+	${_kbdcontrol} \
+	${_kbdmap} \
+	${_keyserv} \
+	${_kgmon} \
+	${_kgzip} \
+	kldxref \
+	lastlogin \
+	${_lmcconfig} \
+	${_lpr} \
+	${_lptcontrol} \
+	${_mailstats} \
+	mailwrapper \
+	makefs \
+	${_makemap} \
+	${_manctl} \
+	memcontrol \
+	mergemaster \
+	mfiutil \
+	mixer \
+	${_mld6query} \
+	mlxcontrol \
+	mountd \
+	${_mount_nwfs} \
+	mount_portalfs \
+	${_mount_smbfs} \
+	${_moused} \
+	${_mptable} \
+	mptutil \
+	mtest \
+	mtree \
+	${_named} \
+	${_named-checkconf} \
+	${_named-checkzone} \
+	${_named.reload} \
+	${_ndiscvt} \
+	${_ndp} \
+	newsyslog \
+	nfscbd \
+	nfsd \
+	nfsdumpstate \
+	nfsrevoke \
+	nfsuserd \
+	${_ngctl} \
+	${_nghook} \
+	nologin \
+	${_nscd} \
+	${_ntp} \
+	${_nvram} \
+	${_ofwdump} \
+	pc-sysinstall \
+	pciconf \
+	periodic \
+	${_pkg_install} \
+	${_pmcannotate} \
+	${_pmccontrol} \
+	${_pmcstat} \
+	${_pnpinfo} \
+	${_portsnap} \
+	powerd \
+	${_ppp} \
+	${_pppctl} \
+	${_praliases} \
+	${_praudit} \
+	procctl \
+	pstat \
+	pw \
+	pwd_mkdb \
+	quot \
+	${_quotaon} \
+	rarpd \
+	${_repquota} \
+	${_rip6query} \
+	rmt \
+	${_rndc} \
+	${_rndc-confgen} \
+	${_route6d} \
+	rpcbind \
+	rpc.lockd \
+	rpc.statd \
+	rpc.umntall \
+	${_rpc.yppasswdd} \
+	${_rpc.ypupdated} \
+	${_rpc.ypxfrd} \
+	${_rrenumd} \
+	${_rtadvd} \
+	rtprio \
+	${_rtsold} \
+	${_rwhod} \
+	${_sa} \
+	${_sade} \
+	${_sendmail} \
+	service \
+	services_mkdb \
+	setfib \
+	setfmac \
+	setpmac \
+	${_sicontrol} \
+	smbmsg \
+	snapinfo \
+	${_spkrtest} \
+	spray \
+	${_sysinstall} \
+	syslogd \
+	tcpdchk \
+	tcpdmatch \
+	tcpdrop \
+	tcpdump \
+	timed \
+	traceroute \
+	${_traceroute6} \
+	trpt \
+	tzsetup \
+	${_uathload} \
+	ugidfw \
+	${_uhsoctl} \
+	${_usbdevs} \
+	${_usbconfig} \
+	${_vidcontrol} \
+	vipw \
+	wake \
+	watch \
+	watchdogd \
+	${_wlandebug} \
+	${_wlconfig} \
+	${_wpa} \
+	${_ypbind} \
+	${_yp_mkdb} \
+	${_yppoll} \
+	${_yppush} \
+	${_ypserv} \
+	${_ypset} \
+	zic \
+	${_zzz}
+
+# NB: keep these sorted by MK_* knobs
+
+.if ${MK_ACCT} != "no"
+_ac=		ac
+_accton=	accton
+_sa=		sa
+.endif
+
+.if ${MK_AMD} != "no"
+_amd=		amd
+.endif
+
+.if ${MK_AUDIT} != "no"
+_audit=		audit
+_auditd=	auditd
+_auditreduce=	auditreduce
+_praudit=	praudit
+.endif
+
+.if ${MK_AUTHPF} != "no"
+_authpf=	authpf
+.endif
+
+.if ${MK_BIND_DNSSEC} != "no" && ${MK_OPENSSL} != "no"
+_dnssec-dsfromkey=	dnssec-dsfromkey
+_dnssec-keyfromlabel=	dnssec-keyfromlabel
+_dnssec-keygen=		dnssec-keygen
+_dnssec-signzone=	dnssec-signzone
+.endif
+.if ${MK_BIND_NAMED} != "no"
+_named=			named
+_named-checkconf=	named-checkconf
+_named-checkzone=	named-checkzone
+_named.reload=		named.reload
+_rndc=			rndc
+_rndc-confgen=		rndc-confgen
+.endif
+
+.if ${MK_BLUETOOTH} != "no"
+_bluetooth=	bluetooth
+.endif
+
+.if ${MK_BSNMP} != "no"
+_bsnmpd=	bsnmpd
+.endif
+
+.if ${MK_CTM} != "no"
+_ctm=		ctm
+.endif
+
+.if ${MK_FLOPPY} != "no"
+_fdcontrol=	fdcontrol
+_fdformat=	fdformat
+_fdread=	fdread
+_fdwrite=	fdwrite
+.endif
+
+.if ${MK_FREEBSD_UPDATE} != "no"
+_freebsd-update= freebsd-update
+.endif
+
+.if ${MK_GSSAPI} != no
+_gssd=		gssd
+.endif
+
+.if ${MK_INET6} != "no"
+_faithd=	faithd
+_ip6addrctl=	ip6addrctl
+_mld6query=	mld6query
+_ndp=		ndp
+_rip6query=	rip6query
+_route6d=	route6d
+_rrenumd=	rrenumd
+_rtadvd=	rtadvd
+_rtsold=	rtsold
+_traceroute6=	traceroute6
+.endif
+
+.if ${MK_IPFW} != "no"
+_ipfwpcap=	ipfwpcap
+.endif
+
+.if ${MK_IPX} != "no"
+_IPXrouted=	IPXrouted
+.endif
+
+.if ${MK_JAIL} != "no"
+_jail=		jail
+_jexec=		jexec
+_jls=		jls
+.endif
+
+# XXX MK_SYSCONS
+.if ${MK_LEGACY_CONSOLE} != "no"
+_kbdcontrol=	kbdcontrol
+_kbdmap=	kbdmap
+_moused=	moused
+_vidcontrol=	vidcontrol
+.endif
+
+.if ${MK_LIBTHR} != "no" || ${MK_LIBPTHREAD} != "no"
+.if ${MK_PPP} != "no"
+_pppctl=	pppctl
+.endif
+.if ${MK_NS_CACHING} != "no"
+_nscd=		nscd
+.endif
+.endif
+
+.if ${MK_LPR} != "no"
+_lpr=		lpr
+.endif
+
+.if ${MK_MAN_UTILS} != "no"
+_manctl=	manctl
+.endif
+
+.if ${MK_NETGRAPH} != "no"
+_flowctl=	flowctl
+_lmcconfig=	lmcconfig
+_ngctl=		ngctl
+_nghook=	nghook
+.endif
+
+.if ${MK_NIS} != "no"
+_rpc.yppasswdd=	rpc.yppasswdd
+_rpc.ypupdated=	rpc.ypupdated
+_rpc.ypxfrd=	rpc.ypxfrd
+_ypbind=	ypbind
+_yp_mkdb=	yp_mkdb
+_yppoll=	yppoll
+_yppush=	yppush
+_ypserv=	ypserv
+_ypset=		ypset
+.endif
+
+.if ${MK_NTP} != "no"
+_ntp=		ntp
+.endif
+
+.if ${MK_OPENSSL} != "no"
+_keyserv=	keyserv
+.endif
+
+.if ${MK_PF} != "no"
+_ftp-proxy=	ftp-proxy
+.endif
+
+.if ${MK_PKGTOOLS} != "no"
+_pkg_install=	pkg_install
+.endif
+
+# XXX MK_TOOLCHAIN?
+.if ${MK_PMC} != "no"
+_pmcannotate=	pmcannotate
+_pmccontrol=	pmccontrol
+_pmcstat=	pmcstat
+.endif
+
+.if ${MK_PORTSNAP} != "no"
+_portsnap=	portsnap
+.endif
+
+.if ${MK_PPP} != "no"
+_ppp=		ppp
+#_pppctl handled below
+.endif
+
+.if ${MK_QUOTAS} != "no"
+_edquota=	edquota
+_quotaon=	quotaon
+_repquota=	repquota
+.endif
+
+.if ${MK_RCMDS} != "no"
+_rwhod=		rwhod
+.endif
+
+.if ${MK_SENDMAIL} != "no"
+_editmap=	editmap
+_mailstats=	mailstats
+_makemap=	makemap
+_praliases=	praliases
+_sendmail=	sendmail
+.endif
+
+.if ${MK_SYSINSTALL} != "no"
+.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386" || \
+    ${MACHINE_ARCH} == "sparc64"
+_sade=		sade
+.endif
+.if ${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
+_sysinstall=	sysinstall
+.endif
+.endif
+
+.if ${MK_TOOLCHAIN} != "no"
+_config=	config
+_crunch=	crunch
+.endif
+
+.if ${MK_USB} != "no"
+.if ${MACHINE_ARCH} != "ia64" && \
+   !(${MACHINE_ARCH} == "mips" && defined(TARGET_ABI) && ${TARGET_ABI} == "n64")
+_uathload=	uathload
+.endif
+_uhsoctl=	uhsoctl
+#_usbdevs=	usbdevs
+_usbconfig=	usbconfig
+.endif
+
+.if ${MK_WIRELESS} != "no"
+_ancontrol=	ancontrol
+_wlandebug=	wlandebug
+_wpa=		wpa
+.endif
+
+.if ${MACHINE_ARCH} == "arm"
+_kgmon=		kgmon
+.endif
+
+.if ${MACHINE_ARCH} == "i386"
+.if ${MK_APM} != "no"
+_apm=		apm
+_apmd=		apmd
+.endif
+_asf=		asf
+.if ${MK_TOOLCHAIN} != "no"
+_btxld=		btxld
+.endif
+_cpucontrol=	cpucontrol
+_kgmon=		kgmon
+_kgzip=		kgzip
+_lptcontrol=	lptcontrol
+.if ${MK_NCP} != "no"
+_mount_nwfs=	mount_nwfs
+.endif
+_mount_smbfs=	mount_smbfs
+_mptable=	mptable
+.if ${MK_NDIS} != "no"
+_ndiscvt=	ndiscvt
+.endif
+_pnpinfo=	pnpinfo
+_sicontrol=	sicontrol
+_spkrtest=	spkrtest
+_zzz=		zzz
+.if ${MACHINE} == "i386"
+.if ${MK_ACPI} != "no"
+_acpi=		acpi
+.endif
+_boot0cfg=	boot0cfg
+.if ${MK_WIRELESS} != "no"
+_wlconfig=	wlconfig
+.endif
+.elif ${MACHINE} == "pc98"
+_boot98cfg=	boot98cfg
+.endif
+.endif
+
+# kgzip: builds, but missing support files
+# mptable: broken (not 64 bit clean)
+# pnpinfo: crashes (not really useful anyway)
+.if ${MACHINE_ARCH} == "amd64"
+.if ${MK_ACPI} != "no"
+_acpi=		acpi
+.endif
+.if ${MK_APM} != "no"
+_apm=		apm
+.endif
+_asf=		asf
+_boot0cfg=	boot0cfg
+.if ${MK_TOOLCHAIN} != "no"
+_btxld=		btxld
+.endif
+_cpucontrol=	cpucontrol
+_kgmon=		kgmon
+_lptcontrol=	lptcontrol
+.if ${MK_NCP} != "no"
+_mount_nwfs=	mount_nwfs
+.endif
+_mount_smbfs=	mount_smbfs
+_mptable=	mptable
+.if ${MK_NDIS} != "no"
+_ndiscvt=	ndiscvt
+.endif
+_sicontrol=	sicontrol
+_spkrtest=	spkrtest
+_zzz=		zzz
+.endif
+
+.if ${MACHINE_ARCH} == "arm"
+_ofwdump=	ofwdump
+.endif
+
+.if ${MACHINE_ARCH} == "ia64"
+.if ${MK_ACPI} != "no"
+_acpi=		acpi
+.endif
+_kgmon=		kgmon
+_mount_smbfs=	mount_smbfs
+_zzz=		zzz
+.endif
+
+.if ${MACHINE_CPUARCH} == "powerpc"
+_mount_smbfs=	mount_smbfs
+_nvram=		nvram
+_ofwdump=	ofwdump
+.endif
+
+.if ${MACHINE_ARCH} == "sparc64"
+_eeprom=	eeprom
+_mount_smbfs=	mount_smbfs
+_ofwdump=	ofwdump
+.endif
+
+.include 
diff --git a/usr.sbin/Makefile.powerpc b/usr.sbin/Makefile.powerpc
new file mode 100644
index 00000000000..8833a2741e1
--- /dev/null
+++ b/usr.sbin/Makefile.powerpc
@@ -0,0 +1,5 @@
+# $FreeBSD$
+
+SUBDIR+=	mount_smbfs
+SUBDIR+=	nvram
+SUBDIR+=	ofwdump
diff --git a/usr.sbin/Makefile.sparc64 b/usr.sbin/Makefile.sparc64
new file mode 100644
index 00000000000..320226d0599
--- /dev/null
+++ b/usr.sbin/Makefile.sparc64
@@ -0,0 +1,8 @@
+# $FreeBSD$
+
+SUBDIR+=	eeprom
+SUBDIR+=	mount_smbfs
+SUBDIR+=	ofwdump
+.if ${MK_SYSINSTALL} != "no"
+SUBDIR+=	sade
+.endif

From 22e2f727d0cef7394177c6ecab32de674c1d3404 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 02:23:03 +0000
Subject: [PATCH 0679/1624] Merge from tbemd: Move to using Makefile.arch to
 control what's build.

Reviewed by:	(arch@, no objection)
---
 usr.bin/Makefile.amd64   | 7 +++++++
 usr.bin/Makefile.arm     | 3 +++
 usr.bin/Makefile.i386    | 7 +++++++
 usr.bin/Makefile.ia64    | 3 +++
 usr.bin/Makefile.powerpc | 3 +++
 usr.bin/Makefile.sparc64 | 3 +++
 6 files changed, 26 insertions(+)
 create mode 100644 usr.bin/Makefile.amd64
 create mode 100644 usr.bin/Makefile.arm
 create mode 100644 usr.bin/Makefile.i386
 create mode 100644 usr.bin/Makefile.ia64
 create mode 100644 usr.bin/Makefile.powerpc
 create mode 100644 usr.bin/Makefile.sparc64

diff --git a/usr.bin/Makefile.amd64 b/usr.bin/Makefile.amd64
new file mode 100644
index 00000000000..2eba205a7a5
--- /dev/null
+++ b/usr.bin/Makefile.amd64
@@ -0,0 +1,7 @@
+# $FreeBSD$
+
+.if ${MK_NCP} != "no"
+SUBDIR+=	ncplist
+SUBDIR+=	ncplogin
+.endif
+SUBDIR+=	smbutil
diff --git a/usr.bin/Makefile.arm b/usr.bin/Makefile.arm
new file mode 100644
index 00000000000..3c4e7a5fbbe
--- /dev/null
+++ b/usr.bin/Makefile.arm
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR:=	${SUBDIR:Ntruss}
diff --git a/usr.bin/Makefile.i386 b/usr.bin/Makefile.i386
new file mode 100644
index 00000000000..2eba205a7a5
--- /dev/null
+++ b/usr.bin/Makefile.i386
@@ -0,0 +1,7 @@
+# $FreeBSD$
+
+.if ${MK_NCP} != "no"
+SUBDIR+=	ncplist
+SUBDIR+=	ncplogin
+.endif
+SUBDIR+=	smbutil
diff --git a/usr.bin/Makefile.ia64 b/usr.bin/Makefile.ia64
new file mode 100644
index 00000000000..fee2fb07681
--- /dev/null
+++ b/usr.bin/Makefile.ia64
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR+=	smbutil
diff --git a/usr.bin/Makefile.powerpc b/usr.bin/Makefile.powerpc
new file mode 100644
index 00000000000..fee2fb07681
--- /dev/null
+++ b/usr.bin/Makefile.powerpc
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR+=	smbutil
diff --git a/usr.bin/Makefile.sparc64 b/usr.bin/Makefile.sparc64
new file mode 100644
index 00000000000..fee2fb07681
--- /dev/null
+++ b/usr.bin/Makefile.sparc64
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR+=	smbutil

From 130ecf684fe7de319b897e5af4b352edb1e19157 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 02:25:21 +0000
Subject: [PATCH 0680/1624] MF tbemd: Move to using Makefile.arch to select
 what to build.

Reviewed by:	arch@ (no objection)
---
 sbin/Makefile         | 70 +++++++++----------------------------------
 sbin/Makefile.amd64   |  4 +++
 sbin/Makefile.arm     |  4 +++
 sbin/Makefile.i386    |  5 ++++
 sbin/Makefile.ia64    |  3 ++
 sbin/Makefile.mips    |  4 +++
 sbin/Makefile.pc98    |  5 ++++
 sbin/Makefile.sparc64 |  4 +++
 8 files changed, 43 insertions(+), 56 deletions(-)
 create mode 100644 sbin/Makefile.amd64
 create mode 100644 sbin/Makefile.arm
 create mode 100644 sbin/Makefile.i386
 create mode 100644 sbin/Makefile.ia64
 create mode 100644 sbin/Makefile.mips
 create mode 100644 sbin/Makefile.pc98
 create mode 100644 sbin/Makefile.sparc64

diff --git a/sbin/Makefile b/sbin/Makefile
index 72f4bff7782..0623574c1d6 100644
--- a/sbin/Makefile
+++ b/sbin/Makefile
@@ -5,26 +5,21 @@
 
 # XXX MISSING:		icheck ncheck
 
-SUBDIR=	adjkerntz \
+SUBDIR=adjkerntz \
 	atacontrol \
-	${_atm} \
 	badsect \
-	${_bsdlabel} \
 	camcontrol \
 	ccdconfig \
 	clri \
 	comcontrol \
 	conscontrol \
 	ddb \
-	${_devd} \
 	devfs \
 	dhclient \
 	dmesg \
 	dump \
 	dumpfs \
 	dumpon \
-	${_fdisk} \
-	${_fdisk_pc98} \
 	ffsinfo \
 	fsck \
 	fsck_ffs \
@@ -40,15 +35,12 @@ SUBDIR=	adjkerntz \
 	hastd \
 	ifconfig \
 	init \
-	${_ipf} \
-	${_ipfw} \
 	iscontrol \
 	kldconfig \
 	kldload \
 	kldstat \
 	kldunload \
 	ldconfig \
-	${_mca} \
 	md5 \
 	mdconfig \
 	mdmfs \
@@ -62,96 +54,62 @@ SUBDIR=	adjkerntz \
 	mount_nullfs \
 	mount_udf \
 	mount_unionfs \
-	${_natd} \
 	newfs \
 	newfs_msdos \
 	nfsiod \
 	nos-tun \
-	${_pfctl} \
-	${_pflogd} \
 	ping \
-	${_ping6} \
-	${_quotacheck} \
 	rcorder \
 	reboot \
 	recoverdisk \
 	restore \
 	route \
-	${_routed} \
-	${_rtsol} \
 	savecore \
-	${_sconfig} \
 	setkey \
 	shutdown \
 	spppcontrol \
-	${_sunlabel} \
 	swapon \
 	sysctl \
 	tunefs \
 	umount \
 
 .if ${MK_ATM} != "no"
-_atm=		atm
+SUBDIR+=	atm
 .endif
 
 .if ${MK_CXX} != "no"
-_devd=		devd
+SUBDIR+=	devd
 .endif
 
 .if ${MK_IPFILTER} != "no"
-_ipf=		ipf
+SUBDIR+=	ipf
 .endif
 
 .if ${MK_IPFW} != "no"
-_ipfw=		ipfw
-_natd=		natd
+SUBDIR+=	ipfw
+SUBDIR+=	natd
 .endif
 
 .if ${MK_PF} != "no"
-_pfctl=		pfctl
-_pflogd=	pflogd
+SUBDIR+=	pfctl
+SUBDIR+=	pflogd
 .endif
 
 .if ${MK_INET6} != "no"
-_ping6=		ping6
-_rtsol=		rtsol
-.endif
-
-.if ${MACHINE_ARCH} != "ia64" && ${MACHINE_ARCH} != "powerpc"
-_bsdlabel=	bsdlabel
+SUBDIR+=	ping6
+SUBDIR+=	rtsol
 .endif
 
 .if ${MK_QUOTAS} != "no"
-_quotacheck=	quotacheck
+SUBDIR+=	quotacheck
 .endif
 
 .if ${MK_ROUTED} != "no"
-_routed=	routed
+SUBDIR+=	routed
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
-.if ${MACHINE} == "i386"
-_fdisk=		fdisk
-.elif ${MACHINE} == "pc98"
-_fdisk_pc98=	fdisk_pc98
-.endif
-_sconfig=	sconfig
-.endif
+.include 
 
-.if ${MACHINE_ARCH} == "amd64"
-_fdisk=		fdisk
-.endif
-
-.if ${MACHINE_ARCH} == "arm"
-_fdisk=		fdisk
-.endif
-
-.if ${MACHINE_ARCH} == "ia64"
-_mca=		mca
-.endif
-
-.if ${MACHINE_ARCH} == "sparc64"
-_sunlabel=	sunlabel
-.endif
+SUBDIR:=	${SUBDIR:O}
 
 .include 
diff --git a/sbin/Makefile.amd64 b/sbin/Makefile.amd64
new file mode 100644
index 00000000000..2d231b0cb2b
--- /dev/null
+++ b/sbin/Makefile.amd64
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR += bsdlabel
+SUBDIR += fdisk
diff --git a/sbin/Makefile.arm b/sbin/Makefile.arm
new file mode 100644
index 00000000000..2d231b0cb2b
--- /dev/null
+++ b/sbin/Makefile.arm
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR += bsdlabel
+SUBDIR += fdisk
diff --git a/sbin/Makefile.i386 b/sbin/Makefile.i386
new file mode 100644
index 00000000000..4135c44082c
--- /dev/null
+++ b/sbin/Makefile.i386
@@ -0,0 +1,5 @@
+# $FreeBSD$
+
+SUBDIR += bsdlabel
+SUBDIR += fdisk
+SUBDIR += sconfig
diff --git a/sbin/Makefile.ia64 b/sbin/Makefile.ia64
new file mode 100644
index 00000000000..c1e6a417ac8
--- /dev/null
+++ b/sbin/Makefile.ia64
@@ -0,0 +1,3 @@
+# $FreeBSD$
+
+SUBDIR += mca
diff --git a/sbin/Makefile.mips b/sbin/Makefile.mips
new file mode 100644
index 00000000000..2d231b0cb2b
--- /dev/null
+++ b/sbin/Makefile.mips
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR += bsdlabel
+SUBDIR += fdisk
diff --git a/sbin/Makefile.pc98 b/sbin/Makefile.pc98
new file mode 100644
index 00000000000..4aab559ad6d
--- /dev/null
+++ b/sbin/Makefile.pc98
@@ -0,0 +1,5 @@
+# $FreeBSD$
+
+SUBDIR += bsdlabel
+SUBDIR += fdisk_pc98
+SUBDIR += sconfig
diff --git a/sbin/Makefile.sparc64 b/sbin/Makefile.sparc64
new file mode 100644
index 00000000000..9a5bbe63bf1
--- /dev/null
+++ b/sbin/Makefile.sparc64
@@ -0,0 +1,4 @@
+# $FreeBSD$
+
+SUBDIR += bsdlabel
+SUBDIR += sunlabel

From 4a9a1e43a5fe25115bd7df195ae95932dac6fa29 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 02:26:36 +0000
Subject: [PATCH 0681/1624] Ooops!  Shouldn't have committed this

---
 usr.sbin/Makefile.orig | 528 -----------------------------------------
 1 file changed, 528 deletions(-)
 delete mode 100644 usr.sbin/Makefile.orig

diff --git a/usr.sbin/Makefile.orig b/usr.sbin/Makefile.orig
deleted file mode 100644
index 3012da0fb37..00000000000
--- a/usr.sbin/Makefile.orig
+++ /dev/null
@@ -1,528 +0,0 @@
-#	From: @(#)Makefile	5.20 (Berkeley) 6/12/93
-# $FreeBSD$
-
-.include 
-
-SUBDIR=	${_ac} \
-	${_accton} \
-	${_acpi} \
-	adduser \
-	${_amd} \
-	${_ancontrol} \
-	${_apm} \
-	${_apmd} \
-	arp \
-	${_asf} \
-	${_atm} \
-	${_audit} \
-	${_auditd} \
-	${_auditreduce} \
-	${_authpf} \
-	${_bluetooth} \
-	${_boot0cfg} \
-	${_boot98cfg} \
-	bootparamd \
-	${_bsnmpd} \
-	${_btxld} \
-	burncd \
-	cdcontrol \
-	chkgrp \
-	chown \
-	chroot \
-	ckdist \
-	clear_locks \
-	${_config} \
-	${_cpucontrol} \
-	crashinfo \
-	cron \
-	${_crunch} \
-	${_ctm} \
-	daemon \
-	dconschat \
-	devinfo \
-	digictl \
-	diskinfo \
-	${_dnssec-dsfromkey} \
-	${_dnssec-keyfromlabel} \
-	${_dnssec-keygen} \
-	${_dnssec-signzone} \
-	dumpcis \
-	${_editmap} \
-	${_edquota} \
-	${_eeprom} \
-	extattr \
-	extattrctl \
-	${_faithd} \
-	${_fdcontrol} \
-	${_fdformat} \
-	${_fdread} \
-	${_fdwrite} \
-	fifolog \
-	${_flowctl} \
-	${_freebsd-update} \
-	${_ftp-proxy} \
-	fwcontrol \
-	getfmac \
-	getpmac \
-	gstat \
-	${_gssd} \
-	i2c \
-	ifmcstat \
-	inetd \
-	iostat \
-	${_ip6addrctl} \
-	${_ipfwpcap} \
-	${_IPXrouted} \
-	${_jail} \
-	${_jexec} \
-	${_jls} \
-	${_kbdcontrol} \
-	${_kbdmap} \
-	${_keyserv} \
-	${_kgmon} \
-	${_kgzip} \
-	kldxref \
-	lastlogin \
-	${_lmcconfig} \
-	${_lpr} \
-	${_lptcontrol} \
-	${_mailstats} \
-	mailwrapper \
-	makefs \
-	${_makemap} \
-	${_manctl} \
-	memcontrol \
-	mergemaster \
-	mfiutil \
-	mixer \
-	${_mld6query} \
-	mlxcontrol \
-	mountd \
-	${_mount_nwfs} \
-	mount_portalfs \
-	${_mount_smbfs} \
-	${_moused} \
-	${_mptable} \
-	mptutil \
-	mtest \
-	mtree \
-	${_named} \
-	${_named-checkconf} \
-	${_named-checkzone} \
-	${_named.reload} \
-	${_ndiscvt} \
-	${_ndp} \
-	newsyslog \
-	nfscbd \
-	nfsd \
-	nfsdumpstate \
-	nfsrevoke \
-	nfsuserd \
-	${_ngctl} \
-	${_nghook} \
-	nologin \
-	${_nscd} \
-	${_ntp} \
-	${_nvram} \
-	${_ofwdump} \
-	pc-sysinstall \
-	pciconf \
-	periodic \
-	${_pkg_install} \
-	${_pmcannotate} \
-	${_pmccontrol} \
-	${_pmcstat} \
-	${_pnpinfo} \
-	${_portsnap} \
-	powerd \
-	${_ppp} \
-	${_pppctl} \
-	${_praliases} \
-	${_praudit} \
-	procctl \
-	pstat \
-	pw \
-	pwd_mkdb \
-	quot \
-	${_quotaon} \
-	rarpd \
-	${_repquota} \
-	${_rip6query} \
-	rmt \
-	${_rndc} \
-	${_rndc-confgen} \
-	${_route6d} \
-	rpcbind \
-	rpc.lockd \
-	rpc.statd \
-	rpc.umntall \
-	${_rpc.yppasswdd} \
-	${_rpc.ypupdated} \
-	${_rpc.ypxfrd} \
-	${_rrenumd} \
-	${_rtadvd} \
-	rtprio \
-	${_rtsold} \
-	${_rwhod} \
-	${_sa} \
-	${_sade} \
-	${_sendmail} \
-	service \
-	services_mkdb \
-	setfib \
-	setfmac \
-	setpmac \
-	${_sicontrol} \
-	smbmsg \
-	snapinfo \
-	${_spkrtest} \
-	spray \
-	${_sysinstall} \
-	syslogd \
-	tcpdchk \
-	tcpdmatch \
-	tcpdrop \
-	tcpdump \
-	timed \
-	traceroute \
-	${_traceroute6} \
-	trpt \
-	tzsetup \
-	${_uathload} \
-	ugidfw \
-	${_uhsoctl} \
-	${_usbdevs} \
-	${_usbconfig} \
-	${_vidcontrol} \
-	vipw \
-	wake \
-	watch \
-	watchdogd \
-	${_wlandebug} \
-	${_wlconfig} \
-	${_wpa} \
-	${_ypbind} \
-	${_yp_mkdb} \
-	${_yppoll} \
-	${_yppush} \
-	${_ypserv} \
-	${_ypset} \
-	zic \
-	${_zzz}
-
-# NB: keep these sorted by MK_* knobs
-
-.if ${MK_ACCT} != "no"
-_ac=		ac
-_accton=	accton
-_sa=		sa
-.endif
-
-.if ${MK_AMD} != "no"
-_amd=		amd
-.endif
-
-.if ${MK_AUDIT} != "no"
-_audit=		audit
-_auditd=	auditd
-_auditreduce=	auditreduce
-_praudit=	praudit
-.endif
-
-.if ${MK_AUTHPF} != "no"
-_authpf=	authpf
-.endif
-
-.if ${MK_BIND_DNSSEC} != "no" && ${MK_OPENSSL} != "no"
-_dnssec-dsfromkey=	dnssec-dsfromkey
-_dnssec-keyfromlabel=	dnssec-keyfromlabel
-_dnssec-keygen=		dnssec-keygen
-_dnssec-signzone=	dnssec-signzone
-.endif
-.if ${MK_BIND_NAMED} != "no"
-_named=			named
-_named-checkconf=	named-checkconf
-_named-checkzone=	named-checkzone
-_named.reload=		named.reload
-_rndc=			rndc
-_rndc-confgen=		rndc-confgen
-.endif
-
-.if ${MK_BLUETOOTH} != "no"
-_bluetooth=	bluetooth
-.endif
-
-.if ${MK_BSNMP} != "no"
-_bsnmpd=	bsnmpd
-.endif
-
-.if ${MK_CTM} != "no"
-_ctm=		ctm
-.endif
-
-.if ${MK_FLOPPY} != "no"
-_fdcontrol=	fdcontrol
-_fdformat=	fdformat
-_fdread=	fdread
-_fdwrite=	fdwrite
-.endif
-
-.if ${MK_FREEBSD_UPDATE} != "no"
-_freebsd-update= freebsd-update
-.endif
-
-.if ${MK_GSSAPI} != no
-_gssd=		gssd
-.endif
-
-.if ${MK_INET6} != "no"
-_faithd=	faithd
-_ip6addrctl=	ip6addrctl
-_mld6query=	mld6query
-_ndp=		ndp
-_rip6query=	rip6query
-_route6d=	route6d
-_rrenumd=	rrenumd
-_rtadvd=	rtadvd
-_rtsold=	rtsold
-_traceroute6=	traceroute6
-.endif
-
-.if ${MK_IPFW} != "no"
-_ipfwpcap=	ipfwpcap
-.endif
-
-.if ${MK_IPX} != "no"
-_IPXrouted=	IPXrouted
-.endif
-
-.if ${MK_JAIL} != "no"
-_jail=		jail
-_jexec=		jexec
-_jls=		jls
-.endif
-
-# XXX MK_SYSCONS
-.if ${MK_LEGACY_CONSOLE} != "no"
-_kbdcontrol=	kbdcontrol
-_kbdmap=	kbdmap
-_moused=	moused
-_vidcontrol=	vidcontrol
-.endif
-
-.if ${MK_LIBTHR} != "no" || ${MK_LIBPTHREAD} != "no"
-.if ${MK_PPP} != "no"
-_pppctl=	pppctl
-.endif
-.if ${MK_NS_CACHING} != "no"
-_nscd=		nscd
-.endif
-.endif
-
-.if ${MK_LPR} != "no"
-_lpr=		lpr
-.endif
-
-.if ${MK_MAN_UTILS} != "no"
-_manctl=	manctl
-.endif
-
-.if ${MK_NETGRAPH} != "no"
-_flowctl=	flowctl
-_lmcconfig=	lmcconfig
-_ngctl=		ngctl
-_nghook=	nghook
-.endif
-
-.if ${MK_NIS} != "no"
-_rpc.yppasswdd=	rpc.yppasswdd
-_rpc.ypupdated=	rpc.ypupdated
-_rpc.ypxfrd=	rpc.ypxfrd
-_ypbind=	ypbind
-_yp_mkdb=	yp_mkdb
-_yppoll=	yppoll
-_yppush=	yppush
-_ypserv=	ypserv
-_ypset=		ypset
-.endif
-
-.if ${MK_NTP} != "no"
-_ntp=		ntp
-.endif
-
-.if ${MK_OPENSSL} != "no"
-_keyserv=	keyserv
-.endif
-
-.if ${MK_PF} != "no"
-_ftp-proxy=	ftp-proxy
-.endif
-
-.if ${MK_PKGTOOLS} != "no"
-_pkg_install=	pkg_install
-.endif
-
-# XXX MK_TOOLCHAIN?
-.if ${MK_PMC} != "no"
-_pmcannotate=	pmcannotate
-_pmccontrol=	pmccontrol
-_pmcstat=	pmcstat
-.endif
-
-.if ${MK_PORTSNAP} != "no"
-_portsnap=	portsnap
-.endif
-
-.if ${MK_PPP} != "no"
-_ppp=		ppp
-#_pppctl handled below
-.endif
-
-.if ${MK_QUOTAS} != "no"
-_edquota=	edquota
-_quotaon=	quotaon
-_repquota=	repquota
-.endif
-
-.if ${MK_RCMDS} != "no"
-_rwhod=		rwhod
-.endif
-
-.if ${MK_SENDMAIL} != "no"
-_editmap=	editmap
-_mailstats=	mailstats
-_makemap=	makemap
-_praliases=	praliases
-_sendmail=	sendmail
-.endif
-
-.if ${MK_SYSINSTALL} != "no"
-.if ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "i386" || \
-    ${MACHINE_ARCH} == "sparc64"
-_sade=		sade
-.endif
-.if ${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
-_sysinstall=	sysinstall
-.endif
-.endif
-
-.if ${MK_TOOLCHAIN} != "no"
-_config=	config
-_crunch=	crunch
-.endif
-
-.if ${MK_USB} != "no"
-.if ${MACHINE_ARCH} != "ia64" && \
-   !(${MACHINE_ARCH} == "mips" && defined(TARGET_ABI) && ${TARGET_ABI} == "n64")
-_uathload=	uathload
-.endif
-_uhsoctl=	uhsoctl
-#_usbdevs=	usbdevs
-_usbconfig=	usbconfig
-.endif
-
-.if ${MK_WIRELESS} != "no"
-_ancontrol=	ancontrol
-_wlandebug=	wlandebug
-_wpa=		wpa
-.endif
-
-.if ${MACHINE_ARCH} == "arm"
-_kgmon=		kgmon
-.endif
-
-.if ${MACHINE_ARCH} == "i386"
-.if ${MK_APM} != "no"
-_apm=		apm
-_apmd=		apmd
-.endif
-_asf=		asf
-.if ${MK_TOOLCHAIN} != "no"
-_btxld=		btxld
-.endif
-_cpucontrol=	cpucontrol
-_kgmon=		kgmon
-_kgzip=		kgzip
-_lptcontrol=	lptcontrol
-.if ${MK_NCP} != "no"
-_mount_nwfs=	mount_nwfs
-.endif
-_mount_smbfs=	mount_smbfs
-_mptable=	mptable
-.if ${MK_NDIS} != "no"
-_ndiscvt=	ndiscvt
-.endif
-_pnpinfo=	pnpinfo
-_sicontrol=	sicontrol
-_spkrtest=	spkrtest
-_zzz=		zzz
-.if ${MACHINE} == "i386"
-.if ${MK_ACPI} != "no"
-_acpi=		acpi
-.endif
-_boot0cfg=	boot0cfg
-.if ${MK_WIRELESS} != "no"
-_wlconfig=	wlconfig
-.endif
-.elif ${MACHINE} == "pc98"
-_boot98cfg=	boot98cfg
-.endif
-.endif
-
-# kgzip: builds, but missing support files
-# mptable: broken (not 64 bit clean)
-# pnpinfo: crashes (not really useful anyway)
-.if ${MACHINE_ARCH} == "amd64"
-.if ${MK_ACPI} != "no"
-_acpi=		acpi
-.endif
-.if ${MK_APM} != "no"
-_apm=		apm
-.endif
-_asf=		asf
-_boot0cfg=	boot0cfg
-.if ${MK_TOOLCHAIN} != "no"
-_btxld=		btxld
-.endif
-_cpucontrol=	cpucontrol
-_kgmon=		kgmon
-_lptcontrol=	lptcontrol
-.if ${MK_NCP} != "no"
-_mount_nwfs=	mount_nwfs
-.endif
-_mount_smbfs=	mount_smbfs
-_mptable=	mptable
-.if ${MK_NDIS} != "no"
-_ndiscvt=	ndiscvt
-.endif
-_sicontrol=	sicontrol
-_spkrtest=	spkrtest
-_zzz=		zzz
-.endif
-
-.if ${MACHINE_ARCH} == "arm"
-_ofwdump=	ofwdump
-.endif
-
-.if ${MACHINE_ARCH} == "ia64"
-.if ${MK_ACPI} != "no"
-_acpi=		acpi
-.endif
-_kgmon=		kgmon
-_mount_smbfs=	mount_smbfs
-_zzz=		zzz
-.endif
-
-.if ${MACHINE_CPUARCH} == "powerpc"
-_mount_smbfs=	mount_smbfs
-_nvram=		nvram
-_ofwdump=	ofwdump
-.endif
-
-.if ${MACHINE_ARCH} == "sparc64"
-_eeprom=	eeprom
-_mount_smbfs=	mount_smbfs
-_ofwdump=	ofwdump
-.endif
-
-.include 

From fca5b4f4d9b05faab92b49ca6003d5288a72e25f Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 04:23:23 +0000
Subject: [PATCH 0682/1624] This is exactly the same as the .else, so remove
 it.

---
 lib/msun/Makefile | 2 --
 1 file changed, 2 deletions(-)

diff --git a/lib/msun/Makefile b/lib/msun/Makefile
index 1c5869e8483..87bd95441ad 100644
--- a/lib/msun/Makefile
+++ b/lib/msun/Makefile
@@ -14,8 +14,6 @@
 
 .if ${MACHINE_CPUARCH} == "i386"
 ARCH_SUBDIR= i387
-.elif ${MACHINE_ARCH} == "powerpc64"
-ARCH_SUBDIR= powerpc
 .else
 ARCH_SUBDIR= ${MACHINE_CPUARCH}
 .endif

From a3e0e990de88dec25facbb506ace417e9d810092 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 13 Sep 2010 05:03:37 +0000
Subject: [PATCH 0683/1624] The functions in sys/mips/mips/psraccess.S can be
 implemented with mips_rd_status/mips_wr_status.  Implement them in
 mips/include/cpufunc.h, and remove psraccess.S.

Reviewed by:	neel, imp
---
 sys/conf/files.mips        |  1 -
 sys/mips/include/cpufunc.h | 18 +++++++++
 sys/mips/include/md_var.h  |  6 +--
 sys/mips/mips/psraccess.S  | 81 --------------------------------------
 4 files changed, 19 insertions(+), 87 deletions(-)
 delete mode 100644 sys/mips/mips/psraccess.S

diff --git a/sys/conf/files.mips b/sys/conf/files.mips
index c33fa9afbb7..99a772358e0 100644
--- a/sys/conf/files.mips
+++ b/sys/conf/files.mips
@@ -22,7 +22,6 @@
 mips/mips/machdep.c		standard
 mips/mips/mp_machdep.c		optional smp
 mips/mips/mpboot.S		optional smp
-mips/mips/psraccess.S		standard
 # ----------------------------------------------------------------------
 # Phase 3
 # ----------------------------------------------------------------------
diff --git a/sys/mips/include/cpufunc.h b/sys/mips/include/cpufunc.h
index 11109e7ae36..efaa3f4f94b 100644
--- a/sys/mips/include/cpufunc.h
+++ b/sys/mips/include/cpufunc.h
@@ -266,6 +266,24 @@ intr_restore(register_t ie)
 	}
 }
 
+static __inline uint32_t
+set_intr_mask(uint32_t mask)
+{
+	uint32_t ostatus;
+
+	ostatus = mips_rd_status();
+	mask = (ostatus & ~MIPS_SR_INT_MASK) | (~mask & MIPS_SR_INT_MASK);
+	mips_wr_status(mask);
+	return (ostatus);
+}
+
+static __inline uint32_t
+get_intr_mask(void)
+{
+
+	return (mips_rd_status() & MIPS_SR_INT_MASK);
+}
+
 static __inline void
 breakpoint(void)
 {
diff --git a/sys/mips/include/md_var.h b/sys/mips/include/md_var.h
index 33171bff80f..ba3da96a958 100644
--- a/sys/mips/include/md_var.h
+++ b/sys/mips/include/md_var.h
@@ -75,9 +75,5 @@ void	mips_postboot_fixup(void);
 void	platform_identify(void);
 
 extern int busdma_swi_pending;
-void busdma_swi(void);
-
-u_int32_t set_intr_mask(u_int32_t);
-u_int32_t get_intr_mask(void);
-
+void	busdma_swi(void);
 #endif /* !_MACHINE_MD_VAR_H_ */
diff --git a/sys/mips/mips/psraccess.S b/sys/mips/mips/psraccess.S
deleted file mode 100644
index 02be3368e3e..00000000000
--- a/sys/mips/mips/psraccess.S
+++ /dev/null
@@ -1,81 +0,0 @@
-/*	$OpenBSD$ */
-/*
- * Copyright (c) 2001 Opsycon AB  (www.opsycon.se / www.opsycon.com)
- *
- * 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 Opsycon AB, Sweden.
- * 4. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
- *
- *	JNPR: psraccess.S,v 1.4.2.1 2007/09/10 10:36:50 girish
- * $FreeBSD$
- *
- */
-
-/*
- *  Low level code to manage processor specific registers.
- */
-
-#include 
-#include 
-#include 
-
-#include "opt_cputype.h"
-
-#include "assym.s"
-
-/*
- * FREEBSD_DEVELOPERS_FIXME
- * Some MIPS CPU may need delays using nops between executing CP0 Instructions
- */
-#define	MIPS_CPU_NOP_DELAY	nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
-
-	.set	noreorder		# Noreorder is default style!
-
-LEAF(set_intr_mask)
-	li	t0, MIPS_SR_INT_MASK	# 1 means masked so invert.
-	not	a0, a0			# 1 means masked so invert.
-	and	a0, t0			# 1 means masked so invert.
-	mfc0	v0, MIPS_COP_0_STATUS
-	li	v1, ~MIPS_SR_INT_MASK
-	and	v1, v0
-	or	v1, a0
-	mtc0	v1, MIPS_COP_0_STATUS
-	MIPS_CPU_NOP_DELAY
-	move	v0, v1
-	jr	ra
-	nop
-
-END(set_intr_mask)
-
-LEAF(get_intr_mask)
-	li	a0, 0
-	mfc0	v0, MIPS_COP_0_STATUS
-	li	v1, MIPS_SR_INT_MASK
-	and	v0, v1
-	or	v0, a0
-	jr	ra
-	nop
-
-END(get_intr_mask)

From 373d257ef06c2336f4a77c4bc307a4d4f666588a Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Mon, 13 Sep 2010 06:32:56 +0000
Subject: [PATCH 0684/1624] Add tunable 'hint.hpet.X.per_cpu' to specify how
 much per-CPU timers driver should provide if there is sufficient hardware.
 Default is 1.

---
 sys/dev/acpica/acpi_hpet.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/sys/dev/acpica/acpi_hpet.c b/sys/dev/acpica/acpi_hpet.c
index bc8cd852aef..2a8eb301a09 100644
--- a/sys/dev/acpica/acpi_hpet.c
+++ b/sys/dev/acpica/acpi_hpet.c
@@ -74,6 +74,7 @@ struct hpet_softc {
 	int			irq;
 	int			useirq;
 	int			legacy_route;
+	int			per_cpu;
 	uint32_t		allowed_irqs;
 	struct resource		*mem_res;
 	struct resource		*intr_res;
@@ -501,6 +502,11 @@ hpet_attach(device_t dev)
 	resource_int_value(device_get_name(dev), device_get_unit(dev),
 	     "allowed_irqs", &sc->allowed_irqs);
 
+	/* Get how much per-CPU timers we should try to provide. */
+	sc->per_cpu = 1;
+	resource_int_value(device_get_name(dev), device_get_unit(dev),
+	     "per_cpu", &sc->per_cpu);
+
 	num_msi = 0;
 	sc->useirq = 0;
 	/* Find IRQ vectors for all timers. */
@@ -556,7 +562,7 @@ hpet_attach(device_t dev)
 	if (sc->legacy_route)
 		hpet_enable(sc);
 	/* Group timers for per-CPU operation. */
-	num_percpu_et = min(num_msi / mp_ncpus, 1);
+	num_percpu_et = min(num_msi / mp_ncpus, sc->per_cpu);
 	num_percpu_t = num_percpu_et * mp_ncpus;
 	pcpu_master = 0;
 	cur_cpu = CPU_FIRST();

From d2fb1699acb629ec3975d5f46c3ce8cd4ed3df4d Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 06:35:35 +0000
Subject: [PATCH 0685/1624] Revert r212513 and reimplement the search order to
 be ARCH, CPUARCH

---
 usr.bin/xlint/Makefile.inc               | 11 +++--
 usr.bin/xlint/arch/powerpc/targparam.h   |  9 ----
 usr.bin/xlint/arch/powerpc64/targparam.h | 55 ++++++++++++++++++++++++
 3 files changed, 62 insertions(+), 13 deletions(-)
 create mode 100644 usr.bin/xlint/arch/powerpc64/targparam.h

diff --git a/usr.bin/xlint/Makefile.inc b/usr.bin/xlint/Makefile.inc
index f4956ab25e5..ebdcbe33c38 100644
--- a/usr.bin/xlint/Makefile.inc
+++ b/usr.bin/xlint/Makefile.inc
@@ -7,14 +7,17 @@ WARNS?=		0
 
 # These assignments duplicate much of the functionality of
 # MACHINE_CPUARCH, but there's no easy way to export make functions...
-
 .if defined(TARGET_ARCH)
-TARGET_CPUARCH=${TARGET_ARCH:C/mipse[bl]/mips/:C/armeb/arm/}
+TARGET_CPUARCH=	${TARGET_ARCH:C/mipse[bl]/mips/:C/armeb/arm/}
 .else
-TARGET_CPUARCH=${MACHINE_CPUARCH}
+TARGET_CPUARCH=	${MACHINE_CPUARCH}
+TARGET_ARCH=	${MACHINE_ARCH}
 .endif
-TARGET_ARCH?=	${MACHINE_ARCH}
+.if exists(${.CURDIR}/../arch/${TARGET_ARCH}
+CFLAGS+=	-I${.CURDIR}/../arch/${TARGET_ARCH}
+.else
 CFLAGS+=	-I${.CURDIR}/../arch/${TARGET_CPUARCH}
+.enidf
 CFLAGS+=	-I${.CURDIR}/../common
 
 OBJECT_FMT=	ELF
diff --git a/usr.bin/xlint/arch/powerpc/targparam.h b/usr.bin/xlint/arch/powerpc/targparam.h
index 2316f30983b..554f9b3942d 100644
--- a/usr.bin/xlint/arch/powerpc/targparam.h
+++ b/usr.bin/xlint/arch/powerpc/targparam.h
@@ -37,11 +37,7 @@
  * Machine-dependent target parameters for lint1.
  */
 
-#ifdef __powerpc64__
-#include "lp64.h"
-#else
 #include "ilp32.h"
-#endif
 
 /*    
  * Should be set to 1 if the difference of two pointers is of type long
@@ -49,13 +45,8 @@
  * kept in sync with the compiler!
  */     
 
-#ifdef __powerpc64__
-#define	PTRDIFF_IS_LONG		1
-#define	SIZEOF_IS_ULONG		1
-#else
 #define	PTRDIFF_IS_LONG		0
 #define	SIZEOF_IS_ULONG		0
-#endif
 
 #define	FLOAT_SIZE		(4 * CHAR_BIT)
 #define	DOUBLE_SIZE		(8 * CHAR_BIT)
diff --git a/usr.bin/xlint/arch/powerpc64/targparam.h b/usr.bin/xlint/arch/powerpc64/targparam.h
new file mode 100644
index 00000000000..09bfd3e2b3c
--- /dev/null
+++ b/usr.bin/xlint/arch/powerpc64/targparam.h
@@ -0,0 +1,55 @@
+/*	$NetBSD: targparam.h,v 1.1 2002/01/18 20:39:20 thorpej Exp $	*/
+
+/*
+ * Copyright (c) 1994, 1995 Jochen Pohl
+ * 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 Jochen Pohl for
+ *	The NetBSD Project.
+ * 4. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * $FreeBSD$
+ */
+
+/*
+ * Machine-dependent target parameters for lint1.
+ */
+
+#include "lp64.h"
+
+/*    
+ * Should be set to 1 if the difference of two pointers is of type long
+ * or the value of sizeof is of type unsigned long.  Note this MUST be
+ * kept in sync with the compiler!
+ */     
+
+#define	PTRDIFF_IS_LONG		1
+#define	SIZEOF_IS_ULONG		1
+
+#define	FLOAT_SIZE		(4 * CHAR_BIT)
+#define	DOUBLE_SIZE		(8 * CHAR_BIT)
+#define	LDOUBLE_SIZE		(8 * CHAR_BIT)
+
+#define	ENUM_SIZE		(4 * CHAR_BIT)

From 336c4b45ea49ce233b26d4aded1b8f32ec636ce4 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 06:50:07 +0000
Subject: [PATCH 0686/1624] Doh! two last second refactoring typos crept in. 
 Fix.

---
 usr.bin/xlint/Makefile.inc | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/usr.bin/xlint/Makefile.inc b/usr.bin/xlint/Makefile.inc
index ebdcbe33c38..32cfcb783c9 100644
--- a/usr.bin/xlint/Makefile.inc
+++ b/usr.bin/xlint/Makefile.inc
@@ -13,11 +13,11 @@ TARGET_CPUARCH=	${TARGET_ARCH:C/mipse[bl]/mips/:C/armeb/arm/}
 TARGET_CPUARCH=	${MACHINE_CPUARCH}
 TARGET_ARCH=	${MACHINE_ARCH}
 .endif
-.if exists(${.CURDIR}/../arch/${TARGET_ARCH}
+.if exists(${.CURDIR}/../arch/${TARGET_ARCH})
 CFLAGS+=	-I${.CURDIR}/../arch/${TARGET_ARCH}
 .else
 CFLAGS+=	-I${.CURDIR}/../arch/${TARGET_CPUARCH}
-.enidf
+.endif
 CFLAGS+=	-I${.CURDIR}/../common
 
 OBJECT_FMT=	ELF

From a9b764e218bfdbf5f746d64ff503348a2363db6e Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Mon, 13 Sep 2010 07:03:01 +0000
Subject: [PATCH 0687/1624] Convert thread list lock from mutex to rwlock.

---
 lib/libthr/thread/thr_affinity.c   | 21 +++++---
 lib/libthr/thread/thr_attr.c       | 13 ++---
 lib/libthr/thread/thr_cancel.c     |  6 +--
 lib/libthr/thread/thr_create.c     | 25 ++++------
 lib/libthr/thread/thr_detach.c     | 12 ++---
 lib/libthr/thread/thr_exit.c       | 17 +++----
 lib/libthr/thread/thr_fork.c       |  4 +-
 lib/libthr/thread/thr_init.c       |  2 +-
 lib/libthr/thread/thr_join.c       | 29 ++++++-----
 lib/libthr/thread/thr_kill.c       |  8 +++-
 lib/libthr/thread/thr_list.c       | 77 ++++++++++++++++--------------
 lib/libthr/thread/thr_private.h    | 44 +++++++++++++----
 lib/libthr/thread/thr_resume_np.c  |  6 +--
 lib/libthr/thread/thr_stack.c      |  2 +-
 lib/libthr/thread/thr_suspend_np.c | 16 ++++---
 15 files changed, 153 insertions(+), 129 deletions(-)

diff --git a/lib/libthr/thread/thr_affinity.c b/lib/libthr/thread/thr_affinity.c
index 7a12a898a9e..ae43fcb2390 100644
--- a/lib/libthr/thread/thr_affinity.c
+++ b/lib/libthr/thread/thr_affinity.c
@@ -50,8 +50,7 @@ _pthread_setaffinity_np(pthread_t td, size_t cpusetsize, const cpuset_t *cpusetp
 			-1, cpusetsize, cpusetp);
 		if (error == -1)
 			error = errno;
-	} else {
-		THR_THREAD_LOCK(curthread, td);
+	} else if ((error = _thr_find_thread(curthread, td, 0)) == 0) {
 		if (td->state == PS_DEAD) {
 			THR_THREAD_UNLOCK(curthread, td);
 			return (EINVAL);
@@ -73,10 +72,18 @@ _pthread_getaffinity_np(pthread_t td, size_t cpusetsize, cpuset_t *cpusetp)
 	lwpid_t tid;
 	int error;
 
-	tid = TID(td);
-	error = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
-		(td == curthread) ? -1 : tid, cpusetsize, cpusetp);
-	if (error == -1)
-		error = errno;
+	if (td == curthread) {
+		error = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
+			(td == curthread) ? -1 : tid, cpusetsize, cpusetp);
+		if (error == -1)
+			error = errno;
+	} else if ((error = _thr_find_thread(curthread, td, 0)) == 0) {
+		tid = TID(td);
+		error = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
+			(td == curthread) ? -1 : tid, cpusetsize, cpusetp);
+		if (error == -1)
+			error = errno;
+		THR_THREAD_UNLOCK(curthread, td);
+	}
 	return (error);
 }
diff --git a/lib/libthr/thread/thr_attr.c b/lib/libthr/thread/thr_attr.c
index bc6a891b3a4..fedf4224269 100644
--- a/lib/libthr/thread/thr_attr.c
+++ b/lib/libthr/thread/thr_attr.c
@@ -132,22 +132,23 @@ _pthread_attr_destroy(pthread_attr_t *attr)
 __weak_reference(_pthread_attr_get_np, pthread_attr_get_np);
 
 int
-_pthread_attr_get_np(pthread_t pid, pthread_attr_t *dst)
+_pthread_attr_get_np(pthread_t pthread, pthread_attr_t *dst)
 {
 	struct pthread *curthread;
 	struct pthread_attr attr;
 	int	ret;
 
-	if (pid == NULL || dst == NULL || *dst == NULL)
+	if (pthread == NULL || dst == NULL || *dst == NULL)
 		return (EINVAL);
 
 	curthread = _get_curthread();
-	if ((ret = _thr_ref_add(curthread, pid, /*include dead*/0)) != 0)
+	if ((ret = _thr_find_thread(curthread, pthread, /*include dead*/0)) != 0)
 		return (ret);
-	attr = pid->attr;
-	if (pid->tlflags & TLFLAGS_DETACHED)
+	attr = pthread->attr;
+	if (pthread->flags & THR_FLAGS_DETACHED)
 		attr.flags |= PTHREAD_DETACHED;
-	_thr_ref_delete(curthread, pid);
+	THR_THREAD_UNLOCK(curthread, pthread);
+
 	memcpy(*dst, &attr, sizeof(struct pthread_attr));
 	/* XXX */
 	(*dst)->cpuset = NULL;
diff --git a/lib/libthr/thread/thr_cancel.c b/lib/libthr/thread/thr_cancel.c
index c61cedeeac3..6a6e9ecf34d 100644
--- a/lib/libthr/thread/thr_cancel.c
+++ b/lib/libthr/thread/thr_cancel.c
@@ -60,18 +60,16 @@ _pthread_cancel(pthread_t pthread)
 
 	/*
 	 * POSIX says _pthread_cancel should be async cancellation safe.
-	 * _thr_ref_add and _thr_ref_delete will enter and leave critical
+	 * _thr_find_thread and THR_THREAD_UNLOCK will enter and leave critical
 	 * region automatically.
 	 */
-	if ((ret = _thr_ref_add(curthread, pthread, 0)) == 0) {
-		THR_THREAD_LOCK(curthread, pthread);
+	if ((ret = _thr_find_thread(curthread, pthread, 0)) == 0) {
 		if (!pthread->cancel_pending) {
 			pthread->cancel_pending = 1;
 			if (pthread->state != PS_DEAD)
 				_thr_send_sig(pthread, SIGCANCEL);
 		}
 		THR_THREAD_UNLOCK(curthread, pthread);
-		_thr_ref_delete(curthread, pthread);
 	}
 	return (ret);
 }
diff --git a/lib/libthr/thread/thr_create.c b/lib/libthr/thread/thr_create.c
index 2677571b424..d4f5a11820e 100644
--- a/lib/libthr/thread/thr_create.c
+++ b/lib/libthr/thread/thr_create.c
@@ -125,7 +125,7 @@ _pthread_create(pthread_t * thread, const pthread_attr_t * attr,
 	new_thread->state = PS_RUNNING;
 
 	if (new_thread->attr.flags & PTHREAD_CREATE_DETACHED)
-		new_thread->tlflags |= TLFLAGS_DETACHED;
+		new_thread->flags |= THR_FLAGS_DETACHED;
 
 	/* Add the new thread. */
 	new_thread->refcount = 1;
@@ -185,16 +185,14 @@ _pthread_create(pthread_t * thread, const pthread_attr_t * attr,
 			THR_THREAD_LOCK(curthread, new_thread);
 		new_thread->state = PS_DEAD;
 		new_thread->tid = TID_TERMINATED;
+		new_thread->flags |= THR_FLAGS_DETACHED;
+		new_thread->refcount--;
 		if (new_thread->flags & THR_FLAGS_NEED_SUSPEND) {
 			new_thread->cycle++;
 			_thr_umtx_wake(&new_thread->cycle, INT_MAX, 0);
 		}
-		THR_THREAD_UNLOCK(curthread, new_thread);
-		THREAD_LIST_LOCK(curthread);
-		_thread_active_threads--;
-		new_thread->tlflags |= TLFLAGS_DETACHED;
-		_thr_ref_delete_unlocked(curthread, new_thread);
-		THREAD_LIST_UNLOCK(curthread);
+		_thr_try_gc(curthread, new_thread); /* thread lock released */
+		atomic_add_int(&_thread_active_threads, -1);
 	} else if (locked) {
 		if (cpusetp != NULL) {
 			if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
@@ -202,22 +200,17 @@ _pthread_create(pthread_t * thread, const pthread_attr_t * attr,
 				ret = errno;
 				/* kill the new thread */
 				new_thread->force_exit = 1;
-				THR_THREAD_UNLOCK(curthread, new_thread);
+				new_thread->flags |= THR_FLAGS_DETACHED;
+				_thr_try_gc(curthread, new_thread);
+				 /* thread lock released */
 				goto out;
 			}
 		}
 
 		_thr_report_creation(curthread, new_thread);
 		THR_THREAD_UNLOCK(curthread, new_thread);
-out:
-		if (ret) {
-			THREAD_LIST_LOCK(curthread);
-			new_thread->tlflags |= TLFLAGS_DETACHED;
-			THR_GCLIST_ADD(new_thread);
-			THREAD_LIST_UNLOCK(curthread);
-		}
 	}
-
+out:
 	if (ret)
 		(*thread) = 0;
 	return (ret);
diff --git a/lib/libthr/thread/thr_detach.c b/lib/libthr/thread/thr_detach.c
index bfcb6e63f71..c494f7c3b30 100644
--- a/lib/libthr/thread/thr_detach.c
+++ b/lib/libthr/thread/thr_detach.c
@@ -47,25 +47,21 @@ _pthread_detach(pthread_t pthread)
 	if (pthread == NULL)
 		return (EINVAL);
 
-	THREAD_LIST_LOCK(curthread);
 	if ((rval = _thr_find_thread(curthread, pthread,
 			/*include dead*/1)) != 0) {
-		THREAD_LIST_UNLOCK(curthread);
 		return (rval);
 	}
 
 	/* Check if the thread is already detached or has a joiner. */
-	if ((pthread->tlflags & TLFLAGS_DETACHED) != 0 ||
+	if ((pthread->flags & THR_FLAGS_DETACHED) != 0 ||
 	    (pthread->joiner != NULL)) {
-		THREAD_LIST_UNLOCK(curthread);
+		THR_THREAD_UNLOCK(curthread, pthread);
 		return (EINVAL);
 	}
 
 	/* Flag the thread as detached. */
-	pthread->tlflags |= TLFLAGS_DETACHED;
-	if (pthread->state == PS_DEAD)
-		THR_GCLIST_ADD(pthread);
-	THREAD_LIST_UNLOCK(curthread);
+	pthread->flags |= THR_FLAGS_DETACHED;
+	_thr_try_gc(curthread, pthread); /* thread lock released */
 
 	return (0);
 }
diff --git a/lib/libthr/thread/thr_exit.c b/lib/libthr/thread/thr_exit.c
index 10581ab2395..9e2e0cb7ccf 100644
--- a/lib/libthr/thread/thr_exit.c
+++ b/lib/libthr/thread/thr_exit.c
@@ -108,37 +108,34 @@ _pthread_exit_mask(void *status, sigset_t *mask)
 	if (!_thr_isthreaded())
 		exit(0);
 
-	THREAD_LIST_LOCK(curthread);
-	_thread_active_threads--;
-	if (_thread_active_threads == 0) {
-		THREAD_LIST_UNLOCK(curthread);
+	if (atomic_fetchadd_int(&_thread_active_threads, -1) == 1) {
 		exit(0);
 		/* Never reach! */
 	}
-	THREAD_LIST_UNLOCK(curthread);
 
 	/* Tell malloc that the thread is exiting. */
 	_malloc_thread_cleanup();
 
-	THREAD_LIST_LOCK(curthread);
 	THR_LOCK(curthread);
 	curthread->state = PS_DEAD;
 	if (curthread->flags & THR_FLAGS_NEED_SUSPEND) {
 		curthread->cycle++;
 		_thr_umtx_wake(&curthread->cycle, INT_MAX, 0);
 	}
-	THR_UNLOCK(curthread);
 	/*
 	 * Thread was created with initial refcount 1, we drop the
 	 * reference count to allow it to be garbage collected.
 	 */
 	curthread->refcount--;
-	if (curthread->tlflags & TLFLAGS_DETACHED)
-		THR_GCLIST_ADD(curthread);
-	THREAD_LIST_UNLOCK(curthread);
+	_thr_try_gc(curthread, curthread); /* thread lock released */
+
 	if (!curthread->force_exit && SHOULD_REPORT_EVENT(curthread, TD_DEATH))
 		_thr_report_death(curthread);
 
+#if defined(_PTHREADS_INVARIANTS)
+	if (THR_IN_CRITICAL(curthread))
+		PANIC("thread exits with resources held!");
+#endif
 	/*
 	 * Kernel will do wakeup at the address, so joiner thread
 	 * will be resumed if it is sleeping at the address.
diff --git a/lib/libthr/thread/thr_fork.c b/lib/libthr/thread/thr_fork.c
index c15e8f9a32a..dd6005a8e48 100644
--- a/lib/libthr/thread/thr_fork.c
+++ b/lib/libthr/thread/thr_fork.c
@@ -178,13 +178,13 @@ _fork(void)
 		/* Child process */
 		errsave = errno;
 		curthread->cancel_pending = 0;
-		curthread->flags &= ~THR_FLAGS_NEED_SUSPEND;
+		curthread->flags &= ~(THR_FLAGS_NEED_SUSPEND|THR_FLAGS_DETACHED);
 
 		/*
 		 * Thread list will be reinitialized, and later we call
 		 * _libpthread_init(), it will add us back to list.
 		 */
-		curthread->tlflags &= ~(TLFLAGS_IN_TDLIST | TLFLAGS_DETACHED);
+		curthread->tlflags &= ~TLFLAGS_IN_TDLIST;
 
 		/* child is a new kernel thread. */
 		thr_self(&curthread->tid);
diff --git a/lib/libthr/thread/thr_init.c b/lib/libthr/thread/thr_init.c
index e5dc2ce400d..c20f3c8d784 100644
--- a/lib/libthr/thread/thr_init.c
+++ b/lib/libthr/thread/thr_init.c
@@ -111,7 +111,7 @@ struct umutex	_mutex_static_lock = DEFAULT_UMUTEX;
 struct umutex	_cond_static_lock = DEFAULT_UMUTEX;
 struct umutex	_rwlock_static_lock = DEFAULT_UMUTEX;
 struct umutex	_keytable_lock = DEFAULT_UMUTEX;
-struct umutex	_thr_list_lock = DEFAULT_UMUTEX;
+struct urwlock	_thr_list_lock = DEFAULT_URWLOCK;
 struct umutex	_thr_event_lock = DEFAULT_UMUTEX;
 
 int	__pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);
diff --git a/lib/libthr/thread/thr_join.c b/lib/libthr/thread/thr_join.c
index d3c8367dc13..4f26862dd9d 100644
--- a/lib/libthr/thread/thr_join.c
+++ b/lib/libthr/thread/thr_join.c
@@ -43,12 +43,12 @@ __weak_reference(_pthread_timedjoin_np, pthread_timedjoin_np);
 
 static void backout_join(void *arg)
 {
-	struct pthread *curthread = _get_curthread();
 	struct pthread *pthread = (struct pthread *)arg;
+	struct pthread *curthread = _get_curthread();
 
-	THREAD_LIST_LOCK(curthread);
+	THR_THREAD_LOCK(curthread, pthread);
 	pthread->joiner = NULL;
-	THREAD_LIST_UNLOCK(curthread);
+	THR_THREAD_LOCK(curthread, pthread);
 }
 
 int
@@ -88,23 +88,23 @@ join_common(pthread_t pthread, void **thread_return,
 	if (pthread == curthread)
 		return (EDEADLK);
 
-	THREAD_LIST_LOCK(curthread);
-	if ((ret = _thr_find_thread(curthread, pthread, 1)) != 0) {
-		ret = ESRCH;
-	} else if ((pthread->tlflags & TLFLAGS_DETACHED) != 0) {
+	if ((ret = _thr_find_thread(curthread, pthread, 1)) != 0)
+		return (ESRCH);
+
+	if ((pthread->flags & THR_FLAGS_DETACHED) != 0) {
 		ret = EINVAL;
 	} else if (pthread->joiner != NULL) {
 		/* Multiple joiners are not supported. */
 		ret = ENOTSUP;
 	}
 	if (ret) {
-		THREAD_LIST_UNLOCK(curthread);
+		THR_THREAD_UNLOCK(curthread, pthread);
 		return (ret);
 	}
 	/* Set the running thread to be the joiner: */
 	pthread->joiner = curthread;
 
-	THREAD_LIST_UNLOCK(curthread);
+	THR_THREAD_UNLOCK(curthread, pthread);
 
 	THR_CLEANUP_PUSH(curthread, backout_join, pthread);
 	_thr_cancel_enter(curthread);
@@ -131,17 +131,16 @@ join_common(pthread_t pthread, void **thread_return,
 	THR_CLEANUP_POP(curthread, 0);
 
 	if (ret == ETIMEDOUT) {
-		THREAD_LIST_LOCK(curthread);
+		THR_THREAD_LOCK(curthread, pthread);
 		pthread->joiner = NULL;
-		THREAD_LIST_UNLOCK(curthread);
+		THR_THREAD_UNLOCK(curthread, pthread);
 	} else {
 		ret = 0;
 		tmp = pthread->ret;
-		THREAD_LIST_LOCK(curthread);
-		pthread->tlflags |= TLFLAGS_DETACHED;
+		THR_THREAD_LOCK(curthread, pthread);
+		pthread->flags |= THR_FLAGS_DETACHED;
 		pthread->joiner = NULL;
-		THR_GCLIST_ADD(pthread);
-		THREAD_LIST_UNLOCK(curthread);
+		_thr_try_gc(curthread, pthread); /* thread lock released */
 
 		if (thread_return != NULL)
 			*thread_return = tmp;
diff --git a/lib/libthr/thread/thr_kill.c b/lib/libthr/thread/thr_kill.c
index 97d4fe6d2b2..b54458c5857 100644
--- a/lib/libthr/thread/thr_kill.c
+++ b/lib/libthr/thread/thr_kill.c
@@ -54,11 +54,15 @@ _pthread_kill(pthread_t pthread, int sig)
 	 * signal is valid (signal 0 specifies error checking only) and
 	 * not being ignored:
 	 */
-	else if ((ret = _thr_ref_add(curthread, pthread, /*include dead*/0))
+	else if (curthread == pthread) {
+		if (sig > 0)
+			_thr_send_sig(pthread, sig);
+		ret = 0;
+	} if ((ret = _thr_find_thread(curthread, pthread, /*include dead*/0))
 	    == 0) {
 		if (sig > 0)
 			_thr_send_sig(pthread, sig);
-		_thr_ref_delete(curthread, pthread);
+		THR_THREAD_UNLOCK(curthread, pthread);
 	}
 
 	/* Return the completion status: */
diff --git a/lib/libthr/thread/thr_list.c b/lib/libthr/thread/thr_list.c
index e23e57d44f7..7541fd3f48a 100644
--- a/lib/libthr/thread/thr_list.c
+++ b/lib/libthr/thread/thr_list.c
@@ -79,7 +79,7 @@ _thr_list_init(void)
 
 	_gc_count = 0;
 	total_threads = 1;
-	_thr_umutex_init(&_thr_list_lock);
+	_thr_urwlock_init(&_thr_list_lock);
 	TAILQ_INIT(&_thread_list);
 	TAILQ_INIT(&free_threadq);
 	_thr_umutex_init(&free_thread_lock);
@@ -98,7 +98,7 @@ _thr_gc(struct pthread *curthread)
 	TAILQ_HEAD(, pthread) worklist;
 
 	TAILQ_INIT(&worklist);
-	THREAD_LIST_LOCK(curthread);
+	THREAD_LIST_WRLOCK(curthread);
 
 	/* Check the threads waiting for GC. */
 	TAILQ_FOREACH_SAFE(td, &_thread_gc_list, gcle, td_next) {
@@ -107,17 +107,8 @@ _thr_gc(struct pthread *curthread)
 			continue;
 		}
 		_thr_stack_free(&td->attr);
-		if (((td->tlflags & TLFLAGS_DETACHED) != 0) &&
-		    (td->refcount == 0)) {
-			THR_GCLIST_REMOVE(td);
-			/*
-			 * The thread has detached and is no longer
-			 * referenced.  It is safe to remove all
-			 * remnants of the thread.
-			 */
-			THR_LIST_REMOVE(td);
-			TAILQ_INSERT_HEAD(&worklist, td, gcle);
-		}
+		THR_GCLIST_REMOVE(td);
+		TAILQ_INSERT_HEAD(&worklist, td, gcle);
 	}
 	THREAD_LIST_UNLOCK(curthread);
 
@@ -228,10 +219,10 @@ thr_destroy(struct pthread *curthread __unused, struct pthread *thread)
 void
 _thr_link(struct pthread *curthread, struct pthread *thread)
 {
-	THREAD_LIST_LOCK(curthread);
+	THREAD_LIST_WRLOCK(curthread);
 	THR_LIST_ADD(thread);
-	_thread_active_threads++;
 	THREAD_LIST_UNLOCK(curthread);
+	atomic_add_int(&_thread_active_threads, 1);
 }
 
 /*
@@ -240,10 +231,10 @@ _thr_link(struct pthread *curthread, struct pthread *thread)
 void
 _thr_unlink(struct pthread *curthread, struct pthread *thread)
 {
-	THREAD_LIST_LOCK(curthread);
+	THREAD_LIST_WRLOCK(curthread);
 	THR_LIST_REMOVE(thread);
-	_thread_active_threads--;
 	THREAD_LIST_UNLOCK(curthread);
+	atomic_add_int(&_thread_active_threads, -1);
 }
 
 void
@@ -290,12 +281,11 @@ _thr_ref_add(struct pthread *curthread, struct pthread *thread,
 		/* Invalid thread: */
 		return (EINVAL);
 
-	THREAD_LIST_LOCK(curthread);
 	if ((ret = _thr_find_thread(curthread, thread, include_dead)) == 0) {
 		thread->refcount++;
 		THR_CRITICAL_ENTER(curthread);
+		THR_THREAD_UNLOCK(curthread, thread);
 	}
-	THREAD_LIST_UNLOCK(curthread);
 
 	/* Return zero if the thread exists: */
 	return (ret);
@@ -304,41 +294,56 @@ _thr_ref_add(struct pthread *curthread, struct pthread *thread,
 void
 _thr_ref_delete(struct pthread *curthread, struct pthread *thread)
 {
-	THREAD_LIST_LOCK(curthread);
-	_thr_ref_delete_unlocked(curthread, thread);
-	THREAD_LIST_UNLOCK(curthread);
+	THR_THREAD_LOCK(curthread, thread);
+	thread->refcount--;
+	_thr_try_gc(curthread, thread);
+	THR_CRITICAL_LEAVE(curthread);
 }
 
+/* entered with thread lock held, exit with thread lock released */
 void
-_thr_ref_delete_unlocked(struct pthread *curthread,
-	struct pthread *thread)
+_thr_try_gc(struct pthread *curthread, struct pthread *thread)
 {
-	if (thread != NULL) {
-		thread->refcount--;
-		if ((thread->refcount == 0) && thread->state == PS_DEAD &&
-		    (thread->tlflags & TLFLAGS_DETACHED) != 0)
+	if (THR_SHOULD_GC(thread)) {
+		THR_REF_ADD(curthread, thread);
+		THR_THREAD_UNLOCK(curthread, thread);
+		THREAD_LIST_WRLOCK(curthread);
+		THR_THREAD_LOCK(curthread, thread);
+		THR_REF_DEL(curthread, thread);
+		if (THR_SHOULD_GC(thread)) {
+			THR_LIST_REMOVE(thread);
 			THR_GCLIST_ADD(thread);
-		THR_CRITICAL_LEAVE(curthread);
+		}
+		THR_THREAD_UNLOCK(curthread, thread);
+		THREAD_LIST_UNLOCK(curthread);
+	} else {
+		THR_THREAD_UNLOCK(curthread, thread);
 	}
 }
 
+/* return with thread lock held if thread is found */
 int
-_thr_find_thread(struct pthread *curthread __unused, struct pthread *thread,
+_thr_find_thread(struct pthread *curthread, struct pthread *thread,
     int include_dead)
 {
 	struct pthread *pthread;
+	int ret;
 
 	if (thread == NULL)
-		/* Invalid thread: */
 		return (EINVAL);
 
+	ret = 0;
+	THREAD_LIST_RDLOCK(curthread);
 	pthread = _thr_hash_find(thread);
 	if (pthread) {
+		THR_THREAD_LOCK(curthread, pthread);
 		if (include_dead == 0 && pthread->state == PS_DEAD) {
-			pthread = NULL;
-		}	
+			THR_THREAD_UNLOCK(curthread, pthread);
+			ret = ESRCH;
+		}
+	} else {
+		ret = ESRCH;
 	}
-
-	/* Return zero if the thread exists: */
-	return ((pthread != NULL) ? 0 : ESRCH);
+	THREAD_LIST_UNLOCK(curthread);
+	return (ret);
 }
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index a6bc205450f..bdf4aa4673f 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -415,13 +415,13 @@ struct pthread {
 #define THR_FLAGS_PRIVATE	0x0001
 #define	THR_FLAGS_NEED_SUSPEND	0x0002	/* thread should be suspended */
 #define	THR_FLAGS_SUSPENDED	0x0004	/* thread is suspended */
+#define	THR_FLAGS_IN_GCLIST	0x0004	/* thread in gc list */
+#define	THR_FLAGS_DETACHED	0x0008	/* thread is detached */
 
 	/* Thread list flags; only set with thread list lock held. */
 	int			tlflags;
 #define	TLFLAGS_GC_SAFE		0x0001	/* thread safe for cleaning */
 #define	TLFLAGS_IN_TDLIST	0x0002	/* thread in all thread list */
-#define	TLFLAGS_IN_GCLIST	0x0004	/* thread in gc list */
-#define	TLFLAGS_DETACHED	0x0008	/* thread is detached */
 
 	/* Queue of currently owned NORMAL or PRIO_INHERIT type mutexes. */
 	struct mutex_queue	mutexq;
@@ -463,6 +463,10 @@ struct pthread {
 	td_event_msg_t		event_buf;
 };
 
+#define THR_SHOULD_GC(thrd) 						\
+	((thrd)->refcount == 0 && (thrd)->state == PS_DEAD &&		\
+	 ((thrd)->flags & THR_FLAGS_DETACHED) != 0)
+
 #define	THR_IN_CRITICAL(thrd)				\
 	(((thrd)->locklevel > 0) ||			\
 	((thrd)->critical_count > 0))
@@ -517,14 +521,23 @@ do {							\
 #define	THR_THREAD_LOCK(curthrd, thr)	THR_LOCK_ACQUIRE(curthrd, &(thr)->lock)
 #define	THR_THREAD_UNLOCK(curthrd, thr)	THR_LOCK_RELEASE(curthrd, &(thr)->lock)
 
-#define	THREAD_LIST_LOCK(curthrd)				\
+#define	THREAD_LIST_RDLOCK(curthrd)				\
 do {								\
-	THR_LOCK_ACQUIRE((curthrd), &_thr_list_lock);		\
+	(curthrd)->locklevel++;					\
+	_thr_rwl_rdlock(&_thr_list_lock);			\
+} while (0)
+
+#define	THREAD_LIST_WRLOCK(curthrd)				\
+do {								\
+	(curthrd)->locklevel++;					\
+	_thr_rwl_wrlock(&_thr_list_lock);			\
 } while (0)
 
 #define	THREAD_LIST_UNLOCK(curthrd)				\
 do {								\
-	THR_LOCK_RELEASE((curthrd), &_thr_list_lock);		\
+	_thr_rwl_unlock(&_thr_list_lock);			\
+	(curthrd)->locklevel--;					\
+	_thr_ast(curthrd);					\
 } while (0)
 
 /*
@@ -546,20 +559,30 @@ do {								\
 	}							\
 } while (0)
 #define	THR_GCLIST_ADD(thrd) do {				\
-	if (((thrd)->tlflags & TLFLAGS_IN_GCLIST) == 0) {	\
+	if (((thrd)->flags & THR_FLAGS_IN_GCLIST) == 0) {	\
 		TAILQ_INSERT_HEAD(&_thread_gc_list, thrd, gcle);\
-		(thrd)->tlflags |= TLFLAGS_IN_GCLIST;		\
+		(thrd)->flags |= THR_FLAGS_IN_GCLIST;		\
 		_gc_count++;					\
 	}							\
 } while (0)
 #define	THR_GCLIST_REMOVE(thrd) do {				\
-	if (((thrd)->tlflags & TLFLAGS_IN_GCLIST) != 0) {	\
+	if (((thrd)->flags & THR_FLAGS_IN_GCLIST) != 0) {	\
 		TAILQ_REMOVE(&_thread_gc_list, thrd, gcle);	\
-		(thrd)->tlflags &= ~TLFLAGS_IN_GCLIST;		\
+		(thrd)->flags &= ~THR_FLAGS_IN_GCLIST;		\
 		_gc_count--;					\
 	}							\
 } while (0)
 
+#define THR_REF_ADD(curthread, pthread) {			\
+	THR_CRITICAL_ENTER(curthread);				\
+	pthread->refcount++;					\
+} while (0)
+
+#define THR_REF_DEL(curthread, pthread) {			\
+	pthread->refcount--;					\
+	THR_CRITICAL_LEAVE(curthread);				\
+} while (0)
+
 #define GC_NEEDED()	(_gc_count >= 5)
 
 #define SHOULD_REPORT_EVENT(curthr, e)			\
@@ -618,7 +641,7 @@ extern struct umutex	_mutex_static_lock __hidden;
 extern struct umutex	_cond_static_lock __hidden;
 extern struct umutex	_rwlock_static_lock __hidden;
 extern struct umutex	_keytable_lock __hidden;
-extern struct umutex	_thr_list_lock __hidden;
+extern struct urwlock	_thr_list_lock __hidden;
 extern struct umutex	_thr_event_lock __hidden;
 
 /*
@@ -673,6 +696,7 @@ int	_thr_setscheduler(lwpid_t, int, const struct sched_param *) __hidden;
 void	_thr_signal_prefork(void) __hidden;
 void	_thr_signal_postfork(void) __hidden;
 void	_thr_signal_postfork_child(void) __hidden;
+void	_thr_try_gc(struct pthread *, struct pthread *) __hidden;
 int	_rtp_to_schedparam(const struct rtprio *rtp, int *policy,
 		struct sched_param *param) __hidden;
 int	_schedparam_to_rtp(int policy, const struct sched_param *param,
diff --git a/lib/libthr/thread/thr_resume_np.c b/lib/libthr/thread/thr_resume_np.c
index 50b561ac877..a3066bc30ff 100644
--- a/lib/libthr/thread/thr_resume_np.c
+++ b/lib/libthr/thread/thr_resume_np.c
@@ -50,12 +50,10 @@ _pthread_resume_np(pthread_t thread)
 	int ret;
 
 	/* Add a reference to the thread: */
-	if ((ret = _thr_ref_add(curthread, thread, /*include dead*/0)) == 0) {
+	if ((ret = _thr_find_thread(curthread, thread, /*include dead*/0)) == 0) {
 		/* Lock the threads scheduling queue: */
-		THR_THREAD_LOCK(curthread, thread);
 		resume_common(thread);
 		THR_THREAD_UNLOCK(curthread, thread);
-		_thr_ref_delete(curthread, thread);
 	}
 	return (ret);
 }
@@ -67,7 +65,7 @@ _pthread_resume_all_np(void)
 	struct pthread *thread;
 
 	/* Take the thread list lock: */
-	THREAD_LIST_LOCK(curthread);
+	THREAD_LIST_RDLOCK(curthread);
 
 	TAILQ_FOREACH(thread, &_thread_list, tle) {
 		if (thread != curthread) {
diff --git a/lib/libthr/thread/thr_stack.c b/lib/libthr/thread/thr_stack.c
index 9376086552d..76849530159 100644
--- a/lib/libthr/thread/thr_stack.c
+++ b/lib/libthr/thread/thr_stack.c
@@ -154,7 +154,7 @@ _thr_stack_alloc(struct pthread_attr *attr)
 	 * Use the garbage collector lock for synchronization of the
 	 * spare stack lists and allocations from usrstack.
 	 */
-	THREAD_LIST_LOCK(curthread);
+	THREAD_LIST_WRLOCK(curthread);
 	/*
 	 * If the stack and guard sizes are default, try to allocate a stack
 	 * from the default-size stack cache:
diff --git a/lib/libthr/thread/thr_suspend_np.c b/lib/libthr/thread/thr_suspend_np.c
index 7d4a2e231bb..d5868e86b95 100644
--- a/lib/libthr/thread/thr_suspend_np.c
+++ b/lib/libthr/thread/thr_suspend_np.c
@@ -76,7 +76,7 @@ _pthread_suspend_all_np(void)
 	struct pthread *thread;
 	int ret;
 
-	THREAD_LIST_LOCK(curthread);
+	THREAD_LIST_RDLOCK(curthread);
 
 	TAILQ_FOREACH(thread, &_thread_list, tle) {
 		if (thread != curthread) {
@@ -96,13 +96,15 @@ restart:
 			THR_THREAD_LOCK(curthread, thread);
 			ret = suspend_common(curthread, thread, 0);
 			if (ret == 0) {
-				/* Can not suspend, try to wait */
-				thread->refcount++;
 				THREAD_LIST_UNLOCK(curthread);
+				/* Can not suspend, try to wait */
+				THR_REF_ADD(curthread, thread);
 				suspend_common(curthread, thread, 1);
-				THR_THREAD_UNLOCK(curthread, thread);
-				THREAD_LIST_LOCK(curthread);
-				_thr_ref_delete_unlocked(curthread, thread);
+				THR_REF_DEL(curthread, thread);
+				_thr_try_gc(curthread, thread);
+				/* thread lock released */
+
+				THREAD_LIST_RDLOCK(curthread);
 				/*
 				 * Because we were blocked, things may have
 				 * been changed, we have to restart the
@@ -127,8 +129,8 @@ suspend_common(struct pthread *curthread, struct pthread *thread,
 	      !(thread->flags & THR_FLAGS_SUSPENDED)) {
 		thread->flags |= THR_FLAGS_NEED_SUSPEND;
 		tmp = thread->cycle;
-		THR_THREAD_UNLOCK(curthread, thread);
 		_thr_send_sig(thread, SIGCANCEL);
+		THR_THREAD_UNLOCK(curthread, thread);
 		if (waitok) {
 			_thr_umtx_wait_uint(&thread->cycle, tmp, NULL, 0);
 			THR_THREAD_LOCK(curthread, thread);

From 9117ce0c8885b725decbe9ad4adb8b2cd155c940 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 07:15:01 +0000
Subject: [PATCH 0688/1624] It turns out that TARGET_CPUARCH doesn't buy us
 much here, if anything, but costs us another copy of the transform.  Revert
 it.

# Maybe makefile.inc1 should set TARGET_CPUARCH for the cross-tools, but
# it doesn't now.  That would solve problems in other places too.

Submitted by:	jmallet@
---
 usr.sbin/crunch/crunchide/Makefile | 13 ++-----------
 1 file changed, 2 insertions(+), 11 deletions(-)

diff --git a/usr.sbin/crunch/crunchide/Makefile b/usr.sbin/crunch/crunchide/Makefile
index 34e5674420a..3e173e48608 100644
--- a/usr.sbin/crunch/crunchide/Makefile
+++ b/usr.sbin/crunch/crunchide/Makefile
@@ -3,14 +3,6 @@
 PROG=   crunchide
 SRCS=	crunchide.c
 
-# These assignments duplicate much of the functionality of
-# MACHINE_CPUARCH, but there's no easy way to export make functions...
-
-.if defined(TARGET_ARCH)
-TARGET_CPUARCH=${TARGET_ARCH:C/mipse[bl]/mips/:C/armeb/arm/}
-.else
-TARGET_CPUARCH=${MACHINE_CPUARCH}
-.endif
 TARGET_ARCH?=	${MACHINE_ARCH}
 
 .if ${TARGET_ARCH} == i386 && ${MACHINE_ARCH} == i386
@@ -18,9 +10,8 @@ CFLAGS+=-DNLIST_AOUT
 SRCS+=	exec_aout.c
 .endif
 
-# nb: TARGET_ARCH for powerpc64 is correct here
-.if ${TARGET_CPUARCH} == ia64 || ${TARGET_ARCH} == powerpc64 || \
-    ${TARGET_CPUARCH} == sparc64 || ${TARGET_CPUARCH} == amd64
+.if ${TARGET_ARCH} == ia64 || ${TARGET_ARCH} == powerpc64 || \
+    ${TARGET_ARCH} == sparc64 || ${TARGET_ARCH} == amd64
 CFLAGS+=-DNLIST_ELF64
 SRCS+=	exec_elf64.c
 exec_elf64.o: exec_elf32.c

From 3a0d123e5f334b97fb036e5f43398aec3e1e3f52 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 07:16:48 +0000
Subject: [PATCH 0689/1624] Use MACHINE_CPUARCH as appropriate Define
 __KLD_SHARED to be yes or no depending on if the target uses shared binaries
 for klds or not (this also eliminates 4 uses of MACHINE_ARCH).

---
 sys/conf/kmod.mk | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/sys/conf/kmod.mk b/sys/conf/kmod.mk
index 63f47486ec3..de4ba3696c9 100644
--- a/sys/conf/kmod.mk
+++ b/sys/conf/kmod.mk
@@ -81,6 +81,13 @@ OBJCOPY?=	objcopy
 
 .SUFFIXES: .out .o .c .cc .cxx .C .y .l .s .S
 
+# amd64 and mips use direct linking for kmod, all others use shared binaries
+.if ${MACHINE_CPUARCH} != amd64 && ${MACHINE_CPUARCH} != mips
+__KLD_SHARED=yes
+.else
+__KLD_SHARED=no
+.endif
+
 .if ${CC:T:Micc} == "icc"
 CFLAGS:=	${CFLAGS:C/(-x[^M^K^W]+)[MKW]+|-x[MKW]+/\1/}
 .else
@@ -128,15 +135,15 @@ CFLAGS+=	-fno-common
 LDFLAGS+=	-d -warn-common
 
 CFLAGS+=	${DEBUG_FLAGS}
-.if ${MACHINE_ARCH} == amd64
+.if ${MACHINE_CPUARCH} == amd64
 CFLAGS+=	-fno-omit-frame-pointer
 .endif
 
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_CPUARCH} == powerpc
 CFLAGS+=	-mlongcall -fno-omit-frame-pointer
 .endif
 
-.if ${MACHINE_ARCH} == "mips"
+.if ${MACHINE_CPUARCH} == mips
 CFLAGS+=	-G0 -fno-pic -mno-abicalls -mlong-calls
 .endif
 
@@ -190,7 +197,7 @@ ${PROG}.symbols: ${FULLPROG}
 	${OBJCOPY} --only-keep-debug ${FULLPROG} ${.TARGET}
 .endif
 
-.if ${MACHINE_ARCH} != amd64 && ${MACHINE_ARCH} != mips
+.if ${__KLD_SHARED} == yes
 ${FULLPROG}: ${KMOD}.kld
 	${LD} -Bshareable ${LDFLAGS} -o ${.TARGET} ${KMOD}.kld
 .if !defined(DEBUG_FLAGS)
@@ -203,7 +210,7 @@ EXPORT_SYMS?=	NO
 CLEANFILES+=	export_syms
 .endif
 
-.if ${MACHINE_ARCH} != amd64 && ${MACHINE_ARCH} != mips
+.if ${__KLD_SHARED} == yes
 ${KMOD}.kld: ${OBJS}
 .else
 ${FULLPROG}: ${OBJS}
@@ -223,8 +230,7 @@ ${FULLPROG}: ${OBJS}
 	    export_syms | xargs -J% ${OBJCOPY} % ${.TARGET}
 .endif
 .endif
-.if !defined(DEBUG_FLAGS) && \
-    (${MACHINE_ARCH} == amd64 || ${MACHINE_ARCH} == mips)
+.if !defined(DEBUG_FLAGS) && ${__KLD_SHARED} == no
 	${OBJCOPY} --strip-debug ${.TARGET}
 .endif
 

From b749a04db32fc52b86810fee215f2097ee02dcf1 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Mon, 13 Sep 2010 07:18:00 +0000
Subject: [PATCH 0690/1624] PS_DEAD state needs not be checked because
 _thr_find_thread() has already checked it.

---
 lib/libthr/thread/thr_affinity.c | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/lib/libthr/thread/thr_affinity.c b/lib/libthr/thread/thr_affinity.c
index ae43fcb2390..3f9322453f9 100644
--- a/lib/libthr/thread/thr_affinity.c
+++ b/lib/libthr/thread/thr_affinity.c
@@ -51,10 +51,6 @@ _pthread_setaffinity_np(pthread_t td, size_t cpusetsize, const cpuset_t *cpusetp
 		if (error == -1)
 			error = errno;
 	} else if ((error = _thr_find_thread(curthread, td, 0)) == 0) {
-		if (td->state == PS_DEAD) {
-			THR_THREAD_UNLOCK(curthread, td);
-			return (EINVAL);
-		}
 		tid = TID(td);
 		error = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, tid,
 			cpusetsize, cpusetp);

From 3c7f49dcf28dcb78fd219f420504e50518ccea48 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 07:22:14 +0000
Subject: [PATCH 0691/1624] Prefer MACHINE_CPUARCH to MACHINE_ARCH unless
 there's a good reason...

---
 share/mk/bsd.cpu.mk | 36 ++++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)

diff --git a/share/mk/bsd.cpu.mk b/share/mk/bsd.cpu.mk
index e3ad18b98d4..93d8bc483d1 100644
--- a/share/mk/bsd.cpu.mk
+++ b/share/mk/bsd.cpu.mk
@@ -6,18 +6,18 @@
 
 .if !defined(CPUTYPE) || empty(CPUTYPE)
 _CPUCFLAGS =
-. if ${MACHINE_ARCH} == "i386"
+. if ${MACHINE_CPUARCH} == "i386"
 MACHINE_CPU = i486
-. elif ${MACHINE_ARCH} == "amd64"
+. elif ${MACHINE_CPUARCH} == "amd64"
 MACHINE_CPU = amd64 sse2 sse mmx
-. elif ${MACHINE_ARCH} == "ia64"
+. elif ${MACHINE_CPUARCH} == "ia64"
 MACHINE_CPU = itanium
-. elif ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+. elif ${MACHINE_CPUARCH} == "powerpc"
 MACHINE_CPU = aim
-. elif ${MACHINE_ARCH} == "sparc64"
-. elif ${MACHINE_ARCH} == "arm"
+. elif ${MACHINE_CPUARCH} == "sparc64"
+. elif ${MACHINE_CPUARCH} == "arm"
 MACHINE_CPU = arm
-. elif ${MACHINE_ARCH} == "mips"
+. elif ${MACHINE_CPUARCH} == "mips"
 MACHINE_CPU = mips
 . endif
 .else
@@ -25,7 +25,7 @@ MACHINE_CPU = mips
 # Handle aliases (not documented in make.conf to avoid user confusion
 # between e.g. i586 and pentium)
 
-. if ${MACHINE_ARCH} == "i386"
+. if ${MACHINE_CPUARCH} == "i386"
 .  if ${CPUTYPE} == "nocona"
 CPUTYPE = prescott
 .  elif ${CPUTYPE} == "core" || ${CPUTYPE} == "core2"
@@ -54,7 +54,7 @@ CPUTYPE = athlon-mp
 .  elif ${CPUTYPE} == "k7"
 CPUTYPE = athlon
 .  endif
-. elif ${MACHINE_ARCH} == "amd64"
+. elif ${MACHINE_CPUARCH} == "amd64"
 .  if ${CPUTYPE} == "prescott" || ${CPUTYPE} == "core2"
 CPUTYPE = nocona
 .  endif
@@ -71,7 +71,7 @@ CPUTYPE = nocona
 #	http://gcc.gnu.org/onlinedocs/gcc/SPARC-Options.html
 #	http://gcc.gnu.org/onlinedocs/gcc/i386-and-x86_002d64-Options.html
 
-. if ${MACHINE_ARCH} == "i386"
+. if ${MACHINE_CPUARCH} == "i386"
 .  if ${CPUTYPE} == "crusoe"
 _CPUCFLAGS = -march=i686 -falign-functions=0 -falign-jumps=0 -falign-loops=0
 .  elif ${CPUTYPE} == "k5"
@@ -104,9 +104,9 @@ _ICC_CPUCFLAGS = -tpp5
 .  else
 _ICC_CPUCFLAGS =
 .  endif # ICC on 'i386'
-. elif ${MACHINE_ARCH} == "amd64"
+. elif ${MACHINE_CPUARCH} == "amd64"
 _CPUCFLAGS = -march=${CPUTYPE}
-. elif ${MACHINE_ARCH} == "arm"
+. elif ${MACHINE_CPUARCH} == "arm"
 .  if ${CPUTYPE} == "xscale"
 #XXX: gcc doesn't seem to like -mcpu=xscale, and dies while rebuilding itself
 #_CPUCFLAGS = -mcpu=xscale
@@ -123,7 +123,7 @@ _CPUCFLAGS = -mcpu=${CPUTYPE} -mno-powerpc64
 .  endif
 . elif ${MACHINE_ARCH} == "powerpc64"
 _CPUCFLAGS = -mcpu=${CPUTYPE}
-. elif ${MACHINE_ARCH} == "mips"
+. elif ${MACHINE_CPUARCH} == "mips"
 .  if ${CPUTYPE} == "mips32"
 _CPUCFLAGS = -march=mips32
 .  elif ${CPUTYPE} == "mips32r2"
@@ -143,7 +143,7 @@ _CPUCFLAGS = -march=24kc
 # unordered list to make it easy for client makefiles to test for the
 # presence of a CPU feature.
 
-. if ${MACHINE_ARCH} == "i386"
+. if ${MACHINE_CPUARCH} == "i386"
 .  if ${CPUTYPE} == "opteron" || ${CPUTYPE} == "athlon64"
 MACHINE_CPU = athlon-xp athlon k7 3dnow sse2 sse mmx k6 k5 i586 i486 i386
 .  elif ${CPUTYPE} == "athlon-mp" || ${CPUTYPE} == "athlon-xp" || \
@@ -182,27 +182,27 @@ MACHINE_CPU = i486 i386
 .  elif ${CPUTYPE} == "i386"
 MACHINE_CPU = i386
 .  endif
-. elif ${MACHINE_ARCH} == "amd64"
+. elif ${MACHINE_CPUARCH} == "amd64"
 .  if ${CPUTYPE} == "opteron" || ${CPUTYPE} == "athlon64" || ${CPUTYPE} == "k8"
 MACHINE_CPU = k8 3dnow
 .  elif ${CPUTYPE} == "nocona"
 MACHINE_CPU = sse3
 .  endif
 MACHINE_CPU += amd64 sse2 sse mmx
-. elif ${MACHINE_ARCH} == "ia64"
+. elif ${MACHINE_CPUARCH} == "ia64"
 .  if ${CPUTYPE} == "itanium"
 MACHINE_CPU = itanium
 .  endif
 . endif
 .endif
 
-.if ${MACHINE_ARCH} == "arm" && defined(TARGET_BIG_ENDIAN)
+.if ${MACHINE_CPUARCH} == "arm" && defined(TARGET_BIG_ENDIAN)
 CFLAGS += -mbig-endian
 LDFLAGS += -mbig-endian
 LD += -EB
 .endif
 
-.if ${MACHINE_ARCH} == "mips" 
+.if ${MACHINE_CPUARCH} == "mips" 
 CFLAGS += -G0
 .endif
 

From a157e42516dcee534177e5e0dc59815c3334d647 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Mon, 13 Sep 2010 07:25:35 +0000
Subject: [PATCH 0692/1624] Refactor timer management code with priority to
 one-shot operation mode. The main goal of this is to generate timer
 interrupts only when there is some work to do. When CPU is busy interrupts
 are generating at full rate of hz + stathz to fullfill scheduler and
 timekeeping requirements. But when CPU is idle, only minimum set of
 interrupts (down to 8 interrupts per second per CPU now), needed to handle
 scheduled callouts is executed. This allows significantly increase idle CPU
 sleep time, increasing effect of static power-saving technologies. Also it
 should reduce host CPU load on virtualized systems, when guest system is
 idle.

There is set of tunables, also available as writable sysctls, allowing to
control wanted event timer subsystem behavior:
  kern.eventtimer.timer - allows to choose event timer hardware to use.
On x86 there is up to 4 different kinds of timers. Depending on whether
chosen timer is per-CPU, behavior of other options slightly differs.
  kern.eventtimer.periodic - allows to choose periodic and one-shot
operation mode. In periodic mode, current timer hardware taken as the only
source of time for time events. This mode is quite alike to previous kernel
behavior. One-shot mode instead uses currently selected time counter
hardware to schedule all needed events one by one and program timer to
generate interrupt exactly in specified time. Default value depends of
chosen timer capabilities, but one-shot mode is preferred, until other is
forced by user or hardware.
  kern.eventtimer.singlemul - in periodic mode specifies how much times
higher timer frequency should be, to not strictly alias hardclock() and
statclock() events. Default values are 2 and 4, but could be reduced to 1
if extra interrupts are unwanted.
  kern.eventtimer.idletick - makes each CPU to receive every timer interrupt
independently of whether they busy or not. By default this options is
disabled. If chosen timer is per-CPU and runs in periodic mode, this option
has no effect - all interrupts are generating.

As soon as this patch modifies cpu_idle() on some platforms, I have also
refactored one on x86. Now it makes use of MONITOR/MWAIT instrunctions
(if supported) under high sleep/wakeup rate, as fast alternative to other
methods. It allows SMP scheduler to wake up sleeping CPUs much faster
without using IPI, significantly increasing performance on some highly
task-switching loads.

Tested by:	many (on i386, amd64, sparc64 and powerc)
H/W donated by:	Gheorghe Ardelean
Sponsored by:	iXsystems, Inc.
---
 sys/amd64/amd64/machdep.c          | 246 ++++----
 sys/amd64/amd64/mp_machdep.c       |  24 +-
 sys/amd64/include/apicvar.h        |   3 +-
 sys/dev/acpica/acpi_cpu.c          |  18 +-
 sys/dev/acpica/acpi_hpet.c         |   6 +-
 sys/i386/i386/machdep.c            | 266 ++++-----
 sys/i386/i386/mp_machdep.c         |  24 +-
 sys/i386/include/apicvar.h         |   6 +-
 sys/kern/kern_clock.c              | 140 +++--
 sys/kern/kern_clocksource.c        | 895 ++++++++++++++++++++---------
 sys/kern/kern_et.c                 |   2 +-
 sys/kern/kern_tc.c                 |  18 +-
 sys/kern/kern_timeout.c            |  39 +-
 sys/kern/sched_4bsd.c              |   2 +-
 sys/kern/sched_ule.c               |   8 +-
 sys/mips/include/smp.h             |   1 -
 sys/mips/mips/mp_machdep.c         |   6 +-
 sys/pc98/pc98/machdep.c            | 139 +++--
 sys/powerpc/aim/machdep.c          |  12 +
 sys/powerpc/booke/machdep.c        |  12 +
 sys/powerpc/include/smp.h          |   1 -
 sys/powerpc/powerpc/mp_machdep.c   |   2 +-
 sys/sparc64/include/intr_machdep.h |   1 -
 sys/sparc64/include/smp.h          |   1 -
 sys/sparc64/sparc64/intr_machdep.c |   3 +-
 sys/sparc64/sparc64/mp_machdep.c   |  21 +-
 sys/sun4v/include/intr_machdep.h   |   1 -
 sys/sun4v/include/smp.h            |   2 -
 sys/sun4v/sun4v/intr_machdep.c     |   4 +-
 sys/sun4v/sun4v/mp_machdep.c       |  19 +-
 sys/sys/callout.h                  |   3 +-
 sys/sys/sched.h                    |   2 +-
 sys/sys/systm.h                    |  10 +-
 sys/sys/timeet.h                   |   4 +-
 sys/sys/timetc.h                   |   1 +
 sys/x86/x86/local_apic.c           |   2 +-
 36 files changed, 1207 insertions(+), 737 deletions(-)

diff --git a/sys/amd64/amd64/machdep.c b/sys/amd64/amd64/machdep.c
index fe6860084f9..00182db80fa 100644
--- a/sys/amd64/amd64/machdep.c
+++ b/sys/amd64/amd64/machdep.c
@@ -585,59 +585,89 @@ cpu_halt(void)
 }
 
 void (*cpu_idle_hook)(void) = NULL;	/* ACPI idle hook. */
+static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
+static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
+TUNABLE_INT("machdep.idle_mwait", &idle_mwait);
+SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RW, &idle_mwait,
+    0, "Use MONITOR/MWAIT for short idle");
 
-static void
-cpu_idle_hlt(int busy)
-{
-	/*
-	 * we must absolutely guarentee that hlt is the next instruction
-	 * after sti or we introduce a timing window.
-	 */
-	disable_intr();
-  	if (sched_runnable())
-		enable_intr();
-	else
-		__asm __volatile("sti; hlt");
-}
+#define	STATE_RUNNING	0x0
+#define	STATE_MWAIT	0x1
+#define	STATE_SLEEPING	0x2
 
 static void
 cpu_idle_acpi(int busy)
 {
+	int *state;
+
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_SLEEPING;
 	disable_intr();
-  	if (sched_runnable())
+	if (sched_runnable())
 		enable_intr();
 	else if (cpu_idle_hook)
 		cpu_idle_hook();
 	else
 		__asm __volatile("sti; hlt");
+	*state = STATE_RUNNING;
 }
 
-static int cpu_ident_amdc1e = 0;
-
-static int
-cpu_probe_amdc1e(void)
+static void
+cpu_idle_hlt(int busy)
 {
+	int *state;
+
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_SLEEPING;
+	/*
+	 * We must absolutely guarentee that hlt is the next instruction
+	 * after sti or we introduce a timing window.
+	 */
+	disable_intr();
+	if (sched_runnable())
+		enable_intr();
+	else
+		__asm __volatile("sti; hlt");
+	*state = STATE_RUNNING;
+}
+
+/*
+ * MWAIT cpu power states.  Lower 4 bits are sub-states.
+ */
+#define	MWAIT_C0	0xf0
+#define	MWAIT_C1	0x00
+#define	MWAIT_C2	0x10
+#define	MWAIT_C3	0x20
+#define	MWAIT_C4	0x30
+
+static void
+cpu_idle_mwait(int busy)
+{
+	int *state;
+
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_MWAIT;
+	if (!sched_runnable()) {
+		cpu_monitor(state, 0, 0);
+		if (*state == STATE_MWAIT)
+			cpu_mwait(0, MWAIT_C1);
+	}
+	*state = STATE_RUNNING;
+}
+
+static void
+cpu_idle_spin(int busy)
+{
+	int *state;
 	int i;
 
-	/*
-	 * Forget it, if we're not using local APIC timer.
-	 */
-	if (resource_disabled("apic", 0) ||
-	    (resource_int_value("apic", 0, "clock", &i) == 0 && i == 0))
-		return (0);
-
-	/*
-	 * Detect the presence of C1E capability mostly on latest
-	 * dual-cores (or future) k8 family.
-	 */
-	if (cpu_vendor_id == CPU_VENDOR_AMD &&
-	    (cpu_id & 0x00000f00) == 0x00000f00 &&
-	    (cpu_id & 0x0fff0000) >=  0x00040000) {
-		cpu_ident_amdc1e = 1;
-		return (1);
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_RUNNING;
+	for (i = 0; i < 1000; i++) {
+		if (sched_runnable())
+			return;
+		cpu_spinwait();
 	}
-
-	return (0);
 }
 
 /*
@@ -655,110 +685,83 @@ cpu_probe_amdc1e(void)
 #define	AMDK8_CMPHALT		(AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
 
 static void
-cpu_idle_amdc1e(int busy)
+cpu_probe_amdc1e(void)
 {
 
-	disable_intr();
-	if (sched_runnable())
-		enable_intr();
-	else {
-		uint64_t msr;
-
-		msr = rdmsr(MSR_AMDK8_IPM);
-		if (msr & AMDK8_CMPHALT)
-			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
-
-		if (cpu_idle_hook)
-			cpu_idle_hook();
-		else
-			__asm __volatile("sti; hlt");
+	/*
+	 * Detect the presence of C1E capability mostly on latest
+	 * dual-cores (or future) k8 family.
+	 */
+	if (cpu_vendor_id == CPU_VENDOR_AMD &&
+	    (cpu_id & 0x00000f00) == 0x00000f00 &&
+	    (cpu_id & 0x0fff0000) >=  0x00040000) {
+		cpu_ident_amdc1e = 1;
 	}
 }
 
-static void
-cpu_idle_spin(int busy)
-{
-	return;
-}
-
 void (*cpu_idle_fn)(int) = cpu_idle_acpi;
 
 void
 cpu_idle(int busy)
 {
+	uint64_t msr;
+
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
+	    busy, curcpu);
 #ifdef SMP
 	if (mp_grab_cpu_hlt())
 		return;
 #endif
-	cpu_idle_fn(busy);
-}
-
-/*
- * mwait cpu power states.  Lower 4 bits are sub-states.
- */
-#define	MWAIT_C0	0xf0
-#define	MWAIT_C1	0x00
-#define	MWAIT_C2	0x10
-#define	MWAIT_C3	0x20
-#define	MWAIT_C4	0x30
-
-#define	MWAIT_DISABLED	0x0
-#define	MWAIT_WOKEN	0x1
-#define	MWAIT_WAITING	0x2
-
-static void
-cpu_idle_mwait(int busy)
-{
-	int *mwait;
-
-	mwait = (int *)PCPU_PTR(monitorbuf);
-	*mwait = MWAIT_WAITING;
-	if (sched_runnable())
-		return;
-	cpu_monitor(mwait, 0, 0);
-	if (*mwait == MWAIT_WAITING)
-		cpu_mwait(0, MWAIT_C1);
-}
-
-static void
-cpu_idle_mwait_hlt(int busy)
-{
-	int *mwait;
-
-	mwait = (int *)PCPU_PTR(monitorbuf);
-	if (busy == 0) {
-		*mwait = MWAIT_DISABLED;
-		cpu_idle_hlt(busy);
-		return;
+	/* If we are busy - try to use fast methods. */
+	if (busy) {
+		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
+			cpu_idle_mwait(busy);
+			goto out;
+		}
 	}
-	*mwait = MWAIT_WAITING;
-	if (sched_runnable())
-		return;
-	cpu_monitor(mwait, 0, 0);
-	if (*mwait == MWAIT_WAITING)
-		cpu_mwait(0, MWAIT_C1);
+
+	/* If we have time - switch timers into idle mode. */
+	if (!busy) {
+		critical_enter();
+		cpu_idleclock();
+	}
+
+	/* Apply AMD APIC timer C1E workaround. */
+	if (cpu_ident_amdc1e && cpu_disable_deep_sleep) {
+		msr = rdmsr(MSR_AMDK8_IPM);
+		if (msr & AMDK8_CMPHALT)
+			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
+	}
+
+	/* Call main idle method. */
+	cpu_idle_fn(busy);
+
+	/* Switch timers mack into active mode. */
+	if (!busy) {
+		cpu_activeclock();
+		critical_exit();
+	}
+out:
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
+	    busy, curcpu);
 }
 
 int
 cpu_idle_wakeup(int cpu)
 {
 	struct pcpu *pcpu;
-	int *mwait;
+	int *state;
 
-	if (cpu_idle_fn == cpu_idle_spin)
-		return (1);
-	if (cpu_idle_fn != cpu_idle_mwait && cpu_idle_fn != cpu_idle_mwait_hlt)
-		return (0);
 	pcpu = pcpu_find(cpu);
-	mwait = (int *)pcpu->pc_monitorbuf;
+	state = (int *)pcpu->pc_monitorbuf;
 	/*
 	 * This doesn't need to be atomic since missing the race will
 	 * simply result in unnecessary IPIs.
 	 */
-	if (cpu_idle_fn == cpu_idle_mwait_hlt && *mwait == MWAIT_DISABLED)
+	if (*state == STATE_SLEEPING)
 		return (0);
-	*mwait = MWAIT_WOKEN;
-
+	if (*state == STATE_MWAIT)
+		*state = STATE_RUNNING;
 	return (1);
 }
 
@@ -771,8 +774,6 @@ struct {
 } idle_tbl[] = {
 	{ cpu_idle_spin, "spin" },
 	{ cpu_idle_mwait, "mwait" },
-	{ cpu_idle_mwait_hlt, "mwait_hlt" },
-	{ cpu_idle_amdc1e, "amdc1e" },
 	{ cpu_idle_hlt, "hlt" },
 	{ cpu_idle_acpi, "acpi" },
 	{ NULL, NULL }
@@ -791,8 +792,8 @@ idle_sysctl_available(SYSCTL_HANDLER_ARGS)
 		if (strstr(idle_tbl[i].id_name, "mwait") &&
 		    (cpu_feature2 & CPUID2_MON) == 0)
 			continue;
-		if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
-		    cpu_ident_amdc1e == 0)
+		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
+		    cpu_idle_hook == NULL)
 			continue;
 		p += sprintf(p, "%s, ", idle_tbl[i].id_name);
 	}
@@ -801,6 +802,9 @@ idle_sysctl_available(SYSCTL_HANDLER_ARGS)
 	return (error);
 }
 
+SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
+    0, 0, idle_sysctl_available, "A", "list of available idle functions");
+
 static int
 idle_sysctl(SYSCTL_HANDLER_ARGS)
 {
@@ -824,8 +828,8 @@ idle_sysctl(SYSCTL_HANDLER_ARGS)
 		if (strstr(idle_tbl[i].id_name, "mwait") &&
 		    (cpu_feature2 & CPUID2_MON) == 0)
 			continue;
-		if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
-		    cpu_ident_amdc1e == 0)
+		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
+		    cpu_idle_hook == NULL)
 			continue;
 		if (strcmp(idle_tbl[i].id_name, buf))
 			continue;
@@ -835,9 +839,6 @@ idle_sysctl(SYSCTL_HANDLER_ARGS)
 	return (EINVAL);
 }
 
-SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
-    0, 0, idle_sysctl_available, "A", "list of available idle functions");
-
 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
     idle_sysctl, "A", "currently selected idle function");
 
@@ -1743,8 +1744,7 @@ hammer_time(u_int64_t modulep, u_int64_t physfree)
 	}
 #endif
 
-	if (cpu_probe_amdc1e())
-		cpu_idle_fn = cpu_idle_amdc1e;
+	cpu_probe_amdc1e();
 
 	/* Location of kernel stack for locore */
 	return ((u_int64_t)thread0.td_pcb);
diff --git a/sys/amd64/amd64/mp_machdep.c b/sys/amd64/amd64/mp_machdep.c
index e2f82ec282e..49b380bd6da 100644
--- a/sys/amd64/amd64/mp_machdep.c
+++ b/sys/amd64/amd64/mp_machdep.c
@@ -118,7 +118,6 @@ u_long *ipi_invlcache_counts[MAXCPU];
 u_long *ipi_rendezvous_counts[MAXCPU];
 u_long *ipi_lazypmap_counts[MAXCPU];
 static u_long *ipi_hardclock_counts[MAXCPU];
-static u_long *ipi_statclock_counts[MAXCPU];
 #endif
 
 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
@@ -1196,16 +1195,22 @@ smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
 void
 ipi_bitmap_handler(struct trapframe frame)
 {
+	struct trapframe *oldframe;
+	struct thread *td;
 	int cpu = PCPU_GET(cpuid);
 	u_int ipi_bitmap;
 
+	critical_enter();
+	td = curthread;
+	td->td_intr_nesting_level++;
+	oldframe = td->td_intr_frame;
+	td->td_intr_frame = &frame;
 	ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
-
 	if (ipi_bitmap & (1 << IPI_PREEMPT)) {
 #ifdef COUNT_IPIS
 		(*ipi_preempt_counts[cpu])++;
 #endif
-		sched_preempt(curthread);
+		sched_preempt(td);
 	}
 	if (ipi_bitmap & (1 << IPI_AST)) {
 #ifdef COUNT_IPIS
@@ -1217,14 +1222,11 @@ ipi_bitmap_handler(struct trapframe frame)
 #ifdef COUNT_IPIS
 		(*ipi_hardclock_counts[cpu])++;
 #endif
-		hardclockintr(&frame);
-	}
-	if (ipi_bitmap & (1 << IPI_STATCLOCK)) {
-#ifdef COUNT_IPIS
-		(*ipi_statclock_counts[cpu])++;
-#endif
-		statclockintr(&frame);
+		hardclockintr();
 	}
+	td->td_intr_frame = oldframe;
+	td->td_intr_nesting_level--;
+	critical_exit();
 }
 
 /*
@@ -1579,8 +1581,6 @@ mp_ipi_intrcnt(void *dummy)
 		intrcnt_add(buf, &ipi_lazypmap_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
 		intrcnt_add(buf, &ipi_hardclock_counts[i]);
-		snprintf(buf, sizeof(buf), "cpu%d:statclock", i);
-		intrcnt_add(buf, &ipi_statclock_counts[i]);
 	}
 }
 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);
diff --git a/sys/amd64/include/apicvar.h b/sys/amd64/include/apicvar.h
index 2ebf7c2582f..ae2f5b90791 100644
--- a/sys/amd64/include/apicvar.h
+++ b/sys/amd64/include/apicvar.h
@@ -123,8 +123,7 @@
 #define	IPI_AST		0 	/* Generate software trap. */
 #define IPI_PREEMPT     1
 #define IPI_HARDCLOCK   2
-#define IPI_STATCLOCK   3
-#define IPI_BITMAP_LAST IPI_STATCLOCK
+#define IPI_BITMAP_LAST IPI_HARDCLOCK
 #define IPI_IS_BITMAPED(x) ((x) <= IPI_BITMAP_LAST)
 
 #define	IPI_STOP	(APIC_IPI_INTS + 7)	/* Stop CPU until restarted. */
diff --git a/sys/dev/acpica/acpi_cpu.c b/sys/dev/acpica/acpi_cpu.c
index 5dd6ab97f7e..fabbee90d1c 100644
--- a/sys/dev/acpica/acpi_cpu.c
+++ b/sys/dev/acpica/acpi_cpu.c
@@ -900,7 +900,13 @@ acpi_cpu_idle()
 
     /* Find the lowest state that has small enough latency. */
     cx_next_idx = 0;
-    for (i = sc->cpu_cx_lowest; i >= 0; i--) {
+#ifndef __ia64__
+    if (cpu_disable_deep_sleep)
+	i = sc->cpu_non_c3;
+    else
+#endif
+	i = sc->cpu_cx_lowest;
+    for (; i >= 0; i--) {
 	if (sc->cpu_cx_states[i].trans_lat * 3 <= sc->cpu_prev_sleep) {
 	    cx_next_idx = i;
 	    break;
@@ -929,15 +935,17 @@ acpi_cpu_idle()
     /*
      * Execute HLT (or equivalent) and wait for an interrupt.  We can't
      * precisely calculate the time spent in C1 since the place we wake up
-     * is an ISR.  Assume we slept no more then half of quantum.
+     * is an ISR.  Assume we slept no more then half of quantum, unless
+     * we are called inside critical section, delaying context switch.
      */
     if (cx_next->type == ACPI_STATE_C1) {
 	AcpiHwRead(&start_time, &AcpiGbl_FADT.XPmTimerBlock);
 	acpi_cpu_c1();
 	AcpiHwRead(&end_time, &AcpiGbl_FADT.XPmTimerBlock);
-        end_time = acpi_TimerDelta(end_time, start_time);
-	sc->cpu_prev_sleep = (sc->cpu_prev_sleep * 3 +
-	    min(PM_USEC(end_time), 500000 / hz)) / 4;
+        end_time = PM_USEC(acpi_TimerDelta(end_time, start_time));
+        if (curthread->td_critnest == 0)
+		end_time = min(end_time, 500000 / hz);
+	sc->cpu_prev_sleep = (sc->cpu_prev_sleep * 3 + end_time) / 4;
 	return;
     }
 
diff --git a/sys/dev/acpica/acpi_hpet.c b/sys/dev/acpica/acpi_hpet.c
index 2a8eb301a09..f5cf11a0968 100644
--- a/sys/dev/acpica/acpi_hpet.c
+++ b/sys/dev/acpica/acpi_hpet.c
@@ -683,15 +683,15 @@ hpet_detach(device_t dev)
 static int
 hpet_suspend(device_t dev)
 {
-	struct hpet_softc *sc;
+//	struct hpet_softc *sc;
 
 	/*
 	 * Disable the timer during suspend.  The timer will not lose
 	 * its state in S1 or S2, but we are required to disable
 	 * it.
 	 */
-	sc = device_get_softc(dev);
-	hpet_disable(sc);
+//	sc = device_get_softc(dev);
+//	hpet_disable(sc);
 
 	return (0);
 }
diff --git a/sys/i386/i386/machdep.c b/sys/i386/i386/machdep.c
index ef229ca6f5b..2bf6dd155fd 100644
--- a/sys/i386/i386/machdep.c
+++ b/sys/i386/i386/machdep.c
@@ -1175,9 +1175,6 @@ cpu_est_clockrate(int cpu_id, uint64_t *rate)
 	return (0);
 }
 
-
-void (*cpu_idle_hook)(void) = NULL;	/* ACPI idle hook. */
-
 #ifdef XEN
 
 void
@@ -1208,60 +1205,94 @@ cpu_halt(void)
 		__asm__ ("hlt");
 }
 
-static void
-cpu_idle_hlt(int busy)
-{
-	/*
-	 * we must absolutely guarentee that hlt is the next instruction
-	 * after sti or we introduce a timing window.
-	 */
-	disable_intr();
-  	if (sched_runnable())
-		enable_intr();
-	else
-		__asm __volatile("sti; hlt");
-}
 #endif
 
+void (*cpu_idle_hook)(void) = NULL;	/* ACPI idle hook. */
+static int	cpu_ident_amdc1e = 0;	/* AMD C1E supported. */
+static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
+TUNABLE_INT("machdep.idle_mwait", &idle_mwait);
+SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RW, &idle_mwait,
+    0, "Use MONITOR/MWAIT for short idle");
+
+#define	STATE_RUNNING	0x0
+#define	STATE_MWAIT	0x1
+#define	STATE_SLEEPING	0x2
+
 static void
 cpu_idle_acpi(int busy)
 {
+	int *state;
+
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_SLEEPING;
 	disable_intr();
-  	if (sched_runnable())
+	if (sched_runnable())
 		enable_intr();
 	else if (cpu_idle_hook)
 		cpu_idle_hook();
 	else
 		__asm __volatile("sti; hlt");
+	*state = STATE_RUNNING;
 }
 
-static int cpu_ident_amdc1e = 0;
+#ifndef XEN
+static void
+cpu_idle_hlt(int busy)
+{
+	int *state;
 
-static int
-cpu_probe_amdc1e(void)
-{ 
-#ifdef DEV_APIC
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_SLEEPING;
+	/*
+	 * We must absolutely guarentee that hlt is the next instruction
+	 * after sti or we introduce a timing window.
+	 */
+	disable_intr();
+	if (sched_runnable())
+		enable_intr();
+	else
+		__asm __volatile("sti; hlt");
+	*state = STATE_RUNNING;
+}
+#endif
+
+/*
+ * MWAIT cpu power states.  Lower 4 bits are sub-states.
+ */
+#define	MWAIT_C0	0xf0
+#define	MWAIT_C1	0x00
+#define	MWAIT_C2	0x10
+#define	MWAIT_C3	0x20
+#define	MWAIT_C4	0x30
+
+static void
+cpu_idle_mwait(int busy)
+{
+	int *state;
+
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_MWAIT;
+	if (!sched_runnable()) {
+		cpu_monitor(state, 0, 0);
+		if (*state == STATE_MWAIT)
+			cpu_mwait(0, MWAIT_C1);
+	}
+	*state = STATE_RUNNING;
+}
+
+static void
+cpu_idle_spin(int busy)
+{
+	int *state;
 	int i;
 
-	/*
-	 * Forget it, if we're not using local APIC timer.
-	 */
-	if (resource_disabled("apic", 0) ||
-	    (resource_int_value("apic", 0, "clock", &i) == 0 && i == 0))
-		return (0);
-
-	/*
-	 * Detect the presence of C1E capability mostly on latest
-	 * dual-cores (or future) k8 family.
-	 */
-	if (cpu_vendor_id == CPU_VENDOR_AMD &&
-	    (cpu_id & 0x00000f00) == 0x00000f00 &&
-	    (cpu_id & 0x0fff0000) >=  0x00040000) {
-		cpu_ident_amdc1e = 1;
-		return (1);
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_RUNNING;
+	for (i = 0; i < 1000; i++) {
+		if (sched_runnable())
+			return;
+		cpu_spinwait();
 	}
-#endif
-	return (0);
 }
 
 /*
@@ -1279,32 +1310,20 @@ cpu_probe_amdc1e(void)
 #define	AMDK8_CMPHALT		(AMDK8_SMIONCMPHALT | AMDK8_C1EONCMPHALT)
 
 static void
-cpu_idle_amdc1e(int busy)
+cpu_probe_amdc1e(void)
 {
 
-	disable_intr();
-	if (sched_runnable())
-		enable_intr();
-	else {
-		uint64_t msr;
-
-		msr = rdmsr(MSR_AMDK8_IPM);
-		if (msr & AMDK8_CMPHALT)
-			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
-
-		if (cpu_idle_hook)
-			cpu_idle_hook();
-		else
-			__asm __volatile("sti; hlt");
+	/*
+	 * Detect the presence of C1E capability mostly on latest
+	 * dual-cores (or future) k8 family.
+	 */
+	if (cpu_vendor_id == CPU_VENDOR_AMD &&
+	    (cpu_id & 0x00000f00) == 0x00000f00 &&
+	    (cpu_id & 0x0fff0000) >=  0x00040000) {
+		cpu_ident_amdc1e = 1;
 	}
 }
 
-static void
-cpu_idle_spin(int busy)
-{
-	return;
-}
-
 #ifdef XEN
 void (*cpu_idle_fn)(int) = cpu_idle_hlt;
 #else
@@ -1314,79 +1333,72 @@ void (*cpu_idle_fn)(int) = cpu_idle_acpi;
 void
 cpu_idle(int busy)
 {
+	uint64_t msr;
+
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
+	    busy, curcpu);
 #if defined(SMP) && !defined(XEN)
 	if (mp_grab_cpu_hlt())
 		return;
 #endif
-	cpu_idle_fn(busy);
-}
-
-/*
- * mwait cpu power states.  Lower 4 bits are sub-states.
- */
-#define	MWAIT_C0	0xf0
-#define	MWAIT_C1	0x00
-#define	MWAIT_C2	0x10
-#define	MWAIT_C3	0x20
-#define	MWAIT_C4	0x30
-
-#define	MWAIT_DISABLED	0x0
-#define	MWAIT_WOKEN	0x1
-#define	MWAIT_WAITING	0x2
-
-static void
-cpu_idle_mwait(int busy)
-{
-	int *mwait;
-
-	mwait = (int *)PCPU_PTR(monitorbuf);
-	*mwait = MWAIT_WAITING;
-	if (sched_runnable())
-		return;
-	cpu_monitor(mwait, 0, 0);
-	if (*mwait == MWAIT_WAITING)
-		cpu_mwait(0, MWAIT_C1);
-}
-
-static void
-cpu_idle_mwait_hlt(int busy)
-{
-	int *mwait;
-
-	mwait = (int *)PCPU_PTR(monitorbuf);
-	if (busy == 0) {
-		*mwait = MWAIT_DISABLED;
-		cpu_idle_hlt(busy);
-		return;
+	/* If we are busy - try to use fast methods. */
+	if (busy) {
+		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
+			cpu_idle_mwait(busy);
+			goto out;
+		}
 	}
-	*mwait = MWAIT_WAITING;
-	if (sched_runnable())
-		return;
-	cpu_monitor(mwait, 0, 0);
-	if (*mwait == MWAIT_WAITING)
-		cpu_mwait(0, MWAIT_C1);
+
+#ifndef XEN
+	/* If we have time - switch timers into idle mode. */
+	if (!busy) {
+		critical_enter();
+		cpu_idleclock();
+	}
+#endif
+
+	/* Apply AMD APIC timer C1E workaround. */
+	if (cpu_ident_amdc1e
+#ifndef XEN
+	    && cpu_disable_deep_sleep
+#endif
+	    ) {
+		msr = rdmsr(MSR_AMDK8_IPM);
+		if (msr & AMDK8_CMPHALT)
+			wrmsr(MSR_AMDK8_IPM, msr & ~AMDK8_CMPHALT);
+	}
+
+	/* Call main idle method. */
+	cpu_idle_fn(busy);
+
+#ifndef XEN
+	/* Switch timers mack into active mode. */
+	if (!busy) {
+		cpu_activeclock();
+		critical_exit();
+	}
+#endif
+out:
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
+	    busy, curcpu);
 }
 
 int
 cpu_idle_wakeup(int cpu)
 {
 	struct pcpu *pcpu;
-	int *mwait;
+	int *state;
 
-	if (cpu_idle_fn == cpu_idle_spin)
-		return (1);
-	if (cpu_idle_fn != cpu_idle_mwait && cpu_idle_fn != cpu_idle_mwait_hlt)
-		return (0);
 	pcpu = pcpu_find(cpu);
-	mwait = (int *)pcpu->pc_monitorbuf;
+	state = (int *)pcpu->pc_monitorbuf;
 	/*
 	 * This doesn't need to be atomic since missing the race will
 	 * simply result in unnecessary IPIs.
 	 */
-	if (cpu_idle_fn == cpu_idle_mwait_hlt && *mwait == MWAIT_DISABLED)
+	if (*state == STATE_SLEEPING)
 		return (0);
-	*mwait = MWAIT_WOKEN;
-
+	if (*state == STATE_MWAIT)
+		*state = STATE_RUNNING;
 	return (1);
 }
 
@@ -1399,8 +1411,6 @@ struct {
 } idle_tbl[] = {
 	{ cpu_idle_spin, "spin" },
 	{ cpu_idle_mwait, "mwait" },
-	{ cpu_idle_mwait_hlt, "mwait_hlt" },
-	{ cpu_idle_amdc1e, "amdc1e" },
 	{ cpu_idle_hlt, "hlt" },
 	{ cpu_idle_acpi, "acpi" },
 	{ NULL, NULL }
@@ -1419,8 +1429,8 @@ idle_sysctl_available(SYSCTL_HANDLER_ARGS)
 		if (strstr(idle_tbl[i].id_name, "mwait") &&
 		    (cpu_feature2 & CPUID2_MON) == 0)
 			continue;
-		if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
-		    cpu_ident_amdc1e == 0)
+		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
+		    cpu_idle_hook == NULL)
 			continue;
 		p += sprintf(p, "%s, ", idle_tbl[i].id_name);
 	}
@@ -1429,6 +1439,9 @@ idle_sysctl_available(SYSCTL_HANDLER_ARGS)
 	return (error);
 }
 
+SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
+    0, 0, idle_sysctl_available, "A", "list of available idle functions");
+
 static int
 idle_sysctl(SYSCTL_HANDLER_ARGS)
 {
@@ -1452,8 +1465,8 @@ idle_sysctl(SYSCTL_HANDLER_ARGS)
 		if (strstr(idle_tbl[i].id_name, "mwait") &&
 		    (cpu_feature2 & CPUID2_MON) == 0)
 			continue;
-		if (strcmp(idle_tbl[i].id_name, "amdc1e") == 0 &&
-		    cpu_ident_amdc1e == 0)
+		if (strcmp(idle_tbl[i].id_name, "acpi") == 0 &&
+		    cpu_idle_hook == NULL)
 			continue;
 		if (strcmp(idle_tbl[i].id_name, buf))
 			continue;
@@ -1463,9 +1476,6 @@ idle_sysctl(SYSCTL_HANDLER_ARGS)
 	return (EINVAL);
 }
 
-SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
-    0, 0, idle_sysctl_available, "A", "list of available idle functions");
-
 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
     idle_sysctl, "A", "currently selected idle function");
 
@@ -2695,8 +2705,7 @@ init386(first)
 	thread0.td_pcb->pcb_fsd = PCPU_GET(fsgs_gdt)[0];
 	thread0.td_pcb->pcb_gsd = PCPU_GET(fsgs_gdt)[1];
 
-	if (cpu_probe_amdc1e())
-		cpu_idle_fn = cpu_idle_amdc1e;
+	cpu_probe_amdc1e();
 }
 
 #else
@@ -2970,8 +2979,7 @@ init386(first)
 	thread0.td_pcb->pcb_ext = 0;
 	thread0.td_frame = &proc0_tf;
 
-	if (cpu_probe_amdc1e())
-		cpu_idle_fn = cpu_idle_amdc1e;
+	cpu_probe_amdc1e();
 }
 #endif
 
diff --git a/sys/i386/i386/mp_machdep.c b/sys/i386/i386/mp_machdep.c
index fa50ecfe624..f660e1c8921 100644
--- a/sys/i386/i386/mp_machdep.c
+++ b/sys/i386/i386/mp_machdep.c
@@ -167,7 +167,6 @@ u_long *ipi_invlcache_counts[MAXCPU];
 u_long *ipi_rendezvous_counts[MAXCPU];
 u_long *ipi_lazypmap_counts[MAXCPU];
 static u_long *ipi_hardclock_counts[MAXCPU];
-static u_long *ipi_statclock_counts[MAXCPU];
 #endif
 
 /*
@@ -1284,16 +1283,22 @@ smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
 void
 ipi_bitmap_handler(struct trapframe frame)
 {
+	struct trapframe *oldframe;
+	struct thread *td;
 	int cpu = PCPU_GET(cpuid);
 	u_int ipi_bitmap;
 
+	critical_enter();
+	td = curthread;
+	td->td_intr_nesting_level++;
+	oldframe = td->td_intr_frame;
+	td->td_intr_frame = &frame;
 	ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
-
 	if (ipi_bitmap & (1 << IPI_PREEMPT)) {
 #ifdef COUNT_IPIS
 		(*ipi_preempt_counts[cpu])++;
 #endif
-		sched_preempt(curthread);
+		sched_preempt(td);
 	}
 	if (ipi_bitmap & (1 << IPI_AST)) {
 #ifdef COUNT_IPIS
@@ -1305,14 +1310,11 @@ ipi_bitmap_handler(struct trapframe frame)
 #ifdef COUNT_IPIS
 		(*ipi_hardclock_counts[cpu])++;
 #endif
-		hardclockintr(&frame); 
-	}
-	if (ipi_bitmap & (1 << IPI_STATCLOCK)) {
-#ifdef COUNT_IPIS
-		(*ipi_statclock_counts[cpu])++;
-#endif
-		statclockintr(&frame); 
+		hardclockintr();
 	}
+	td->td_intr_frame = oldframe;
+	td->td_intr_nesting_level--;
+	critical_exit();
 }
 
 /*
@@ -1627,8 +1629,6 @@ mp_ipi_intrcnt(void *dummy)
 		intrcnt_add(buf, &ipi_lazypmap_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
 		intrcnt_add(buf, &ipi_hardclock_counts[i]);
-		snprintf(buf, sizeof(buf), "cpu%d:statclock", i);
-		intrcnt_add(buf, &ipi_statclock_counts[i]);
 	}		
 }
 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);
diff --git a/sys/i386/include/apicvar.h b/sys/i386/include/apicvar.h
index cada0173f75..ff1f6577272 100644
--- a/sys/i386/include/apicvar.h
+++ b/sys/i386/include/apicvar.h
@@ -124,8 +124,7 @@
 #define	IPI_AST		0 	/* Generate software trap. */
 #define IPI_PREEMPT     1
 #define IPI_HARDCLOCK   2 
-#define IPI_STATCLOCK   3 
-#define IPI_BITMAP_LAST IPI_STATCLOCK
+#define IPI_BITMAP_LAST IPI_HARDCLOCK
 #define IPI_IS_BITMAPED(x) ((x) <= IPI_BITMAP_LAST)
 
 #define	IPI_STOP	(APIC_IPI_INTS + 7)	/* Stop CPU until restarted. */
@@ -152,8 +151,7 @@
 #define	IPI_AST		0 	/* Generate software trap. */
 #define IPI_PREEMPT     1
 #define IPI_HARDCLOCK   2 
-#define IPI_STATCLOCK   3 
-#define IPI_BITMAP_LAST IPI_STATCLOCK
+#define IPI_BITMAP_LAST IPI_HARDCLOCK
 #define IPI_IS_BITMAPED(x) ((x) <= IPI_BITMAP_LAST)
 
 #define	IPI_STOP	(APIC_IPI_INTS + 7)	/* Stop CPU until restarted. */
diff --git a/sys/kern/kern_clock.c b/sys/kern/kern_clock.c
index c283b6b1e6a..ff5747e104c 100644
--- a/sys/kern/kern_clock.c
+++ b/sys/kern/kern_clock.c
@@ -373,11 +373,9 @@ int	profprocs;
 int	ticks;
 int	psratio;
 
-int	timer1hz;
-int	timer2hz;
-static DPCPU_DEFINE(u_int, hard_cnt);
-static DPCPU_DEFINE(u_int, stat_cnt);
-static DPCPU_DEFINE(u_int, prof_cnt);
+static DPCPU_DEFINE(int, pcputicks);	/* Per-CPU version of ticks. */
+static struct mtx	global_hardclock_mtx;
+MTX_SYSINIT(global_hardclock_mtx, &global_hardclock_mtx, "ghc_mtx", MTX_SPIN);
 
 /*
  * Initialize clock frequencies and start both clocks running.
@@ -408,52 +406,6 @@ initclocks(dummy)
 #endif
 }
 
-void
-timer1clock(int usermode, uintfptr_t pc)
-{
-	u_int *cnt;
-
-	cnt = DPCPU_PTR(hard_cnt);
-	*cnt += hz;
-	if (*cnt >= timer1hz) {
-		*cnt -= timer1hz;
-		if (*cnt >= timer1hz)
-			*cnt = 0;
-		if (PCPU_GET(cpuid) == 0)
-			hardclock(usermode, pc);
-		else
-			hardclock_cpu(usermode);
-	}
-	if (timer2hz == 0)
-		timer2clock(usermode, pc);
-}
-
-void
-timer2clock(int usermode, uintfptr_t pc)
-{
-	u_int *cnt;
-	int t2hz = timer2hz ? timer2hz : timer1hz;
-
-	cnt = DPCPU_PTR(stat_cnt);
-	*cnt += stathz;
-	if (*cnt >= t2hz) {
-		*cnt -= t2hz;
-		if (*cnt >= t2hz)
-			*cnt = 0;
-		statclock(usermode);
-	}
-	if (profprocs == 0)
-		return;
-	cnt = DPCPU_PTR(prof_cnt);
-	*cnt += profhz;
-	if (*cnt >= t2hz) {
-		*cnt -= t2hz;
-		if (*cnt >= t2hz)
-			*cnt = 0;
-		profclock(usermode, pc);
-	}
-}
-
 /*
  * Each time the real-time timer fires, this function is called on all CPUs.
  * Note that hardclock() calls hardclock_cpu() for the boot CPU, so only
@@ -486,7 +438,7 @@ hardclock_cpu(int usermode)
 		PROC_SUNLOCK(p);
 	}
 	thread_lock(td);
-	sched_tick();
+	sched_tick(1);
 	td->td_flags |= flags;
 	thread_unlock(td);
 
@@ -507,6 +459,7 @@ hardclock(int usermode, uintfptr_t pc)
 	atomic_add_int((volatile int *)&ticks, 1);
 	hardclock_cpu(usermode);
 	tc_ticktock();
+	cpu_tick_calibration();
 	/*
 	 * If no separate statistics clock is available, run it from here.
 	 *
@@ -525,6 +478,89 @@ hardclock(int usermode, uintfptr_t pc)
 #endif /* SW_WATCHDOG */
 }
 
+void
+hardclock_anycpu(int cnt, int usermode)
+{
+	struct pstats *pstats;
+	struct thread *td = curthread;
+	struct proc *p = td->td_proc;
+	int *t = DPCPU_PTR(pcputicks);
+	int flags;
+	int global, newticks;
+
+	/*
+	 * Update per-CPU and possibly global ticks values.
+	 */
+	*t += cnt;
+	do {
+		global = ticks;
+		newticks = *t - global;
+		if (newticks <= 0) {
+			if (newticks < -1)
+				*t = global - 1;
+			newticks = 0;
+			break;
+		}
+	} while (!atomic_cmpset_int(&ticks, global, *t));
+
+	/*
+	 * Run current process's virtual and profile time, as needed.
+	 */
+	pstats = p->p_stats;
+	flags = 0;
+	if (usermode &&
+	    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value)) {
+		PROC_SLOCK(p);
+		if (itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL],
+		    tick * cnt) == 0)
+			flags |= TDF_ALRMPEND | TDF_ASTPENDING;
+		PROC_SUNLOCK(p);
+	}
+	if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value)) {
+		PROC_SLOCK(p);
+		if (itimerdecr(&pstats->p_timer[ITIMER_PROF],
+		    tick * cnt) == 0)
+			flags |= TDF_PROFPEND | TDF_ASTPENDING;
+		PROC_SUNLOCK(p);
+	}
+	thread_lock(td);
+	sched_tick(cnt);
+	td->td_flags |= flags;
+	thread_unlock(td);
+
+#ifdef	HWPMC_HOOKS
+	if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
+		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
+#endif
+	callout_tick();
+	/* We are in charge to handle this tick duty. */
+	if (newticks > 0) {
+		mtx_lock_spin(&global_hardclock_mtx);
+		tc_ticktock();
+#ifdef DEVICE_POLLING
+		hardclock_device_poll(); /* This is very short and quick. */
+#endif /* DEVICE_POLLING */
+#ifdef SW_WATCHDOG
+		if (watchdog_enabled > 0) {
+			watchdog_ticks -= newticks;
+			if (watchdog_ticks <= 0)
+				watchdog_fire();
+		}
+#endif /* SW_WATCHDOG */
+		mtx_unlock_spin(&global_hardclock_mtx);
+	}
+	if (curcpu == CPU_FIRST())
+		cpu_tick_calibration();
+}
+
+void
+hardclock_sync(int cpu)
+{
+	int	*t = DPCPU_ID_PTR(cpu, pcputicks);
+
+	*t = ticks;
+}
+
 /*
  * Compute number of ticks in the specified amount of time.
  */
diff --git a/sys/kern/kern_clocksource.c b/sys/kern/kern_clocksource.c
index 6b005de8c5e..29304a496cb 100644
--- a/sys/kern/kern_clocksource.c
+++ b/sys/kern/kern_clocksource.c
@@ -41,6 +41,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -59,28 +60,79 @@ __FBSDID("$FreeBSD$");
 cyclic_clock_func_t	cyclic_clock_func[MAXCPU];
 #endif
 
-static void		cpu_restartclocks(void);
-static void		timercheck(void);
-inline static int	doconfigtimer(int i);
-static void		configtimer(int i);
+int			cpu_disable_deep_sleep = 0; /* Timer dies in C3. */
 
-static struct eventtimer *timer[2] = { NULL, NULL };
-static int		timertest = 0;
-static int		timerticks[2] = { 0, 0 };
-static int		profiling_on = 0;
-static struct bintime	timerperiod[2];
+static void		setuptimer(void);
+static void		loadtimer(struct bintime *now, int first);
+static int		doconfigtimer(void);
+static void		configtimer(int start);
+static int		round_freq(struct eventtimer *et, int freq);
 
-static char		timername[2][32];
-TUNABLE_STR("kern.eventtimer.timer1", timername[0], sizeof(*timername));
-TUNABLE_STR("kern.eventtimer.timer2", timername[1], sizeof(*timername));
+static void		getnextcpuevent(struct bintime *event, int idle);
+static void		getnextevent(struct bintime *event);
+static int		handleevents(struct bintime *now, int fake);
+#ifdef SMP
+static void		cpu_new_callout(int cpu, int ticks);
+#endif
 
-static u_int		singlemul = 0;
+static struct mtx	et_hw_mtx;
+
+#define	ET_HW_LOCK(state)						\
+	{								\
+		if (timer->et_flags & ET_FLAGS_PERCPU)			\
+			mtx_lock_spin(&(state)->et_hw_mtx);		\
+		else							\
+			mtx_lock_spin(&et_hw_mtx);			\
+	}
+
+#define	ET_HW_UNLOCK(state)						\
+	{								\
+		if (timer->et_flags & ET_FLAGS_PERCPU)			\
+			mtx_unlock_spin(&(state)->et_hw_mtx);		\
+		else							\
+			mtx_unlock_spin(&et_hw_mtx);			\
+	}
+
+static struct eventtimer *timer = NULL;
+static struct bintime	timerperiod;	/* Timer period for periodic mode. */
+static struct bintime	hardperiod;	/* hardclock() events period. */
+static struct bintime	statperiod;	/* statclock() events period. */
+static struct bintime	profperiod;	/* profclock() events period. */
+static struct bintime	nexttick;	/* Next global timer tick time. */
+static u_int		busy = 0;	/* Reconfiguration is in progress. */
+static int		profiling = 0;	/* Profiling events enabled. */
+
+static char		timername[32];	/* Wanted timer. */
+TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
+
+static u_int		singlemul = 0;	/* Multiplier for periodic mode. */
 TUNABLE_INT("kern.eventtimer.singlemul", &singlemul);
 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RW, &singlemul,
-    0, "Multiplier, used in single timer mode");
+    0, "Multiplier for periodic mode");
 
-typedef u_int tc[2];
-static DPCPU_DEFINE(tc, configtimer);
+static u_int		idletick = 0;	/* Idle mode allowed. */
+TUNABLE_INT("kern.eventtimer.idletick", &idletick);
+SYSCTL_INT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RW, &idletick,
+    0, "Run periodic events when idle");
+
+static int		periodic = 0;	/* Periodic or one-shot mode. */
+TUNABLE_INT("kern.eventtimer.periodic", &periodic);
+
+struct pcpu_state {
+	struct mtx	et_hw_mtx;	/* Per-CPU timer mutex. */
+	u_int		action;		/* Reconfiguration requests. */
+	u_int		handle;		/* Immediate handle resuests. */
+	struct bintime	now;		/* Last tick time. */
+	struct bintime	nextevent;	/* Next scheduled event on this CPU. */
+	struct bintime	nexttick;	/* Next timer tick time. */
+	struct bintime	nexthard;	/* Next hardlock() event. */
+	struct bintime	nextstat;	/* Next statclock() event. */
+	struct bintime	nextprof;	/* Next profclock() event. */
+	int		ipi;		/* This CPU needs IPI. */
+	int		idle;		/* This CPU is in idle mode. */
+};
+
+static DPCPU_DEFINE(struct pcpu_state, timerstate);
 
 #define FREQ2BT(freq, bt)						\
 {									\
@@ -91,159 +143,325 @@ static DPCPU_DEFINE(tc, configtimer);
 	(((uint64_t)0x8000000000000000 + ((bt)->frac >> 2)) /		\
 	    ((bt)->frac >> 1))
 
-/* Per-CPU timer1 handler. */
-static int
-hardclockhandler(struct trapframe *frame)
+/*
+ * Timer broadcast IPI handler.
+ */
+int
+hardclockintr(void)
 {
+	struct bintime now;
+	struct pcpu_state *state;
+	int done;
 
+	if (doconfigtimer() || busy)
+		return (FILTER_HANDLED);
+	state = DPCPU_PTR(timerstate);
+	now = state->now;
+	CTR4(KTR_SPARE2, "ipi  at %d:    now  %d.%08x%08x",
+	    curcpu, now.sec, (unsigned int)(now.frac >> 32),
+			     (unsigned int)(now.frac & 0xffffffff));
+	done = handleevents(&now, 0);
+	return (done ? FILTER_HANDLED : FILTER_STRAY);
+}
+
+/*
+ * Handle all events for specified time on this CPU
+ */
+static int
+handleevents(struct bintime *now, int fake)
+{
+	struct bintime t;
+	struct trapframe *frame;
+	struct pcpu_state *state;
+	uintfptr_t pc;
+	int usermode;
+	int done, runs;
+
+	CTR4(KTR_SPARE2, "handle at %d:  now  %d.%08x%08x",
+	    curcpu, now->sec, (unsigned int)(now->frac >> 32),
+		     (unsigned int)(now->frac & 0xffffffff));
+	done = 0;
+	if (fake) {
+		frame = NULL;
+		usermode = 0;
+		pc = 0;
+	} else {
+		frame = curthread->td_intr_frame;
+		usermode = TRAPF_USERMODE(frame);
+		pc = TRAPF_PC(frame);
+	}
 #ifdef KDTRACE_HOOKS
 	/*
 	 * If the DTrace hooks are configured and a callback function
 	 * has been registered, then call it to process the high speed
 	 * timers.
 	 */
-	int cpu = curcpu;
-	if (cyclic_clock_func[cpu] != NULL)
-		(*cyclic_clock_func[cpu])(frame);
+	if (!fake && cyclic_clock_func[curcpu] != NULL)
+		(*cyclic_clock_func[curcpu])(frame);
 #endif
-
-	timer1clock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
-	return (FILTER_HANDLED);
-}
-
-/* Per-CPU timer2 handler. */
-static int
-statclockhandler(struct trapframe *frame)
-{
-
-	timer2clock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
-	return (FILTER_HANDLED);
-}
-
-/* timer1 broadcast IPI handler. */
-int
-hardclockintr(struct trapframe *frame)
-{
-
-	if (doconfigtimer(0))
-		return (FILTER_HANDLED);
-	return (hardclockhandler(frame));
-}
-
-/* timer2 broadcast IPI handler. */
-int
-statclockintr(struct trapframe *frame)
-{
-
-	if (doconfigtimer(1))
-		return (FILTER_HANDLED);
-	return (statclockhandler(frame));
-}
-
-/* timer1 callback. */
-static void
-timer1cb(struct eventtimer *et, void *arg)
-{
-
-#ifdef SMP
-	/* Broadcast interrupt to other CPUs for non-per-CPU timers */
-	if (smp_started && (et->et_flags & ET_FLAGS_PERCPU) == 0)
-		ipi_all_but_self(IPI_HARDCLOCK);
-#endif
-	if (timertest) {
-		if ((et->et_flags & ET_FLAGS_PERCPU) == 0 || curcpu == 0) {
-			timerticks[0]++;
-			if (timerticks[0] >= timer1hz) {
-				ET_LOCK();
-				timercheck();
-				ET_UNLOCK();
-			}
-		}
+	runs = 0;
+	state = DPCPU_PTR(timerstate);
+	while (bintime_cmp(now, &state->nexthard, >=)) {
+		bintime_add(&state->nexthard, &hardperiod);
+		runs++;
 	}
-	hardclockhandler(curthread->td_intr_frame);
-}
-
-/* timer2 callback. */
-static void
-timer2cb(struct eventtimer *et, void *arg)
-{
-
-#ifdef SMP
-	/* Broadcast interrupt to other CPUs for non-per-CPU timers */
-	if (smp_started && (et->et_flags & ET_FLAGS_PERCPU) == 0)
-		ipi_all_but_self(IPI_STATCLOCK);
-#endif
-	if (timertest) {
-		if ((et->et_flags & ET_FLAGS_PERCPU) == 0 || curcpu == 0) {
-			timerticks[1]++;
-			if (timerticks[1] >= timer2hz * 2) {
-				ET_LOCK();
-				timercheck();
-				ET_UNLOCK();
-			}
-		}
+	if (runs) {
+		hardclock_anycpu(runs, usermode);
+		done = 1;
 	}
-	statclockhandler(curthread->td_intr_frame);
+	while (bintime_cmp(now, &state->nextstat, >=)) {
+		statclock(usermode);
+		bintime_add(&state->nextstat, &statperiod);
+		done = 1;
+	}
+	if (profiling) {
+		while (bintime_cmp(now, &state->nextprof, >=)) {
+			if (!fake)
+				profclock(usermode, pc);
+			bintime_add(&state->nextprof, &profperiod);
+			done = 1;
+		}
+	} else
+		state->nextprof = state->nextstat;
+	getnextcpuevent(&t, 0);
+	ET_HW_LOCK(state);
+	if (!busy) {
+		state->idle = 0;
+		state->nextevent = t;
+		loadtimer(now, 0);
+	}
+	ET_HW_UNLOCK(state);
+	return (done);
 }
 
 /*
- * Check that both timers are running with at least 1/4 of configured rate.
- * If not - replace the broken one.
+ * Schedule binuptime of the next event on current CPU.
  */
 static void
-timercheck(void)
+getnextcpuevent(struct bintime *event, int idle)
 {
+	struct bintime tmp;
+	struct pcpu_state *state;
+	int skip;
 
-	if (!timertest)
-		return;
-	timertest = 0;
-	if (timerticks[0] * 4 < timer1hz) {
-		printf("Event timer \"%s\" is dead.\n", timer[0]->et_name);
-		timer1hz = 0;
-		configtimer(0);
-		et_ban(timer[0]);
-		et_free(timer[0]);
-		timer[0] = et_find(NULL, ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
-		if (timer[0] == NULL) {
-			timer2hz = 0;
-			configtimer(1);
-			et_free(timer[1]);
-			timer[1] = NULL;
-			timer[0] = timer[1];
+	state = DPCPU_PTR(timerstate);
+	*event = state->nexthard;
+	if (idle) { /* If CPU is idle - ask callouts for how long. */
+		skip = callout_tickstofirst() - 1;
+		CTR2(KTR_SPARE2, "skip   at %d: %d", curcpu, skip);
+		tmp = hardperiod;
+		bintime_mul(&tmp, skip);
+		bintime_add(event, &tmp);
+	} else { /* If CPU is active - handle all types of events. */
+		if (bintime_cmp(event, &state->nextstat, >))
+			*event = state->nextstat;
+		if (profiling &&
+		    bintime_cmp(event, &state->nextprof, >))
+			*event = state->nextprof;
+	}
+}
+
+/*
+ * Schedule binuptime of the next event on all CPUs.
+ */
+static void
+getnextevent(struct bintime *event)
+{
+	struct pcpu_state *state;
+#ifdef SMP
+	int	cpu;
+#endif
+	int	c;
+
+	state = DPCPU_PTR(timerstate);
+	*event = state->nextevent;
+	c = curcpu;
+#ifdef SMP
+	if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
+		CPU_FOREACH(cpu) {
+			if (curcpu == cpu)
+				continue;
+			state = DPCPU_ID_PTR(cpu, timerstate);
+			if (bintime_cmp(event, &state->nextevent, >)) {
+				*event = state->nextevent;
+				c = cpu;
+			}
 		}
-		et_init(timer[0], timer1cb, NULL, NULL);
-		cpu_restartclocks();
-		return;
 	}
-	if (timerticks[1] * 4 < timer2hz) {
-		printf("Event timer \"%s\" is dead.\n", timer[1]->et_name);
-		timer2hz = 0;
-		configtimer(1);
-		et_ban(timer[1]);
-		et_free(timer[1]);
-		timer[1] = et_find(NULL, ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
-		if (timer[1] != NULL)
-			et_init(timer[1], timer2cb, NULL, NULL);
-		cpu_restartclocks();
+#endif
+	CTR5(KTR_SPARE2, "next at %d:    next %d.%08x%08x by %d",
+	    curcpu, event->sec, (unsigned int)(event->frac >> 32),
+			     (unsigned int)(event->frac & 0xffffffff), c);
+}
+
+/* Hardware timer callback function. */
+static void
+timercb(struct eventtimer *et, void *arg)
+{
+	struct bintime now;
+	struct bintime *next;
+	struct pcpu_state *state;
+#ifdef SMP
+	int cpu, bcast;
+#endif
+
+	/* Do not touch anything if somebody reconfiguring timers. */
+	if (busy)
 		return;
+	/* Update present and next tick times. */
+	state = DPCPU_PTR(timerstate);
+	if (et->et_flags & ET_FLAGS_PERCPU) {
+		next = &state->nexttick;
+	} else
+		next = &nexttick;
+	if (periodic) {
+		now = *next;	/* Ex-next tick time becomes present time. */
+		bintime_add(next, &timerperiod); /* Next tick in 1 period. */
+	} else {
+		binuptime(&now);	/* Get present time from hardware. */
+		next->sec = -1;		/* Next tick is not scheduled yet. */
 	}
+	state->now = now;
+	CTR4(KTR_SPARE2, "intr at %d:    now  %d.%08x%08x",
+	    curcpu, now.sec, (unsigned int)(now.frac >> 32),
+			     (unsigned int)(now.frac & 0xffffffff));
+
+#ifdef SMP
+	/* Prepare broadcasting to other CPUs for non-per-CPU timers. */
+	bcast = 0;
+	if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
+		CPU_FOREACH(cpu) {
+			if (curcpu == cpu)
+				continue;
+			state = DPCPU_ID_PTR(cpu, timerstate);
+			ET_HW_LOCK(state);
+			state->now = now;
+			if (bintime_cmp(&now, &state->nextevent, >=)) {
+				state->nextevent.sec++;
+				state->ipi = 1;
+				bcast = 1;
+			}
+			ET_HW_UNLOCK(state);
+		}
+	}
+#endif
+
+	/* Handle events for this time on this CPU. */
+	handleevents(&now, 0);
+
+#ifdef SMP
+	/* Broadcast interrupt to other CPUs for non-per-CPU timers. */
+	if (bcast) {
+		CPU_FOREACH(cpu) {
+			if (curcpu == cpu)
+				continue;
+			state = DPCPU_ID_PTR(cpu, timerstate);
+			if (state->ipi) {
+				state->ipi = 0;
+				ipi_cpu(cpu, IPI_HARDCLOCK);
+			}
+		}
+	}
+#endif
+}
+
+/*
+ * Load new value into hardware timer.
+ */
+static void
+loadtimer(struct bintime *now, int start)
+{
+	struct pcpu_state *state;
+	struct bintime new;
+	struct bintime *next;
+	uint64_t tmp;
+	int eq;
+
+	if (periodic) {
+		if (start) {
+			/*
+			 * Try to start all periodic timers aligned
+			 * to period to make events synchronous.
+			 */
+			tmp = ((uint64_t)now->sec << 36) + (now->frac >> 28);
+			tmp = (tmp % (timerperiod.frac >> 28)) << 28;
+			tmp = timerperiod.frac - tmp;
+			new = timerperiod;
+			bintime_addx(&new, tmp);
+			CTR5(KTR_SPARE2, "load p at %d:   now %d.%08x first in %d.%08x",
+			    curcpu, now->sec, (unsigned int)(now->frac >> 32),
+			    new.sec, (unsigned int)(new.frac >> 32));
+			et_start(timer, &new, &timerperiod);
+		}
+	} else {
+		if (timer->et_flags & ET_FLAGS_PERCPU) {
+			state = DPCPU_PTR(timerstate);
+			next = &state->nexttick;
+		} else
+			next = &nexttick;
+		getnextevent(&new);
+		eq = bintime_cmp(&new, next, ==);
+		CTR5(KTR_SPARE2, "load at %d:    next %d.%08x%08x eq %d",
+		    curcpu, new.sec, (unsigned int)(new.frac >> 32),
+			     (unsigned int)(new.frac & 0xffffffff),
+			     eq);
+		if (!eq) {
+			*next = new;
+			bintime_sub(&new, now);
+			et_start(timer, &new, NULL);
+		}
+	}
+}
+
+/*
+ * Prepare event timer parameters after configuration changes.
+ */
+static void
+setuptimer(void)
+{
+	int freq;
+
+	if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
+		periodic = 0;
+	else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
+		periodic = 1;
+	freq = hz * singlemul;
+	while (freq < (profiling ? profhz : stathz))
+		freq += hz;
+	freq = round_freq(timer, freq);
+	FREQ2BT(freq, &timerperiod);
 }
 
 /*
  * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
  */
-inline static int
-doconfigtimer(int i)
+static int
+doconfigtimer(void)
 {
-	tc *conf;
+	struct bintime now;
+	struct pcpu_state *state;
 
-	conf = DPCPU_PTR(configtimer);
-	if (atomic_load_acq_int(*conf + i)) {
-		if (i == 0 ? timer1hz : timer2hz)
-			et_start(timer[i], NULL, &timerperiod[i]);
-		else
-			et_stop(timer[i]);
-		atomic_store_rel_int(*conf + i, 0);
+	state = DPCPU_PTR(timerstate);
+	switch (atomic_load_acq_int(&state->action)) {
+	case 1:
+		binuptime(&now);
+		ET_HW_LOCK(state);
+		loadtimer(&now, 1);
+		ET_HW_UNLOCK(state);
+		state->handle = 0;
+		atomic_store_rel_int(&state->action, 0);
+		return (1);
+	case 2:
+		ET_HW_LOCK(state);
+		et_stop(timer);
+		ET_HW_UNLOCK(state);
+		state->handle = 0;
+		atomic_store_rel_int(&state->action, 0);
+		return (1);
+	}
+	if (atomic_readandclear_int(&state->handle) && !busy) {
+		binuptime(&now);
+		handleevents(&now, 0);
 		return (1);
 	}
 	return (0);
@@ -254,45 +472,79 @@ doconfigtimer(int i)
  * For per-CPU timers use IPI to make other CPUs to reconfigure.
  */
 static void
-configtimer(int i)
+configtimer(int start)
 {
-#ifdef SMP
-	tc *conf;
+	struct bintime now, next;
+	struct pcpu_state *state;
 	int cpu;
 
+	if (start) {
+		setuptimer();
+		binuptime(&now);
+	}
 	critical_enter();
-#endif
-	/* Start/stop global timer or per-CPU timer of this CPU. */
-	if (i == 0 ? timer1hz : timer2hz)
-		et_start(timer[i], NULL, &timerperiod[i]);
-	else
-		et_stop(timer[i]);
+	ET_HW_LOCK(DPCPU_PTR(timerstate));
+	if (start) {
+		/* Initialize time machine parameters. */
+		next = now;
+		bintime_add(&next, &timerperiod);
+		if (periodic)
+			nexttick = next;
+		else
+			nexttick.sec = -1;
+		CPU_FOREACH(cpu) {
+			state = DPCPU_ID_PTR(cpu, timerstate);
+			state->now = now;
+			state->nextevent = next;
+			if (periodic)
+				state->nexttick = next;
+			else
+				state->nexttick.sec = -1;
+			state->nexthard = next;
+			state->nextstat = next;
+			state->nextprof = next;
+			hardclock_sync(cpu);
+		}
+		busy = 0;
+		/* Start global timer or per-CPU timer of this CPU. */
+		loadtimer(&now, 1);
+	} else {
+		busy = 1;
+		/* Stop global timer or per-CPU timer of this CPU. */
+		et_stop(timer);
+	}
+	ET_HW_UNLOCK(DPCPU_PTR(timerstate));
 #ifdef SMP
-	if ((timer[i]->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
+	/* If timer is global or there is no other CPUs yet - we are done. */
+	if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
 		critical_exit();
 		return;
 	}
 	/* Set reconfigure flags for other CPUs. */
 	CPU_FOREACH(cpu) {
-		conf = DPCPU_ID_PTR(cpu, configtimer);
-		atomic_store_rel_int(*conf + i, (cpu == curcpu) ? 0 : 1);
+		state = DPCPU_ID_PTR(cpu, timerstate);
+		atomic_store_rel_int(&state->action,
+		    (cpu == curcpu) ? 0 : ( start ? 1 : 2));
 	}
-	/* Send reconfigure IPI. */
-	ipi_all_but_self(i == 0 ? IPI_HARDCLOCK : IPI_STATCLOCK);
+	/* Broadcast reconfigure IPI. */
+	ipi_all_but_self(IPI_HARDCLOCK);
 	/* Wait for reconfiguration completed. */
 restart:
 	cpu_spinwait();
 	CPU_FOREACH(cpu) {
 		if (cpu == curcpu)
 			continue;
-		conf = DPCPU_ID_PTR(cpu, configtimer);
-		if (atomic_load_acq_int(*conf + i))
+		state = DPCPU_ID_PTR(cpu, timerstate);
+		if (atomic_load_acq_int(&state->action))
 			goto restart;
 	}
-	critical_exit();
 #endif
+	critical_exit();
 }
 
+/*
+ * Calculate nearest frequency supported by hardware timer.
+ */
 static int
 round_freq(struct eventtimer *et, int freq)
 {
@@ -314,23 +566,49 @@ round_freq(struct eventtimer *et, int freq)
 }
 
 /*
- * Configure and start event timers.
+ * Configure and start event timers (BSP part).
  */
 void
 cpu_initclocks_bsp(void)
 {
-	int base, div;
+	struct pcpu_state *state;
+	int base, div, cpu;
 
-	timer[0] = et_find(timername[0], ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
-	if (timer[0] == NULL)
-		timer[0] = et_find(NULL, ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
-	if (timer[0] == NULL)
+	mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
+	CPU_FOREACH(cpu) {
+		state = DPCPU_ID_PTR(cpu, timerstate);
+		mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
+	}
+#ifdef SMP
+	callout_new_inserted = cpu_new_callout;
+#endif
+	/* Grab requested timer or the best of present. */
+	if (timername[0])
+		timer = et_find(timername, 0, 0);
+	if (timer == NULL && periodic) {
+		timer = et_find(NULL,
+		    ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
+	}
+	if (timer == NULL) {
+		timer = et_find(NULL,
+		    ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
+	}
+	if (timer == NULL && !periodic) {
+		timer = et_find(NULL,
+		    ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
+	}
+	if (timer == NULL)
 		panic("No usable event timer found!");
-	et_init(timer[0], timer1cb, NULL, NULL);
-	timer[1] = et_find(timername[1][0] ? timername[1] : NULL,
-	    ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
-	if (timer[1])
-		et_init(timer[1], timer2cb, NULL, NULL);
+	et_init(timer, timercb, NULL, NULL);
+
+	/* Adapt to timer capabilities. */
+	if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
+		periodic = 0;
+	else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
+		periodic = 1;
+	if (timer->et_flags & ET_FLAGS_C3STOP)
+		cpu_disable_deep_sleep++;
+
 	/*
 	 * We honor the requested 'hz' value.
 	 * We want to run stathz in the neighborhood of 128hz.
@@ -344,8 +622,8 @@ cpu_initclocks_bsp(void)
 		else
 			singlemul = 4;
 	}
-	if (timer[1] == NULL) {
-		base = round_freq(timer[0], hz * singlemul);
+	if (periodic) {
+		base = round_freq(timer, hz * singlemul);
 		singlemul = max((base + hz / 2) / hz, 1);
 		hz = (base + singlemul / 2) / singlemul;
 		if (base <= 128)
@@ -359,175 +637,236 @@ cpu_initclocks_bsp(void)
 		profhz = stathz;
 		while ((profhz + stathz) <= 128 * 64)
 			profhz += stathz;
-		profhz = round_freq(timer[0], profhz);
+		profhz = round_freq(timer, profhz);
 	} else {
-		hz = round_freq(timer[0], hz);
-		stathz = round_freq(timer[1], 127);
-		profhz = round_freq(timer[1], stathz * 64);
+		hz = round_freq(timer, hz);
+		stathz = round_freq(timer, 127);
+		profhz = round_freq(timer, stathz * 64);
 	}
 	tick = 1000000 / hz;
+	FREQ2BT(hz, &hardperiod);
+	FREQ2BT(stathz, &statperiod);
+	FREQ2BT(profhz, &profperiod);
 	ET_LOCK();
-	cpu_restartclocks();
+	configtimer(1);
 	ET_UNLOCK();
 }
 
-/* Start per-CPU event timers on APs. */
+/*
+ * Start per-CPU event timers on APs.
+ */
 void
 cpu_initclocks_ap(void)
 {
+	struct bintime now;
+	struct pcpu_state *state;
 
-	ET_LOCK();
-	if (timer[0]->et_flags & ET_FLAGS_PERCPU)
-		et_start(timer[0], NULL, &timerperiod[0]);
-	if (timer[1] && timer[1]->et_flags & ET_FLAGS_PERCPU)
-		et_start(timer[1], NULL, &timerperiod[1]);
-	ET_UNLOCK();
-}
-
-/* Reconfigure and restart event timers after configuration changes. */
-static void
-cpu_restartclocks(void)
-{
-
-	/* Stop all event timers. */
-	timertest = 0;
-	if (timer1hz) {
-		timer1hz = 0;
-		configtimer(0);
-	}
-	if (timer[1] && timer2hz) {
-		timer2hz = 0;
-		configtimer(1);
-	}
-	/* Calculate new event timers parameters. */
-	if (timer[1] == NULL) {
-		timer1hz = hz * singlemul;
-		while (timer1hz < (profiling_on ? profhz : stathz))
-			timer1hz += hz;
-		timer2hz = 0;
-	} else {
-		timer1hz = hz;
-		timer2hz = profiling_on ? profhz : stathz;
-		timer2hz = round_freq(timer[1], timer2hz);
-	}
-	timer1hz = round_freq(timer[0], timer1hz);
-	printf("Starting kernel event timers: %s @ %dHz, %s @ %dHz\n",
-	    timer[0]->et_name, timer1hz,
-	    timer[1] ? timer[1]->et_name : "NONE", timer2hz);
-	/* Restart event timers. */
-	FREQ2BT(timer1hz, &timerperiod[0]);
-	configtimer(0);
-	if (timer[1]) {
-		timerticks[0] = 0;
-		timerticks[1] = 0;
-		FREQ2BT(timer2hz, &timerperiod[1]);
-		configtimer(1);
-		timertest = 1;
+	if (timer->et_flags & ET_FLAGS_PERCPU) {
+		state = DPCPU_PTR(timerstate);
+		binuptime(&now);
+		ET_HW_LOCK(state);
+		loadtimer(&now, 1);
+		ET_HW_UNLOCK(state);
 	}
 }
 
-/* Switch to profiling clock rates. */
+/*
+ * Switch to profiling clock rates.
+ */
 void
 cpu_startprofclock(void)
 {
 
 	ET_LOCK();
-	profiling_on = 1;
-	cpu_restartclocks();
+	if (periodic) {
+		configtimer(0);
+		profiling = 1;
+		configtimer(1);
+	} else
+		profiling = 1;
 	ET_UNLOCK();
 }
 
-/* Switch to regular clock rates. */
+/*
+ * Switch to regular clock rates.
+ */
 void
 cpu_stopprofclock(void)
 {
 
 	ET_LOCK();
-	profiling_on = 0;
-	cpu_restartclocks();
+	if (periodic) {
+		configtimer(0);
+		profiling = 0;
+		configtimer(1);
+	} else
+		profiling = 0;
 	ET_UNLOCK();
 }
 
-/* Report or change the active event timers hardware. */
+/*
+ * Switch to idle mode (all ticks handled).
+ */
+void
+cpu_idleclock(void)
+{
+	struct bintime now, t;
+	struct pcpu_state *state;
+
+	if (idletick || busy ||
+	    (periodic && (timer->et_flags & ET_FLAGS_PERCPU)))
+		return;
+	state = DPCPU_PTR(timerstate);
+	if (periodic)
+		now = state->now;
+	else
+		binuptime(&now);
+	CTR4(KTR_SPARE2, "idle at %d:    now  %d.%08x%08x",
+	    curcpu, now.sec, (unsigned int)(now.frac >> 32),
+			     (unsigned int)(now.frac & 0xffffffff));
+	getnextcpuevent(&t, 1);
+	ET_HW_LOCK(state);
+	state->idle = 1;
+	state->nextevent = t;
+	if (!periodic)
+		loadtimer(&now, 0);
+	ET_HW_UNLOCK(state);
+}
+
+/*
+ * Switch to active mode (skip empty ticks).
+ */
+void
+cpu_activeclock(void)
+{
+	struct bintime now;
+	struct pcpu_state *state;
+	struct thread *td;
+
+	state = DPCPU_PTR(timerstate);
+	if (state->idle == 0 || busy)
+		return;
+	if (periodic)
+		now = state->now;
+	else
+		binuptime(&now);
+	CTR4(KTR_SPARE2, "active at %d:  now  %d.%08x%08x",
+	    curcpu, now.sec, (unsigned int)(now.frac >> 32),
+			     (unsigned int)(now.frac & 0xffffffff));
+	spinlock_enter();
+	td = curthread;
+	td->td_intr_nesting_level++;
+	handleevents(&now, 1);
+	td->td_intr_nesting_level--;
+	spinlock_exit();
+}
+
+#ifdef SMP
+static void
+cpu_new_callout(int cpu, int ticks)
+{
+	struct bintime tmp;
+	struct pcpu_state *state;
+
+	CTR3(KTR_SPARE2, "new co at %d:    on %d in %d",
+	    curcpu, cpu, ticks);
+	state = DPCPU_ID_PTR(cpu, timerstate);
+	ET_HW_LOCK(state);
+	if (state->idle == 0 || busy) {
+		ET_HW_UNLOCK(state);
+		return;
+	}
+	/*
+	 * If timer is periodic - just update next event time for target CPU.
+	 */
+	if (periodic) {
+		state->nextevent = state->nexthard;
+		tmp = hardperiod;
+		bintime_mul(&tmp, ticks - 1);
+		bintime_add(&state->nextevent, &tmp);
+		ET_HW_UNLOCK(state);
+		return;
+	}
+	/*
+	 * Otherwise we have to wake that CPU up, as we can't get present
+	 * bintime to reprogram global timer from here. If timer is per-CPU,
+	 * we by definition can't do it from here.
+	 */
+	ET_HW_UNLOCK(state);
+	if (timer->et_flags & ET_FLAGS_PERCPU) {
+		state->handle = 1;
+		ipi_cpu(cpu, IPI_HARDCLOCK);
+	} else {
+		if (!cpu_idle_wakeup(cpu))
+			ipi_cpu(cpu, IPI_AST);
+	}
+}
+#endif
+
+/*
+ * Report or change the active event timers hardware.
+ */
 static int
-sysctl_kern_eventtimer_timer1(SYSCTL_HANDLER_ARGS)
+sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
 {
 	char buf[32];
 	struct eventtimer *et;
 	int error;
 
 	ET_LOCK();
-	et = timer[0];
+	et = timer;
 	snprintf(buf, sizeof(buf), "%s", et->et_name);
 	ET_UNLOCK();
 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
 	ET_LOCK();
-	et = timer[0];
+	et = timer;
 	if (error != 0 || req->newptr == NULL ||
-	    strcmp(buf, et->et_name) == 0) {
+	    strcasecmp(buf, et->et_name) == 0) {
 		ET_UNLOCK();
 		return (error);
 	}
-	et = et_find(buf, ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
+	et = et_find(buf, 0, 0);
 	if (et == NULL) {
 		ET_UNLOCK();
 		return (ENOENT);
 	}
-	timer1hz = 0;
 	configtimer(0);
-	et_free(timer[0]);
-	timer[0] = et;
-	et_init(timer[0], timer1cb, NULL, NULL);
-	cpu_restartclocks();
+	et_free(timer);
+	if (et->et_flags & ET_FLAGS_C3STOP)
+		cpu_disable_deep_sleep++;
+	if (timer->et_flags & ET_FLAGS_C3STOP)
+		cpu_disable_deep_sleep--;
+	timer = et;
+	et_init(timer, timercb, NULL, NULL);
+	configtimer(1);
 	ET_UNLOCK();
 	return (error);
 }
-SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer1,
+SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
     CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
-    0, 0, sysctl_kern_eventtimer_timer1, "A", "Primary event timer");
+    0, 0, sysctl_kern_eventtimer_timer, "A", "Kernel event timer");
 
+/*
+ * Report or change the active event timer periodicity.
+ */
 static int
-sysctl_kern_eventtimer_timer2(SYSCTL_HANDLER_ARGS)
+sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
 {
-	char buf[32];
-	struct eventtimer *et;
-	int error;
+	int error, val;
 
-	ET_LOCK();
-	et = timer[1];
-	if (et == NULL)
-		snprintf(buf, sizeof(buf), "NONE");
-	else
-		snprintf(buf, sizeof(buf), "%s", et->et_name);
-	ET_UNLOCK();
-	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
-	ET_LOCK();
-	et = timer[1];
-	if (error != 0 || req->newptr == NULL ||
-	    strcmp(buf, et ? et->et_name : "NONE") == 0) {
-		ET_UNLOCK();
+	val = periodic;
+	error = sysctl_handle_int(oidp, &val, 0, req);
+	if (error != 0 || req->newptr == NULL)
 		return (error);
-	}
-	et = et_find(buf, ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
-	if (et == NULL && strcasecmp(buf, "NONE") != 0) {
-		ET_UNLOCK();
-		return (ENOENT);
-	}
-	if (timer[1] != NULL) {
-		timer2hz = 0;
-		configtimer(1);
-		et_free(timer[1]);
-	}
-	timer[1] = et;
-	if (timer[1] != NULL)
-		et_init(timer[1], timer2cb, NULL, NULL);
-	cpu_restartclocks();
+	ET_LOCK();
+	configtimer(0);
+	periodic = val;
+	configtimer(1);
 	ET_UNLOCK();
 	return (error);
 }
-SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer2,
-    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
-    0, 0, sysctl_kern_eventtimer_timer2, "A", "Secondary event timer");
+SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
+    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
+    0, 0, sysctl_kern_eventtimer_periodic, "I", "Kernel event timer periodic");
 
 #endif
-
diff --git a/sys/kern/kern_et.c b/sys/kern/kern_et.c
index 17b9c676422..8c375561c42 100644
--- a/sys/kern/kern_et.c
+++ b/sys/kern/kern_et.c
@@ -38,7 +38,7 @@ SLIST_HEAD(et_eventtimers_list, eventtimer);
 static struct et_eventtimers_list eventtimers = SLIST_HEAD_INITIALIZER(et_eventtimers);
 
 struct mtx	et_eventtimers_mtx;
-MTX_SYSINIT(et_eventtimers_init, &et_eventtimers_mtx, "et_mtx", MTX_SPIN);
+MTX_SYSINIT(et_eventtimers_init, &et_eventtimers_mtx, "et_mtx", MTX_DEF);
 
 SYSCTL_NODE(_kern, OID_AUTO, eventtimer, CTLFLAG_RW, 0, "Event timers");
 SYSCTL_NODE(_kern_eventtimer, OID_AUTO, et, CTLFLAG_RW, 0, "");
diff --git a/sys/kern/kern_tc.c b/sys/kern/kern_tc.c
index d97334849ce..811b24f30e5 100644
--- a/sys/kern/kern_tc.c
+++ b/sys/kern/kern_tc.c
@@ -770,16 +770,11 @@ void
 tc_ticktock(void)
 {
 	static int count;
-	static time_t last_calib;
 
 	if (++count < tc_tick)
 		return;
 	count = 0;
 	tc_windup();
-	if (time_uptime != last_calib && !(time_uptime & 0xf)) {
-		cpu_tick_calibrate(0);
-		last_calib = time_uptime;
-	}
 }
 
 static void
@@ -830,9 +825,20 @@ tc_cpu_ticks(void)
 	return (u + base);
 }
 
+void
+cpu_tick_calibration(void)
+{
+	static time_t last_calib;
+
+	if (time_uptime != last_calib && !(time_uptime & 0xf)) {
+		cpu_tick_calibrate(0);
+		last_calib = time_uptime;
+	}
+}
+
 /*
  * This function gets called every 16 seconds on only one designated
- * CPU in the system from hardclock() via tc_ticktock().
+ * CPU in the system from hardclock() via cpu_tick_calibration()().
  *
  * Whenever the real time clock is stepped we get called with reset=1
  * to make sure we handle suspend/resume and similar events correctly.
diff --git a/sys/kern/kern_timeout.c b/sys/kern/kern_timeout.c
index 32d5691812d..56977923548 100644
--- a/sys/kern/kern_timeout.c
+++ b/sys/kern/kern_timeout.c
@@ -111,6 +111,7 @@ struct callout_cpu {
 	int 			cc_softticks;
 	int			cc_cancel;
 	int			cc_waiting;
+	int 			cc_firsttick;
 };
 
 #ifdef SMP
@@ -126,6 +127,7 @@ struct callout_cpu cc_cpu;
 #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
 
 static int timeout_cpu;
+void (*callout_new_inserted)(int cpu, int ticks) = NULL;
 
 MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
 
@@ -260,7 +262,7 @@ callout_tick(void)
 	need_softclock = 0;
 	cc = CC_SELF();
 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
-	cc->cc_ticks++;
+	cc->cc_firsttick = cc->cc_ticks = ticks;
 	for (; (cc->cc_softticks - cc->cc_ticks) <= 0; cc->cc_softticks++) {
 		bucket = cc->cc_softticks & callwheelmask;
 		if (!TAILQ_EMPTY(&cc->cc_callwheel[bucket])) {
@@ -277,6 +279,34 @@ callout_tick(void)
 		swi_sched(cc->cc_cookie, 0);
 }
 
+int
+callout_tickstofirst(void)
+{
+	struct callout_cpu *cc;
+	struct callout *c;
+	struct callout_tailq *sc;
+	int curticks;
+	int skip = 1;
+
+	cc = CC_SELF();
+	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
+	curticks = cc->cc_ticks;
+	while( skip < ncallout && skip < hz/8 ) {
+		sc = &cc->cc_callwheel[ (curticks+skip) & callwheelmask ];
+		/* search scanning ticks */
+		TAILQ_FOREACH( c, sc, c_links.tqe ){
+			if (c && (c->c_time <= curticks + ncallout)
+			    && (c->c_time > 0))
+				goto out;
+		}
+		skip++;
+	}
+out:
+	cc->cc_firsttick = curticks + skip;
+	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
+	return (skip);
+}
+
 static struct callout_cpu *
 callout_lock(struct callout *c)
 {
@@ -639,9 +669,14 @@ retry:
 	c->c_arg = arg;
 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
 	c->c_func = ftn;
-	c->c_time = cc->cc_ticks + to_ticks;
+	c->c_time = ticks + to_ticks;
 	TAILQ_INSERT_TAIL(&cc->cc_callwheel[c->c_time & callwheelmask], 
 			  c, c_links.tqe);
+	if ((c->c_time - cc->cc_firsttick) < 0) {
+		cc->cc_firsttick = c->c_time;
+		(*callout_new_inserted)(cpu,
+		    to_ticks + (ticks - cc->cc_ticks));
+	}
 	CTR5(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d",
 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, to_ticks);
 	CC_UNLOCK(cc);
diff --git a/sys/kern/sched_4bsd.c b/sys/kern/sched_4bsd.c
index 780dc6d1760..9face648de9 100644
--- a/sys/kern/sched_4bsd.c
+++ b/sys/kern/sched_4bsd.c
@@ -1547,7 +1547,7 @@ sched_pctcpu(struct thread *td)
 }
 
 void
-sched_tick(void)
+sched_tick(int cnt)
 {
 }
 
diff --git a/sys/kern/sched_ule.c b/sys/kern/sched_ule.c
index bb2d34a37ca..e1cc172592f 100644
--- a/sys/kern/sched_ule.c
+++ b/sys/kern/sched_ule.c
@@ -196,7 +196,7 @@ static int preempt_thresh = 0;
 #endif
 static int static_boost = PRI_MIN_TIMESHARE;
 static int sched_idlespins = 10000;
-static int sched_idlespinthresh = 64;
+static int sched_idlespinthresh = 16;
 
 /*
  * tdq - per processor runqs and statistics.  All fields are protected by the
@@ -2163,7 +2163,7 @@ sched_clock(struct thread *td)
  * is easier than trying to scale based on stathz.
  */
 void
-sched_tick(void)
+sched_tick(int cnt)
 {
 	struct td_sched *ts;
 
@@ -2175,7 +2175,7 @@ sched_tick(void)
 	if (ts->ts_incrtick == ticks)
 		return;
 	/* Adjust ticks for pctcpu */
-	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
+	ts->ts_ticks += cnt << SCHED_TICK_SHIFT;
 	ts->ts_ltick = ticks;
 	ts->ts_incrtick = ticks;
 	/*
@@ -2549,7 +2549,7 @@ sched_idletd(void *dummy)
 		if (tdq->tdq_load == 0) {
 			tdq->tdq_cpu_idle = 1;
 			if (tdq->tdq_load == 0) {
-				cpu_idle(switchcnt > sched_idlespinthresh);
+				cpu_idle(switchcnt > sched_idlespinthresh * 4);
 				tdq->tdq_switchcnt++;
 			}
 			tdq->tdq_cpu_idle = 0;
diff --git a/sys/mips/include/smp.h b/sys/mips/include/smp.h
index 28efd4c8caf..58aaf03165b 100644
--- a/sys/mips/include/smp.h
+++ b/sys/mips/include/smp.h
@@ -28,7 +28,6 @@
 #define	IPI_STOP_HARD		0x0008
 #define	IPI_PREEMPT		0x0010
 #define	IPI_HARDCLOCK		0x0020
-#define	IPI_STATCLOCK		0x0040
 
 #ifndef LOCORE
 
diff --git a/sys/mips/mips/mp_machdep.c b/sys/mips/mips/mp_machdep.c
index c7ff3d8560b..ef2f24c035d 100644
--- a/sys/mips/mips/mp_machdep.c
+++ b/sys/mips/mips/mp_machdep.c
@@ -164,11 +164,7 @@ mips_ipi_handler(void *arg)
 			break;
 		case IPI_HARDCLOCK:
 			CTR1(KTR_SMP, "%s: IPI_HARDCLOCK", __func__);
-			hardclockintr(arg);;
-			break;
-		case IPI_STATCLOCK:
-			CTR1(KTR_SMP, "%s: IPI_STATCLOCK", __func__);
-			statclockintr(arg);;
+			hardclockintr();;
 			break;
 		default:
 			panic("Unknown IPI 0x%0x on cpu %d", ipi, curcpu);
diff --git a/sys/pc98/pc98/machdep.c b/sys/pc98/pc98/machdep.c
index 671ce5b3cf3..22dc8f0c5e0 100644
--- a/sys/pc98/pc98/machdep.c
+++ b/sys/pc98/pc98/machdep.c
@@ -1120,40 +1120,36 @@ cpu_halt(void)
 		__asm__ ("hlt");
 }
 
+static int	idle_mwait = 1;		/* Use MONITOR/MWAIT for short idle. */
+TUNABLE_INT("machdep.idle_mwait", &idle_mwait);
+SYSCTL_INT(_machdep, OID_AUTO, idle_mwait, CTLFLAG_RW, &idle_mwait,
+    0, "Use MONITOR/MWAIT for short idle");
+
+#define	STATE_RUNNING	0x0
+#define	STATE_MWAIT	0x1
+#define	STATE_SLEEPING	0x2
+
 static void
 cpu_idle_hlt(int busy)
 {
+	int *state;
+
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_SLEEPING;
 	/*
-	 * we must absolutely guarentee that hlt is the next instruction
+	 * We must absolutely guarentee that hlt is the next instruction
 	 * after sti or we introduce a timing window.
 	 */
 	disable_intr();
-  	if (sched_runnable())
+	if (sched_runnable())
 		enable_intr();
 	else
 		__asm __volatile("sti; hlt");
-}
-
-static void
-cpu_idle_spin(int busy)
-{
-	return;
-}
-
-void (*cpu_idle_fn)(int) = cpu_idle_hlt;
-
-void
-cpu_idle(int busy)
-{
-#if defined(SMP)
-	if (mp_grab_cpu_hlt())
-		return;
-#endif
-	cpu_idle_fn(busy);
+	*state = STATE_RUNNING;
 }
 
 /*
- * mwait cpu power states.  Lower 4 bits are sub-states.
+ * MWAIT cpu power states.  Lower 4 bits are sub-states.
  */
 #define	MWAIT_C0	0xf0
 #define	MWAIT_C1	0x00
@@ -1161,63 +1157,91 @@ cpu_idle(int busy)
 #define	MWAIT_C3	0x20
 #define	MWAIT_C4	0x30
 
-#define	MWAIT_DISABLED	0x0
-#define	MWAIT_WOKEN	0x1
-#define	MWAIT_WAITING	0x2
-
 static void
 cpu_idle_mwait(int busy)
 {
-	int *mwait;
+	int *state;
 
-	mwait = (int *)PCPU_PTR(monitorbuf);
-	*mwait = MWAIT_WAITING;
-	if (sched_runnable())
-		return;
-	cpu_monitor(mwait, 0, 0);
-	if (*mwait == MWAIT_WAITING)
-		cpu_mwait(0, MWAIT_C1);
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_MWAIT;
+	if (!sched_runnable()) {
+		cpu_monitor(state, 0, 0);
+		if (*state == STATE_MWAIT)
+			cpu_mwait(0, MWAIT_C1);
+	}
+	*state = STATE_RUNNING;
 }
 
 static void
-cpu_idle_mwait_hlt(int busy)
+cpu_idle_spin(int busy)
 {
-	int *mwait;
+	int *state;
+	int i;
 
-	mwait = (int *)PCPU_PTR(monitorbuf);
-	if (busy == 0) {
-		*mwait = MWAIT_DISABLED;
-		cpu_idle_hlt(busy);
-		return;
+	state = (int *)PCPU_PTR(monitorbuf);
+	*state = STATE_RUNNING;
+	for (i = 0; i < 1000; i++) {
+		if (sched_runnable())
+			return;
+		cpu_spinwait();
 	}
-	*mwait = MWAIT_WAITING;
-	if (sched_runnable())
+}
+
+void (*cpu_idle_fn)(int) = cpu_idle_hlt;
+
+void
+cpu_idle(int busy)
+{
+
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
+	    busy, curcpu);
+#ifdef SMP
+	if (mp_grab_cpu_hlt())
 		return;
-	cpu_monitor(mwait, 0, 0);
-	if (*mwait == MWAIT_WAITING)
-		cpu_mwait(0, MWAIT_C1);
+#endif
+	/* If we are busy - try to use fast methods. */
+	if (busy) {
+		if ((cpu_feature2 & CPUID2_MON) && idle_mwait) {
+			cpu_idle_mwait(busy);
+			goto out;
+		}
+	}
+
+	/* If we have time - switch timers into idle mode. */
+	if (!busy) {
+		critical_enter();
+		cpu_idleclock();
+	}
+
+	/* Call main idle method. */
+	cpu_idle_fn(busy);
+
+	/* Switch timers mack into active mode. */
+	if (!busy) {
+		cpu_activeclock();
+		critical_exit();
+	}
+out:
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
+	    busy, curcpu);
 }
 
 int
 cpu_idle_wakeup(int cpu)
 {
 	struct pcpu *pcpu;
-	int *mwait;
+	int *state;
 
-	if (cpu_idle_fn == cpu_idle_spin)
-		return (1);
-	if (cpu_idle_fn != cpu_idle_mwait && cpu_idle_fn != cpu_idle_mwait_hlt)
-		return (0);
 	pcpu = pcpu_find(cpu);
-	mwait = (int *)pcpu->pc_monitorbuf;
+	state = (int *)pcpu->pc_monitorbuf;
 	/*
 	 * This doesn't need to be atomic since missing the race will
 	 * simply result in unnecessary IPIs.
 	 */
-	if (cpu_idle_fn == cpu_idle_mwait_hlt && *mwait == MWAIT_DISABLED)
+	if (*state == STATE_SLEEPING)
 		return (0);
-	*mwait = MWAIT_WOKEN;
-
+	if (*state == STATE_MWAIT)
+		*state = STATE_RUNNING;
 	return (1);
 }
 
@@ -1230,7 +1254,6 @@ struct {
 } idle_tbl[] = {
 	{ cpu_idle_spin, "spin" },
 	{ cpu_idle_mwait, "mwait" },
-	{ cpu_idle_mwait_hlt, "mwait_hlt" },
 	{ cpu_idle_hlt, "hlt" },
 	{ NULL, NULL }
 };
@@ -1255,6 +1278,9 @@ idle_sysctl_available(SYSCTL_HANDLER_ARGS)
 	return (error);
 }
 
+SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
+    0, 0, idle_sysctl_available, "A", "list of available idle functions");
+
 static int
 idle_sysctl(SYSCTL_HANDLER_ARGS)
 {
@@ -1286,9 +1312,6 @@ idle_sysctl(SYSCTL_HANDLER_ARGS)
 	return (EINVAL);
 }
 
-SYSCTL_PROC(_machdep, OID_AUTO, idle_available, CTLTYPE_STRING | CTLFLAG_RD,
-    0, 0, idle_sysctl_available, "A", "list of available idle functions");
-
 SYSCTL_PROC(_machdep, OID_AUTO, idle, CTLTYPE_STRING | CTLFLAG_RW, 0, 0,
     idle_sysctl, "A", "currently selected idle function");
 
diff --git a/sys/powerpc/aim/machdep.c b/sys/powerpc/aim/machdep.c
index 3290fa67441..ba06531bc84 100644
--- a/sys/powerpc/aim/machdep.c
+++ b/sys/powerpc/aim/machdep.c
@@ -638,7 +638,13 @@ cpu_idle(int busy)
 		panic("ints disabled in idleproc!");
 	}
 #endif
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
+	    busy, curcpu);
 	if (powerpc_pow_enabled) {
+		if (!busy) {
+			critical_enter();
+			cpu_idleclock();
+		}
 		switch (vers) {
 		case IBM970:
 		case IBM970FX:
@@ -658,7 +664,13 @@ cpu_idle(int busy)
 			isync();
 			break;
 		}
+		if (!busy) {
+			cpu_activeclock();
+			critical_exit();
+		}
 	}
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
+	    busy, curcpu);
 }
 
 int
diff --git a/sys/powerpc/booke/machdep.c b/sys/powerpc/booke/machdep.c
index c725dd85bf3..c4b80cc665e 100644
--- a/sys/powerpc/booke/machdep.c
+++ b/sys/powerpc/booke/machdep.c
@@ -488,9 +488,21 @@ cpu_idle (int busy)
 	}
 #endif
 
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
+	    busy, curcpu);
+	if (!busy) {
+		critical_enter();
+		cpu_idleclock();
+	}
 	/* Freescale E500 core RM section 6.4.1. */
 	msr = msr | PSL_WE;
 	__asm __volatile("msync; mtmsr %0; isync" :: "r" (msr));
+	if (!busy) {
+		cpu_activeclock();
+		critical_exit();
+	}
+	CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
+	    busy, curcpu);
 }
 
 int
diff --git a/sys/powerpc/include/smp.h b/sys/powerpc/include/smp.h
index c78af741f70..cf952788c68 100644
--- a/sys/powerpc/include/smp.h
+++ b/sys/powerpc/include/smp.h
@@ -37,7 +37,6 @@
 #define	IPI_STOP		3
 #define	IPI_STOP_HARD		3
 #define	IPI_HARDCLOCK		4
-#define	IPI_STATCLOCK		5
 
 #ifndef LOCORE
 
diff --git a/sys/powerpc/powerpc/mp_machdep.c b/sys/powerpc/powerpc/mp_machdep.c
index a8336389f45..6915c4bb728 100644
--- a/sys/powerpc/powerpc/mp_machdep.c
+++ b/sys/powerpc/powerpc/mp_machdep.c
@@ -315,7 +315,7 @@ powerpc_ipi_handler(void *arg)
 			break;
 		case IPI_HARDCLOCK:
 			CTR1(KTR_SMP, "%s: IPI_HARDCLOCK", __func__);
-			hardclockintr(curthread->td_intr_frame);
+			hardclockintr();
 			break;
 		}
 	}
diff --git a/sys/sparc64/include/intr_machdep.h b/sys/sparc64/include/intr_machdep.h
index 254ac78a90b..158b5b6017a 100644
--- a/sys/sparc64/include/intr_machdep.h
+++ b/sys/sparc64/include/intr_machdep.h
@@ -47,7 +47,6 @@
 #define	PIL_STOP	5	/* stop cpu ipi */
 #define	PIL_PREEMPT	6	/* preempt idle thread cpu ipi */
 #define	PIL_HARDCLOCK	7	/* hardclock broadcast */
-#define	PIL_STATCLOCK	8	/* statclock broadcast */
 #define	PIL_FILTER	12	/* filter interrupts */
 #define	PIL_FAST	13	/* fast interrupts */
 #define	PIL_TICK	14	/* tick interrupts */
diff --git a/sys/sparc64/include/smp.h b/sys/sparc64/include/smp.h
index 3812431c143..3ca8e038044 100644
--- a/sys/sparc64/include/smp.h
+++ b/sys/sparc64/include/smp.h
@@ -59,7 +59,6 @@
 #define	IPI_RENDEZVOUS	PIL_RENDEZVOUS
 #define	IPI_PREEMPT	PIL_PREEMPT
 #define	IPI_HARDCLOCK	PIL_HARDCLOCK
-#define	IPI_STATCLOCK	PIL_STATCLOCK
 #define	IPI_STOP	PIL_STOP
 #define	IPI_STOP_HARD	PIL_STOP
 
diff --git a/sys/sparc64/sparc64/intr_machdep.c b/sys/sparc64/sparc64/intr_machdep.c
index 8e610f63951..85712865b1b 100644
--- a/sys/sparc64/sparc64/intr_machdep.c
+++ b/sys/sparc64/sparc64/intr_machdep.c
@@ -97,8 +97,7 @@ static const char *const pil_names[] = {
 	"stop",		/* PIL_STOP */
 	"preempt",	/* PIL_PREEMPT */
 	"hardclock",	/* PIL_HARDCLOCK */
-	"statclock",	/* PIL_STATCLOCK */
-	"stray", "stray", "stray",
+	"stray", "stray", "stray", "stray",
 	"filter",	/* PIL_FILTER */
 	"fast",		/* PIL_FAST */
 	"tick",		/* PIL_TICK */
diff --git a/sys/sparc64/sparc64/mp_machdep.c b/sys/sparc64/sparc64/mp_machdep.c
index 57a2d6f38ac..e5a9fb3eeb6 100644
--- a/sys/sparc64/sparc64/mp_machdep.c
+++ b/sys/sparc64/sparc64/mp_machdep.c
@@ -98,7 +98,6 @@ __FBSDID("$FreeBSD$");
 static ih_func_t cpu_ipi_ast;
 static ih_func_t cpu_ipi_hardclock;
 static ih_func_t cpu_ipi_preempt;
-static ih_func_t cpu_ipi_statclock;
 static ih_func_t cpu_ipi_stop;
 
 /*
@@ -292,7 +291,6 @@ cpu_mp_start(void)
 	intr_setup(PIL_STOP, cpu_ipi_stop, -1, NULL, NULL);
 	intr_setup(PIL_PREEMPT, cpu_ipi_preempt, -1, NULL, NULL);
 	intr_setup(PIL_HARDCLOCK, cpu_ipi_hardclock, -1, NULL, NULL);
-	intr_setup(PIL_STATCLOCK, cpu_ipi_statclock, -1, NULL, NULL);
 
 	cpuid_to_mid[curcpu] = PCPU_GET(mid);
 
@@ -524,15 +522,18 @@ cpu_ipi_preempt(struct trapframe *tf)
 static void
 cpu_ipi_hardclock(struct trapframe *tf)
 {
+	struct trapframe *oldframe;
+	struct thread *td;
 
-	hardclockintr(tf);
-}
-
-static void
-cpu_ipi_statclock(struct trapframe *tf)
-{
-
-	statclockintr(tf);
+	critical_enter();
+	td = curthread;
+	td->td_intr_nesting_level++;
+	oldframe = td->td_intr_frame;
+	td->td_intr_frame = tf;
+	hardclockintr();
+	td->td_intr_frame = oldframe;
+	td->td_intr_nesting_level--;
+	critical_exit();
 }
 
 static void
diff --git a/sys/sun4v/include/intr_machdep.h b/sys/sun4v/include/intr_machdep.h
index 370a5c0e2f4..f686e66f37e 100644
--- a/sys/sun4v/include/intr_machdep.h
+++ b/sys/sun4v/include/intr_machdep.h
@@ -47,7 +47,6 @@
 #define	PIL_STOP	5	/* stop cpu ipi */
 #define	PIL_PREEMPT	6	/* preempt idle thread cpu ipi */
 #define	PIL_HARDCLOCK	7	/* hardclock broadcast */
-#define	PIL_STATCLOCK	8	/* statclock broadcast */
 #define	PIL_FAST	13	/* fast interrupts */
 #define	PIL_TICK	14
 
diff --git a/sys/sun4v/include/smp.h b/sys/sun4v/include/smp.h
index 56c50ebbaed..3202089cbf1 100644
--- a/sys/sun4v/include/smp.h
+++ b/sys/sun4v/include/smp.h
@@ -47,7 +47,6 @@
 #define	IPI_STOP_HARD	PIL_STOP
 #define IPI_PREEMPT     PIL_PREEMPT
 #define	IPI_HARDCLOCK	PIL_HARDCLOCK
-#define	IPI_STATCLOCK	PIL_STATCLOCK
 
 #define	IPI_RETRIES	5000
 
@@ -83,7 +82,6 @@ void cpu_ipi_ast(struct trapframe *tf);
 void cpu_ipi_stop(struct trapframe *tf);
 void cpu_ipi_preempt(struct trapframe *tf);
 void cpu_ipi_hardclock(struct trapframe *tf);
-void cpu_ipi_statclock(struct trapframe *tf);
 
 void	ipi_all_but_self(u_int ipi);
 void	ipi_cpu(int cpu, u_int ipi);
diff --git a/sys/sun4v/sun4v/intr_machdep.c b/sys/sun4v/sun4v/intr_machdep.c
index 123493ef5bf..358740237f5 100644
--- a/sys/sun4v/sun4v/intr_machdep.c
+++ b/sys/sun4v/sun4v/intr_machdep.c
@@ -110,8 +110,7 @@ static char *pil_names[] = {
 	"stop",		/* PIL_STOP */
 	"preempt",      /* PIL_PREEMPT */
 	"hardclock",	/* PIL_HARDCLOCK */
-	"statclock",	/* PIL_STATCLOCK */
-	"stray", "stray", "stray", "stray",
+	"stray", "stray", "stray", "stray", "stray",
 	"fast",		/* PIL_FAST */
 	"tick",		/* PIL_TICK */
 };
@@ -265,7 +264,6 @@ intr_init(void)
 	intr_handlers[PIL_STOP]= cpu_ipi_stop;
 	intr_handlers[PIL_PREEMPT]= cpu_ipi_preempt;
 	intr_handlers[PIL_HARDCLOCK]= cpu_ipi_hardclock;
-	intr_handlers[PIL_STATCLOCK]= cpu_ipi_statclock;
 #endif
 	mtx_init(&intr_table_lock, "intr table", NULL, MTX_SPIN);
 	cpu_intrq_alloc();
diff --git a/sys/sun4v/sun4v/mp_machdep.c b/sys/sun4v/sun4v/mp_machdep.c
index 2e9a378d0ac..a9535e34d77 100644
--- a/sys/sun4v/sun4v/mp_machdep.c
+++ b/sys/sun4v/sun4v/mp_machdep.c
@@ -472,15 +472,18 @@ cpu_ipi_preempt(struct trapframe *tf)
 void
 cpu_ipi_hardclock(struct trapframe *tf)
 {
+	struct trapframe *oldframe;
+	struct thread *td;
 
-	hardclockintr(tf);
-}
-
-void
-cpu_ipi_statclock(struct trapframe *tf)
-{
-
-	statclockintr(tf);
+	critical_enter();
+	td = curthread;
+	td->td_intr_nesting_level++;
+	oldframe = td->td_intr_frame;
+	td->td_intr_frame = tf;
+	hardclockintr();
+	td->td_intr_frame = oldframe;
+	td->td_intr_nesting_level--;
+	critical_exit();
 }
 
 void
diff --git a/sys/sys/callout.h b/sys/sys/callout.h
index 2d43d1494ae..8fcd06e4f15 100644
--- a/sys/sys/callout.h
+++ b/sys/sys/callout.h
@@ -96,7 +96,8 @@ int	callout_schedule_on(struct callout *, int, int);
 #define	callout_stop(c)		_callout_stop_safe(c, 0)
 int	_callout_stop_safe(struct callout *, int);
 void	callout_tick(void);
-
+int	callout_tickstofirst(void);
+extern void (*callout_new_inserted)(int cpu, int ticks);
 
 #endif
 
diff --git a/sys/sys/sched.h b/sys/sys/sched.h
index d0ebffd5684..92dd4c4a138 100644
--- a/sys/sys/sched.h
+++ b/sys/sys/sched.h
@@ -111,7 +111,7 @@ void	sched_preempt(struct thread *td);
 void	sched_add(struct thread *td, int flags);
 void	sched_clock(struct thread *td);
 void	sched_rem(struct thread *td);
-void	sched_tick(void);
+void	sched_tick(int cnt);
 void	sched_relinquish(struct thread *td);
 struct thread *sched_choose(void);
 void	sched_idletd(void *);
diff --git a/sys/sys/systm.h b/sys/sys/systm.h
index f913887a0cd..8e98ef4bec5 100644
--- a/sys/sys/systm.h
+++ b/sys/sys/systm.h
@@ -237,20 +237,22 @@ void	realitexpire(void *);
 int	sysbeep(int hertz, int period);
 
 void	hardclock(int usermode, uintfptr_t pc);
+void	hardclock_anycpu(int cnt, int usermode);
 void	hardclock_cpu(int usermode);
+void	hardclock_sync(int cpu);
 void	softclock(void *);
 void	statclock(int usermode);
 void	profclock(int usermode, uintfptr_t pc);
-void	timer1clock(int usermode, uintfptr_t pc);
-void	timer2clock(int usermode, uintfptr_t pc);
 
-int	hardclockintr(struct trapframe *frame);
-int	statclockintr(struct trapframe *frame);
+int	hardclockintr(void);
 
 void	startprofclock(struct proc *);
 void	stopprofclock(struct proc *);
 void	cpu_startprofclock(void);
 void	cpu_stopprofclock(void);
+void	cpu_idleclock(void);
+void	cpu_activeclock(void);
+extern int	cpu_disable_deep_sleep;
 
 int	cr_cansee(struct ucred *u1, struct ucred *u2);
 int	cr_canseesocket(struct ucred *cred, struct socket *so);
diff --git a/sys/sys/timeet.h b/sys/sys/timeet.h
index bc713d68ed3..87392a29a64 100644
--- a/sys/sys/timeet.h
+++ b/sys/sys/timeet.h
@@ -83,8 +83,8 @@ struct eventtimer {
 };
 
 extern struct mtx	et_eventtimers_mtx;
-#define	ET_LOCK()	mtx_lock_spin(&et_eventtimers_mtx)
-#define	ET_UNLOCK()	mtx_unlock_spin(&et_eventtimers_mtx)
+#define	ET_LOCK()	mtx_lock(&et_eventtimers_mtx)
+#define	ET_UNLOCK()	mtx_unlock(&et_eventtimers_mtx)
 
 /* Driver API */
 int	et_register(struct eventtimer *et);
diff --git a/sys/sys/timetc.h b/sys/sys/timetc.h
index d5a818b4c0e..3249788563e 100644
--- a/sys/sys/timetc.h
+++ b/sys/sys/timetc.h
@@ -70,6 +70,7 @@ u_int64_t tc_getfrequency(void);
 void	tc_init(struct timecounter *tc);
 void	tc_setclock(struct timespec *ts);
 void	tc_ticktock(void);
+void	cpu_tick_calibration(void);
 
 #ifdef SYSCTL_DECL
 SYSCTL_DECL(_kern_timecounter);
diff --git a/sys/x86/x86/local_apic.c b/sys/x86/x86/local_apic.c
index f479bbee769..6d7a53b5fdc 100644
--- a/sys/x86/x86/local_apic.c
+++ b/sys/x86/x86/local_apic.c
@@ -261,7 +261,7 @@ lapic_init(vm_paddr_t addr)
 		lapic_et.et_quality = 600;
 		if (!arat) {
 			lapic_et.et_flags |= ET_FLAGS_C3STOP;
-			lapic_et.et_quality -= 100;
+			lapic_et.et_quality -= 200;
 		}
 		lapic_et.et_frequency = 0;
 		/* We don't know frequency yet, so trying to guess. */

From c614f4e2db8a59e491c5a6914b7f3c236c56884d Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 07:27:03 +0000
Subject: [PATCH 0693/1624] Prefer MACHINE_CPUARCH over MACHINE_ARCH

---
 sys/conf/kern.mk | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)

diff --git a/sys/conf/kern.mk b/sys/conf/kern.mk
index 32b71689a4f..4d8636cf734 100644
--- a/sys/conf/kern.mk
+++ b/sys/conf/kern.mk
@@ -29,7 +29,7 @@ CWARNFLAGS?=	-Wall -Wredundant-decls -Wnested-externs -Wstrict-prototypes \
 # operations inside the kernel itself.  These operations are exclusively
 # reserved for user applications.
 #
-.if ${MACHINE_ARCH} == "i386" && ${CC:T:Micc} != "icc"
+.if ${MACHINE_CPUARCH} == "i386" && ${CC:T:Micc} != "icc"
 .if ${CC:T:Mclang} != "clang"
 CFLAGS+=	-mno-align-long-strings -mpreferred-stack-boundary=2
 .endif
@@ -37,14 +37,14 @@ CFLAGS+=	-mno-mmx -mno-3dnow -mno-sse -mno-sse2 -mno-sse3
 INLINE_LIMIT?=	8000
 .endif
 
-.if ${MACHINE_ARCH} == "arm"
+.if ${MACHINE_CPUARCH} == "arm"
 INLINE_LIMIT?=	8000
 .endif
 #
 # For IA-64, we use r13 for the kernel globals pointer and we only use
 # a very small subset of float registers for integer divides.
 #
-.if ${MACHINE_ARCH} == "ia64"
+.if ${MACHINE_CPUARCH} == "ia64"
 CFLAGS+=	-ffixed-r13 -mfixed-range=f32-f127 -fpic #-mno-sdata
 INLINE_LIMIT?=	15000
 .endif
@@ -54,7 +54,7 @@ INLINE_LIMIT?=	15000
 # point emulation.  This avoids using floating point registers for integer
 # operations which it has a tendency to do.
 #
-.if ${MACHINE_ARCH} == "sparc64"
+.if ${MACHINE_CPUARCH} == "sparc64"
 CFLAGS+=	-mcmodel=medany -msoft-float
 INLINE_LIMIT?=	15000
 .endif
@@ -64,7 +64,7 @@ INLINE_LIMIT?=	15000
 # operations inside the kernel itself.  These operations are exclusively
 # reserved for user applications.
 #
-.if ${MACHINE_ARCH} == "amd64"
+.if ${MACHINE_CPUARCH} == "amd64"
 CFLAGS+=	-mcmodel=kernel -mno-red-zone \
 		-mfpmath=387 -mno-sse -mno-sse2 -mno-sse3 -mno-mmx -mno-3dnow \
 		-msoft-float -fno-asynchronous-unwind-tables
@@ -76,7 +76,7 @@ INLINE_LIMIT?=	8000
 # floating point registers for integer operations which it has a tendency to do.
 # Also explicitly disable Altivec instructions inside the kernel.
 #
-.if ${MACHINE_ARCH} == "powerpc" || ${MACHINE_ARCH} == "powerpc64"
+.if ${MACHINE_CPUARCH} == "powerpc"
 CFLAGS+=	-msoft-float -mno-altivec
 INLINE_LIMIT?=	15000
 .endif
@@ -84,7 +84,7 @@ INLINE_LIMIT?=	15000
 #
 # For MIPS we also tell gcc to use floating point emulation
 #
-.if ${MACHINE_ARCH} == "mips"
+.if ${MACHINE_CPUARCH} == "mips"
 CFLAGS+=	-msoft-float
 INLINE_LIMIT?=	8000
 .endif
@@ -106,8 +106,9 @@ CFLAGS+=	-restrict
 #
 # GCC SSP support.
 #
-.if ${MK_SSP} != "no" && ${CC:T:Micc} != "icc" && ${MACHINE_ARCH} != "ia64" && \
-	${MACHINE_ARCH} != "arm" && ${MACHINE_ARCH} != "mips"
+.if ${MK_SSP} != "no" && ${CC:T:Micc} != "icc" && \
+    ${MACHINE_CPUARCH} != "ia64" && ${MACHINE_CPUARCH} != "arm" && \
+    ${MACHINE_CPUARCH} != "mips"
 CFLAGS+=	-fstack-protector
 .endif
 

From 80dfae5fe2432fd72dead5aebe4a1592aaf39281 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 07:29:02 +0000
Subject: [PATCH 0694/1624] Simplify atomic selection

---
 sys/modules/opensolaris/Makefile |  8 ++++++--
 sys/modules/zfs/Makefile         | 13 ++++++++-----
 2 files changed, 14 insertions(+), 7 deletions(-)

diff --git a/sys/modules/opensolaris/Makefile b/sys/modules/opensolaris/Makefile
index eef8ffd6e35..ca4f12a39f6 100644
--- a/sys/modules/opensolaris/Makefile
+++ b/sys/modules/opensolaris/Makefile
@@ -8,8 +8,12 @@ SRCS=		opensolaris.c		\
 		opensolaris_kmem.c	\
 		opensolaris_misc.c
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "ia64" || ${MACHINE_ARCH} == "sparc64" || ${MACHINE_ARCH} == "powerpc64"
-.PATH:	${.CURDIR}/../../cddl/contrib/opensolaris/common/atomic/${MACHINE_ARCH}
+_A=${.CURDIR}/../../cddl/contrib/opensolaris/common/atomic
+.if exists(${_A}/${MACHINE_CPUARCH}/opensolaris_atomic.S)
+.PATH:	${_A}/${MACHINE_CPUARCH}
+SRCS+=		opensolaris_atomic.S
+.elif exists(${_A}/${MACHINE_ARCH}/opensolaris_atomic.S)
+.PATH:	${_A}/${MACHINE_ARCH}
 SRCS+=		opensolaris_atomic.S
 .else
 SRCS+=		opensolaris_atomic.c
diff --git a/sys/modules/zfs/Makefile b/sys/modules/zfs/Makefile
index e4cf297fc7d..d0a6f44bde3 100644
--- a/sys/modules/zfs/Makefile
+++ b/sys/modules/zfs/Makefile
@@ -27,12 +27,15 @@ SRCS+=	opensolaris_uio.c
 SRCS+=	opensolaris_vfs.c
 SRCS+=	opensolaris_zone.c
 
-.if ${MACHINE_ARCH} == "i386" || ${MACHINE_ARCH} == "amd64" || ${MACHINE_ARCH} == "ia64" || ${MACHINE_ARCH} == "sparc64" || ${MACHINE_ARCH} == "powerpc64"
-.PATH:	${SUNW}/common/atomic/${MACHINE_ARCH}
-SRCS+=	opensolaris_atomic.S
+_A=${.CURDIR}/../../cddl/contrib/opensolaris/common/atomic
+.if exists(${_A}/${MACHINE_CPUARCH}/opensolaris_atomic.S)
+.PATH:	${_A}/${MACHINE_CPUARCH}
+SRCS+=		opensolaris_atomic.S
+.elif exists(${_A}/${MACHINE_ARCH}/opensolaris_atomic.S)
+.PATH:	${_A}/${MACHINE_ARCH}
+SRCS+=		opensolaris_atomic.S
 .else
-.PATH:	${.CURDIR}/../../cddl/compat/opensolaris/kern
-SRCS+=	opensolaris_atomic.c
+SRCS+=		opensolaris_atomic.c
 .endif
 
 .PATH:	${SUNW}/uts/common/fs

From b7d28b2e0b39e28d5f7f35c66be2ab81de3cc75c Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Mon, 13 Sep 2010 08:34:20 +0000
Subject: [PATCH 0695/1624] bus_add_child: add specialized default
 implementation that calls panic

If a kobj method doesn't have any explicitly provided default
implementation, then it is auto-assigned kobj_error_method.
kobj_error_method is proper only for methods that return error code,
because it just returns ENXIO.
So, in the case of unimplemented bus_add_child caller would get
(device_t)ENXIO as a return value, which would cause the mistake to go
unnoticed, because return value is typically checked for NULL.
Thus, a specialized null_add_child is added.  It would have sufficied
for correctness to return NULL, but this type of mistake was deemed to
be rare and serious enough to call panic instead.

Watch out for this kind of problem with other kobj methods.

Suggested by:	jhb, imp
MFC after:	2 weeks
---
 sys/kern/bus_if.m | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/sys/kern/bus_if.m b/sys/kern/bus_if.m
index 688a47010e8..de808ded638 100644
--- a/sys/kern/bus_if.m
+++ b/sys/kern/bus_if.m
@@ -26,6 +26,8 @@
 # $FreeBSD$
 #
 
+#include 
+#include 
 #include 
 
 /**
@@ -56,6 +58,14 @@ CODE {
 			return (BUS_REMAP_INTR(dev, NULL, irq));
 		return (ENXIO);
 	}
+
+	static device_t
+	null_add_child(device_t bus, int order, const char *name,
+	    int unit)
+	{
+
+		panic("bus_add_child is not implemented");
+	}
 };
 
 /**
@@ -203,7 +213,7 @@ METHOD device_t add_child {
 	u_int _order;
 	const char *_name;
 	int _unit;
-};
+} DEFAULT null_add_child;
 
 /**
  * @brief Allocate a system resource

From a478ea74908024df80e60a025777d0aa23e23a2c Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 13 Sep 2010 08:56:07 +0000
Subject: [PATCH 0696/1624] - Allow to specify value as const pointers. - Make
 optional string values always an empty string.

---
 sbin/geom/class/eli/geom_eli.c       | 33 +++++++++++++---------------
 sbin/geom/class/mirror/geom_mirror.c |  7 +++---
 sbin/geom/class/part/geom_part.c     | 17 +++++++-------
 sbin/geom/class/sched/geom_sched.c   | 10 ++++-----
 sbin/geom/core/geom.c                | 32 ++++++++++++++-------------
 sbin/geom/core/geom.h                |  2 +-
 sys/geom/eli/g_eli_ctl.c             |  2 +-
 sys/geom/mirror/g_mirror_ctl.c       |  4 ++--
 8 files changed, 53 insertions(+), 54 deletions(-)

diff --git a/sbin/geom/class/eli/geom_eli.c b/sbin/geom/class/eli/geom_eli.c
index d772a9a11e6..d5acc99e4b5 100644
--- a/sbin/geom/class/eli/geom_eli.c
+++ b/sbin/geom/class/eli/geom_eli.c
@@ -55,15 +55,12 @@ uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_ELI_VERSION;
 
 #define	GELI_BACKUP_DIR	"/var/backups/"
+#define	GELI_ENC_ALGO	"aes"
 
-static char aalgo[] = "none";
-static char ealgo[] = "aes";
 static intmax_t keylen = 0;
 static intmax_t keyno = -1;
 static intmax_t iterations = -1;
 static intmax_t sectorsize = 0;
-static char keyfile[] = "", newkeyfile[] = "";
-static char backupfile[] = "";
 
 static void eli_main(struct gctl_req *req, unsigned flags);
 static void eli_init(struct gctl_req *req);
@@ -101,12 +98,12 @@ static int eli_backup_create(struct gctl_req *req, const char *prov,
 struct g_command class_commands[] = {
 	{ "init", G_FLAG_VERBOSE, eli_main,
 	    {
-		{ 'a', "aalgo", aalgo, G_TYPE_STRING },
+		{ 'a', "aalgo", "", G_TYPE_STRING },
 		{ 'b', "boot", NULL, G_TYPE_BOOL },
-		{ 'B', "backupfile", backupfile, G_TYPE_STRING },
-		{ 'e', "ealgo", ealgo, G_TYPE_STRING },
+		{ 'B', "backupfile", "", G_TYPE_STRING },
+		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
 		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
-		{ 'K', "newkeyfile", newkeyfile, G_TYPE_STRING },
+		{ 'K', "newkeyfile", "", G_TYPE_STRING },
 		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
 		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
 		{ 's', "sectorsize", §orsize, G_TYPE_NUMBER },
@@ -116,12 +113,12 @@ struct g_command class_commands[] = {
 	},
 	{ "label", G_FLAG_VERBOSE, eli_main,
 	    {
-		{ 'a', "aalgo", aalgo, G_TYPE_STRING },
+		{ 'a', "aalgo", "", G_TYPE_STRING },
 		{ 'b', "boot", NULL, G_TYPE_BOOL },
-		{ 'B', "backupfile", backupfile, G_TYPE_STRING },
-		{ 'e', "ealgo", ealgo, G_TYPE_STRING },
+		{ 'B', "backupfile", "", G_TYPE_STRING },
+		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
 		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
-		{ 'K', "newkeyfile", newkeyfile, G_TYPE_STRING },
+		{ 'K', "newkeyfile", "", G_TYPE_STRING },
 		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
 		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
 		{ 's', "sectorsize", §orsize, G_TYPE_NUMBER },
@@ -132,7 +129,7 @@ struct g_command class_commands[] = {
 	{ "attach", G_FLAG_VERBOSE | G_FLAG_LOADKLD, eli_main,
 	    {
 		{ 'd', "detach", NULL, G_TYPE_BOOL },
-		{ 'k', "keyfile", keyfile, G_TYPE_STRING },
+		{ 'k', "keyfile", "", G_TYPE_STRING },
 		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
 		{ 'r', "readonly", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
@@ -157,9 +154,9 @@ struct g_command class_commands[] = {
 	},
 	{ "onetime", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
 	    {
-		{ 'a', "aalgo", aalgo, G_TYPE_STRING },
+		{ 'a', "aalgo", "", G_TYPE_STRING },
 		{ 'd', "detach", NULL, G_TYPE_BOOL },
-		{ 'e', "ealgo", ealgo, G_TYPE_STRING },
+		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
 		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
 		{ 's', "sectorsize", §orsize, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
@@ -177,8 +174,8 @@ struct g_command class_commands[] = {
 	{ "setkey", G_FLAG_VERBOSE, eli_main,
 	    {
 		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
-		{ 'k', "keyfile", keyfile, G_TYPE_STRING },
-		{ 'K', "newkeyfile", newkeyfile, G_TYPE_STRING },
+		{ 'k', "keyfile", "", G_TYPE_STRING },
+		{ 'K', "newkeyfile", "", G_TYPE_STRING },
 		{ 'n', "keyno", &keyno, G_TYPE_NUMBER },
 		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
 		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
@@ -551,7 +548,7 @@ eli_init(struct gctl_req *req)
 		md.md_flags |= G_ELI_FLAG_BOOT;
 	md.md_ealgo = CRYPTO_ALGORITHM_MIN - 1;
 	str = gctl_get_ascii(req, "aalgo");
-	if (strcmp(str, "none") != 0) {
+	if (*str != '\0') {
 		md.md_aalgo = g_eli_str2aalgo(str);
 		if (md.md_aalgo >= CRYPTO_ALGORITHM_MIN &&
 		    md.md_aalgo <= CRYPTO_ALGORITHM_MAX) {
diff --git a/sbin/geom/class/mirror/geom_mirror.c b/sbin/geom/class/mirror/geom_mirror.c
index cf15c60af9d..de51fb13f0b 100644
--- a/sbin/geom/class/mirror/geom_mirror.c
+++ b/sbin/geom/class/mirror/geom_mirror.c
@@ -44,7 +44,8 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_MIRROR_VERSION;
 
-static char label_balance[] = "load", configure_balance[] = "none";
+#define	GMIRROR_BALANCE	"load"
+
 static intmax_t label_slice = 4096, configure_slice = -1;
 static intmax_t insert_priority = 0, configure_priority = -1;
 
@@ -64,7 +65,7 @@ struct g_command class_commands[] = {
 	{ "configure", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'a', "autosync", NULL, G_TYPE_BOOL },
-		{ 'b', "balance", configure_balance, G_TYPE_STRING },
+		{ 'b', "balance", "", G_TYPE_STRING },
 		{ 'd', "dynamic", NULL, G_TYPE_BOOL },
 		{ 'f', "failsync", NULL, G_TYPE_BOOL },
 		{ 'F', "nofailsync", NULL, G_TYPE_BOOL },
@@ -88,7 +89,7 @@ struct g_command class_commands[] = {
 	},
 	{ "label", G_FLAG_VERBOSE, mirror_main,
 	    {
-		{ 'b', "balance", label_balance, G_TYPE_STRING },
+		{ 'b', "balance", GMIRROR_BALANCE, G_TYPE_STRING },
 		{ 'F', "nofailsync", NULL, G_TYPE_BOOL },
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
 		{ 'n', "noautosync", NULL, G_TYPE_BOOL },
diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index cc1145e1aa5..658fba6ed7f 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -59,7 +59,6 @@ uint32_t PUBSYM(lib_version) = G_LIB_VERSION;
 uint32_t PUBSYM(version) = 0;
 
 static char autofill[] = "*";
-static char optional[] = "";
 static char flags[] = "C";
 
 static char sstart[32];
@@ -91,16 +90,16 @@ struct g_command PUBSYM(class_commands)[] = {
 		{ 'b', "start", autofill, G_TYPE_STRING },
 		{ 's', "size", autofill, G_TYPE_STRING },
 		{ 't', "type", NULL, G_TYPE_STRING },
-		{ 'i', index_param, optional, G_TYPE_ASCNUM },
-		{ 'l', "label", optional, G_TYPE_STRING },
+		{ 'i', index_param, "", G_TYPE_ASCNUM },
+		{ 'l', "label", "", G_TYPE_STRING },
 		{ 'f', "flags", flags, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	  "geom", NULL
 	},
 	{ "bootcode", 0, gpart_bootcode, {
-		{ 'b', bootcode_param, optional, G_TYPE_STRING },
-		{ 'p', partcode_param, optional, G_TYPE_STRING },
-		{ 'i', index_param, optional, G_TYPE_ASCNUM },
+		{ 'b', bootcode_param, "", G_TYPE_STRING },
+		{ 'p', partcode_param, "", G_TYPE_STRING },
+		{ 'i', index_param, "", G_TYPE_ASCNUM },
 		{ 'f', "flags", flags, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	  "geom", NULL
@@ -108,7 +107,7 @@ struct g_command PUBSYM(class_commands)[] = {
 	{ "commit", 0, gpart_issue, G_NULL_OPTS, "geom", NULL },
 	{ "create", 0, gpart_issue, {
 		{ 's', "scheme", NULL, G_TYPE_STRING },
-		{ 'n', "entries", optional, G_TYPE_ASCNUM },
+		{ 'n', "entries", "", G_TYPE_ASCNUM },
 		{ 'f', "flags", flags, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	  "provider", NULL
@@ -125,8 +124,8 @@ struct g_command PUBSYM(class_commands)[] = {
 	  "geom", NULL },
 	{ "modify", 0, gpart_issue, {
 		{ 'i', index_param, NULL, G_TYPE_ASCNUM },
-		{ 'l', "label", optional, G_TYPE_STRING },
-		{ 't', "type", optional, G_TYPE_STRING },
+		{ 'l', "label", "", G_TYPE_STRING },
+		{ 't', "type", "", G_TYPE_STRING },
 		{ 'f', "flags", flags, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	  "geom", NULL
diff --git a/sbin/geom/class/sched/geom_sched.c b/sbin/geom/class/sched/geom_sched.c
index ca05350805b..eba8e49e78e 100644
--- a/sbin/geom/class/sched/geom_sched.c
+++ b/sbin/geom/class/sched/geom_sched.c
@@ -54,7 +54,7 @@ uint32_t version = G_SCHED_VERSION;
  * storage for parameters used by this geom class.
  * Right now only the scheduler name is used.
  */
-static char algo[] = "rr";	/* default scheduler */
+#define	GSCHED_ALGO	"rr"	/* default scheduler */
 
 /*
  * Adapt to differences in geom library.
@@ -76,7 +76,7 @@ gcmd_createinsert(struct gctl_req *req, unsigned flags __unused)
 	if (gctl_has_param(req, "algo"))
 		reqalgo = gctl_get_ascii(req, "algo");
 	else
-		reqalgo = algo;
+		reqalgo = GSCHED_ALGO;
 
 	snprintf(name, sizeof(name), "gsched_%s", reqalgo);
 	/*
@@ -91,21 +91,21 @@ gcmd_createinsert(struct gctl_req *req, unsigned flags __unused)
 struct g_command class_commands[] = {
 	{ "create", G_FLAG_VERBOSE | G_FLAG_LOADKLD, gcmd_createinsert,
 	    {
-		{ 'a', "algo", algo, G_TYPE_STRING },
+		{ 'a', "algo", GSCHED_ALGO, G_TYPE_STRING },
 		G_OPT_SENTINEL
 	    },
 	    G_ARGNAME "[-v] [-a algorithm_name] dev ..."
 	},
 	{ "insert", G_FLAG_VERBOSE | G_FLAG_LOADKLD, gcmd_createinsert,
 	    {
-		{ 'a', "algo", algo, G_TYPE_STRING },
+		{ 'a', "algo", GSCHED_ALGO, G_TYPE_STRING },
 		G_OPT_SENTINEL
 	    },
 	    G_ARGNAME "[-v] [-a algorithm_name] dev ..."
 	},
 	{ "configure", G_FLAG_VERBOSE, NULL,
 	    {
-		{ 'a', "algo", algo, G_TYPE_STRING },
+		{ 'a', "algo", GSCHED_ALGO, G_TYPE_STRING },
 		G_OPT_SENTINEL
 	    },
 	    G_ARGNAME "[-v] [-a algorithm_name] prov ..."
diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index f673aad5413..b891098df03 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -236,8 +236,8 @@ find_option(struct g_command *cmd, char ch)
 static void
 set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 {
-	char *s;
 	uint64_t number;
+	void *ptr;
 
 	if (G_OPT_TYPE(opt) == G_TYPE_NUMBER ||
 	    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {
@@ -245,27 +245,29 @@ set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 			err(EXIT_FAILURE, "Invalid value for '%c' argument.",
 			    opt->go_char);
 		}
-		if (G_OPT_TYPE(opt) == G_TYPE_NUMBER)
-			opt->go_val = malloc(sizeof(intmax_t));
-		else {
-			asprintf(&s, "%jd", number);
-			opt->go_val = s;
-		}
-		if (opt->go_val == NULL)
-			errx(EXIT_FAILURE, "No memory.");
 		if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) {
-			*(intmax_t *)opt->go_val = number;
+			ptr = malloc(sizeof(intmax_t));
+			if (ptr == NULL)
+				errx(EXIT_FAILURE, "No memory.");
+			*(intmax_t *)ptr = number;
+			opt->go_val = ptr;
 			gctl_ro_param(req, opt->go_name, sizeof(intmax_t),
 			    opt->go_val);
-		} else
+		} else {
+			asprintf((void *)(&ptr), "%jd", number);
+			if (ptr == NULL)
+				errx(EXIT_FAILURE, "No memory.");
+			opt->go_val = ptr;
 			gctl_ro_param(req, opt->go_name, -1, opt->go_val);
+		}
 	} else if (G_OPT_TYPE(opt) == G_TYPE_STRING) {
 		gctl_ro_param(req, opt->go_name, -1, val);
 	} else if (G_OPT_TYPE(opt) == G_TYPE_BOOL) {
-		opt->go_val = malloc(sizeof(int));
-		if (opt->go_val == NULL)
+		ptr = malloc(sizeof(int));
+		if (ptr == NULL)
 			errx(EXIT_FAILURE, "No memory.");
-		*(int *)opt->go_val = *val - '0';
+		*(int *)ptr = *val - '0';
+		opt->go_val = ptr;
 		gctl_ro_param(req, opt->go_name, sizeof(int), opt->go_val);
 	} else {
 		assert(!"Invalid type");
@@ -354,7 +356,7 @@ parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc,
 				    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {
 					if (cmd->gc_argname == NULL ||
 					    opt->go_val == NULL ||
-					    *(char *)opt->go_val != '\0')
+					    *(const char *)opt->go_val != '\0')
 						gctl_ro_param(req, opt->go_name,
 						    -1, opt->go_val);
 				} else {
diff --git a/sbin/geom/core/geom.h b/sbin/geom/core/geom.h
index 424695bd76e..e2f96e9b846 100644
--- a/sbin/geom/core/geom.h
+++ b/sbin/geom/core/geom.h
@@ -54,7 +54,7 @@
 struct g_option {
 	char		 go_char;
 	const char	*go_name;
-	void		*go_val;
+	const void	*go_val;
 	unsigned	 go_type;
 };
 
diff --git a/sys/geom/eli/g_eli_ctl.c b/sys/geom/eli/g_eli_ctl.c
index 558a4f278f1..1d0dddfffc9 100644
--- a/sys/geom/eli/g_eli_ctl.c
+++ b/sys/geom/eli/g_eli_ctl.c
@@ -269,7 +269,7 @@ g_eli_ctl_onetime(struct gctl_req *req, struct g_class *mp)
 		gctl_error(req, "No '%s' argument.", "aalgo");
 		return;
 	}
-	if (strcmp(name, "none") != 0) {
+	if (*name != '\0') {
 		md.md_aalgo = g_eli_str2aalgo(name);
 		if (md.md_aalgo >= CRYPTO_ALGORITHM_MIN &&
 		    md.md_aalgo <= CRYPTO_ALGORITHM_MAX) {
diff --git a/sys/geom/mirror/g_mirror_ctl.c b/sys/geom/mirror/g_mirror_ctl.c
index 4524a90d8dd..dc59e185133 100644
--- a/sys/geom/mirror/g_mirror_ctl.c
+++ b/sys/geom/mirror/g_mirror_ctl.c
@@ -192,7 +192,7 @@ g_mirror_ctl_configure(struct gctl_req *req, struct g_class *mp)
 		gctl_error(req, "No such device: %s.", name);
 		return;
 	}
-	if (strcmp(balancep, "none") == 0)
+	if (*balancep == '\0')
 		balance = sc->sc_balance;
 	else {
 		if (balance_id(balancep) == -1) {
@@ -215,7 +215,7 @@ g_mirror_ctl_configure(struct gctl_req *req, struct g_class *mp)
 	/* Enforce usage() of -p not allowing any other options. */
 	if (do_priority && (*autosync || *noautosync || *failsync ||
 	    *nofailsync || *hardcode || *dynamic || *slicep != -1 ||
-	    strcmp(balancep, "none") != 0)) {
+	    *balancep != '\0')) {
 		sx_xunlock(&sc->sc_lock);
 		gctl_error(req, "only -p accepted when setting priority");
 		return;

From fa1efe5efd9e628141df7f9fbaad9b0e60b961a1 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Mon, 13 Sep 2010 09:23:38 +0000
Subject: [PATCH 0697/1624] Update symbol.

---
 lib/libthr/pthread.map | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/libthr/pthread.map b/lib/libthr/pthread.map
index 4eebb6254d4..bcb5c085d8f 100644
--- a/lib/libthr/pthread.map
+++ b/lib/libthr/pthread.map
@@ -173,6 +173,7 @@ FBSDprivate_1.0 {
 	___creat;
 	___pause;
 	___pselect;
+	___sigwait;
 	___sleep;
 	___system;
 	___tcdrain;
@@ -206,7 +207,6 @@ FBSDprivate_1.0 {
 	__sendto;
 	__sigsuspend;
 	__sigtimedwait;
-	__sigwait;
 	__sigwaitinfo;
 	__wait3;
 	__wait4;

From 09c22c66e1ae111929ebb1ac68d556f2e95bedd5 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Mon, 13 Sep 2010 09:51:24 +0000
Subject: [PATCH 0698/1624] acpi_cpu: do not apply P_LVLx_LAT rules to
 latencies returned by _CST

ACPI specification sates that if P_LVL2_LAT > 100, then a system doesn't
support C2; if P_LVL3_LAT > 1000, then C3 is not supported.
But there are no such rules for Cx state data returned by _CST.  If a
state is not supported it should not be included into the return
package.  In other words, any latency value returned by _CST is valid,
it's up to the OS and/or user to decide whether to use it.

Submitted by:	nork
Suggested by:	mav
MFC after:	1 week
---
 sys/dev/acpica/acpi_cpu.c | 10 +---------
 1 file changed, 1 insertion(+), 9 deletions(-)

diff --git a/sys/dev/acpica/acpi_cpu.c b/sys/dev/acpica/acpi_cpu.c
index fabbee90d1c..9f0ca8923d6 100644
--- a/sys/dev/acpica/acpi_cpu.c
+++ b/sys/dev/acpica/acpi_cpu.c
@@ -690,19 +690,11 @@ acpi_cpu_cx_cst(struct acpi_cpu_softc *sc)
 	    sc->cpu_cx_count++;
 	    continue;
 	case ACPI_STATE_C2:
-	    if (cx_ptr->trans_lat > 100) {
-		ACPI_DEBUG_PRINT((ACPI_DB_INFO,
-				 "acpi_cpu%d: C2[%d] not available.\n",
-				 device_get_unit(sc->cpu_dev), i));
-		continue;
-	    }
 	    sc->cpu_non_c3 = i;
 	    break;
 	case ACPI_STATE_C3:
 	default:
-	    if (cx_ptr->trans_lat > 1000 ||
-		(cpu_quirks & CPU_QUIRK_NO_C3) != 0) {
-
+	    if ((cpu_quirks & CPU_QUIRK_NO_C3) != 0) {
 		ACPI_DEBUG_PRINT((ACPI_DB_INFO,
 				 "acpi_cpu%d: C3[%d] not available.\n",
 				 device_get_unit(sc->cpu_dev), i));

From 04a68e090438c846523ef46483bd38edea959b44 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 13 Sep 2010 11:47:35 +0000
Subject: [PATCH 0699/1624] bus_add_child method is needed now.

---
 sys/mips/rmi/iodi.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c
index c9913f20d48..31cc6e7be3b 100644
--- a/sys/mips/rmi/iodi.c
+++ b/sys/mips/rmi/iodi.c
@@ -305,6 +305,7 @@ static device_method_t iodi_methods[] = {
 	DEVMETHOD(device_identify, iodi_identify),
 	DEVMETHOD(bus_alloc_resource, iodi_alloc_resource),
 	DEVMETHOD(bus_activate_resource, iodi_activate_resource),
+	DEVMETHOD(bus_add_child, bus_generic_add_child),
 	DEVMETHOD(bus_setup_intr, iodi_setup_intr),
 	{0, 0},
 };

From cbadc1d7ad2d648c65c6683a0d5c92e2ac1d50c9 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Mon, 13 Sep 2010 11:57:46 +0000
Subject: [PATCH 0700/1624] Fix copy&paste problem.

---
 lib/libthr/thread/thr_private.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index bdf4aa4673f..aff59a2224e 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -415,8 +415,8 @@ struct pthread {
 #define THR_FLAGS_PRIVATE	0x0001
 #define	THR_FLAGS_NEED_SUSPEND	0x0002	/* thread should be suspended */
 #define	THR_FLAGS_SUSPENDED	0x0004	/* thread is suspended */
-#define	THR_FLAGS_IN_GCLIST	0x0004	/* thread in gc list */
-#define	THR_FLAGS_DETACHED	0x0008	/* thread is detached */
+#define	THR_FLAGS_IN_GCLIST	0x0008	/* thread in gc list */
+#define	THR_FLAGS_DETACHED	0x0010	/* thread is detached */
 
 	/* Thread list flags; only set with thread list lock held. */
 	int			tlflags;

From 7820a71113a0aa4ebd652d9125aafc416e3c426d Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Mon, 13 Sep 2010 11:58:42 +0000
Subject: [PATCH 0701/1624] Don't compare thread pointers again.

---
 lib/libthr/thread/thr_affinity.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/lib/libthr/thread/thr_affinity.c b/lib/libthr/thread/thr_affinity.c
index 3f9322453f9..7e9b0f9620f 100644
--- a/lib/libthr/thread/thr_affinity.c
+++ b/lib/libthr/thread/thr_affinity.c
@@ -70,13 +70,13 @@ _pthread_getaffinity_np(pthread_t td, size_t cpusetsize, cpuset_t *cpusetp)
 
 	if (td == curthread) {
 		error = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
-			(td == curthread) ? -1 : tid, cpusetsize, cpusetp);
+			-1, cpusetsize, cpusetp);
 		if (error == -1)
 			error = errno;
 	} else if ((error = _thr_find_thread(curthread, td, 0)) == 0) {
 		tid = TID(td);
-		error = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
-			(td == curthread) ? -1 : tid, cpusetsize, cpusetp);
+		error = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, tid,
+			    cpusetsize, cpusetp);
 		if (error == -1)
 			error = errno;
 		THR_THREAD_UNLOCK(curthread, td);

From 480f6157fbe19fe844ea93c24e7c32aa24572373 Mon Sep 17 00:00:00 2001
From: "Jayachandran C." 
Date: Mon, 13 Sep 2010 13:11:50 +0000
Subject: [PATCH 0702/1624] sys/mips/rmi/msgring.h - fixes and clean up.

- Remove sync from msgrng_send, sync needs to be called just once before
  sending.
- Fix retry logic - don't reload registers when retrying in message_send,
  also fix check for send pending fail.
- remove unused message_send_block_fast()
- merge message_receive_fast() to message_receive
- style(9) fixes, and comments
- rge and nlge updated for the sys/mips/rmi/msgring.h changes
---
 sys/mips/rmi/dev/nlge/if_nlge.c |   4 +-
 sys/mips/rmi/dev/xlr/rge.c      |   4 +-
 sys/mips/rmi/msgring.h          | 425 +++++++++++++++-----------------
 3 files changed, 198 insertions(+), 235 deletions(-)

diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c
index d6c16a50cd9..a80b2674539 100644
--- a/sys/mips/rmi/dev/nlge/if_nlge.c
+++ b/sys/mips/rmi/dev/nlge/if_nlge.c
@@ -1035,7 +1035,7 @@ nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc)
 		n = 0;
 		do {
 			msgrng_flags = msgrng_access_enable();
-			ret = message_send_retry(1, code, stid, &msg);
+			ret = message_send(1, code, stid, &msg);
 			msgrng_restore(msgrng_flags);
 			KASSERT(n++ < 100000, ("Too many credit fails\n"));
 		} while (ret != 0);
@@ -1960,7 +1960,7 @@ send_fmn_msg_tx(struct nlge_softc *sc, struct msgrng_msg *msg,
 
 	do {
 		msgrng_flags = msgrng_access_enable();
-		ret = message_send_retry(n_entries, MSGRNG_CODE_MAC,
+		ret = message_send(n_entries, MSGRNG_CODE_MAC,
 		    sc->tx_bucket_id, msg);
 		msgrng_restore(msgrng_flags);
 		KASSERT(i++ < 100000, ("Too many credit fails\n"));
diff --git a/sys/mips/rmi/dev/xlr/rge.c b/sys/mips/rmi/dev/xlr/rge.c
index 661c7895b57..c7a02c261d1 100644
--- a/sys/mips/rmi/dev/xlr/rge.c
+++ b/sys/mips/rmi/dev/xlr/rge.c
@@ -731,7 +731,7 @@ xlr_mac_send_fr(struct driver_data *priv,
 
 	do {
 		msgrng_flags = msgrng_access_enable();
-		ret = message_send_retry(1, code, stid, &msg);
+		ret = message_send(1, code, stid, &msg);
 		msgrng_restore(msgrng_flags);
 		KASSERT(i++ < 100000, ("Too many credit fails\n"));
 	} while (ret != 0);
@@ -1468,7 +1468,7 @@ mac_xmit(struct mbuf *m, struct rge_softc *sc,
 
 	else {
 		mflags = msgrng_access_enable();
-		if ((rv = message_send_retry(1, MSGRNG_CODE_MAC, stid, &msg)) != 0) {
+		if ((rv = message_send(1, MSGRNG_CODE_MAC, stid, &msg)) != 0) {
 			msg_snd_failed++;
 			msgrng_restore(mflags);
 			release_tx_desc(&msg, 0);
diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h
index 6e61b50d8d9..ae3d9d49dce 100644
--- a/sys/mips/rmi/msgring.h
+++ b/sys/mips/rmi/msgring.h
@@ -46,16 +46,16 @@
 #define	MSGRNG_MSG_CONFIG_REG	3
 #define MSGRNG_MSG_BUCKSIZE_REG	4
 
-#define	MSGRNG_CC_0_REG	16
-#define	MSGRNG_CC_1_REG	17
-#define	MSGRNG_CC_2_REG	18
-#define	MSGRNG_CC_3_REG	19
-#define	MSGRNG_CC_4_REG	20
-#define	MSGRNG_CC_5_REG	21
-#define	MSGRNG_CC_6_REG	22
-#define	MSGRNG_CC_7_REG	23
-#define	MSGRNG_CC_8_REG	24
-#define	MSGRNG_CC_9_REG	25
+#define	MSGRNG_CC_0_REG		16
+#define	MSGRNG_CC_1_REG		17
+#define	MSGRNG_CC_2_REG		18
+#define	MSGRNG_CC_3_REG		19
+#define	MSGRNG_CC_4_REG		20
+#define	MSGRNG_CC_5_REG		21
+#define	MSGRNG_CC_6_REG		22
+#define	MSGRNG_CC_7_REG		23
+#define	MSGRNG_CC_8_REG		24
+#define	MSGRNG_CC_9_REG		25
 #define	MSGRNG_CC_10_REG	26
 #define	MSGRNG_CC_11_REG	27
 #define	MSGRNG_CC_12_REG	28
@@ -64,173 +64,170 @@
 #define	MSGRNG_CC_15_REG	31
 
 /* Station IDs */
-#define MSGRNG_STNID_CPU0  0x00
-#define MSGRNG_STNID_CPU1  0x08
-#define MSGRNG_STNID_CPU2  0x10
-#define MSGRNG_STNID_CPU3  0x18
-#define MSGRNG_STNID_CPU4  0x20
-#define MSGRNG_STNID_CPU5  0x28
-#define MSGRNG_STNID_CPU6  0x30
-#define MSGRNG_STNID_CPU7  0x38
-#define MSGRNG_STNID_XGS0_TX 64
-#define MSGRNG_STNID_XMAC0_00_TX 64
-#define MSGRNG_STNID_XMAC0_01_TX 65
-#define MSGRNG_STNID_XMAC0_02_TX 66
-#define MSGRNG_STNID_XMAC0_03_TX 67
-#define MSGRNG_STNID_XMAC0_04_TX 68
-#define MSGRNG_STNID_XMAC0_05_TX 69
-#define MSGRNG_STNID_XMAC0_06_TX 70
-#define MSGRNG_STNID_XMAC0_07_TX 71
-#define MSGRNG_STNID_XMAC0_08_TX 72
-#define MSGRNG_STNID_XMAC0_09_TX 73
-#define MSGRNG_STNID_XMAC0_10_TX 74
-#define MSGRNG_STNID_XMAC0_11_TX 75
-#define MSGRNG_STNID_XMAC0_12_TX 76
-#define MSGRNG_STNID_XMAC0_13_TX 77
-#define MSGRNG_STNID_XMAC0_14_TX 78
-#define MSGRNG_STNID_XMAC0_15_TX 79
+#define	MSGRNG_STNID_CPU0	0x00
+#define	MSGRNG_STNID_CPU1	0x08
+#define	MSGRNG_STNID_CPU2	0x10
+#define	MSGRNG_STNID_CPU3	0x18
+#define	MSGRNG_STNID_CPU4	0x20
+#define	MSGRNG_STNID_CPU5	0x28
+#define	MSGRNG_STNID_CPU6	0x30
+#define	MSGRNG_STNID_CPU7	0x38
+#define	MSGRNG_STNID_XGS0_TX	64
+#define	MSGRNG_STNID_XMAC0_00_TX	64
+#define	MSGRNG_STNID_XMAC0_01_TX	65
+#define	MSGRNG_STNID_XMAC0_02_TX	66
+#define	MSGRNG_STNID_XMAC0_03_TX	67
+#define	MSGRNG_STNID_XMAC0_04_TX	68
+#define	MSGRNG_STNID_XMAC0_05_TX	69
+#define	MSGRNG_STNID_XMAC0_06_TX	70
+#define	MSGRNG_STNID_XMAC0_07_TX	71
+#define	MSGRNG_STNID_XMAC0_08_TX	72
+#define	MSGRNG_STNID_XMAC0_09_TX	73
+#define	MSGRNG_STNID_XMAC0_10_TX	74
+#define	MSGRNG_STNID_XMAC0_11_TX	75
+#define	MSGRNG_STNID_XMAC0_12_TX	76
+#define	MSGRNG_STNID_XMAC0_13_TX	77
+#define	MSGRNG_STNID_XMAC0_14_TX	78
+#define	MSGRNG_STNID_XMAC0_15_TX	79
 
-#define MSGRNG_STNID_XGS1_TX 80
-#define MSGRNG_STNID_XMAC1_00_TX 80
-#define MSGRNG_STNID_XMAC1_01_TX 81
-#define MSGRNG_STNID_XMAC1_02_TX 82
-#define MSGRNG_STNID_XMAC1_03_TX 83
-#define MSGRNG_STNID_XMAC1_04_TX 84
-#define MSGRNG_STNID_XMAC1_05_TX 85
-#define MSGRNG_STNID_XMAC1_06_TX 86
-#define MSGRNG_STNID_XMAC1_07_TX 87
-#define MSGRNG_STNID_XMAC1_08_TX 88
-#define MSGRNG_STNID_XMAC1_09_TX 89
-#define MSGRNG_STNID_XMAC1_10_TX 90
-#define MSGRNG_STNID_XMAC1_11_TX 91
-#define MSGRNG_STNID_XMAC1_12_TX 92
-#define MSGRNG_STNID_XMAC1_13_TX 93
-#define MSGRNG_STNID_XMAC1_14_TX 94
-#define MSGRNG_STNID_XMAC1_15_TX 95
+#define	MSGRNG_STNID_XGS1_TX		80
+#define	MSGRNG_STNID_XMAC1_00_TX	80
+#define	MSGRNG_STNID_XMAC1_01_TX	81
+#define	MSGRNG_STNID_XMAC1_02_TX	82
+#define	MSGRNG_STNID_XMAC1_03_TX	83
+#define	MSGRNG_STNID_XMAC1_04_TX	84
+#define	MSGRNG_STNID_XMAC1_05_TX	85
+#define	MSGRNG_STNID_XMAC1_06_TX	86
+#define	MSGRNG_STNID_XMAC1_07_TX	87
+#define	MSGRNG_STNID_XMAC1_08_TX	88
+#define	MSGRNG_STNID_XMAC1_09_TX	89
+#define	MSGRNG_STNID_XMAC1_10_TX	90
+#define	MSGRNG_STNID_XMAC1_11_TX	91
+#define	MSGRNG_STNID_XMAC1_12_TX	92
+#define	MSGRNG_STNID_XMAC1_13_TX	93
+#define	MSGRNG_STNID_XMAC1_14_TX	94
+#define	MSGRNG_STNID_XMAC1_15_TX	95
 
-#define MSGRNG_STNID_GMAC 96
-#define MSGRNG_STNID_GMACJFR_0  96
-#define MSGRNG_STNID_GMACRFR_0  97
-#define MSGRNG_STNID_GMACTX0    98
-#define MSGRNG_STNID_GMACTX1    99
-#define MSGRNG_STNID_GMACTX2    100
-#define MSGRNG_STNID_GMACTX3    101
-#define MSGRNG_STNID_GMACJFR_1  102
-#define MSGRNG_STNID_GMACRFR_1  103
+#define	MSGRNG_STNID_GMAC		96
+#define	MSGRNG_STNID_GMACJFR_0		96
+#define	MSGRNG_STNID_GMACRFR_0		97
+#define	MSGRNG_STNID_GMACTX0		98
+#define	MSGRNG_STNID_GMACTX1		99
+#define	MSGRNG_STNID_GMACTX2		100
+#define	MSGRNG_STNID_GMACTX3		101
+#define	MSGRNG_STNID_GMACJFR_1		102
+#define	MSGRNG_STNID_GMACRFR_1		103
 
-#define MSGRNG_STNID_DMA      104
-#define MSGRNG_STNID_DMA_0    104
-#define MSGRNG_STNID_DMA_1    105
-#define MSGRNG_STNID_DMA_2    106
-#define MSGRNG_STNID_DMA_3    107
+#define	MSGRNG_STNID_DMA		104
+#define	MSGRNG_STNID_DMA_0		104
+#define	MSGRNG_STNID_DMA_1		105
+#define	MSGRNG_STNID_DMA_2		106
+#define	MSGRNG_STNID_DMA_3		107
 
-#define MSGRNG_STNID_XGS0FR 112
-#define MSGRNG_STNID_XMAC0JFR 112
-#define MSGRNG_STNID_XMAC0RFR 113
+#define	MSGRNG_STNID_XGS0FR		112
+#define	MSGRNG_STNID_XMAC0JFR		112
+#define	MSGRNG_STNID_XMAC0RFR		113
 
-#define MSGRNG_STNID_XGS1FR 114
-#define MSGRNG_STNID_XMAC1JFR 114
-#define MSGRNG_STNID_XMAC1RFR 115
-#define MSGRNG_STNID_SEC 120
-#define MSGRNG_STNID_SEC0 120
-#define MSGRNG_STNID_SEC1 121
-#define MSGRNG_STNID_SEC2 122
-#define MSGRNG_STNID_SEC3 123
-#define MSGRNG_STNID_PK0  124
-#define MSGRNG_STNID_SEC_RSA 124
-#define MSGRNG_STNID_SEC_RSVD0 125
-#define MSGRNG_STNID_SEC_RSVD1 126
-#define MSGRNG_STNID_SEC_RSVD2 127
+#define	MSGRNG_STNID_XGS1FR		114
+#define	MSGRNG_STNID_XMAC1JFR		114
+#define	MSGRNG_STNID_XMAC1RFR		115
+#define	MSGRNG_STNID_SEC		120
+#define	MSGRNG_STNID_SEC0		120
+#define	MSGRNG_STNID_SEC1		121
+#define	MSGRNG_STNID_SEC2		122
+#define	MSGRNG_STNID_SEC3		123
+#define	MSGRNG_STNID_PK0		124
+#define	MSGRNG_STNID_SEC_RSA		124
+#define	MSGRNG_STNID_SEC_RSVD0		125
+#define	MSGRNG_STNID_SEC_RSVD1		126
+#define	MSGRNG_STNID_SEC_RSVD2		127
 
-#define MSGRNG_STNID_GMAC1      80
-#define MSGRNG_STNID_GMAC1_FR_0   81
-#define MSGRNG_STNID_GMAC1_TX0  82
-#define MSGRNG_STNID_GMAC1_TX1  83
-#define MSGRNG_STNID_GMAC1_TX2  84
-#define MSGRNG_STNID_GMAC1_TX3  85
-#define MSGRNG_STNID_GMAC1_FR_1   87
-#define MSGRNG_STNID_GMAC0      96
-#define MSGRNG_STNID_GMAC0_FR_0   97
-#define MSGRNG_STNID_GMAC0_TX0  98
-#define MSGRNG_STNID_GMAC0_TX1  99
-#define MSGRNG_STNID_GMAC0_TX2  100
-#define MSGRNG_STNID_GMAC0_TX3  101
-#define MSGRNG_STNID_GMAC0_FR_1   103
-#define MSGRNG_STNID_CMP_0      108
-#define MSGRNG_STNID_CMP_1      109
-#define MSGRNG_STNID_CMP_2      110
-#define MSGRNG_STNID_CMP_3      111
-#define MSGRNG_STNID_PCIE_0     116
-#define MSGRNG_STNID_PCIE_1     117
-#define MSGRNG_STNID_PCIE_2     118
-#define MSGRNG_STNID_PCIE_3     119
-#define MSGRNG_STNID_XLS_PK0    121
+#define	MSGRNG_STNID_GMAC1		80
+#define	MSGRNG_STNID_GMAC1_FR_0		81
+#define	MSGRNG_STNID_GMAC1_TX0		82
+#define	MSGRNG_STNID_GMAC1_TX1		83
+#define	MSGRNG_STNID_GMAC1_TX2		84
+#define	MSGRNG_STNID_GMAC1_TX3		85
+#define	MSGRNG_STNID_GMAC1_FR_1		87
+#define	MSGRNG_STNID_GMAC0		96
+#define	MSGRNG_STNID_GMAC0_FR_0		97
+#define	MSGRNG_STNID_GMAC0_TX0		98
+#define	MSGRNG_STNID_GMAC0_TX1		99
+#define	MSGRNG_STNID_GMAC0_TX2		100
+#define	MSGRNG_STNID_GMAC0_TX3		101
+#define	MSGRNG_STNID_GMAC0_FR_1		103
+#define	MSGRNG_STNID_CMP_0		108
+#define	MSGRNG_STNID_CMP_1		109
+#define	MSGRNG_STNID_CMP_2		110
+#define	MSGRNG_STNID_CMP_3		111
+#define	MSGRNG_STNID_PCIE_0		116
+#define	MSGRNG_STNID_PCIE_1		117
+#define	MSGRNG_STNID_PCIE_2		118
+#define	MSGRNG_STNID_PCIE_3		119
+#define	MSGRNG_STNID_XLS_PK0		121
 
-#define MSGRNG_CODE_MAC 0
-#define MSGRNG_CODE_XGMAC 2
-#define MSGRNG_CODE_SEC 0
-#define MSGRNG_CODE_BOOT_WAKEUP 200
-#define MSGRNG_CODE_SPI4 3
-#define msgrng_read_status() read_c2_register32(MSGRNG_MSG_STATUS_REG, 0)
+#define	MSGRNG_CODE_MAC		0
+#define	MSGRNG_CODE_XGMAC	2
+#define	MSGRNG_CODE_SEC		0
+#define	MSGRNG_CODE_BOOT_WAKEUP	200
+#define	MSGRNG_CODE_SPI4	3
+#define	msgrng_read_status()	read_c2_register32(MSGRNG_MSG_STATUS_REG, 0)
 
-#define msgrng_read_config() read_c2_register32(MSGRNG_MSG_CONFIG_REG, 0)
-#define msgrng_write_config(value) write_c2_register32(MSGRNG_MSG_CONFIG_REG, 0, value)
+#define	msgrng_read_config()	read_c2_register32(MSGRNG_MSG_CONFIG_REG, 0)
+#define	msgrng_write_config(v)	write_c2_register32(MSGRNG_MSG_CONFIG_REG, 0, v)
 
-#define msgrng_read_bucksize(bucket) read_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, bucket)
-#define msgrng_write_bucksize(bucket, value) write_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, bucket, value)
+#define	msgrng_read_bucksize(b)	read_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, b)
+#define	msgrng_write_bucksize(b, v)	write_c2_register32(MSGRNG_MSG_BUCKSIZE_REG, b, v)
 
-#define msgrng_read_cc(reg, pri) read_c2_register32(reg, pri)
-#define msgrng_write_cc(reg, value, pri) write_c2_register32(reg, pri, value)
+#define	msgrng_read_cc(r, s)	read_c2_register32(r, s)
+#define	msgrng_write_cc(r, v, s)	write_c2_register32(r, s, v)
 
-#define msgrng_load_rx_msg0() read_c2_register64(MSGRNG_RX_BUF_REG, 0)
-#define msgrng_load_rx_msg1() read_c2_register64(MSGRNG_RX_BUF_REG, 1)
-#define msgrng_load_rx_msg2() read_c2_register64(MSGRNG_RX_BUF_REG, 2)
-#define msgrng_load_rx_msg3() read_c2_register64(MSGRNG_RX_BUF_REG, 3)
+#define	msgrng_load_rx_msg0()	read_c2_register64(MSGRNG_RX_BUF_REG, 0)
+#define	msgrng_load_rx_msg1()	read_c2_register64(MSGRNG_RX_BUF_REG, 1)
+#define	msgrng_load_rx_msg2()	read_c2_register64(MSGRNG_RX_BUF_REG, 2)
+#define	msgrng_load_rx_msg3()	read_c2_register64(MSGRNG_RX_BUF_REG, 3)
 
-#define msgrng_load_tx_msg0(value) write_c2_register64(MSGRNG_TX_BUF_REG, 0, value)
-#define msgrng_load_tx_msg1(value) write_c2_register64(MSGRNG_TX_BUF_REG, 1, value)
-#define msgrng_load_tx_msg2(value) write_c2_register64(MSGRNG_TX_BUF_REG, 2, value)
-#define msgrng_load_tx_msg3(value) write_c2_register64(MSGRNG_TX_BUF_REG, 3, value)
+#define	msgrng_load_tx_msg0(v)	write_c2_register64(MSGRNG_TX_BUF_REG, 0, v)
+#define	msgrng_load_tx_msg1(v)	write_c2_register64(MSGRNG_TX_BUF_REG, 1, v)
+#define	msgrng_load_tx_msg2(v)	write_c2_register64(MSGRNG_TX_BUF_REG, 2, v)
+#define	msgrng_load_tx_msg3(v)	write_c2_register64(MSGRNG_TX_BUF_REG, 3, v)
 
-static inline void 
+static __inline void 
 msgrng_send(unsigned int stid)
 {
 	__asm__ volatile (
-	             ".set push\n"
-	             ".set noreorder\n"
-	             "sync\n"
-	    //       "msgsnd %0\n"
-	             "move  $8, %0\n"
-	             "c2    0x80001\n"
-	             ".set pop\n"
-	    ::       "r" (stid):"$8"
+	    ".set	push\n"
+	    ".set	noreorder\n"
+	    "move	$8, %0\n"
+	    "c2		0x80001\n"	/* msgsnd $8 */
+	    ".set	pop\n"
+	    :: "r" (stid): "$8"
 	);
 }
 
-static inline void 
+static __inline void 
 msgrng_receive(unsigned int pri)
 {
 	__asm__ volatile (
-	             ".set push\n"
-	             ".set noreorder\n"
-	    //       "msgld %0\n"
-	             "move $8, %0\n"
-	             "c2   0x80002\n"
-	             ".set pop\n"
-	    ::       "r" (pri):"$8"
+	    ".set	push\n"
+	    ".set	noreorder\n"
+	    "move	$8, %0\n"
+	    "c2		0x80002\n"    /* msgld $8 */
+	    ".set	pop\n"
+	    :: "r" (pri): "$8"
 	);
 }
-static inline void 
+
+static __inline void 
 msgrng_wait(unsigned int mask)
 {
 	__asm__ volatile (
-	             ".set push\n"
-	             ".set noreorder\n"
-	    //       "msgwait %0\n"
-	             "move $8, %0\n"
-	             "c2   0x80003\n"
-	             ".set pop\n"
-	    ::       "r" (mask):"$8"
+	    ".set	push\n"
+	    ".set	noreorder\n"
+	    "move	$8, %0\n"
+	    "c2		0x80003\n"    /* msgwait $8 */
+	    ".set	pop\n"
+	    :: "r" (mask): "$8"
 	);
 }
 
@@ -251,111 +248,77 @@ msgrng_restore(uint32_t sr)
 }
 
 struct msgrng_msg {
-	__uint64_t msg0;
-	__uint64_t msg1;
-	__uint64_t msg2;
-	__uint64_t msg3;
+	uint64_t msg0;
+	uint64_t msg1;
+	uint64_t msg2;
+	uint64_t msg3;
 };
 
-static inline void 
-message_send_block_fast(int size, unsigned int code, unsigned int stid,
-    unsigned long long msg0, unsigned long long msg1,
-    unsigned long long msg2, unsigned long long msg3)
-{
-	__asm__ __volatile__(".set push\n"
-	            ".set noreorder\n"
-	            ".set mips64\n"
-	            "dmtc2 %1, $0, 0\n"
-	            "dmtc2 %2, $0, 1\n"
-	            "dmtc2 %3, $0, 2\n"
-	            "dmtc2 %4, $0, 3\n"
-	            "move $8, %0\n"
-	            "1: c2 0x80001\n"
-	            "mfc2 $8, $2\n"
-	            "andi $8, $8, 0x6\n"
-	            "bnez $8, 1b\n"
-	            "move $8, %0\n"
-	            ".set pop\n"
-	    :
-	    :       "r"(((size - 1) << 16) | (code << 8) | stid), "r"(msg0), "r"(msg1), "r"(msg2), "r"(msg3)
-	    :       "$8"
-	);
-}
-
-#define message_receive_fast(bucket, size, code, stid, msg0, msg1, msg2, msg3)      \
-        ( { unsigned int _status=0, _tmp=0;                     \
-           msgrng_receive(bucket);                              \
-           while ( (_status=msgrng_read_status()) & 0x08) ;     \
-           _tmp = _status & 0x30;                               \
-           if (__builtin_expect((!_tmp), 1)) {                  \
-                 (size)=((_status & 0xc0)>>6)+1;                \
-                 (code)=(_status & 0xff00)>>8;                  \
-                 (stid)=(_status & 0x7f0000)>>16;               \
-                 (msg0)=msgrng_load_rx_msg0();                  \
-                 (msg1)=msgrng_load_rx_msg1();                  \
-                 (msg2)=msgrng_load_rx_msg2();                  \
-                 (msg3)=msgrng_load_rx_msg3();                  \
-                 _tmp=0;                                        \
-                }                                               \
-           _tmp;                                                \
-        } )
-
-static __inline int 
+static __inline int
 message_send(unsigned int size, unsigned int code,
     unsigned int stid, struct msgrng_msg *msg)
 {
 	unsigned int dest = 0;
 	unsigned long long status = 0;
-#ifdef INVARIANTS
 	int i = 0;
-#endif
 
+	/* 
+	 * Make sure that all the writes pending at the cpu are flushed.
+	 * Any writes pending on CPU will not be see by devices. L1/L2
+	 * caches are coherent with IO, so no cache flush needed.
+	 */ 
+	__asm __volatile ("sync");
+
+	/* Load TX message buffers */
 	msgrng_load_tx_msg0(msg->msg0);
 	msgrng_load_tx_msg1(msg->msg1);
 	msgrng_load_tx_msg2(msg->msg2);
 	msgrng_load_tx_msg3(msg->msg3);
-
-	dest = ((size - 1) << 16) | (code << 8) | (stid);
-	msgrng_send(dest);
-
-	/* Wait for the thread pending to clear */
-	do {
-		status = msgrng_read_status();
-		KASSERT(i++ < 10000, ("Too many fails\n"));
-	} while ((status & 0x2) != 0);
-
-	/* If there is a credit failure, return error */
-	return status & 0x06;
-}
-
-static __inline int 
-message_send_retry(unsigned int size, unsigned int code,
-    unsigned int stid, struct msgrng_msg *msg)
-{
-	int i, ret;
+	dest = ((size - 1) << 16) | (code << 8) | stid;
 
 	/*
-	 * we are in with interrupt disabled, retrying too many 
-	 * times is not good
+	 * Retry a few times on credit fail, this should be a 
+	 * transient condition, unless there is a configuration
+	 * failure, or the receiver is stuck.
 	 */
-	for (i = 0; i < 16; i++) {
-		ret = message_send(size, code, stid, msg);
-		if (ret == 0)
+	for (i = 0; i < 8; i++) {
+		msgrng_send(dest);
+		status = msgrng_read_status();
+		KASSERT((status & 0x2) == 0, ("Send pending fail!"));
+		if ((status & 0x4) == 0)
 			return (0);
 	}
 
-	return (1);
+	/* If there is a credit failure, return error */
+	return (status & 0x06);
 }
 
-static __inline__ int 
-message_receive(int pri, int *size, int *code, int *src_id,
+static __inline int 
+message_receive(int bucket, int *size, int *code, int *stid,
     struct msgrng_msg *msg)
 {
-	int res;
+	uint32_t status = 0, tmp = 0;
        
-	res = message_receive_fast(pri, *size, *code, *src_id,
-			msg->msg0, msg->msg1, msg->msg2, msg->msg3);
-	return res;
+	msgrng_receive(bucket); 
+
+	/* wait for load pending to clear */
+	do {
+           status = msgrng_read_status();
+	} while ((status & 0x08) != 0);
+
+	/* receive error bits */
+	tmp = status & 0x30;
+	if (tmp != 0)
+		return (tmp);
+
+	*size = ((status & 0xc0) >> 6) + 1;
+	*code = (status & 0xff00) >> 8;
+	*stid = (status & 0x7f0000) >> 16;
+	msg->msg0 = msgrng_load_rx_msg0();
+	msg->msg1 = msgrng_load_rx_msg1();
+	msg->msg2 = msgrng_load_rx_msg2();
+	msg->msg3 = msgrng_load_rx_msg3();
+	return (0);
 }
 
 #define MSGRNG_STN_RX_QSIZE 256

From 946e2f3595dcf6edbd73d9039aaad36084e25719 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 13 Sep 2010 13:48:18 +0000
Subject: [PATCH 0703/1624] - Remove gc_argname field. It was introduced for
 gpart(8), but if I   understand everything correctly, we don't really need
 it. - Provide default numeric value as strings. This allows to simplify   a
 lot of code. - Bump version number.

---
 sbin/geom/class/cache/geom_cache.c         |  34 +++----
 sbin/geom/class/concat/geom_concat.c       |  12 +--
 sbin/geom/class/eli/geom_eli.c             |  55 +++++------
 sbin/geom/class/journal/geom_journal.c     |  14 ++-
 sbin/geom/class/label/geom_label.c         |  12 +--
 sbin/geom/class/mirror/geom_mirror.c       |  39 ++++----
 sbin/geom/class/mountver/geom_mountver.c   |   4 +-
 sbin/geom/class/multipath/geom_multipath.c |  12 +--
 sbin/geom/class/nop/geom_nop.c             |  33 +++----
 sbin/geom/class/part/geom_part.c           | 109 +++++++++++----------
 sbin/geom/class/raid3/geom_raid3.c         |  22 ++---
 sbin/geom/class/sched/geom_sched.c         |   8 +-
 sbin/geom/class/shsec/geom_shsec.c         |   8 +-
 sbin/geom/class/stripe/geom_stripe.c       |  18 ++--
 sbin/geom/class/virstor/geom_virstor.c     |  69 ++++++-------
 sbin/geom/core/geom.c                      |  51 ++++------
 sbin/geom/core/geom.h                      |   5 +-
 sys/geom/part/g_part.c                     |  12 +--
 18 files changed, 244 insertions(+), 273 deletions(-)

diff --git a/sbin/geom/class/cache/geom_cache.c b/sbin/geom/class/cache/geom_cache.c
index 636c54119ce..4b18e67dd0b 100644
--- a/sbin/geom/class/cache/geom_cache.c
+++ b/sbin/geom/class/cache/geom_cache.c
@@ -42,10 +42,8 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_CACHE_VERSION;
 
-static intmax_t blocksize_label = 65536;
-static intmax_t size_label = 100;
-static intmax_t blocksize_configure = 0;
-static intmax_t size_configure = 0;
+#define	GCACHE_BLOCKSIZE	"65536"
+#define	GCACHE_SIZE		"100"
 
 static void cache_main(struct gctl_req *req, unsigned flags);
 static void cache_clear(struct gctl_req *req);
@@ -53,44 +51,44 @@ static void cache_dump(struct gctl_req *req);
 static void cache_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "clear", G_FLAG_VERBOSE, cache_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, cache_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	{ "configure", G_FLAG_VERBOSE, NULL,
 	    {
-		{ 'b', "blocksize", &blocksize_configure, G_TYPE_NUMBER },
-		{ 's', "size", &size_configure, G_TYPE_NUMBER },
+		{ 'b', "blocksize", "0", G_TYPE_NUMBER },
+		{ 's', "size", "0", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] [-b blocksize] [-s size] name"
+	    "[-v] [-b blocksize] [-s size] name"
 	},
 	{ "create", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
 	    {
-		{ 'b', "blocksize", &blocksize_label, G_TYPE_NUMBER },
-		{ 's', "size", &size_label, G_TYPE_NUMBER },
+		{ 'b', "blocksize", GCACHE_BLOCKSIZE, G_TYPE_NUMBER },
+		{ 's', "size", GCACHE_SIZE, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] [-b blocksize] [-s size] name prov"
+	    "[-v] [-b blocksize] [-s size] name prov"
 	},
 	{ "destroy", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
-	{ "dump", 0, cache_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, cache_main, G_NULL_OPTS,
 	    "prov ..."
 	},
 	{ "label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, cache_main,
 	    {
-		{ 'b', "blocksize", &blocksize_label, G_TYPE_NUMBER },
-		{ 's', "size", &size_label, G_TYPE_NUMBER },
+		{ 'b', "blocksize", GCACHE_BLOCKSIZE, G_TYPE_NUMBER },
+		{ 's', "size", GCACHE_SIZE, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] [-b blocksize] [-s size] name prov"
+	    "[-v] [-b blocksize] [-s size] name prov"
 	},
-	{ "reset", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "reset", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v] name ..."
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
@@ -98,7 +96,7 @@ struct g_command class_commands[] = {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/concat/geom_concat.c b/sbin/geom/class/concat/geom_concat.c
index e1b7342a037..80fe26bedef 100644
--- a/sbin/geom/class/concat/geom_concat.c
+++ b/sbin/geom/class/concat/geom_concat.c
@@ -51,20 +51,20 @@ static void concat_dump(struct gctl_req *req);
 static void concat_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "clear", G_FLAG_VERBOSE, concat_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, concat_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	{ "create", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL, G_NULL_OPTS,
-	    NULL, "[-v] name prov ..."
+	    "[-v] name prov ..."
 	},
 	{ "destroy", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
-	{ "dump", 0, concat_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, concat_main, G_NULL_OPTS,
 	    "prov ..."
 	},
 	{ "label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, concat_main,
@@ -72,14 +72,14 @@ struct g_command class_commands[] = {
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hv] name prov ..."
+	    "[-hv] name prov ..."
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/eli/geom_eli.c b/sbin/geom/class/eli/geom_eli.c
index d5acc99e4b5..59c6be79b96 100644
--- a/sbin/geom/class/eli/geom_eli.c
+++ b/sbin/geom/class/eli/geom_eli.c
@@ -57,11 +57,6 @@ uint32_t version = G_ELI_VERSION;
 #define	GELI_BACKUP_DIR	"/var/backups/"
 #define	GELI_ENC_ALGO	"aes"
 
-static intmax_t keylen = 0;
-static intmax_t keyno = -1;
-static intmax_t iterations = -1;
-static intmax_t sectorsize = 0;
-
 static void eli_main(struct gctl_req *req, unsigned flags);
 static void eli_init(struct gctl_req *req);
 static void eli_attach(struct gctl_req *req);
@@ -102,14 +97,14 @@ struct g_command class_commands[] = {
 		{ 'b', "boot", NULL, G_TYPE_BOOL },
 		{ 'B', "backupfile", "", G_TYPE_STRING },
 		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
-		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
+		{ 'i', "iterations", "-1", G_TYPE_NUMBER },
 		{ 'K', "newkeyfile", "", G_TYPE_STRING },
-		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
+		{ 'l', "keylen", "0", G_TYPE_NUMBER },
 		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
-		{ 's', "sectorsize", §orsize, G_TYPE_NUMBER },
+		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-bPv] [-a aalgo] [-B backupfile] [-e ealgo] [-i iterations] [-l keylen] [-K newkeyfile] [-s sectorsize] prov"
+	    "[-bPv] [-a aalgo] [-B backupfile] [-e ealgo] [-i iterations] [-l keylen] [-K newkeyfile] [-s sectorsize] prov"
 	},
 	{ "label", G_FLAG_VERBOSE, eli_main,
 	    {
@@ -117,14 +112,14 @@ struct g_command class_commands[] = {
 		{ 'b', "boot", NULL, G_TYPE_BOOL },
 		{ 'B', "backupfile", "", G_TYPE_STRING },
 		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
-		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
+		{ 'i', "iterations", "-1", G_TYPE_NUMBER },
 		{ 'K', "newkeyfile", "", G_TYPE_STRING },
-		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
+		{ 'l', "keylen", "0", G_TYPE_NUMBER },
 		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
-		{ 's', "sectorsize", §orsize, G_TYPE_NUMBER },
+		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "- an alias for 'init'"
+	    "- an alias for 'init'"
 	},
 	{ "attach", G_FLAG_VERBOSE | G_FLAG_LOADKLD, eli_main,
 	    {
@@ -134,7 +129,7 @@ struct g_command class_commands[] = {
 		{ 'r', "readonly", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-dprv] [-k keyfile] prov"
+	    "[-dprv] [-k keyfile] prov"
 	},
 	{ "detach", 0, NULL,
 	    {
@@ -142,7 +137,7 @@ struct g_command class_commands[] = {
 		{ 'l', "last", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fl] prov ..."
+	    "[-fl] prov ..."
 	},
 	{ "stop", 0, NULL,
 	    {
@@ -150,18 +145,18 @@ struct g_command class_commands[] = {
 		{ 'l', "last", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "- an alias for 'detach'"
+	    "- an alias for 'detach'"
 	},
 	{ "onetime", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
 	    {
 		{ 'a', "aalgo", "", G_TYPE_STRING },
 		{ 'd', "detach", NULL, G_TYPE_BOOL },
 		{ 'e', "ealgo", GELI_ENC_ALGO, G_TYPE_STRING },
-		{ 'l', "keylen", &keylen, G_TYPE_NUMBER },
-		{ 's', "sectorsize", §orsize, G_TYPE_NUMBER },
+		{ 'l', "keylen", "0", G_TYPE_NUMBER },
+		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-d] [-a aalgo] [-e ealgo] [-l keylen] [-s sectorsize] prov"
+	    "[-d] [-a aalgo] [-e ealgo] [-l keylen] [-s sectorsize] prov"
 	},
 	{ "configure", G_FLAG_VERBOSE, eli_main,
 	    {
@@ -169,46 +164,46 @@ struct g_command class_commands[] = {
 		{ 'B', "noboot", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-bB] prov ..."
+	    "[-bB] prov ..."
 	},
 	{ "setkey", G_FLAG_VERBOSE, eli_main,
 	    {
-		{ 'i', "iterations", &iterations, G_TYPE_NUMBER },
+		{ 'i', "iterations", "-1", G_TYPE_NUMBER },
 		{ 'k', "keyfile", "", G_TYPE_STRING },
 		{ 'K', "newkeyfile", "", G_TYPE_STRING },
-		{ 'n', "keyno", &keyno, G_TYPE_NUMBER },
+		{ 'n', "keyno", "-1", G_TYPE_NUMBER },
 		{ 'p', "nopassphrase", NULL, G_TYPE_BOOL },
 		{ 'P', "nonewpassphrase", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-pPv] [-n keyno] [-i iterations] [-k keyfile] [-K newkeyfile] prov"
+	    "[-pPv] [-n keyno] [-i iterations] [-k keyfile] [-K newkeyfile] prov"
 	},
 	{ "delkey", G_FLAG_VERBOSE, eli_main,
 	    {
 		{ 'a', "all", NULL, G_TYPE_BOOL },
 		{ 'f', "force", NULL, G_TYPE_BOOL },
-		{ 'n', "keyno", &keyno, G_TYPE_NUMBER },
+		{ 'n', "keyno", "-1", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-afv] [-n keyno] prov"
+	    "[-afv] [-n keyno] prov"
 	},
 	{ "kill", G_FLAG_VERBOSE, eli_main,
 	    {
 		{ 'a', "all", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-av] [prov ...]"
+	    "[-av] [prov ...]"
 	},
-	{ "backup", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS, NULL,
+	{ "backup", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
 	    "[-v] prov file"
 	},
-	{ "restore", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS, NULL,
+	{ "restore", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
 	    "[-v] file prov"
 	},
-	{ "clear", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
-	{ "dump", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS, NULL,
+	{ "dump", G_FLAG_VERBOSE, eli_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	G_CMD_SENTINEL
diff --git a/sbin/geom/class/journal/geom_journal.c b/sbin/geom/class/journal/geom_journal.c
index 37169990ac4..b887fabb290 100644
--- a/sbin/geom/class/journal/geom_journal.c
+++ b/sbin/geom/class/journal/geom_journal.c
@@ -47,18 +47,16 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_JOURNAL_VERSION;
 
-static intmax_t default_jsize = -1;
-
 static void journal_main(struct gctl_req *req, unsigned flags);
 static void journal_clear(struct gctl_req *req);
 static void journal_dump(struct gctl_req *req);
 static void journal_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "clear", G_FLAG_VERBOSE, journal_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, journal_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
-	{ "dump", 0, journal_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, journal_main, G_NULL_OPTS,
 	    "prov ..."
 	},
 	{ "label", G_FLAG_VERBOSE, journal_main,
@@ -66,19 +64,19 @@ struct g_command class_commands[] = {
 		{ 'c', "checksum", NULL, G_TYPE_BOOL },
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
-		{ 's', "jsize", &default_jsize, G_TYPE_NUMBER },
+		{ 's', "jsize", "-1", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-cfhv] [-s jsize] dataprov [jprov]"
+	    "[-cfhv] [-s jsize] dataprov [jprov]"
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
-	{ "sync", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "sync", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v]"
 	},
 	G_CMD_SENTINEL
diff --git a/sbin/geom/class/label/geom_label.c b/sbin/geom/class/label/geom_label.c
index e77fdf054a1..6c880eebed7 100644
--- a/sbin/geom/class/label/geom_label.c
+++ b/sbin/geom/class/label/geom_label.c
@@ -55,31 +55,31 @@ static void label_dump(struct gctl_req *req);
 static void label_label(struct gctl_req *req);
 
 struct g_command PUBSYM(class_commands)[] = {
-	{ "clear", G_FLAG_VERBOSE, label_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, label_main, G_NULL_OPTS,
 	    "[-v] dev ..."
 	},
 	{ "create", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL, G_NULL_OPTS,
-	    NULL, "[-v] name dev"
+	    "[-v] name dev"
 	},
 	{ "destroy", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
-	{ "dump", 0, label_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, label_main, G_NULL_OPTS,
 	    "dev ..."
 	},
 	{ "label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, label_main, G_NULL_OPTS,
-	    NULL, "[-v] name dev"
+	    "[-v] name dev"
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/mirror/geom_mirror.c b/sbin/geom/class/mirror/geom_mirror.c
index de51fb13f0b..2cb52a98982 100644
--- a/sbin/geom/class/mirror/geom_mirror.c
+++ b/sbin/geom/class/mirror/geom_mirror.c
@@ -44,10 +44,9 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_MIRROR_VERSION;
 
-#define	GMIRROR_BALANCE	"load"
-
-static intmax_t label_slice = 4096, configure_slice = -1;
-static intmax_t insert_priority = 0, configure_priority = -1;
+#define	GMIRROR_BALANCE		"load"
+#define	GMIRROR_SLICE		"4096"
+#define	GMIRROR_PRIORITY	"0"
 
 static void mirror_main(struct gctl_req *req, unsigned flags);
 static void mirror_activate(struct gctl_req *req);
@@ -56,10 +55,10 @@ static void mirror_dump(struct gctl_req *req);
 static void mirror_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "activate", G_FLAG_VERBOSE, mirror_main, G_NULL_OPTS, NULL,
+	{ "activate", G_FLAG_VERBOSE, mirror_main, G_NULL_OPTS,
 	    "[-v] name prov ..."
 	},
-	{ "clear", G_FLAG_VERBOSE, mirror_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, mirror_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	{ "configure", G_FLAG_VERBOSE, NULL,
@@ -71,20 +70,20 @@ struct g_command class_commands[] = {
 		{ 'F', "nofailsync", NULL, G_TYPE_BOOL },
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
 		{ 'n', "noautosync", NULL, G_TYPE_BOOL },
-		{ 'p', "priority", &configure_priority, G_TYPE_NUMBER },
-		{ 's', "slice", &configure_slice, G_TYPE_NUMBER },
+		{ 'p', "priority", "-1", G_TYPE_NUMBER },
+		{ 's', "slice", "-1", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-adfFhnv] [-b balance] [-s slice] name\n"
-		  "[-v] -p priority name prov"
+	    "[-adfFhnv] [-b balance] [-s slice] name\n"
+	    "[-v] -p priority name prov"
 	},
-	{ "deactivate", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "deactivate", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v] name prov ..."
 	},
-	{ "dump", 0, mirror_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, mirror_main, G_NULL_OPTS,
 	    "prov ..."
 	},
-	{ "forget", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "forget", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "name ..."
 	},
 	{ "label", G_FLAG_VERBOSE, mirror_main,
@@ -93,24 +92,24 @@ struct g_command class_commands[] = {
 		{ 'F', "nofailsync", NULL, G_TYPE_BOOL },
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
 		{ 'n', "noautosync", NULL, G_TYPE_BOOL },
-		{ 's', "slice", &label_slice, G_TYPE_NUMBER },
+		{ 's', "slice", GMIRROR_SLICE, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-Fhnv] [-b balance] [-s slice] name prov ..."
+	    "[-Fhnv] [-b balance] [-s slice] name prov ..."
 	},
 	{ "insert", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
 		{ 'i', "inactive", NULL, G_TYPE_BOOL },
-		{ 'p', "priority", &insert_priority, G_TYPE_NUMBER },
+		{ 'p', "priority", GMIRROR_PRIORITY, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hiv] [-p priority] name prov ..."
+	    "[-hiv] [-p priority] name prov ..."
 	},
-	{ "rebuild", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "rebuild", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v] name prov ..."
 	},
-	{ "remove", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "remove", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v] name prov ..."
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
@@ -118,7 +117,7 @@ struct g_command class_commands[] = {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/mountver/geom_mountver.c b/sbin/geom/class/mountver/geom_mountver.c
index fa276ca3e88..a1ed95d6c87 100644
--- a/sbin/geom/class/mountver/geom_mountver.c
+++ b/sbin/geom/class/mountver/geom_mountver.c
@@ -43,14 +43,14 @@ struct g_command class_commands[] = {
 	    {
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] dev ..."
+	    "[-v] dev ..."
 	},
 	{ "destroy", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] prov ..."
+	    "[-fv] prov ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/multipath/geom_multipath.c b/sbin/geom/class/multipath/geom_multipath.c
index 2d7236247e9..6364bc3ecdd 100644
--- a/sbin/geom/class/multipath/geom_multipath.c
+++ b/sbin/geom/class/multipath/geom_multipath.c
@@ -53,27 +53,27 @@ static void mp_add(struct gctl_req *);
 struct g_command class_commands[] = {
 	{
 		"label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, mp_main, G_NULL_OPTS,
-		NULL, "[-v] name prov ..."
+		"[-v] name prov ..."
 	},
 	{
 		"add", G_FLAG_VERBOSE | G_FLAG_LOADKLD, mp_main, G_NULL_OPTS,
-		NULL, "[-v] name prov ..."
+		"[-v] name prov ..."
 	},
 	{
 		"destroy", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
-		NULL, "[-v] prov ..."
+		"[-v] prov ..."
 	},
 	{
 		"clear", G_FLAG_VERBOSE, mp_main, G_NULL_OPTS,
-		NULL, "[-v] prov ..."
+		"[-v] prov ..."
 	},
 	{
 		"rotate", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
-		NULL, "[-v] prov ..."
+		"[-v] prov ..."
 	},
 	{
 		"getactive", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
-		NULL, "[-v] prov ..."
+		"[-v] prov ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/nop/geom_nop.c b/sbin/geom/class/nop/geom_nop.c
index 7306add3674..25163ccf0d7 100644
--- a/sbin/geom/class/nop/geom_nop.c
+++ b/sbin/geom/class/nop/geom_nop.c
@@ -38,44 +38,37 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_NOP_VERSION;
 
-static intmax_t error = -1;
-static intmax_t rfailprob = -1;
-static intmax_t wfailprob = -1;
-static intmax_t offset = 0;
-static intmax_t secsize = 0;
-static intmax_t size = 0;
-
 struct g_command class_commands[] = {
 	{ "create", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
 	    {
-		{ 'e', "error", &error, G_TYPE_NUMBER },
-		{ 'o', "offset", &offset, G_TYPE_NUMBER },
-		{ 'r', "rfailprob", &rfailprob, G_TYPE_NUMBER },
-		{ 's', "size", &size, G_TYPE_NUMBER },
-		{ 'S', "secsize", &secsize, G_TYPE_NUMBER },
-		{ 'w', "wfailprob", &wfailprob, G_TYPE_NUMBER },
+		{ 'e', "error", "-1", G_TYPE_NUMBER },
+		{ 'o', "offset", "0", G_TYPE_NUMBER },
+		{ 'r', "rfailprob", "-1", G_TYPE_NUMBER },
+		{ 's', "size", "0", G_TYPE_NUMBER },
+		{ 'S', "secsize", "0", G_TYPE_NUMBER },
+		{ 'w', "wfailprob", "-1", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] [-e error] [-o offset] [-r rfailprob] [-s size] "
+	    "[-v] [-e error] [-o offset] [-r rfailprob] [-s size] "
 	    "[-S secsize] [-w wfailprob] dev ..."
 	},
 	{ "configure", G_FLAG_VERBOSE, NULL,
 	    {
-		{ 'e', "error", &error, G_TYPE_NUMBER },
-		{ 'r', "rfailprob", &rfailprob, G_TYPE_NUMBER },
-		{ 'w', "wfailprob", &wfailprob, G_TYPE_NUMBER },
+		{ 'e', "error", "-1", G_TYPE_NUMBER },
+		{ 'r', "rfailprob", "-1", G_TYPE_NUMBER },
+		{ 'w', "wfailprob", "-1", G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] [-e error] [-r rfailprob] [-w wfailprob] prov ..."
+	    "[-v] [-e error] [-r rfailprob] [-w wfailprob] prov ..."
 	},
 	{ "destroy", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] prov ..."
+	    "[-fv] prov ..."
 	},
-	{ "reset", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "reset", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	G_CMD_SENTINEL
diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index 658fba6ed7f..673d90cd161 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -58,15 +58,15 @@ __FBSDID("$FreeBSD$");
 uint32_t PUBSYM(lib_version) = G_LIB_VERSION;
 uint32_t PUBSYM(version) = 0;
 
-static char autofill[] = "*";
-static char flags[] = "C";
-
 static char sstart[32];
 static char ssize[32];
 
-static const char const bootcode_param[] = "bootcode";
-static const char const index_param[] = "index";
-static const char const partcode_param[] = "partcode";
+#define	GPART_AUTOFILL	"*"
+#define	GPART_FLAGS	"C"
+
+#define	GPART_PARAM_BOOTCODE	"bootcode"
+#define	GPART_PARAM_INDEX	"index"
+#define	GPART_PARAM_PARTCODE	"partcode"
 
 static struct gclass *find_class(struct gmesh *, const char *);
 static struct ggeom * find_geom(struct gclass *, const char *);
@@ -87,76 +87,81 @@ static void gpart_write_partcode_vtoc8(struct ggeom *, int, void *);
 
 struct g_command PUBSYM(class_commands)[] = {
 	{ "add", 0, gpart_issue, {
-		{ 'b', "start", autofill, G_TYPE_STRING },
-		{ 's', "size", autofill, G_TYPE_STRING },
+		{ 'b', "start", GPART_AUTOFILL, G_TYPE_STRING },
+		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
 		{ 't', "type", NULL, G_TYPE_STRING },
-		{ 'i', index_param, "", G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, "", G_TYPE_ASCNUM },
 		{ 'l', "label", "", G_TYPE_STRING },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "[-b start] [-s size] -t type [-i index] [-l label] [-f flags] geom"
 	},
 	{ "bootcode", 0, gpart_bootcode, {
-		{ 'b', bootcode_param, "", G_TYPE_STRING },
-		{ 'p', partcode_param, "", G_TYPE_STRING },
-		{ 'i', index_param, "", G_TYPE_ASCNUM },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'b', GPART_PARAM_BOOTCODE, "", G_TYPE_STRING },
+		{ 'p', GPART_PARAM_PARTCODE, "", G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, "", G_TYPE_ASCNUM },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "bootcode [-b bootcode] [-p partcode] [-i index] [-f flags] geom"
+	},
+	{ "commit", 0, gpart_issue, G_NULL_OPTS,
+	    "geom"
 	},
-	{ "commit", 0, gpart_issue, G_NULL_OPTS, "geom", NULL },
 	{ "create", 0, gpart_issue, {
 		{ 's', "scheme", NULL, G_TYPE_STRING },
 		{ 'n', "entries", "", G_TYPE_ASCNUM },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "provider", NULL
+	    "-s scheme [-n entries] [-f flags] provider"
 	},
 	{ "delete", 0, gpart_issue, {
-		{ 'i', index_param, NULL, G_TYPE_ASCNUM },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "-i index [-f flags] geom"
 	},
 	{ "destroy", 0, gpart_issue, {
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL },
+	    "[-f flags] geom"
+	},
 	{ "modify", 0, gpart_issue, {
-		{ 'i', index_param, NULL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
 		{ 'l', "label", "", G_TYPE_STRING },
 		{ 't', "type", "", G_TYPE_STRING },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "-i index [-l label] [-t type] [-f flags] geom"
 	},
 	{ "set", 0, gpart_issue, {
 		{ 'a', "attrib", NULL, G_TYPE_STRING },
-		{ 'i', index_param, NULL, G_TYPE_ASCNUM },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "-a attrib -i index [-f flags] geom"
 	},
 	{ "show", 0, gpart_show, {
 		{ 'l', "show_label", NULL, G_TYPE_BOOL },
 		{ 'r', "show_rawtype", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL },
-	  NULL, "[-lr] [geom ...]"
+	    "[-lr] [geom ...]"
+	},
+	{ "undo", 0, gpart_issue, G_NULL_OPTS,
+	    "geom"
 	},
-	{ "undo", 0, gpart_issue, G_NULL_OPTS, "geom", NULL },
 	{ "unset", 0, gpart_issue, {
 		{ 'a', "attrib", NULL, G_TYPE_STRING },
-		{ 'i', index_param, NULL, G_TYPE_ASCNUM },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "-a attrib -i index [-f flags] geom"
 	},
 	{ "resize", 0, gpart_issue, {
-		{ 's', "size", autofill, G_TYPE_STRING },
-		{ 'i', index_param, NULL, G_TYPE_ASCNUM },
-		{ 'f', "flags", flags, G_TYPE_STRING },
+		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
-	  "geom", NULL
+	    "[-s size] -i index [-f flags] geom"
 	},
 	G_CMD_SENTINEL
 };
@@ -281,7 +286,7 @@ gpart_autofill_resize(struct gctl_req *req)
 	char *val;
 	int error, idx;
 
-	s = gctl_get_ascii(req, index_param);
+	s = gctl_get_ascii(req, GPART_PARAM_INDEX);
 	idx = strtol(s, &val, 10);
 	if (idx < 1 || *s == '\0' || *val != '\0')
 		errx(EXIT_FAILURE, "invalid partition index");
@@ -773,11 +778,11 @@ gpart_bootcode(struct gctl_req *req, unsigned int fl)
 	size_t bootsize, partsize;
 	int error, idx, vtoc8;
 
-	if (gctl_has_param(req, bootcode_param)) {
-		s = gctl_get_ascii(req, bootcode_param);
+	if (gctl_has_param(req, GPART_PARAM_BOOTCODE)) {
+		s = gctl_get_ascii(req, GPART_PARAM_BOOTCODE);
 		bootsize = 800 * 1024;		/* Arbitrary limit. */
 		bootcode = gpart_bootfile_read(s, &bootsize);
-		error = gctl_change_param(req, bootcode_param, bootsize,
+		error = gctl_change_param(req, GPART_PARAM_BOOTCODE, bootsize,
 		    bootcode);
 		if (error)
 			errc(EXIT_FAILURE, error, "internal error");
@@ -797,7 +802,7 @@ gpart_bootcode(struct gctl_req *req, unsigned int fl)
 		geom_deletetree(&mesh);
 		errx(EXIT_FAILURE, "Class %s not found.", s);
 	}
-	s = gctl_get_ascii(req, "geom");
+	s = gctl_get_ascii(req, "arg0");
 	if (s == NULL)
 		abort();
 	gp = find_geom(classp, s);
@@ -808,11 +813,11 @@ gpart_bootcode(struct gctl_req *req, unsigned int fl)
 	if (strcmp(s, "VTOC8") == 0)
 		vtoc8 = 1;
 
-	if (gctl_has_param(req, partcode_param)) {
-		s = gctl_get_ascii(req, partcode_param);
+	if (gctl_has_param(req, GPART_PARAM_PARTCODE)) {
+		s = gctl_get_ascii(req, GPART_PARAM_PARTCODE);
 		partsize = vtoc8 != 0 ? VTOC_BOOTSIZE : bootsize * 1024;
 		partcode = gpart_bootfile_read(s, &partsize);
-		error = gctl_delete_param(req, partcode_param);
+		error = gctl_delete_param(req, GPART_PARAM_PARTCODE);
 		if (error)
 			errc(EXIT_FAILURE, error, "internal error");
 	} else {
@@ -820,14 +825,14 @@ gpart_bootcode(struct gctl_req *req, unsigned int fl)
 		partsize = 0;
 	}
 
-	if (gctl_has_param(req, index_param)) {
+	if (gctl_has_param(req, GPART_PARAM_INDEX)) {
 		if (partcode == NULL)
 			errx(EXIT_FAILURE, "-i is only valid with -p");
-		s = gctl_get_ascii(req, index_param);
+		s = gctl_get_ascii(req, GPART_PARAM_INDEX);
 		idx = strtol(s, &sp, 10);
 		if (idx < 1 || *s == '\0' || *sp != '\0')
 			errx(EXIT_FAILURE, "invalid partition index");
-		error = gctl_delete_param(req, index_param);
+		error = gctl_delete_param(req, GPART_PARAM_INDEX);
 		if (error)
 			errc(EXIT_FAILURE, error, "internal error");
 	} else
@@ -858,6 +863,10 @@ gpart_issue(struct gctl_req *req, unsigned int fl __unused)
 	const char *errstr;
 	int error, status;
 
+	if (gctl_get_int(req, "nargs") != 1)
+		errx(EXIT_FAILURE, "Invalid number of arguments.");
+	(void)gctl_delete_param(req, "nargs");
+
 	/* autofill parameters (if applicable). */
 	error = gpart_autofill(req);
 	if (error) {
diff --git a/sbin/geom/class/raid3/geom_raid3.c b/sbin/geom/class/raid3/geom_raid3.c
index 89ce1689ba8..220fb09237e 100644
--- a/sbin/geom/class/raid3/geom_raid3.c
+++ b/sbin/geom/class/raid3/geom_raid3.c
@@ -45,15 +45,13 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_RAID3_VERSION;
 
-static intmax_t default_blocksize = 0;
-
 static void raid3_main(struct gctl_req *req, unsigned f);
 static void raid3_clear(struct gctl_req *req);
 static void raid3_dump(struct gctl_req *req);
 static void raid3_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "clear", G_FLAG_VERBOSE, raid3_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, raid3_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	{ "configure", G_FLAG_VERBOSE, NULL,
@@ -70,9 +68,9 @@ struct g_command class_commands[] = {
 		{ 'W', "noverify", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-adfFhnrRvwW] name"
+	    "[-adfFhnrRvwW] name"
 	},
-	{ "dump", 0, raid3_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, raid3_main, G_NULL_OPTS,
 	    "prov ..."
 	},
 	{ "insert", G_FLAG_VERBOSE, NULL,
@@ -81,7 +79,7 @@ struct g_command class_commands[] = {
 		{ 'n', "number", NULL, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hv] <-n number> name prov"
+	    "[-hv] <-n number> name prov"
 	},
 	{ "label", G_FLAG_VERBOSE, raid3_main,
 	    {
@@ -89,13 +87,13 @@ struct g_command class_commands[] = {
 		{ 'F', "nofailsync", NULL, G_TYPE_BOOL },
 		{ 'n', "noautosync", NULL, G_TYPE_BOOL },
 		{ 'r', "round_robin", NULL, G_TYPE_BOOL },
-		{ 's', "blocksize", &default_blocksize, G_TYPE_NUMBER },
+		{ 's', "sectorsize", "0", G_TYPE_NUMBER },
 		{ 'w', "verify", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hFnrvw] [-s blocksize] name prov prov prov ..."
+	    "[-hFnrvw] [-s blocksize] name prov prov prov ..."
 	},
-	{ "rebuild", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
+	{ "rebuild", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
 	    "[-v] name prov"
 	},
 	{ "remove", G_FLAG_VERBOSE, NULL,
@@ -103,14 +101,14 @@ struct g_command class_commands[] = {
 		{ 'n', "number", NULL, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-v] <-n number> name"
+	    "[-v] <-n number> name"
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
@@ -193,7 +191,7 @@ raid3_label(struct gctl_req *req)
 	 * sectorsizes of every disk and find the smallest mediasize.
 	 */
 	mediasize = 0;
-	sectorsize = gctl_get_intmax(req, "blocksize");
+	sectorsize = gctl_get_intmax(req, "sectorsize");
 	for (i = 1; i < nargs; i++) {
 		str = gctl_get_ascii(req, "arg%d", i);
 		msize = g_get_mediasize(str);
diff --git a/sbin/geom/class/sched/geom_sched.c b/sbin/geom/class/sched/geom_sched.c
index eba8e49e78e..727913c9762 100644
--- a/sbin/geom/class/sched/geom_sched.c
+++ b/sbin/geom/class/sched/geom_sched.c
@@ -60,11 +60,13 @@ uint32_t version = G_SCHED_VERSION;
  * Adapt to differences in geom library.
  * in V1 struct g_command misses gc_argname, eld, and G_BOOL is undefined
  */
-#if G_LIB_VERSION == 1
-#define G_ARGNAME
+#if G_LIB_VERSION <= 1
 #define G_TYPE_BOOL	G_TYPE_NUMBER
-#else
+#endif
+#if G_LIB_VERSION >= 3 && G_LIB_VERSION <= 4
 #define G_ARGNAME	NULL,
+#else
+#define	G_ARGNAME
 #endif
 
 static void
diff --git a/sbin/geom/class/shsec/geom_shsec.c b/sbin/geom/class/shsec/geom_shsec.c
index 8af47ee62d1..75791de6ac0 100644
--- a/sbin/geom/class/shsec/geom_shsec.c
+++ b/sbin/geom/class/shsec/geom_shsec.c
@@ -52,10 +52,10 @@ static void shsec_dump(struct gctl_req *req);
 static void shsec_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "clear", G_FLAG_VERBOSE, shsec_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, shsec_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
-	{ "dump", 0, shsec_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, shsec_main, G_NULL_OPTS,
 	    "prov ..."
 	},
 	{ "label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, shsec_main,
@@ -63,14 +63,14 @@ struct g_command class_commands[] = {
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hv] name prov prov ..."
+	    "[-hv] name prov prov ..."
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/stripe/geom_stripe.c b/sbin/geom/class/stripe/geom_stripe.c
index 16808cc7afd..215dae04543 100644
--- a/sbin/geom/class/stripe/geom_stripe.c
+++ b/sbin/geom/class/stripe/geom_stripe.c
@@ -46,7 +46,7 @@ __FBSDID("$FreeBSD$");
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_STRIPE_VERSION;
 
-static intmax_t default_stripesize = 65536;
+#define	GSTRIPE_STRIPESIZE	"65536"
 
 static void stripe_main(struct gctl_req *req, unsigned flags);
 static void stripe_clear(struct gctl_req *req);
@@ -54,40 +54,40 @@ static void stripe_dump(struct gctl_req *req);
 static void stripe_label(struct gctl_req *req);
 
 struct g_command class_commands[] = {
-	{ "clear", G_FLAG_VERBOSE, stripe_main, G_NULL_OPTS, NULL,
+	{ "clear", G_FLAG_VERBOSE, stripe_main, G_NULL_OPTS,
 	    "[-v] prov ..."
 	},
 	{ "create", G_FLAG_VERBOSE | G_FLAG_LOADKLD, NULL,
 	    {
-		{ 's', "stripesize", &default_stripesize, G_TYPE_NUMBER },
+		{ 's', "stripesize", GSTRIPE_STRIPESIZE, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hv] [-s stripesize] name prov prov ..."
+	    "[-hv] [-s stripesize] name prov prov ..."
 	},
 	{ "destroy", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
-	{ "dump", 0, stripe_main, G_NULL_OPTS, NULL,
+	{ "dump", 0, stripe_main, G_NULL_OPTS,
 	    "prov ..."
 	},
 	{ "label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, stripe_main,
 	    {
 		{ 'h', "hardcode", NULL, G_TYPE_BOOL },
-		{ 's', "stripesize", &default_stripesize, G_TYPE_NUMBER },
+		{ 's', "stripesize", GSTRIPE_STRIPESIZE, G_TYPE_NUMBER },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-hv] [-s stripesize] name prov prov ..."
+	    "[-hv] [-s stripesize] name prov prov ..."
 	},
 	{ "stop", G_FLAG_VERBOSE, NULL,
 	    {
 		{ 'f', "force", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-fv] name ..."
+	    "[-fv] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/class/virstor/geom_virstor.c b/sbin/geom/class/virstor/geom_virstor.c
index 5630de21d0b..b08a8b9e489 100644
--- a/sbin/geom/class/virstor/geom_virstor.c
+++ b/sbin/geom/class/virstor/geom_virstor.c
@@ -48,8 +48,9 @@ __FBSDID("$FreeBSD$");
 
 uint32_t lib_version = G_LIB_VERSION;
 uint32_t version = G_VIRSTOR_VERSION;
-static intmax_t chunk_size = 4 * 1024 * 1024; /* in kB (default: 4 MB) */
-static intmax_t vir_size = 2ULL << 40; /* in MB (default: 2 TB) */
+
+#define	GVIRSTOR_CHUNK_SIZE	"4M"
+#define	GVIRSTOR_VIR_SIZE	"2T"
 
 #if G_LIB_VERSION == 1
 /* Support RELENG_6 */
@@ -62,44 +63,44 @@ static intmax_t vir_size = 2ULL << 40; /* in MB (default: 2 TB) */
 static void virstor_main(struct gctl_req *req, unsigned flags);
 
 struct g_command class_commands[] = {
-	{"clear", G_FLAG_VERBOSE, virstor_main, G_NULL_OPTS, NULL,
-		"[-v] prov ..."
+	{ "clear", G_FLAG_VERBOSE, virstor_main, G_NULL_OPTS,
+	    "[-v] prov ..."
 	},
-	{"dump", 0, virstor_main, G_NULL_OPTS, NULL,
-		"prov ..."
+	{ "dump", 0, virstor_main, G_NULL_OPTS,
+	    "prov ..."
 	},
-	{"label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, virstor_main,
-		{
-			{'h', "hardcode", NULL, G_TYPE_BOOL},
-			{'m', "chunk_size", &chunk_size, G_TYPE_NUMBER},
-			{'s', "vir_size", &vir_size, G_TYPE_NUMBER},
-			G_OPT_SENTINEL
-		},
-		NULL, "[-h] [-v] [-m chunk_size] [-s vir_size] name provider0 [provider1 ...]"
+	{ "label", G_FLAG_VERBOSE | G_FLAG_LOADKLD, virstor_main,
+	    {
+		{ 'h', "hardcode", NULL, G_TYPE_BOOL},
+		{ 'm', "chunk_size", GVIRSTOR_CHUNK_SIZE, G_TYPE_NUMBER},
+		{ 's', "vir_size", GVIRSTOR_VIR_SIZE, G_TYPE_NUMBER},
+		G_OPT_SENTINEL
+	    },
+	    "[-h] [-v] [-m chunk_size] [-s vir_size] name provider0 [provider1 ...]"
 	},
-	{"destroy", G_FLAG_VERBOSE, NULL,
-		{
-			{'f', "force", NULL, G_TYPE_BOOL},
-			G_OPT_SENTINEL
-		},
-		NULL, "[-fv] name ..."
+	{ "destroy", G_FLAG_VERBOSE, NULL,
+	    {
+		{ 'f', "force", NULL, G_TYPE_BOOL},
+		G_OPT_SENTINEL
+	    },
+	    "[-fv] name ..."
 	},
-	{"stop", G_FLAG_VERBOSE, NULL,
-		{
-			{'f', "force", NULL, G_TYPE_BOOL},
-			G_OPT_SENTINEL
-		},
-		NULL, "[-fv] name ... (alias for \"destroy\")"
+	{ "stop", G_FLAG_VERBOSE, NULL,
+	    {
+		{ 'f', "force", NULL, G_TYPE_BOOL},
+		G_OPT_SENTINEL
+	    },
+	    "[-fv] name ... (alias for \"destroy\")"
 	},
-	{"add", G_FLAG_VERBOSE, NULL,
-		{
-			{'h', "hardcode", NULL, G_TYPE_BOOL},
-			G_OPT_SENTINEL
-		},
-		NULL, "[-vh] name prov [prov ...]"
+	{ "add", G_FLAG_VERBOSE, NULL,
+	    {
+		{ 'h', "hardcode", NULL, G_TYPE_BOOL},
+		G_OPT_SENTINEL
+	    },
+	    "[-vh] name prov [prov ...]"
 	},
-	{"remove", G_FLAG_VERBOSE, NULL, G_NULL_OPTS, NULL,
-		"[-v] name ..."
+	{ "remove", G_FLAG_VERBOSE, NULL, G_NULL_OPTS,
+	    "[-v] name ..."
 	},
 	G_CMD_SENTINEL
 };
diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index b891098df03..4a3dcd46543 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -75,8 +75,8 @@ static void std_load(struct gctl_req *req, unsigned flags);
 static void std_unload(struct gctl_req *req, unsigned flags);
 
 struct g_command std_commands[] = {
-	{ "help", 0, std_help, G_NULL_OPTS, NULL, NULL },
-	{ "list", 0, std_list, G_NULL_OPTS, NULL, 
+	{ "help", 0, std_help, G_NULL_OPTS, NULL },
+	{ "list", 0, std_list, G_NULL_OPTS,
 	    "[name ...]"
 	},
 	{ "status", 0, std_status,
@@ -84,11 +84,11 @@ struct g_command std_commands[] = {
 		{ 's', "script", NULL, G_TYPE_BOOL },
 		G_OPT_SENTINEL
 	    },
-	    NULL, "[-s] [name ...]"
+	    "[-s] [name ...]"
 	},
 	{ "load", G_FLAG_VERBOSE | G_FLAG_LOADKLD, std_load, G_NULL_OPTS,
-	    NULL, NULL },
-	{ "unload", G_FLAG_VERBOSE, std_unload, G_NULL_OPTS, NULL, NULL },
+	    NULL },
+	{ "unload", G_FLAG_VERBOSE, std_unload, G_NULL_OPTS, NULL },
 	G_CMD_SENTINEL
 };
 
@@ -129,8 +129,6 @@ usage_command(struct g_command *cmd, const char *prefix)
 		if (opt->go_val != NULL || G_OPT_TYPE(opt) == G_TYPE_BOOL)
 			fprintf(stderr, "]");
 	}
-	if (cmd->gc_argname)
-		fprintf(stderr, " %s", cmd->gc_argname);
 	fprintf(stderr, "\n");
 }
 
@@ -348,39 +346,24 @@ parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc,
 				warnx("Option '%c' not specified.",
 				    opt->go_char);
 				usage();
+			} else if (G_OPT_TYPE(opt) == G_TYPE_ASCNUM &&
+			    *(const char *)opt->go_val == '\0') {
+			    	;	/* add nothing. */
 			} else {
-				if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) {
-					gctl_ro_param(req, opt->go_name,
-					    sizeof(intmax_t), opt->go_val);
-				} else if (G_OPT_TYPE(opt) == G_TYPE_STRING ||
-				    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {
-					if (cmd->gc_argname == NULL ||
-					    opt->go_val == NULL ||
-					    *(const char *)opt->go_val != '\0')
-						gctl_ro_param(req, opt->go_name,
-						    -1, opt->go_val);
-				} else {
-					assert(!"Invalid type");
-				}
+				set_option(req, opt, opt->go_val);
 			}
 		}
 	}
 
-	if (cmd->gc_argname == NULL) {
-		/*
-		 * Add rest of given arguments.
-		 */
-		gctl_ro_param(req, "nargs", sizeof(int), argc);
-		for (i = 0; i < (unsigned)*argc; i++) {
-			char argname[16];
+	/*
+	 * Add rest of given arguments.
+	 */
+	gctl_ro_param(req, "nargs", sizeof(int), argc);
+	for (i = 0; i < (unsigned)*argc; i++) {
+		char argname[16];
 
-			snprintf(argname, sizeof(argname), "arg%u", i);
-			gctl_ro_param(req, argname, -1, (*argv)[i]);
-		}
-	} else {
-		if (*argc != 1)
-			usage();
-		gctl_ro_param(req, cmd->gc_argname, -1, (*argv)[0]);
+		snprintf(argname, sizeof(argname), "arg%u", i);
+		gctl_ro_param(req, argname, -1, (*argv)[i]);
 	}
 }
 
diff --git a/sbin/geom/core/geom.h b/sbin/geom/core/geom.h
index e2f96e9b846..92c97a3eb05 100644
--- a/sbin/geom/core/geom.h
+++ b/sbin/geom/core/geom.h
@@ -28,7 +28,7 @@
 
 #ifndef _GEOM_H_
 #define	_GEOM_H_
-#define	G_LIB_VERSION	4
+#define	G_LIB_VERSION	5
 
 #define	G_FLAG_NONE	0x0000
 #define	G_FLAG_VERBOSE	0x0001
@@ -49,7 +49,7 @@
 
 #define G_OPT_SENTINEL	{ '\0', NULL, NULL, G_TYPE_NONE }
 #define G_NULL_OPTS	{ G_OPT_SENTINEL }
-#define	G_CMD_SENTINEL	{ NULL, 0, NULL, G_NULL_OPTS, NULL, NULL }
+#define	G_CMD_SENTINEL	{ NULL, 0, NULL, G_NULL_OPTS, NULL }
 
 struct g_option {
 	char		 go_char;
@@ -63,7 +63,6 @@ struct g_command {
 	unsigned	 gc_flags;
 	void		(*gc_func)(struct gctl_req *, unsigned);
 	struct g_option	gc_options[G_OPT_MAX];
-	const char	*gc_argname;
 	const char	*gc_usage;
 };
 #endif	/* !_GEOM_H_ */
diff --git a/sys/geom/part/g_part.c b/sys/geom/part/g_part.c
index b9fca082dad..cedc3ac6461 100644
--- a/sys/geom/part/g_part.c
+++ b/sys/geom/part/g_part.c
@@ -1327,6 +1327,10 @@ g_part_ctlreq(struct gctl_req *req, struct g_class *mp, const char *verb)
 		parm = 0;
 		switch (ap->name[0]) {
 		case 'a':
+			if (!strcmp(ap->name, "arg0")) {
+				parm = mparms &
+				    (G_PART_PARM_GEOM | G_PART_PARM_PROVIDER);
+			}
 			if (!strcmp(ap->name, "attrib"))
 				parm = G_PART_PARM_ATTRIB;
 			break;
@@ -1346,10 +1350,6 @@ g_part_ctlreq(struct gctl_req *req, struct g_class *mp, const char *verb)
 			if (!strcmp(ap->name, "flags"))
 				parm = G_PART_PARM_FLAGS;
 			break;
-		case 'g':
-			if (!strcmp(ap->name, "geom"))
-				parm = G_PART_PARM_GEOM;
-			break;
 		case 'i':
 			if (!strcmp(ap->name, "index"))
 				parm = G_PART_PARM_INDEX;
@@ -1362,10 +1362,6 @@ g_part_ctlreq(struct gctl_req *req, struct g_class *mp, const char *verb)
 			if (!strcmp(ap->name, "output"))
 				parm = G_PART_PARM_OUTPUT;
 			break;
-		case 'p':
-			if (!strcmp(ap->name, "provider"))
-				parm = G_PART_PARM_PROVIDER;
-			break;
 		case 's':
 			if (!strcmp(ap->name, "scheme"))
 				parm = G_PART_PARM_SCHEME;

From 315fcbf7db9813644198f7037e46d7043df62a5f Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 13 Sep 2010 13:59:28 +0000
Subject: [PATCH 0704/1624] Add G_TYPE_MULTI flag, which when set for the given
 option, will allow the option to be specified multiple times. This will help
 to implement things like passing multiple keyfiles to geli(8) instead of
 cat(1)ing them all into stdin and reading from there using one '-k -' option.

---
 sbin/geom/core/geom.c | 40 ++++++++++++++++++++++++++++++++++------
 sbin/geom/core/geom.h |  6 ++++++
 2 files changed, 40 insertions(+), 6 deletions(-)

diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index 4a3dcd46543..39731e964a3 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -234,9 +234,31 @@ find_option(struct g_command *cmd, char ch)
 static void
 set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 {
+	const char *optname;
 	uint64_t number;
 	void *ptr;
 
+	if (G_OPT_ISMULTI(opt)) {
+		size_t optnamesize;
+
+		if (G_OPT_NUM(opt) == UCHAR_MAX)
+			errx(EXIT_FAILURE, "Too many -%c options.", opt->go_char);
+
+		/*
+		 * Base option name length plus 3 bytes for option number
+		 * (max. 255 options) plus 1 byte for terminating '\0'.
+		 */
+		optnamesize = strlen(opt->go_name) + 3 + 1;
+		ptr = malloc(optnamesize);
+		if (ptr == NULL)
+			errx(EXIT_FAILURE, "No memory.");
+		snprintf(ptr, optnamesize, "%s%u", opt->go_name, G_OPT_NUM(opt));
+		G_OPT_NUMINC(opt);
+		optname = ptr;
+	} else {
+		optname = opt->go_name;
+	}
+
 	if (G_OPT_TYPE(opt) == G_TYPE_NUMBER ||
 	    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {
 		if (expand_number(val, &number) == -1) {
@@ -249,27 +271,30 @@ set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 				errx(EXIT_FAILURE, "No memory.");
 			*(intmax_t *)ptr = number;
 			opt->go_val = ptr;
-			gctl_ro_param(req, opt->go_name, sizeof(intmax_t),
+			gctl_ro_param(req, optname, sizeof(intmax_t),
 			    opt->go_val);
 		} else {
 			asprintf((void *)(&ptr), "%jd", number);
 			if (ptr == NULL)
 				errx(EXIT_FAILURE, "No memory.");
 			opt->go_val = ptr;
-			gctl_ro_param(req, opt->go_name, -1, opt->go_val);
+			gctl_ro_param(req, optname, -1, opt->go_val);
 		}
 	} else if (G_OPT_TYPE(opt) == G_TYPE_STRING) {
-		gctl_ro_param(req, opt->go_name, -1, val);
+		gctl_ro_param(req, optname, -1, val);
 	} else if (G_OPT_TYPE(opt) == G_TYPE_BOOL) {
 		ptr = malloc(sizeof(int));
 		if (ptr == NULL)
 			errx(EXIT_FAILURE, "No memory.");
 		*(int *)ptr = *val - '0';
 		opt->go_val = ptr;
-		gctl_ro_param(req, opt->go_name, sizeof(int), opt->go_val);
+		gctl_ro_param(req, optname, sizeof(int), opt->go_val);
 	} else {
 		assert(!"Invalid type");
 	}
+
+	if (G_OPT_ISMULTI(opt))
+		free(__DECONST(char *, optname));
 }
 
 /*
@@ -294,7 +319,10 @@ parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc,
 		if (opt->go_name == NULL)
 			break;
 		assert(G_OPT_TYPE(opt) != 0);
-		assert((opt->go_type & ~G_TYPE_MASK) == 0);
+		assert((opt->go_type & ~(G_TYPE_MASK | G_TYPE_MULTI)) == 0);
+		/* Multiple bool arguments makes no sense. */
+		assert(G_OPT_TYPE(opt) != G_TYPE_BOOL ||
+		    (opt->go_type & G_TYPE_MULTI) == 0);
 		strlcatf(opts, sizeof(opts), "%c", opt->go_char);
 		if (G_OPT_TYPE(opt) != G_TYPE_BOOL)
 			strlcat(opts, ":", sizeof(opts));
@@ -314,7 +342,7 @@ parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc,
 		opt = find_option(cmd, ch);
 		if (opt == NULL)
 			usage();
-		if (G_OPT_ISDONE(opt)) {
+		if (!G_OPT_ISMULTI(opt) && G_OPT_ISDONE(opt)) {
 			warnx("Option '%c' specified twice.", opt->go_char);
 			usage();
 		}
diff --git a/sbin/geom/core/geom.h b/sbin/geom/core/geom.h
index 92c97a3eb05..c88005ef10a 100644
--- a/sbin/geom/core/geom.h
+++ b/sbin/geom/core/geom.h
@@ -41,11 +41,17 @@
 #define	G_TYPE_ASCNUM	0x04
 #define	G_TYPE_MASK	0x0f
 #define	G_TYPE_DONE	0x10
+#define	G_TYPE_MULTI	0x20
+#define	G_TYPE_NUMMASK	0xff00
+#define	G_TYPE_NUMSHIFT	8
 
 #define	G_OPT_MAX	16
 #define	G_OPT_DONE(opt)		do { (opt)->go_type |= G_TYPE_DONE; } while (0)
 #define	G_OPT_ISDONE(opt)	((opt)->go_type & G_TYPE_DONE)
+#define	G_OPT_ISMULTI(opt)	((opt)->go_type & G_TYPE_MULTI)
 #define	G_OPT_TYPE(opt)		((opt)->go_type & G_TYPE_MASK)
+#define	G_OPT_NUM(opt)		(((opt)->go_type & G_TYPE_NUMMASK) >> G_TYPE_NUMSHIFT)
+#define	G_OPT_NUMINC(opt)	((opt)->go_type += (1 << G_TYPE_NUMSHIFT))
 
 #define G_OPT_SENTINEL	{ '\0', NULL, NULL, G_TYPE_NONE }
 #define G_NULL_OPTS	{ G_OPT_SENTINEL }

From 6bbbd18b8367305d6afd227d1e49a5241b0db821 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Mon, 13 Sep 2010 14:25:07 +0000
Subject: [PATCH 0705/1624] Change call order to enable interrupts only after
 timer being programmed.

Submitted by:	nwhitehorn
---
 sys/powerpc/powerpc/mp_machdep.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/sys/powerpc/powerpc/mp_machdep.c b/sys/powerpc/powerpc/mp_machdep.c
index 6915c4bb728..54951b7b315 100644
--- a/sys/powerpc/powerpc/mp_machdep.c
+++ b/sys/powerpc/powerpc/mp_machdep.c
@@ -91,12 +91,12 @@ machdep_ap_bootstrap(void)
 	PCPU_SET(curthread, PCPU_GET(idlethread));
 	PCPU_SET(curpcb, curthread->td_pcb);
 
-	/* Let the DEC and external interrupts go */
-	mtmsr(mfmsr() | PSL_EE);
-
 	/* Start per-CPU event timers. */
 	cpu_initclocks_ap();
 
+	/* Let the DEC and external interrupts go */
+	mtmsr(mfmsr() | PSL_EE);
+
 	/* Announce ourselves awake, and enter the scheduler */
 	sched_throw(NULL);
 }

From 8cfc82586ec3b4987fdb9d4a415b3bee234aa363 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 15:30:09 +0000
Subject: [PATCH 0706/1624] Move to using Makefile.arch to include the proper
 target-specific programs.

---
 usr.bin/Makefile | 193 ++++++++++++++---------------------------------
 1 file changed, 57 insertions(+), 136 deletions(-)

diff --git a/usr.bin/Makefile b/usr.bin/Makefile
index 3214761f60a..3f59bd90a08 100644
--- a/usr.bin/Makefile
+++ b/usr.bin/Makefile
@@ -11,48 +11,29 @@
 
 SUBDIR=	alias \
 	apply \
-	${_ar} \
 	asa \
-	${_at} \
-	${_atm} \
 	awk \
 	banner \
 	basename \
-	${_bc} \
-	${_biff} \
-	${_bluetooth} \
 	brandelf \
 	bsdiff \
 	bzip2 \
 	bzip2recover \
-	${_c89} \
-	${_c99} \
-	${_calendar} \
 	cap_mkdb \
-	${_catman} \
 	chat \
-	${_checknr} \
-	${_chkey} \
 	chpass \
 	cksum \
 	${_clang} \
 	cmp \
 	col \
-	${_colcrt} \
 	colldef \
 	colrm \
 	column \
 	comm \
-	${_compile_et} \
 	compress \
-	${_cpio} \
 	cpuset \
 	csplit \
-	${_csup} \
-	${_ctags} \
 	cut \
-	${_dc} \
-	${_dig} \
 	dirname \
 	du \
 	ee \
@@ -64,12 +45,10 @@ SUBDIR=	alias \
 	false \
 	fetch \
 	file \
-	${_file2c} \
 	find \
 	finger \
 	fmt \
 	fold \
-	${_from} \
 	fstat \
 	fsync \
 	ftp \
@@ -78,15 +57,11 @@ SUBDIR=	alias \
 	getconf \
 	getent \
 	getopt \
-	${_gprof} \
 	${_grep} \
 	gzip \
 	head \
-	${_hesinfo} \
 	hexdump \
-	${_host} \
 	id \
-	${_indent} \
 	ipcrm \
 	ipcs \
 	join \
@@ -105,10 +80,8 @@ SUBDIR=	alias \
 	less \
 	lessecho \
 	lesskey \
-	${_lex} \
 	limits \
 	locale \
-	${_locate} \
 	lock \
 	lockf \
 	logger \
@@ -120,8 +93,6 @@ SUBDIR=	alias \
 	lsvfs \
 	lzmainfo \
 	m4 \
-	${_mail} \
-	${_make} \
 	${_makewhatis} \
 	mesg \
 	minigzip \
@@ -129,24 +100,16 @@ SUBDIR=	alias \
 	mkdep \
 	mkfifo \
 	mklocale \
-	${_mkstr} \
 	mktemp \
 	mkuzip \
-	${_msgs} \
 	mt \
-	${_nc} \
 	ncal \
-	${_ncplist} \
-	${_ncplogin} \
 	netstat \
 	newgrp \
-	${_newkey} \
 	nfsstat \
 	nice \
 	nl \
 	nohup \
-	${_nslookup} \
-	${_nsupdate} \
 	opieinfo \
 	opiekey \
 	opiepasswd \
@@ -159,26 +122,19 @@ SUBDIR=	alias \
 	printenv \
 	printf \
 	procstat \
-	${_quota} \
 	renice \
 	rev \
 	revoke \
-	${_rlogin} \
-	${_rpcgen} \
 	rpcinfo \
 	rs \
-	${_rsh} \
 	rup \
-	${_ruptime} \
 	rusers \
 	rwall \
-	${_rwho} \
 	script \
 	sed \
 	seq \
 	shar \
 	showmount \
-	${_smbutil} \
 	sockstat \
 	split \
 	stat \
@@ -190,7 +146,6 @@ SUBDIR=	alias \
 	tar \
 	tcopy \
 	tee \
-	${_telnet} \
 	tftp \
 	time \
 	tip \
@@ -200,25 +155,19 @@ SUBDIR=	alias \
 	tr \
 	true \
 	truncate \
-	${_truss} \
+	truss \
 	tset \
 	tsort \
 	tty \
-	${_ul} \
 	uname \
 	unexpand \
-	${_unifdef} \
 	uniq \
 	unzip \
 	units \
 	unvis \
-	${_usbhidaction} \
-	${_usbhidctl} \
 	users \
 	uudecode \
 	uuencode \
-	${_vacation} \
-	${_vgrind} \
 	vi \
 	vis \
 	vmstat \
@@ -244,37 +193,33 @@ SUBDIR=	alias \
 	${_ypmatch} \
 	${_ypwhich}
 
-.if ${MACHINE_ARCH} != "arm"
-_truss=		truss
-.endif
-
 # NB: keep these sorted by MK_* knobs
 
 .if ${MK_AT} != "no"
-_at=		at
+SUBDIR+=	at
 .endif
 
 .if ${MK_ATM} != "no"
-_atm=		atm
+SUBDIR+=	atm
 .endif
 
 .if ${MK_MAN_UTILS} != "no"
-_catman=	catman
+SUBDIR+=	catman
 .endif
 
 .if ${MK_BIND_UTILS} != "no"
-_dig=		dig
-_host=		host
-_nslookup=	nslookup
-_nsupdate=	nsupdate
+SUBDIR+=	dig
+SUBDIR+=	host
+SUBDIR+=	nslookup
+SUBDIR+=	nsupdate
 .endif
 
 .if ${MK_BLUETOOTH} != "no"
-_bluetooth=	bluetooth
+SUBDIR+=	bluetooth
 .endif
 
 .if ${MK_BSD_CPIO} != "no"
-_cpio=		cpio
+SUBDIR+=	cpio
 .endif
 
 .if ${MK_BSD_GREP} != "no"
@@ -282,7 +227,7 @@ _grep=		grep
 .endif
 
 .if ${MK_CALENDAR} != "no"
-_calendar=	calendar
+SUBDIR+=	calendar
 .endif
 
 .if ${MK_CLANG} != "no"
@@ -290,33 +235,33 @@ _clang=		clang
 .endif
 
 .if ${MK_HESIOD} != "no"
-_hesinfo=	hesinfo
+SUBDIR+=	hesinfo
 .endif
 
 .if ${MK_OPENSSL} != "no"
-_bc=		bc
-_chkey=		chkey
-_dc=		dc
-_newkey=	newkey
+SUBDIR+=	bc
+SUBDIR+=	chkey
+SUBDIR+=	dc
+SUBDIR+=	newkey
 .if ${MK_LIBTHR} != "no"
-_csup=		csup
+SUBDIR+=	csup
 .endif
 .endif
 
 .if ${MK_LOCATE} != "no"
-_locate=	locate
+SUBDIR+=	locate
 .endif
 
 # XXX msgs?
 .if ${MK_MAIL} != "no"
-_biff=		biff
-_from=		from
-_mail=		mail
-_msgs=		msgs
+SUBDIR+=	biff
+SUBDIR+=	from
+SUBDIR+=	mail
+SUBDIR+=	msgs
 .endif
 
 .if ${MK_MAKE} != "no"
-_make=		make
+SUBDIR+=	make
 .endif
 
 .if ${MK_MAN_UTILS} != "no"
@@ -324,91 +269,67 @@ _makewhatis=	makewhatis
 .endif
 
 .if ${MK_NETCAT} != "no"
-_nc=		nc
+SUBDIR+=	nc
 .endif
 
 .if ${MK_NIS} != "no"
-_ypcat=		ypcat
-_ypmatch=	ypmatch
-_ypwhich=	ypwhich
+SUBDIR+=	ypcat
+SUBDIR+=	ypmatch
+SUBDIR+=	ypwhich
 .endif
 
 .if ${MK_QUOTAS} != "no"
-_quota=		quota
+SUBDIR+=	quota
 .endif
 
 .if ${MK_RCMDS} != "no"
-_rlogin=	rlogin
-_rsh=		rsh
-_ruptime=	ruptime
-_rwho=		rwho
+SUBDIR+=	rlogin
+SUBDIR+=	rsh
+SUBDIR+=	ruptime
+SUBDIR+=	rwho
 .endif
 
 .if ${MK_SENDMAIL} != "no"
-_vacation=	vacation
+SUBDIR+=	vacation
 .endif
 
 .if ${MK_TELNET} != "no"
-_telnet=	telnet
+SUBDIR+=	telnet
 .endif
 
 .if ${MK_TEXTPROC} != "no"
-_checknr=	checknr
-_colcrt=	colcrt
-_ul=		ul
+SUBDIR+=	checknr
+SUBDIR+=	colcrt
+SUBDIR+=	ul
 .endif
 
 .if ${MK_TOOLCHAIN} != "no"
-_ar=		ar
-_c89=		c89
-_c99=		c99
-_compile_et=	compile_et
-_ctags=		ctags
-_file2c=	file2c
-_gprof=		gprof
-_indent=	indent
-_lex=		lex
-_mkstr=		mkstr
-_rpcgen=	rpcgen
-_unifdef=	unifdef
-_xlint=		xlint
-_xstr=		xstr
+SUBDIR+=	ar
+SUBDIR+=	c89
+SUBDIR+=	c99
+SUBDIR+=	compile_et
+SUBDIR+=	ctags
+SUBDIR+=	file2c
+SUBDIR+=	gprof
+SUBDIR+=	indent
+SUBDIR+=	lex
+SUBDIR+=	mkstr
+SUBDIR+=	rpcgen
+SUBDIR+=	unifdef
+SUBDIR+=	xlint
+SUBDIR+=	xstr
 # XXX maybe under textproc?
-_vgrind=	vgrind
-_yacc=		yacc
+SUBDIR+=	vgrind
+SUBDIR+=	yacc
 .endif
 
 .if ${MK_USB} != "no"
-_usbhidaction=	usbhidaction
-_usbhidctl=	usbhidctl
+SUBDIR+=	usbhidaction
+SUBDIR+=	usbhidctl
 .endif
 
-.if ${MACHINE_ARCH} == "i386"
-.if ${MK_NCP} != "no"
-_ncplist=	ncplist
-_ncplogin=	ncplogin
-.endif
-_smbutil=	smbutil
-.endif
+.include 
 
-.if ${MACHINE_ARCH} == "ia64"
-_smbutil=	smbutil
-.endif
-
-.if ${MACHINE_ARCH} == "amd64"
-.if ${MK_NCP} != "no"
-_ncplist=	ncplist
-_ncplogin=	ncplogin
-.endif
-_smbutil=	smbutil
-.endif
-
-.if ${MACHINE_ARCH} == "powerpc"
-_smbutil=	smbutil
-.endif
-
-.if ${MACHINE_ARCH} == "sparc64"
-_smbutil=	smbutil
-.endif
+SUBDIR:=	${SUBDIR:O}
 
 .include 

From 7a7811e7bf45f07bd523622e57a3f95732f7df03 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Mon, 13 Sep 2010 15:36:42 +0000
Subject: [PATCH 0707/1624] Fix a subtle bug uncovered by the recent one-shot
 timer import in which any spin locks acquired between the enabling of
 interrupts in machdep_ap_bootstrap() and the invocation of the scheduler
 would fail to have interrupts disabled due to the fake spinlock already held
 by the idle thread. sched_throw(NULL) will enable interrupts by itself when
 exiting this spinlock, so just let it do that and don't enable interrupts
 here.

---
 sys/powerpc/powerpc/mp_machdep.c | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/sys/powerpc/powerpc/mp_machdep.c b/sys/powerpc/powerpc/mp_machdep.c
index 54951b7b315..9086db5299c 100644
--- a/sys/powerpc/powerpc/mp_machdep.c
+++ b/sys/powerpc/powerpc/mp_machdep.c
@@ -94,9 +94,6 @@ machdep_ap_bootstrap(void)
 	/* Start per-CPU event timers. */
 	cpu_initclocks_ap();
 
-	/* Let the DEC and external interrupts go */
-	mtmsr(mfmsr() | PSL_EE);
-
 	/* Announce ourselves awake, and enter the scheduler */
 	sched_throw(NULL);
 }

From 747e7efda0ba0d0772e3f5606c3fbf94fe2ffcfd Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Mon, 13 Sep 2010 16:39:33 +0000
Subject: [PATCH 0708/1624] TARGET_64BIT isn't needed anymore, GC it (partial
 merge from tbemd).

---
 sys/conf/Makefile.mips | 8 --------
 sys/mips/conf/MALTA64  | 1 -
 sys/mips/conf/OCTEON1  | 1 -
 3 files changed, 10 deletions(-)

diff --git a/sys/conf/Makefile.mips b/sys/conf/Makefile.mips
index 0b56bb72518..6291d6cb464 100644
--- a/sys/conf/Makefile.mips
+++ b/sys/conf/Makefile.mips
@@ -54,20 +54,12 @@ SYSTEM_LD+=-EB
 EXTRA_FLAGS+=-EB 
 TRAMP_LDFLAGS+=-Wl,-EB 
 HACK_EXTRA_FLAGS+=-EB -Wl,-EB
-.if defined(TARGET_64BIT)
-SYSTEM_LD+=-m elf64btsmip_fbsd
-HACK_EXTRA_FLAGS+=-Wl,-m,elf64btsmip_fbsd
-.endif
 .else
 CFLAGS+=-EL
 SYSTEM_LD+=-EL
 EXTRA_FLAGS+=-EL
 TRAMP_LDFLAGS+=-Wl,-EL
 HACK_EXTRA_FLAGS+=-EL -Wl,-EL
-.if defined(TARGET_64BIT)
-SYSTEM_LD+=-m elf64ltsmip_fbsd
-HACK_EXTRA_FLAGS+=-Wl,-m,elf64ltsmip_fbsd
-.endif
 .endif
 
 
diff --git a/sys/mips/conf/MALTA64 b/sys/mips/conf/MALTA64
index e7f01c7093b..65b1e986779 100644
--- a/sys/mips/conf/MALTA64
+++ b/sys/mips/conf/MALTA64
@@ -21,7 +21,6 @@ ident		MALTA
 
 makeoptions	ARCH_FLAGS="-march=mips64 -mabi=64"
 makeoptions	MIPS_LITTLE_ENDIAN=defined
-makeoptions	TARGET_64BIT=t
 makeoptions	LDSCRIPT_NAME=	ldscript.mips.mips64
 
 options 	YAMON
diff --git a/sys/mips/conf/OCTEON1 b/sys/mips/conf/OCTEON1
index 3c8b3f2b7f7..f9774dff5a3 100644
--- a/sys/mips/conf/OCTEON1
+++ b/sys/mips/conf/OCTEON1
@@ -34,7 +34,6 @@ makeoptions	LDSCRIPT_NAME=ldscript.mips.octeon1.64
 # Don't build any modules yet.
 makeoptions	MODULES_OVERRIDE=""
 makeoptions	TARGET_BIG_ENDIAN=defined
-makeoptions	TARGET_64BIT=defined
 makeoptions	KERNLOADADDR=0xffffffff80100000
 
 include		"../cavium/std.octeon1"

From d69eb5201dd88d7a7235aaf0687593b76600b546 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Mon, 13 Sep 2010 17:49:39 +0000
Subject: [PATCH 0709/1624] Add a note about userland DTracing.

Sponsored by:	The FreeBSD Foundation
---
 UPDATING | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/UPDATING b/UPDATING
index 22fd3c62415..f4a8fed2aaf 100644
--- a/UPDATING
+++ b/UPDATING
@@ -22,6 +22,16 @@ NOTE TO PEOPLE WHO THINK THAT FreeBSD 9.x IS SLOW:
 	machines to maximize performance.  (To disable malloc debugging, run
 	ln -s aj /etc/malloc.conf.)
 
+20100913:
+	DTrace has grown support for userland tracing. Due to this, DTrace is
+	now i386 and amd64 only.
+	dtruss(1) is now installed by default on those systems and a new
+	kernel module is needed for userland tracing: fasttrap.
+	No changes to your kernel config file are necessary to enable
+	userland tracing, but you might consider adding 'STRIP=' and
+	'CFLAGS+=-fno-omit-frame-pointer' to your make.conf if you want
+	to have informative userland stack traces in DTrace (ustack).
+
 20100725:
 	The acpi_aiboost(4) driver has been removed in favor of the new
 	aibs(4) driver. You should update your kernel configuration file.

From ec88dcaec13daa417b8493cdb08564faca363d78 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Mon, 13 Sep 2010 17:53:43 +0000
Subject: [PATCH 0710/1624] Bump __FreeBSD_version to reflect the userland
 DTrace changes.

Sponsored by:	The FreeBSD Foundation
---
 sys/sys/param.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/param.h b/sys/sys/param.h
index 7f1878b80dd..8ca03f3392b 100644
--- a/sys/sys/param.h
+++ b/sys/sys/param.h
@@ -58,7 +58,7 @@
  *		in the range 5 to 9.
  */
 #undef __FreeBSD_version
-#define __FreeBSD_version 900020	/* Master, propagated to newvers */
+#define __FreeBSD_version 900021	/* Master, propagated to newvers */
 
 #ifndef LOCORE
 #include 

From cbb9ebd738981292ab65558e231987415552f589 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Mon, 13 Sep 2010 18:26:34 +0000
Subject: [PATCH 0711/1624] Allow a kernel config to specify a set but empty
 value via 'makeoptions OPTION=' for consistency with the make commandline.

Previously 'makeoptions WERROR=' would result in a syntax error; now
it produces the same effect as 'makeoptions WERROR'.  Both forms now
result in 'WERROR=' in the generated Makefile.
---
 usr.sbin/config/config.y | 1 +
 1 file changed, 1 insertion(+)

diff --git a/usr.sbin/config/config.y b/usr.sbin/config/config.y
index 430bbf09602..808b67317ea 100644
--- a/usr.sbin/config/config.y
+++ b/usr.sbin/config/config.y
@@ -261,6 +261,7 @@ Mkopt_list:
 
 Mkoption:
 	Save_id { newopt(&mkopt, $1, ns(""), 0); } |
+	Save_id EQUALS { newopt(&mkopt, $1, ns(""), 0); } |
 	Save_id EQUALS Opt_value { newopt(&mkopt, $1, $3, 0); } |
 	Save_id PLUSEQUALS Opt_value { newopt(&mkopt, $1, $3, 1); } ;
 

From 404a593e2891361fbfd6da1f2f43770d38da0607 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Mon, 13 Sep 2010 18:48:23 +0000
Subject: [PATCH 0712/1624] Revert r212370, as it causes a LOR on powerpc. 
 powerpc does a few unexpected things in copyout(9) and so wiring the user
 buffer is not sufficient to perform a copyout(9) while holding a random
 mutex.

Requested by: nwhitehorn
---
 sys/dev/cxgb/cxgb_sge.c    | 48 ++++++++++++++++++++-----------
 sys/kern/kern_malloc.c     | 58 ++++++++++++++++++++++++++++++++------
 sys/kern/kern_sysctl.c     | 28 ------------------
 sys/kern/subr_lock.c       | 20 +++++++++----
 sys/kern/subr_sbuf.c       |  4 +--
 sys/kern/subr_sleepqueue.c | 14 +++++++--
 sys/kern/subr_witness.c    | 17 +++++++++--
 sys/sys/sysctl.h           |  3 --
 sys/vm/uma_core.c          | 54 +++++++++++++++++++++++++++++------
 sys/vm/vm_phys.c           | 27 ++++++++++++++----
 sys/vm/vm_reserv.c         |  9 ++++--
 11 files changed, 194 insertions(+), 88 deletions(-)

diff --git a/sys/dev/cxgb/cxgb_sge.c b/sys/dev/cxgb/cxgb_sge.c
index 5fb206b8ba3..015f8414d12 100644
--- a/sys/dev/cxgb/cxgb_sge.c
+++ b/sys/dev/cxgb/cxgb_sge.c
@@ -3227,6 +3227,7 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 	struct sge_rspq *rspq;
 	struct sge_qset *qs;
 	int i, err, dump_end, idx;
+	static int multiplier = 1;
 	struct sbuf *sb;
 	struct rsp_desc *rspd;
 	uint32_t data[4];
@@ -3251,8 +3252,8 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 	err = t3_sge_read_rspq(qs->port->adapter, rspq->cntxt_id, data);
 	if (err)
 		return (err);
-
-	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
+retry_sbufops:
+	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
 
 	sbuf_printf(sb, " \n index=%u size=%u MSI-X/RspQ=%u intr enable=%u intr armed=%u\n",
 	    (data[0] & 0xffff), data[0] >> 16, ((data[2] >> 20) & 0x3f),
@@ -3275,11 +3276,13 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 		    rspd->rss_hdr.rss_hash_val, be32toh(rspd->flags),
 		    be32toh(rspd->len_cq), rspd->intr_gen);
 	}
-
-	err = sbuf_finish(sb);
-	/* Output a trailing NUL. */
-	if (err == 0)
-		err = SYSCTL_OUT(req, "", 1);
+	if (sbuf_error(sb) != 0) {
+		sbuf_delete(sb);
+		multiplier++;
+		goto retry_sbufops;
+	}
+	sbuf_finish(sb);
+	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
 	sbuf_delete(sb);
 	return (err);
 }	
@@ -3290,6 +3293,7 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 	struct sge_txq *txq;
 	struct sge_qset *qs;
 	int i, j, err, dump_end;
+	static int multiplier = 1;
 	struct sbuf *sb;
 	struct tx_desc *txd;
 	uint32_t *WR, wr_hi, wr_lo, gen;
@@ -3317,7 +3321,9 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 	if (err)
 		return (err);
 	
-	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
+	    
+retry_sbufops:
+	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
 
 	sbuf_printf(sb, " \n credits=%u GTS=%u index=%u size=%u rspq#=%u cmdq#=%u\n",
 	    (data[0] & 0x7fff), ((data[0] >> 15) & 1), (data[0] >> 16), 
@@ -3344,10 +3350,13 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 			    WR[j], WR[j + 1], WR[j + 2], WR[j + 3]);
 
 	}
-	err = sbuf_finish(sb);
-	/* Output a trailing NUL. */
-	if (err == 0)
-		err = SYSCTL_OUT(req, "", 1);
+	if (sbuf_error(sb) != 0) {
+		sbuf_delete(sb);
+		multiplier++;
+		goto retry_sbufops;
+	}
+	sbuf_finish(sb);
+	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
 	sbuf_delete(sb);
 	return (err);
 }
@@ -3358,6 +3367,7 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 	struct sge_txq *txq;
 	struct sge_qset *qs;
 	int i, j, err, dump_end;
+	static int multiplier = 1;
 	struct sbuf *sb;
 	struct tx_desc *txd;
 	uint32_t *WR, wr_hi, wr_lo, gen;
@@ -3381,7 +3391,8 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 		return (EINVAL);
 	}
 
-	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
+retry_sbufops:
+	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
 	sbuf_printf(sb, " qid=%d start=%d -> end=%d\n", qs->idx,
 	    txq->txq_dump_start,
 	    (txq->txq_dump_start + txq->txq_dump_count) & 255);
@@ -3401,10 +3412,13 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 			    WR[j], WR[j + 1], WR[j + 2], WR[j + 3]);
 
 	}
-	err = sbuf_finish(sb);
-	/* Output a trailing NUL. */
-	if (err == 0)
-		err = SYSCTL_OUT(req, "", 1);
+	if (sbuf_error(sb) != 0) {
+		sbuf_delete(sb);
+		multiplier++;
+		goto retry_sbufops;
+	}
+	sbuf_finish(sb);
+	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
 	sbuf_delete(sb);
 	return (err);
 }
diff --git a/sys/kern/kern_malloc.c b/sys/kern/kern_malloc.c
index 6d9b77574a6..1e97b55dc03 100644
--- a/sys/kern/kern_malloc.c
+++ b/sys/kern/kern_malloc.c
@@ -828,11 +828,25 @@ sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
 	struct malloc_type_internal *mtip;
 	struct malloc_type_header mth;
 	struct malloc_type *mtp;
-	int error, i;
+	int buflen, count, error, i;
 	struct sbuf sbuf;
+	char *buffer;
 
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	mtx_lock(&malloc_mtx);
+restart:
+	mtx_assert(&malloc_mtx, MA_OWNED);
+	count = kmemcount;
+	mtx_unlock(&malloc_mtx);
+	buflen = sizeof(mtsh) + count * (sizeof(mth) +
+	    sizeof(struct malloc_type_stats) * MAXCPU) + 1;
+	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
+	mtx_lock(&malloc_mtx);
+	if (count < kmemcount) {
+		free(buffer, M_TEMP);
+		goto restart;
+	}
+
+	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
 
 	/*
 	 * Insert stream header.
@@ -841,7 +855,11 @@ sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
 	mtsh.mtsh_maxcpus = MAXCPU;
 	mtsh.mtsh_count = kmemcount;
-	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
+	if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
+		mtx_unlock(&malloc_mtx);
+		error = ENOMEM;
+		goto out;
+	}
 
 	/*
 	 * Insert alternating sequence of type headers and type statistics.
@@ -854,19 +872,30 @@ sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
 		 */
 		bzero(&mth, sizeof(mth));
 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
-		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
+		if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
+			mtx_unlock(&malloc_mtx);
+			error = ENOMEM;
+			goto out;
+		}
 
 		/*
 		 * Insert type statistics for each CPU.
 		 */
 		for (i = 0; i < MAXCPU; i++) {
-			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
-			    sizeof(mtip->mti_stats[i]));
+			if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
+			    sizeof(mtip->mti_stats[i])) < 0) {
+				mtx_unlock(&malloc_mtx);
+				error = ENOMEM;
+				goto out;
+			}
 		}
 	}
 	mtx_unlock(&malloc_mtx);
-	error = sbuf_finish(&sbuf);
+	sbuf_finish(&sbuf);
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+out:
 	sbuf_delete(&sbuf);
+	free(buffer, M_TEMP);
 	return (error);
 }
 
@@ -976,19 +1005,26 @@ DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
 static int
 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
 {
+	int linesize = 64;
 	struct sbuf sbuf;
 	uint64_t count;
 	uint64_t waste;
 	uint64_t mem;
+	int bufsize;
 	int error;
+	char *buf;
 	int rsize;
 	int size;
 	int i;
 
+	bufsize = linesize * (KMEM_ZSIZE + 1);
+	bufsize += 128; 	/* For the stats line */
+	bufsize += 128; 	/* For the banner line */
 	waste = 0;
 	mem = 0;
 
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
+	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
+	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
 	sbuf_printf(&sbuf, 
 	    "\n  Size                    Requests  Real Size\n");
 	for (i = 0; i < KMEM_ZSIZE; i++) {
@@ -1006,8 +1042,12 @@ sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
 	sbuf_printf(&sbuf,
 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
 	    (unsigned long long)mem, (unsigned long long)waste);
-	error = sbuf_finish(&sbuf);
+	sbuf_finish(&sbuf);
+
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+
 	sbuf_delete(&sbuf);
+	free(buf, M_TEMP);
 	return (error);
 }
 
diff --git a/sys/kern/kern_sysctl.c b/sys/kern/kern_sysctl.c
index 49ccc505278..b83502c2f41 100644
--- a/sys/kern/kern_sysctl.c
+++ b/sys/kern/kern_sysctl.c
@@ -51,7 +51,6 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -1545,30 +1544,3 @@ userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
 	}
 	return (error);
 }
-
-/*
- * Drain into a sysctl struct.  The user buffer must be wired.
- */
-static int
-sbuf_sysctl_drain(void *arg, const char *data, int len)
-{
-	struct sysctl_req *req = arg;
-	int error;
-
-	error = SYSCTL_OUT(req, data, len);
-	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
-	return (error == 0 ? len : -error);
-}
-
-struct sbuf *
-sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
-    struct sysctl_req *req)
-{
-
-	/* Wire the user buffer, so we can write without blocking. */
-	sysctl_wire_old_buffer(req, 0);
-
-	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN);
-	sbuf_set_drain(s, sbuf_sysctl_drain, req);
-	return (s);
-}
diff --git a/sys/kern/subr_lock.c b/sys/kern/subr_lock.c
index 530ebc5b265..0c97052c76e 100644
--- a/sys/kern/subr_lock.c
+++ b/sys/kern/subr_lock.c
@@ -191,7 +191,8 @@ struct lock_prof_cpu *lp_cpu[MAXCPU];
 volatile int lock_prof_enable = 0;
 static volatile int lock_prof_resetting;
 
-#define LPROF_SBUF_SIZE		256
+/* SWAG: sbuf size = avg stat. line size * number of locks */
+#define LPROF_SBUF_SIZE		256 * 400
 
 static int lock_prof_rejected;
 static int lock_prof_skipspin;
@@ -383,6 +384,8 @@ lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
 				continue;
 			lock_prof_sum(l, &lp, i, spin, t);
 			lock_prof_output(&lp, sb);
+			if (sbuf_error(sb) != 0)
+				return;
 		}
 	}
 }
@@ -390,11 +393,13 @@ lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
 static int
 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
 {
+	static int multiplier = 1;
 	struct sbuf *sb;
 	int error, cpu, t;
 	int enabled;
 
-	sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
+retry_sbufops:
+	sb = sbuf_new(NULL, NULL, LPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
 	sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
 	    "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
 	enabled = lock_prof_enable;
@@ -406,13 +411,16 @@ dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
 			continue;
 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[0], sb, 0, t);
 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[1], sb, 1, t);
+		if (sbuf_error(sb) != 0) {
+			sbuf_delete(sb);
+			multiplier++;
+			goto retry_sbufops;
+		}
 	}
 	lock_prof_enable = enabled;
 
-	error = sbuf_finish(sb);
-	/* Output a trailing NUL. */
-	if (error == 0)
-		error = SYSCTL_OUT(req, "", 1);
+	sbuf_finish(sb);
+	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
 	sbuf_delete(sb);
 	return (error);
 }
diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index 0d083b4b33e..e81faa52036 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -303,8 +303,8 @@ sbuf_drain(struct sbuf *s)
 		s->s_error = -len;
 		return (s->s_error);
 	}
-	KASSERT(len > 0 && len <= s->s_len,
-	    ("Bad drain amount %d for sbuf %p", len, s));
+
+	KASSERT(len > 0, ("Drain must either error or work!"));
 	s->s_len -= len;
 	/*
 	 * Fast path for the expected case where all the data was
diff --git a/sys/kern/subr_sleepqueue.c b/sys/kern/subr_sleepqueue.c
index cdf7a47c368..b8be8f49210 100644
--- a/sys/kern/subr_sleepqueue.c
+++ b/sys/kern/subr_sleepqueue.c
@@ -1018,7 +1018,7 @@ sleepq_abort(struct thread *td, int intrval)
 
 #ifdef SLEEPQUEUE_PROFILING
 #define	SLEEPQ_PROF_LOCATIONS	1024
-#define	SLEEPQ_SBUFSIZE		512
+#define	SLEEPQ_SBUFSIZE		(40 * 512)
 struct sleepq_prof {
 	LIST_ENTRY(sleepq_prof) sp_link;
 	const char	*sp_wmesg;
@@ -1123,13 +1123,15 @@ reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 static int
 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 {
+	static int multiplier = 1;
 	struct sleepq_prof *sp;
 	struct sbuf *sb;
 	int enabled;
 	int error;
 	int i;
 
-	sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req);
+retry_sbufops:
+	sb = sbuf_new(NULL, NULL, SLEEPQ_SBUFSIZE * multiplier, SBUF_FIXEDLEN);
 	sbuf_printf(sb, "\nwmesg\tcount\n");
 	enabled = prof_enabled;
 	mtx_lock_spin(&sleepq_prof_lock);
@@ -1139,13 +1141,19 @@ dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 		LIST_FOREACH(sp, &sleepq_hash[i], sp_link) {
 			sbuf_printf(sb, "%s\t%ld\n",
 			    sp->sp_wmesg, sp->sp_count);
+			if (sbuf_error(sb) != 0) {
+				sbuf_delete(sb);
+				multiplier++;
+				goto retry_sbufops;
+			}
 		}
 	}
 	mtx_lock_spin(&sleepq_prof_lock);
 	prof_enabled = enabled;
 	mtx_unlock_spin(&sleepq_prof_lock);
 
-	error = sbuf_finish(sb);
+	sbuf_finish(sb);
+	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
 	sbuf_delete(sb);
 	return (error);
 }
diff --git a/sys/kern/subr_witness.c b/sys/kern/subr_witness.c
index 3fec4c420b2..e5aa8dcaa2b 100644
--- a/sys/kern/subr_witness.c
+++ b/sys/kern/subr_witness.c
@@ -154,7 +154,8 @@ __FBSDID("$FreeBSD$");
 #define	MAX_W_NAME	64
 
 #define	BADSTACK_SBUF_SIZE	(256 * WITNESS_COUNT)
-#define	FULLGRAPH_SBUF_SIZE	512
+#define	CYCLEGRAPH_SBUF_SIZE	8192
+#define	FULLGRAPH_SBUF_SIZE	32768
 
 /*
  * These flags go in the witness relationship matrix and describe the
@@ -2544,7 +2545,7 @@ sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
 		return (error);
 	}
 	error = 0;
-	sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
+	sb = sbuf_new(NULL, NULL, FULLGRAPH_SBUF_SIZE, SBUF_FIXEDLEN);
 	if (sb == NULL)
 		return (ENOMEM);
 	sbuf_printf(sb, "\n");
@@ -2556,10 +2557,20 @@ sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
 		witness_add_fullgraph(sb, w);
 	mtx_unlock_spin(&w_mtx);
 
+	/*
+	 * While using SBUF_FIXEDLEN, check if the sbuf overflowed.
+	 */
+	if (sbuf_error(sb) != 0) {
+		sbuf_delete(sb);
+		panic("%s: sbuf overflowed, bump FULLGRAPH_SBUF_SIZE value\n",
+		    __func__);
+	}
+
 	/*
 	 * Close the sbuf and return to userland.
 	 */
-	error = sbuf_finish(sb);
+	sbuf_finish(sb);
+	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
 	sbuf_delete(sb);
 
 	return (error);
diff --git a/sys/sys/sysctl.h b/sys/sys/sysctl.h
index fbfd6e84202..1ee49cab246 100644
--- a/sys/sys/sysctl.h
+++ b/sys/sys/sysctl.h
@@ -710,9 +710,6 @@ void	sysctl_lock(void);
 void	sysctl_unlock(void);
 int	sysctl_wire_old_buffer(struct sysctl_req *req, size_t len);
 
-struct sbuf;
-struct sbuf	*sbuf_new_for_sysctl(struct sbuf *, char *, int,
-		    struct sysctl_req *);
 #else	/* !_KERNEL */
 #include 
 
diff --git a/sys/vm/uma_core.c b/sys/vm/uma_core.c
index 23b88ee45c2..558b4c727e7 100644
--- a/sys/vm/uma_core.c
+++ b/sys/vm/uma_core.c
@@ -3175,16 +3175,36 @@ sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
 	uma_keg_t kz;
 	uma_zone_t z;
 	uma_keg_t k;
-	int count, error, i;
+	char *buffer;
+	int buflen, count, error, i;
 
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
-
-	count = 0;
 	mtx_lock(&uma_mtx);
+restart:
+	mtx_assert(&uma_mtx, MA_OWNED);
+	count = 0;
 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
 			count++;
 	}
+	mtx_unlock(&uma_mtx);
+
+	buflen = sizeof(ush) + count * (sizeof(uth) + sizeof(ups) *
+	    (mp_maxid + 1)) + 1;
+	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
+
+	mtx_lock(&uma_mtx);
+	i = 0;
+	LIST_FOREACH(kz, &uma_kegs, uk_link) {
+		LIST_FOREACH(z, &kz->uk_zones, uz_link)
+			i++;
+	}
+	if (i > count) {
+		free(buffer, M_TEMP);
+		goto restart;
+	}
+	count =  i;
+
+	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
 
 	/*
 	 * Insert stream header.
@@ -3193,7 +3213,11 @@ sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
 	ush.ush_version = UMA_STREAM_VERSION;
 	ush.ush_maxcpus = (mp_maxid + 1);
 	ush.ush_count = count;
-	(void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
+	if (sbuf_bcat(&sbuf, &ush, sizeof(ush)) < 0) {
+		mtx_unlock(&uma_mtx);
+		error = ENOMEM;
+		goto out;
+	}
 
 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
@@ -3226,7 +3250,12 @@ sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
 			uth.uth_frees = z->uz_frees;
 			uth.uth_fails = z->uz_fails;
 			uth.uth_sleeps = z->uz_sleeps;
-			(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
+			if (sbuf_bcat(&sbuf, &uth, sizeof(uth)) < 0) {
+				ZONE_UNLOCK(z);
+				mtx_unlock(&uma_mtx);
+				error = ENOMEM;
+				goto out;
+			}
 			/*
 			 * While it is not normally safe to access the cache
 			 * bucket pointers while not on the CPU that owns the
@@ -3251,14 +3280,21 @@ sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
 				ups.ups_allocs = cache->uc_allocs;
 				ups.ups_frees = cache->uc_frees;
 skip:
-				(void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
+				if (sbuf_bcat(&sbuf, &ups, sizeof(ups)) < 0) {
+					ZONE_UNLOCK(z);
+					mtx_unlock(&uma_mtx);
+					error = ENOMEM;
+					goto out;
+				}
 			}
 			ZONE_UNLOCK(z);
 		}
 	}
 	mtx_unlock(&uma_mtx);
-	error = sbuf_finish(&sbuf);
-	sbuf_delete(&sbuf);
+	sbuf_finish(&sbuf);
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+out:
+	free(buffer, M_TEMP);
 	return (error);
 }
 
diff --git a/sys/vm/vm_phys.c b/sys/vm/vm_phys.c
index 26e4981606a..e75c3401acf 100644
--- a/sys/vm/vm_phys.c
+++ b/sys/vm/vm_phys.c
@@ -123,9 +123,12 @@ sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	struct vm_freelist *fl;
+	char *cbuf;
+	const int cbufsize = vm_nfreelists*(VM_NFREEORDER + 1)*81;
 	int error, flind, oind, pind;
 
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
+	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
+	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
 	for (flind = 0; flind < vm_nfreelists; flind++) {
 		sbuf_printf(&sbuf, "\nFREE LIST %d:\n"
 		    "\n  ORDER (SIZE)  |  NUMBER"
@@ -146,8 +149,10 @@ sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
 			sbuf_printf(&sbuf, "\n");
 		}
 	}
-	error = sbuf_finish(&sbuf);
+	sbuf_finish(&sbuf);
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
 	sbuf_delete(&sbuf);
+	free(cbuf, M_TEMP);
 	return (error);
 }
 
@@ -159,9 +164,12 @@ sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	struct vm_phys_seg *seg;
+	char *cbuf;
+	const int cbufsize = VM_PHYSSEG_MAX*(VM_NFREEORDER + 1)*81;
 	int error, segind;
 
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
+	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
+	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
 		sbuf_printf(&sbuf, "\nSEGMENT %d:\n\n", segind);
 		seg = &vm_phys_segs[segind];
@@ -172,8 +180,10 @@ sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
 		sbuf_printf(&sbuf, "domain:    %d\n", seg->domain);
 		sbuf_printf(&sbuf, "free list: %p\n", seg->free_queues);
 	}
-	error = sbuf_finish(&sbuf);
+	sbuf_finish(&sbuf);
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
 	sbuf_delete(&sbuf);
+	free(cbuf, M_TEMP);
 	return (error);
 }
 
@@ -185,18 +195,23 @@ static int
 sysctl_vm_phys_lookup_lists(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
+	char *cbuf;
+	const int cbufsize = (vm_nfreelists + 1) * VM_NDOMAIN * 81;
 	int domain, error, flind, ndomains;
 
 	ndomains = vm_nfreelists - VM_NFREELIST + 1;
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
+	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
+	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
 	for (domain = 0; domain < ndomains; domain++) {
 		sbuf_printf(&sbuf, "\nDOMAIN %d:\n\n", domain);
 		for (flind = 0; flind < vm_nfreelists; flind++)
 			sbuf_printf(&sbuf, "  [%d]:\t%p\n", flind,
 			    vm_phys_lookup_lists[domain][flind]);
 	}
-	error = sbuf_finish(&sbuf);
+	sbuf_finish(&sbuf);
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
 	sbuf_delete(&sbuf);
+	free(cbuf, M_TEMP);
 	return (error);
 }
 #endif
diff --git a/sys/vm/vm_reserv.c b/sys/vm/vm_reserv.c
index aa8e80f7311..d9e908f62a3 100644
--- a/sys/vm/vm_reserv.c
+++ b/sys/vm/vm_reserv.c
@@ -180,9 +180,12 @@ sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	vm_reserv_t rv;
+	char *cbuf;
+	const int cbufsize = (VM_NRESERVLEVEL + 1) * 81;
 	int counter, error, level, unused_pages;
 
-	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
+	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
+	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
 	sbuf_printf(&sbuf, "\nLEVEL     SIZE  NUMBER\n\n");
 	for (level = -1; level <= VM_NRESERVLEVEL - 2; level++) {
 		counter = 0;
@@ -196,8 +199,10 @@ sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
 		sbuf_printf(&sbuf, "%5.5d: %6.6dK, %6.6d\n", level,
 		    unused_pages * (PAGE_SIZE / 1024), counter);
 	}
-	error = sbuf_finish(&sbuf);
+	sbuf_finish(&sbuf);
+	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
 	sbuf_delete(&sbuf);
+	free(cbuf, M_TEMP);
 	return (error);
 }
 

From 3c907063e99f1c6290f53aa0fd9ccaf8d2e2c5ab Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Mon, 13 Sep 2010 19:47:09 +0000
Subject: [PATCH 0713/1624] Remove the page queues lock around
 vm_page_undirty() - it is no longer needed.

Reviewed by:	alc
---
 sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 180ac4fc4ef..0779a4b050c 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -326,9 +326,7 @@ page_lookup(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
 			if (vm_page_sleep_if_busy(pp, FALSE, "zfsmwb"))
 				continue;
 			vm_page_busy(pp);
-			vm_page_lock_queues();
 			vm_page_undirty(pp);
-			vm_page_unlock_queues();
 		} else {
 			if (__predict_false(obj->cache != NULL)) {
 				vm_page_cache_free(obj, OFF_TO_IDX(start),

From c5ad71aff5854cad1fb1f11396d4ade7f2ed510a Mon Sep 17 00:00:00 2001
From: Hiroki Sato 
Date: Mon, 13 Sep 2010 19:51:15 +0000
Subject: [PATCH 0714/1624] Revert changes in r206408.

Discussed with:	dougb, core.5, and core.6
---
 etc/defaults/rc.conf     |   8 +-
 etc/network.subr         | 221 +++++++++++++++++++++++----------------
 etc/rc.d/ip6addrctl      |   2 +
 etc/rc.d/netif           |   9 +-
 etc/rc.d/netoptions      |   7 --
 share/man/man5/rc.conf.5 | 136 ++++++++++--------------
 6 files changed, 192 insertions(+), 191 deletions(-)

diff --git a/etc/defaults/rc.conf b/etc/defaults/rc.conf
index 427fe2d0c16..c875b28953d 100644
--- a/etc/defaults/rc.conf
+++ b/etc/defaults/rc.conf
@@ -210,8 +210,6 @@ cloned_interfaces=""		# List of cloned network interfaces to create.
 ifconfig_lo0="inet 127.0.0.1"	# default loopback device configuration.
 #ifconfig_lo0_alias0="inet 127.0.0.254 netmask 0xffffffff" # Sample alias entry.
 #ifconfig_ed0_ipx="ipx 0x00010010"	# Sample IPX address family entry.
-#ifconfig_ed0_ipv6="RTADV" 	# Sample IPv6 entry for RA/rtsol(8)
-#ifconfig_ed0_ipv6="inet6 auto_linklocal" 	# To configure only link-local
 #ifconfig_ed0_ipv6="inet6 2001:db8:1::1 prefixlen 64" # Sample IPv6 addr entry
 #ifconfig_ed0_alias0="inet6 2001:db8:2::1 prefixlen 64" # Sample IPv6 alias
 #ifconfig_fxp0_name="net0"	# Change interface name from fxp0 to net0.
@@ -446,9 +444,8 @@ ubthidhci_enable="NO"		# Switch an USB BT controller present on
 icmp_bmcastecho="NO"	# respond to broadcast ping packets
 
 ### IPv6 options: ###
-ipv6_network_interfaces="AUTO"	# List of IPv6 network interfaces
-ipv6_prefer="YES" 		# Use IPv6 when both IPv4 and IPv6 can be used
-ipv6_privacy="NO" 		# Use privacy addresses with RTADV (RFC 4193)
+ipv6_network_interfaces="none"	# List of IPv6 network interfaces
+				# (or "auto" or "none").
 ipv6_defaultrouter="NO"		# Set to IPv6 default gateway (or NO).
 #ipv6_defaultrouter="2002:c058:6301::"	# Use this for 6to4 (RFC 3068)
 ipv6_static_routes=""		# Set to static route list (or leave empty).
@@ -507,6 +504,7 @@ ipv6_ipfilter_rules="/etc/ipf6.rules"	# rules definition file for ipfilter,
 					# for examples
 ip6addrctl_enable="YES"	# Set to YES to enable default address selection
 ip6addrctl_verbose="NO"	# Set to YES to enable verbose configuration messages
+ipv6_prefer="NO"	# Use IPv6 when both IPv4 and IPv6 can be used
 
 ##############################################################
 ###  System console options  #################################
diff --git a/etc/network.subr b/etc/network.subr
index 21c15895eba..e7b5945877c 100644
--- a/etc/network.subr
+++ b/etc/network.subr
@@ -96,32 +96,44 @@ ifconfig_up()
 	# inet6 specific
 	if afexists inet6; then
 		if ipv6if $1; then
-			# Implicitly handles ipv6_gateway_enable
-			_ipv6_opts='-ifdisabled -accept_rtadv'
-
-			if ipv6_autoconfif $1; then
-				_ipv6_opts='-ifdisabled accept_rtadv'
-			fi
-
-			ifconfig $1 inet6 $_ipv6_opts
-
-			# ifconfig_IF_ipv6
-			ifconfig_args=`ifconfig_getargs $1 ipv6`
-
-			if [ -n "$ifconfig_args" ]; then
-				ifconfig $1 $ifconfig_args
-				_cfg=0
+			if checkyesno ipv6_gateway_enable; then
+				_ipv6_opts="-accept_rtadv"
 			fi
 		else
-		# Remove in FreeBSD 10.x
-		# Explicit test is necessary here to avoid nonexistence error
-			case "$ipv6_enable" in
-			[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
-			warn "Interface $1 will NOT be configured for IPv6"
+			if checkyesno ipv6_prefer; then
+				_ipv6_opts="-ifdisabled"
+			else
+				_ipv6_opts="ifdisabled"
+			fi
+
+			# backward compatibility: $ipv6_enable
+			case $ipv6_enable in
+			[Yy][Ee][Ss])
+				_ipv6_opts="${_ipv6_opts} accept_rtadv"
 				;;
 			esac
+		fi
 
-			ifconfig $1 inet6 ifdisabled
+		if [ -n "${_ipv6_opts}" ]; then
+			ifconfig $1 inet6 ${_ipv6_opts}
+		fi
+
+		# ifconfig_IF_ipv6
+		ifconfig_args=`ifconfig_getargs $1 ipv6`
+		if [ -n "${ifconfig_args}" ]; then
+			ifconfig $1 inet6 -ifdisabled
+			ifconfig $1 ${ifconfig_args}
+			_cfg=0
+		fi
+
+		# backward compatiblity: $ipv6_ifconfig_IF
+		ifconfig_args=`get_if_var $1 ipv6_ifconfig_IF`
+		if [ -n "${ifconfig_args}" ]; then
+			warn "\$ipv6_ifconfig_$1 is obsolete." \
+			    "  Use ifconfig_$1_ipv6 instead."
+			ifconfig $1 inet6 -ifdisabled
+			ifconfig $1 inet6 ${ifconfig_args}
+			_cfg=0
 		fi
 	fi
 
@@ -182,7 +194,7 @@ ifconfig_down()
 #	$default if given.
 get_if_var()
 {
-	local _if _punct _punct_c _var _default prefix suffix
+	local _if _punct _var _default prefix suffix
 
 	if [ $# -ne 2 -a $# -ne 3 ]; then
 		err 3 'USAGE: get_if_var name var [default]'
@@ -207,7 +219,7 @@ get_if_var()
 #	outside this file.
 _ifconfig_getargs()
 {
-	local _ifn _af value
+	local _ifn _af
 	_ifn=$1
 	_af=${2+_$2}
 
@@ -215,18 +227,7 @@ _ifconfig_getargs()
 		return 1
 	fi
 
-	value=`get_if_var $_ifn ifconfig_IF$_af "$ifconfig_DEFAULT"`
-
-	# Remove in FreeBSD 10.x
-	if [ "$_af" = _ipv6 -a -z "$value" ]; then
-		value=`get_if_var $_ifn ipv6_ifconfig_IF "$ifconfig_DEFAULT"`
-		if [ -n "$value" ]; then
-			warn "\$ipv6_ifconfig_$1 is obsolete." \
-			"  Use ifconfig_$1_ipv6 instead."
-		fi
-	fi
-
-	echo $value
+	get_if_var $_ifn ifconfig_IF$_af "$ifconfig_DEFAULT"
 }
 
 # ifconfig_getargs if [af]
@@ -248,8 +249,6 @@ ifconfig_getargs()
 		[Nn][Oo][Ss][Yy][Nn][Cc][Dd][Hh][Cc][Pp]) ;;
 		[Ss][Yy][Nn][Cc][Dd][Hh][Cc][Pp]) ;;
 		[Ww][Pp][Aa]) ;;
-		[Rr][Tt][Aa][Dd][Vv]) ;;
-		[Nn][Oo][Rr][Tt][Aa][Dd][Vv]) ;;
 		*)
 			_args="$_args $_arg"
 			;;
@@ -373,47 +372,77 @@ afexists()
 	esac
 }
 
+# noafif if
+#	Returns 0 if the interface has no af configuration and 1 otherwise.
+noafif()
+{
+	local _if
+	_if=$1
+
+	case $_if in
+	pflog[0-9]*|\
+	pfsync[0-9]*|\
+	an[0-9]*|\
+	ath[0-9]*|\
+	ipw[0-9]*|\
+	iwi[0-9]*|\
+	iwn[0-9]*|\
+	ral[0-9]*|\
+	wi[0-9]*|\
+	wl[0-9]*|\
+	wpi[0-9]*)
+		return 0
+		;;
+	esac
+
+	return 1
+}
+
 # ipv6if if
 #	Returns 0 if the interface should be configured for IPv6 and
 #	1 otherwise.
 ipv6if()
 {
+	local _if _tmpargs i
+	_if=$1
+
 	if ! afexists inet6; then
 		return 1
 	fi
 
 	# lo0 is always IPv6-enabled
-	case $1 in
+	case $_if in
 	lo0)
 		return 0
 		;;
 	esac
 
-	local _if _tmpargs i
-	_if=$1
+	# True if $ifconfig_IF_ipv6 is defined.
+	_tmpargs=`_ifconfig_getargs $_if ipv6`
+	if [ -n "${_tmpargs}" ]; then
+		return 0
+	fi
 
-	case "$ipv6_network_interfaces" in
+	# backward compatibility: True if $ipv6_ifconfig_IF is defined.
+	_tmpargs=`get_if_var $_if ipv6_ifconfig_IF`
+	if [ -n "${_tmpargs}" ]; then
+		return 0
+	fi
+
+	case "${ipv6_network_interfaces}" in
+	[Aa][Uu][Tt][Oo])
+		return 0
+		;;
 	''|[Nn][Oo][Nn][Ee])
 		return 1
 		;;
-	$_if|"$_if "*|*" $_if"|*" $_if "*|[Aa][Uu][Tt][Oo])
-		# True if $ifconfig_IF_ipv6 is defined.
-		_tmpargs=`_ifconfig_getargs $_if ipv6`
-		# Also true if ipv6_prefix_IF is defined
-		[ -n "$_tmpargs" ] || _tmpargs=`get_if_var $_if ipv6_prefix_IF`
-		;;
 	esac
 
-	if [ -n "$_tmpargs" ]; then
-		# Remove in FreeBSD 10.x
-		# Explicit test is necessary here to avoid nonexistence error
-		case "$ipv6_enable" in
-		[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
-			;;
-		*)	return 0
-			;;
-		esac
-	fi
+	for i in ${ipv6_network_interfaces}; do
+		if [ "$i" = "$_if" ]; then
+			return 0
+		fi
+	done
 
 	return 1
 }
@@ -423,7 +452,24 @@ ipv6if()
 #	Stateless Address Configuration, 1 otherwise.
 ipv6_autoconfif()
 {
-	case $1 in
+	local _if _tmpargs _arg
+	_if=$1
+
+	if ! ipv6if $_if; then
+		return 1
+	fi
+	if noafif $_if; then
+		return 1
+	fi
+	if checkyesno ipv6_gateway_enable; then
+		return 1
+	fi
+	_tmpargs=`get_if_var $_if ipv6_prefix_IF`
+	if [ -n "${_tmpargs}" ]; then
+		return 1
+	fi
+
+	case $_if in
 	lo0|\
 	stf[0-9]*|\
 	faith[0-9]*|\
@@ -435,37 +481,32 @@ ipv6_autoconfif()
 		;;
 	esac
 
-	local _if _tmpargs _arg
-	_if=$1
-
-	if ! ipv6if $_if; then
-		return 1
-	fi
-	if checkyesno ipv6_gateway_enable; then
-		return 1
-	fi
-	_tmpargs=`get_if_var $_if ipv6_prefix_IF`
-	if [ -n "${_tmpargs}" ]; then
-		return 1
-	fi
-	if ! is_wired_interface $_if; then
-		case $_if in
-		wlan[0-9]*)	;;	# Allow test to continue
-		*)	return 1
-			;;
-		esac
-	fi
-
-	_tmpargs=`_ifconfig_getargs $_if ipv6`
-	case "$_tmpargs" in
-	*inet6\ *|*[Nn][Oo][Rr][Tt][Aa][Dd][Vv]*|*-accept_rtadv*)
-		return 1
-		;;
-	*[Rr][Tt][Aa][Dd][Vv]*|*accept_rtadv*)
+	# backward compatibility: $ipv6_enable
+	case $ipv6_enable in
+	[Yy][Ee][Ss])
 		return 0
 		;;
 	esac
 
+	_tmpargs=`_ifconfig_getargs $_if ipv6`
+	for _arg in $_tmpargs; do
+		case $_arg in
+		accept_rtadv)
+			return 0
+			;;
+		esac
+	done
+
+	# backward compatibility: $ipv6_ifconfig_IF
+	_tmpargs=`get_if_var $_if ipv6_ifconfig_IF`
+	for _arg in $_tmpargs; do
+		case $_arg in
+		accept_rtadv)
+			return 0
+			;;
+		esac
+	done
+
 	return 1
 }
 
@@ -478,7 +519,7 @@ ifexists()
 }
 
 # ipv4_up if
-#	add IPv4 addresses to the interface $if
+#	add IPv4 addresses to the interface $if 
 ipv4_up()
 {
 	local _if _ret
@@ -588,14 +629,14 @@ ipv6_down()
 ipv4_addrs_common()
 {
 	local _ret _if _action _cidr _cidr_addr
-	local _ipaddr _netmask _range _ipnet _iplow _iphigh _ipcount
+	local _ipaddr _netmask _range _ipnet _iplow _iphigh _ipcount 
 	_ret=1
 	_if=$1
 	_action=$2
-
+    
 	# get ipv4-addresses
 	cidr_addr=`get_if_var $_if ipv4_addrs_IF`
-
+    
 	for _cidr in ${cidr_addr}; do
 		_ipaddr=${_cidr%%/*}
 		_netmask="/"${_cidr##*/}
@@ -608,7 +649,7 @@ ipv4_addrs_common()
 		if [ "${_action}" = "-alias" ]; then
 			_netmask=""
 		fi
-
+        
 		_ipcount=${_iplow}
 		while [ "${_ipcount}" -le "${_iphigh}" ]; do
 			eval "ifconfig ${_if} ${_action} ${_ipnet}.${_ipcount}${_netmask}"
diff --git a/etc/rc.d/ip6addrctl b/etc/rc.d/ip6addrctl
index 3963b071c73..d3b18561795 100755
--- a/etc/rc.d/ip6addrctl
+++ b/etc/rc.d/ip6addrctl
@@ -20,6 +20,8 @@ status_cmd="ip6addrctl"
 prefer_ipv6_cmd="ip6addrctl_prefer_ipv6"
 prefer_ipv4_cmd="ip6addrctl_prefer_ipv4"
 
+set_rcvar_obsolete ipv6_enable ipv6_prefer
+
 ip6addrctl_prefer_ipv6()
 {
 	afexists inet6 || return 0
diff --git a/etc/rc.d/netif b/etc/rc.d/netif
index 06b8e76cfa9..f982cfce647 100755
--- a/etc/rc.d/netif
+++ b/etc/rc.d/netif
@@ -34,7 +34,6 @@
 . /etc/network.subr
 
 name="network"
-start_precmd="network_prestart"
 start_cmd="network_start"
 stop_cmd="network_stop"
 cloneup_cmd="clone_up"
@@ -42,13 +41,7 @@ clonedown_cmd="clone_down"
 extra_commands="cloneup clonedown"
 cmdifn=
 
-network_prestart()
-{
-	if [ -n "$ipv6_enable" ]; then
-		warn 'The ipv6_enable option is deprecated.'
-		warn 'See rc.conf(5) for information on disabling IPv6.'
-	fi
-}
+set_rcvar_obsolete ipv6_enable ipv6_prefer
 
 network_start()
 {
diff --git a/etc/rc.d/netoptions b/etc/rc.d/netoptions
index 433ce82f8a7..46313045679 100755
--- a/etc/rc.d/netoptions
+++ b/etc/rc.d/netoptions
@@ -99,13 +99,6 @@ netoptions_inet6()
 	else
 		${SYSCTL_W} net.inet6.ip6.v6only=1 >/dev/null
 	fi
-
-	if checkyesno ipv6_privacy; then
-		netoptions_init
-		echo -n " IPv6 Privacy Addresses"
-		${SYSCTL_W} net.inet6.ip6.use_tempaddr=1 >/dev/null
-		${SYSCTL_W} net.inet6.ip6.prefer_tempaddr=1 >/dev/null
-	fi
 }
 
 load_rc_config $name
diff --git a/share/man/man5/rc.conf.5 b/share/man/man5/rc.conf.5
index 80f187b662b..29084500088 100644
--- a/share/man/man5/rc.conf.5
+++ b/share/man/man5/rc.conf.5
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd September 4, 2010
+.Dd September 13, 2010
 .Dt RC.CONF 5
 .Os
 .Sh NAME
@@ -1261,86 +1261,26 @@ It is also possible to rename an interface by doing:
 ifconfig_ed0_name="net0"
 ifconfig_net0="inet 192.0.2.1 netmask 0xffffff00"
 .Ed
-.\" Remove in FreeBSD 10.x
 .It Va ipv6_enable
 .Pq Vt bool
-.Pp
-This option is deprecated.
-.Pp
 If the variable is
-.Dq Li YES
-it has no effect.
-To configure IPv6 for an interface see
-.Va ipv6_network_interfaces
-below.
+.Dq Li YES ,
+.Dq Li inet6 accept_rtadv
+is added to all of
+.Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
+and the
+.Va ipv6_prefer
+is defined as
+.Dq Li YES .
 .Pp
-If the variable is
-.Dq Li NO
-then other than
-.Dq Li lo0
-IPv6 will be disabled for each interface,
-however the same effect can be achieved by
-not configuring the interface.
-.It Va ipv6_network_interfaces
-.Pq Vt str
-This is the IPv6 equivalent of
-.Va network_interfaces .
-Normally configuration of this variable is not needed,
-the value should be left as
-.Dq Li AUTO .
-.Pp
-If
-.Dq Li INET6
-is configured in the kernel configuration for the
-.Dq Li lo0
-interface will always be performed.
-It is not necessary to list it in
-.Va ipv6_network_interfaces .
-.Pp
-Example configuration to accept Router Advertisements (RA) for the
-.Dq Li ed0
-interface:
-.Bd -literal
-ifconfig_ed0_ipv6="RTADV"
-.Ed
-.Pp
-To configure only a link-local address on the
-.Dq Li ed0
-interface:
-.Bd -literal
-ifconfig_ed0_ipv6="inet6 auto_linklocal"
-.Ed
-.Pp
-To disable RA the
-.Dq Li NORTADV
-option is available, although not required if manual
-configuration is performed as described below.
-.Pp
-An IPv6 interface can be configured manually with
+This variable is deprecated.  Use
+.Va ipv6_prefer
+and
 .Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6 .
-For example:
-.Bd -literal
-ifconfig_ed0_ipv6="inet6 2001:db8:1::1 prefixlen 64"
-.Ed
-.Pp
-Manual configuration of an IPv6 address will also
-require configuration of the
-.Va ipv6_defaultrouter
-option.
-.Pp
-Aliases should be set by
-.Va ifconfig_ Ns Ao Ar interface Ac Ns Va _alias Ns Aq Ar n
-with the
-.Dq Li inet6
-keyword.
-For example:
-.Pp
-.Bd -literal
-ifconfig_ed0_alias0="inet6 2001:db8:2::1 prefixlen 64"
-.Ed
-.Pp
 .It Va ipv6_prefer
 .Pq Vt bool
+This variable does the following:
+.Pp
 If the variable is
 .Dq Li YES ,
 the default policy of the source address selection set by
@@ -1351,15 +1291,49 @@ If the variable is
 .Dq Li NO ,
 the default policy of the source address selection set by
 .Xr ip6addrctl 8
-will be IPv4-preferred.
+will be IPv4-preferred, and all of interfaces which does not have the
+corrsponding
+.Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
+variable will be marked as
+.Dq Li IFDISABLED .
+This means only IPv6 functionality on that interface is completely
+disabled.  For more details of
+.Dq Li IFDISABLED
+flag and keywords
+.Dq Li inet6 ifdisabled ,
+see
+.Xr ifconfig 8 .
 .Pp
-.It Va ipv6_privacy
-.Pq Vt bool
-If the variable is
-.Dq Li YES
-privacy addresses will be generated for each IPv6
-interface as described in RFC 4193.
+.It Va ipv6_network_interfaces
+.Pq Vt str
+This is the IPv6 equivalent of
+.Va network_interfaces .
+Normally manual configuration of this variable is not needed.
 .Pp
+IPv6 functionality on an interface should be configured by
+.Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6 ,
+instead of setting ifconfig parameters in
+.Va ifconfig_ Ns Aq Ar interface .
+Aliases should be set by
+.Va ifconfig_ Ns Ao Ar interface Ac Ns Va _alias Ns Aq Ar n
+with
+.Dq Li inet6
+keyword.  For example:
+.Bd -literal
+ifconfig_ed0_ipv6="inet6 2001:db8:1::1 prefixlen 64"
+ifconfig_ed0_alias0="inet6 2001:db8:2::1 prefixlen 64"
+.Ed
+.Pp
+Interfaces that have an
+.Dq Li inet6 accept_rtadv
+keyword in
+.Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
+setting will be automatically configured by
+.Xr rtsol 8 .
+Note that this automatic configuration is disabled if the
+.Va ipv6_gateway_enable
+is set to
+.Dq Li YES .
 .It Va ipv6_prefix_ Ns Aq Ar interface
 .Pq Vt str
 If one or more prefixes are defined in

From e5481092bb4bea9edb21b3967194acc7da214ae2 Mon Sep 17 00:00:00 2001
From: Hiroki Sato 
Date: Mon, 13 Sep 2010 19:52:04 +0000
Subject: [PATCH 0715/1624] Fix $ipv6_network_interfaces and set it as AUTO by
 default.

Based on:	changes in r206408 by dougb
---
 etc/defaults/rc.conf |  2 +-
 etc/network.subr     | 35 ++++++++++++-----------------------
 2 files changed, 13 insertions(+), 24 deletions(-)

diff --git a/etc/defaults/rc.conf b/etc/defaults/rc.conf
index c875b28953d..5ff00fcbfb6 100644
--- a/etc/defaults/rc.conf
+++ b/etc/defaults/rc.conf
@@ -444,7 +444,7 @@ ubthidhci_enable="NO"		# Switch an USB BT controller present on
 icmp_bmcastecho="NO"	# respond to broadcast ping packets
 
 ### IPv6 options: ###
-ipv6_network_interfaces="none"	# List of IPv6 network interfaces
+ipv6_network_interfaces="auto"	# List of IPv6 network interfaces
 				# (or "auto" or "none").
 ipv6_defaultrouter="NO"		# Set to IPv6 default gateway (or NO).
 #ipv6_defaultrouter="2002:c058:6301::"	# Use this for 6to4 (RFC 3068)
diff --git a/etc/network.subr b/etc/network.subr
index e7b5945877c..aba8e451a3a 100644
--- a/etc/network.subr
+++ b/etc/network.subr
@@ -417,32 +417,21 @@ ipv6if()
 		;;
 	esac
 
-	# True if $ifconfig_IF_ipv6 is defined.
-	_tmpargs=`_ifconfig_getargs $_if ipv6`
-	if [ -n "${_tmpargs}" ]; then
-		return 0
-	fi
-
-	# backward compatibility: True if $ipv6_ifconfig_IF is defined.
-	_tmpargs=`get_if_var $_if ipv6_ifconfig_IF`
-	if [ -n "${_tmpargs}" ]; then
-		return 0
-	fi
-
 	case "${ipv6_network_interfaces}" in
-	[Aa][Uu][Tt][Oo])
-		return 0
-		;;
-	''|[Nn][Oo][Nn][Ee])
-		return 1
-		;;
-	esac
-
-	for i in ${ipv6_network_interfaces}; do
-		if [ "$i" = "$_if" ]; then
+	$_if|"$_if "*|*" $_if"|*" $_if "*|[Aa][Uu][Tt][Oo])
+		# True if $ifconfig_IF_ipv6 is defined.
+		_tmpargs=`_ifconfig_getargs $_if ipv6`
+		if [ -n "${_tmpargs}" ]; then
 			return 0
 		fi
-	done
+
+		# backward compatibility: True if $ipv6_ifconfig_IF is defined.
+		_tmpargs=`get_if_var $_if ipv6_ifconfig_IF`
+		if [ -n "${_tmpargs}" ]; then
+			return 0
+		fi
+		;;
+	esac
 
 	return 1
 }

From abe3ac576acc01d2af46f987e6e263b7bc7ab8fa Mon Sep 17 00:00:00 2001
From: Hiroki Sato 
Date: Mon, 13 Sep 2010 19:52:46 +0000
Subject: [PATCH 0716/1624] Add $ipv6_privacy to support
 net.inet6.ip6.use_tempaddr.  Note that this will be replaced with a per-IF
 version later.

Based on:	changes in r206408 by dougb
---
 etc/defaults/rc.conf     | 2 ++
 etc/rc.d/netoptions      | 7 +++++++
 share/man/man5/rc.conf.5 | 6 ++++++
 3 files changed, 15 insertions(+)

diff --git a/etc/defaults/rc.conf b/etc/defaults/rc.conf
index 5ff00fcbfb6..b041f15f332 100644
--- a/etc/defaults/rc.conf
+++ b/etc/defaults/rc.conf
@@ -453,6 +453,8 @@ ipv6_static_routes=""		# Set to static route list (or leave empty).
 				#  route toward loopback interface.
 #ipv6_route_xxx="fec0:0000:0000:0006:: -prefixlen 64 ::1"
 ipv6_gateway_enable="NO"	# Set to YES if this host will be a gateway.
+ipv6_privacy="NO"		# Use privacy address on RA-receiving IFs
+				# (RFC 4193)
 
 route6d_enable="NO"		# Set to YES to enable an IPv6 routing daemon.
 route6d_program="/usr/sbin/route6d"	# Name of IPv6 routing daemon.
diff --git a/etc/rc.d/netoptions b/etc/rc.d/netoptions
index 46313045679..433ce82f8a7 100755
--- a/etc/rc.d/netoptions
+++ b/etc/rc.d/netoptions
@@ -99,6 +99,13 @@ netoptions_inet6()
 	else
 		${SYSCTL_W} net.inet6.ip6.v6only=1 >/dev/null
 	fi
+
+	if checkyesno ipv6_privacy; then
+		netoptions_init
+		echo -n " IPv6 Privacy Addresses"
+		${SYSCTL_W} net.inet6.ip6.use_tempaddr=1 >/dev/null
+		${SYSCTL_W} net.inet6.ip6.prefer_tempaddr=1 >/dev/null
+	fi
 }
 
 load_rc_config $name
diff --git a/share/man/man5/rc.conf.5 b/share/man/man5/rc.conf.5
index 29084500088..7ad0cab0202 100644
--- a/share/man/man5/rc.conf.5
+++ b/share/man/man5/rc.conf.5
@@ -1304,6 +1304,12 @@ flag and keywords
 see
 .Xr ifconfig 8 .
 .Pp
+.It Va ipv6_privacy
+.Pq Vt bool
+If the variable is
+.Dq Li YES
+privacy addresses will be generated for each IPv6
+interface as described in RFC 4193.
 .It Va ipv6_network_interfaces
 .Pq Vt str
 This is the IPv6 equivalent of

From fa3b84643a064204b41d73c99a206f8f9c4d9775 Mon Sep 17 00:00:00 2001
From: Hiroki Sato 
Date: Mon, 13 Sep 2010 19:53:22 +0000
Subject: [PATCH 0717/1624] - Check some specific IFs first in
 ipv6_autoconfif(). - $ipv6_enable supports YES|TRUE|ON|1 as in checkyesno().

Based on:	changes in r206408 by dougb
---
 etc/network.subr | 33 +++++++++++++++------------------
 1 file changed, 15 insertions(+), 18 deletions(-)

diff --git a/etc/network.subr b/etc/network.subr
index aba8e451a3a..8737c215b9a 100644
--- a/etc/network.subr
+++ b/etc/network.subr
@@ -108,7 +108,7 @@ ifconfig_up()
 
 			# backward compatibility: $ipv6_enable
 			case $ipv6_enable in
-			[Yy][Ee][Ss])
+			[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
 				_ipv6_opts="${_ipv6_opts} accept_rtadv"
 				;;
 			esac
@@ -385,6 +385,7 @@ noafif()
 	an[0-9]*|\
 	ath[0-9]*|\
 	ipw[0-9]*|\
+	ipfw[0-9]*|\
 	iwi[0-9]*|\
 	iwn[0-9]*|\
 	ral[0-9]*|\
@@ -444,10 +445,19 @@ ipv6_autoconfif()
 	local _if _tmpargs _arg
 	_if=$1
 
-	if ! ipv6if $_if; then
+	case $_if in
+	lo0|\
+	stf[0-9]*|\
+	faith[0-9]*|\
+	lp[0-9]*|\
+	sl[0-9]*)
+		return 1
+		;;
+	esac
+	if noafif $_if; then
 		return 1
 	fi
-	if noafif $_if; then
+	if ! ipv6if $_if; then
 		return 1
 	fi
 	if checkyesno ipv6_gateway_enable; then
@@ -457,24 +467,11 @@ ipv6_autoconfif()
 	if [ -n "${_tmpargs}" ]; then
 		return 1
 	fi
-
-	case $_if in
-	lo0|\
-	stf[0-9]*|\
-	faith[0-9]*|\
-	lp[0-9]*|\
-	sl[0-9]*|\
-	pflog[0-9]*|\
-	pfsync[0-9]*)
-		return 1
-		;;
-	esac
-
 	# backward compatibility: $ipv6_enable
 	case $ipv6_enable in
-	[Yy][Ee][Ss])
+	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
 		return 0
-		;;
+	;;
 	esac
 
 	_tmpargs=`_ifconfig_getargs $_if ipv6`

From 95f15c1589eee6e4b8147e21f3cde2264b00c55a Mon Sep 17 00:00:00 2001
From: Hiroki Sato 
Date: Mon, 13 Sep 2010 19:53:54 +0000
Subject: [PATCH 0718/1624] Localize $_punct_c in get_if_var() and whitespace
 clean-ups.

Based on:	changes in r206408 by dougb
---
 etc/network.subr | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/etc/network.subr b/etc/network.subr
index 8737c215b9a..8097463d735 100644
--- a/etc/network.subr
+++ b/etc/network.subr
@@ -194,7 +194,7 @@ ifconfig_down()
 #	$default if given.
 get_if_var()
 {
-	local _if _punct _var _default prefix suffix
+	local _if _punct _punct_c _var _default prefix suffix
 
 	if [ $# -ne 2 -a $# -ne 3 ]; then
 		err 3 'USAGE: get_if_var name var [default]'
@@ -505,7 +505,7 @@ ifexists()
 }
 
 # ipv4_up if
-#	add IPv4 addresses to the interface $if 
+#	add IPv4 addresses to the interface $if
 ipv4_up()
 {
 	local _if _ret
@@ -615,14 +615,14 @@ ipv6_down()
 ipv4_addrs_common()
 {
 	local _ret _if _action _cidr _cidr_addr
-	local _ipaddr _netmask _range _ipnet _iplow _iphigh _ipcount 
+	local _ipaddr _netmask _range _ipnet _iplow _iphigh _ipcount
 	_ret=1
 	_if=$1
 	_action=$2
-    
+
 	# get ipv4-addresses
 	cidr_addr=`get_if_var $_if ipv4_addrs_IF`
-    
+
 	for _cidr in ${cidr_addr}; do
 		_ipaddr=${_cidr%%/*}
 		_netmask="/"${_cidr##*/}
@@ -635,7 +635,7 @@ ipv4_addrs_common()
 		if [ "${_action}" = "-alias" ]; then
 			_netmask=""
 		fi
-        
+
 		_ipcount=${_iplow}
 		while [ "${_ipcount}" -le "${_iphigh}" ]; do
 			eval "ifconfig ${_if} ${_action} ${_ipnet}.${_ipcount}${_netmask}"

From d3a8a8b9fa8d418ef26b4101b6bacd77b4e647dd Mon Sep 17 00:00:00 2001
From: Hiroki Sato 
Date: Mon, 13 Sep 2010 19:55:40 +0000
Subject: [PATCH 0719/1624] Split $ipv6_prefer into $ip6addrctl_policy and
 $ipv6_activate_all_interfaces.

The $ip6addrctl_policy is a variable to choose a pre-defined address
selection policy set by ip6addrctl(8).
The keyword "ipv4_prefer" sets IPv4-preferred one described in Section 10.3,
the keyword "ipv6_prefer" sets IPv6-preferred one in Section 2.1 in RFC 3484,
respectively.  When "AUTO" is specified, it attempts to read
/etc/ip6addrctl.conf first.  If it is found, it reads and installs it as
a policy table.  If not, either of the two pre-defined policy tables is
chosen automatically according to $ipv6_activate_all_interfaces.

When $ipv6_activate_all_interfaces=NO, interfaces which have no corresponding
$ifconfig_IF_ipv6 is marked as IFDISABLED for security reason.

The default values are ip6addrctl_policy=AUTO and
ipv6_activate_all_interfaces=NO.

Discussed with:	ume and bz
---
 UPDATING                 | 19 +++++++++
 etc/defaults/rc.conf     |  7 +++-
 etc/network.subr         |  2 +-
 etc/rc.d/ip6addrctl      | 45 +++++++++++++++-----
 etc/rc.d/netif           |  3 +-
 share/man/man5/rc.conf.5 | 90 +++++++++++++++++++++++++++++-----------
 6 files changed, 128 insertions(+), 38 deletions(-)

diff --git a/UPDATING b/UPDATING
index f4a8fed2aaf..7a17089717f 100644
--- a/UPDATING
+++ b/UPDATING
@@ -22,6 +22,25 @@ NOTE TO PEOPLE WHO THINK THAT FreeBSD 9.x IS SLOW:
 	machines to maximize performance.  (To disable malloc debugging, run
 	ln -s aj /etc/malloc.conf.)
 
+20100913:
+	The $ipv6_prefer variable in rc.conf(5) has been split into
+	$ip6addrctl_policy and $ipv6_activate_all_interfaces.
+
+	The $ip6addrctl_policy is a variable to choose a pre-defined
+	address selection policy set by ip6addrctl(8).  A value
+	"ipv4_prefer", "ipv6_prefer" or "AUTO" can be specified.  The
+	default is "AUTO".
+
+	The $ipv6_activate_all_interfaces specifies whether IFDISABLED
+	flag (see an entry of 20090926) is set on an interface with no
+	corresponding $ifconfig_IF_ipv6 line.  The default is "NO" for
+	security reason.  If you want IPv6 link-local address on all
+	interfaces by default, set this to "YES".
+
+	The old ipv6_prefer="YES" is equivalent to
+	ipv6_activate_all_interfaces="YES" and
+	ip6addrctl_policy="ipv6_prefer".
+
 20100913:
 	DTrace has grown support for userland tracing. Due to this, DTrace is
 	now i386 and amd64 only.
diff --git a/etc/defaults/rc.conf b/etc/defaults/rc.conf
index b041f15f332..10213fe2519 100644
--- a/etc/defaults/rc.conf
+++ b/etc/defaults/rc.conf
@@ -446,6 +446,10 @@ icmp_bmcastecho="NO"	# respond to broadcast ping packets
 ### IPv6 options: ###
 ipv6_network_interfaces="auto"	# List of IPv6 network interfaces
 				# (or "auto" or "none").
+ipv6_activate_all_interfaces="NO"	# If NO, interfaces which have no
+					# corresponding $ifconfig_IF_ipv6 is
+					# marked as IFDISABLED for security
+					# reason.
 ipv6_defaultrouter="NO"		# Set to IPv6 default gateway (or NO).
 #ipv6_defaultrouter="2002:c058:6301::"	# Use this for 6to4 (RFC 3068)
 ipv6_static_routes=""		# Set to static route list (or leave empty).
@@ -506,7 +510,8 @@ ipv6_ipfilter_rules="/etc/ipf6.rules"	# rules definition file for ipfilter,
 					# for examples
 ip6addrctl_enable="YES"	# Set to YES to enable default address selection
 ip6addrctl_verbose="NO"	# Set to YES to enable verbose configuration messages
-ipv6_prefer="NO"	# Use IPv6 when both IPv4 and IPv6 can be used
+ip6addrctl_policy="AUTO"	# A pre-defined address selection policy
+				# (ipv4_prefer, ipv6_prefer, or AUTO)
 
 ##############################################################
 ###  System console options  #################################
diff --git a/etc/network.subr b/etc/network.subr
index 8097463d735..afd568cbfb5 100644
--- a/etc/network.subr
+++ b/etc/network.subr
@@ -100,7 +100,7 @@ ifconfig_up()
 				_ipv6_opts="-accept_rtadv"
 			fi
 		else
-			if checkyesno ipv6_prefer; then
+			if checkyesno ipv6_activate_all_interfaces; then
 				_ipv6_opts="-ifdisabled"
 			else
 				_ipv6_opts="ifdisabled"
diff --git a/etc/rc.d/ip6addrctl b/etc/rc.d/ip6addrctl
index d3b18561795..d38018c4cdd 100755
--- a/etc/rc.d/ip6addrctl
+++ b/etc/rc.d/ip6addrctl
@@ -19,8 +19,10 @@ extra_commands="status prefer_ipv6 prefer_ipv4"
 status_cmd="ip6addrctl"
 prefer_ipv6_cmd="ip6addrctl_prefer_ipv6"
 prefer_ipv4_cmd="ip6addrctl_prefer_ipv4"
+config_file="/etc/ip6addrctl.conf"
 
-set_rcvar_obsolete ipv6_enable ipv6_prefer
+set_rcvar_obsolete ipv6_enable ipv6_activate_all_interfaces
+set_rcvar_obsolete ipv6_prefer ip6addrctl_policy
 
 ip6addrctl_prefer_ipv6()
 {
@@ -53,17 +55,40 @@ ip6addrctl_start()
 	afexists inet6 || return 0
 
 	# install the policy of the address selection algorithm.
-	if [ -f /etc/ip6addrctl.conf ]; then
-		ip6addrctl flush >/dev/null 2>&1
-		ip6addrctl install /etc/ip6addrctl.conf
-		checkyesno ip6addrctl_verbose && ip6addrctl
-	else
-		if checkyesno ipv6_prefer; then
-			ip6addrctl_prefer_ipv6
+	case "${ip6addrctl_policy}" in
+	[Aa][Uu][Tt][Oo])
+		if [ -r "${config_file}" -a -s "${config_file}" ]; then
+			ip6addrctl flush >/dev/null 2>&1
+			ip6addrctl install "${config_file}"
+			checkyesno ip6addrctl_verbose && ip6addrctl
 		else
-			ip6addrctl_prefer_ipv4
+			if checkyesno ipv6_activate_all_interfaces; then
+				ip6addrctl_prefer_ipv6
+			else
+				ip6addrctl_prefer_ipv4
+			fi
 		fi
-	fi
+	;;
+	ipv4_prefer)
+		ip6addrctl_prefer_ipv4
+	;;
+	ipv6_prefer)
+		ip6addrctl_prefer_ipv6
+	;;
+	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
+		# Backward compatibility when ipv6_prefer=YES
+		ip6addrctl_prefer_ipv6
+	;;
+	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
+		# Backward compatibility when ipv6_prefer=NO
+		ip6addrctl_prefer_ipv4
+	;;
+	*)
+		warn "\$ip6addrctl_policy is invalid: ${ip6addrctl_policy}. " \
+		    " \"ipv4_prefer\" is used instead."
+		ip6addrctl_prefer_ipv4
+	;;
+	esac
 }
 
 ip6addrctl_stop()
diff --git a/etc/rc.d/netif b/etc/rc.d/netif
index f982cfce647..01da302c5df 100755
--- a/etc/rc.d/netif
+++ b/etc/rc.d/netif
@@ -41,7 +41,8 @@ clonedown_cmd="clone_down"
 extra_commands="cloneup clonedown"
 cmdifn=
 
-set_rcvar_obsolete ipv6_enable ipv6_prefer
+set_rcvar_obsolete ipv6_enable ipv6_activate_all_interfaces
+set_rcvar_obsolete ipv6_prefer
 
 network_start()
 {
diff --git a/share/man/man5/rc.conf.5 b/share/man/man5/rc.conf.5
index 7ad0cab0202..a884bfff1f4 100644
--- a/share/man/man5/rc.conf.5
+++ b/share/man/man5/rc.conf.5
@@ -1269,41 +1269,49 @@ If the variable is
 is added to all of
 .Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
 and the
-.Va ipv6_prefer
+.Va ipv6_activate_all_interfaces
 is defined as
 .Dq Li YES .
 .Pp
 This variable is deprecated.  Use
-.Va ipv6_prefer
+.Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
 and
-.Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6 .
+.Va ipv6_activate_all_interfaces
+if necessary.
 .It Va ipv6_prefer
 .Pq Vt bool
-This variable does the following:
-.Pp
 If the variable is
 .Dq Li YES ,
-the default policy of the source address selection set by
+the default address selection policy table set by
 .Xr ip6addrctl 8
 will be IPv6-preferred.
 .Pp
 If the variable is
 .Dq Li NO ,
-the default policy of the source address selection set by
+the default address selection policy table set by
 .Xr ip6addrctl 8
-will be IPv4-preferred, and all of interfaces which does not have the
-corrsponding
+will be IPv4-preferred.
+.Pp
+This variable is deprecated.  Use
+.Va ip6addtctl_policy
+instead.
+.It Va ipv6_activate_all_interfaces
+If the variable is
+.Dq Li NO ,
+all of interfaces which do not have the corrsponding
 .Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
 variable will be marked as
-.Dq Li IFDISABLED .
-This means only IPv6 functionality on that interface is completely
-disabled.  For more details of
+.Dq Li IFDISABLED
+for security reason.  This means only IPv6 functionality on that interface
+is completely disabled.  For more details of
 .Dq Li IFDISABLED
 flag and keywords
 .Dq Li inet6 ifdisabled ,
 see
 .Xr ifconfig 8 .
 .Pp
+Default is
+.Dq Li NO .
 .It Va ipv6_privacy
 .Pq Vt bool
 If the variable is
@@ -1316,6 +1324,8 @@ This is the IPv6 equivalent of
 .Va network_interfaces .
 Normally manual configuration of this variable is not needed.
 .Pp
+.It Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6
+.Pq Vt str
 IPv6 functionality on an interface should be configured by
 .Va ifconfig_ Ns Ao Ar interface Ac Ns _ipv6 ,
 instead of setting ifconfig parameters in
@@ -1354,22 +1364,52 @@ this is the default output interface for scoped addresses.
 This works only with ipv6_gateway_enable="NO".
 .It Va ip6addrctl_enable
 .Pq Vt bool
-If set to
-.Dq Li YES ,
-install default address selection policy table
+This variable is to enable configuring default address selection policy table
 .Pq RFC 3484 .
-If a file
-.Pa /etc/ip6addrctl.conf
-is found the
+The table can be specified in another variable
+.Va ip6addrctl_policy .
+For
+.Va ip6addrctl_policy
+the following keywords can be specified:
+.Dq Li ipv4_prefer ,
+.Dq Li ipv6_prefer ,
+or
+.Dq Li AUTO .
+.Pp
+If
+.Dq Li ipv4_prefer
+or
+.Dq Li ipv6_prefer
+is specified,
 .Xr ip6addrctl 8
-reads and installs it.
-If not, a pre-defined policy table will be installed.
-There are two pre-defined ones; IPv4-preferred and IPv6-preferred.
-If set
-.Va ipv6_prefer
-variable to
+installs a pre-defined policy table described in Section 2.1
+.Pq IPv6-preferred
+or 10.3
+.Pq IPv4-preferred
+of RFC 3484.
+.Pp
+If
+.Dq Li AUTO
+is specified, it attempts to read a file
+.Pa /etc/ip6addrctl.conf
+first.  If this file is found,
+.Xr ip6addrctl 8
+reads and installs it.  If not found, a policy is automatically set
+according to
+.Va ipv6_activate_all_interfaces
+variable; if the variable is set to
 .Dq Li YES
-the IPv6-preferred one is used. Default is IPv4-preferred.
+the IPv6-preferred one is used.  Otherwise IPv4-preferred.
+.Pp
+The default value of
+.Va ip6addrctl_enable
+and
+.Va ip6addrctl_policy
+are
+.Dq Li YES
+and
+.Dq Li AUTO ,
+respectively.
 .It Va cloned_interfaces
 .Pq Vt str
 Set to the list of clonable network interfaces to create on this host.

From f6ff063a6efa260d0e0ec2bd2de18616483910a2 Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Mon, 13 Sep 2010 19:58:46 +0000
Subject: [PATCH 0720/1624] Fix segment:offset calculation of interrupt vector
 for relocated video BIOS when the original offset is bigger than size of one
 page.  X86BIOS macros cannot be used here because it is assumed address is
 only linear in a page.

Tested by:	netchild
---
 sys/dev/fb/vesa.c | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/sys/dev/fb/vesa.c b/sys/dev/fb/vesa.c
index 4cb3fb5895e..0c05699ff97 100644
--- a/sys/dev/fb/vesa.c
+++ b/sys/dev/fb/vesa.c
@@ -804,18 +804,16 @@ vesa_bios_init(void)
 		vbios = x86bios_get_orm(vesa_bios_offs);
 		if (vbios != NULL) {
 			vesa_bios_size = vbios[2] * 512;
-			offs = BIOS_SADDRTOLADDR(vesa_bios_int10);
-			if (offs > vesa_bios_offs &&
-			    offs < vesa_bios_offs + vesa_bios_size) {
+			if (((VESA_BIOS_OFFSET << 12) & 0xffff0000) ==
+			    (vesa_bios_int10 & 0xffff0000) &&
+			    vesa_bios_size > (vesa_bios_int10 & 0xffff)) {
 				vesa_bios = x86bios_alloc(&vesa_bios_offs,
 				    vesa_bios_size, M_WAITOK);
 				memcpy(vesa_bios, vbios, vesa_bios_size);
-				offs = offs - VESA_BIOS_OFFSET + vesa_bios_offs;
-				offs = (X86BIOS_PHYSTOSEG(offs) << 16) +
-				    X86BIOS_PHYSTOOFF(offs);
+				offs = ((vesa_bios_offs << 12) & 0xffff0000) +
+				    (vesa_bios_int10 & 0xffff);
 				x86bios_set_intr(0x10, offs);
-			} else
-				offs = vesa_bios_int10;
+			}
 		}
 		if (vesa_bios == NULL)
 			printf("VESA: failed to shadow video ROM\n");

From 07ae21bae9d38e0c27ebde828bf6afa4761a9511 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Mon, 13 Sep 2010 22:50:05 +0000
Subject: [PATCH 0721/1624] Fix a missing set of parantheses that could cause
 recent versions of libthr to crash deferencing a NULL pointer to the user
 context on powerpc64 systems with COMPAT_FREEBSD32 defined.

---
 sys/powerpc/powerpc/exec_machdep.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/powerpc/powerpc/exec_machdep.c b/sys/powerpc/powerpc/exec_machdep.c
index 2ca646f005b..a4e397db901 100644
--- a/sys/powerpc/powerpc/exec_machdep.c
+++ b/sys/powerpc/powerpc/exec_machdep.c
@@ -251,9 +251,9 @@ sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
 	tf->fixreg[FIRSTARG] = sig;
 	#ifdef COMPAT_FREEBSD32
 	tf->fixreg[FIRSTARG+2] = (register_t)usfp +
-	    (p->p_sysent->sv_flags & SV_ILP32) ?
+	    ((p->p_sysent->sv_flags & SV_ILP32) ?
 	    offsetof(struct sigframe32, sf_uc) :
-	    offsetof(struct sigframe, sf_uc);
+	    offsetof(struct sigframe, sf_uc));
 	#else
 	tf->fixreg[FIRSTARG+2] = (register_t)usfp +
 	    offsetof(struct sigframe, sf_uc);

From b503d5c50ea1594863626b8fb6f29522573db49d Mon Sep 17 00:00:00 2001
From: Neel Natu 
Date: Tue, 14 Sep 2010 01:27:53 +0000
Subject: [PATCH 0722/1624] Enforce that pmap_mapdev() always returns
 uncacheable mappings.

Reviewed by:	imp, jchandra, jmallett
---
 sys/mips/mips/pmap.c | 26 +++++++++++++++++---------
 1 file changed, 17 insertions(+), 9 deletions(-)

diff --git a/sys/mips/mips/pmap.c b/sys/mips/mips/pmap.c
index 89332d3168c..6d212f7513d 100644
--- a/sys/mips/mips/pmap.c
+++ b/sys/mips/mips/pmap.c
@@ -828,8 +828,8 @@ retry:
 /*
  * add a wired page to the kva
  */
- /* PMAP_INLINE */ void
-pmap_kenter(vm_offset_t va, vm_paddr_t pa)
+static void
+pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int attr)
 {
 	pt_entry_t *pte;
 	pt_entry_t opte, npte;
@@ -837,12 +837,7 @@ pmap_kenter(vm_offset_t va, vm_paddr_t pa)
 #ifdef PMAP_DEBUG
 	printf("pmap_kenter:  va: %p -> pa: %p\n", (void *)va, (void *)pa);
 #endif
-	npte = TLBLO_PA_TO_PFN(pa) | PTE_D | PTE_V | PTE_G | PTE_W;
-
-	if (is_cacheable_mem(pa))
-		npte |= PTE_C_CACHE;
-	else
-		npte |= PTE_C_UNCACHED;
+	npte = TLBLO_PA_TO_PFN(pa) | PTE_D | PTE_V | PTE_G | PTE_W | attr;
 
 	pte = pmap_pte(kernel_pmap, va);
 	opte = *pte;
@@ -851,6 +846,19 @@ pmap_kenter(vm_offset_t va, vm_paddr_t pa)
 		pmap_update_page(kernel_pmap, va, npte);
 }
 
+void
+pmap_kenter(vm_offset_t va, vm_paddr_t pa)
+{
+	int attr;
+
+	if (is_cacheable_mem(pa))
+		attr = PTE_C_CACHE;
+	else
+		attr = PTE_C_UNCACHED;
+
+	pmap_kenter_attr(va, pa, attr);
+}
+
 /*
  * remove a page from the kernel pagetables
  */
@@ -2863,7 +2871,7 @@ pmap_mapdev(vm_offset_t pa, vm_size_t size)
 			panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
 		pa = trunc_page(pa);
 		for (tmpva = va; size > 0;) {
-			pmap_kenter(tmpva, pa);
+			pmap_kenter_attr(tmpva, pa, PTE_C_UNCACHED);
 			size -= PAGE_SIZE;
 			tmpva += PAGE_SIZE;
 			pa += PAGE_SIZE;

From b3f4d7e17c51c07a51fc0b6733007c44bb0475e2 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Tue, 14 Sep 2010 01:33:21 +0000
Subject: [PATCH 0723/1624] Remove extra ;

---
 usr.bin/calendar/parsedata.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/usr.bin/calendar/parsedata.c b/usr.bin/calendar/parsedata.c
index 51834390d5a..55997337514 100644
--- a/usr.bin/calendar/parsedata.c
+++ b/usr.bin/calendar/parsedata.c
@@ -971,7 +971,7 @@ floattoday(int year, double f)
 	int *cumdays = cumdaytab[isleap(year)];
 
 	for (i = 0; 1 + cumdays[i] < f; i++)
-		;;
+		;
 	m = --i;
 	d = floor(f - 1 - cumdays[i]);
 	f -= floor(f);

From 8744fd1ce1b68c78c14f07cc49bd6d89366b78ed Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Tue, 14 Sep 2010 01:40:59 +0000
Subject: [PATCH 0724/1624] Remove libf2c.  It hasn't been used for more than
 11 years, since revision 1.90 (CVS; SVN r45770) of lib/Makefile.

---
 contrib/libf2c/ChangeLog              | 2467 --------------------
 contrib/libf2c/FREEBSD-upgrade        |   22 -
 contrib/libf2c/Makefile.in            |  276 ---
 contrib/libf2c/README                 |  109 -
 contrib/libf2c/TODO                   |   14 -
 contrib/libf2c/aclocal.m4             |  236 --
 contrib/libf2c/changes.netlib         | 3026 -------------------------
 contrib/libf2c/configure              | 2939 ------------------------
 contrib/libf2c/configure.in           |  121 -
 contrib/libf2c/disclaimer.netlib      |   15 -
 contrib/libf2c/f2c.h                  |   64 -
 contrib/libf2c/f2cext.c               |  582 -----
 contrib/libf2c/g2c.hin                |  234 --
 contrib/libf2c/libF77/F77_aloc.c      |   24 -
 contrib/libf2c/libF77/Makefile.in     |  255 ---
 contrib/libf2c/libF77/Notice          |   23 -
 contrib/libf2c/libF77/README.netlib   |  112 -
 contrib/libf2c/libF77/Version.c       |   94 -
 contrib/libf2c/libF77/abort_.c        |   11 -
 contrib/libf2c/libF77/c_abs.c         |    9 -
 contrib/libf2c/libF77/c_cos.c         |   12 -
 contrib/libf2c/libF77/c_div.c         |   43 -
 contrib/libf2c/libF77/c_exp.c         |   14 -
 contrib/libf2c/libF77/c_log.c         |   13 -
 contrib/libf2c/libF77/c_sin.c         |   12 -
 contrib/libf2c/libF77/c_sqrt.c        |   30 -
 contrib/libf2c/libF77/cabs.c          |   24 -
 contrib/libf2c/libF77/configure       | 1568 -------------
 contrib/libf2c/libF77/configure.in    |  111 -
 contrib/libf2c/libF77/d_abs.c         |    9 -
 contrib/libf2c/libF77/d_acos.c        |    9 -
 contrib/libf2c/libF77/d_asin.c        |    9 -
 contrib/libf2c/libF77/d_atan.c        |    9 -
 contrib/libf2c/libF77/d_atn2.c        |    9 -
 contrib/libf2c/libF77/d_cnjg.c        |    9 -
 contrib/libf2c/libF77/d_cos.c         |    9 -
 contrib/libf2c/libF77/d_cosh.c        |    9 -
 contrib/libf2c/libF77/d_dim.c         |    7 -
 contrib/libf2c/libF77/d_exp.c         |    9 -
 contrib/libf2c/libF77/d_imag.c        |    7 -
 contrib/libf2c/libF77/d_int.c         |    9 -
 contrib/libf2c/libF77/d_lg10.c        |   11 -
 contrib/libf2c/libF77/d_log.c         |    9 -
 contrib/libf2c/libF77/d_mod.c         |   33 -
 contrib/libf2c/libF77/d_nint.c        |    9 -
 contrib/libf2c/libF77/d_prod.c        |    7 -
 contrib/libf2c/libF77/d_sign.c        |    9 -
 contrib/libf2c/libF77/d_sin.c         |    9 -
 contrib/libf2c/libF77/d_sinh.c        |    9 -
 contrib/libf2c/libF77/d_sqrt.c        |    9 -
 contrib/libf2c/libF77/d_tan.c         |    9 -
 contrib/libf2c/libF77/d_tanh.c        |    9 -
 contrib/libf2c/libF77/derf_.c         |    8 -
 contrib/libf2c/libF77/derfc_.c        |    9 -
 contrib/libf2c/libF77/dtime_.c        |   49 -
 contrib/libf2c/libF77/ef1asc_.c       |   15 -
 contrib/libf2c/libF77/ef1cmc_.c       |   10 -
 contrib/libf2c/libF77/erf_.c          |    8 -
 contrib/libf2c/libF77/erfc_.c         |    8 -
 contrib/libf2c/libF77/etime_.c        |   43 -
 contrib/libf2c/libF77/exit_.c         |   25 -
 contrib/libf2c/libF77/f2ch.add        |  163 --
 contrib/libf2c/libF77/getarg_.c       |   25 -
 contrib/libf2c/libF77/getenv_.c       |   49 -
 contrib/libf2c/libF77/h_abs.c         |    9 -
 contrib/libf2c/libF77/h_dim.c         |    7 -
 contrib/libf2c/libF77/h_dnnt.c        |    9 -
 contrib/libf2c/libF77/h_indx.c        |   23 -
 contrib/libf2c/libF77/h_len.c         |    7 -
 contrib/libf2c/libF77/h_mod.c         |    7 -
 contrib/libf2c/libF77/h_nint.c        |    9 -
 contrib/libf2c/libF77/h_sign.c        |    9 -
 contrib/libf2c/libF77/hl_ge.c         |    8 -
 contrib/libf2c/libF77/hl_gt.c         |    8 -
 contrib/libf2c/libF77/hl_le.c         |    8 -
 contrib/libf2c/libF77/hl_lt.c         |    8 -
 contrib/libf2c/libF77/i_abs.c         |    9 -
 contrib/libf2c/libF77/i_dim.c         |    7 -
 contrib/libf2c/libF77/i_dnnt.c        |    9 -
 contrib/libf2c/libF77/i_indx.c        |   23 -
 contrib/libf2c/libF77/i_len.c         |    7 -
 contrib/libf2c/libF77/i_mod.c         |    7 -
 contrib/libf2c/libF77/i_nint.c        |    9 -
 contrib/libf2c/libF77/i_sign.c        |    9 -
 contrib/libf2c/libF77/iargc_.c        |    8 -
 contrib/libf2c/libF77/l_ge.c          |    8 -
 contrib/libf2c/libF77/l_gt.c          |    8 -
 contrib/libf2c/libF77/l_le.c          |    8 -
 contrib/libf2c/libF77/l_lt.c          |    8 -
 contrib/libf2c/libF77/lbitbits.c      |   58 -
 contrib/libf2c/libF77/lbitshft.c      |    7 -
 contrib/libf2c/libF77/main.c          |   35 -
 contrib/libf2c/libF77/makefile.netlib |  103 -
 contrib/libf2c/libF77/pow_ci.c        |   16 -
 contrib/libf2c/libF77/pow_dd.c        |    9 -
 contrib/libf2c/libF77/pow_di.c        |   32 -
 contrib/libf2c/libF77/pow_hh.c        |   31 -
 contrib/libf2c/libF77/pow_ii.c        |   31 -
 contrib/libf2c/libF77/pow_qq.c        |   31 -
 contrib/libf2c/libF77/pow_ri.c        |   32 -
 contrib/libf2c/libF77/pow_zi.c        |   50 -
 contrib/libf2c/libF77/pow_zz.c        |   25 -
 contrib/libf2c/libF77/qbitbits.c      |   62 -
 contrib/libf2c/libF77/qbitshft.c      |    7 -
 contrib/libf2c/libF77/r_abs.c         |    9 -
 contrib/libf2c/libF77/r_acos.c        |    9 -
 contrib/libf2c/libF77/r_asin.c        |    9 -
 contrib/libf2c/libF77/r_atan.c        |    9 -
 contrib/libf2c/libF77/r_atn2.c        |    9 -
 contrib/libf2c/libF77/r_cnjg.c        |    9 -
 contrib/libf2c/libF77/r_cos.c         |    9 -
 contrib/libf2c/libF77/r_cosh.c        |    9 -
 contrib/libf2c/libF77/r_dim.c         |    7 -
 contrib/libf2c/libF77/r_exp.c         |    9 -
 contrib/libf2c/libF77/r_imag.c        |    7 -
 contrib/libf2c/libF77/r_int.c         |    9 -
 contrib/libf2c/libF77/r_lg10.c        |   11 -
 contrib/libf2c/libF77/r_log.c         |    9 -
 contrib/libf2c/libF77/r_mod.c         |   33 -
 contrib/libf2c/libF77/r_nint.c        |    9 -
 contrib/libf2c/libF77/r_sign.c        |    9 -
 contrib/libf2c/libF77/r_sin.c         |    9 -
 contrib/libf2c/libF77/r_sinh.c        |    9 -
 contrib/libf2c/libF77/r_sqrt.c        |    9 -
 contrib/libf2c/libF77/r_tan.c         |    9 -
 contrib/libf2c/libF77/r_tanh.c        |    9 -
 contrib/libf2c/libF77/s_cat.c         |   70 -
 contrib/libf2c/libF77/s_cmp.c         |   49 -
 contrib/libf2c/libF77/s_copy.c        |   50 -
 contrib/libf2c/libF77/s_paus.c        |   71 -
 contrib/libf2c/libF77/s_rnge.c        |   22 -
 contrib/libf2c/libF77/s_stop.c        |   32 -
 contrib/libf2c/libF77/setarg.c        |   14 -
 contrib/libf2c/libF77/setsig.c        |   86 -
 contrib/libf2c/libF77/sig_die.c       |   37 -
 contrib/libf2c/libF77/signal1.h       |    5 -
 contrib/libf2c/libF77/signal1.h0      |   26 -
 contrib/libf2c/libF77/signal_.c       |   11 -
 contrib/libf2c/libF77/system_.c       |   28 -
 contrib/libf2c/libF77/z_abs.c         |    8 -
 contrib/libf2c/libF77/z_cos.c         |   11 -
 contrib/libf2c/libF77/z_div.c         |   41 -
 contrib/libf2c/libF77/z_exp.c         |   13 -
 contrib/libf2c/libF77/z_log.c         |   59 -
 contrib/libf2c/libF77/z_sin.c         |   11 -
 contrib/libf2c/libF77/z_sqrt.c        |   25 -
 contrib/libf2c/libI77/Makefile.in     |  169 --
 contrib/libf2c/libI77/Notice          |   23 -
 contrib/libf2c/libI77/README.netlib   |  225 --
 contrib/libf2c/libI77/Version.c       |  324 ---
 contrib/libf2c/libI77/backspace.c     |   81 -
 contrib/libf2c/libI77/close.c         |  101 -
 contrib/libf2c/libI77/config.h.in     |   62 -
 contrib/libf2c/libI77/configure       | 2123 -----------------
 contrib/libf2c/libI77/configure.in    |  222 --
 contrib/libf2c/libI77/dfe.c           |  156 --
 contrib/libf2c/libI77/dolio.c         |   10 -
 contrib/libf2c/libI77/due.c           |   80 -
 contrib/libf2c/libI77/endfile.c       |  130 --
 contrib/libf2c/libI77/err.c           |  285 ---
 contrib/libf2c/libI77/f2ch.add        |  163 --
 contrib/libf2c/libI77/fio.h           |  104 -
 contrib/libf2c/libI77/fmt.c           |  602 -----
 contrib/libf2c/libI77/fmt.h           |   92 -
 contrib/libf2c/libI77/fmtlib.c        |   46 -
 contrib/libf2c/libI77/fp.h            |   28 -
 contrib/libf2c/libI77/ftell_.c        |   35 -
 contrib/libf2c/libI77/iio.c           |  157 --
 contrib/libf2c/libI77/ilnw.c          |   70 -
 contrib/libf2c/libI77/inquire.c       |  143 --
 contrib/libf2c/libI77/lio.h           |   64 -
 contrib/libf2c/libI77/lread.c         |  845 -------
 contrib/libf2c/libI77/lwrite.c        |  277 ---
 contrib/libf2c/libI77/makefile.netlib |  104 -
 contrib/libf2c/libI77/open.c          |  301 ---
 contrib/libf2c/libI77/rdfmt.c         |  615 -----
 contrib/libf2c/libI77/rewind.c        |   25 -
 contrib/libf2c/libI77/rsfe.c          |   97 -
 contrib/libf2c/libI77/rsli.c          |   99 -
 contrib/libf2c/libI77/rsne.c          |  604 -----
 contrib/libf2c/libI77/sfe.c           |   44 -
 contrib/libf2c/libI77/stamp-h.in      |    1 -
 contrib/libf2c/libI77/sue.c           |   93 -
 contrib/libf2c/libI77/typesize.c      |   14 -
 contrib/libf2c/libI77/uio.c           |   60 -
 contrib/libf2c/libI77/util.c          |   52 -
 contrib/libf2c/libI77/wref.c          |  306 ---
 contrib/libf2c/libI77/wrtfmt.c        |  407 ----
 contrib/libf2c/libI77/wsfe.c          |   79 -
 contrib/libf2c/libI77/wsle.c          |   38 -
 contrib/libf2c/libI77/wsne.c          |   22 -
 contrib/libf2c/libI77/xwsne.c         |   71 -
 contrib/libf2c/libU77/COPYING.LIB     |  504 ----
 contrib/libf2c/libU77/Makefile.in     |  187 --
 contrib/libf2c/libU77/PROJECTS        |   10 -
 contrib/libf2c/libU77/README          |   40 -
 contrib/libf2c/libU77/Version.c       |    1 -
 contrib/libf2c/libU77/access_.c       |   84 -
 contrib/libf2c/libU77/acconfig.h      |   11 -
 contrib/libf2c/libU77/aclocal.m4      |   69 -
 contrib/libf2c/libU77/alarm_.c        |   57 -
 contrib/libf2c/libU77/chdir_.c        |   50 -
 contrib/libf2c/libU77/chmod_.c        |   82 -
 contrib/libf2c/libU77/config.hin      |  128 --
 contrib/libf2c/libU77/configure       | 2066 -----------------
 contrib/libf2c/libU77/configure.in    |  124 -
 contrib/libf2c/libU77/ctime_.c        |   51 -
 contrib/libf2c/libU77/date_.c         |   56 -
 contrib/libf2c/libU77/datetime_.c     |  109 -
 contrib/libf2c/libU77/dtime_.c        |  174 --
 contrib/libf2c/libU77/etime_.c        |  163 --
 contrib/libf2c/libU77/fdate_.c        |   55 -
 contrib/libf2c/libU77/fgetc_.c        |   63 -
 contrib/libf2c/libU77/flush1_.c       |   40 -
 contrib/libf2c/libU77/fnum_.c         |   38 -
 contrib/libf2c/libU77/fputc_.c        |   56 -
 contrib/libf2c/libU77/fstat_.c        |   66 -
 contrib/libf2c/libU77/gerror_.c       |   44 -
 contrib/libf2c/libU77/getcwd_.c       |   88 -
 contrib/libf2c/libU77/getgid_.c       |   38 -
 contrib/libf2c/libU77/getlog_.c       |   69 -
 contrib/libf2c/libU77/getpid_.c       |   32 -
 contrib/libf2c/libU77/getuid_.c       |   38 -
 contrib/libf2c/libU77/gmtime_.c       |   52 -
 contrib/libf2c/libU77/hostnm_.c       |   51 -
 contrib/libf2c/libU77/idate_.c        |   54 -
 contrib/libf2c/libU77/ierrno_.c       |   29 -
 contrib/libf2c/libU77/irand_.c        |   48 -
 contrib/libf2c/libU77/isatty_.c       |   39 -
 contrib/libf2c/libU77/itime_.c        |   48 -
 contrib/libf2c/libU77/kill_.c         |   38 -
 contrib/libf2c/libU77/link_.c         |   63 -
 contrib/libf2c/libU77/lnblnk_.c       |   38 -
 contrib/libf2c/libU77/lstat_.c        |   78 -
 contrib/libf2c/libU77/ltime_.c        |   52 -
 contrib/libf2c/libU77/mclock_.c       |   44 -
 contrib/libf2c/libU77/perror_.c       |   44 -
 contrib/libf2c/libU77/rand_.c         |   51 -
 contrib/libf2c/libU77/rename_.c       |   53 -
 contrib/libf2c/libU77/secnds_.c       |   51 -
 contrib/libf2c/libU77/second_.c       |   28 -
 contrib/libf2c/libU77/sleep_.c        |   33 -
 contrib/libf2c/libU77/srand_.c        |   33 -
 contrib/libf2c/libU77/stamp-h.in      |    1 -
 contrib/libf2c/libU77/stat_.c         |   71 -
 contrib/libf2c/libU77/symlnk_.c       |   61 -
 contrib/libf2c/libU77/sys_clock_.c    |   79 -
 contrib/libf2c/libU77/time_.c         |   43 -
 contrib/libf2c/libU77/ttynam_.c       |   61 -
 contrib/libf2c/libU77/u77-test.f      |  415 ----
 contrib/libf2c/libU77/umask_.c        |   30 -
 contrib/libf2c/libU77/unlink_.c       |   51 -
 contrib/libf2c/libU77/vxtidate_.c     |   65 -
 contrib/libf2c/libU77/vxttime_.c      |   51 -
 contrib/libf2c/permission.netlib      |   23 -
 contrib/libf2c/readme.netlib          |  791 -------
 256 files changed, 31660 deletions(-)
 delete mode 100644 contrib/libf2c/ChangeLog
 delete mode 100644 contrib/libf2c/FREEBSD-upgrade
 delete mode 100644 contrib/libf2c/Makefile.in
 delete mode 100644 contrib/libf2c/README
 delete mode 100644 contrib/libf2c/TODO
 delete mode 100644 contrib/libf2c/aclocal.m4
 delete mode 100644 contrib/libf2c/changes.netlib
 delete mode 100755 contrib/libf2c/configure
 delete mode 100644 contrib/libf2c/configure.in
 delete mode 100644 contrib/libf2c/disclaimer.netlib
 delete mode 100644 contrib/libf2c/f2c.h
 delete mode 100644 contrib/libf2c/f2cext.c
 delete mode 100644 contrib/libf2c/g2c.hin
 delete mode 100644 contrib/libf2c/libF77/F77_aloc.c
 delete mode 100644 contrib/libf2c/libF77/Makefile.in
 delete mode 100644 contrib/libf2c/libF77/Notice
 delete mode 100644 contrib/libf2c/libF77/README.netlib
 delete mode 100644 contrib/libf2c/libF77/Version.c
 delete mode 100644 contrib/libf2c/libF77/abort_.c
 delete mode 100644 contrib/libf2c/libF77/c_abs.c
 delete mode 100644 contrib/libf2c/libF77/c_cos.c
 delete mode 100644 contrib/libf2c/libF77/c_div.c
 delete mode 100644 contrib/libf2c/libF77/c_exp.c
 delete mode 100644 contrib/libf2c/libF77/c_log.c
 delete mode 100644 contrib/libf2c/libF77/c_sin.c
 delete mode 100644 contrib/libf2c/libF77/c_sqrt.c
 delete mode 100644 contrib/libf2c/libF77/cabs.c
 delete mode 100755 contrib/libf2c/libF77/configure
 delete mode 100644 contrib/libf2c/libF77/configure.in
 delete mode 100644 contrib/libf2c/libF77/d_abs.c
 delete mode 100644 contrib/libf2c/libF77/d_acos.c
 delete mode 100644 contrib/libf2c/libF77/d_asin.c
 delete mode 100644 contrib/libf2c/libF77/d_atan.c
 delete mode 100644 contrib/libf2c/libF77/d_atn2.c
 delete mode 100644 contrib/libf2c/libF77/d_cnjg.c
 delete mode 100644 contrib/libf2c/libF77/d_cos.c
 delete mode 100644 contrib/libf2c/libF77/d_cosh.c
 delete mode 100644 contrib/libf2c/libF77/d_dim.c
 delete mode 100644 contrib/libf2c/libF77/d_exp.c
 delete mode 100644 contrib/libf2c/libF77/d_imag.c
 delete mode 100644 contrib/libf2c/libF77/d_int.c
 delete mode 100644 contrib/libf2c/libF77/d_lg10.c
 delete mode 100644 contrib/libf2c/libF77/d_log.c
 delete mode 100644 contrib/libf2c/libF77/d_mod.c
 delete mode 100644 contrib/libf2c/libF77/d_nint.c
 delete mode 100644 contrib/libf2c/libF77/d_prod.c
 delete mode 100644 contrib/libf2c/libF77/d_sign.c
 delete mode 100644 contrib/libf2c/libF77/d_sin.c
 delete mode 100644 contrib/libf2c/libF77/d_sinh.c
 delete mode 100644 contrib/libf2c/libF77/d_sqrt.c
 delete mode 100644 contrib/libf2c/libF77/d_tan.c
 delete mode 100644 contrib/libf2c/libF77/d_tanh.c
 delete mode 100644 contrib/libf2c/libF77/derf_.c
 delete mode 100644 contrib/libf2c/libF77/derfc_.c
 delete mode 100644 contrib/libf2c/libF77/dtime_.c
 delete mode 100644 contrib/libf2c/libF77/ef1asc_.c
 delete mode 100644 contrib/libf2c/libF77/ef1cmc_.c
 delete mode 100644 contrib/libf2c/libF77/erf_.c
 delete mode 100644 contrib/libf2c/libF77/erfc_.c
 delete mode 100644 contrib/libf2c/libF77/etime_.c
 delete mode 100644 contrib/libf2c/libF77/exit_.c
 delete mode 100644 contrib/libf2c/libF77/f2ch.add
 delete mode 100644 contrib/libf2c/libF77/getarg_.c
 delete mode 100644 contrib/libf2c/libF77/getenv_.c
 delete mode 100644 contrib/libf2c/libF77/h_abs.c
 delete mode 100644 contrib/libf2c/libF77/h_dim.c
 delete mode 100644 contrib/libf2c/libF77/h_dnnt.c
 delete mode 100644 contrib/libf2c/libF77/h_indx.c
 delete mode 100644 contrib/libf2c/libF77/h_len.c
 delete mode 100644 contrib/libf2c/libF77/h_mod.c
 delete mode 100644 contrib/libf2c/libF77/h_nint.c
 delete mode 100644 contrib/libf2c/libF77/h_sign.c
 delete mode 100644 contrib/libf2c/libF77/hl_ge.c
 delete mode 100644 contrib/libf2c/libF77/hl_gt.c
 delete mode 100644 contrib/libf2c/libF77/hl_le.c
 delete mode 100644 contrib/libf2c/libF77/hl_lt.c
 delete mode 100644 contrib/libf2c/libF77/i_abs.c
 delete mode 100644 contrib/libf2c/libF77/i_dim.c
 delete mode 100644 contrib/libf2c/libF77/i_dnnt.c
 delete mode 100644 contrib/libf2c/libF77/i_indx.c
 delete mode 100644 contrib/libf2c/libF77/i_len.c
 delete mode 100644 contrib/libf2c/libF77/i_mod.c
 delete mode 100644 contrib/libf2c/libF77/i_nint.c
 delete mode 100644 contrib/libf2c/libF77/i_sign.c
 delete mode 100644 contrib/libf2c/libF77/iargc_.c
 delete mode 100644 contrib/libf2c/libF77/l_ge.c
 delete mode 100644 contrib/libf2c/libF77/l_gt.c
 delete mode 100644 contrib/libf2c/libF77/l_le.c
 delete mode 100644 contrib/libf2c/libF77/l_lt.c
 delete mode 100644 contrib/libf2c/libF77/lbitbits.c
 delete mode 100644 contrib/libf2c/libF77/lbitshft.c
 delete mode 100644 contrib/libf2c/libF77/main.c
 delete mode 100644 contrib/libf2c/libF77/makefile.netlib
 delete mode 100644 contrib/libf2c/libF77/pow_ci.c
 delete mode 100644 contrib/libf2c/libF77/pow_dd.c
 delete mode 100644 contrib/libf2c/libF77/pow_di.c
 delete mode 100644 contrib/libf2c/libF77/pow_hh.c
 delete mode 100644 contrib/libf2c/libF77/pow_ii.c
 delete mode 100644 contrib/libf2c/libF77/pow_qq.c
 delete mode 100644 contrib/libf2c/libF77/pow_ri.c
 delete mode 100644 contrib/libf2c/libF77/pow_zi.c
 delete mode 100644 contrib/libf2c/libF77/pow_zz.c
 delete mode 100644 contrib/libf2c/libF77/qbitbits.c
 delete mode 100644 contrib/libf2c/libF77/qbitshft.c
 delete mode 100644 contrib/libf2c/libF77/r_abs.c
 delete mode 100644 contrib/libf2c/libF77/r_acos.c
 delete mode 100644 contrib/libf2c/libF77/r_asin.c
 delete mode 100644 contrib/libf2c/libF77/r_atan.c
 delete mode 100644 contrib/libf2c/libF77/r_atn2.c
 delete mode 100644 contrib/libf2c/libF77/r_cnjg.c
 delete mode 100644 contrib/libf2c/libF77/r_cos.c
 delete mode 100644 contrib/libf2c/libF77/r_cosh.c
 delete mode 100644 contrib/libf2c/libF77/r_dim.c
 delete mode 100644 contrib/libf2c/libF77/r_exp.c
 delete mode 100644 contrib/libf2c/libF77/r_imag.c
 delete mode 100644 contrib/libf2c/libF77/r_int.c
 delete mode 100644 contrib/libf2c/libF77/r_lg10.c
 delete mode 100644 contrib/libf2c/libF77/r_log.c
 delete mode 100644 contrib/libf2c/libF77/r_mod.c
 delete mode 100644 contrib/libf2c/libF77/r_nint.c
 delete mode 100644 contrib/libf2c/libF77/r_sign.c
 delete mode 100644 contrib/libf2c/libF77/r_sin.c
 delete mode 100644 contrib/libf2c/libF77/r_sinh.c
 delete mode 100644 contrib/libf2c/libF77/r_sqrt.c
 delete mode 100644 contrib/libf2c/libF77/r_tan.c
 delete mode 100644 contrib/libf2c/libF77/r_tanh.c
 delete mode 100644 contrib/libf2c/libF77/s_cat.c
 delete mode 100644 contrib/libf2c/libF77/s_cmp.c
 delete mode 100644 contrib/libf2c/libF77/s_copy.c
 delete mode 100644 contrib/libf2c/libF77/s_paus.c
 delete mode 100644 contrib/libf2c/libF77/s_rnge.c
 delete mode 100644 contrib/libf2c/libF77/s_stop.c
 delete mode 100644 contrib/libf2c/libF77/setarg.c
 delete mode 100644 contrib/libf2c/libF77/setsig.c
 delete mode 100644 contrib/libf2c/libF77/sig_die.c
 delete mode 100644 contrib/libf2c/libF77/signal1.h
 delete mode 100644 contrib/libf2c/libF77/signal1.h0
 delete mode 100644 contrib/libf2c/libF77/signal_.c
 delete mode 100644 contrib/libf2c/libF77/system_.c
 delete mode 100644 contrib/libf2c/libF77/z_abs.c
 delete mode 100644 contrib/libf2c/libF77/z_cos.c
 delete mode 100644 contrib/libf2c/libF77/z_div.c
 delete mode 100644 contrib/libf2c/libF77/z_exp.c
 delete mode 100644 contrib/libf2c/libF77/z_log.c
 delete mode 100644 contrib/libf2c/libF77/z_sin.c
 delete mode 100644 contrib/libf2c/libF77/z_sqrt.c
 delete mode 100644 contrib/libf2c/libI77/Makefile.in
 delete mode 100644 contrib/libf2c/libI77/Notice
 delete mode 100644 contrib/libf2c/libI77/README.netlib
 delete mode 100644 contrib/libf2c/libI77/Version.c
 delete mode 100644 contrib/libf2c/libI77/backspace.c
 delete mode 100644 contrib/libf2c/libI77/close.c
 delete mode 100644 contrib/libf2c/libI77/config.h.in
 delete mode 100755 contrib/libf2c/libI77/configure
 delete mode 100644 contrib/libf2c/libI77/configure.in
 delete mode 100644 contrib/libf2c/libI77/dfe.c
 delete mode 100644 contrib/libf2c/libI77/dolio.c
 delete mode 100644 contrib/libf2c/libI77/due.c
 delete mode 100644 contrib/libf2c/libI77/endfile.c
 delete mode 100644 contrib/libf2c/libI77/err.c
 delete mode 100644 contrib/libf2c/libI77/f2ch.add
 delete mode 100644 contrib/libf2c/libI77/fio.h
 delete mode 100644 contrib/libf2c/libI77/fmt.c
 delete mode 100644 contrib/libf2c/libI77/fmt.h
 delete mode 100644 contrib/libf2c/libI77/fmtlib.c
 delete mode 100644 contrib/libf2c/libI77/fp.h
 delete mode 100644 contrib/libf2c/libI77/ftell_.c
 delete mode 100644 contrib/libf2c/libI77/iio.c
 delete mode 100644 contrib/libf2c/libI77/ilnw.c
 delete mode 100644 contrib/libf2c/libI77/inquire.c
 delete mode 100644 contrib/libf2c/libI77/lio.h
 delete mode 100644 contrib/libf2c/libI77/lread.c
 delete mode 100644 contrib/libf2c/libI77/lwrite.c
 delete mode 100644 contrib/libf2c/libI77/makefile.netlib
 delete mode 100644 contrib/libf2c/libI77/open.c
 delete mode 100644 contrib/libf2c/libI77/rdfmt.c
 delete mode 100644 contrib/libf2c/libI77/rewind.c
 delete mode 100644 contrib/libf2c/libI77/rsfe.c
 delete mode 100644 contrib/libf2c/libI77/rsli.c
 delete mode 100644 contrib/libf2c/libI77/rsne.c
 delete mode 100644 contrib/libf2c/libI77/sfe.c
 delete mode 100644 contrib/libf2c/libI77/stamp-h.in
 delete mode 100644 contrib/libf2c/libI77/sue.c
 delete mode 100644 contrib/libf2c/libI77/typesize.c
 delete mode 100644 contrib/libf2c/libI77/uio.c
 delete mode 100644 contrib/libf2c/libI77/util.c
 delete mode 100644 contrib/libf2c/libI77/wref.c
 delete mode 100644 contrib/libf2c/libI77/wrtfmt.c
 delete mode 100644 contrib/libf2c/libI77/wsfe.c
 delete mode 100644 contrib/libf2c/libI77/wsle.c
 delete mode 100644 contrib/libf2c/libI77/wsne.c
 delete mode 100644 contrib/libf2c/libI77/xwsne.c
 delete mode 100644 contrib/libf2c/libU77/COPYING.LIB
 delete mode 100644 contrib/libf2c/libU77/Makefile.in
 delete mode 100644 contrib/libf2c/libU77/PROJECTS
 delete mode 100644 contrib/libf2c/libU77/README
 delete mode 100644 contrib/libf2c/libU77/Version.c
 delete mode 100644 contrib/libf2c/libU77/access_.c
 delete mode 100644 contrib/libf2c/libU77/acconfig.h
 delete mode 100644 contrib/libf2c/libU77/aclocal.m4
 delete mode 100644 contrib/libf2c/libU77/alarm_.c
 delete mode 100644 contrib/libf2c/libU77/chdir_.c
 delete mode 100644 contrib/libf2c/libU77/chmod_.c
 delete mode 100644 contrib/libf2c/libU77/config.hin
 delete mode 100755 contrib/libf2c/libU77/configure
 delete mode 100644 contrib/libf2c/libU77/configure.in
 delete mode 100644 contrib/libf2c/libU77/ctime_.c
 delete mode 100644 contrib/libf2c/libU77/date_.c
 delete mode 100644 contrib/libf2c/libU77/datetime_.c
 delete mode 100644 contrib/libf2c/libU77/dtime_.c
 delete mode 100644 contrib/libf2c/libU77/etime_.c
 delete mode 100644 contrib/libf2c/libU77/fdate_.c
 delete mode 100644 contrib/libf2c/libU77/fgetc_.c
 delete mode 100644 contrib/libf2c/libU77/flush1_.c
 delete mode 100644 contrib/libf2c/libU77/fnum_.c
 delete mode 100644 contrib/libf2c/libU77/fputc_.c
 delete mode 100644 contrib/libf2c/libU77/fstat_.c
 delete mode 100644 contrib/libf2c/libU77/gerror_.c
 delete mode 100644 contrib/libf2c/libU77/getcwd_.c
 delete mode 100644 contrib/libf2c/libU77/getgid_.c
 delete mode 100644 contrib/libf2c/libU77/getlog_.c
 delete mode 100644 contrib/libf2c/libU77/getpid_.c
 delete mode 100644 contrib/libf2c/libU77/getuid_.c
 delete mode 100644 contrib/libf2c/libU77/gmtime_.c
 delete mode 100644 contrib/libf2c/libU77/hostnm_.c
 delete mode 100644 contrib/libf2c/libU77/idate_.c
 delete mode 100644 contrib/libf2c/libU77/ierrno_.c
 delete mode 100644 contrib/libf2c/libU77/irand_.c
 delete mode 100644 contrib/libf2c/libU77/isatty_.c
 delete mode 100644 contrib/libf2c/libU77/itime_.c
 delete mode 100644 contrib/libf2c/libU77/kill_.c
 delete mode 100644 contrib/libf2c/libU77/link_.c
 delete mode 100644 contrib/libf2c/libU77/lnblnk_.c
 delete mode 100644 contrib/libf2c/libU77/lstat_.c
 delete mode 100644 contrib/libf2c/libU77/ltime_.c
 delete mode 100644 contrib/libf2c/libU77/mclock_.c
 delete mode 100644 contrib/libf2c/libU77/perror_.c
 delete mode 100644 contrib/libf2c/libU77/rand_.c
 delete mode 100644 contrib/libf2c/libU77/rename_.c
 delete mode 100644 contrib/libf2c/libU77/secnds_.c
 delete mode 100644 contrib/libf2c/libU77/second_.c
 delete mode 100644 contrib/libf2c/libU77/sleep_.c
 delete mode 100644 contrib/libf2c/libU77/srand_.c
 delete mode 100644 contrib/libf2c/libU77/stamp-h.in
 delete mode 100644 contrib/libf2c/libU77/stat_.c
 delete mode 100644 contrib/libf2c/libU77/symlnk_.c
 delete mode 100644 contrib/libf2c/libU77/sys_clock_.c
 delete mode 100644 contrib/libf2c/libU77/time_.c
 delete mode 100644 contrib/libf2c/libU77/ttynam_.c
 delete mode 100644 contrib/libf2c/libU77/u77-test.f
 delete mode 100644 contrib/libf2c/libU77/umask_.c
 delete mode 100644 contrib/libf2c/libU77/unlink_.c
 delete mode 100644 contrib/libf2c/libU77/vxtidate_.c
 delete mode 100644 contrib/libf2c/libU77/vxttime_.c
 delete mode 100644 contrib/libf2c/permission.netlib
 delete mode 100644 contrib/libf2c/readme.netlib

diff --git a/contrib/libf2c/ChangeLog b/contrib/libf2c/ChangeLog
deleted file mode 100644
index e5f5c08c9ca..00000000000
--- a/contrib/libf2c/ChangeLog
+++ /dev/null
@@ -1,2467 +0,0 @@
-2006-03-05  Release Manager
-
-	* GCC 3.4.6 released.
-
-2005-11-30  Release Manager
-
-	* GCC 3.4.5 released.
-
-2005-05-19  Release Manager
-
-	* GCC 3.4.4 released.
-
-2005-01-05  Eric Botcazou  
-
-	PR libf2c/17636
-	* libI77/err.c (f__nowwriting): Call fseek if end-of-file.
-
-2004-11-04  Release Manager
-
-	* GCC 3.4.3 released.
-
-2004-09-06  Release Manager
-
-	* GCC 3.4.2 released.
-
-2004-07-01  Release Manager
-
-	* GCC 3.4.1 released.
-
-2004-05-06  Bud Davis  
-
-	PR libf2c/15151
-	* libI77/wrtfmt.c(wrt_L):  Make sizes and types consistent.
-
-2004-04-18  Release Manager
-
-	* GCC 3.4.0 released.
-
-Thu Feb  5 15:08:08 2004  Geoffrey Keating  
-
-	PR 12179
-	* aclocal.m4 (GLIBCPP_EXPORT_INSTALL_INFO): Use 'gcc', not 'gcc-lib'.
-	Add comment about poorly-named variables.
-	* Makefile.in (libsubdir): Use 'gcc', not 'gcc-lib'.
-	* configure: Regenerate.
-
-2004-01-31  Bud Davis  
-
-	PR fortran/12884
-	* libI77/rsne.c: Enable reading a '/' when reading
-	a '$' delimited namelist.
-
-2004-01-14 Kelley Cook  
-
-	* libF77/configure.in: Update to AC_PREREQ(2.13)
-	* libI77/configure.in: Update to AC_PREREQ(2.13)
-	* libU77/configure.in: Update to AC_PREREQ(2.13)
-	* libU77/configure: Regenerate. 
-
-2003-10-14  Nathanael Nerode  
-
-	* configure: Regenerate.
-
-2003-09-21  Toon Moene  
-
-	PR libf2c/11918
-	* fstat_.c: Call f_init().
-	* isatty_.c: Ditto.
-	* fnum_.c: Check file descriptor before handing it back.
-
-Tue Sep  9 15:22:57 2003  Alan Modra  
-
-	* configure: Regenerate.
-
-2003-07-04  H.J. Lu 
-
-	* Makefile.in: Replace PWD with PWD_COMMAND.
-
-2003-06-15  Nathanael Nerode  
-
-	* libU77/bes.c, libU77/dbes.c: Remove.
-	* libU77/Makefile.in: Remove references to bes.c, dbes.c
-
-2003-04-21  Loren J. Rittle  
-
-	* libI77/configure.in (_XOPEN_SOURCE): Bump to 600.
-	* libI77/configure: Regenerate. 
-	* libU77/configure.in (_XOPEN_SOURCE): Bump to 600.
-	* libU77/configure: Regenerate. 
-
-2003-04-11  Bud Davis 
-
-	PR Fortran/1832
-	* libf2c/libI77/iio.c (z_putc): Check for overflowing length
-	of output string.
-
-2003-03-24  Bud Davis  
-
-	PR fortran/10197
-	* libI77/open.c (f_open): A DIRECT ACCESS file is
-	UNFORMATTED by default.
-
-Wed Mar 12 22:27:14 2003  Andreas Schwab  
-
-	* aclocal.m4 (GLIBCPP_EXPORT_INSTALL_INFO): Avoid trailing /. in
-	glibcpp_toolexeclibdir.
-	* configure: Rebuilt.
-
-2003-02-20  Alexandre Oliva  
-
-	* configure.in: Propagate ORIGINAL_LD_FOR_MULTILIBS to
-	config.status.
-	* configure: Rebuilt.
-
-2003-02-03  Andreas Jaeger  
-
-	* libU77/configure.in (AC_PROG_CC_WORKS): Define _GNU_SOURCE.
-	* libU77/config.hin: Regenerated.
-	* libU77/configure: Regenerated.
-
-2003-01-27  Alexandre Oliva  
-
-	* Makefile.in ($(LIBG2C)): -rpath is glibcpp_toolexeclibdir.
-	* aclocal.m4 (glibcpp_toolexeclibdir): Instead of
-	$(MULTISUBDIR), use `$CC -print-multi-os-directory`, unless
-	version_specific_libs is enabled.
-	* configure: Rebuilt.
-
-2003-01-09  Christian Cornelssen  
-
-	* Makefile.in (FLAGS_TO_PASS): Also pass DESTDIR.
-	(install, uninstall): Prepend $(DESTDIR) to destination
-	paths in all (un)installation commands.
-
-Wed Dec 18 11:33:35 2002  Jason Merrill  
-
-	* libU77/date_.c (G77_date_y2kbuggy_0): Declare G77_abort_0 noreturn.
-	* libU77/vxtidate_.c (G77_vxtidate_y2kbuggy_0): Likewise.
-
-2002-11-26  Nathanael Nerode  
-
-	* configure.in: Remove skip-this-dir support.
-	* configure: Regenerate.
-
-2002-11-19  Toon Moene  
-
-	PR fortran/8587
-	* libF77/pow_zz.c: Handle (0.0, 0.0) ** power.
-
-2002-10-18  Krister Walfridsson  
-
-	* libU77/configure.in (_XOPEN_SOURCE, _XOPEN_SOURCE_EXTENDED,
-	__EXTENSIONS__, _FILE_OFFSET_BITS): Check that _XOPEN_SOURCE 500L
-	may be defined before defining these.
-	* libU77/configure: Regenerate.
-	* libI77/configure.in (_XOPEN_SOURCE, _XOPEN_SOURCE_EXTENDED,
-	__EXTENSIONS__, _FILE_OFFSET_BITS): Check that _XOPEN_SOURCE 500L
-	may be defined before defining these.
-	* libI77/configure: Regenerate.
-
-2002-09-23  Zack Weinberg  
-
-	* libF77/Version.c: Rename junk to __LIBF77_VERSION__.  Add
-	external decls for __LIBI77_VERSION__ and __LIBU77_VERSION__.
-	Delete __G77_LIBF77_VERSION__
-	(g77__fvers__): Print all three __LIB*77_VERSION__ strings,
-	and __VERSION__ if we have it; nothing else.
-
-	* libI77/Version.c: Provide only __LIBI77_VERSION__ (formerly junk).
-	* libU77/Version.c: Provide only __LIBU77_VERSION__ (formerly junk).
-
-Sun Sep 22 23:43:37 2002  Kaveh R. Ghazi  
-
-	* Makefile.in (all): Fix multilib parallel build.
-
-2002-09-14  Tim Prince  
-
-	PR libf2c/7384
-	* libU77/datetime_.c: Use GetLocalTime on MS-Windows.
-
-2002-08-31  Toon Moene  
-
-	PR fortran/6367
-	* libI77/rsne.c (x_rsne): Use local variable no2 to count further
-	list elements to read.
-
-2002-07-10  Toon Moene  
-
-	* libI77/open.c (f_open): Do not indicate unformatted file
-	if record length is given without a FORMATTED/UNFORMATTED
-	specification.
-
-2002-06-25  DJ Delorie  
-
-	* aclocal.m4 (GLIBCPP_CONFIGURE): Split out
-	GLIBCPP_TOPREL_CONFIGURE.
-	* configure.in: Call it before AC_CANONICAL_SYSTEM.
-	* configure: Regenerate.
-
-Wed Jun  5 15:05:41 2002  Kaveh R. Ghazi  
-
-	* f2cext.c (alarm_): Mark parameter(s) with attribute `unused'.
-	* libF77/h_len.c (h_len): Likewise.
-	* libF77/i_len.c (i_len): Likewise.
-	* libI77/rsli.c (i_ungetc): Likewise.
-	* libU77/date_.c (G77_date_y2kbuggy_0): Likewise.
-	* libU77/fputc_.c (G77_fputc_0): Likewise.
-	* libU77/vxtidate_.c (G77_vxtidate_y2kbuggy_0): Likewise.
-	* libU77/vxttime_.c (G77_vxttime_0): Likewise.
-
-Mon Jun  3 22:24:48 2002  Kaveh R. Ghazi  
-
-	* libF77/main.c (f_setarg, f_setsig): Prototype.
-	* libI77/lread.c (quad_read): Delete.
-	* libI77/uio.c: Include config.h.
-	* libI77/wref.c (wrt_E): Cast isdigit arg to unsigned char.
-	* libU77/dtime_.c (clk_tck): Move to the scope where it is used.
-	* libU77/etime_.c (clk_tck): Likewise.
-
-Mon Jun  3 22:23:03 2002  Kaveh R. Ghazi  
-
-	* libF77/lbitbits.c (lbit_cshift): disambiguate expressions
-	with parentheses.
-	* libF77/qbitbits.c (qbit_cshift): Likewise.
-	* libI77/inquire.c (f_inqu): Likewise.
-	* libI77/rdfmt.c (rd_Z): Likewise.
-	* libI77/rsne.c (x_rsne): Likewise.
-
-Mon Jun  3 22:21:23 2002  Kaveh R. Ghazi  
-
-	* Makefile.in (s-libe77): Add WARN_CFLAGS.
-
-Sun Jun  2 10:32:35 2002  Kaveh R. Ghazi  
-
-	* libI77/dfe.c (s_rdfe, s_wdfe): Wrap parentheses around
-	assignment used as truth value.
-	* libI77/due.c (s_rdue, s_wdue): Likewise.
-	* libI77/endfile.c (f_end): Likewise.
-	* libI77/iio.c (s_rsfi, s_wsfi): Likewise.
-	* libI77/lread.c (ERR, l_C, nmL_getc, s_rsle): Likewise.
-	* libI77/lwrite.c (l_g, l_put): Likewise.
-	* libI77/open.c (f_open): Likewise.
-	* libI77/rdfmt.c (rd_Z): Likewise.
-	* libI77/rsfe.c (s_rsfe): Likewise.
-	* libI77/rsne.c (hash, mk_hashtab, nl_init, getname, getdimen,
-	x_rsne, s_rsne): Likewise.
-	* libI77/sue.c (s_rsue, s_wsue): Likewise.
-	* libI77/wref.c (wrt_E, wrt_F): Likewise.
-	* libI77/wsfe.c (s_wsfe): Likewise.
-	* libI77/wsle.c (s_wsle): Likewise.
-	* libI77/wsne.c (s_wsne): Likewise.
-
-Sun Jun  2 08:59:50 2002  Kaveh R. Ghazi  
-
-	* libF77/main.c (main): Avoid implicit int.
-	* libI77/dfe.c (y_rsk, y_getc, c_dfe): Likewise.
-	* libI77/due.c (c_due): Likewise.
-	* libI77/err.c (f__canseek, f__nowreading, f__nowwriting):
-	Likewise.
-	* libI77/fmt.c (op_gen, ne_d, e_d, pars_f, type_f, en_fio):
-	Likewise.
-	* libI77/iio.c (z_getc, z_rnew, c_si, z_wnew): Likewise.
-	* libI77/lread.c (t_getc, c_le, l_read): Likewise.
-	* libI77/lwrite.c (l_write): Likewise.
-	* libI77/open.c (fk_open): Likewise.
-	* libI77/rdfmt.c (rd_ed, rd_ned): Likewise.
-	* libI77/rsfe.c (xrd_SL, x_getc, x_endp, x_rev): Likewise.
-	* libI77/rsne.c (t_getc, x_rsne): Likewise.
-	* libI77/sfe.c (c_sfe): Likewise.
-	* libI77/sue.c (c_sue): Likewise.
-	* libI77/uio.c (do_us): Likewise.
-	* libI77/wref.c (wrt_E, wrt_F): Likewise.
-	* libI77/wrtfmt.c (wrt_L, w_ed, w_ned): Likewise.
-
-Sun Jun  2 08:58:05 2002  Kaveh R. Ghazi  
-
-	* libI77/rdfmt.c (rd_I): Delete unused variable(s).
-	* libU77/access_.c (G77_access_0): Likewise.
-	* libU77/chdir_.c (G77_chdir_0): Likewise.
-	* libU77/chmod_.c (G77_chmod_0): Likewise.
-	* libU77/ctime_.c (G77_ctime_0): Likewise.
-	* libU77/link_.c (G77_link_0): Likewise.
-	* libU77/lstat_.c (G77_lstat_0): Likewise.
-	* libU77/rename_.c (G77_rename_0): Likewise.
-	* libU77/stat_.c (G77_stat_0): Likewise.
-	* libU77/symlnk_.c (G77_symlnk_0): Likewise.
-	* libU77/unlink_.c (G77_unlink_0): Likewise.
-
-Sun Jun  2 08:55:20 2002  Kaveh R. Ghazi  
-
-	* libI77/inquire.c (f_inqu): Avoid ambiguous else clauses.
-	* libI77/lread.c (l_C, l_L): Likewise.
-	* libI77/open.c (f_open): Likewise.
-	* libI77/rsne.c (x_rsne): Likewise.
-	* libI77/wref.c (wrt_F): Likewise.
-
-Sun Jun  2 08:53:15 2002  Kaveh R. Ghazi  
-
-	* libF77/getenv_.c (G77_getenv_0): Avoid signed/unsigned warning.
-	* libF77/system_.c (G77_system_0): Likewise.
-	* libI77/open.c (f_open): Likewise.
-	* libI77/rdfmt.c (rd_Z): Likewise.
-	* libI77/uio.c (do_us, do_ud): Likewise.
-
-Sat Jun  1 08:33:14 2002  Kaveh R. Ghazi  
-
-	* libF77/*: Fix formatting.
-	* libI77/*: Likewise.
-	* libU77/*: Likewise.
-
-Fri May 31 21:56:30 2002  Kaveh R. Ghazi  
-
-	* g2c.hin, libF77/d_cnjg.c, libF77/main.c, libF77/r_cnjg.c,
-	libF77/s_cat.c, libF77/s_paus.c, libF77/s_rnge.c, libF77/setarg.c,
-	libF77/setsig.c, libF77/signal1.h0, libI77/dfe.c, libI77/due.c,
-	libI77/err.c, libI77/fio.h, libI77/fmt.c, libI77/iio.c,
-	libI77/ilnw.c, libI77/lread.c, libI77/lwrite.c, libI77/rsfe.c,
-	libI77/rsli.c, libI77/rsne.c, libI77/sfe.c, libI77/sue.c,
-	libI77/util.c, libI77/wrtfmt.c, libI77/wsfe.c, libI77/wsle.c,
-	libI77/xwsne.c, libU77/date_.c: Kill VOID, Void and Int.
-
-Fri May 31 21:54:37 2002  Kaveh R. Ghazi  
-
-	* libF77/F77_aloc.c, libF77/exit_.c, libF77/main.c,
-	libF77/s_paus.c, libF77/s_stop.c, libF77/setarg.c,
-	libF77/setsig.c, libF77/sig_die.c, libF77/signal1.h0,
-	libI77/close.c, libI77/dolio.c, libI77/fio.h, libI77/fmt.h,
-	libI77/lio.h: Delete checks on __cplusplus.
-
-Fri May 31 21:50:01 2002  Kaveh R. Ghazi  
-
-	* libF77/*: Delete KR_headers cruft.
-	* libI77/*: Likewise.
-	* libU77/*: Likewise.
-
-Thu May 30 23:04:52 2002  Kaveh R. Ghazi  
-
-	* Makefile.in (WARN_CFLAGS): New.
-	(FLAGS_TO_PASS): Add WARN_CFLAGS.
-	* libF77/Makefile.in (ALL_CFLAGS): Likewise.
-	* libI77/Makefile.in (ALL_CFLAGS): Likewise.
-	* libU77/Makefile.in (ALL_CFLAGS): Likewise.
-
-2002-05-30  H.J. Lu  (hjl@gnu.org)
-
-	* libI77/open.c (_XOPEN_SOURCE): Removed.
-
-Mon May 20 13:03:54 2002  Kaveh R. Ghazi  
-
-	* libF77/Makefile.in (SHELL): Set to @SHELL@.
-	* libI77/Makefile.in (SHELL): Likewise.
-	* libU77/Makefile.in (SHELL): Likewise.
-
-2002-05-20  Toon Moene  
-
-	* Makefile.in: Use @SHELL@, not /bin/sh for SHELL
-	definition.
-
-2002-05-16  Rainer Orth  
-
-	* Makefile.in: Allow for PWDCMD to override hardcoded pwd.
-	* aclocal.m4: Likewise.
-	* configure: Regenerate.
-
-2002-05-08  Alexandre Oliva  
-
-	* configure.in (ORIGINAL_LD_FOR_MULTILIBS): Preserve LD at
-	script entry, and set LD to it when configuring multilibs.
-	* configure: Rebuilt.
-
-2002-05-02  Alexandre Oliva  
-
-	* Makefile.in: Fix for multilibbed natives.
-
-2002-04-15  Loren J. Rittle  
-
-	* aclocal.m4 (gcc_version_trigger): Use robust path construction.
-	* configure: Rebuilt.
-
-2002-04-11  Toon Moene  
-
-	* libI77/lio.h: Treat INTEGER*1 as signed char.
-
-2002-03-06  Phil Edwards  
-
-	* libF77/Version.c:  Fix misplaced leading blanks on first line.
-	* libI77/Version.c:  Likewise.
-	* libU77/Version.c:  Likewise.
-
-2002-01-28  Geoffrey Keating  
-
-	* aclocal.m4: Replace with version copied from libstdc++-v3.
-	* configure.in: Update for changes to aclocal and Makefile.
-	* configure: Regenerate.
-	* Makefile.in: Correct install and uninstall for cross targets.
-	* libU77/configure: Regenerate.
-
-2002-01-20  Toon Moene  
-
-	* Makefile.in: $(MULTISUBDIR) has an implied leading `/';
-	remove duplicates.
-	Use libtool for removing libg2c{a|la|so} for the `uninstall' target.
-
-2002-01-18  Toon Moene  
-
-	* Makefile.in: Add missing `/' separator in last change.
-
-2002-01-18  Toon Moene  
-
-	* Makefile.in: Install libg2c.{a|la|so} in $(libdir)$(MULTISUBDIR)
-	instead of $(libsubdir)$(MULTISUBDIR).
-
-2002-01-15  Loren J. Rittle  
-
-	* libI77/configure.in: Remove fcntl.h check; never define
-	_POSIX_SOURCE, NO_FCNTL or OPEN_DECL.  Add check for tmpnam().
-	* libI77/configure: Rebuilt.
-	* libI77/config.h.in: Rebuilt.
-	* libI77/Makefile.in: Remove all traces of rawio.h from
-	dependencies lists.
-	* libI77/fio.h (FSEEK): Unroll -j1.7 -j1.6 made 2002-01-04.
-	* libI77/open.c (f_open): Use HAVE_TMPNAM.
-	* libI77/rawio.h: Remove file.
-
-2002-01-14  John David Anglin  
-
-	* libI77/configure.in (_LARGEFILE_SOURCE): AC_DEFINE.
-	* libI77/configure: Rebuilt.
-	* libI77/config.h.in: Rebuilt.
-
-2002-01-04  Loren J. Rittle  
-
-	* libI77/fio.h (FSEEK): Enforce type of second parameter to be
-	off_t when prototype is missing from system headers for the
-	non-standard function.
-
-2002-01-03  Loren J. Rittle  
-
-	* Makefile.in ($(LIBG2C):): Let libtool decide when to add -lc.
-
-2001-12-04  Alexandre Oliva  
-
-	* Makefile.in ($(LIBG2C)): Fix -rpath argument to libtool.
-
-	* Makefile.in (AR, RANLIB): Add, for substitutions.
-	(all-unilib, $(LIBG2C)): Depend on object lists, not
-	convenience libraries.
-	(s-libe77): Renamed from libE77.la; build object list.
-	(install): Do not move libraries to libdir.
-	(mostlyclean, clean): Adjust.
-	* libF77/Makefile.in (RANLIB): Add.
-	(LINK): Remove.
-	(../s-libf77): Renamed from ../libF77.la; build object list.
-	(../libfrtbegin.a): Remove target first.  Don't use $<.
-	(all, clean, distclean): Adjust.
-	* libF77/configure.in: Substitute RANLIB.
-	* libF77/configure: Rebuilt.
-	* libI77/Makefile.in (LINK): Delete.
-	(../s-libi77): Renamed from ../libI77.la; build object list.
-	(all, clean, distclean): Adjust.
-	* libU77/Makefile.in: Likewise.
-
-2001-12-02  Toon Moene  
-
-	PR fortran/4885
-	* endfile.c (t_runc): After ftruncate, seek to end-of-file.
-
-2001-11-25  Toon Moene  
-
-	* libF77/Makefile.in: Fix non-portable use of `$<' in z_log.c's rule.
-
-2001-11-23  Toon Moene  
-
-	PR libf2c/4930
-	* libF77/Makefile.in: Compile z_log.c with -ffloat-store.
-
-2001-11-16  John David Anglin  
-
-	* Makefile.in: Add MAKEOVERRIDES= to suppress exporting
-	environment to (sub)shells.
-
-2001-11-13  Toon Moene  
-
-	* Makefile.in: Change dependencies on stamp files
-	into dependencies on the generated .la files.
-	Get rid of objlist.  Update comment.
-	* libF77/Makefile.in: Ditto.
-	* libI77/Makefile.in: Ditto.
-	* libU77/Makefile.in: Ditto.
-
-2001-10-20  Hans-Peter Nilsson  
-
-	* configure.in: Fake AC_EXEEXT invocation.
-	* configure: Regenerate.
-
-2001-10-20  David Edelsohn  
-
-	* Makefile.in: Do not include SUBDIRS in objlist.  Create
-	libg2c.so from F2CEXT and SUBDIRS archives.
-	* libF77/Makefile.in: Create archive.
-	* libI77/Makefile.in: Same.
-	* libU77/Makefile.in: Same.
-
-2001-10-05  Toon Moene  
-
-	* Makefile.in: Move libg2c.so and libg2c.{l}a to
-	the same directory at install.
-
-2001-10-03  Toon Moene  
-
-	* Makefile.in: Add "AR" reference, change
-	from frtbegin.o to libfrtbegin.a.
-	* libF77/Makefile.in: Ditto.
-
-2001-10-02  Toon Moene  
-
-	* libF77/Makefile.in: Make .lo the target of compilation.
-	* libI77/Makefile.in: Ditto.
-	* libU77/Makefile.in: Ditto.
-
-2001-10-01  Toon Moene  
-
-	* Makefile.in: Set major:minor:sub version number
-	of shared libf2c to 0:0:0.
-
-2001-09-29  Juergen Pfeifer  
-	    Toon Moene  
-
-	Make libf2c a shared library.
-
-	* aclocal.m4: Get definition of libtool.
-	* Makefile.in: Use libtool.
-	* configure.in: Use libtool.
-	* configure: Regenerated.
-	* libF77/Makefile.in: Use libtool; treat main program contained in
-	libF77/main.c specially.
-	* libF77/configure.in: Use libtool.
-	* libF77/configure: Regenerated.
-	* libI77/Makefile.in: Use libtool.
-	* libI77/configure.in: Use libtool.
-	* libI77/configure: Regenerated.
-	* libU77/Makefile.in: Use libtool.
-	* libU77/configure.in: Use libtool.
-	* libU77/configure: Regenerated.
-	* libU77/date_.c: Adapt for -fPIC compiling.
-	* libU77/vxtidate_.c: Ditto.
-
-2001-09-22  Richard Earnshaw  
-
-	* libI77/configure.in (__EXTENSIONS__): Define.
-	* libI77/config.h.in, libI77/conifgure: regenerate.
-	* libU77/configure.in (__EXTENSIONS__): Likewise.
-
-2001-07-18  Toon Moene  
-
-	* libI77/configure.in (_XOPEN_SOURCE, _FILE_OFFSET_BITS): Move
-	these defines before tests which might be affected by them.
-	(_XOPEN_SOURCE_EXTENDED): Define.
-	* libI77/configure, libI77/config.h.in: Regenerate.
-
-Wed Jul 18 11:14:33 2001  Kaveh R. Ghazi  
-
-	* libU77/configure.in (_XOPEN_SOURCE, _FILE_OFFSET_BITS): Move
-	these defines before tests which might be affected by them.
-	(_XOPEN_SOURCE_EXTENDED): Define.
-
-	* libU77/configure, libU77/config.hin: Regenerate.
-
-2001-07-10  Toon Moene  
-
-	* libI77/fio.h: Revert type of url from off_t to int.
-	* libI77/dfe.c (c_dfe): Cast offset expression in FSEEK to off_t.
-	* libI77/due.c (c_due): Ditto.  (e_rdue): Ditto.
-	* libI77/ftell_.c (G77_ftell_0): Cast result of FTELL to integer.
-	(G77_fseek_0): Cast offset argument of FSEEK to off_t.
-
-2001-07-07  Toon Moene  
-
-	* libI77/Makefile.in: Update config.h dependencies.
-	* libI77/configure.in: Define _XOPEN_SOURCE and
-	_FILE_OFFSET_BITS unconditionally.
-	* libI77/configure: Rebuilt.
-	* libI77/config.h.in: Rebuilt.
-	* libI77/endfile.c (t_runc): Replace rewind by FSEEK.
-	* libI77/err.c (f__nowwriting): The type of `loc' is off_t.
-	* libI77/open.c (f_open): Replace rewind by FSEEK.
-	* libI77/rewind.c: Include config.h.  (f_rew): Replace
-	rewind by FSEEK.
-	* libI77/sfe.c: Include config.h.
-	* libI77/wsfe.c: Ditto.
-	* libU77/configure.in: Define _XOPEN_SOURCE and
-	_FILE_OFFSET_BITS unconditionally.
-	* libU77/configure: Rebuilt.
-	* libU77/config.hin: Rebuilt.
-
-2001-07-07  Toon Moene  
-
-	* libI77/Makefile.in: Add necessary dependencies on config.h.
-
-2001-07-06  Toon Moene  
-	    Pedro Vazquez  
-
-	* libI77/configure.in: Check for fseeko, ftello.
-	* libI77/configure: Rebuilt.
-	* libI77/config.h.in: Rebuilt.
-	* libI77/fio.h: Define FSEEK to be fseek or fseeko, depending
-	on configure's findings.  Ditto for FTELL and ftell / ftello.
-	* libI77/backspace.c (f_back): Use FSEEK for fseek, FTELL for ftell.
-	* libI77/dfe.c (c_dfe): Ditto.
-	* libI77/due.c (c_due, e_rdue): Ditto.
-	* libI77/endfile.c (t_runc): Ditto.
-	* libI77/err.c (f__nowreading, f__nowwriting): Ditto.
-	* libI77/ftell_.c (G77_ftell_0, G77_fseek_0): Ditto.
-	* libI77/inquire.c (f_inqu): Ditto.
-	* libI77/open.c (f_open): Ditto.
-	* libI77/rdfmt.c (rd_ed): Ditto.
-	* libI77/sue.c (s_wsue, e_wsue, e_rsue): Ditto.
-
-2001-07-04  Zack Weinberg  
-
-	* Makefile.in: Take PICFLAG and RUNTESTFLAGS out of FLAGS_TO_PASS.
-
-2001-07-01  Toon Moene  
-
-	* libI77/fio.h: Include  for off_t.
-
-2001-07-01  Toon Moene  
-	    Pedro Vazquez  
-
-	* libI77/fio.h: Use off_t when appropriate.
-	* libI77/backspace.c (f_back): Ditto.
-	* libI77/endfile.c (t_runc): Ditto.
-	* libI77/err.c (f__nowreading): Ditto.
-	* libI77/ftell_.c (unit_chk): Ditto.
-	* libI77/sue.c (global f__recloc, s_wsue): Ditto.
-
-2001-06-13  Toon Moene  
-
-	* libI77/inquire.c: Include "config.h".
-
-2001-05-21  Loren J. Rittle  
-
-	* libI77/Makefile.in (stamp-h): Create in $(objdir) instead
-	of $(srcdir).
-
-2001-05-18  Andreas Jaeger  
-
-	* libI77/Makefile.in (stamp-h): Only create config.h, touch stamp-h.
-	(${srcdir}/config.h.in): Add true rule.
-
-	* libI77/stamp-h.in: Added.
-
-2001-05-17  Andreas Jaeger  
-
-	* libI77/Makefile.in: Add rules to rebuild config.h.in when
-	needed.
-
-2001-05-16  Andreas Jaeger  
-
-	* libI77/backspace.c: Include "config.h".
-	* libI77/close.c: Likewise.
-	* libI77/dfe.c: Likewise.
-	* libI77/dolio.c: Likewise.
-	* libI77/due.c: Likewise.
-	* libI77/err.c: Likewise.
-	* libI77/fmt.c: Likewise.
-	* libI77/fmtlib.c: Likewise.
-	* libI77/ftell_.c: Likewise.
-	* libI77/ilnw.c: Likewise.
-	* libI77/lread.c: Likewise.
-	* libI77/open.c: Likewise.
-	* libI77/rdfmt.c: Likewise.
-	* libI77/rsfe.c: Likewise.
-	* libI77/rsne.c: Likewise.
-	* libI77/util.c: Likewise.
-	* libI77/wrtfmt.c: Likewise.
-	* libI77/wsne.c: Likewise.
-	* libI77/xwsne.c: Likewise.
-
-	* libI77/config.h.in: Generate with autoheader.
-
-	* libI77/configure.in: Add comments for all AC_DEFINES so that
-	autoheader can grok it.
-	* libI77/configure: Regenerated.
-
-2001-05-16  Andreas Jaeger  
-
-	* libI77/Makefile.in (endfile.o): Add dependency on config.h.
-
-	* libI77/endfile.c: Include config.h and sys/types for off_t.
-
-	* libI77/config.h.in: New file.
-
-	* libI77/configure.in: Add test for off_t, create config.h file.
-	* libI77/configure: Regenerated.
-
-2001-05-15  Loren J. Rittle  
-
-	* libI77/endfile.c (t_runc): Add cast to help case where
-	ftruncate() prototype is somehow missing even though autoconf
-	test found it properly.
-
-2001-02-26  Toon Moene  
-
-	* libI77/configure.in: Test for ftruncate.
-	* libI77/configure: Rebuilt.
-	* libI77/endfile.c: Use fflush/ftruncate when available.
-
-2001-02-19  Joseph S. Myers  
-
-	* libF77/Version.c, libI77/Version.c, libU77/Version.c: Update G77
-	version number to 0.5.27.
-
-2001-02-08  Geoffrey Keating  
-
-	* configure.in: Don't run AC_PROG_CC_WORKS, because
-	we're not interested in the result and it might fail.
-	* libF77/configure.in: Likewise.
-	* libI77/configure.in: Likewise.
-	* libU77/configure.in: Likewise.
-	* configure: Regenerated.
-	* libF77/configure: Likewise.
-	* libI77/configure: Likewise.
-	* libU77/configure: Likewise.
-
-2001-01-29  Phil Edwards  
-
-	* libU77/COPYING.LIB:  Update to LGPL 2.1 from the FSF.
-
-2001-01-24  Michael Sokolov  
-
-	* libU77/alarm_.c: Separate the #ifdef KR_headers logic from the
-	G77_alarm_0 function definition.  Check for SIG_ERR and provide our own
-	if missing.
-
-2001-01-24  David Billinghurst 
-
-	* libU77/Makefile.in:  Explicitly generate a.out for check.
-
-2001-01-23  Michael Sokolov  
-
-	* libU77/ctime_.c: #include  for time_t.
-	* libU77/datetime_.c: Likewise.
-	* libU77/fdate_.c: Likewise.
-	* libU77/gmtime_.c: Likewise.
-	* libU77/idate_.c: Likewise.
-	* libU77/itime_.c: Likewise.
-	* libU77/ltime_.c: Likewise.
-	* libU77/sys_clock_.c: Likewise.
-	* libU77/vxtidate_.c: Likewise.
-	* libU77/vxttime_.c: Likewise.
-
-	* libU77/sys_clock_.c: #include  for the clock tick rate.
-
-2000-12-09  Toon Moene  
-
-	Update to Netlib version 20001205.
-	Thanks go to David M. Gay for these updates.
-
-	* libF77/Version.c: Update version information.
-	* libF77/z_log.c: Improve accuracy of real(log(z)) for
-	z near (+-1,eps) with |eps| small.
-	* libF77/s_cat.c: Adjust call when ftnint and ftnlen are
-	of different size.
-	* libF77/dtime_.c, libF77/etime_.c: Use floating point divide.
-
-	* libI77/Version.c: Update version information.
-	* libI77/rsne.c, libI77/xwsne.c: Adjust code for when ftnint
-	and ftnlen differ in size.
-	* libI77/lread.c: Fix reading of namelist logical values followed
-	by = where  starts with T or F.
-
-2000-11-26  Toon Moene  
-
-	* libI77/Version.c, libF77/Version.c, libU77/Version.c:
-	Designate version as (experimental) instead of (prerelease)
-
-2000-11-15  Toon Moene  
-
-	* libI77/configure.in: See if `mkstemp' is available.
-	* libI77/configure: Regenerate.
-	* libI77/open.c: Use `mkstemp' to create scratch
-	file atomically.
-
-2000-07-03  Donn Terry  (donnte@microsoft.com)
-	* libU77/aclocal.m4: check for 2 argument gettimeofday without
-	struct timezone
-
-2000-07-02  Toon Moene  
-	* libF77/Version.c: Bumped version number to 0.5.26.
-	* libI77/Version.c: Ditto.
-	* libU77/Version.c: Ditto.
-
-2000-06-21  Zack Weinberg  
-
-	* libU77/dtime_.c, libU77/etime_.c: Include stdlib.h if
-	HAVE_STDLIB_H is defined.
-
-2000-06-11  Herman A.J. ten Brugge  
-
-	* rdfmt.c (rd_L): Use if-then-else instead of case statement to
-	solve problems when sizeof(char) == sizeof(short).
-
-2000-05-18  Chris Demetriou  
-
-	* configure.in: Test for __g77_integer, __g77_uinteger,
-	__g77_longint, and __g77_ulongint builtin types, rather
-	than mucking around with compiler headers.
-	* configure: Regenerate.
-	* g2c.hin (integer, logical, flag, ftnlen, ftnint): Use
-	__g77_integer rather than autoconfigured value.
-	(uinteger): Use __g77_uinteger rather than autoconfigured value.
-	(longint): Use __g77_longint rather than autoconfigured value.
-	(ulongint): Use __g77_ulongint rather than autoconfigured value.
-
-Sun Mar 12 20:12;30 2000  Toon Moene  
-	Based on work done by David M. Gay (Bell Labs)
-
-	* libF77/configure.in: Define IEEE_COMPLEX_DIVIDE.
-	* libF77/[cz]_div.c: Arrange for compilation under
-	-DIEEE_COMPLEX_DIVIDE to make these routines
-	avoid calling sig_die when the denominator vanishes.
-	* libF77/s_rnge.c: Add casts for the case of
-	sizeof(ftnint) == sizeof(int) < sizeof(long).
-	* libI77/endfile.c: Set state to writing (b->uwrt = 1) when an
-	endfile statement requires copying the file
-	Also, supply a missing (long) cast in the sprintf call.
-	* libI77/sfe.c: Add #ifdef ALWAYS_FLUSH logic, for formatted I/O.
-
-Wed Feb 16 11:10:05 2000  Kaveh R. Ghazi  
-
-	* configure.in (gcc_version): When setting, narrow search to
-	lines containing `version_string'.
-
-Tue Nov 16 20:39:42 1999  Geoffrey Keating  
-
-	* libU77/u77-test.f (wd): Allow for longer working directory
-	pathnames.
-
-1999-10-14 Theo Papadopoulo  
-
-	* libU77/acconfig.h: Define GETTIMEOFDAY_ONE_ARGUMENT and
-	HAVE_TIMEZONE in acconfig.h.
-	* libU77/config.hin: Rebuilt.
-
-1999-10-12  Dave Love  
-
-	* libU77/aclocal.m4: Re-write, defining LIBU77_GETTIMEOFDAY, not
-	LIBU77_HAVE_STRUCT_TIMEZONE.
-
-	* libU77/configure.in: Use LIBU77_GETTIMEOFDAY, not
-	LIBU77_HAVE_STRUCT_TIMEZONE.  Don't check for gettimeofday
-	separately.
-
-	* libU77/datetime_.c (G77_date_and_time_0): Use
-	GETTIMEOFDAY_ONE_ARGUMENT.
-
-Tue Sep 14 01:44:01 1999  Marc Espie 
-
-	* Makefile.in:  Prepend $(SHELL) to move-if-change calls.
-
-Fri Aug  6 23:32:29 1999  Daniel Jacobowitz 
-
-	* Makefile.in (FLAGS_TO_PASS): Include prefix, exec_prefix,
-	libdir, libsubdir and tooldir.
-
-Wed Jul  7 15:58:16 1999  Craig Burley  
-
-	* libU77/date_.c (G77_date_y2kbug_0): G77_time_0 returns
-	longint, not integer, and G77_ctime_0 takes longint, not
-	integer, argument.
-
-	* libU77/Version.c: Bump version.
-
-Mon Jun 28 21:27:08 1999  Craig Burley  
-
-	Update to Netlib version of 1999-06-28:
-	* changes.netlib, libI77/Version.c, libI77/rsne.c
-	readme.netlib: See changes.netlib for info.
-
-Fri Jun 18 11:38:07 1999  Craig Burley  
-
-	* libU77/ttynam_.c: if !defined (HAVE_TTYNAM),
-	write all spaces into return value instead of trying
-	to return -1 from a void function.
-
-Fri Jun 18 11:22:21 1999  Craig Burley  
-
-	Update to Netlib version of 1999-05-10:
-	* changes.netlib, libI77/Version.c, libI77/backspace.c
-	readme.netlib: See changes.netlib for info.
-
-Fri Jun 18 11:15:24 1999  Craig Burley  
-
-	* libI77/backspace.c: Undo Wednesday's change, in
-	preparation for slightly different Netlib change.
-
-Wed Jun 16 11:38:58 1999  Craig Burley  
-
-	From Ian Watson  1999-06-12:
-	* libI77/backspace.c: Reload file descriptor after
-	calling t_runc.
-	* libI77/Version.c: Bump libg2c version.
-
-Wed May 26 14:26:35 1999  Craig Burley  
-
-	* libF77/Version.c, libI77/Version.c, libU77/Version.c:
-	Use 0.5.24 to designate the version of g77 within GCC 2.95.
-
-Thu May 20 03:20:59 1999  Jeffrey A Law  (law@cygnus.com)
-
-	* configure.in (AC_EXEEXT): Remove call.
-	(compiler_name): Explicitly check with no extension and .exe
-	extension.
-	* configure: Regenerate.
-
-Mon May 10 17:33:45 1999  Craig Burley  
-
-	Update to Netlib version of 1999-05-10:
-	* changes.netlib, libF77/Version.c, libF77/abort_.c,
-	libF77/c_log.c, libF77/ef1asc_.c, libF77/s_rnge.c,
-	libF77/s_stop.c, libI77/Version.c, libI77/open.c,
-	readme.netlib: See changes.netlib for info.
-
-Fri May 7 9:33:55 1999 Donn Terry (donn@interix.com)
-
-	* libU77/dtime_.c (G77_dtime_0): Standard-conforming error check.
-	* libU77/etime_.c (G77_etime_0): Likewise.
-
-Mon May  3 19:15:07 1999  Craig Burley  
-
-	* libU77/u77-test.f (main): Declare ABORT as intrinsic.
-
-1999-05-03  Craig Burley  
-
-	* libU77/u77-test.f: Reverse order of two arguments to
-	CTIME_subr, DTIME_subr, ETIME_subr, and TTYNAM_subr.
-
-Mon May  3 11:21:35 1999  Craig Burley  
-
-	* libF77/c_log.c: Cope with partial overlap a la z_log.c.
-	(Change likely to be made to netlib version shortly.)
-
-Mon May  3 11:12:38 1999  Craig Burley  
-
-	Update to Netlib version of 1999-05-03:
-	* changes.netlib, libF77/Version.c, libF77/c_cos.c,
-	libF77/c_exp.c, libF77/c_sin.c, libF77/d_cnjg.c,
-	libF77/dtime_.c, libF77/etime_.c, libF77/getenv_.c,
-	libF77/r_cnjg.c, libF77/z_cos.c, libF77/z_exp.c,
-	libF77/z_log.c, libF77/z_sin.c, libI77/Version.c,
-	libI77/err.c, libI77/open.c, libI77/rdfmt.c, readme.netlib:
-	See changes.netlib for info.
-
-Mon May  3 10:52:53 1999  Craig Burley  
-
-	* libF77/c_cos.c, libF77/c_div.c, libF77/c_exp.c, libF77/c_log.c,
-	libF77/c_sin.c, libF77/c_sqrt.c, libF77/d_cnjg.c, libF77/pow_zi.c,
-	libF77/r_cnjg.c, libF77/z_cos.c, libF77/z_div.c, libF77/z_exp.c,
-	libF77/z_log.c, libF77/z_sin.c, libF77/z_sqrt.c: Revert back to
-	netlib versions as of f2c-19990501.
-
-Sun May  2 01:38:50 1999  Craig Burley  
-
-	* libU77/u77-test.f (main): Declare FTELL as intrinsic.
-
-Sun May  2 01:13:37 1999  Craig Burley  
-
-	* libU77/u77-test.f (main): List libU77 intrinsics
-	not currently tested.
-	Add tests for TIME8, CTIME_subr, IARGC, TTYNAM_subr,
-	GETENV, FDATE_subr, DTIME_subr, ETIME_subr, DATE, ITIME,
-	FTELL_subr, MCLOCK, MCLOCK8, and CPU_TIME.
-	Trim blanks off the ends of some printed strings.
-
-Sun May  2 00:06:45 1999  Craig Burley  
-
-	* libU77/u77-test.f (main): Just warn about FSTAT gid
-	disagreement, as it's expected on some systems.
-
-Sat May  1 23:57:18 1999  Craig Burley  
-
-	* libU77/u77-test.f: Generalize sum-checking to
-	use a new function, which allows for some slop.
-	Clean up some commentary.
-	(issum): The new function.
-	(sgladd): Deleted subroutine.
-
-Sat May  1 23:35:18 1999  Craig Burley  
-
-	* libU77/u77-test.f: Modify to be more like testsuite
-	version, bringing patches to that version here.
-	Add suitable commentary.
-
-Sat Apr 24 11:02:48 1999  Craig Burley  
-
-	* Makefile.in (s-libi77, s-libf77, s-libu77): Revert
-	the patch from , as per the commentary.
-
-Sat Apr 17 17:33:30 1999  Craig Burley  
-
-	From H.J. Lu :
-	* Makefile.in (s-libi77): Depend on i77.
-	(s-libf77): Depend on i77.
-	(s-libu77): Depend on u77.
-
-Mon Apr 12 21:38:14 1999  Mumit Khan  
-
-	* libF77/getenv_.c: Include stdlib.h.
-
-Sun Apr 11 23:30:42 1999  Mumit Khan  
-
-	* libU77/dtime_.c: Handle all variants of WIN32.
-	* libU77/etime_.c: Likewise.
-
-	* libU77/aclocal.m4: New file.
-	* libU77/configure.in (LIBU77_HAVE_STRUCT_TIMEZONE): Add test.
-	* libU77/acconfig.h (HAVE_STRUCT_TIMEZONE): Add macro.
-	* libU77/datetime_c.c (G77_date_and_time_0): Use.
-	* libU77/config.hin: Regenerate.
-	* libU77/configure: Likewise.
-
-Wed Mar 31 13:50:24 1999  Kaveh R. Ghazi  
-
-	* configure.in (extra_includes): Don't attempt to calculate the
-	location of the gcc src or obj directories.  Instead rely on
-	precomputed variables, $topsrcdir and $r, to obtain these values.
-	Set -I flags appropriately.
-
-1999-03-28  Dave Love  
-
-	* configure: Rebuilt.
-
-	* configure.in: Fix integer size tests: sanity check first; search
-	toplevel include dir (from Rainer Orth); only mess with ac_cpp
-	once; use -DIN_GCC -DHAVE_CONFIG_H.
-
-	* configure.in: Use `g77_cv_...', not `f77_cv_...'.
-
-Wed Mar 24 22:41:28 1999  Mumit Khan  
-
-	* configure.in (AC_PREREQ): Update to 2.13.
-	(AC_EXEEXT): Call to find possible file extension.
-	(compiler_name): Use.
-	* configure: Regenerate.
-
-1999-03-17  Craig Burley  
-
-	Update to Netlib version of 1999-03-17:
-	* libF77/F77_aloc.c, libF77/README.netlib, libF77/dtime_.c,
-	libF77/etime_.c, libF77/signal1.h0, libI77/Version.c,
-	libI77/dfe.c, libI77/endfile.c, libI77/lread.c,
-	libI77/sfe.c, readme.netlib, changes.netlib:
-	See changes.netlib for info.
-
-1999-03-06  Craig Burley  
-
-	Mon Dec 21 23:03:54 1998 Hans-Peter Nilsson :
-	* libI77/Makefile.in (all *.o except VersionI.o): Added dependence
-	on respective .c file.
-	* libF77/Makefile.in (all .o except VersionF.o): Similarly.
-	* libU77/Makefile.in (date_.o): Added dependence on date_.c
-
-1999-03-06  Craig Burley  
-
-	Rename non-Y2K-compliant intrinsics:
-	* Makefile.in (F2CEXT): Now two versions each of
-	`date' and `vxtidt'.
-	* f2cext.c (date_, vxtidate_): Split into two versions,
-	the existing one calling a new "y2kbuggy" routine that
-	does not exist, and a new one named with "y2kbug" that
-	calls the newly renamed underlying routine.
-	* libU77/date_.c (G77_date_y2kbug_0): Rename from G77_date_0.
-	* libU77/vxtidate_.c (G77_vxtidate_y2kbug_0): Rename from
-	G77_vxtidate_0.
-	* libU77/Version.c: Bump version.
-
-1999-03-03  Craig Burley  
-
-	* libU77/vxtidate_.c (G77_vxtidate_0): Truncate
-	year to last two digits (i.e. modulo 100), as per
-	documentation and (documented) Y2K non-compliance.
-
-1999-02-20  Craig Burley  
-
-	From Krister Walfridsson :
-	* libU77/lstat_.c (G77_lstat_0): Kill spurious setting
-	of element 6 to zero, as it undid the previous setting.
-
-1999-02-15  Craig Burley  
-
-	* f2c.h: Delete my (old) email address.
-
-1999-02-14  Craig Burley  
-
-	* libU77/Version.c: Bump ("update" below) to date of last change.
-	* libI77/Version.c: Bump to date of last change.
-
-Tue Feb  9 18:13:30 GMT 1999  Nathan Sidwell  
-
-	* Makefile.in (distclean): Move Makefile deletion to end of
-	commands.
-
-1999-01-15  Dave Love  
-
-	* libU77/datetime_.c (G77_date_and_time_0): Return milliseconds as
-	such, not as microseconds.
-	(s_copy): Declare.
-
-1998-11-26  Manfred Hollstein  
-
-	* configure.in (compiler_name): Add check to detect if this
-	language's compiler has been built.
-	* configure: Regenerate.
-
-Mon Nov 23 16:52:22 1998  Kaveh R. Ghazi  
-
-	* configure.in: Use AC_PREREQ(2.12.1).
-	* libF77/configure.in: Likewise.
-	* libI77/configure.in: Likewise.
-	* libU77/configure.in: Likewise.
-
-1998-10-24  Dave Love  
-
-	* configure.in: Touch g2c.h in AC_OUTPUT after multilib
-	disturbance.
-
-1998-10-23  Dave Love  
-
-	* f2cext.c: Include math.h.
-
-1998-10-19  Dave Love  
-
-	* configure: Regenerate.
-
-	* configure.in: Use AC_CONFIG_AUX_DIR.
-
-1998-10-12  Dave Love  
-
-	* libI77/open.c (_XOPEN_SOURCE): Define.
-
-1998-10-12  Dave Love  
-
-	* Makefile.in (.SUFFIXES): Don't use any.
-	(all-unilib): New target, like old all.
-	(all): Use it.
-	(.PHONY): Add all-unilib.
-
-1998-10-12  Dave Love  
-
-	* configure.in: Reorder Makefile, g2c.h in AC_OUTPUT.
-
-Tue Oct  6 21:16:58 1998  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in: Revert last patch.
-
-Mon Oct  5 01:16:10 1998  H.J. Lu  (hjl@gnu.org)
-
-	* Makefile.in (s-libi77): Depend on i77.
-	(s-libf77): Depend on i77.
-	(s-libu77): Depend on u77.
-
-1998-09-30  Dave Love  
-
-	* Makefile.in (f2cext.c): Depend on g2c.h.
-
-1998-09-30  Robert Lipe  
-
-	* Makefile.in (all): Correct dependencies so --disable-multilibs
-	works again.
-	(distclean): Correct typo.
-
-1998-09-28  Dave Love  
-
-	* libI77/open.c: Back out part of last Netlib update affecting
-	scratch files which clashed with the g77 variations and broke
-	implicit endfile on rewind.
-
-1998-09-21  Dave Love  
-
-	* libI77/Version.c: Update.
-
-Mon Sep 21 12:27:27 1998  Robert Lipe  
-
-	* Makefile.in (distclean, clean, uninstall, install, all): Add
-	multilib support.
-	* configure.in: Likewise.
-	* configure: Regenerate.
-	* libF77/Makefile.in, libU77/Makefile.in, libI77/Makefile.in (clean):
-	Explictly remove stamp in parent's directory.
-
-1998-09-20  Dave Love  
-
-	* libI77/sfe.c (e_wdfe): Set f__init to avoid spurious recursive
-	i/o error from formatted direct i/o.
-
-Thu Sep 10 14:57:25 1998  Kamil Iskra  
-
-	* Makefile.in (install): Add missing "else true;".
-
-1998-09-09  Craig Burley  
-
-	* configure.in: Test $srcdir, not $subdir (probable typo).
-	Clarify commentary, fix a bit of spacing.
-
-1998-09-07  Dave Love  
-
-	* ChangeLog.egcs: Deleted.  Entries merged here.
-
-1998-09-07  Dave Love  
-
-	* libI77/sfe.c, libI77/dfe.c: Revert last change.
-
-1998-09-06  Dave Love  
-
-	From Toon to fix spurious recursive i/o errors:
-	* libI77/sfe.c (e_wdfe): Set f__init.
-
-	* libI77/dfe.c (c_dfe): Check and set f__init.
-	(s_rdfe, s_wdfe): Don't check and set f__init.
-
-Fri Sep  4 18:40:32 1998  Craig Burley  
-
-	* libU77/sys_clock_.c (G77_system_clock_0): Fix indentation.
-
-Tue Sep  1 10:06:06 1998  Craig Burley  
-
-	* libF77/Version.c: Update.
-	* libU77/Version.c: Update.
-	* libI77/Version.c: Update.
-
-Wed Aug 26 23:19:40 1998  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in (FLAGS_TO_PASS): Fix typo.
-
-1998-08-11  Dave Love  
-
-	* README: Update from Craig.
-
-1998-07-24  Dave Love  
-
-	* Makefile.in (s-libe77, ${srcdir}/configure, g2c.h, Makefile)
-	(config.status, rebuilt): Rely on VPATH, dropping explicit use of
-	$(srcdir) in various places.
-
-1998-07-19  Dave Love  
-
-	* Makefile.in (all): Depend on s-libe77, not e77.
-	(.PHONY): Remove e77.
-
-Thu Jul 16 00:58:52 1998  Jeffrey A Law  (law@cygnus.com)
-
-	* libU77/Makefile.in: Missed one config.h.in -> config.hin change.
-
-	* g2c.hin: Renamed from g2c.h.in.
-	* Makefile.in, configure.in: Changed as needed.
-	* configure: Rebuilt.
-
-	* libU77/config.hin: Renamed from libU77/config.h.in.
-	* Makefile.in, configure.in: Changed as needed.
-	* configure: Rebuilt.
-
-Tue Jul 14 21:35:30 1998  Gerald Pfeifer  
-
-	* Makefile.in (all): Invoke $(MAKE) instead of just make.
-
-Tue Jul 14 02:16:34 1998  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in: stamp-lib* -> s-lib*.
-	* libU77/Makefile.in: Likewise.
-	* libF77/Makefile.in: Likewise.
-	* libI77/Makefile.in: Likewise.
-
-	* libU77/Makefile.in (ALL_CFLAGS): Add -I$(F2C_H_DIR).
-
-Mon Jul 13 13:31:03 1998  Craig Burley  
-
-	* libU77/u77-test.f: Double-check ETIME results, just
-	like 0.5.24 does.
-
-1998-07-10  Dave Love  
-
-	* Makefile.in: Re-write build procedure mainly to honour
-	dependencies correctly but also allow making in the build
-	directory by configuring the relevant variables.  The lib[FIU]77
-	subdirs do dependency checking of their objects.  Stamp files
-	dictate when to run (new) archive targets in subdirs.  Some
-	tidying of variables.  Supply full set of standard targets.
-
-	* configure.in: Move much of testing to new configures in
-	subdirs.  Tidy up handling of RANLIB etc.
-
-	* stamp-h.in, libF77/configure.in, libI77/configure.in:
-	* libF77/configure, libI77/configure: New files.
-
-	* libF77/Makefile.in, libI77/Makefile.in, libU77/Makefile.in:
-	Change in step with libf2c/Makefile.in.
-
-1998-07-09  Dave Love  
-
-	* libU77/Makefile.in (check): Wrap -lg2c ... -lm around $(LIBS) in
-	case of static link.
-
-	* libU77/Version.c, libI77/Version.c: Update version info.
-
-	* libU77/sys_clock_.c: Replace TIMES conditional stuff removed in
-	error by last change.
-
-1998-07-06  Mike Stump  
-
-	* Makefile.in (clean): Don't remove Makefiles, that is done in
-	distclean.
-
-1998-07-06  Dave Love  
-
-	* libU77/Makefile.in (lib): Change variable lib to LIBS.
-
-1998-07-06  Robert Lipe 
-
-	* libU77/configure.in: Look for -lsocket, add to LIBS if found.
-
-	* libU77/Makefile.in (lib):  Use LIBS from above.
-
-1998-07-05  Dave Love  
-
-	* f2cext.c (system_clock_): Remove (just f90 intrinsic).
-
-	* Makefile.in (F2CEXT): Remove sclock.
-	(UOBJ): Add libU77/datetime_.o.
-
-	* libU77/config.h.in: Add HAVE_GETTIMEOFDAY.
-
-	* libU77/configure.in: Check for gettimeofday.
-
-	* libU77/datetime_.c: New file.
-
-	* libU77/sys_clock_.c: Allow optional args.
-
-	* libU77/Makefile.in (G77DIR): Fix for current directory
-	structure.
-	(SRCS, OBJS): Add datetime.
-
-	* libU77/u77-test.f: Call date_and_time.  Call system_clock
-	omitting args.
-
-1998-06-29  Dave Love  
-
-	* libI77/wsfe.c (s_wsfe): Fix setting of f__curunit lost in
-	previous change.
-	* libI77/rsfe.c (s_rsfe): Likewise.
-
-Sat Jun 27 23:04:49 1998  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in (FLAGS_TO_PASS, case G2C_H_DIR): Use $(TARGET_SUBDIR)
-	instead of hardcoding "libraries".
-
-1998-06-26  Manfred Hollstein  
-
-	* Makefile.in (gcc_version_trigger): Add new macro.
-	(config.status): Add dependency upon $(gcc_version_trigger).
-
-	* configure.in (gcc_version_trigger): New variable; initialize
-	using value from toplevel configure; add AC_SUBST for it.
-	(gcc_version): Change initialization to use this new variable.
-	* configure: Regenerate.
-
-1998-06-24  Manfred Hollstein  
-
-	* Makefile.in (version): Rename to gcc_version.
-	* configure.in (version): Likewise.
-	(gcc_version): Add code to use an option passed from parent configure.
-	* configure: Regenerate.
-
-1998-06-23  Dave Love  
-
-	* libI77/backspace.c, libI77/dfe.c, libI77/due.c, libI77/iio.c:
-	* libI77/lread.c, libI77/sfe.c, libI77/sue.c, libI77/wsfe.c: Update
-	to Netlib version of 1998-06-18.
-
-1998-06-21  Dave Love  
-
-	* configure.in (version, target_alias): Define.
-
-	* Makefile.in (version, target_alias, libsubdir): Define.
-	(install): Remove check for libsubdir.
-
-Sat Jun 13 03:46:40 1998  Craig Burley  
-
-	* Makefile.in (install): Don't install if $(libsubdir)
-	is empty; issue a diagnostic saying top-level Makefile
-	must pass it in instead, and exit.
-
-	* Makefile.in (g2c.h): Rename from f2c.h.
-
-	* Makefile.in, libF77/Makefile.in, libI77/Makefile.in:
-	* libU77/Makefile.in: Rewrite config and var assignment
-	sections to be even more minimal than before, and to
-	more clearly documented what macros are expected to be
-	set and to what sorts of values.  Eliminate CROSS and
-	related stuff, since there's no such things as CROSS
-	in egcs.  Rename GCC_FOR_TARGET to CC throughout.
-	* Makefile.in (stamp-libi77, stamp-libf77, stamp-libu77):
-	Eliminate CROSS.
-	* configure.in: Eliminate CROSS.
-
-	Rename libf2c.a and f2c.h to libg2c.a and g2c.h,
-	normalize and simplify g77/libg2c build process:
-	* Makefile.in: Remove all stuff pertaining to
-	installation, cleaning, and so on.  Parent Makefile
-	does all that now.  Pass F2C_H_DIR,
-	G2C_H_DIR, and GCC_H_DIR, the pathnames for the
-	directories containing f2c.h, g2c.h, and other
-	#include files, to subdirectory Makefiles.
-	(stamp-libf77, stamp-libi77, stamp-libu77):
-	Don't specify `-f Makefile' anymore, it's not needed
-	now that subdirectory makefile's from netlib are
-	renamed to makefile.netlib in g77 source (and to
-	makefile.ori by configuration process, in case they're
-	still around somehow).
-	(stamp-libe77): Don't make libE77 dir unless it doesn't
-	exist, if it does just delete all objects in it.
-	Compile using $(GCC_FOR_TARGET), not $(CC).
-	(rebuilt): Remove this and all subordinate targets,
-	as parent Makefile now handles all that.
-	(*clean): Remove.
-	* configure.in (Pad_UDread, ALWAYS_FLUSH, WANT_LEAD_0):
-	Remove these and commentary to new f2c.h file.
-	AC_OUTPUT g2c.h instead of f2c.h.  Remove old commentary
-	regarding concatenation.
-	* g2c.h.in: Rename from f2c.h.in, add appropriate
-	commentary.
-	* f2c.h: New file, a wrapper for g2c.h that does
-	libg2c-specific stuff.
-	* libF77/Makefile.in, libI77/Makefile.in, libU77/Makefile.in:
-	Change $(ALL_CFLAGS) to use F2C_H_DIR, G2C_H_DIR, and GCC_H_DIR
-	macros.  Remove F2C_H macro, replace use with explicit
-	dependencies on f2c.h and g2c.h.
-	(*clean): Remove.
-
-Mon Apr 27 22:52:31 1998  Richard Henderson  
-
-	* libU77/ltime_.c: Bounce the ftnint argument through a local time_t.
-	* libU77/gmtime_.c: Likewise.
-
-Sun Apr 26 18:07:56 1998  Richard Henderson  
-
-	* configure.in: Adjust include paths in F2C_INTEGER and F2C_LONGINT
-	tests to work out of the build directory.
-
-1998-05-20  Dave Love  
-
-	* Makefile.in ($(lib)): Use shell loop instead of unportable
-	make variable substitution.
-
-Tue May 19 12:50:27 1998  Craig Burley  
-
-	Break up main() into separate .o's so making and
-	linking against shared libraries with non-Fortran
-	main() routines is easier:
-	* Makefile.in (MISC): Add setarg.o and setsig.o.
-	* libF77/Makefile.in (MISC): Ditto.
-	* libF77/setarg.c: New file, contains f_setarg().
-	* libF77/setsig.c: New file, contains f_setsig().
-	* libF77/getarg_.c: Rename xarg* to f__xarg*.
-	* libF77/iargc_.c: Ditto
-
-Sat May  2 16:44:46 1998  Craig Burley  
-
-	* libF77/signal_.c, libI77/dfe.c, libI77/due.c,
-	libI77/wsfe.c: Tweaks to eliminate unnecessary
-	differences vs. netlib libf2c.
-
-Fri May  1 11:57:45 1998  Craig Burley  
-
-	Update to Netlib version of 1998-04-20:
-	* libF77/dtime_.c, libF77/etime_.c, libF77/h_dnnt.c,
-	libF77/h_nint.c, libF77/i_dnnt.c, libF77/i_nint.c,
-	libF77/main.c, libF77/s_paus.c, libF77/signal1.h0,
-	libI77/backspace.c, libI77/close.c, libI77/dfe.c,
-	libI77/endfile.c, libI77/err.c, libI77/fio.h,
-	libI77/iio.c, libI77/ilnw.c, libI77/lread.c,
-	libI77/lwrite.c, libI77/open.c, libI77/rawio.h,
-	libI77/sfe.c, libI77/util.c, libI77/wrtfmt.c,
-	libI77/wsfe.c, libI77/wsle.c, libI77/wsne.c:
-	See changes.netlib for info.
-
-Sun Apr 26 09:13:41 1998  Craig Burley  
-
-	* libU77/hostnm_.c (G77_hostnm_0): Fix off-by-one error
-	that was trashing the byte just beyond the CHARACTER*(*)
-	argument.
-
-Wed Mar  4 16:32:46 1998  Craig Burley  
-
-	* libU77/u77-test.f: Don't bother declaring etime.
-	Use `implicit none' and declare mask and lenstr.
-	Do ETIME/DTIME consistency check before loop, then
-	use loop to verify that dtime "ticks" at some point.
-	Check ETIME array-sum using single-precision add, to
-	avoid spurious complaint on systems (like x86) that
-	use more precision for intermediate results.
-	Fix `Results of ETIME and DTIME...' message to print
-	pertinent values (r1 and r2 instead of i and j).
-	Change loop from 10M to 1K repeated up to 1000 times
-	or until dtime "ticks".
-	Print the number of 1K loops needed to see this tick.
-	Answer a commented question.
-	Split up a long line of output and do other prettying.
-	Preset lognam in case GETLOG fails to overwrite it.
-
-Sat Feb 28 15:32:15 1998  Craig Burley  
-
-	* libI77/open.c (f_open): Use sizeof(buf) instead of
-	256, for the usual reasons.
-
-1998-02-17  Dave Love  
-
-	* libU77/u77-test.f: Tweak some o/p.
-
-	* libU77/Makefile.in (check): Use -L for new directory structure.
-
-	* Makefile.in (check): Run the u77 check.
-	(config.status,	Makefile): New targets.
-
-Wed Feb 11 01:46:20 1998  Manfred Hollstein 
-
-	* Makefile.in ($(lib)): Call $(AR) repeatedly to avoid overflowing
-	argument size limit on ancious System V.
-
-Sun Feb  8 00:32:17 1998  Manfred Hollstein  
-
-	* Makefile.in: Add `info install-info clean-info check dvi' targets.
-
-Mon Feb  2 11:08:49 1998  Richard Henderson  
-
-	* configure.in: Update F2C_INTEGER and F2C_LONGINT tests
-	for the new placement in the hierarchy.
-
-Sun Feb  1 02:36:33 1998  Richard Henderson  
-
-	* Previous contents of gcc/f/runtime moved into toplevel
-	"libf2c" directory.
-
-Sun Feb  1 01:42:47 1998  Mumit Khan 
-
-	* libU77/configure.in (getlogin,getgid,getuid, kill,link,ttyname):
-	Check.
-	* libU77/config.h.in (HAVE_GETLOGIN, HAVE_GETGID, HAVE_GETUID,
-	HAVE_KILL, HAVE_LINK, HAVE_TTYNAME): New defs.
-	* libU77/getlog_.c: Conditionalize for target platform. Set errno
-	to ENOSYS if target libc doesn't have the function.
-	* libU77/getgid_.c: Likewise.
-	* libU77/getuid_.c: Likewise.
-	* libU77/kill_.c: Likewise.
-	* libU77/link_.c: Likewise.
-	* libU77/ttynam_.c: Likewise.
-
-Sun Jan 18 20:01:37 1998  Toon Moene  
-
-	* libI77/backspace.c: (f_back): Use type `uiolen' to determine size
-	of record length specifier.
-
-Sat Jan 17 22:40:31 1998  Mumit Khan 
-
-	* libU77/configure.in (sys/param.h,sys/times.h): Check.
-	(times,alarm): Likewise.
-	* libU77/config.h.in (HAVE_SYS_PARAM_H, HAVE_SYS_TIMES_H)
-	(HAVE_ALARM, HAVE_TIMES): New defs.
-	* libU77/alarm_.c: Conditionalize for target platform. Set errno
-	to ENOSYS if target libc doesn't have the function.
-	* libU77/dtime_.c: Likewise.
-	* libU77/etime_.c: Likewise.
-	* libU77/sys_clock_.c: Likewise.
-
-	* configure.in (NON_UNIX_STDIO): Define if MINGW32.
-	(NON_ANSI_RW_MODE): Do not define for CYGWIN32 or MINGW32.
-
-	* libI77/rawio.h: Don't providing conflicting declarations for
-	read() and write(). MINGW32 header files use "const" quals.
-
-	* libF77/s_paus.c: _WIN32 does not have pause().
-
-Mon Apr 27 22:52:31 1998  Richard Henderson  
-
-	* libU77/ltime_.c: Bounce the ftnint argument through a local time_t.
-	* libU77/gmtime_.c: Likewise.
-
-Sun Apr 26 18:07:56 1998  Richard Henderson  
-
-	* configure.in: Adjust include paths in F2C_INTEGER and F2C_LONGINT
-	tests to work out of the build directory.
-
-Tue Dec 23 22:56:01 1997  Craig Burley  
-
-	* libF77/signal_.c (G77_signal_0): Return type is
-	now `void *', to cope with returning previous signal
-	handler on 64-bit systems like Alphas.
-	* f2cext.c (signal_): Changed accordingly.
-
-Tue Nov 18 09:49:04 1997  Mumit Khan   (khan@xraylith.wisc.edu)
-
-	* libI77/close.c (f_exit): Reset f__init so that f_clos does not
-	(incorrectly) think there is an I/O recursion when program is
-	interrupted.
-
-Sat Nov  1 18:03:42 1997  Jeffrey A Law  (law@cygnus.com)
-
-	* libF77/signal_.c: Undo last change until we can fix it right.
-
-Wed Oct 29 01:01:04 1997  Mumit Khan  
-
-	* configure.in: Set CC to CC_FOR_TARGET when cross-compiling.
-
-Fri Oct 24 11:15:22 1997  Mumit Khan 
-
-	* libI77/close.c (f_exit): Reset f__init so that f_clos does not
-	(incorrectly) think there is an I/O recursion when program is
-	interrupted.
-
-Wed Oct 15 10:06:29 1997  Richard Henderson  
-
-	* libF77/signal_.c (G77_signal_0): Make return type sig_pf as well.
-	* libI77/fio.h: Include  if STDC_HEADERS.
-	* libU77/chmod_.c: Likewise.
-
-Tue Oct  7 18:22:10 1997  Richard Henderson  
-
-	* Makefile.in (CGFLAGS): Don't force -g0.
-	* libF77/Makefile.in, libI77/Makefile.in, libU77/Makefile.in: Likewise.
-
-Mon Oct  6 14:16:46 1997  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in (distclean): Do a better job at cleaning up.
-
-1997-10-03  Dave Love  
-
-	* configure.in: Check for tempnam (best because it obeys TMPDIR).
-	* libI77/open.c: Use it.
-	* libI77/err.c: New message # 132.
-
-Wed Oct  1 01:46:16 1997  Philippe De Muyter  
-
-	* libU77/sys_clock_.c: File renamed from system_clock_.c.
-	* libU77/Makefile.in, Makefile.in : Reference sys_clock_.*, not
-	system_clock_.*.
-	* libU77/dtime_.c (clk_tck): Try also HZ macro.
-	* libU77/access.c (G77_access_0): Check malloc return value against 0,
-	not NULL.
-	* libU77/getlog_.c, libU77/ttynam_.c, libU77/chdir_.c: Ditto.
-	* libU77/chmod_.c, libU77/rename_.c: Ditto.
-
-Tue Sep 30 00:41:39 1997  Craig Burley  
-
-	Do a better job of printing the offending FORMAT string
-	when producing a diagnostic:
-	* libI77/err.c (f__fmtlen): New variable to hold operating
-	length of format string.
-	(f__fatal): Use new variable to limit length of printed string.
-	* libI77/fmt.c (f_s): Don't skip spaces after closing paren,
-	so nicer message results (and nested case already skips them).
-	(pars_f): Record operating length of format string as indicated
-	by a successful call to f_s, or ad-hoc-calculate it if failure,
-	limiting the length to 80 characters (and stopping at NUL).
-	(do_fio): Use new variable to limit length of printed string.
-	* libI77/fmt.h (f__fmtlen): Declare new variable.
-	* libI77/lread.c (c_le): Set new variable to known length.
-
-Mon Sep 29 16:30:31 1997  Craig Burley  
-
-	Update to Netlib version of 1997-09-23:
-	* libF77/dtime_.c (dtime_), libF77/etime_.c (dtime_):
-	Return `double' instead of `float' (these are not used
-	in g77's version of libf2c).
-	* libI77/fmt.c, libI77/fmt.h, libI77/rdfmt.c, libI77/wrtfmt.c:
-	Support machines with 64-bit pointers and 32-bit ints (e.g.
-	Linux on DEC Alpha).
-
-1997-09-19  Dave Love  
-
-	* libU77/dtime_.c (G77_dtime_0): Fix types in HAVE_GETRUSAGE case
-	so as not to truncate results to integer values.
-	* libU77/Version.c: Bump.
-
-Thu Sep 18 16:58:46 1997  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in (stamp-lib): Don't use '$?', explicitly
-	list the variables containing the object files to include
-	in libf2c.a
-
-Tue Sep  9 00:33:24 1997  Craig Burley  
-
-	* Version 0.5.21 released.
-
-Mon Sep  8 19:39:01 1997  Craig Burley  
-
-	* libI77/close.c (f_exit): Fix thinko, inverted test
-	of whether initialization done, so exiting now closes
-	open units again.
-
-Fri Sep  5 00:18:17 1997  Jeffrey A Law  (law@cygnus.com)
-
-	* Makefile.in (clean): Don't remove config.cache.
-	(distclean): Do it here instead.
-
-Tue Aug 26 20:14:08 1997  Robert Lipe  (robertl@dgii.com)
-
-	* hostnm_.c: Include errno.h
-
-Tue Aug 26 01:42:21 1997  Craig Burley  
-
-	From Jim Wilson:
-	* configure.in: Make sure RANLIB_TEST is set also.
-
-	From Robert Lipe :
-	* libU77/getcwd_.c, libU77/hostnm_.c, libU77/lstat_.c:
-	Also #include , to define ENOSYS.
-
-Tue Aug 26 01:25:58 1997  Craig Burley  
-
-	* Makefile.in (stamp-lib): Put all f2cext.c objects in
-	a temp directory named libE77, then `ar' them all at
-	once into libf2c.a, to get the job done a bit faster.
-	Still remove the objects (and libE77 directory) afterward.
-
-Mon Aug 25 23:26:05 1997  H.J. Lu  (hjl@gnu.ai.mit.edu)
-
-	* Makefile.in (mostlyclean, clean): Check if Makefile exists
-	before using it. Remove stamp-*.
-	(stamp-libi77, stamp-libf77, stamp-libu77): New.
-	(stamp-lib): Only depend on stamp-libi77 stamp-libf77
-	stamp-libu77
-
-Sun Aug 24 05:04:35 1997  Craig Burley  
-
-	* libU77/rand_.c (G77_rand_0), libU77/dtime_.c (G77_dtime_0),
-	libU77/etime_.c (G77_etime_0), libU77/secnds_.c (G77_secnds_0),
-	libU77/second_.c (G77_second_0): Really return `double', not
-	`doublereal', since the result is cast to `float'.
-	* f2cext.c: (rand_, dtime_, etime_, secnds_, second_): Ditto.
-	(erf_, erfc_, besj0_, besj1_, besjn_, besy0_, besy1_,
-	besyn_, dbesj0_, dbesj1_, dbesjn_, dbesy0_, dbesy1_,
-	dbesyn_): All of these return `double', not `doublereal',
-	as they either have `float' or `double' results.
-	* libU77/bes.c (besj0_, besj1_, besjn_, besy0_, besy1_,
-	besyn_): Ditto.
-	* libU77/dbes.c (dbesj0_, dbesj1_, dbesjn_, dbesy0_, dbesy1_,
-	dbesyn_): Ditto.
-
-	Update to Netlib version of 1997-08-16:
-	* libI77/iio.c: Fix bug in internal writes to an array
-	of character strings.
-
-	* Makefile.in (UOBJ): Restore fixes made by Dan Pettet I
-	lost, which included the addition of mclock_.o already noted
-	below, plus adding symlnk_.o.
-
-Thu Aug 21 03:58:34 1997  Craig Burley  
-
-	* Makefile.in (UOBJ): Add mclock_.o, thanks to Mumit Khan!
-
-1997-08-21  Dave Love  
-
-	* libU77/alarm_.c: Fix return type: `integer'.
-
-Mon Aug 11 20:12:42 1997  Craig Burley  
-
-	* Makefile.in ($(lib), stamp-lib): Ensure that library
-	gets fully updated even if updating was aborted earlier.
-
-	* libU77/hostnm_.c (G77_hostnm_0): Return ENOSYS and stuff
-	in errno if system has no gethostname() function.
-
-	* libU77/lstat_.c (G77_lstat_0): Return ENOSYS and stuff
-	in errno if system has no lstat() function.
-
-	* libU77/getcwd_.c (G77_getcwd_0): Return ENOSYS and stuff
-	in errno if system has no getcwd() or getwd() function.
-	Test HAVE_GETCWD properly.
-
-	* libU77/symlnk_.c (G77_symlink_0): Return ENOSYS and stuff
-	in errno if system has no symlink() function.
-
-	* libU77/mclock_.c (G77_mclock_0): Return -1 if system
-	has no clock() function.
-
-Mon Aug 11 01:55:36 1997  Craig Burley  
-
-	* Makefile.in (F2CEXT): Add `alarm' to this list.
-
-	* f2cext.c (alarm_): Fix some typos in this function.
-	Delete third `status' argument.
-
-	* libU77/alarm_.c: Delete third `status' argument,
-	as caller gets this from function result; return
-	status value as function result for caller.
-
-	* configure.in: Rename `ac_cv_struct_FILE' to
-	`g77_cv_struct_FILE' according to 1997-06-26 change.
-
-1997-08-06  Dave Love  
-
-	* libU77/vxtidate_.c: Correct day/month argument order.
-	* f2cext.c: Likewise.
-
-1997-07-07  Dave Love  
-
-	* f2cext.c: Add alarm_.
-
-	* Makefile.in, libU77/Makefile.in: Add alarm_.
-
-	* libU77/alarm_.c: New file.
-
-1997-06-26  Dave Love  
-
-	* configure.in: Generally use prefix `g77_' for cached values
-	we've invented, not `ac_'.
-
-Tue Jun 24 18:50:06 1997  Craig Burley  
-
-	* libI77/ilnw.c (s_wsni): Call f_init() here.
-	(s_wsli): Ditto.
-	(e_wsli): Turn off "doing I/O" flag here.
-
-1997-06-20  Dave Love  
-
-	* runtime/configure.in: Check for cygwin32 after Mumit Khan (but
-	differently); if cygwin32 define NON_UNIX_STDIO and don't define
-	NON_ANSI_RW_MODES.
-
-Tue Jun 01 06:26:29 1997  Craig Burley  
-
-	* libI77/rsne.c (nl_init): Don't call f_init() here,
-	since s_rsne() already does.
-	(c_lir): Call f_init() here instead.
-	* libI77/rsli.c (e_rsli): Turn off "doing I/O" flag here.
-	* libI77/sue.c (e_rsue): Ditto.
-
-Sun Jun 22 23:27:22 1997  Craig Burley  
-
-	* libI77/fio.h (err): Mark I/O as no longer in progress
-	before returning a non-zero error indicator (since
-	that tells the caller to jump over the remaining I/O
-	calls, including the corresponding `e_whatever' call).
-	* libI77/err.c (endif): Ditto.
-	* libI77/sfe.c (e_wsfe): Ditto.
-	* libI77/lread.c (ERR): Ditto.
-	* libI77/lread.c (l_read): Ditto by having quad case
-	use ERR, not return, to return non-zero error code.
-
-Sat Jun 21 12:31:28 1997  Craig Burley  
-
-	* libI77/open.c (fk_open): Temporarily turn off
-	"doing I/O" flag during f_open() call to avoid recursive
-	I/O error.
-
-Tue Jun 17 22:40:47 1997  Craig Burley  
-
-	* err.c, close.c, rewind.c, inquire.c, backspace.c, endfile.c,
-	iio.c, open.c, Version.c, sfe.c, wsle.c, rsne.c, sue.c, rsfe.c,
-	lread.c, wsfe.c, fio.h, due.c, dfe.c: Change f__init from
-	`flag' to `int' and to signal not just whether initialization
-	has happened (bit 0), but also whether I/O is in progress
-	already (bit 1).  Consistently produce a clear diagnostic
-	in cases of recursive I/O.  Avoid infinite recursion in
-	f__fatal, in case sig_die triggers another error.  Don't
-	output info on internals if not initialized in f__fatal.  Don't
-	bother closing units in f_exit if initialization hasn't
-	happened.
-
-Tue Jun 10 12:57:44 1997  Craig Burley  
-
-	Update to Netlib version of 1997-06-09:
-	* libI77/err.c, libI77/lread.c, libI77/rdfmt.c,
-	libI77/wref.c: Move some #include's around.
-
-Mon Jun  9 18:11:56 1997  Craig Burley  
-
-	* libU77/kill_.c (kill_): KR_headers version needed
-	`*' in front of args in decls.
-
-Sun May 25 03:16:53 1997  Craig Burley  
-
-	Update to Netlib version of 1997-05-24:
-	* libF77/README, libF77/Version.c, libF77/main.c,
-	libF77/makefile, libF77/s_paus.c, libF77/signal1.h,
-	libF77/signal_.c, libF77/z_div.c, libI77/Notice,
-	libI77/README, libI77/Version.c, libI77/dfe.c,
-	libI77/err.c, libI77/fmt.c, libI77/makefile,
-	libI77/rawio.h: Apply many, but not all, of the changes
-	made to libf2c since last update.
-	* libF77/Makefile.in (MISC), Makefile.in (MISC): Rename
-	exit.o to exit_.o to go along with Netlib.
-	* libF77/signal.c: Make the prologue much simpler than
-	Netlib has it.
-
-Sun May 18 20:56:02 1997  Craig Burley  
-
-	* libU77/unlink_.c, libU77/stat_.c, libU77/symlnk_.c,
-	libU77/chmod_.c: g_char first arg is const.
-
-	* libU77/chmod_.c: s_cat expects ftnlen[], not int[] or
-	integer[], change types of array and variables
-	accordingly.
-
-May 7 1997  Daniel Pettet  
-
-	* libU77/dbes_.c: Commented out the code in the
-	same way the bes* routines are commented out.  This
-	was done because corresponding C routines are referenced
-	directly in com-rt.def.
-
-Mon May  5 13:56:02 1997  Craig Burley  
-
-	* libU77/stat_.c: Reverse KR/ANSI decls of g_char().
-
-Apr 18 1997  Daniel Pettet  
-
-	* libF77/F77_aloc.c, libF77/abort_.c, libF77/derf_.c,
-	libF77/derfc_.c, libF77/ef1asc_.c, libF77/ef1cmc_.c,
-	libF77/erf_.c, libF77/erfc_.c, libF77/exit.c,
-	libF77/getarg_.c, libF77/getenv_.c, libF77/iargc_.c,
-	libF77/s_cat.c, libF77/signal_.c, libF77/system_.c,
-	libI77/close.c, libI77/ftell_.c, libU77/access_.c,
-	libU77/bes.c, libU77/chdir_.c, libU77/chmod_.c, libU77/ctime_.c,
-	libU77/date_.c, libU77/dbes.c, libU77/dtime_.c, libU77/etime_.c,
-	libU77/fdate_.c, libU77/fgetc_.c, libU77/flush1_.c,
-	libU77/fnum_.c, libU77/fputc_.c, libU77/fstat_.c,
-	libU77/gerror_.c, libU77/getcwd_.c, libU77/getgid_.c,
-	libU77/getlog_.c, libU77/getpid_.c, libU77/getuid_.c,
-	libU77/gmtime_.c, libU77/hostnm_.c, libU77/idate_.c,
-	libU77/ierrno_.c, libU77/irand_.c, libU77/isatty_.c,
-	libU77/itime_.c, libU77/kill_.c, libU77/link_.c,
-	libU77/lnblnk_.c, libU77/ltime_.c, libU77/mclock_.c,
-	libU77/perror_.c, libU77/rand_.c, libU77/rename_.c,
-	libU77/secnds_.c, libU77/second_.c, libU77/sleep_.c,
-	libU77/srand_.c, libU77/stat_.c, libU77/symlnk_.c,
-	libU77/system_clock_.c, libU77/time_.c, libU77/ttynam_.c,
-	libU77/umask_.c, libU77/unlink_.c, libU77/vxtidate_.c,
-	libU77/vxttime_.c: Completed renaming routines that are directly
-	callable from g77 to internal names of the form
-	G77_xxxx_0 that are known as intrinsics by g77.
-
-Apr 8 1997  Daniel Pettet  
-
-	* Makefile.in: Add libU77/mclock_.o and libU77/symlnk_.o to UOBJ.
-	* libU77/Makefile.in: Add mclock_.c to SRCS.
-	Add mclock_.o and symlnk_.o to OBJS.
-	Add mclock_.o dependency.
-
-Apr 8 1997  Daniel Pettet  
-
-	* libU77/symlnk_.c: Added a couple of (char*) casts to malloc
-	to silence the compiler.
-
-1997-03-17  Dave Love  
-
-	* libU77/access_.c, libU77/chdir_.c, libU77/chmod_.c,
-	libU77/link_.c, libU77/lstat_.c, libU77/rename_.c, libU77/stat_.c,
-	libU77/symlnk_.c, libU77/u77-test.f, libU77/unlink_.c: Strip
-	trailing blanks from file names for consistency with other
-	implementations (notably Sun's).
-
-	* libU77/chmod_.c: Quote the file name given to the shell.
-
-Mon Mar 10 00:19:17 1997  Craig Burley  
-
-	* libI77/uio.c (do_ud) [PAD_UDread]: Add semicolon to err()
-	invocation when macro not defined (from Mumit Khan
-	).
-
-Fri Feb 28 13:16:50 1997  Craig Burley  
-
-	* Version 0.5.20 released.
-
-Wed Feb 26 20:28:53 1997  Craig Burley  
-
-	* Makefile.in: $(MAKE) invocations now explicitly
-	specify `-f Makefile', just in case the `makefile's
-	from the netlib distribution would get used instead.
-
-Mon Feb 24 16:43:39 1997  Craig Burley  
-
-	* libU77/Makefile.in (check): Specify driver, and
-	don't bother enabling already-enabled intrinsic groups.
-	Also, get the $(srcdir) version of u77-test.f.
-
-Sat Feb 22 14:08:42 1997  Craig Burley  
-
-	* libU77/u77-test.f: Explicitly declare intrinsics, get
-	rid of useless CHARACTER declarations on intrinsics (maybe
-	someday appropriate to implement meaning of that in g77
-	and restore them?).
-	Add spin loop just to fatten up the timings a bit.
-	Clarify ETIME output as having three fields.
-	Call TIME with CHARACTER*8, not CHARACTER*6, argument.
-	Call new SECOND intrinsic subroutine, after calling
-	new DUMDUM subroutine just to ensure the correct value
-	doesn't get left around in a register or something.
-
-Thu Feb 20 15:22:42 1997  Craig Burley  
-
-	* libU77/bes.c: Comment out all the code, as g77 avoids actually
-	calling it, going directly to the system's library instead.
-
-Mon Feb 17 02:27:41 1997  Craig Burley  
-
-	* libU77/fgetc_.c (fgetc_): Allow return value to be
-	CHARACTER*(*), properly handle CHARACTER*0 and blank-pad
-	CHARACTER*n where n>1.
-
-Tue Feb 11 14:12:19 1997  Craig Burley  
-
-	* Makefile.in: Clarify role of $(srcdir) here.  Fix
-	various targets accordingly.  Don't rely at all on
-	gcc/f/include/ being a link to gcc/include/ -- just
-	use it directly.
-	(${srcdir}/configure, ${srcdir}/libU77/configure):
-	Remove the config.cache files in build directory before
-	cd'ing to source directory as well.
-
-	* libF77/Makefile.in, libI77/Makefile.in (ALL_CFLAGS):
-	Include `-I.' to pick up build directory.
-	Use gcc/include/ directly.
-	* libU77/Makefile.in (ALL_CFLAGS): Include `-I$(srcdir)'
-	to pick up source directory.
-	(OBJS): Fix typo in `chmod_.o' (was `chmod.o').
-
-Mon Feb 10 12:54:47 1997  Craig Burley  
-
-	* Makefile.in (UOBJ), libU77/Makefile.in (OBJS): Add
-	libU77/chmod_.o to list of objects.
-	* libU77/chmod_.c: Fix up headers.
-	Fix implementation to not prematurely truncate command
-	string and make room for trailing null.
-
-	* libU77/ctime_.c: Incoming xstime argument is now longint.
-	* libU77/mclock_.c: Now returns longint.
-	* libU77/time_.c: Now returns longint.
-
-1997-02-10  Dave Love  
-
-	* etime_.c, dtime_.c: Typo rounded times to seconds.
-
-	* date_.c: Add missing return.
-
-	* hostnm_.c: #include unistd.h.
-
-Sat Feb  8 03:30:19 1997  Craig Burley  
-
-	INTEGER*8 support built in to f2c.h and libf2c (since
-	gcc will be used to compile relevant code anyway):
-	* Makefile.in, libF77/Makefile.in: Add pow_qq.o,
-	qbitbits.o, and qbitshft.o to $POW and $F90BIT macros,
-	as appropriate.
-	* f2c.h.in: Define appropriate types and macros.
-	Place #error directive correctly.
-	* configure.in: Determine appropriate types for long
-	integer (F2C_LONGINT).
-	Meanwhile, quote strings in #error, for consistency.
-	Fix restoring of ac_cpp macro.
-	* configure: Regenerated using autoconf-2.12.
-
-	* libF77/Version.c, libI77/Version.c, libU77/Version.c:
-	Update version numbers.
-	Change names and code for g77-specific version-printing
-	routines (shorter names should be safer to link on
-	weird, 8-char systems).
-
-	* libF77/c_cos.c, libF77/c_div.c, libF77/c_exp.c,
-	libF77/c_log.c, libF77/c_sin.c, libF77/c_sqrt.c,
-	libF77/d_cnjg.c, libF77/pow_zi.c, libF77/r_cnjg.c,
-	libF77/z_cos.c, libF77/z_div.c, libF77/z_exp.c,
-	libF77/z_log.c, libF77/z_sin.c, libF77/z_sqrt.c:
-	Changed to work properly even when result is aliased
-	with any inputs.
-
-	* libF77/makefile, libI77/makefile: Leave these in
-	the g77 distribution, so it is easier to track changes
-	to official libf2c.
-
-	* libF77/signal_.c: Eliminate redundant `return 0;'.
-
-	* libI77/fio.h (err, errfl): Fix these so they work
-	(and must be expressed) as statements.
-	Fix up many users of err() to include trailing semicolon.
-
-	* Incorporate changes by Bell Labs to libf2c through 1997-02-07.
-
-1997-02-06  Dave Love  
-
-	* libU77/etime_.c, libU77/dtime_.c: Fix getrusage stuff.
-
-	* libU77/config.h.in: Regenerate for HAVE_GETRUSAGE.
-
-	* libU77/Makefile.in, libI77/Makefile.in, libF77/Makefile.in:
-	Redo *clean targets; distclean and maintainer-clean remove the stage?
-	and include links.  This probably want looking at further.
-
-Wed Feb  5 00:21:23 1997  Craig Burley  
-
-	Add libU77 library from Dave Love :
-	* Makefile.in: Add libU77 directory, rules, etc.
-	* configure.in: New libU77 directory, Makefile, etc.
-
-	* Makefile.in, libF77/Makefile.in, libI77/Makefile.in,
-	libU77/Makefile.in: Reorganize these so $(AR) commands
-	handled by the top-level Makefile instead of the
-	subordinates.  This permits it to do $(AR) only when
-	one or more object files actually change, instead of
-	having to force-update it as was necessary before.
-	And that had the disadvantage of requiring, e.g., user
-	root to have access to $(AR) to the library simply to
-	install g77, which might be problematic on an NFS setup.
-	(mostlyclean, clean, distclean, maintainer-clean):
-	Properly handle these rules.
-
-	* Makefile.in: Don't invoke config.status here -- let
-	compiler-level stuff handle all that.
-
-	* libI77/err.c [MISSING_FILE_ELEMS]: Declare malloc in this case
-	too, so it doesn't end up as an integer.
-
-Sat Feb  1 02:43:48 1997  Craig Burley  
-
-	* libF77/Makefile.in: More fixup for $(F90BIT) -- wasn't
-	in list for ar command, and it wasn't correctly listed
-	in the list of things depending on f2c.h.
-
-	* f2c.h.in: Fix up #error directive.
-
-1997-01-31  Dave Love  
-
-	* libF77/Makefile.in ($(lib)): Add $(F90BIT); shouldn't exclude
-	stuff f2c needs so we can share the library.
-
-Sat Jan 18 19:39:03 1997  Craig Burley  
-
-	* configure.in: No longer define ALWAYS_FLUSH, the
-	resulting performance is too low.
-
-Wed Dec 18 12:06:02 1996  Craig Burley  
-
-	Patch from Mumit Khan :
-	* libF77/s_paus.c: Add __CYGWIN32__ to list of macros
-	controlling how to pause.
-
-Sun Dec  1 21:25:27 1996  Craig Burley  
-
-	* configure: Regenerated using autoconf-2.12.
-
-Mon Nov 25 21:16:15 1996  Craig Burley  
-
-	* configure: Regenerated using autoconf-2.11.
-
-1996-11-19  Dave Love  
-
-	* libI77/backspace.c: Include sys/types.h for size_t.
-
-Wed Nov  6 14:17:27 1996  Craig Burley  
-
-	* f2c.h.in: Properly comment out the unsupported stuff so
-	we don't get build-time errors.
-
-	* libF77/Version.c, libI77/Version.c: Restore macro definition
-	of version information.
-
-	* libI77/Makefile.in (OBJ) [foo]: Add ftell_.o to list of objects.
-
-	* libI77/uio.c (do_ud): Fix up casts in PAD_UDread case just
-	like they were fixed in the other case.
-
-Thu Oct 31 22:27:45 1996  Craig Burley  
-
-	* libI77/ftell_.c (fseek_): Map incoming whence argument to
-	system's actual SEEK_CUR, SEEK_SET, or SEEK_END macro for
-	fseek(), and crash (gracefully) if the argument is invalid.
-
-1996-10-19  Dave Love  
-
-	* configure.in: Add check that we have the tools to cross-compile
-	if appropriate.
-	(NO_EOF_CHAR_CHECK,Skip_f2c_Undefs): Define.
-
-	* libF77/Makefile.in (F90BIT): New routines from Netlib.
-
-	* f2c.h.in:
-	Use more sanitary #error (indented for K&R compliance if necessary) if
-	f2c_i2 defined.
-	Sync with Netlib: Add `uninteger'.  (Commented out) integer*8 stuff.
-	bit_{test,clear,set} macros.
-
-1996-10-19  Dave Love  
-
-	Update to Netlib version of 1996-09-26.
-
-	* libI77/Version.c: Use , not "stdio.h".
-	* libF77/Version.c: Likewise.
-
-Wed Aug 28 13:25:29 1996  Dave Love  
-
-	* libI77/rsne.c (x_rsne): Use size_t instead of int.
-
-	* libI77/endfile.c (copy): Use size_t in place of int.
-
-Wed Aug 28 13:22:20 1996  Dave Love  
-
-	* libI77/backspace.c (f_back): Cast fread arg to size_t.
-
-Tue Aug 27 19:11:30 1996  Dave Love  
-
-	* libI77/Version.c: Supply */ to avoid apparent nested comment.
-
-Tue Aug 20 09:21:43 1996  Dave Love  
-
-	* libF77/Makefile.in (ALL_CFLAGS): Fix missing ../ for include.
-	* libI77/Makefile.in (ALL_CFLAGS): Likewise.
-
-Sat Aug 17 13:00:47 1996  Dave Love  
-
-	* libF77/qbitshft.c, libF77/qbitbits.c, libF77/lbitshft.c,
-	libF77/lbitbits.c: New file from Netlib.  qbit... not currently
-	compiled.
-
-Sun Jul  7 18:06:33 1996  Dave Love  
-
-	* libF77/z_sqrt.c, libF77/z_sin.c, libF77/z_exp.c, libF77/z_log.c,
-	libF77/system_.c, libF77/z_cos.c, libF77/signal_.c,
-	libF77/s_stop.c, libF77/sig_die.c, libF77/s_paus.c,
-	libF77/s_rnge.c, libF77/s_cat.c, libF77/r_tan.c, libF77/r_tanh.c,
-	libF77/r_sinh.c, libF77/r_sqrt.c, libF77/r_sin.c, libF77/r_mod.c,
-	libF77/r_nint.c, libF77/r_lg10.c, libF77/r_log.c, libF77/r_exp.c,
-	libF77/r_int.c, libF77/r_cosh.c, libF77/r_atn2.c, libF77/r_cos.c,
-	libF77/r_asin.c, libF77/r_atan.c, libF77/r_acos.c,
-	libF77/pow_dd.c, libF77/pow_zz.c, libF77/main.c, libF77/i_dnnt.c,
-	libF77/i_nint.c, libF77/h_dnnt.c, libF77/h_nint.c, libF77/exit.c,
-	libF77/d_tan.c, libF77/d_tanh.c, libF77/d_sqrt.c, libF77/d_sin.c,
-	libF77/d_sinh.c, libF77/d_mod.c, libF77/d_nint.c, libF77/d_log.c,
-	libF77/d_int.c, libF77/d_lg10.c, libF77/d_cosh.c, libF77/d_exp.c,
-	libF77/d_atn2.c, libF77/d_cos.c, libF77/d_atan.c, libF77/d_acos.c,
-	libF77/d_asin.c, libF77/c_sqrt.c, libF77/cabs.c, libF77/c_sin.c,
-	libF77/c_exp.c, libF77/c_log.c, libF77/c_cos.c, libF77/F77_aloc.c,
-	libF77/abort_.c, libI77/xwsne.c, libI77/wref.c, libI77/util.c,
-	libI77/uio.c, libI77/rsne.c, libI77/rdfmt.c, libI77/rawio.h,
-	libI77/open.c, libI77/lread.c, libI77/inquire.c, libI77/fio.h,
-	libI77/err.c, libI77/endfile.c, libI77/close.c:
-	Use #include <...>, not #include "..." for mkdeps
-
-Sat Jul  6 21:39:21 1996  Dave Love  
-
-	* libI77/ftell_.c: Added from Netlib distribution.
-
-Sat Mar 30 20:57:24 1996  Dave Love  
-
-	* configure.in: Eliminate explicit use of
-	{RANLIB,AR}_FOR_TARGET.
-	* Makefile.in: Likewise.
-	* libF77/Makefile.in: Likewise.
-	* libI77/Makefile.in: Likewise.
-	* configure: Regenerated.
-
-Sat Mar 30 21:02:03 1996  Dave Love  
-
-	* Makefile.in: Eliminate explicit use of
-	{RANLIB,AR}_FOR_TARGET.
-
-Tue Mar 26 23:39:59 1996  Dave Love  
-
-	* Makefile.in: Remove hardwired RANLIB and RANLIB_TEST (unnoted
-	change).
-
-Mon Mar 25 21:04:56 1996  Craig Burley  
-
-	* Incorporate changes by Bell Labs to libf2c through 1996-03-23,
-	including changes to dmg and netlib email addresses.
-
-Tue Mar 19 13:10:02 1996  Craig Burley  
-
-	* Incorporate changes by AT&T/Bellcore to libf2c through 1996-03-19.
-
-	* Makefile.in (rebuilt): New target.
-
-	* libF77/Makefile.in, libI77/Makefile.in: Use $AR_FOR_TARGET, not
-	$AR.
-
-Tue Mar 19 12:53:19 1996  Dave Love  
-
-	* configure.in (ac_cpp): #include  instead
-	of .
-
-Tue Mar 19 12:52:09 1996  Mumit Khan  
-
-	* configure.in (ac_cpp): For f2c integer type,
-	add -I$srcdir/../.. to make it work on mips-ultrix4.2.
-
-Sat Mar  9 17:37:15 1996  Craig Burley  
-
-	* libI77/Makefile.in (.c.o): Add -DAllow_TYQUAD, to enable
-	I/O support for INTEGER*8.
-	* f2c.h.in: Turn on longint type.
-
-Fri Dec 29 18:22:01 1995  Craig Burley  
-
-	* Makefile.in: Reorganize the *clean rules to more closely
-	parallel gcc's.
-
-	* libF77/Makefile.in, libI77/Makefile.in: Ignore error from $(AR)
-	command, in case just doing an install and installer has no write
-	access to library (this is a kludge fix -- perhaps install targets
-	should never try updating anything?).
-
-Sat Nov 18 19:37:22 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Version 0.5.17 released.
-
-Thu Nov 16 07:20:35 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Incorporate changes by AT&T/Bellcore to libf2c through 1995-11-15.
-
-Fri Sep 22 02:19:59 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libI77/backspace.c, libI77/close.c, libI77/endfile.c,
-	libI77/fio.h, libI77/inquire.c, libI77/rawio.h,
-	libF77/s_paus.c: Not an MSDOS system if GO32
-	is defined, in the sense that the run-time environment
-	is thus more UNIX-like.
-
-Wed Sep 20 02:24:51 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libF77/Makefile.in, libI77/Makefile.in: Comment out `ld -r -x'
-	and `mv' line pairs, since `-x' isn't supported on systems
-	such as Solaris, and these lines don't seem to do anything
-	useful after all.
-
-Wed Aug 30 15:58:35 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Version 0.5.16 released.
-
-	* Incorporate changes by AT&T/Bellcore to libf2c through 950829.
-
-Mon Aug 28 12:50:34 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libF77/Makefile.in, libI77/Makefile.in ($(lib)): Force ar'ing
-	and ranlib'ing of libf2c.a, else after rm'ing libf2c.a and
-	doing a make, only libI77 or libF77 would be added to
-	the newly created archive.
-	Also, instead of `$?' list all targets explicitly so all
-	objects are updated in libf2c.a even if only one actually
-	needs recompiling, for similar reason -- we can't easily tell
-	if a given object is really up-to-date in libf2c.a, or even
-	present there.
-
-Sun Aug 27 14:54:24 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libF77/Makefile.in, libI77/Makefile.in: Fix spacing so
-	initial tabs are present in all appropriate places.
-	Move identical $(AR) commands in if then/else clauses
-	to single command preceding if.
-	(.c.o, Version[FI].o): Use $@ instead of $* because AIX (RS/6000)
-	says $@ means source, not object, basename, and $@ seems to work
-	everywhere.
-
-Wed Aug 23 15:44:25 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libF77/system_.c (system_): Declare as returning `ftnint',
-	consistent with signal_, instead of defaulting to `int'.
-	Hope dmg@research.att.com agrees, else probably will
-	change to whatever he determines is correct (and change
-	g77 accordingly).
-
-Thu Aug 17 08:46:17 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libI77/rsne.c (s_rsne): Call f_init if not already done.
-
-Thu Aug 17 04:35:28 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Incorporate changes by Bellcore to libf2c through 950817.
-	And this text is for EMACS: (foo at bar).
-
-Wed Aug 16 17:33:06 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libF77/Makefile.in, libI77/Makefile.in (CFLAGS): Put -g1
-	after configured CFLAGS but before GCC_CFLAGS, so by default
-	the libraries are built with minimal debugging information.
-
-Fri Jul 28 10:30:15 1995  Dave Love  
-
-	* libI77/open.c (f_open): Call f_init if not already done.
-
-Sat Jul  1 19:31:56 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* libF77/system_.c (system_): Make buff one byte bigger so
-	following byte doesn't get overwritten by call with large
-	string.
-
-Tue Jun 27 23:28:16 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Incorporate changes by Bellcore to libf2c through 950613.
-
-	* libF77/Version.c (__G77_LIBF77_VERSION__): Add this string
-	to track g77 mods to libf2c.
-
-	* libI77/Version.c (__G77_LIBI77_VERSION__): Add this string
-	to track g77 mods to libf2c.
-
-	* libI77/rawio.h: #include  only conditionally,
-	using macro intended for that purpose.
-
-Fri May 19 11:20:00 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* configure.in: Incorporate change made by d.love,
-
-	* configure: Regenerated.
-
-Wed Apr 26 21:08:57 BST 1995  Dave Love  
-
-	* configure.in: Fix quoting problem in atexit check.
-
-	* configure: Regenerated (with current autoconf).
-
-Wed Mar 15 12:49:58 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Incorporate changes by Bellcore to libf2c through 950315.
-
-Sun Mar  5 18:54:29 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* README: Tell people not to read lib[fi]77/README.
-
-Wed Feb 15 14:30:58 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* configure.in: Update copyright notice at top of file.
-
-	* f2c.h.in (f2c_i2): Make sure defining this crashes compilations.
-
-	* libI77/Makefile.in (F2C_H): Fix typo in definition of this
-	symbol (was FF2C_H=...).
-
-Sun Feb 12 13:39:36 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* README: Remove some obsolete items.
-	Add date.
-
-	* TODO: Add date.
-
-Sat Feb 11 22:07:54 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Makefile.in (libf77, libi77): Add rules to .PHONY list.
-
-	* f2c.h.in (flag): Make same type as friends.
-
-	* libF77/Makefile.in (libf77): Rename to $(lib), remove from
-	.PHONY list.  Fix some typos.
-
-	* libI77/Makefile.in (libi77): Rename to $(lib), remove from
-	.PHONY list.  Fix some typos.
-
-Thu Feb  2 12:22:41 1995  Craig Burley  (burley@gnu.ai.mit.edu)
-
-	* Makefile.in (libF77/Makefile): Fix typos in this rule's name
-	and dependencies.
-
-	* libF77/Makefile.in (libf77): Add rule to .PHONY list.
-
-	* libI77/Makefile.in (libi77): Add rule to .PHONY list.
-
-Local Variables:
-add-log-time-format: current-time-string
-End:
diff --git a/contrib/libf2c/FREEBSD-upgrade b/contrib/libf2c/FREEBSD-upgrade
deleted file mode 100644
index e919f546f55..00000000000
--- a/contrib/libf2c/FREEBSD-upgrade
+++ /dev/null
@@ -1,22 +0,0 @@
-# ex:ts=8
-$FreeBSD$
-
-For the import of lib{f,g}2c, files were pruned by:
-
-	tar xvypf gcc-2.95.2.tar.bz2 '*/libf2c'
-
-Then imported by:
-
-	cvs import -m "Virgin import of GCC 2.95.2's libf2c"  \
-		src/contrib/libf2c FSF gcc_2_95_2
-
-
-To make local changes to lib{f,g}2c, simply patch and commit to the main
-branch (aka HEAD).  Never make local changes on the vendor (FSF) branch.
-
-All local changes should be submitted to "gcc-patches@gcc.gnu.org" and/or
-David M. Gay  (as libg2c is based on AT&T's netlib
-collection).
-
-obrien@NUXI.com
-31-October-1999
diff --git a/contrib/libf2c/Makefile.in b/contrib/libf2c/Makefile.in
deleted file mode 100644
index 120bd7c4017..00000000000
--- a/contrib/libf2c/Makefile.in
+++ /dev/null
@@ -1,276 +0,0 @@
-# Makefile for GNU F77 compiler runtime.
-#   Copyright (C) 1995-1998, 2001, 2002, 2003 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of GNU Fortran.
-#
-#GNU Fortran is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-SHELL = @SHELL@
-PWD_COMMAND = $${PWDCMD-pwd}
-MAKEOVERRIDES=
-.NOEXPORTS:
-
-#### Start of system configuration section. ####
-
-srcdir = @glibcpp_srcdir@
-VPATH = @glibcpp_srcdir@
-prefix = @prefix@
-exec_prefix = @exec_prefix@
-target_alias = @target_alias@
-gcc_version = @gcc_version@
-gcc_version_trigger = @gcc_version_trigger@
-top_srcdir = @top_srcdir@
-toplevel_srcdir = @toplevel_srcdir@
-toolexecdir = @glibcpp_toolexecdir@
-glibcpp_toolexecdir = @glibcpp_toolexecdir@
-glibcpp_toolexeclibdir = @glibcpp_toolexeclibdir@
-
-top_builddir = .
-
-libdir = $(exec_prefix)/lib
-libsubdir = $(libdir)/gcc/$(target_alias)/$(gcc_version)
-#
-# Versions should start at 0:0:0 - See libtool manual.
-VERSION_MAJOR=0
-VERSION_MINOR=0
-VERSION_SUB=0
-
-# Multilib support variables.
-MULTISRCTOP =
-MULTIBUILDTOP =
-MULTIDIRS =
-MULTISUBDIR =
-MULTIDO = true
-MULTICLEAN = true
-
-# Not configured per top-level version, since that doesn't get passed
-# Versions should start at 0:0:0 - See libtool manual.
-# down at configure time, but overrridden by the top-level install
-# target.
-INSTALL = @INSTALL@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_DATA = @INSTALL_DATA@
-
-LIBTOOL = @LIBTOOL@
-CC = @CC@
-WARN_CFLAGS = -W -Wall
-CFLAGS = @CFLAGS@
-AR = @AR@
-RANLIB = @RANLIB@
-
-# List of variables to pass to sub-makes.
-# Quote this way so that it can be used to set shell variables too.
-FLAGS_TO_PASS= \
-	CC='$(CC)' \
-	LD='$(LD)' \
-	LIBTOOL='$(LIBTOOL)' \
-	WARN_CFLAGS='$(WARN_CFLAGS)' \
-	CFLAGS='$(CFLAGS)' \
-	CPPFLAGS='$(CPPFLAGS)' \
-	DESTDIR='$(DESTDIR)' \
-	AR='$(AR)' \
-	RANLIB='$(RANLIB)' \
-	prefix='$(prefix)' \
-	exec_prefix='$(exec_prefix)' \
-	libdir='$(libdir)' \
-	libsubdir='$(libsubdir)' \
-	tooldir='$(tooldir)'
-
-LIBG2C_BASE = libg2c
-LIBG2C = $(LIBG2C_BASE).la
-
-SUBDIRS = libI77 libF77 libU77
-
-F2CEXT = abort derf derfc ef1asc ef1cmc erf erfc exit getarg getenv iargc \
-	signal system flush ftell fseek access besj0 besj1 besjn besy0 besy1 \
-	besyn chdir chmod ctime dbesj0 dbesj1 dbesjn dbesy0 dbesy1 dbesyn \
-	dtime etime fdate fgetc fget flush1 fnum fputc fput fstat gerror \
-	getcwd getgid getlog getpid getuid gmtime hostnm idate ierrno irand \
-	isatty itime kill link lnblnk lstat ltime mclock perror rand rename \
-	secnds second sleep srand stat symlnk time ttynam umask unlink \
-	vxttim alarm \
-	date_y2kbuggy date_y2kbug vxtidt_y2kbuggy vxtidt_y2kbug
-
-.SUFFIXES:
-
-# The logic here is partly dictated by the desire to keep the lib?77
-# subdirs for compatibility with the Netlib version and because libU77
-# has a different copyright; then the libe77 bit (EXTERNALly-callable
-# versions) is funny.  Given that, as well as keeping things as simple
-# as possible we want (at least) the following:
-#  * Allow make to be run at the top level (all-target-libf2c), at this
-#    level, or the subdirs of this level.  In the latter case we only
-#    compile, rather than updating libg2c.a;
-#  * A robust set of dependencies, so that we rebuild (as little as
-#    possible) if a configuration file, g2c.h or any lib?77/*.c file
-#    changes;
-#  * Avoid unnecessary running of ar and ranlib;
-#  * Expose parallelism where reasonable, but not as a priority.
-
-# The intended top-level target here does a non-multilib build (via
-# the dependency) and then (perhaps) builds multilibs.
-
-all: all-unilib
-	: $(MAKE) ; exec $(MULTIDO) $(FLAGS_TO_PASS) multi-do DO="all-unilib"
-
-# `all-unilib' is the overall target in the absence of multilibs,
-# meant to be invoked via multi-do for multilibs.
-
-# Its dependencies can be satisfied in parallel.  The [fiu]77 targets
-# update stamp files (object file lists, actually, see the subdir
-# makefiles) on which the $(LIBG2C) depends.  The stamp files
-# s-lib[fiu]77 are intentionally not targets, since we're only meant
-# to come in at the level of this target.  The [fiu]77 targets always
-# invoke sub makes to check dependencies in the subdirs, else we'd
-# have to maintain them at this level; we live with the overhead of
-# some recursive makes which may do nothing.
-
-all-unilib: i77 f77 u77 s-libe77
-	$(MAKE) $(FLAGS_TO_PASS) $(LIBG2C)
-
-i77 f77 u77: g2c.h
-
-# This target should normally only get invoked via `all-unilib' --
-# after all's well in the subdirs -- actually to assemble the library.
-# The stamp files contain the object lists of each component of the
-# library.  The point of breaking them up is to avoid command-line
-# length limitations.
-
-$(LIBG2C): s-libi77 s-libf77 s-libu77 s-libe77
-	$(LIBTOOL) --mode=link $(CC) -o $@ \
-	  -version-info $(VERSION_MAJOR):$(VERSION_MINOR):$(VERSION_SUB) \
-	  -rpath $(glibcpp_toolexeclibdir) \
-	  -objectlist s-libe77 \
-	  -objectlist s-libf77 \
-	  -objectlist s-libi77 \
-	  -objectlist s-libu77 \
-	  -lm
-
-i77:
-	cd libI77; $(MAKE) $(FLAGS_TO_PASS) all
-
-f77:
-	cd libF77; $(MAKE) $(FLAGS_TO_PASS) all
-
-u77:
-	cd libU77; $(MAKE) $(FLAGS_TO_PASS) all
-
-s-libe77: f2cext.c
-	if [ -d libE77 ]; then rm -f libE77/*.o libE77/*.lo; else mkdir libE77; fi
-	-rm -f $@.T $@
-	for name in $(F2CEXT); \
-	do \
-	  echo $${name}; \
-	  $(LIBTOOL) --mode=compile $(CC) -c -I. -I$(srcdir) -I../../include \
-	    $(CPPFLAGS) $(WARN_CFLAGS) $(CFLAGS) -DL$${name} $(srcdir)/f2cext.c \
-	    -o libE77/L$${name}.lo ; \
-	  if [ $$? -eq 0 ] ; then true; else exit 1; fi; \
-	  echo libE77/L$${name}.lo >> $@.T; \
-	done
-	mv $@.T $@
-
-f2cext.c: g2c.h
-
-${srcdir}/configure: configure.in
-	rm -f config.cache
-	cd $(srcdir) && autoconf
-
-# Dependence on Makefile serializes for parallel make.
-g2c.h: g2c.hin config.status Makefile
-# Might try to avoid rebuilding everything if Makefile or configure
-# changes and g2c.h doesn't; see also the Makefile rule.  Should
-# depend on another stamp file rather than using the commented-out
-# lines below, since g2c.h isn't necessarily brought up to date.
-#	mv g2c.h g2c.x
-	$(SHELL) config.status
-#	$(SHELL) $(srcdir)/../move-if-change g2c.h g2c.x && mv g2c.x g2c.h
-
-Makefile: Makefile.in config.status
-# Autoconf doc uses `./config.status'.  Is there a good reason to use $(SHELL)?
-	  $(SHELL) config.status
-
-config.status: configure $(gcc_version_trigger)
-# Make sure we don't pick up a site config file and that configure
-# gets run with correct values of variables such as CC.
-	CONFIG_SITE=no-such-file $(FLAGS_TO_PASS) \
-	  $(SHELL) config.status --recheck
-
-info install-info clean-info dvi TAGS dist installcheck installdirs:
-
-check:
-	cd libU77; $(MAKE) G77DIR=../../../gcc/ check
-
-install: all
-	$(SHELL) $(toplevel_srcdir)/mkinstalldirs $(DESTDIR)$(glibcpp_toolexeclibdir)
-	$(LIBTOOL) --mode=install $(INSTALL) $(LIBG2C) $(DESTDIR)$(glibcpp_toolexeclibdir)
-	$(INSTALL_DATA) libfrtbegin.a $(DESTDIR)$(glibcpp_toolexeclibdir)
-	$(RANLIB) $(DESTDIR)$(glibcpp_toolexeclibdir)/libfrtbegin.a
-	$(INSTALL_DATA) g2c.h $(DESTDIR)$(libsubdir)/include/g2c.h
-	$(MULTIDO) $(FLAGS_TO_PASS) multi-do DO="$@"
-	@-$(LIBTOOL) --mode=finish $(DESTDIR)$(glibcpp_toolexeclibdir)
-
-install-strip:
-	$(MAKE) INSTALL_PROGRAM='$(INSTALL_PROGRAM) -s' install
-
-uninstall:
-	rm -f $(DESTDIR)$(libsubdir)/include/g2c.h
-	rm -f $(DESTDIR)$(glibcpp_toolexeclibdir)/libfrtbegin.a
-	$(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(glibcpp_toolexeclibdir)$(LIBG2C_BASE).la
-	$(MULTIDO) $(FLAGS_TO_PASS) multi-do DO="$@"
-
-mostlyclean:
-	rm -f $(LIBG2C) objlist
-	$(MAKE) DO=$@ DODIRS="$(SUBDIRS)" $(FLAGS_TO_PASS) subdir_do; \
-	$(MULTICLEAN) multi-clean DO=$@
-	rm -fr libE77 s-libe77
-
-clean: mostlyclean
-	rm -f config.log
-	$(MAKE) DO=$@ DODIRS="$(SUBDIRS)" $(FLAGS_TO_PASS) subdir_do; \
-	$(MULTICLEAN) multi-clean DO=$@
-	rm -rf .libs
-
-distclean: clean
-	rm -f g2c.h s-libe77
-	$(MAKE) DO=$@ DODIRS="$(SUBDIRS)" $(FLAGS_TO_PASS) subdir_do; \
-	$(MULTICLEAN) multi-clean DO=distclean
-	rm -f config.cache config.status Makefile
-
-maintainer-clean:
-
-rebuilt: configure
-
-.PHONY: rebuilt mostlyclean clean distclean maintainer-clean all \
-        i77 f77 u77 check uninstall install-strip dist \
-        installcheck installdirs all-unilib
-
-subdir_do:
-	@rootpre=`${PWD_COMMAND}`/; export rootpre; \
-	srcrootpre=`cd $(srcdir); ${PWD_COMMAND}`/; export srcrootpre; \
-	for i in .. $(DODIRS); do \
-	  if [ x$$i != x.. ]; then \
-	    if [ -f ./$$i/Makefile ]; then \
-	      if (cd ./$$i; $(MAKE) $(FLAGS_TO_PASS) $(DO)); then \
-		true; \
-	      else \
-		exit 1; \
-	      fi; \
-	    else true; fi; \
-	  else true; fi; \
-	done
-
-# multidoings may be added here by configure.
diff --git a/contrib/libf2c/README b/contrib/libf2c/README
deleted file mode 100644
index 008654b3c77..00000000000
--- a/contrib/libf2c/README
+++ /dev/null
@@ -1,109 +0,0 @@
-1998-08-11
-
-This directory contains the libf2c library packaged for use with g77
-to configure and build automatically (in principle!) as part of the
-top-level configure and make steps.  g77 names this library `libg2c'
-to avoid conflicts with existing copies of `libf2c' on a system.
-
-Some small changes have been made vis-a-vis the netlib distribution of
-libf2c, which comes from  and is maintained
-(excellently) by David M. Gay .  See the Notice files
-for copyright information.  We usually try to get g77-specific changes
-rolled back into the libf2c distribution.
-
-Files that come directly from netlib are either maintained in the
-libf2c directory under their original names or, if they are not pertinent
-for g77's version of libf2c, under their original names with `.netlib'
-appended.  For example, permissions.netlib is a copy of f2c's top-level
-`permissions' file in the netlib distribution.  In this case, it applies
-only to the relevant portions of the libF77/ and libI77/ directories; it
-does not apply to the libU77/ directory, which is distributed under
-different licensing arrangements.  Similarly, the `makefile.netlib' files
-in the libF77/ and libI77/ subdirectories are copies of the respective
-`makefile' files in the netlib distribution, but are not used when
-building g77's version of libf2c.
-
-The README.netlib files in libF77/ and libI77/ thus might be
-interesting, but should not be taken as guidelines for how to
-configure and build libf2c in g77's distribution.
-
-* Read permissions.netlib for licensing conditions that apply to
-  distributing programs containing portions of code in the libF77/ and
-  libI77/ subdirectories.  Also read disclaimer.netlib.
-
-* Read libU77/COPYING.LIB for licensing conditions that apply to
-  distributing programs containing portions of code in the libU77/
-  subdirectory.
-
-Among the user-visible changes (choices) g77 makes in its version of libf2c:
-
--  f2c.h configured to default to padding unformatted direct reads
-   (#define Pad_UDread), because that's the behavior most users
-   expect.
-
--  f2c.h configured to default to outputting leading zeros before
-   decimal points in formatted and list-directed output, to be compatible
-   with many other compilers (#define WANT_LEAD_0).  Either way is
-   standard-conforming, however, and you should try to avoid writing
-   code that assumes one format or another.
-
--  dtime_() and etime_() are from Dave Love's libU77, not from
-   netlib's libF77.
-
--  Routines that are intended to be called directly via user code
-   (as in `CALL EXIT', but not the support routines for `OPEN')
-   have been renamed from `' to `G77__0'.  This, in
-   combination with g77 recognizing these names as intrinsics and
-   calling them directly by those names, reduces the likelihood of
-   interface mismatches occurring due to use of compiler options
-   that change code generation, and permits use of these names as
-   both intrinsics and user-supplied routines in applications (as
-   required by the Fortran standards).  f2cext.c contains "jacket"
-   routines named `' that call `G77__0', to support
-   code that relies on calling the relevant routines as `EXTERNAL'
-   routines.
-
-   Note that the `_0' in the name denotes version 0 of the *interface*,
-   not the *implementation*, of a routine.  The interface of a
-   given routine *must not change* -- instead, introduce a new copy
-   of the code, with an increment (e.g. `_1') suffix, having the
-   new interface.  Whether the previous interface is maintained is
-   not as important as ensuring the routine implementing the new
-   interface is never successfully linked to a call in existing,
-   e.g. previously compiled, code that expects the old interface.
-
--  Version.c in the subdirectories contains g77-specific version
-   information and a routine (per subdirectory) to print both the
-   netlib and g77 version information when called.  The `g77 -v'
-   command is designed to trigger this, by compiling, linking, and
-   running a small program that calls the routines in sequence.
-
--  libF77/main.c no longer contains the actual code to copy the
-   argc and argv values into globals or to set up the signal-handling
-   environment.  These have been removed to libF77/setarg.c and
-   libF77/setsig.c, respectively.  libF77/main.c contains procedure
-   calls to the new code in place of the code itself.  This should
-   simplify linking executables with a main() function other than
-   that in libF77/main.c (such as one written by the user in C or
-   C++).  See the g77 documentation for more information.
-
--  Complex-arithmetic support routines in libF77/ take a different approach
-   to avoiding problems resulting from aliased input and output arguments,
-   which should avoid particularly unusual alias problems that netlib
-   libf2c might suffer from.
-
--  libF77/signal_.c supports systems with 64-bit pointers and 32-bit
-   integers.
-
--  I/O routines in libI77/ have code to detect attempts to do recursive
-   I/O more "directly", mainly to lead to a clearer diagnostic than
-   typically occurs under such conditions.
-
--  Formatted-I/O routines in libI77/ have code to pretty-print a FORMAT
-   string when printing a fatal diagnostic involving formatted I/O.
-
--  libI77/open.c supports a more robust, perhaps more secure, method
-   of naming temporary files on some systems.
-
--  Some g77-specific handling of building under Microsoft operating
-   systems exists, mainly in libI77/.
diff --git a/contrib/libf2c/TODO b/contrib/libf2c/TODO
deleted file mode 100644
index 84cbb0c733d..00000000000
--- a/contrib/libf2c/TODO
+++ /dev/null
@@ -1,14 +0,0 @@
-980709
-
-TODO list for the g77 library
-
-* Investigate building shared libraries on systems we know about
-  (probably using libtool).
-
-* Better test cases.
-
-* Allow the library to be stripped to save space.  (The install-strip
-  makefile target now allows this, should it be easily invocable.)
-
-* An interface to IEEE maths functions from libc where this makes
-  sense.
diff --git a/contrib/libf2c/aclocal.m4 b/contrib/libf2c/aclocal.m4
deleted file mode 100644
index b84eda0d2cf..00000000000
--- a/contrib/libf2c/aclocal.m4
+++ /dev/null
@@ -1,236 +0,0 @@
-dnl Copyright (C) 1994, 1995-8, 1999, 2001, 2002 Free Software Foundation, Inc.
-dnl This file is free software; the Free Software Foundation
-dnl gives unlimited permission to copy and/or distribute it,
-dnl with or without modifications, as long as this notice is preserved.
-
-dnl This program is distributed in the hope that it will be useful,
-dnl but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-dnl even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-dnl PARTICULAR PURPOSE.
-
-dnl
-dnl Initialize configure bits.
-dnl
-dnl GLIBCPP_TOPREL_CONFIGURE
-AC_DEFUN(GLIBCPP_TOPREL_CONFIGURE, [
-  dnl Default to --enable-multilib
-  AC_ARG_ENABLE(multilib,
-  [  --enable-multilib       build hella library versions (default)],
-  [case "${enableval}" in
-    yes) multilib=yes ;;
-    no)  multilib=no ;;
-    *)   AC_MSG_ERROR(bad value ${enableval} for multilib option) ;;
-   esac], [multilib=yes])dnl
-
-# When building with srcdir == objdir, links to the source files will
-# be created in directories within the target_subdir.  We have to
-# adjust toplevel_srcdir accordingly, so that configure finds
-# install-sh and other auxiliary files that live in the top-level
-# source directory.
-if test "${srcdir}" = "."; then
-  if test -z "${with_target_subdir}"; then
-    toprel=".."
-  else
-    if test "${with_target_subdir}" != "."; then
-      toprel="${with_multisrctop}../.."
-    else
-      toprel="${with_multisrctop}.."
-    fi
-  fi
-else
-  toprel=".."
-fi
-AC_CONFIG_AUX_DIR(${srcdir}/$toprel)
-toplevel_srcdir=\${top_srcdir}/$toprel
-AC_SUBST(toplevel_srcdir)
-])
-
-dnl
-dnl Initialize configure bits.
-dnl
-dnl GLIBCPP_CONFIGURE
-AC_DEFUN(GLIBCPP_CONFIGURE, [
-# Export build and source directories.
-# These need to be absolute paths, yet at the same time need to
-# canonicalize only relative paths, because then amd will not unmount
-# drives. Thus the use of PWDCMD: set it to 'pawd' or 'amq -w' if using amd.
-glibcpp_builddir=`${PWDCMD-pwd}`
-case $srcdir in
-[\\/$]* | ?:[\\/]*) glibcpp_srcdir=${srcdir} ;;
-*) glibcpp_srcdir=`cd "$srcdir" && ${PWDCMD-pwd} || echo "$srcdir"` ;;
-esac
-AC_SUBST(glibcpp_builddir)
-AC_SUBST(glibcpp_srcdir)
-
-dnl This is here just to satisfy automake.
-ifelse(not,equal,[AC_CONFIG_AUX_DIR(..)])
-
-# Will set LN_S to either 'ln -s' or 'ln'.  With autoconf 2.50+, can also
-# be 'cp -p' if linking isn't available.
-#ac_cv_prog_LN_S='cp -p'
-AC_PROG_LN_S
-
-# We use these options to decide which functions to include.
-AC_ARG_WITH(target-subdir,
-[  --with-target-subdir=SUBDIR
-                           configuring in a subdirectory])
-AC_ARG_WITH(cross-host,
-[  --with-cross-host=HOST  configuring with a cross compiler])
-
-  # Never versions of autoconf add an underscore to these functions.
-  # Prevent future problems ...
-  ifdef([AC_PROG_CC_G],[],[define([AC_PROG_CC_G],defn([_AC_PROG_CC_G]))])
-  ifdef([AC_PROG_CC_GNU],[],[define([AC_PROG_CC_GNU],defn([_AC_PROG_CC_GNU]))])
-  ifdef([AC_PROG_CXX_G],[],[define([AC_PROG_CXX_G],defn([_AC_PROG_CXX_G]))])
-  ifdef([AC_PROG_CXX_GNU],[],[define([AC_PROG_CXX_GNU],defn([_AC_PROG_CXX_GNU]))])
-
-#  AC_PROG_CC
-
-# FIXME: We temporarily define our own version of AC_PROG_CC.  This is
-# copied from autoconf 2.12, but does not call AC_PROG_CC_WORKS.  We
-# are probably using a cross compiler, which will not be able to fully
-# link an executable.  This should really be fixed in autoconf
-# itself.
-
-AC_DEFUN(LIB_AC_PROG_CC,
-[AC_BEFORE([$0], [AC_PROG_CPP])dnl
-dnl Fool anybody using AC_PROG_CC.
-AC_PROVIDE([AC_PROG_CC])
-AC_CHECK_PROG(CC, gcc, gcc)
-if test -z "$CC"; then
-  AC_CHECK_PROG(CC, cc, cc, , , /usr/ucb/cc)
-  test -z "$CC" && AC_MSG_ERROR([no acceptable cc found in \$PATH])
-fi
-
-AC_PROG_CC_GNU
-
-if test $ac_cv_prog_gcc = yes; then
-  GCC=yes
-dnl Check whether -g works, even if CFLAGS is set, in case the package
-dnl plays around with CFLAGS (such as to build both debugging and
-dnl normal versions of a library), tasteless as that idea is.
-  ac_test_CFLAGS="${CFLAGS+set}"
-  ac_save_CFLAGS="$CFLAGS"
-  CFLAGS=
-  AC_PROG_CC_G
-  if test "$ac_test_CFLAGS" = set; then
-    CFLAGS="$ac_save_CFLAGS"
-  elif test $ac_cv_prog_cc_g = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-O2"
-  fi
-else
-  GCC=
-  test "${CFLAGS+set}" = set || CFLAGS="-g"
-fi
-])
-
-LIB_AC_PROG_CC
-
-  AC_CHECK_TOOL(AS, as)
-  AC_CHECK_TOOL(AR, ar)
-  AC_CHECK_TOOL(RANLIB, ranlib, ranlib-not-found-in-path-error)
-  AC_PROG_INSTALL
-
-  # We need AC_EXEEXT to keep automake happy in cygnus mode.  However,
-  # at least currently, we never actually build a program, so we never
-  # need to use $(EXEEXT).  Moreover, the test for EXEEXT normally
-  # fails, because we are probably configuring with a cross compiler
-  # which can't create executables.  So we include AC_EXEEXT to keep
-  # automake happy, but we don't execute it, since we don't care about
-  # the result.
-  if false; then
-    # autoconf 2.50 runs AC_EXEEXT by default, and the macro expands
-    # to nothing, so nothing would remain between `then' and `fi' if it
-    # were not for the `:' below.
-    :
-    AC_EXEEXT
-  fi
-])
-
-
-dnl
-dnl  GLIBCPP_EXPORT_INSTALL_INFO
-dnl  calculates gxx_install_dir
-dnl  exports glibcpp_toolexecdir
-dnl  exports glibcpp_toolexeclibdir
-dnl  exports glibcpp_prefixdir
-dnl
-dnl Assumes cross_compiling bits already done, and with_cross_host in
-dnl particular
-dnl
-dnl GLIBCPP_EXPORT_INSTALL_INFO
-AC_DEFUN(GLIBCPP_EXPORT_INSTALL_INFO, [
-# Assumes glibcpp_builddir, glibcpp_srcdir are alreay set up and
-# exported correctly in GLIBCPP_CONFIGURE.
-glibcpp_toolexecdir=no
-glibcpp_toolexeclibdir=no
-glibcpp_prefixdir=${prefix}
-
-AC_MSG_CHECKING([for interface version number])
-libstdcxx_interface=$INTERFACE
-AC_MSG_RESULT($libstdcxx_interface)
-
-# Process the option "--enable-version-specific-runtime-libs"
-AC_MSG_CHECKING([for --enable-version-specific-runtime-libs])
-AC_ARG_ENABLE(version-specific-runtime-libs,
-[  --enable-version-specific-runtime-libs    Specify that runtime libraries should be installed in a compiler-specific directory ],
-[case "$enableval" in
- yes) version_specific_libs=yes ;;
- no)  version_specific_libs=no ;;
- *)   AC_MSG_ERROR([Unknown argument to enable/disable version-specific libs]);;
- esac],
-version_specific_libs=no)dnl
-# Option set, now we can test it.
-AC_MSG_RESULT($version_specific_libs)
-
-gcc_version_trigger=${toplevel_srcdir}/gcc/version.c
-gcc_version_full=`grep version_string ${gcc_version_trigger} | sed -e 's/.*\"\([[^ \"]]*\)[[ \"]].*/\1/'`
-gcc_version=`echo ${gcc_version_full} | sed -e 's/\([^ ]*\) .*/\1/'`
-AC_SUBST(gcc_version)
-AC_SUBST(gcc_version_trigger)
-
-if test $version_specific_libs = yes; then
-  # Need the gcc compiler version to know where to install libraries
-  # and header files if --enable-version-specific-runtime-libs option
-  # is selected.  FIXME: "toolexecdir" is a misnomer, there are no
-  # executables installed there.
-  changequote(,)dnl
-  glibcpp_toolexecdir='$(libdir)/gcc/$(target_alias)'
-  glibcpp_toolexeclibdir='$(toolexecdir)/'${gcc_version}'$(MULTISUBDIR)'
-  changequote([,])dnl
-fi
-
-# Calculate glibcpp_toolexecdir, glibcpp_toolexeclibdir
-# Install a library built with a cross compiler in tooldir, not libdir.
-if test x"$glibcpp_toolexecdir" = x"no"; then 
-  if test -n "$with_cross_host" &&
-     test x"$with_cross_host" != x"no"; then
-    glibcpp_toolexecdir='$(exec_prefix)/$(target_alias)'
-    glibcpp_toolexeclibdir='$(toolexecdir)/lib'
-  else
-    glibcpp_toolexecdir='$(libdir)/gcc/$(target_alias)'
-    glibcpp_toolexeclibdir='$(libdir)'
-  fi
-  multi_os_directory=`$CC -print-multi-os-directory`
-  case $multi_os_directory in
-    .) ;; # Avoid trailing /.
-    *) glibcpp_toolexeclibdir=$glibcpp_toolexeclibdir/$multi_os_directory ;;
-  esac
-fi
-
-AC_SUBST(glibcpp_prefixdir)
-AC_SUBST(glibcpp_toolexecdir)
-AC_SUBST(glibcpp_toolexeclibdir)
-])
-
-sinclude(../libtool.m4)
-dnl The lines below arrange for aclocal not to bring an installed
-dnl libtool.m4 into aclocal.m4, while still arranging for automake to
-dnl add a definition of LIBTOOL to Makefile.in.
-ifelse(,,,[AC_SUBST(LIBTOOL)
-AC_DEFUN([AM_PROG_LIBTOOL])
-AC_DEFUN([AC_LIBTOOL_DLOPEN])
-AC_DEFUN([AC_PROG_LD])
-])
diff --git a/contrib/libf2c/changes.netlib b/contrib/libf2c/changes.netlib
deleted file mode 100644
index 4ec0e7f5825..00000000000
--- a/contrib/libf2c/changes.netlib
+++ /dev/null
@@ -1,3026 +0,0 @@
-31 Aug. 1989:
-   1. A(min(i,j)) now is translated correctly (where A is an array).
-   2. 7 and 8 character variable names are allowed (but elicit a
-      complaint under -ext).
-   3. LOGICAL*1 is treated as LOGICAL, with just one error message
-      per LOGICAL*1 statement (rather than one per variable declared
-      in that statement).  [Note that LOGICAL*1 is not in Fortran 77.]
-      Like f77, f2c now allows the format in a read or write statement
-      to be an integer array.
-
-5 Sept. 1989:
-   Fixed botch in argument passing of substrings of equivalenced
-variables.
-
-15 Sept. 1989:
-   Warn about incorrect code generated when a character-valued
-function is not declared external and is passed as a parameter
-(in violation of the Fortran 77 standard) before it is invoked.
-Example:
-
-	subroutine foo(a,b)
-	character*10 a,b
-	call goo(a,b)
-	b = a(3)
-	end
-
-18 Sept. 1989:
-   Complain about overlapping initializations.
-
-20 Sept. 1989:
-   Warn about names declared EXTERNAL but never referenced;
-include such names as externs in the generated C (even
-though most C compilers will discard them).
-
-24 Sept. 1989:
-   New option -w8 to suppress complaint when COMMON or EQUIVALENCE
-forces word alignment of a double.
-   Under -A (for ANSI C), ensure that floating constants (terminated
-by 'f') contain either a decimal point or an exponent field.
-   Repair bugs sometimes encountered with CHAR and ICHAR intrinsic
-functions.
-   Restore f77's optimizations for copying and comparing character
-strings of length 1.
-   Always assume floating-point valued routines in libF77 return
-doubles, even under -R.
-   Repair occasional omission of arguments in routines having multiple
-entry points.
-   Repair bugs in computing offsets of character strings involved
-in EQUIVALENCE.
-   Don't omit structure qualification when COMMON variables are used
-as FORMATs or internal files.
-
-2 Oct. 1989:
-   Warn about variables that appear only in data stmts; don't emit them.
-   Fix bugs in character DATA for noncharacter variables
-involved in EQUIVALENCE.
-   Treat noncharacter variables initialized (at least partly) with
-character data as though they were equivalenced -- put out a struct
-and #define the variables.  This eliminates the hideous and nonportable
-numeric values that were used to initialize such variables.
-   Treat IMPLICIT NONE as IMPLICIT UNDEFINED(A-Z) .
-   Quit when given invalid options.
-
-8 Oct. 1989:
-  Modified naming scheme for generated intermediate variables;
-more are recycled, fewer distinct ones used.
-  New option -W nn specifies nn characters/word for Hollerith
-data initializing non-character variables.
-  Bug fix: x(i:min(i+10,j)) used to elicit "Can't handle opcode 31 yet".
-  Integer expressions of the form (i+const1) - (i+const2), where
-i is a scalar integer variable, are now simplified to (const1-const2);
-this leads to simpler translation of some substring expressions.
-  Initialize uninitialized portions of character string arrays to 0
-rather than to blanks.
-
-9 Oct. 1989:
-  New option -c to insert comments showing original Fortran source.
-  New option -g to insert line numbers of original Fortran source.
-
-10 Oct. 1989:
-  ! recognized as in-line comment delimiter (a la Fortran 88).
-
-24 Oct. 1989:
-  New options to ease coping with systems that want the structs
-that result from COMMON blocks to be defined just once:
-  -E causes uninitialized COMMON blocks to be declared Extern;
-if Extern is undefined, f2c.h #defines it to be extern.
-  -ec causes a separate .c file to be emitted for each
-uninitialized COMMON block: COMMON /ABC/ yields abc_com.c;
-thus one can compile *_com.c into a library to ensure
-precisely one definition.
-  -e1c is similar to -ec, except that everything goes into
-one file, along with comments that give a sed script for
-splitting the file into the pieces that -ec would give.
-This is for use with netlib's "execute f2c" service (for which
--ec is coerced into -e1c, and the sed script will put everything
-but the COMMON definitions into f2c_out.c ).
-
-28 Oct. 1989:
-  Convert "i = i op ..." into "i op= ...;" even when i is a
-dummy argument.
-
-13 Nov. 1989:
-  Name integer constants (passed as arguments) c__... rather
-than c_... so
-	common /c/stuff
-	call foo(1)
-	...
-is translated correctly.
-
-19 Nov. 1989:
-  Floating-point constants are now kept as strings unless they
-are involved in constant expressions that get simplified.  The
-floating-point constants kept as strings can have arbitrarily
-many significant figures and a very large exponent field (as
-large as long int allows on the machine on which f2c runs).
-Thus, for example, the body of
-
-	subroutine zot(x)
-	double precision x(6), pi
-	parameter (pi=3.1415926535897932384626433832795028841972)
-	x(1) = pi
-	x(2) = pi+1
-	x(3) = 9287349823749272.7429874923740978492734D-298374
-	x(4) = .89
-	x(5) = 4.0005
-	x(6) = 10D7
-	end
-
-now gets translated into
-
-    x[1] = 3.1415926535897932384626433832795028841972;
-    x[2] = 4.1415926535897931;
-    x[3] = 9.2873498237492727429874923740978492734e-298359;
-    x[4] = (float).89;
-    x[5] = (float)4.0005;
-    x[6] = 1e8;
-
-rather than the former
-
-    x[1] = 3.1415926535897931;
-    x[2] = 4.1415926535897931;
-    x[3] = 0.;
-    x[4] = (float)0.89000000000000003;
-    x[5] = (float)4.0004999999999997;
-    x[6] = 100000000.;
-
-  Recognition of f77 machine-constant intrinsics deleted, i.e.,
-epbase, epprec, epemin, epemax, eptiny, ephuge, epmrsp.
-
-22 Nov. 1989:
-  Workarounds for glitches on some Sun systems...
-  libf77: libF77/makefile modified to point out possible need
-to compile libF77/main.c with -Donexit=on_exit .
-  libi77: libI77/wref.c (and libI77/README) modified so non-ANSI
-systems can compile with USE_STRLEN defined, which will cause
-	sprintf(b = buf, "%#.*f", d, x);
-	n = strlen(b) + d1;
-rather than
-	n = sprintf(b = buf, "%#.*f", d, x) + d1;
-to be compiled.
-
-26 Nov. 1989:
-  Longer names are now accepted (up to 50 characters); names may
-contain underscores (in which case they will have two underscores
-appended, to avoid clashes with library names).
-
-28 Nov. 1989:
-  libi77 updated:
-	1. Allow 3 (or, on Crays, 4) digit exponents under format Ew.d .
-	2. Try to get things right on machines where ints have 16 bits.
-
-29 Nov. 1989:
-  Supplied missing semicolon in parameterless subroutines that
-have multiple entry points (all of them parameterless).
-
-30 Nov. 1989:
-  libf77 and libi77 revised to use types from f2c.h.
-  f2c now types floating-point valued C library routines as "double"
-rather than "doublereal" (for use with nonstandard C compilers for
-which "double" is IEEE double extended).
-
-1 Dec. 1989:
-  f2c.h updated to eliminate #defines rendered unnecessary (and,
-indeed, dangerous) by change of 26 Nov. to long names possibly
-containing underscores.
-  libi77 further revised: yesterday's change omitted two tweaks to fmt.h
-(tweaks which only matter if float and real or double and doublereal are
-different types).
-
-2 Dec. 1989:
-  Better error message (than "bad tag") for NAMELIST, which no longer
-inhibits C output.
-
-4 Dec. 1989:
-  Allow capital letters in hex constants (f77 extension; e.g.,
-x'a012BCd', X'A012BCD' and x'a012bcd' are all treated as the integer
-167848909).
-  libi77 further revised: lio.c lio.h lread.c wref.c wrtfmt.c tweaked
-again to allow float and real or double and doublereal to be different.
-
-6 Dec. 1989:
-  Revised f2c.h -- required for the following...
-  Simpler looking translations for abs, min, max, using #defines in
-revised f2c.h .
-  libi77: more corrections to types; additions for NAMELIST.
-  Corrected casts in some I/O calls.
-  Translation of NAMELIST; libi77 must still be revised.  Currently
-libi77 gives you a run-time error message if you attempt NAMELIST I/O.
-
-7 Dec. 1989:
-  Fixed bug that prevented local integer variables that appear in DATA
-stmts from being ASSIGNed statement labels.
-  Fillers (for DATA statements initializing EQUIVALENCEd variables and
-variables in COMMON) typed integer rather than doublereal (for slightly
-more portability, e.g. to Crays).
-  libi77: missing return values supplied in a few places; some tests
-reordered for better working on the Cray.
-  libf77: better accuracy for complex divide, complex square root,
-real mod function (casts to double; double temporaries).
-
-9 Dec. 1989:
-  Fixed bug that caused needless (albeit harmless) empty lines to be
-inserted in the C output when a comment line contained trailing blanks.
-  Further tweak to type of fillers: allow doublereal fillers if the
-struct has doublereal data.
-
-11 Dec. 1989:
-  Alteration of rule for producing external (C) names from names that
-contain underscores.  Now the external name is always obtained by
-appending a pair of underscores.
-
-12 Dec. 1989:
-  C production inhibited after most errors.
-
-15 Dec. 1989:
-  Fixed bug in headers for subroutines having two or more character
-strings arguments:  the length arguments were reversed.
-
-19 Dec. 1989:
-  f2c.h libf77 libi77: adjusted so #undefs in f2c.h should not foil
-compilation of libF77 and libI77.
-  libf77: getenv_ adjusted to work with unsorted environments.
-  libi77: the iostat= specifier should now work right with internal I/O.
-
-20 Dec. 1989:
-  f2c bugs fixed: In the absence of an err= specifier, the iostat=
-specifier was generally set wrong.  Character strings containing
-explicit nulls (\0) were truncated at the first null.
-  Unlabeled DO loops recognized; must be terminated by ENDDO.
-(Don't ask for CYCLE, EXIT, named DO loops, or DO WHILE.)
-
-29 Dec. 1989:
-  Nested unlabeled DO loops now handled properly; new warning for
-extraneous text at end of FORMAT.
-
-30 Dec. 1989:
-  Fixed bug in translating dble(real(...)), dble(sngl(...)), and
-dble(float(...)), where ... is either of type double complex or
-is an expression requiring assignment to intermediate variables (e.g.,
-dble(real(foo(x+1))), where foo is a function and x is a variable).
-Regard nonblank label fields on continuation lines as an error.
-
-3 Jan. 1990:
-  New option -C++ yields output that should be understood
-by C++ compilers.
-
-6 Jan. 1989:
-  -a now excludes variables that appear in a namelist from those
-that it makes automatic.  (As before, it also excludes variables
-that appear in a common, data, equivalence, or save statement.)
-  The syntactically correct Fortran
-	read(*,i) x
-	end
-now yields syntactically correct C (even though both the Fortran
-and C are buggy -- no FORMAT has not been ASSIGNed to i).
-
-7 Jan. 1990:
-  libi77: routines supporting NAMELIST added.  Surrounding quotes
-made optional when no ambiguity arises in a list or namelist READ
-of a character-string value.
-
-9 Jan. 1990:
-  f2c.src made available.
-
-16 Jan. 1990:
-  New options -P to produce ANSI C or C++ prototypes for procedures
-defined.  Change to -A and -C++: f2c tries to infer prototypes for
-invoked procedures unless the new -!P option is given.  New warning
-messages for inconsistent calling sequences among procedures within
-a single file.  Most of f2c/src is affected.
-  f2c.h: typedefs for procedure arguments added; netlib's f2c service
-will insert appropriate typedefs for use with older versions of f2c.h.
-
-17 Jan. 1990:
-  f2c/src: defs.h exec.c format.c proc.c putpcc.c version.c xsum0.out
-updated.  Castargs and protofile made extern in defs.h; exec.c
-modified so superfluous else clauses are diagnosed; unused variables
-omitted from declarations in format.c proc.c putpcc.c .
-
-21 Jan. 1990:
-  No C emitted for procedures declared external but not referenced.
-  f2c.h: more new types added for use with -P.
-  New feature: f2c accepts as arguments files ending in .p or .P;
-such files are assumed to be prototype files, such as produced by
-the -P option.  All prototype files are read before any Fortran files
-and apply globally to all Fortran files.  Suitable prototypes help f2c
-warn about calling-sequence errors and can tell f2c how to type
-procedures declared external but not explicitly typed; the latter is
-mainly of interest for users of the -A and -C++ options.  (Prototype
-arguments are not available to netlib's "execute f2c" service.)
-  New option -it tells f2c to try to infer types of untyped external
-arguments from their use as parameters to prototyped or previously
-defined procedures.
-  f2c/src: many minor cleanups; most modules changed.  Individual
-files in f2c/src are now in "bundle" format.  The former f2c.1 is
-now f2c.1t; "f2c.1t from f2c" and "f2c.1t from f2c/src" are now the
-same, as are "f2c.1 from f2c" and "f2c.1 from f2c/src".  People who
-do not obtain a new copy of "all from f2c/src" should at least add
-	fclose(sortfp);
-after the call on do_init_data(outfile, sortfp) in format_data.c .
-
-22 Jan. 1990:
-  Cleaner man page wording (thanks to Doug McIlroy).
-  -it now also applies to all untyped EXTERNAL procedures, not just
-arguments.
-
-23 Jan. 01:34:00 EST 1990:
-  Bug fixes: under -A and -C++, incorrect C was generated for
-subroutines having multiple entries but no arguments.
-  Under -A -P, subroutines of no arguments were given prototype
-calling sequence () rather than (void).
-  Character-valued functions elicited erroneous warning messages
-about inconsistent calling sequences when referenced by another
-procedure in the same file.
-  f2c.1t: omit first appearance of libF77.a in FILES section;
-load order of libraries is -lF77 -lI77, not vice versa (bug
-introduced in yesterday's edits); define .F macro for those whose
--man lacks it.  (For a while after yesterday's fixes were posted,
-f2c.1t was out of date.  Sorry!)
-
-23 Jan. 9:53:24 EST 1990:
-  Character substring expressions involving function calls having
-character arguments (including the intrinsic len function) yielded
-incorrect C.
-  Procedures defined after invocation (in the same file) with
-conflicting argument types also got an erroneous message about
-the wrong number of arguments.
-
-24 Jan. 11:44:00 EST 1990:
-  Bug fixes: -p omitted #undefs; COMMON block names containing
-underscores had their C names incorrectly computed; a COMMON block
-having the name of a previously defined procedure wreaked havoc;
-if all arguments were .P files, f2c tried reading the second as a
-Fortran file.
-  New feature: -P emits comments showing COMMON block lengths, so one
-can get warnings of incompatible COMMON block lengths by having f2c
-read .P (or .p) files.  Now by running f2c twice, first with -P -!c
-(or -P!c),  then with *.P among the arguments, you can be warned of
-inconsistent COMMON usage, and COMMON blocks having inconsistent
-lengths will be given the maximum length.  (The latter always did
-happen within each input file; now -P lets you extend this behavior
-across files.)
-
-26 Jan. 16:44:00 EST 1990:
-  Option -it made less aggressive: untyped external procedures that
-are invoked are now typed by the rules of Fortran, rather than by
-previous use of procedures to which they are passed as arguments
-before being invoked.
-  Option -P now includes information about references, i.e., called
-procedures, in the prototype files (in the form of special comments).
-This allows iterative invocations of f2c to infer more about untyped
-external names, particularly when multiple Fortran files are involved.
-  As usual, there are some obscure bug fixes:
-1.  Repair of erroneous warning messages about inconsistent number of
-arguments that arose when a character dummy parameter was discovered
-to be a function or when multiple entry points involved character
-variables appearing in a previous entry point.
-2.  Repair of memory fault after error msg about "adjustable character
-function".
-3.  Under -U, allow MAIN_ as a subroutine name (in the same file as a
-main program).
-4.  Change for consistency: a known function invoked as a subroutine,
-then as a function elicits a warning rather than an error.
-
-26 Jan. 22:32:00 EST 1990:
-  Fixed two bugs that resulted in incorrect C for substrings, within
-the body of a character-valued function, of the function's name, when
-those substrings were arguments to another function (even implicitly,
-as in character-string assignment).
-
-28 Jan. 18:32:00 EST 1990:
-  libf77, libi77: checksum files added; "make check" looks for
-transmission errors.  NAMELIST read modified to allow $ rather than &
-to precede a namelist name, to allow $ rather than / to terminate
-input where the name of another variable would otherwise be expected,
-and to regard all nonprinting ASCII characters <= ' ' as spaces.
-
-29 Jan. 02:11:00 EST 1990:
-  "fc from f2c" added.
-  -it option made the default; -!it turns it off.  Type information is
-now updated in a previously missed case.
-  -P option tweaked again; message about when rerunning f2c may change
-prototypes or declarations made more accurate.
-  New option -Ps implies -P and returns exit status 4 if rerunning
-f2c -P with prototype inputs might change prototypes or declarations.
-Now you can execute a crude script like
-
-	cat *.f >zap.F
-	rm -f zap.P
-	while :; do
-		f2c -Ps -!c zap.[FP]
-		case $? in 4) ;; *) break;; esac
-		done
-
-to get a file zap.P of the best prototypes f2c can determine for *.f .
-
-Jan. 29 07:30:21 EST 1990:
-  Forgot to check for error status when setting return code 4 under -Ps;
-error status (1, 2, 3, or, for caught signal, 126) now takes precedence.
-
-Jan 29 14:17:00 EST 1990:
-  Incorrect handling of
-	open(n,'filename')
-repaired -- now treated as
-	open(n,file='filename')
-(and, under -ext, given an error message).
-  New optional source file memset.c for people whose systems don't
-provide memset, memcmp, and memcpy; #include  in mem.c
-changed to #include "string.h" so BSD people can create a local
-string.h that simply says #include  .
-
-Jan 30 10:34:00 EST 1990:
-  Fix erroneous warning at end of definition of a procedure with
-character arguments when the procedure had previously been called with
-a numeric argument instead of a character argument.  (There were two
-warnings, the second one incorrectly complaining of a wrong number of
-arguments.)
-
-Jan 30 16:29:41 EST 1990:
-  Fix case where -P and -Ps erroneously reported another iteration
-necessary.  (Only harm is the extra iteration.)
-
-Feb 3 01:40:00 EST 1990:
-  Supply semicolon occasionally omitted under -c .
-  Try to force correct alignment when numeric variables are initialized
-with character data (a non-standard and non-portable practice).  You
-must use the -W option if your code has such data statements and is
-meant to run on a machine with other than 4 characters/word; e.g., for
-code meant to run on a Cray, you would specify -W8 .
-  Allow parentheses around expressions in output lists (in write and
-print statements).
-  Rename source files so their names are <= 12 characters long
-(so there's room to append .Z and still have <= 14 characters);
-renamed files:  formatdata.c niceprintf.c niceprintf.h safstrncpy.c .
-  f2c material made available by anonymous ftp from research.att.com
-(look in dist/f2c ).
-
-Feb 3 03:49:00 EST 1990:
-  Repair memory fault that arose from use (in an assignment or
-call) of a non-argument variable declared CHARACTER*(*).
-
-Feb 9 01:35:43 EST 1990:
-  Fix erroneous error msg about bad types in
-	subroutine foo(a,adim)
-	dimension a(adim)
-	integer adim
-  Fix improper passing of character args (and possible memory fault)
-in the expression part of a computed goto.
-  Fix botched calling sequences in array references involving
-functions having character args.
-  Fix memory fault caused by invocation of character-valued functions
-of no arguments.
-  Fix botched calling sequence of a character*1-valued function
-assigned to a character*1 variable.
-  Fix bug in error msg for inconsistent number of args in prototypes.
-  Allow generation of C output despite inconsistencies in prototypes,
-but give exit code 8.
-  Simplify include logic (by removing some bogus logic); never
-prepend "/usr/include/" to file names.
-  Minor cleanups (that should produce no visible change in f2c's
-behavior) in intr.c parse.h main.c defs.h formatdata.c p1output.c .
-
-Feb 10 00:19:38 EST 1990:
-  Insert (integer) casts when floating-point expressions are used
-as subscripts.
-  Make SAVE stmt (with no variable list) override -a .
-  Minor cleanups: change field to Field in struct Addrblock (for the
-benefit of buggy C compilers); omit system("/bin/cp ...") in misc.c .
-
-Feb 13 00:39:00 EST 1990:
-  Error msg fix in gram.dcl: change "cannot make %s parameter"
-to "cannot make into parameter".
-
-Feb 14 14:02:00 EST 1990:
-  Various cleanups (invisible on systems with 4-byte ints), thanks
-to Dave Regan: vaxx.c eliminated; %d changed to %ld various places;
-external names adjusted for the benefit of stupid systems (that ignore
-case and recognize only 6 significant characters in external names);
-buffer shortened in xsum.c (e.g. for MS-DOS); fopen modes distinguish
-text and binary files; several unused functions eliminated; missing
-arg supplied to an unlikely fatalstr invocation.
-
-Thu Feb 15 19:15:53 EST 1990:
-  More cleanups (invisible on systems with 4 byte ints); casts inserted
-so most complaints from cyntax(1) and lint(1) go away; a few (int)
-versus (long) casts corrected.
-
-Fri Feb 16 19:55:00 EST 1990:
-  Recognize and translate unnamed Fortran 8x do while statements.
-  Fix bug that occasionally caused improper breaking of character
-strings.
-  New error message for attempts to provide DATA in a type-declaration
-statement.
-
-Sat Feb 17 11:43:00 EST 1990:
-  Fix infinite loop clf -> Fatal -> done -> clf after I/O error.
-  Change "if (addrp->vclass = CLPROC)" to "if (addrp->vclass == CLPROC)"
-in p1_addr (in p1output.c); this was probably harmless.
-  Move a misplaced } in lex.c (which slowed initkey()).
-  Thanks to Gary Word for pointing these things out.
-
-Sun Feb 18 18:07:00 EST 1990:
-  Detect overlapping initializations of arrays and scalar variables
-in previously missed cases.
-  Treat logical*2 as logical (after issuing a warning).
-  Don't pass string literals to p1_comment().
-  Correct a cast (introduced 16 Feb.) in gram.expr; this matters e.g.
-on a Cray.
-  Attempt to isolate UNIX-specific things in sysdep.c (a new source
-file).  Unless sysdep.c is compiled with SYSTEM_SORT defined, the
-intermediate files created for DATA statements are now sorted in-core
-without invoking system().
-
-Tue Feb 20 16:10:35 EST 1990:
-  Move definition of binread and binwrite from init.c to sysdep.c .
-  Recognize Fortran 8x tokens < <= == >= > <> as synonyms for
-.LT. .LE. .EQ. .GE. .GT. .NE.
-  Minor cleanup in putpcc.c:  fully remove simoffset().
-  More discussion of system dependencies added to libI77/README.
-
-Tue Feb 20 21:44:07 EST 1990:
-  Minor cleanups for the benefit of EBCDIC machines -- try to remove
-the assumption that 'a' through 'z' are contiguous.  (Thanks again to
-Gary Word.)  Also, change log2 to log_2 (shouldn't be necessary).
-
-Wed Feb 21 06:24:56 EST 1990:
-  Fix botch in init.c introduced in previous change; only matters
-to non-ASCII machines.
-
-Thu Feb 22 17:29:12 EST 1990:
-  Allow several entry points to mention the same array.  Protect
-parameter adjustments with if's (for the case that an array is not
-an argument to all entrypoints).
-  Under -u, allow
-	subroutine foo(x,n)
-	real x(n)
-	integer n
-  Compute intermediate variables used to evaluate dimension expressions
-at the right time.  Example previously mistranslated:
-	subroutine foo(x,k,m,n)
-	real x(min(k,m,n))
-	...
-	write(*,*) x
-  Detect duplicate arguments.  (The error msg points to the first
-executable stmt -- not wonderful, but not worth fixing.)
-  Minor cleanup of min/max computation (sometimes slightly simpler).
-
-Sun Feb 25 09:39:01 EST 1990:
-  Minor tweak to multiple entry points: protect parameter adjustments
-with if's only for (array) args that do not appear in all entry points.
-  Minor tweaks to format.c and io.c (invisible unless your compiler
-complained at the duplicate #defines of IOSUNIT and IOSFMT or at
-comparisons of p1gets(...) with NULL).
-
-Sun Feb 25 18:40:10 EST 1990:
-  Fix bug introduced Feb. 22: if a subprogram contained DATA and the
-first executable statement was labeled, then the label got lost.
-(Just change INEXEC to INDATA in p1output.c; it occurs just once.)
-
-Mon Feb 26 17:45:10 EST 1990:
-  Fix bug in handling of " and ' in comments.
-
-Wed Mar 28 01:43:06 EST 1990:
-libI77:
- 1. Repair nasty I/O bug: opening two files and closing the first
-(after possibly reading or writing it), then writing the second caused
-the last buffer of the second to be lost.
- 2. Formatted reads of logical values treated all letters other than
-t or T as f (false).
- libI77 files changed: err.c rdfmt.c Version.c
- (Request "libi77 from f2c" -- you can't get these files individually.)
-
-f2c itself:
-  Repair nasty bug in translation of
-	ELSE IF (condition involving complicated abs, min, or max)
--- auxiliary statements were emitted at the wrong place.
-  Supply semicolon previously omitted from the translation of a label
-(of a CONTINUE) immediately preceding an ELSE IF or an ELSE.  This
-bug made f2c produce invalid C.
-  Correct a memory fault that occurred (on some machines) when the
-error message "adjustable dimension on non-argument" should be given.
-  Minor tweaks to remove some harmless warnings by overly chatty C
-compilers.
-  Argument arays having constant dimensions but a variable lower bound
-(e.g., x(n+1:n+3)) had a * omitted from scalar arguments involved in
-the array offset computation.
-
-Wed Mar 28 18:47:59 EST 1990:
-libf77: add exit(0) to end of main [return(0) encounters a Cray bug]
-
-Sun Apr  1 16:20:58 EDT 1990:
-  Avoid dereferencing null when processing equivalences after an error.
-
-Fri Apr  6 08:29:49 EDT 1990:
-  Calls involving alternate return specifiers omitted processing
-needed for things like min, max, abs, and // (concatenation).
-  INTEGER*2 PARAMETERs were treated as INTEGER*4.
-  Convert some O(n^2) parsing to O(n).
-
-Tue Apr 10 20:07:02 EDT 1990:
-  When inconsistent calling sequences involve differing numbers of
-arguments, report the first differing argument rather than the numbers
-of arguments.
-  Fix bug under -a: formatted I/O in which either the unit or the
-format was a local character variable sometimes resulted in invalid C
-(a static struct initialized with an automatic component).
-  Improve error message for invalid flag after elided -.
-  Complain when literal table overflows, rather than infinitely
-looping.  (The complaint mentions the new and otherwise undocumented
--NL option for specifying a larger literal table.)
-  New option -h for forcing strings to word (or, with -hd, double-word)
-boundaries where possible.
-  Repair a bug that could cause improper splitting of strings.
-  Fix bug (cast of c to doublereal) in
-	subroutine foo(c,r)
-	double complex c
-	double precision r
-	c = cmplx(r,real(c))
-	end
-  New include file "sysdep.h" has some things from defs.h (and
-elsewhere) that one may need to modify on some systems.
-  Some large arrays that were previously statically allocated are now
-dynamically allocated when f2c starts running.
-  f2c/src files changed:
-	README cds.c defs.h f2c.1 f2c.1t format.c formatdata.c init.c
-	io.c lex.c main.c makefile mem.c misc.c names.c niceprintf.c
-	output.c parse_args.c pread.c put.c putpcc.c sysdep.h
-	version.c xsum0.out
-
-Wed Apr 11 18:27:12 EDT 1990:
-  Fix bug in argument consistency checking of character, complex, and
-double complex valued functions.  If the same source file contained a
-definition of such a function with arguments not explicitly typed,
-then subsequent references to the function might get erroneous
-warnings of inconsistent calling sequences.
-  Tweaks to sysdep.h for partially ANSI systems.
-  New options -kr and -krd cause f2c to use temporary variables to
-enforce Fortran evaluation-order rules with pernicious, old-style C
-compilers that apply the associative law to floating-point operations.
-
-Sat Apr 14 15:50:15 EDT 1990:
-  libi77: libI77 adjusted to allow list-directed and namelist I/O
-of internal files; bug in namelist I/O of logical and character arrays
-fixed; list input of complex numbers adjusted to permit d or D to
-denote the start of the exponent field of a component.
-  f2c itself: fix bug in handling complicated lower-bound
-expressions for character substrings; e.g., min and max did not work
-right, nor did function invocations involving character arguments.
-  Switch to octal notation, rather than hexadecimal, for nonprinting
-characters in character and string constants.
-  Fix bug (when neither -A nor -C++ was specified) in typing of
-external arguments of type complex, double complex, or character:
-	subroutine foo(c)
-	external c
-	complex c
-now results in
-	/* Complex */ int (*c) ();
-(as, indeed, it once did) rather than
-	complex (*c) ();
-
-Sat Apr 14 22:50:39 EDT 1990:
-  libI77/makefile: updated "make check" to omit lio.c
-  lib[FI]77/makefile: trivial change: define CC = cc, reference $(CC).
-  (Request, e.g., "libi77 from f2c" -- you can't ask for individual
-files from lib[FI]77.)
-
-Wed Apr 18 00:56:37 EDT 1990:
-  Move declaration of atof() from defs.h to sysdep.h, where it is
-now not declared if stdlib.h is included.  (NeXT's stdlib.h has a
-#define atof that otherwise wreaks havoc.)
-  Under -u, provide a more intelligible error message (than "bad tag")
-for an attempt to define a function without specifying its type.
-
-Wed Apr 18 17:26:27 EDT 1990:
-  Recognize \v (vertical tab) in Hollerith as well as quoted strings;
-add recognition of \r (carriage return).
-  New option -!bs turns off recognition of escapes in character strings
-(\0, \\, \b, \f, \n, \r, \t, \v).
-  Move to sysdep.c initialization of some arrays whose initialization
-assumed ASCII; #define Table_size in sysdep.h rather than using
-hard-coded 256 in allocating arrays of size 1 << (bits/byte).
-
-Thu Apr 19 08:13:21 EDT 1990:
-  Warn when escapes would make Hollerith extend beyond statement end.
-  Omit max() definition from misc.c (should be invisible except on
-systems that erroneously #define max in stdlib.h).
-
-Mon Apr 23 22:24:51 EDT 1990:
-  When producing default-style C (no -A or -C++), cast switch
-expressions to (int).
-  Move "-lF77 -lI77 -lm -lc" to link_msg, defined in sysdep.c .
-  Add #define scrub(x) to sysdep.h, with invocations in format.c and
-formatdata.c, so that people who have systems like VMS that would
-otherwise create multiple versions of intermediate files can
-#define scrub(x) unlink(x)
-
-Tue Apr 24 18:28:36 EDT 1990:
-  Pass string lengths once rather than twice to a function of character
-arguments involved in comparison of character strings of length 1.
-
-Fri Apr 27 13:11:52 EDT 1990:
-  Fix bug that made f2c gag on concatenations involving char(...) on
-some systems.
-
-Sat Apr 28 23:20:16 EDT 1990:
-  Fix control-stack bug in
-	if(...) then
-	else if (complicated condition)
-	else
-	endif
-(where the complicated condition causes assignment to an auxiliary
-variable, e.g., max(a*b,c)).
-
-Mon Apr 30 13:30:10 EDT 1990:
-  Change fillers for DATA with holes from substructures to arrays
-(in an attempt to make things work right with C compilers that have
-funny padding rules for substructures, e.g., Sun C compilers).
-  Minor cleanup of exec.c (should not affect generated C).
-
-Mon Apr 30 23:13:51 EDT 1990:
-  Fix bug in handling return values of functions having multiple
-entry points of differing return types.
-
-Sat May  5 01:45:18 EDT 1990:
-  Fix type inference bug in
-	subroutine foo(x)
-	call goo(x)
-	end
-	subroutine goo(i)
-	i = 3
-	end
-Instead of warning of inconsistent calling sequences for goo,
-f2c was simply making i a real variable; now i is correctly
-typed as an integer variable, and f2c issues an error message.
-  Adjust error messages issued at end of declarations so they
-don't blame the first executable statement.
-
-Sun May  6 01:29:07 EDT 1990:
-  Fix bug in -P and -Ps: warn when the definition of a subprogram adds
-information that would change prototypes or previous declarations.
-
-Thu May 10 18:09:15 EDT 1990:
-  Fix further obscure bug with (default) -it: inconsistent calling
-sequences and I/O statements could interact to cause a memory fault.
-Example:
-      SUBROUTINE FOO
-      CALL GOO(' Something') ! Forgot integer first arg
-      END
-      SUBROUTINE GOO(IUNIT,MSG)
-      CHARACTER*(*)MSG
-      WRITE(IUNIT,'(1X,A)') MSG
-      END
-
-Fri May 11 16:49:11 EDT 1990:
-  Under -!c, do not delete any .c files (when there are errors).
-  Avoid dereferencing 0 when a fatal error occurs while reading
-Fortran on stdin.
-
-Wed May 16 18:24:42 EDT 1990:
-  f2c.ps made available.
-
-Mon Jun  4 12:53:08 EDT 1990:
-  Diagnose I/O units of invalid type.
-  Add specific error msg about dummy arguments in common.
-
-Wed Jun 13 12:43:17 EDT 1990:
-  Under -A, supply a missing "[1]" for CHARACTER*1 variables that appear
-both in a DATA statement and in either COMMON or EQUIVALENCE.
-
-Mon Jun 18 16:58:31 EDT 1990:
-  Trivial updates to f2c.ps .  ("Fortran 8x" --> "Fortran 90"; omit
-"(draft)" from "(draft) ANSI C".)
-
-Tue Jun 19 07:36:32 EDT 1990:
-  Fix incorrect code generated for ELSE IF(expression involving
-function call passing non-constant substring).
-  Under -h, preserve the property that strings are null-terminated
-where possible.
-  Remove spaces between # and define in lex.c output.c parse.h .
-
-Mon Jun 25 07:22:59 EDT 1990:
-  Minor tweak to makefile to reduce unnecessary recompilations.
-
-Tue Jun 26 11:49:53 EDT 1990:
-  Fix unintended truncation of some integer constants on machines
-where casting a long to (int) may change the value.  E.g., when f2c
-ran on machines with 16-bit ints, "i = 99999" was being translated
-to "i = -31073;".
-
-Wed Jun 27 11:05:32 EDT 1990:
-  Arrange for CHARACTER-valued PARAMETERs to honor their length
-specifications.  Allow CHAR(nn) in expressions defining such PARAMETERs.
-
-Fri Jul 20 09:17:30 EDT 1990:
-  Avoid dereferencing 0 when a FORMAT statement has no label.
-
-Thu Jul 26 11:09:39 EDT 1990:
-  Remarks about VOID and binread,binwrite added to README.
-  Tweaks to parse_args: should be invisible unless your compiler
-complained at (short)*store.
-
-Thu Aug  2 02:07:58 EDT 1990:
-  f2c.ps: change the first line of page 5 from
-	include stuff
-to
-	include 'stuff'
-
-Tue Aug 14 13:21:24 EDT 1990:
-  libi77: libI77 adjusted to treat tabs as spaces in list input.
-
-Fri Aug 17 07:24:53 EDT 1990:
-  libi77: libI77 adjusted so a blank='ZERO' clause (upper case Z)
-in an open of a currently open file works right.
-
-Tue Aug 28 01:56:44 EDT 1990:
-  Fix bug in warnings of inconsistent calling sequences: if an
-argument to a subprogram was never referenced, then a previous
-invocation of the subprogram (in the same source file) that
-passed something of the wrong type for that argument did not
-elicit a warning message.
-
-Thu Aug 30 09:46:12 EDT 1990:
-  libi77: prevent embedded blanks in list output of complex values;
-omit exponent field in list output of values of magnitude between
-10 and 1e8; prevent writing stdin and reading stdout or stderr;
-don't close stdin, stdout, or stderr when reopening units 5, 6, 0.
-
-Tue Sep  4 12:30:57 EDT 1990:
-  Fix bug in C emitted under -I2 or -i2 for INTEGER*4 FUNCTION.
-  Warn of missing final END even if there are previous errors.
-
-Fri Sep  7 13:55:34 EDT 1990:
-  Remark about "make xsum.out" and "make f2c" added to README.
-
-Tue Sep 18 23:50:01 EDT 1990:
-  Fix null dereference (and, on some systems, writing of bogus *_com.c
-files) under -ec or -e1c when a prototype file (*.p or *.P) describes
-COMMON blocks that do not appear in the Fortran source.
-  libi77:
-    Add some #ifdef lines (#ifdef MSDOS, #ifndef MSDOS) to avoid
-references to stat and fstat on non-UNIX systems.
-    On UNIX systems, add component udev to unit; decide that old
-and new files are the same iff both the uinode and udev components
-of unit agree.
-    When an open stmt specifies STATUS='OLD', use stat rather than
-access (on UNIX systems) to check the existence of the file (in case
-directories leading to the file have funny permissions and this is
-a setuid or setgid program).
-
-Thu Sep 27 16:04:09 EDT 1990:
-  Supply missing entry for Impldoblock in blksize array of cpexpr
-(in expr.c).  No examples are known where this omission caused trouble.
-
-Tue Oct  2 22:58:09 EDT 1990:
-  libf77: test signal(...) == SIG_IGN rather than & 01 in main().
-  libi77: adjust rewind.c so two successive rewinds after a write
-don't clobber the file.
-
-Thu Oct 11 18:00:14 EDT 1990:
-  libi77: minor cleanups: add #include "fcntl.h" to endfile.c, err.c,
-open.c; adjust g_char in util.c for segmented memories; in f_inqu
-(inquire.c), define x appropriately when MSDOS is defined.
-
-Mon Oct 15 20:02:11 EDT 1990:
-  Add #ifdef MSDOS pointer adjustments to mem.c; treat NAME= as a
-synonym for FILE= in OPEN statements.
-
-Wed Oct 17 16:40:37 EDT 1990:
-  libf77, libi77: minor cleanups: _cleanup() and abort() invocations
-replaced by invocations of sig_die in main.c; some error messages
-previously lost in buffers will now appear.
-
-Mon Oct 22 16:11:27 EDT 1990:
-  libf77: separate sig_die from main (for folks who don't want to use
-the main in libF77).
-  libi77: minor tweak to comments in README.
-
-Fri Nov  2 13:49:35 EST 1990:
-  Use two underscores rather than one in generated temporary variable
-names to avoid conflict with COMMON names.  f2c.ps updated to reflect
-this change and the NAME= extension introduced 15 Oct.
-  Repair a rare memory fault in io.c .
-
-Mon Nov  5 16:43:55 EST 1990:
-  libi77: changes to open.c (and err.c): complain if an open stmt
-specifies new= and the file already exists (as specified by Fortrans 77
-and 90); allow file= to be omitted in open stmts and allow
-status='replace' (Fortran 90 extensions).
-
-Fri Nov 30 10:10:14 EST 1990:
-  Adjust malloc.c for unusual systems whose sbrk() can return values
-not properly aligned for doubles.
-  Arrange for slightly more helpful and less repetitive warnings for
-non-character variables initialized with character data; these warnings
-are (still) suppressed by -w66.
-
-Fri Nov 30 15:57:59 EST 1990:
-  Minor tweak to README (about changing VOID in f2c.h).
-
-Mon Dec  3 07:36:20 EST 1990:
-  Fix spelling of "character" in f2c.1t.
-
-Tue Dec  4 09:48:56 EST 1990:
-  Remark about link_msg and libf2c added to f2c/README.
-
-Thu Dec  6 08:33:24 EST 1990:
-  Under -U, render label nnn as L_nnn rather than Lnnn.
-
-Fri Dec  7 18:05:00 EST 1990:
-  Add more names from f2c.h (e.g. integer, real) to the c_keywords
-list of names to which an underscore is appended to avoid confusion.
-
-Mon Dec 10 19:11:15 EST 1990:
-  Minor tweaks to makefile (./xsum) and README (binread/binwrite).
-  libi77: a few modifications for POSIX systems; meant to be invisible
-elsewhere.
-
-Sun Dec 16 23:03:16 EST 1990:
-  Fix null dereference caused by unusual erroneous input, e.g.
-	call foo('abc')
-	end
-	subroutine foo(msg)
-	data n/3/
-	character*(*) msg
-	end
-(Subroutine foo is illegal because the character statement comes after a
-data statement.)
-  Use decimal rather than hex constants in xsum.c (to prevent
-erroneous warning messages about constant overflow).
-
-Mon Dec 17 12:26:40 EST 1990:
-  Fix rare extra underscore in character length parameters passed
-for multiple entry points.
-
-Wed Dec 19 17:19:26 EST 1990:
-  Allow generation of C despite error messages about bad alignment
-forced by equivalence.
-  Allow variable-length concatenations in I/O statements, such as
-	open(3, file=bletch(1:n) // '.xyz')
-
-Fri Dec 28 17:08:30 EST 1990:
-  Fix bug under -p with formats and internal I/O "units" in COMMON,
-as in
-      COMMON /FIGLEA/F
-      CHARACTER*20 F
-      F = '(A)'
-      WRITE (*,FMT=F) 'Hello, world!'
-      END
-
-Tue Jan 15 12:00:24 EST 1991:
-  Fix bug when two equivalence groups are merged, the second with
-nonzero offset, and the result is then merged into a common block.
-Example:
-      INTEGER W(3), X(3), Y(3), Z(3)
-      COMMON /ZOT/ Z
-      EQUIVALENCE (W(1),X(1)), (X(2),Y(1)), (Z(3),X(1))
-***** W WAS GIVEN THE WRONG OFFSET
-  Recognize Fortran 90's optional NML= in NAMELIST READs and WRITEs.
-(Currently NML= and FMT= are treated as synonyms -- there's no
-error message if, e.g., NML= specifies a format.)
-  libi77: minor adjustment to allow internal READs from character
-string constants in read-only memory.
-
-Fri Jan 18 22:56:15 EST 1991:
-  Add comment to README about needing to comment out the typedef of
-size_t in sysdep.h on some systems, e.g. Sun 4.1.
-  Fix misspelling of "statement" in an error message in lex.c
-
-Wed Jan 23 00:38:48 EST 1991:
-  Allow hex, octal, and binary constants to have the qualifying letter
-(z, x, o, or b) either before or after the quoted string containing the
-digits.  For now this change will not be reflected in f2c.ps .
-
-Tue Jan 29 16:23:45 EST 1991:
-  Arrange for character-valued statement functions to give results of
-the right length (that of the statement function's name).
-
-Wed Jan 30 07:05:32 EST 1991:
-  More tweaks for character-valued statement functions: an error
-check and an adjustment so a right-hand side of nonconstant length
-(e.g., a substring) is handled right.
-
-Wed Jan 30 09:49:36 EST 1991:
-  Fix p1_head to avoid printing (char *)0 with %s.
-
-Thu Jan 31 13:53:44 EST 1991:
-  Add a test after the cleanup call generated for I/O statements with
-ERR= or END= clauses to catch the unlikely event that the cleanup
-routine encounters an error.
-
-Mon Feb  4 08:00:58 EST 1991:
-  Minor cleanup: omit unneeded jumps and labels from code generated for
-some NAMELIST READs and WRITEs with IOSTAT=, ERR=, and/or END=.
-
-Tue Feb  5 01:39:36 EST 1991:
-  Change Mktemp to mktmp (for the benefit of systems so brain-damaged
-that they do not distinguish case in external names -- and that for
-some reason want to load mktemp).  Try to get xsum0.out right this
-time (it somehow didn't get updated on 4 Feb. 1991).
-  Add note to libi77/README about adjusting the interpretation of
-RECL= specifiers in OPENs for direct unformatted I/O.
-
-Thu Feb  7 17:24:42 EST 1991:
-  New option -r casts values of REAL functions, including intrinsics,
-to REAL.  This only matters for unportable code like
-	real r
-	r = asin(1.)
-	if (r .eq. asin(1.)) ...
-[The behavior of such code varies with the Fortran compiler used --
-and sometimes is affected by compiler options.]  For now, the man page
-at the end of f2c.ps is the only part of f2c.ps that reflects this new
-option.
-
-Fri Feb  8 18:12:51 EST 1991:
-  Cast pointer differences passed as arguments to the appropriate type.
-This matters, e.g., with MSDOS compilers that yield a long pointer
-difference but have int == short.
-  Disallow nonpositive dimensions.
-
-Fri Feb 15 12:24:15 EST 1991:
-  Change %d to %ld in sprintf call in putpower in putpcc.c.
-  Free more memory (e.g. allowing translation of larger Fortran
-files under MS-DOS).
-  Recognize READ (character expression) and WRITE (character expression)
-as formatted I/O with the format given by the character expression.
-  Update year in Notice.
-
-Sat Feb 16 00:42:32 EST 1991:
-  Recant recognizing WRITE(character expression) as formatted output
--- Fortran 77 is not symmetric in its syntax for READ and WRITE.
-
-Mon Mar  4 15:19:42 EST 1991:
-  Fix bug in passing the real part of a complex argument to an intrinsic
-function.  Omit unneeded parentheses in nested calls to intrinsics.
-Example:
-	subroutine foo(x, y)
-	complex y
-	x = exp(sin(real(y))) + exp(imag(y))
-	end
-
-Fri Mar  8 15:05:42 EST 1991:
-  Fix a comment in expr.c; omit safstrncpy.c (which had bugs in
-cases not used by f2c).
-
-Wed Mar 13 02:27:23 EST 1991:
-  Initialize firstmemblock->next in mem_init in mem.c .  [On most
-systems it was fortuituously 0, but with System V, -lmalloc could
-trip on this missed initialization.]
-
-Wed Mar 13 11:47:42 EST 1991:
-  Fix a reference to freed memory.
-
-Wed Mar 27 00:42:19 EST 1991:
-  Fix a memory fault caused by such illegal Fortran as
-       function foo
-       x = 3
-       logical foo	! declaration among executables
-       foo=.false.	! used to suffer memory fault
-       end
-
-Fri Apr  5 08:30:31 EST 1991:
-  Fix loss of % in some format expressions, e.g.
-	write(*,'(1h%)')
-  Fix botch introduced 27 March 1991 that caused subroutines with
-multiple entry points to have extraneous declarations of ret_val.
-
-Fri Apr  5 12:44:02 EST 1991
-  Try again to omit extraneous ret_val declarations -- this morning's
-fix was sometimes wrong.
-
-Mon Apr  8 13:47:06 EDT 1991:
-  Arrange for s_rnge to have the right prototype under -A -C .
-
-Wed Apr 17 13:36:03 EDT 1991:
-  New fatal error message for apparent invocation of a recursive
-statement function.
-
-Thu Apr 25 15:13:37 EDT 1991:
-  F2c and libi77 adjusted so NAMELIST works with -i2.  (I forgot
-about -i2 when adding NAMELIST.)  This required a change to f2c.h
-(that only affects NAMELIST I/O under -i2.)  Man-page description of
--i2 adjusted to reflect that -i2 stores array lengths in short ints.
-
-Fri Apr 26 02:54:41 EDT 1991:
-  Libi77: fix some bugs in NAMELIST reading of multi-dimensional arrays
-(file rsne.c).
-
-Thu May  9 02:13:51 EDT 1991:
-  Omit a trailing space in expr.c (could cause a false xsum value if
-a mailer drops the trailing blank).
-
-Thu May 16 13:14:59 EDT 1991:
-  Libi77: increase LEFBL in lio.h to overcome a NeXT bug.
-  Tweak for compilers that recognize "nested" comments: inside comments,
-turn /* into /+ (as well as */ into +/).
-
-Sat May 25 11:44:25 EDT 1991:
-  libf77: s_rnge: declare line long int rather than int.
-
-Fri May 31 07:51:50 EDT 1991:
-  libf77: system_: officially return status.
-
-Mon Jun 17 16:52:53 EDT 1991:
-  Minor tweaks: omit unnecessary declaration of strcmp (that caused
-trouble on a system where strcmp was a macro) from misc.c; add
-SHELL = /bin/sh to makefiles.
-  Fix a dereference of null when a CHARACTER*(*) declaration appears
-(illegally) after DATA.  Complain only once per subroutine about
-declarations appearing after DATA.
-
-Mon Jul  1 00:28:13 EDT 1991:
-  Add test and error message for illegal use of subroutine names, e.g.
-      SUBROUTINE ZAP(A)
-      ZAP = A
-      END
-
-Mon Jul  8 21:49:20 EDT 1991:
-  Issue a warning about things like
-	integer i
-	i = 'abc'
-(which is treated as i = ichar('a')).  [It might be nice to treat 'abc'
-as an integer initialized (in a DATA statement) with 'abc', but
-other matters have higher priority.]
-  Render
-	i = ichar('A')
-as
-	i = 'A';
-rather than
-	i = 65;
-(which assumes ASCII).
-
-Fri Jul 12 07:41:30 EDT 1991:
-  Note added to README about erroneous definitions of __STDC__ .
-
-Sat Jul 13 13:38:54 EDT 1991:
-  Fix bugs in double type convesions of complex values, e.g.
-sngl(real(...)) or dble(real(...)) (where ... is complex).
-
-Mon Jul 15 13:21:42 EDT 1991:
-  Fix bug introduced 8 July 1991 that caused erroneous warnings
-"ichar([first char. of] char. string) assumed for conversion to numeric"
-when a subroutine had an array of character strings as an argument.
-
-Wed Aug 28 01:12:17 EDT 1991:
-  Omit an unused function in format.c, an unused variable in proc.c .
-  Under -r8, promote complex to double complex (as the man page claims).
-
-Fri Aug 30 17:19:17 EDT 1991:
-  f2c.ps updated: slightly expand description of intrinsics and,or,xor,
-not; add mention of intrinsics lshift, rshift; add note about f2c
-accepting Fortran 90 inline comments (starting with !); update Cobalt
-Blue address.
-
-Tue Sep 17 07:17:33 EDT 1991:
-  libI77: err.c and open.c modified to use modes "rb" and "wb"
-when (f)opening unformatted files; README updated to point out
-that it may be necessary to change these modes to "r" and "w"
-on some non-ANSI systems.
-
-Tue Oct 15 10:25:49 EDT 1991:
-  Minor tweaks that make some PC compilers happier: insert some
-casts, add args to signal functions.
-  Change -g to emit uncommented #line lines -- and to emit more of them;
-update fc, f2c.1, f2c.1t, f2c.ps to reflect this.
-  Change uchar to Uchar in xsum.c .
-  Bring gram.c up to date.
-
-Thu Oct 17 09:22:05 EDT 1991:
-  libi77: README, fio.h, sue.c, uio.c changed so the length field
-in unformatted sequential records has type long rather than int
-(unless UIOLEN_int is #defined).  This is for systems where sizeof(int)
-can vary, depending on the compiler or compiler options.
-
-Thu Oct 17 13:42:59 EDT 1991:
-  libi77: inquire.c: when MSDOS is defined, don't strcmp units[i].ufnm
-when it is NULL.
-
-Fri Oct 18 15:16:00 EDT 1991:
-  Correct xsum0.out in "all from f2c/src" (somehow botched on 15 Oct.).
-
-Tue Oct 22 18:12:56 EDT 1991:
-  Fix memory fault when a character*(*) argument is used (illegally)
-as a dummy variable in the definition of a statement function.  (The
-memory fault occurred when the statement function was invoked.)
-  Complain about implicit character*(*).
-
-Thu Nov 14 08:50:42 EST 1991:
-  libi77: change uint to Uint in fmt.h, rdfmt.c, wrtfmt.c; this change
-should be invisible unless you're running a brain-damaged system.
-
-Mon Nov 25 19:04:40 EST 1991:
-  libi77: correct botches introduced 17 Oct. 1991 and 14 Nov. 1991
-(change uint to Uint in lwrite.c; other changes that only matter if
-sizeof(int) != sizeof(long)).
-  Add a more meaningful error message when bailing out due to an attempt
-to invoke a COMMON variable as a function.
-
-Sun Dec  1 19:29:24 EST 1991:
-  libi77: uio.c: add test for read failure (seq. unformatted reads);
-adjust an error return from EOF to off end of record.
-
-Tue Dec 10 17:42:28 EST 1991:
-  Add tests to prevent memory faults with bad uses of character*(*).
-
-Thu Dec 12 11:24:41 EST 1991:
-  libi77: fix bug with internal list input that caused the last
-character of each record to be ignored; adjust error message in
-internal formatted input from "end-of-file" to "off end of record"
-if the format specifies more characters than the record contains.
-
-Wed Dec 18 17:48:11 EST 1991:
-  Fix bug in translating nonsensical ichar invocations involving
-concatenations.
-  Fix bug in passing intrinsics lle, llt, lge, lgt as arguments;
-hl_le was being passed rather than l_le, etc.
-  libf77: adjust length parameters from long to ftnlen, for
-compiling with f2c_i2 defined.
-
-Sat Dec 21 15:30:57 EST 1991:
-  Allow DO nnn ... to end with an END DO statement labelled nnn.
-
-Tue Dec 31 13:53:47 EST 1991:
-  Fix bug in handling dimension a(n**3,2) -- pow_ii was called
-incorrectly.
-  Fix bug in translating
-	subroutine x(abc,n)
-	character abc(n)
-	write(abc,'(i10)') 123
-	end
-(omitted declaration and initialiation of abc_dim1).
-  Complain about dimension expressions of such invalid types
-as complex and logical.
-
-Fri Jan 17 11:54:20 EST 1992:
-  Diagnose some illegal uses of main program name (rather than
-memory faulting).
-  libi77:  (1) In list and namelist input, treat "r* ," and "r*,"
-alike (where r is a positive integer constant), and fix a bug in
-handling null values following items with repeat counts (e.g.,
-2*1,,3).  (2) For namelist reading of a numeric array, allow a new
-name-value subsequence to terminate the current one (as though the
-current one ended with the right number of null values).
-(3) [lio.h, lwrite.c]:  omit insignificant zeros in list and namelist
-output.  (Compile with -DOld_list_output to get the old behavior.)
-
-Sat Jan 18 15:58:01 EST 1992:
-  libi77:  make list output consistent with F format by printing .1
-rather than 0.1 (introduced yesterday).
-
-Wed Jan 22 08:32:43 EST 1992:
-  libi77:  add comment to README pointing out preconnection of
-Fortran units 5, 6, 0 to stdin, stdout, stderr (respectively).
-
-Mon Feb  3 11:57:53 EST 1992:
-  libi77:  fix namelist read bug that caused the character following
-a comma to be ignored.
-
-Fri Feb 28 01:04:26 EST 1992:
-  libf77:  fix buggy z_sqrt.c (double precision square root), which
-misbehaved for arguments in the southwest quadrant.
-
-Thu Mar 19 15:05:18 EST 1992:
-  Fix bug (introduced 17 Jan 1992) in handling multiple entry points
-of differing types (with implicitly typed entries appearing after
-the first executable statement).
-  Fix memory fault in the following illegal Fortran:
-        double precision foo(i)
-*	illegal: above should be "double precision function foo(i)"
-        foo = i * 3.2
-        entry moo(i)
-        end
-  Note about ANSI_Libraries (relevant, e.g., to IRIX 4.0.1 and AIX)
-added to README.
-  Abort zero divides during constant simplification.
-
-Sat Mar 21 01:27:09 EST 1992:
-  Tweak ckalloc (misc.c) for systems where malloc(0) = 0; this matters
-for subroutines with multiple entry points but no arguments.
-  Add "struct memblock;" to init.c (irrelevant to most compilers).
-
-Wed Mar 25 13:31:05 EST 1992:
-  Fix bug with IMPLICIT INTEGER*4(...): under -i2 or -I2, the *4 was
-ignored.
-
-Tue May  5 09:53:55 EDT 1992:
-  Tweaks to README; e.g., ANSI_LIbraries changed to ANSI_Libraries .
-
-Wed May  6 23:49:07 EDT 1992
-  Under -A and -C++, have subroutines return 0 (even if they have
-no * arguments).
-  Adjust libi77 (rsne.c and lread.c) for systems where ungetc is
-a macro.  Tweak lib[FI]77/makefile to use unique intermediate file
-names (for parallel makes).
-
-Tue May 19 09:03:05 EDT 1992:
-  Adjust libI77 to make err= work with internal list and formatted I/O.
-
-Sat May 23 18:17:42 EDT 1992:
-  Under -A and -C++, supply "return 0;" after the code generated for
-a STOP statement -- the C compiler doesn't know that s_stop won't
-return.
-  New (mutually exclusive) options:
-	-f	treats all input lines as free-format lines,
-		honoring text that appears after column 72
-		and not padding lines shorter than 72 characters
-		with blanks (which matters if a character string
-		is continued across 2 or more lines).
-	-72	treats text appearing after column 72 as an error.
-
-Sun May 24 09:45:37 EDT 1992:
-  Tweak description of -f in f2c.1 and f2c.1t; update f2c.ps .
-
-Fri May 29 01:17:15 EDT 1992:
-  Complain about externals used as variables.  Example
-	subroutine foo(a,b)
-	external b
-	a = a*b		! illegal use of b; perhaps should be b()
-	end
-
-Mon Jun 15 11:15:27 EDT 1992:
-  Fix bug in handling namelists with names that have underscores.
-
-Sat Jun 27 17:30:59 EDT 1992:
-  Under -A and -C++, end Main program aliases with "return 0;".
-  Under -A and -C++, use .P files and usage in previous subprograms
-in the current file to give prototypes for functions declared EXTERNAL
-but not invoked.
-  Fix memory fault under -d1 -P .
-  Under -A and -C++, cast arguments to the right types in calling
-a function that has been defined in the current file or in a .P file.
-  Fix bug in handling multi-dimensional arrays with array references
-in their leading dimensions.
-  Fix bug in the intrinsic cmplx function when the first argument
-involves an expression for which f2c generates temporary variables,
-e.g. cmplx(abs(real(a)),1.) .
-
-Sat Jul 18 07:36:58 EDT 1992:
-  Fix buglet with -e1c (invisible on most systems) temporary file
-f2c_functions was unlinked before being closed.
-  libf77: fix bugs in evaluating m**n for integer n < 0 and m an
-integer different from 1 or a real or double precision 0.
-Catch SIGTRAP (to print "Trace trap" before aborting).  Programs
-that previously erroneously computed 1 for 0**-1 may now fault.
-Relevant routines: main.c pow_di.c pow_hh.c pow_ii.c pow_ri.c .
-
-Sat Jul 18 08:40:10 EDT 1992:
-  libi77: allow namelist input to end with & (e.g. &end).
-
-Thu Jul 23 00:14:43 EDT 1992
-  Append two underscores rather than one to C keywords used as
-local variables to avoid conflicts with similarly named COMMON blocks.
-
-Thu Jul 23 11:20:55 EDT 1992:
-  libf77, libi77 updated to assume ANSI prototypes unless KR_headers
-is #defined.
-  libi77 now recognizes a Z format item as in Fortran 90;
-the implementation assumes 8-bit bytes and botches character strings
-on little-endian machines (by printing their bytes from right to
-left): expect this bug to persist; fixing it would require a
-change to the I/O calling sequences.
-
-Tue Jul 28 15:18:33 EDT 1992:
-  libi77: insert missed "#ifdef KR_headers" lines around getnum
-header in rsne.c.  Version not updated.
-
-NOTE: "index from f2c" now ends with current timestamps of files in
-"all from f2c/src", sorted by time.  To bring your source up to date,
-obtain source files with a timestamp later than the time shown in your
-version.c.
-
-Fri Aug 14 08:07:09 EDT 1992:
-  libi77: tweak wrt_E in wref.c to avoid signing NaNs.
-
-Sun Aug 23 19:05:22 EDT 1992:
-  fc: supply : after O in getopt invocation (for -O1 -O2 -O3).
-
-Mon Aug 24 18:37:59 EDT 1992:
-  Recant above tweak to fc: getopt is dumber than I thought;
-it's necessary to say -O 1 (etc.).
-  libF77/README: add comments about ABORT, ERF, DERF, ERFC, DERFC,
-GETARG, GETENV, IARGC, SIGNAL, and SYSTEM.
-
-Tue Oct 27 01:57:42 EST 1992:
-  libf77, libi77:
-    1.  Fix botched indirection in signal_.c.
-    2.  Supply missing l_eof = 0 assignment to s_rsne() in rsne.c (so
-end-of-file on other files won't confuse namelist reads of external
-files).
-    3.  Prepend f__ to external names that are only of internal
-interest to lib[FI]77.
-
-Thu Oct 29 12:37:18 EST 1992:
-  libf77: Fix botch in signal_.c when KR_headers is #defined;
-add CFLAGS to makefile.
-  libi77: trivial change to makefile for consistency with
-libF77/makefile.
-
-Wed Feb  3 02:05:16 EST 1993:
-  Recognize types INTEGER*1, LOGICAL*1, LOGICAL*2, INTEGER*8.
-INTEGER*8 is not well tested and will only work reasonably on
-systems where int = 4 bytes, long = 8 bytes; on such systems,
-you'll have to modify f2c.h appropriately, changing integer
-from long to int and adding typedef long longint.  You'll also
-have to compile libI77 with Allow_TYQUAD #defined and adjust
-libF77/makefile to compile pow_qq.c.  In the f2c source, changes
-for INTEGER*8 are delimited by #ifdef TYQUAD ... #endif.  You
-can omit the INTEGER*8 changes by compiling with NO_TYQUAD
-#defined.  Otherwise, the new command-line option -!i8
-disables recognition of INTEGER*8.
-  libf77: add pow_qq.c
-  libi77: add #ifdef Allow_TYQUAD stuff.  Changes for INTEGER*1,
-LOGICAL*1, and LOGICAL*2 came last 23 July 1992.  Fix bug in
-backspace (that only bit when the last character of the second
-or subsequent buffer read was the previous newline).  Guard
-against L_tmpnam being too small in endfile.c.  For MSDOS,
-close and reopen files when copying to truncate.  Lengthen
-LINTW (buffer size in lwrite.c).
-  Add \ to the end of #define lines that get broken.
-  Fix bug in handling NAMELIST of items in EQUIVALENCE.
-  Under -h (or -hd), convert Hollerith to integer in general expressions
-(e.g., assignments), not just when they're passed as arguments, and
-blank-pad rather than 0-pad the Hollerith to a multiple of
-sizeof(integer) or sizeof(doublereal).
-  Add command-line option -s, which instructs f2c preserve multi-
-dimensional subscripts (by emitting and using appropriate #defines).
-  Fix glitch (with default type inferences) in examples like
-	call foo('abc')
-	end
-	subroutine foo(goo)
-	end
-This gave two warning messages:
-	Warning on line 4 of y.f: inconsistent calling sequences for foo:
-	        here 1, previously 2 args and string lengths.
-	Warning on line 4 of y.f: inconsistent calling sequences for foo:
-	        here 2, previously 1 args and string lengths.
-Now the second Warning is suppressed.
-  Complain about all inconsistent arguments, not just the first.
-  Switch to automatic creation of "all from f2c/src".  For folks
-getting f2c source via ftp, this means f2c/src/all.Z is now an
-empty file rather than a bundle.
-  Separate -P and -A: -P no longer implies -A.
-
-Thu Feb  4 00:32:20 EST 1993:
-  Fix some glitches (introduced yesterday) with -h .
-
-Fri Feb  5 01:40:38 EST 1993:
-  Fix bug in types conveyed for namelists (introduced 3 Feb. 1993).
-
-Fri Feb  5 21:26:43 EST 1993:
-  libi77: tweaks to NAMELIST and open (after comments by Harold
-Youngren):
- 1. Reading a ? instead of &name (the start of a namelist) causes
-    the namelist being sought to be written to stdout (unit 6);
-    to omit this feature, compile rsne.c with -DNo_Namelist_Questions.
- 2. Reading the wrong namelist name now leads to an error message
-    and an attempt to skip input until the right namelist name is found;
-    to omit this feature, compile rsne.c with -DNo_Bad_Namelist_Skip.
- 3. Namelist writes now insert newlines before each variable; to omit
-    this feature, compile xwsne.c with -DNo_Extra_Namelist_Newlines.
- 4. For OPEN of sequential files, ACCESS='APPEND' (or
-    access='anything else starting with "A" or "a"') causes the file to
-    be positioned at end-of-file, so a write will append to the file.
-    (This is nonstandard, but does not require modifying data
-    structures.)
-
-Mon Feb  8 14:40:37 EST 1993:
-  Increase number of continuation lines allowed from 19 to 99,
-and allow changing this limit with -NC (e.g. -NC200 for 200 lines).
-  Treat control-Z (at the beginning of a line) as end-of-file: see
-the new penultimate paragraph of README.
-  Fix a rarely seen glitch that could make an error messages to say
-"line 0".
-
-Tue Feb  9 02:05:40 EST 1993
-  libi77: change some #ifdef MSDOS lines to #ifdef NON_UNIX_STDIO,
-and, in err.c under NON_UNIX_STDIO, avoid close(creat(name,0666))
-when the unit has another file descriptor for name.
-
-Tue Feb  9 17:12:49 EST 1993
-  libi77: more tweaks for NON_UNIX_STDIO: use stdio routines
-rather than open, close, creat, seek, fdopen (except for f__isdev).
-
-Fri Feb 12 15:49:33 EST 1993
-  Update src/gram.c (which was forgotten in the recent updates).
-Most folks regenerate it anyway (wity yacc or bison).
-
-Thu Mar  4 17:07:38 EST 1993
-  Increase default max labels in computed gotos and alternate returns
-to 257, and allow -Nl1234 to specify this number.
-  Tweak put.c to check p->tag == TADDR in realpart() and imagpart().
-  Adjust fc script to allow .r (RATFOR) files and -C (check subscripts).
-  Avoid declaring strchr in niceprintf.c under -DANSI_Libraries .
-  gram.c updated again.
-  libi77: err.c, open.c: take declaration of fdopen from rawio.h.
-
-Sat Mar  6 07:09:11 EST 1993
-  libi77: uio.c: adjust off-end-of-record test for sequential
-unformatted reads to respond to err= rather than end= .
-
-Sat Mar  6 16:12:47 EST 1993
-  Treat scalar arguments of the form (v) and v+0, where v is a variable,
-as expressions: assign to a temporary variable, and pass the latter.
-  gram.c updated.
-
-Mon Mar  8 09:35:38 EST 1993
-  "f2c.h from f2c" updated to add types logical1 and integer1 for
-LOGICAL*1 and INTEGER*1.  ("f2c.h from f2c" is supposed to be the
-same as "f2c.h from f2c/src", which was updated 3 Feb. 1993.)
-
-Mon Mar  8 17:57:55 EST 1993
-  Fix rarely seen bug that could cause strange casts in function
-invocations (revealed by an example with msdos/f2c.exe).
-  msdos/f2cx.exe.Z and msdos/f2c.exe.Z updated (ftp access only).
-
-Fri Mar 12 12:37:01 EST 1993
-  Fix bug with -s in handling subscripts involving min, max, and
-complicated expressions requiring temporaries.
-  Fix bug in handling COMMONs that need padding by a char array.
-  msdos/f2cx.exe.Z and msdos/f2c.exe.Z updated (ftp access only).
-
-Fri Mar 12 17:16:16 EST 1993
-  libf77, libi77: updated for compiling under C++.
-
-Mon Mar 15 16:21:37 EST 1993
-  libi77: more minor tweaks (for -DKR_headers); Version.c not changed.
-
-Thu Mar 18 12:37:30 EST 1993
-  Flag -r (for discarding carriage-returns on systems that end lines
-with carriage-return/newline pairs, e.g. PCs) added to xsum, and
-xsum.c converted to ANSI/ISO syntax (with K&R syntax available with
--DKR_headers).  [When time permits, the f2c source will undergo a
-similar conversion.]
-  libi77: tweaks to #includes in endfile.c, err.c, open.c, rawio.h;
-Version.c not changed.
-  f2c.ps updated (to pick up revision of 2 Feb. 1993 to f2c.1).
-
-Fri Mar 19 09:19:26 EST 1993
-  libi77: add (char *) casts to malloc and realloc invocations
-in err.c, open.c; Version.c not changed.
-
-Tue Mar 30 07:17:15 EST 1993
-  Fix bug introduced 6 March 1993: possible memory corruption when
-loops in data statements involve constant subscripts, as in
-	 DATA (GUNIT(1,I),I=0,14)/15*-1/
-
-Tue Mar 30 16:17:42 EST 1993
-  Fix bug with -s: (floating-point array item)*(complex item)
-generates an _subscr() reference for the floating-point array,
-but a #define for the _subscr() was omitted.
-
-Tue Apr  6 12:11:22 EDT 1993
-  libi77: adjust error returns for formatted inputs to flush the current
-input line when err= is specified.  To restore the old behavior (input
-left mid-line), either adjust the #definition of errfl in fio.h or omit
-the invocation of f__doend in err__fl (in err.c).
-
-Tue Apr  6 13:30:04 EDT 1993
-  Fix bug revealed in
-	subroutine foo(i)
-	call goo(int(i))
-	end
-which now passes a copy of i, rather than i itself.
-
-Sat Apr 17 11:41:02 EDT 1993
-  Adjust appending of underscores to conform with f2c.ps ("A Fortran
-to C Converter"): names that conflict with C keywords or f2c type
-names now have just one underscore appended (rather than two); add
-"integer1", "logical1", "longint" to the keyword list.
-  Append underscores to names that appear in EQUIVALENCE and are
-component names in a structure declared in f2c.h, thus avoiding a
-problem caused by the #defines emitted for equivalences.  Example:
-	complex a
-	equivalence (i,j)
-	a = 1	! a.i went awry because of #define i
-	j = 2
-	write(*,*) a, i
-	end
-  Adjust line-breaking logic to avoid splitting very long constants
-(and names).  Example:
-	! The next line starts with tab and thus is a free-format line.
-	a=.012345689012345689012345689012345689012345689012345689012345689012345689
-	end
-  Omit extraneous "return 0;" from entry stubs emitted for multiple
-entry points of type character, complex, or double complex.
-
-Sat Apr 17 14:35:05 EDT 1993
-  Fix bug (introduced 4 Feb.) in separating -P from -A that kept f2c
-from re-reading a .P file written without -A or -C++ describing a
-routine with an external argument.  [See the just-added note about
-separating -P from -A in the changes above for 3 Feb. 1993.]
-  Fix bug (type UNKNOWN for V in the example below) revealed by
-	subroutine a()
-	external c
-	call b(c)
-	end
-	subroutine b(v)
-	end
-
-Sun Apr 18 19:55:26 EDT 1993
-  Fix wrong calling sequence for mem() in yesterday's addition to
-equiv.c .
-
-Wed Apr 21 17:39:46 EDT 1993
-  Fix bug revealed in
-
-      ASSIGN 10 TO L1
-      GO TO 20
- 10   ASSIGN 30 TO L2
-      STOP 10
-
- 20   ASSIGN 10 TO L2	! Bug here because 10 had been assigned
-			! to another label, then defined.
-      GO TO L2
- 30   END
-
-Fri Apr 23 18:38:50 EDT 1993
-  Fix bug with -h revealed in
-	CHARACTER*9 FOO
-	WRITE(FOO,'(I6)') 1
-	WRITE(FOO,'(I6)') 2	! struct icilist io___3 botched
-	END
-
-Tue Apr 27 16:08:28 EDT 1993
-  Tweak to makefile: remove "size f2c".
-
-Tue May  4 23:48:20 EDT 1993
-  libf77: tweak signal_ line of f2ch.add .
-
-Tue Jun  1 13:47:13 EDT 1993
-  Fix bug introduced 3 Feb. 1993 in handling multiple entry
-points with differing return types -- the postfix array in proc.c
-needed a new entry for integer*8 (which resulted in wrong
-Multitype suffixes for non-integral types).
-  For (default) K&R C, generate VOID rather than int functions for
-functions of Fortran type character, complex, and double complex.
-  msdos/f2cx.exe.Z and msdos/f2c.exe.Z updated (ftp access only).
-
-Tue Jun  1 23:11:15 EDT 1993
-  f2c.h: add Multitype component g and commented type longint.
-  proc.c: omit "return 0;" from stubs for complex and double complex
-entries (when entries have multiple types); add test to avoid memory
-fault with illegal combinations of entry types.
-
-Mon Jun  7 12:00:47 EDT 1993
-  Fix memory fault in
-	common /c/ m
-	integer m(1)
-	data m(1)/1/, m(2)/2/	! one too many initializers
-	end
-  msdos/f2cx.exe.Z and msdos/f2c.exe.Z updated (ftp access only).
-
-Fri Jun 18 13:55:51 EDT 1993
-  libi77: change type of signal_ in f2ch.add; change type of il in
-union Uint from long to integer (for machines like the DEC Alpha,
-where integer should be the same as int).  Version.c not changed.
-  Tweak gram.dcl and gram.head: add semicolons after some rules that
-lacked them, and remove an extraneous semicolon.  These changes are
-completely transparent to our local yacc programs, but apparently
-matter on some VMS systems.
-
-Wed Jun 23 01:02:56 EDT 1993
-  Update "fc" shell script, and bring f2c.1 and f2c.1t up to date:
-they're meant to be linked with (i.e., the same as) src/f2c.1 and
-src/f2c.1t .  [In the last update of f2c.1* (2 Feb. 1993), only
-src/f2c.1 and src/f2c.1t got changed -- a mistake.]
-
-Wed Jun 23 09:04:31 EDT 1993
-  libi77: fix bug in format reversions for internal writes.
-Example:
-	character*60 lines(2)
-	write(lines,"('n =',i3,2(' more text',i3))") 3, 4, 5, 6
-	write(*,*) 'lines(1) = ', lines(1)
-	write(*,*) 'lines(2) = ', lines(2)
-	end
-gave an error message that began "iio: off end of record", rather
-than giving the correct output:
-
- lines(1) = n =  3 more text  4 more text  5
- lines(2) =  more text  6 more text
-
-Thu Aug  5 11:31:14 EDT 1993
-  libi77: lread.c: fix bug in handling repetition counts for logical
-data (during list or namelist input).  Change struct f__syl to
-struct syl (for buggy compilers).
-
-Sat Aug  7 16:05:30 EDT 1993
-  libi77: lread.c (again): fix bug in namelist reading of incomplete
-logical arrays.
-  Fix minor calling-sequence errors in format.c, output.c, putpcc.c:
-should be invisible.
-
-Mon Aug  9 09:12:38 EDT 1993
-  Fix erroneous cast under -A in translating
-	character*(*) function getc()
-	getc(2:3)=' '		!wrong cast in first arg to s_copy
-	end
-  libi77: lread.c: fix bug in namelist reading of an incomplete array
-of numeric data followed by another namelist item whose name starts
-with 'd', 'D', 'e', or 'E'.
-
-Fri Aug 20 13:22:10 EDT 1993
-  Fix bug in do while revealed by
-	subroutine skdig (line, i)
-	character line*(*), ch*1
-	integer i
-	logical isdigit
-	isdigit(ch) = ch.ge.'0' .and. ch.le.'9'
-	do while (isdigit(line(i:i)))	! ch__1[0] was set before
-					! "while(...) {...}"
-		i = i + 1
-		enddo
-	end
-
-Fri Aug 27 08:22:54 EDT 1993
-  Add #ifdefs to avoid declaring atol when it is a macro; version.c
-not updated.
-
-Wed Sep  8 12:24:26 EDT 1993
-  libi77: open.c: protect #include "sys/..." with
-#ifndef NON_UNIX_STDIO; Version date not changed.
-
-Thu Sep  9 08:51:21 EDT 1993
-  Adjust "include" to interpret file names relative to the directory
-of the file that contains the "include".
-
-Fri Sep 24 00:56:12 EDT 1993
-  Fix offset error resulting from repeating the same equivalence
-statement twice.  Example:
-	real a(2), b(2)
-	equivalence (a(2), b(2))
-	equivalence (a(2), b(2))
-	end
-  Increase MAXTOKENLEN (to roughly the largest allowed by ANSI C).
-
-Mon Sep 27 08:55:09 EDT 1993
-  libi77: endfile.c: protect #include "sys/types.h" with
-#ifndef NON_UNIX_STDIO; Version.c not changed.
-
-Fri Oct 15 15:37:26 EDT 1993
-  Fix rarely seen parsing bug illustrated by
-	subroutine foo(xabcdefghij)
-	character*(*) xabcdefghij
-               IF (xabcdefghij.NE.'##') GOTO 40
- 40	end
-in which the spacing in the IF line is crucial.
-
-Thu Oct 21 13:55:11 EDT 1993
-  Give more meaningful error message (then "unexpected character in
-cds") when constant simplification leads to Infinity or NaN.
-
-Wed Nov 10 15:01:05 EST 1993
-  libi77: backspace.c: adjust, under -DMSDOS, to cope with MSDOS
-text files, as handled by some popular PC C compilers.  Beware:
-the (defective) libraries associated with these compilers assume lines
-end with \r\n (conventional MS-DOS text files) -- and ftell (and
-hence the current implementation of backspace) screws up if lines with
-just \n.
-
-Thu Nov 18 09:37:47 EST 1993
-  Give a better error (than "control stack empty") for an extraneous
-ENDDO.  Example:
-	enddo
-	end
-  Update comments about ftp in "readme from f2c".
-
-Sun Nov 28 17:26:50 EST 1993
-  Change format of time stamp in version.c to yyyymmdd.
-  Sort parameter adjustments (or complain of impossible dependencies)
-so that dummy arguments are referenced only after being adjusted.
-Example:
-	subroutine foo(a,b)
-	integer a(2)		! a must be adjusted before b
-	double precision b(a(1),a(2))
-	call goo(b(3,4))
-	end
-  Adjust structs for initialized common blocks and equivalence classes
-to omit the trailing struct component added to force alignment when
-padding already forces the desired alignment.  Example:
-	PROGRAM TEST
-	COMMON /Z/ A, CC
-	CHARACTER*4 CC
-	DATA cc /'a'/
-	END
-now gives
-	struct {
-	    integer fill_1[1];
-	    char e_2[4];
-	    } z_ = { {0}, {'a', ' ', ' ', ' '} };
-rather than
-struct {
-    integer fill_1[1];
-    char e_2[4];
-    real e_3;
-    } z_ = { {0}, {'a', ' ', ' ', ' '}, (float)0. };
-
-Wed Dec  8 16:24:43 EST 1993
-  Adjust lex.c to recognize # nnn "filename" lines emitted by cpp;
-this affects the file names and line numbers in error messages and
-the #line lines emitted under -g.
-  Under -g, arrange for a file that starts with an executable
-statement to have the first #line line indicate line 1, rather
-than the line number of the END statement ending the main program.
-  Adjust fc script to run files ending in .F through /lib/cpp.
-  Fix bug ("Impossible tag 2") in
-	if (t .eq. (0,2)) write(*,*) 'Bug!'
-	end
-  libi77: iio.c: adjust internal formatted reads to treat short records
-as though padded with blanks (rather than causing an "off end of record"
-error).
-
-Wed Dec 15 15:19:15 EST 1993
-  fc: adjusted for .F files to pass -D and -I options to cpp.
-
-Fri Dec 17 20:03:38 EST 1993
-  Fix botch introduced 28 Nov. 1993 in vax.c; change "version of"
-to "version".
-
-Tue Jan  4 15:39:52 EST 1994
-  msdos/f2cx.exe.Z and msdos/f2c.exe.Z updated (ftp access only).
-
-Wed Jan 19 08:55:19 EST 1994
-  Arrange to accept
-	integer	Nx, Ny, Nz
-	parameter	(Nx = 10, Ny = 20)
-	parameter	(Nz = max(Nx, Ny))
-	integer	c(Nz)
-	call foo(c)
-	end
-rather than complaining "Declaration error for c: adjustable dimension
-on non-argument".  The necessary changes cause some hitherto unfolded
-constant expressions to be folded.
-  Accept BYTE as a synonym for INTEGER*1.
-
-Thu Jan 27 08:57:40 EST 1994
-  Fix botch in changes of 19 Jan. 1994 that broke entry points with
-multi-dimensional array arguments that did not appear in the subprogram
-argument list and whose leading dimensions depend on arguments.
-
-Mon Feb  7 09:24:30 EST 1994
-  Remove artifact in "fc" script that caused -O to be ignored:
-	87c87
-	<		# lcc ignores -O...
-	---
-	>		CFLAGS="$CFLAGS $O"
-
-Sun Feb 20 17:04:58 EST 1994
-  Fix bugs reading .P files for routines with arguments of type
-INTEGER*1, INTEGER*8, LOGICAL*2.
-  Fix glitch in reporting inconsistent arguments for routines involving
-character arguments:  "arg n" had n too large by the number of
-character arguments.
-
-Tue Feb 22 20:50:08 EST 1994
-  Trivial changes to data.c format.c main.c niceprintf.c output.h and
-sysdep.h (consistency improvements).
-  libI77: lread.c: check for NULL return from realloc.
-
-Fri Feb 25 23:56:08 EST 1994
-  output.c, sysdep.h: arrange for -DUSE_DTOA to use dtoa.c and g_fmt.c
-for correctly rounded decimal values on IEEE-arithmetic machines
-(plus machines with VAX and IBM-mainframe arithmetic).  These
-routines are available from netlib's fp directory.
-  msdos/f2cx.exe.Z and msdos/f2c.exe.Z updated (ftp access only); the
-former uses -DUSE_DTOA to keep 12 from printing as 12.000000000000001.
-  vax.c: fix wrong arguments to badtag and frchain introduced
-28 Nov. 1993.
-  Source for f2c converted to ANSI/ISO format, with the K&R format
-available by compilation with -DKR_headers .
-  Arrange for (double precision expression) relop (single precision
-constant) to retain the single-precision nature of the constant.
-Example:
-	double precision t
-	if (t .eq. 0.3) ...
-
-Mon Feb 28 11:40:24 EST 1994
-  README updated to reflect a modification just made to netlib's
-"dtoa.c from fp":
-96a97,105
-> Also add the rule
->
-> 	dtoa.o: dtoa.c
-> 		$(CC) -c $(CFLAGS) -DMALLOC=ckalloc -DIEEE... dtoa.c
->
-> (without the initial tab) to the makefile, where IEEE... is one of
-> IEEE_MC68k, IEEE_8087, VAX, or IBM, depending on your machine's
-> arithmetic.  See the comments near the start of dtoa.c.
->
-
-Sat Mar  5 09:41:52 EST 1994
-  Complain about functions with the name of a previously declared
-common block (which is illegal).
-  New option -d specifies the directory for output .c and .P files;
-f2c.1 and f2c.1t updated.  The former undocumented debug option -dnnn
-is now -Dnnn.
-
-Thu Mar 10 10:21:44 EST 1994
-  libf77: add #undef min and #undef max lines to s_paus.c s_stop.c
-and system_.c; Version.c not changed.
-  libi77: add -DPad_UDread lines to uio.c and explanation to README:
-    Some buggy Fortran programs use unformatted direct I/O to write
-    an incomplete record and later read more from that record than
-    they have written.  For records other than the last, the unwritten
-    portion of the record reads as binary zeros.  The last record is
-    a special case: attempting to read more from it than was written
-    gives end-of-file -- which may help one find a bug.  Some other
-    Fortran I/O libraries treat the last record no differently than
-    others and thus give no help in finding the bug of reading more
-    than was written.  If you wish to have this behavior, compile
-    uio.c with -DPad_UDread .
-Version.c not changed.
-
-Tue Mar 29 17:27:54 EST 1994
-  Adjust make_param so dimensions involving min, max, and other
-complicated constant expressions do not provoke error messages
-about adjustable dimensions on non-arguments.
-  Fix botch introduced 19 Jan 1994: "adjustable dimension on non-
-argument" messages could cause some things to be freed twice.
-
-Tue May 10 07:55:12 EDT 1994
-  Trivial changes to exec.c, p1output.c, parse_args.c, proc.c,
-and putpcc.c: change arguments from
-	type foo[]
-to
-	type *foo
-for consistency with defs.h.  For most compilers, this makes no
-difference.
-
-Thu Jun  2 12:18:18 EDT 1994
-  Fix bug in handling FORMAT statements that have adjacent character
-(or Hollerith) strings: an extraneous \002 appeared between the
-strings.
-  libf77: under -DNO_ONEXIT, arrange for f_exit to be called just
-once; previously, upon abnormal termination (including stop statements),
-it was called twice.
-
-Mon Jun  6 15:52:57 EDT 1994
-  libf77: Avoid references to SIGABRT and SIGIOT if neither is defined;
-Version.c not changed.
-  libi77: Add cast to definition of errfl() in fio.h; this only matters
-on systems with sizeof(int) < sizeof(long).  Under -DNON_UNIX_STDIO,
-use binary mode for direct formatted files (to avoid any confusion
-connected with \n characters).
-
-Fri Jun 10 16:47:31 EDT 1994
-  Fix bug under -A in handling unreferenced (and undeclared)
-external arguments in subroutines with multiple entry points.  Example:
-	subroutine m(fcn,futil)
-	external fcn,futil
-	call fcn
-	entry mintio(i1) ! (D_fp)0 rather than (U_fp)0 for futil
-	end
-
-Wed Jun 15 10:38:14 EDT 1994
-  Allow char(constant expression) function in parameter declarations.
-(This was probably broken in the changes of 29 March 1994.)
-
-Fri Jul  1 23:54:00 EDT 1994
-  Minor adjustments to makefile (rule for f2c.1 commented out) and
-sysdep.h (#undef KR_headers if __STDC__ is #defined, and base test
-for ANSI_Libraries and ANSI_Prototypes on KR_headers rather than
-__STDC__); version.c touched but not changed.
-  libi77: adjust fp.h so local.h is only needed under -DV10;
-Version.c not changed.
-
-Tue Jul  5 03:05:46 EDT 1994
-  Fix segmentation fault in
-	subroutine foo(a,b,k)
-	data i/1/
-	double precision a(k,1)	! sequence error: must precede data
-	b = a(i,1)
-	end
-  libi77: Fix bug (introduced 6 June 1994?) in reopening files under
-NON_UNIX_STDIO.
-  Fix some error messages caused by illegal Fortran.  Examples:
-* 1.
-	x(i) = 0  !Missing declaration for array x
-	call f(x) !Said Impossible storage class 8 in routine mkaddr
-	end	  !Now says invalid use of statement function x
-* 2.
-	f = g	!No declaration for g; by default it's a real variable
-	call g	!Said invalid class code 2 for function g
-	end	!Now says g cannot be called
-* 3.
-	intrinsic foo	!Invalid intrinsic name
-	a = foo(b)	!Said intrcall: bad intrgroup 0
-	end		!Now just complains about line 1
-
-Tue Jul  5 11:14:26 EDT 1994
-  Fix glitch in handling erroneous statement function declarations.
-Example:
-	a(j(i) - i) = a(j(i) - i) + 1	! bad statement function
-	call foo(a(3))	! Said Impossible type 0 in routine mktmpn
-	end		! Now warns that i and j are not used
-
-Wed Jul  6 17:31:25 EDT 1994
-  Tweak test for statement functions that (illegally) call themselves;
-f2c will now proceed to check for other errors, rather than bailing
-out at the first recursive statement function reference.
-  Warn about but retain divisions by 0 (instead of calling them
-"compiler errors" and quiting).  On IEEE machines, this permits
-	double precision nan, ninf, pinf
-	nan = 0.d0/0.d0
-	pinf = 1.d0/0.d0
-	ninf = -1.d0/0.d0
-	write(*,*) 'nan, pinf, ninf = ', nan, pinf, ninf
-	end
-to print
-	nan, pinf, ninf =   NaN  Infinity -Infinity
-  libi77: wref.c: protect with #ifdef GOOD_SPRINTF_EXPONENT an
-optimization that requires exponents to have 2 digits when 2 digits
-suffice.  lwrite.c wsfe.c (list and formatted external output):
-omit ' ' carriage-control when compiled with -DOMIT_BLANK_CC .
-Off-by-one bug fixed in character count for list output of character
-strings.  Omit '.' in list-directed printing of Nan, Infinity.
-
-Mon Jul 11 13:05:33 EDT 1994
-  src/gram.c updated.
-
-Tue Jul 12 10:24:42 EDT 1994
-  libi77: wrtfmt.c: under G11.4, write 0. as "  .0000    " rather
-than "  .0000E+00".
-
-Thu Jul 14 17:55:46 EDT 1994
-  Fix glitch in changes of 6 July 1994 that could cause erroneous
-"division by zero" warnings (or worse).  Example:
-	subroutine foo(a,b)
-	y = b
-	a = a / y	! erroneous warning of division by zero
-	end
-
-Mon Aug  1 16:45:17 EDT 1994
-  libi77: lread.c rsne.c: for benefit of systems with a buggy stdio.h,
-declare ungetc when neither KR_headers nor ungetc is #defined.
-Version.c not changed.
-
-Wed Aug  3 01:53:00 EDT 1994
-  libi77: lwrite.c (list output): do not insert a newline when
-appending an oversize item to an empty line.
-
-Mon Aug  8 00:51:01 EDT 1994
-  Fix bug (introduced 3 Feb. 1993) that, under -i2, kept LOGICAL*2
-variables from appearing in INQUIRE statements.  Under -I2, allow
-LOGICAL*4 variables to appear in INQUIRE.  Fix intrinsic function
-LEN so it returns a short value under -i2, a long value otherwise.
-  exec.c: fix obscure memory fault possible with bizarre (and highly
-erroneous) DO-loop syntax.
-
-Fri Aug 12 10:45:57 EDT 1994
-  libi77: fix glitch that kept ERR= (in list- or format-directed input)
-from working after a NAMELIST READ.
-
-Thu Aug 25 13:58:26 EDT 1994
-  Suppress -s when -C is specified.
-  Give full pathname (netlib@research.att.com) for netlib in readme and
-src/README.
-
-Wed Sep  7 22:13:20 EDT 1994
-  libi77: typesize.c: adjust to allow types LOGICAL*1, LOGICAL*2,
-INTEGER*1, and (under -DAllow_TYQUAD) INTEGER*8 in NAMELISTs.
-
-Fri Sep 16 17:50:18 EDT 1994
-  Change name adjustment for reserved words: instead of just appending
-"_" (a single underscore), append "_a_" to local variable names to avoid
-trouble when a common block is named a reserved word and the same
-reserved word is also a local variable name.  Example:
-	common /const/ a,b,c
-	real const(3)
-	equivalence (const(1),a)
-	a = 1.234
-	end
-  Arrange for ichar() to treat characters as unsigned.
-  libf77: s_cmp.c: treat characters as unsigned in comparisons.
-These changes for unsignedness only matter for strings that contain
-non-ASCII characters.  Now ichar() should always be >= 0.
-
-Sat Sep 17 11:19:32 EDT 1994
-  fc: set rc=$? before exit (to get exit code right in trap code).
-
-Mon Sep 19 17:49:43 EDT 1994
-  libf77: s_paus.c: flush stderr after PAUSE; add #ifdef MSDOS stuff.
-  libi77: README: point out general need for -DMSDOS under MS-DOS.
-
-Tue Sep 20 11:42:30 EDT 1994
-  Fix bug in comparing identically named common blocks, in which
-all components have the same names and types, but at least one is
-dimensioned (1) and the other is not dimensioned.  Example:
-	subroutine foo
-	common /ab/ a
-	a=1.	!!! translated correctly to ab_1.a = (float)1.;
-	end
-	subroutine goo
-	common /ab/ a(1)
-	a(1)=2.	!!! translated erroneously to ab_1.a[0] = (float)2.
-	end
-
-Tue Sep 27 23:47:34 EDT 1994
-  Fix bug introduced 16 Sept. 1994: don't add _a_ to C keywords
-used as external names.  In fact, return to earlier behavior of
-appending __ to C keywords unless they are used as external names,
-in which case they get just one underscore appended.
-  Adjust constant handling so integer and logical PARAMETERs retain
-type information, particularly under -I2.  Example:
-	SUBROUTINE FOO
-	INTEGER I
-	INTEGER*1 I1
-	INTEGER*2 I2
-	INTEGER*4 I4
-	LOGICAL L
-	LOGICAL*1 L1
-	LOGICAL*2 L2
-	LOGICAL*4 L4
-	PARAMETER (L=.FALSE., L1=.FALSE., L2=.FALSE., L4=.FALSE.)
-	PARAMETER (I=0,I1=0,I2=0,I4=0)
-	CALL DUMMY(I, I1, I2, I4, L, L1, L2, L4)
-	END
-  f2c.1t: Change f\^2c to f2c (omit half-narrow space) in line following
-".SH NAME" for benefit of systems that cannot cope with troff commands
-in this context.
-
-Wed Sep 28 12:45:19 EDT 1994
-  libf77: s_cmp.c fix glitch in -DKR_headers version introduced
-12 days ago.
-
-Thu Oct  6 09:46:53 EDT 1994
-  libi77: util.c: omit f__mvgbt (which is never used).
-  f2c.h: change "long" to "long int" to facilitate the adjustments
-by means of sed described above.  Comment out unused typedef of Long.
-
-Fri Oct 21 18:02:24 EDT 1994
-  libf77: add s_catow.c and adjust README to point out that changing
-"s_cat.o" to "s_catow.o" in the makefile will permit the target of a
-concatenation to appear on its right-hand side (contrary to the
-Fortran 77 Standard and at the cost of some run-time efficiency).
-
-Wed Nov  2 00:03:58 EST 1994
-  Adjust -g output to contain only one #line line per statement,
-inserting \ before the \n ending lines broken because of their
-length [this insertion was recanted 10 Dec. 1994].  This change
-accommodates an idiocy in the ANSI/ISO C standard, which leaves
-undefined the behavior of #line lines that occur within the arguments
-to a macro call.
-
-Wed Nov  2 14:44:27 EST 1994
-  libi77: under compilation with -DALWAYS_FLUSH, flush buffers at
-the end of each write statement, and test (via the return from
-fflush) for write failures, which can be caught with an ERR=
-specifier in the write statement.  This extra flushing slows
-execution, but can abort execution or alter the flow of control
-when a disk fills up.
-  f2c/src/io.c: Add ERR= test to e_wsle invocation (end of
-list-directed external output) to catch write failures when libI77
-is compiled with -DALWAYS_FLUSH.
-
-Thu Nov  3 10:59:13 EST 1994
-  Fix bug in handling dimensions involving certain intrinsic
-functions of constant expressions: the expressions, rather than
-pointers to them, were passed.  Example:
-      subroutine subtest(n,x)
-      real x(2**n,n) ! pow_ii(2,n) was called; now it's pow_ii(&c__2,n)
-      x(2,2)=3.
-      end
-
-Tue Nov  8 23:56:30 EST 1994
-  malloc.c: remove assumption that only malloc calls sbrk.  This
-appears to make malloc.c useful on RS6000 systems.
-
-Sun Nov 13 13:09:38 EST 1994
-  Turn off constant folding of integers used in floating-point
-expressions, so the assignment in
-	subroutine foo(x)
-	double precision x
-	x = x*1000000*500000
-	end
-is rendered as
-	*x = *x * 1000000 * 500000;
-rather than as
-	*x *= 1783793664;
-
-Sat Dec 10 16:31:40 EST 1994
-  Supply a better error message (than "Impossible type 14") for
-	subroutine foo
-	foo = 3
-	end
-  Under -g, convey name of included files to #line lines.
-  Recant insertion of \ introduced (under -g) 2 Nov. 1994.
-
-Thu Dec 15 14:33:55 EST 1994
-  New command-line option -Idir specifies directories in which to
-look for non-absolute include files (after looking in the directory
-of the current input file).  There can be several -Idir options, each
-specifying one directory.  All -Idir options are considered, from
-left to right, until a suitably named file is found.  The -I2 and -I4
-command-line options have precedence, so directories named 2 or 4
-must be spelled by some circumlocation, such as -I./2 .
-  f2c.ps updated to mention the new -Idir option, correct a typo,
-and bring the man page at the end up to date.
-  lex.c: fix bug in reading line numbers in #line lines.
-  fc updated to pass -Idir options to f2c.
-
-Thu Dec 29 09:48:03 EST 1994
-  Fix bug (e.g., addressing fault) in diagnosing inconsistency in
-the type of function eta in the following example:
-	function foo(c1,c2)
-	double complex foo,c1,c2
-	double precision eta
-	foo = eta(c1,c2)
-	end
-	function eta(c1,c2)
-	double complex eta,c1,c2
-	eta = c1*c2
-	end
-
-Mon Jan  2 13:27:26 EST 1995
-  Retain casts for SNGL (or FLOAT) that were erroneously optimized
-away.  Example:
-	subroutine foo(a,b)
-	double precision a,b
-	a = float(b)	! now rendered as *a = (real) (*b);
-	end
-  Use float (rather than double) temporaries in certain expressions
-of type complex.  Example: the temporary for sngl(b) in
-	complex a
-	double precision b
-	a = sngl(b) - (3.,4.)
-is now of type float.
-
-Fri Jan  6 00:00:27 EST 1995
-  Adjust intrinsic function cmplx to act as dcmplx (returning
-double complex rather than complex) if either of its args is of
-type double precision.  The double temporaries used prior to 2 Jan.
-1995 previously gave it this same behavior.
-
-Thu Jan 12 12:31:35 EST 1995
-  Adjust -krd to use double temporaries in some calculations of
-type complex.
-  libf77: pow_[dhiqrz][hiq].c: adjust x**i to work on machines
-that sign-extend right shifts when i is the most negative integer.
-
-Wed Jan 25 00:14:42 EST 1995
-  Fix memory fault in handling overlapping initializations in
-	block data
-	common /zot/ d
-	double precision d(3)
-	character*6 v(4)
-	real r(2)
-	equivalence (d(3),r(1)), (d(1),v(1))
-	data v/'abcdef', 'ghijkl', 'mnopqr', 'stuvwx'/
-	data r/4.,5./
-	end
-  names.c: add "far", "huge", "near" to c_keywords (causing them
-to have __ appended when used as local variables).
-  libf77: add s_copyow.c, an alternative to s_copy.c for handling
-(illegal) character assignments where the right- and left-hand
-sides overlap, as in a(2:4) = a(1:3).
-
-Thu Jan 26 14:21:19 EST 1995
-  libf77: roll s_catow.c and s_copyow.c into s_cat.c and s_copy.c,
-respectively, allowing the left-hand side of a character assignment
-to appear on its right-hand side unless s_cat.c and s_copy.c are
-compiled with -DNO_OVERWRITE (which is a bit more efficient).
-Fortran 77 forbids the left-hand side from participating in the
-right-hand side (of a character assignment), but Fortran 90 allows it.
-  libi77: wref.c: fix glitch in printing the exponent of 0 when
-GOOD_SPRINTF_EXPONENT is not #defined.
-
-Fri Jan 27 12:25:41 EST 1995
-  Under -C++ -ec (or -C++ -e1c), surround struct declarations with
-	#ifdef __cplusplus
-	extern "C" {
-	#endif
-and
-	#ifdef __cplusplus
-	}
-	#endif
-(This isn't needed with cfront, but apparently is necessary with
-some other C++ compilers.)
-  libf77: minor tweak to s_copy.c: copy forward whenever possible
-(for better cache behavior).
-
-Wed Feb  1 10:26:12 EST 1995
-  Complain about parameter statements that assign values to dummy
-arguments, as in
-	subroutine foo(x)
-	parameter(x = 3.4)
-	end
-
-Sat Feb  4 20:22:02 EST 1995
-  fc: omit "lib=/lib/num/lib.lo".
-
-Wed Feb  8 08:41:14 EST 1995
-  Minor changes to exec.c, putpcc.c to avoid "bad tag" or "error
-in frexpr" with certain invalid Fortran.
-
-Sat Feb 11 08:57:39 EST 1995
-  Complain about integer overflows, both in simplifying integer
-expressions, and in converting integers from decimal to binary.
-  Fix a memory fault in putcx1() associated with invalid input.
-
-Thu Feb 23 11:20:59 EST 1995
-  Omit MAXTOKENLEN; realloc token if necessary (to handle very long
-strings).
-
-Fri Feb 24 11:02:00 EST 1995
-  libi77: iio.c: z_getc: insert (unsigned char *) to allow internal
-reading of characters with high-bit set (on machines that sign-extend
-characters).
-
-Tue Mar 14 18:22:42 EST 1995
-  Fix glitch (in io.c) in handling 0-length strings in format
-statements, as in
-	write(*,10)
- 10	format(' ab','','cd')
-  libi77: lread.c and rsfe.c: adjust s_rsle and s_rsfe to check for
-end-of-file (to prevent infinite loops with empty read statements).
-
-Wed Mar 22 10:01:46 EST 1995
-  f2c.ps: adjust discussion of -P on p. 7 to reflect a change made
-3 Feb. 1993: -P no longer implies -A.
-
-Fri Apr 21 18:35:00 EDT 1995
-  fc script: remove absolute paths (since PATH specifies only standard
-places).  On most systems, it's still necessary to adjust the PATH
-assignment at the start of fc to fit the local conventions.
-
-Fri May 26 10:03:17 EDT 1995
-  fc script: add recognition of -P and .P files.
-  libi77: iio.c: z_wnew: fix bug in handling T format items in internal
-writes whose last item is written to an earlier position than some
-previous item.
-
-Wed May 31 11:39:48 EDT 1995
-  libf77: added subroutine exit(rc) (with integer return code rc),
-which works like a stop statement but supplies rc as the program's
-return code.
-
-Fri Jun  2 11:56:50 EDT 1995
-  Fix memory fault in
-	parameter (x=2.)
-	data x /2./
-	end
-This now elicits two error messages; the second ("too many
-initializers"), though not desirable, seems hard to eliminate
-without considerable hassle.
-
-Mon Jul 17 23:24:20 EDT 1995
-  Fix botch in simplifying constants in certain complex
-expressions.  Example:
-	subroutine foo(s,z)
-	double complex z
-	double precision s, M, P
-	parameter ( M = 100.d0, P = 2.d0 )
-	z = M * M  / s  * dcmplx (1.d0, P/M)
-*** The imaginary part of z was miscomputed ***
-	end
-  Under -ext, complain about nonintegral dimensions.
-
-Fri Jul 21 11:18:36 EDT 1995
-  Fix glitch on line 159 of init.c: change
-	"(shortlogical *)0)",
-to
-	"(shortlogical *)0",
-This affects multiple entry points when some but not all have
-arguments of type logical*2.
-  libi77: adjust lwrite.c, wref.c, wrtfmt.c so compiling with
--DWANT_LEAD_0 causes formatted writes of floating-point numbers of
-magnitude < 1 to have an explicit 0 before the decimal point (if the
-field-width permits it).  Note that the Fortran 77 Standard leaves it
-up to the implementation whether to supply these superfluous zeros.
-
-Tue Aug  1 09:25:56 EDT 1995
-  Permit real (or double precision) parameters in dimension expressions.
-
-Mon Aug  7 08:04:00 EDT 1995
-  Append "_eqv" rather than just "_" to names that that appear in
-EQUIVALENCE statements as well as structs in f2c.h (to avoid a
-conflict when these names also name common blocks).
-
-Tue Aug  8 12:49:02 EDT 1995
-  Modify yesterday's change: merge st_fields with c_keywords, to
-cope with equivalences introduced to permit initializing numeric
-variables with character data.  DATA statements causing these
-equivalences can appear after executable statements, so the only
-safe course is to rename all local variable with names in the
-former st_fields list.  This has the unfortunate side effect that
-the common local variable "i" will henceforth be renamed "i__".
-
-Wed Aug 30 00:19:32 EDT 1995
-  libf77: add F77_aloc, now used in s_cat and system_ (to allocate
-memory and check for failure in so doing).
-  libi77: improve MSDOS logic in backspace.c.
-
-Wed Sep  6 09:06:19 EDT 1995
-  libf77: Fix return type of system_ (integer) under -DKR_headers.
-  libi77: Move some f_init calls around for people who do not use
-libF77's main(); now open and namelist read statements that are the
-first I/O statements executed should work right in that context.
-Adjust namelist input to treat a subscripted name whose subscripts do
-not involve colons similarly to the name without a subscript:  accept
-several values, stored in successive elements starting at the
-indicated subscript.  Adjust namelist output to quote character
-strings (avoiding confusion with arrays of character strings).
-
-Thu Sep  7 00:36:04 EDT 1995
-  Fix glitch in integer*8 exponentiation function: it's pow_qq, not
-pow_qi.
-  libi77: fix some bugs with -DAllow_TYQUAD (for integer*8); when
-looking for the &name that starts NAMELIST input, treat lines whose
-first nonblank character is something other than &, $, or ? as
-comment lines (i.e., ignore them), unless rsne.c is compiled with
--DNo_Namelist_Comments.
-
-Thu Sep  7 09:05:40 EDT 1995
-  libi77: rdfmt.c:  one more tweak for -DAllow_TYQUAD.
-
-Tue Sep 19 00:03:02 EDT 1995
-  Adjust handling of floating-point subscript bounds (a questionable
-f2c extension) so subscripts in the generated C are of integral type.
-  Move #define of roundup to proc.c (where its use is commented out);
-version.c left at 19950918.
-
-Wed Sep 20 17:24:19 EDT 1995
-  Fix bug in handling ichar() under -h.
-
-Thu Oct  5 07:52:56 EDT 1995
-  libi77: wrtfmt.c: fix bug with t editing (f__cursor was not always
-zeroed in mv_cur).
-
-Tue Oct 10 10:47:54 EDT 1995
-  Under -ext, warn about X**-Y and X**+Y.  Following the original f77,
-f2c treats these as X**(-Y) and X**(+Y), respectively.  (They are not
-allowed by the official Fortran 77 Standard.)  Some Fortran compilers
-give a bizarre interpretation to larger contexts, making multiplication
-noncommutative: they treat X**-Y*Z as X**(-Y*Z) rather than X**(-Y)*Z,
-which, following the rules of Fortran 77, is the same as (X**(-Y))*Z.
-
-Wed Oct 11 13:27:05 EDT 1995
-  libi77: move defs of f__hiwater, f__svic, f__icptr from wrtfmt.c
-to err.c.  This should work around a problem with buggy loaders and
-sometimes leads to smaller executable programs.
-
-Sat Oct 21 23:54:22 EDT 1995
-  Under -h, fix bug in the treatment of ichar('0') in arithmetic
-expressions.
-  Demote to -dneg (a new command-line option not mentioned in the
-man page) imitation of the original f77's treatment of unary minus
-applied to a REAL operand (yielding a DOUBLE PRECISION result).
-Previously this imitation (which was present for debugging) occurred
-under (the default) -!R.  It is still suppressed by -R.
-
-Tue Nov  7 23:52:57 EST 1995
-  Adjust assigned GOTOs to honor SAVE declarations.
-  Add comments about ranlib to lib[FI]77/README and makefile.
-
-Tue Dec 19 22:54:06 EST 1995
-  libf77: s_cat.c: fix bug when 2nd or later arg overlaps lhs.
-
-Tue Jan  2 17:54:00 EST 1996
-  libi77: rdfmt.c: move #include "ctype.h" up before "stdlib.h"; no
-change to Version.c.
-
-Sun Feb 25 22:20:20 EST 1996
-  Adjust expr.c to permit raising the integer constants 1 and -1 to
-negative constant integral powers.
-  Avoid faulting when -T and -d are not followed by a directory name
-(immediately, without intervening spaces).
-
-Wed Feb 28 12:49:01 EST 1996
-  Fix a glitch in handling complex parameters assigned a "wrong" type.
-Example:
-	complex d, z
-	parameter(z = (0d0,0d0))
-	data d/z/	! elicited "non-constant initializer"
-	call foo(d)
-	end
-
-Thu Feb 29 00:53:12 EST 1996
-  Fix bug in handling character parameters assigned a char() value.
-Example:
-	character*2 b,c
-	character*1 esc
-	parameter(esc = char(27))
-	integer i
-	data (b(i:i),i=1,2)/esc,'a'/
-	data (c(i:i),i=1,2)/esc,'b'/	! memory fault
-	call foo(b,c)
-	end
-
-Fri Mar  1 23:44:51 EST 1996
-  Fix glitch in evaluating .EQ. and .NE. when both operands are
-logical constants (.TRUE. or .FALSE.).
-
-Fri Mar 15 17:29:54 EST 1996
-  libi77: lread.c, rsfe.c: honor END= in READ stmts with empty iolist.
-
-Tue Mar 19 23:08:32 EST 1996
-  lex.c: arrange for a "statement" consisting of a single short bogus
-keyword to elicit an error message showing the whole keyword.  The
-error message formerly omitted the last letter of the bad keyword.
-  libf77: s_cat.c: supply missing break after overlap detection.
-
-Mon May 13 23:35:26 EDT 1996
-  Recognize Fortran 90's /= as a synonym for .NE..  (<> remains a
-synonym for .NE..)
-  Emit an empty int function of no arguments to supply an external
-name to named block data subprograms (so they can be called somewhere
-to force them to be loaded from a library).
-  Fix bug (memory fault) in handling the following illegal Fortran:
-	parameter(i=1)
-	equivalence(i,j)
-	end
-  Treat cdabs, cdcos, cdexp, cdlog, cdsin, and cdsqrt as synonyms for
-the double complex intrinsics zabs, zcos, zexp, zlog, zsin, and zsqrt,
-respectively, unless -cd is specified.
-  Recognize the Fortran 90 bit-manipulation intrinsics btest, iand,
-ibclr, ibits, ibset, ieor, ior, ishft, and ishftc, unless -i90 is
-specified.  Note that iand, ieor, and ior are thus now synonyms for
-"and", "xor", and "or", respectively.
-  Add three macros (bit_test, bit_clear, bit_set) to f2c.h for use
-with btest, ibclr, and ibset, respectively.  Add new functions
-[lq]bit_bits, [lq]bit_shift, and [lq]_bit_cshift to libF77 for
-use with ibits, ishft, and ishftc, respectively.
-  Add integer function ftell(unit) (returning -1 on error) and
-subroutine fseek(unit, offset, whence, *) to libI77 (with branch to
-label * on error).
-
-Tue May 14 23:21:12 EDT 1996
-  Fix glitch (possible memory fault, or worse) in handling multiple
-entry points with names over 28 characters long.
-
-Mon Jun 10 01:20:16 EDT 1996
-  Update netlib E-mail and ftp addresses in f2c/readme and
-f2c/src/readme (which are different files) -- to reflect the upcoming
-breakup of AT&T.
-  libf77: trivial tweaks to F77_aloc.c and system_.c; Version.c not
-changed.
-  libi77: Adjust rsli.c and lread.c so internal list input with too
-few items in the input string will honor end= .
-
-Mon Jun 10 22:59:57 EDT 1996
-  Add Bits_per_Byte to sysdep.h and adjust definition of Table_size
-to depend on Bits_per_Byte (forcing Table_size to be a power of 2); in
-lex.c, change "comstart[c & 0xfff]" to "comstart[c & (Table_size-1)]"
-to avoid an out-of-range subscript on end-of-file.
-
-Wed Jun 12 00:24:28 EDT 1996
-  Fix bug in output.c (dereferencing a freed pointer) revealed in
-	print *		!np in out_call in output.c clobbered by free
-	end		!during out_expr.
-
-Wed Jun 19 08:12:47 EDT 1996
-  f2c.h: add types uinteger, ulongint (for libF77); add qbit_clear
-and qbit_set macros (in a commented-out section) for integer*8.
-  For integer*8, use qbit_clear and qbit_set for ibclr and ibset.
-  libf77: add casts to unsigned in [lq]bitshft.c.
-
-Thu Jun 20 13:30:43 EDT 1996
-  Complain at character*(*) in common (rather than faulting).
-  Fix bug in recognizing hex constants that start with "16#" (e.g.,
-16#1234abcd, which is a synonym for z'1234abcd').
-  Fix bugs in constant folding of expressions involving btest, ibclr,
-and ibset.
-  Fix bug in constant folding of rshift(16#80000000, -31) (on a 32-bit
-machine; more generally, the bug was in constant folding of
-rshift(ibset(0,NBITS-1), 1-NBITS) when f2c runs on a machine with
-long ints having NBITS bits.
-
-Mon Jun 24 07:58:53 EDT 1996
-  Adjust struct Literal and newlabel() function to accommodate huge
-source files (with more than 32767 newlabel() invocations).
-  Omit .c file when the .f file has a missing final end statement.
-
-Wed Jun 26 14:00:02 EDT 1996
-  libi77: Add discussion of MXUNIT (highest allowed Fortran unit number)
-to libI77/README.
-
-Fri Jun 28 14:16:11 EDT 1996
-  Fix glitch with -onetrip: the temporary variable used for nonconstant
-initial loop variable values was recycled too soon.  Example:
-	do i = j+1, k
-		call foo(i+1)	! temp for j+1 was reused here
-		enddo
-	end
-
-Tue Jul  2 16:11:27 EDT 1996
-  formatdata.c: add a 0 to the end of the basetype array (for TYBLANK)
-(an omission that was harmless on most machines).
-  expr.c: fix a dereference of NULL that was only possible with buggy
-input, such as
-	subroutine $sub(s)	! the '$' is erroneous
-	character s*(*)
-	s(1:) = ' '
-	end
-
-Sat Jul  6 00:44:56 EDT 1996
-  Fix glitch in the intrinsic "real" function when applied to a
-complex (or double complex) variable and passed as an argument to
-some intrinsic functions.  Example:
-	complex a
-	b = sqrt(a)
-	end
-  Fix glitch (only visible if you do not use f2c's malloc and the
-malloc you do use is defective in the sense that malloc(0) returns 0)
-in handling include files that end with another include (perhaps
-followed by comments).
-  Fix glitch with character*(*) arguments named "h" and "i" when
-the body of the subroutine invokes the intrinsic LEN function.
-  Arrange that after a previous "f2c -P foo.f" has produced foo.P,
-running "f2c foo.P foo.f" will produce valid C when foo.f contains
-	call sub('1234')
-	end
-	subroutine sub(msg)
-	end
-Specifically, the length argument in "call sub" is now suppressed.
-With or without foo.P, it is also now suppressed when the order of
-subprograms in file foo.f is reversed:
-	subroutine sub(msg)
-	end
-	call sub('1234')
-	end
-  Adjust copyright notices to reflect AT&T breakup.
-
-Wed Jul 10 09:25:49 EDT 1996
-  Fix bug (possible memory fault) in handling erroneously placed
-and inconsistent declarations.  Example that faulted:
-	character*1 w(8)
-	call foo(w)
-	end
-	subroutine foo(m)
-	data h /0.5/
-	integer m(2)	! should be before data
-	end
-  Fix bug (possible fault) in handling illegal "if" constructions.
-Example (that faulted):
-	subroutine foo(i,j)
-	if (i) then		! bug: i is integer, not logical
-	else if (j) then	! bug: j is integer, not logical
-	endif
-	end
-  Fix glitch with character*(*) argument named "ret_len" to a
-character*(*) function.
-
-Wed Jul 10 23:04:16 EDT 1996
-  Fix more glitches in the intrinsic "real" function when applied to a
-complex (or double complex) variable and passed as an argument to
-some intrinsic functions.  Example:
-	complex a, b
-	r = sqrt(real(conjg(a))) + sqrt(real(a*b))
-	end
-
-Thu Jul 11 17:27:16 EDT 1996
-  Fix a memory fault associated with complicated, illegal input.
-Example:
-	subroutine goo
-	character a
-	call foo(a)	! inconsistent with subsequent def and call
-	end
-	subroutine foo(a)
-	end
-	call foo(a)
-	end
-
-Wed Jul 17 19:18:28 EDT 1996
-  Fix yet another case of intrinsic "real" applied to a complex
-argument.  Example:
-	complex a(3)
-	x = sqrt(real(a(2)))	! gave error message about bad tag
-	end
-
-Mon Aug 26 11:28:57 EDT 1996
-  Tweak sysdep.c for non-Unix systems in which process ID's can be
-over 5 digits long.
-
-Tue Aug 27 08:31:32 EDT 1996
-  Adjust the ishft intrinsic to use unsigned right shifts.  (Previously,
-a negative constant second operand resulted in a possibly signed shift.)
-
-Thu Sep 12 14:04:07 EDT 1996
-  equiv.c: fix glitch with -DKR_headers.
-  libi77: fmtlib.c: fix bug in printing the most negative integer.
-
-Fri Sep 13 08:54:40 EDT 1996
-  Diagnose some illegal appearances of substring notation.
-
-Tue Sep 17 17:48:09 EDT 1996
-  Fix fault in handling some complex parameters.  Example:
-	subroutine foo(a)
-	double complex a, b
-	parameter(b = (0,1))
-	a = b	! f2c faulted here
-	end
-
-Thu Sep 26 07:47:10 EDT 1996
-  libi77:  fmt.h:  for formatted writes of negative integer*1 values,
-make ic signed on ANSI systems.  If formatted writes of integer*1
-values trouble you when using a K&R C compiler, switch to an ANSI
-compiler or use a compiler flag that makes characters signed.
-
-Tue Oct  1 14:41:36 EDT 1996
-  Give a better error message when dummy arguments appear in data
-statements.
-
-Thu Oct 17 13:37:22 EDT 1996
-  Fix bug in typechecking arguments to character and complex (or
-double complex) functions; the bug could cause length arguments
-for character arguments to be omitted on invocations appearing
-textually after the first invocation.  For example, in
-	subroutine foo
-	character c
-	complex zot
-	call goo(zot(c), zot(c))
-	end
-the length was omitted from the second invocation of zot, and
-there was an erroneous error message about inconsistent calling
-sequences.
-
-Wed Dec  4 13:59:14 EST 1996
-  Fix bug revealed by
-	subroutine test(cdum,rdum)
-	complex cdum
-	rdum=cos(real(cdum))	! "Unexpected tag 3 in opconv_fudge"
-	end
-  Fix glitch in parsing "DO 10 D0 = 1, 10".
-  Fix glitch in parsing
-	real*8 x
-	real*8 x	! erroneous "incompatible type" message
-	call foo(x)
-	end
-
-Mon Dec  9 23:15:02 EST 1996
-  Fix glitch in parameter adjustments for arrays whose lower
-bound depends on a scalar argument.  Example:
-	subroutine bug(p,z,m,n)
-	integer z(*),m,n
-	double precision p(z(m):z(m) + n)	! p_offset botched
-	call foo(p(0), p(n))
-	end
-  libi77: complain about non-positive rec= in direct read and write
-statements.
-  libf77: trivial adjustments; Version.c not changed.
-
-Wed Feb 12 00:18:03 EST 1997
-  output.c: fix (seldom problematic) glitch in out_call: put parens
-around the ... in a test of the form "if (q->tag == TADDR && ...)".
-  vax.c: fix bug revealed in the "psi_offset =" assignment in the
-following example:
-	subroutine foo(psi,m)
-	integer z(100),m
-	common /a/ z
-	double precision psi(z(m):z(m) + 10)
-	call foo(m+1, psi(0),psi(10))
-	end
-
-Mon Feb 24 23:44:54 EST 1997
-  For consistency with f2c's current treatment of adjacent character
-strings in FORMAT statements, recognize a Hollerith string following
-a string (and merge adjacent strings in FORMAT statements).
-
-Wed Feb 26 13:41:11 EST 1997
-  New libf2c.zip, a combination of the libf77 and libi77 bundles (and
-available only by ftp).
-  libf77: adjust functions with a complex output argument to permit
-aliasing it with input arguments.  (For now, at least, this is just
-for possible benefit of g77.)
-  libi77: tweak to ftell_.c for systems with strange definitions of
-SEEK_SET, etc.
-
-Tue Apr  8 20:57:08 EDT 1997
-  libf77: [cz]_div.c: tweaks invisible on most systems (that may
-improve things slightly with optimized compilation on systems that use
-gratuitous extra precision).
-  libi77: fmt.c: adjust to complain at missing numbers in formats
-(but still treat missing ".nnn" as ".0").
-
-Fri Apr 11 14:05:57 EDT 1997
-  libi77: err.c: attempt to make stderr line buffered rather than
-fully buffered.  (Buffering is needed for format items T and TR.)
-
-Thu Apr 17 22:42:43 EDT 1997
- libf77: add F77_aloc.o to makefile (and makefile.u in libf2c.zip).
-
-Fri Apr 25 19:32:09 EDT 1997
- libf77: add [de]time_.c (which may give trouble on some systems).
-
-Tue May 27 09:18:52 EDT 1997
- libi77: ftell_.c: fix typo that caused the third argument to be
-treated as 2 on some systems.
-
-Mon Jun  9 00:04:37 EDT 1997
- libi77 (and libf2c.zip): adjust include order in err.c lread.c wref.c
-rdfmt.c to include fmt.h (etc.) after system includes.  Version.c not
-changed.
-
-Mon Jul 21 16:04:54 EDT 1997
-  proc.c: fix glitch in logic for "nonpositive dimension" message.
-  libi77: inquire.c: always include string.h (for possible use with
--DNON_UNIX_STDIO); Version.c not changed.
-
-Thu Jul 24 17:11:23 EDT 1997
-  Tweak "Notice" to reflect the AT&T breakup -- we missed it when
-updating the copyright notices in the source files last summer.
-  Adjust src/makefile so malloc.o is not used by default, but can
-be specified with "make MALLOC=malloc.o".
-  Add comments to src/README about the "CRAY" T3E.
-
-Tue Aug  5 14:53:25 EDT 1997
-  Add definition of calloc to malloc.c; this makes f2c's malloc
-work on some systems where trouble hitherto arose because references
-to calloc brought in the system's malloc.  (On sensible systems,
-calloc is defined separately from malloc.  To avoid confusion on
-other systems, f2c/malloc.c now defines calloc.)
-  libi77: lread.c: adjust to accord with a change to the Fortran 8X
-draft (in 1990 or 1991) that rescinded permission to elide quote marks
-in namelist input of character data; to get the old behavior, compile
-with F8X_NML_ELIDE_QUOTES #defined.  wrtfmt.o: wrt_G: tweak to print
-the right number of 0's for zero under G format.
-
-Sat Aug 16 05:45:32 EDT 1997
-  libi77: iio.c: fix bug in internal writes to an array of character
-strings that sometimes caused one more array element than required by
-the format to be blank-filled.  Example: format(1x).
-
-Wed Sep 17 00:39:29 EDT 1997
-  libi77: fmt.[ch] rdfmt.c wrtfmt.c: tweak struct syl for machines
-with 64-bit pointers and 32-bit ints that did not 64-bit align
-struct syl (e.g., Linux on the DEC Alpha).  This change should be
-invisible on other machines.
-
-Sun Sep 21 22:05:19 EDT 1997
-  libf77: [de]time_.c (Unix systems only): change return type to double.
-
-Thu Dec  4 22:10:09 EST 1997
-  Fix bug with handling large blocks of comments (over 4k); parts of the
-second and subsequent blocks were likely to be lost (not copied into
-comments in the resulting C).  Allow comment lines to be longer before
-breaking them.
-
-Mon Jan 19 17:19:27 EST 1998
-  makefile: change the rule for making gram.c to one for making gram1.c;
-henceforth, asking netlib to "send all from f2c/src" will bring you a
-working gram.c.  Nowadays there are simply too many broken versions of
-yacc floating around.
-  libi77: backspace.c: for b->ufmt==0, change sizeof(int) to
-sizeof(uiolen).  On machines where this would make a difference, it is
-best for portability to compile libI77 with -DUIOLEN_int, which will
-render the change invisible.
-
-Tue Feb 24 08:35:33 EST 1998
-  makefile: remove gram.c from the "make clean" rule.
-
-Wed Feb 25 08:29:39 EST 1998
-  makefile: change CFLAGS assignment to -O; add "veryclean" rule.
-
-Wed Mar  4 13:13:21 EST 1998
-  libi77: open.c: fix glitch in comparing file names under
--DNON_UNIX_STDIO.
-
-Mon Mar  9 23:56:56 EST 1998
-  putpcc.c: omit an unnecessary temporary variable in computing
-(expr)**3.
-  libf77, libi77: minor tweaks to make some C++ compilers happy;
-Version.c not changed.
-
-Wed Mar 18 18:08:47 EST 1998
-  libf77: minor tweaks to [ed]time_.c; Version.c not changed.
-  libi77: endfile.c, open.c: acquire temporary files from tmpfile(),
-unless compiled with -DNON_ANSI_STDIO, which uses mktemp().
-New buffering scheme independent of NON_UNIX_STDIO for handling T
-format items.  Now -DNON_UNIX_STDIO is no longer be necessary for
-Linux, and libf2c no longer causes stderr to be buffered -- the former
-setbuf or setvbuf call for stderr was to make T format items work.
-open.c: use the Posix access() function to check existence or
-nonexistence of files, except under -DNON_POSIX_STDIO, where trial
-fopen calls are used.  In open.c, fix botch in changes of 19980304.
-  libf2c.zip: the PC makefiles are now set for NT/W95, with comments
-about changes for DOS.
-
-Fri Apr  3 17:22:12 EST 1998
-  Adjust fix of 19960913 to again permit substring notation on
-character variables in data statements.
-
-Sun Apr  5 19:26:50 EDT 1998
-  libi77: wsfe.c: make $ format item work: this was lost in the changes
-of 17 March 1998.
-
-Sat May 16 19:08:51 EDT 1998
-  Adjust output of ftnlen constants: rather than appending L,
-prepend (ftnlen).  This should make the resulting C more portable,
-e.g., to systems (such as DEC Alpha Unix systems) on which long
-may be longer than ftnlen.
-  Adjust -r so it also casts REAL expressions passed to intrinsic
-functions to REAL.
-
-Wed May 27 16:02:35 EDT 1998
-  libf2c.zip: tweak description of compiling libf2c for INTEGER*8
-to accord with makefile.u rather than libF77/makefile.
-
-Thu May 28 22:45:59 EDT 1998
-  libi77: backspace.c dfe.c due.c iio.c lread.c rsfe.c sue.c wsfe.c:
-set f__curunit sooner so various error messages will correctly
-identify the I/O unit involved.
-  libf2c.zip: above, plus tweaks to PC makefiles: for some purposes,
-it's still best to compile with -DMSDOS (even for use with NT).
-
-Thu Jun 18 01:22:52 EDT 1998
-  libi77: lread.c: modified so floating-point numbers (containing
-either a decimal point or an exponent field) are treated as errors
-when they appear as list input for integer data.  Compile lread.c with
--DALLOW_FLOAT_IN_INTEGER_LIST_INPUT to restore the old behavior.
-
-Mon Aug 31 10:38:54 EDT 1998
-  formatdata.c: if possible, and assuming doubles must be aligned on
-double boundaries, use existing holes in DATA for common blocks to
-force alignment of the block.  For example,
-	block data
-	common /abc/ a, b
-	double precision a
-	integer b(2)
-	data b(2)/1/
-	end
-used to generate
-	struct {
-	    integer fill_1[3];
-	    integer e_2;
-	    doublereal e_3;
-	    } abc_ = { {0}, 1, 0. };
-and now generates
-	struct {
-	    doublereal fill_1[1];
-	    integer fill_2[1];
-	    integer e_3;
-	    } abc_ = { {0}, {0}, 1 };
-In the old generated C, e_3 was added to force alignment; in the new C,
-fill_1 does this job.
-
-Mon Sep  7 19:48:51 EDT 1998
-  libi77: move e_wdfe from sfe.c to dfe.c, where it was originally.
-Why did it ever move to sfe.c?
-
-Tue Sep  8 10:22:50 EDT 1998
-  Treat dreal as a synonym for dble unless -cd is specified on the
-command line.
-
-Sun Sep 13 22:23:41 EDT 1998
-  format.c: fix bug in writing prototypes under f2c -A ... *.P:
-under some circumstances involving external functions with no known
-type, a null pointer was passed to printf.
-
-Tue Oct 20 23:25:54 EDT 1998
-  Comments added to libf2c/README and libF77/README, pointing out
-the need to modify signal1.h on some systems.
-
-Wed Feb 10 22:59:52 EST 1999
-  defs.h lex.c: permit long names (up to at least roughly
-MAX_SHARPLINE_LEN = 1000 characters long) in #line lines (which only
-matters under -g).
-  fc: add -U option; recognize .so files.
-
-Sat Feb 13 10:18:27 EST 1999
- libf2c: endfile.c, lread.c, signal1.h0: minor tweaks to make some
-(C++) compilers happier; f77_aloc.c: make exit_() visible to C++
-compilers.  Version strings not changed.
-
-Thu Mar 11 23:14:02 EST 1999
-  Modify f2c (exec.c, expr.c) to diagnose incorrect mixing of types
-when (f2c extended) intrinsic functions are involved, as in
-(not(17) .and. 4).  Catching this in the first executable statement
-is a bit tricky, as some checking must be postponed until all statement
-function declarations have been parsed.  Thus there is a chance of
-today's changes introducing bugs under (let us hope) unusual conditions.
-
-Sun Mar 28 13:17:44 EST 1999
-  lex.c: tweak to get the file name right in error messages caused
-by statements just after a # nnn "filename" line emitted by the C
-preprocessor.  (The trouble is that the line following the # nnn line
-must be read to see if it is a continuation of the stuff that preceded
-the # nnn line.)  When # nnn "filename" lines appear among the lines
-for a Fortran statement, the filename reported in an error message for
-the statement should now be the file that was current when the first
-line of the statement was read.
-
-Sun May  2 22:38:25 EDT 1999
-  libf77, libi77, libf2c.zip: make getenv_() more portable (call
-getenv() rather than knowing about char **environ); adjust some
-complex intrinsics to work with overlapping arguments (caused by
-inappropriate use of equivalence); open.c: get "external" versus
-"internal" right in the error message if a file cannot be opened;
-err.c: cast a pointer difference to (int) for %d; rdfmt.c: omit
-fixed-length buffer that could be overwritten by formats Inn or Lnn
-with nn > 83.
-
-Mon May  3 13:14:07 EDT 1999
-  "Invisible" changes to omit a few compiler warnings in f2c and
-libf2c; two new casts in libf2c/open.c that matter with 64-bit longs,
-and one more tweak (libf2c/c_log.c) for pathological equivalences.
-  Minor update to "fc" script: new -L flag and comment correction.
-
-Fri Jun 18 02:33:08 EDT 1999
-  libf2c.zip: rename backspace.c backspac.c, and fix a glitch in it
--- b->ufd may change in t_runc().  (For now, it's still backspace.c
-in the libi77 bundle.)
-
-Sun Jun 27 22:05:47 EDT 1999
-  libf2c.zip, libi77: rsne.c: fix bug in namelist input: a misplaced
-increment could cause wrong array elements to be assigned; e.g.,
-"&input k(5)=10*1 &end" assigned k(5) and k(15 .. 23).
diff --git a/contrib/libf2c/configure b/contrib/libf2c/configure
deleted file mode 100755
index 93cf71a76ae..00000000000
--- a/contrib/libf2c/configure
+++ /dev/null
@@ -1,2939 +0,0 @@
-#! /bin/sh
-
-# Guess values for system-dependent variables and create Makefiles.
-# Generated automatically using autoconf version 2.13 
-# Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc.
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-
-# Defaults:
-ac_help=
-ac_default_prefix=/usr/local
-# Any additions from configure.in:
-ac_help="$ac_help
-  --enable-multilib       build hella library versions (default)"
-ac_help="$ac_help
-  --with-target-subdir=SUBDIR
-                           configuring in a subdirectory"
-ac_help="$ac_help
-  --with-cross-host=HOST  configuring with a cross compiler"
-ac_help="$ac_help
-  --enable-version-specific-runtime-libs    Specify that runtime libraries should be installed in a compiler-specific directory "
-ac_help="$ac_help
-  --enable-shared[=PKGS]  build shared libraries [default=yes]"
-ac_help="$ac_help
-  --enable-static[=PKGS]  build static libraries [default=yes]"
-ac_help="$ac_help
-  --enable-fast-install[=PKGS]  optimize for fast installation [default=yes]"
-ac_help="$ac_help
-  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]"
-ac_help="$ac_help
-  --disable-libtool-lock  avoid locking (might break parallel builds)"
-ac_help="$ac_help
-  --with-pic              try to use only PIC/non-PIC objects [default=use both]"
-
-# Initialize some variables set by options.
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
-exec_prefix=NONE
-host=NONE
-no_create=
-nonopt=NONE
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-target=NONE
-verbose=
-x_includes=NONE
-x_libraries=NONE
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
-
-# Initialize some other variables.
-subdirs=
-MFLAGS= MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-# Maximum number of lines to put in a shell here document.
-ac_max_here_lines=12
-
-ac_prev=
-for ac_option
-do
-
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
-    ac_prev=
-    continue
-  fi
-
-  case "$ac_option" in
-  -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
-  *) ac_optarg= ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case "$ac_option" in
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file="$ac_optarg" ;;
-
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
-
-  -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    eval "enable_${ac_feature}=no" ;;
-
-  -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "enable_${ac_feature}='$ac_optarg'" ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he)
-    # Omit some internal or obsolete options to make the list less imposing.
-    # This message is too long to be a string in the A/UX 3.1 sh.
-    cat << EOF
-Usage: configure [options] [host]
-Options: [defaults in brackets after descriptions]
-Configuration:
-  --cache-file=FILE       cache test results in FILE
-  --help                  print this message
-  --no-create             do not create output files
-  --quiet, --silent       do not print \`checking...' messages
-  --version               print the version of autoconf that created configure
-Directory and file names:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [same as prefix]
-  --bindir=DIR            user executables in DIR [EPREFIX/bin]
-  --sbindir=DIR           system admin executables in DIR [EPREFIX/sbin]
-  --libexecdir=DIR        program executables in DIR [EPREFIX/libexec]
-  --datadir=DIR           read-only architecture-independent data in DIR
-                          [PREFIX/share]
-  --sysconfdir=DIR        read-only single-machine data in DIR [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data in DIR
-                          [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data in DIR [PREFIX/var]
-  --libdir=DIR            object code libraries in DIR [EPREFIX/lib]
-  --includedir=DIR        C header files in DIR [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc in DIR [/usr/include]
-  --infodir=DIR           info documentation in DIR [PREFIX/info]
-  --mandir=DIR            man documentation in DIR [PREFIX/man]
-  --srcdir=DIR            find the sources in DIR [configure dir or ..]
-  --program-prefix=PREFIX prepend PREFIX to installed program names
-  --program-suffix=SUFFIX append SUFFIX to installed program names
-  --program-transform-name=PROGRAM
-                          run sed PROGRAM on installed program names
-EOF
-    cat << EOF
-Host type:
-  --build=BUILD           configure for building on BUILD [BUILD=HOST]
-  --host=HOST             configure for HOST [guessed]
-  --target=TARGET         configure for TARGET [TARGET=HOST]
-Features and packages:
-  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
-  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --x-includes=DIR        X include files are in DIR
-  --x-libraries=DIR       X library files are in DIR
-EOF
-    if test -n "$ac_help"; then
-      echo "--enable and --with options recognized:$ac_help"
-    fi
-    exit 0 ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir="$ac_optarg" ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir="$ac_optarg" ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix="$ac_optarg" ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix="$ac_optarg" ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir="$ac_optarg" ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers)
-    echo "configure generated by autoconf version 2.13"
-    exit 0 ;;
-
-  -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "with_${ac_package}='$ac_optarg'" ;;
-
-  -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    eval "with_${ac_package}=no" ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes="$ac_optarg" ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries="$ac_optarg" ;;
-
-  -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
-    ;;
-
-  *)
-    if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then
-      echo "configure: warning: $ac_option: invalid host type" 1>&2
-    fi
-    if test "x$nonopt" != xNONE; then
-      { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; }
-    fi
-    nonopt="$ac_option"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; }
-fi
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-# File descriptor usage:
-# 0 standard input
-# 1 file creation
-# 2 errors and warnings
-# 3 some systems may open it to /dev/tty
-# 4 used on the Kubota Titan
-# 6 checking for... messages and results
-# 5 compiler messages saved in config.log
-if test "$silent" = yes; then
-  exec 6>/dev/null
-else
-  exec 6>&1
-fi
-exec 5>./config.log
-
-echo "\
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-" 1>&5
-
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Also quote any args containing shell metacharacters.
-ac_configure_args=
-for ac_arg
-do
-  case "$ac_arg" in
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c) ;;
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;;
-  *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
-  ac_configure_args="$ac_configure_args '$ac_arg'" ;;
-  *) ac_configure_args="$ac_configure_args $ac_arg" ;;
-  esac
-done
-
-# NLS nuisances.
-# Only set these to C if already set.  These must not be set unconditionally
-# because not all systems understand e.g. LANG=C (notably SCO).
-# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
-# Non-C LC_CTYPE values break the ctype check.
-if test "${LANG+set}"   = set; then LANG=C;   export LANG;   fi
-if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
-if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
-if test "${LC_CTYPE+set}"    = set; then LC_CTYPE=C;    export LC_CTYPE;    fi
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo > confdefs.h
-
-# A filename unique to this package, relative to the directory that
-# configure is in, which we can look for to find out if srcdir is correct.
-ac_unique_file=libF77/Version.c
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_prog=$0
-  ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'`
-  test "x$ac_confdir" = "x$ac_prog" && ac_confdir=.
-  srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; }
-  else
-    { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; }
-  fi
-fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
-fi
-for ac_site_file in $CONFIG_SITE; do
-  if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
-    . "$ac_site_file"
-  fi
-done
-
-if test -r "$cache_file"; then
-  echo "loading cache $cache_file"
-  . $cache_file
-else
-  echo "creating cache $cache_file"
-  > $cache_file
-fi
-
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-ac_exeext=
-ac_objext=o
-if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
-  # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu.
-  if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
-    ac_n= ac_c='
-' ac_t='	'
-  else
-    ac_n=-n ac_c= ac_t=
-  fi
-else
-  ac_n= ac_c='\c' ac_t=
-fi
-
-
-
-# This works around the fact that libtool configuration may change LD
-# for this particular configuration, but some shells, instead of
-# keeping the changes in LD private, export them just because LD is
-# exported.
-ORIGINAL_LD_FOR_MULTILIBS=$LD
-
-
-    # Check whether --enable-multilib or --disable-multilib was given.
-if test "${enable_multilib+set}" = set; then
-  enableval="$enable_multilib"
-  case "${enableval}" in
-    yes) multilib=yes ;;
-    no)  multilib=no ;;
-    *)   { echo "configure: error: bad value ${enableval} for multilib option" 1>&2; exit 1; } ;;
-   esac
-else
-  multilib=yes
-fi
-
-# When building with srcdir == objdir, links to the source files will
-# be created in directories within the target_subdir.  We have to
-# adjust toplevel_srcdir accordingly, so that configure finds
-# install-sh and other auxiliary files that live in the top-level
-# source directory.
-if test "${srcdir}" = "."; then
-  if test -z "${with_target_subdir}"; then
-    toprel=".."
-  else
-    if test "${with_target_subdir}" != "."; then
-      toprel="${with_multisrctop}../.."
-    else
-      toprel="${with_multisrctop}.."
-    fi
-  fi
-else
-  toprel=".."
-fi
-ac_aux_dir=
-for ac_dir in ${srcdir}/$toprel $srcdir/${srcdir}/$toprel; do
-  if test -f $ac_dir/install-sh; then
-    ac_aux_dir=$ac_dir
-    ac_install_sh="$ac_aux_dir/install-sh -c"
-    break
-  elif test -f $ac_dir/install.sh; then
-    ac_aux_dir=$ac_dir
-    ac_install_sh="$ac_aux_dir/install.sh -c"
-    break
-  fi
-done
-if test -z "$ac_aux_dir"; then
-  { echo "configure: error: can not find install-sh or install.sh in ${srcdir}/$toprel $srcdir/${srcdir}/$toprel" 1>&2; exit 1; }
-fi
-ac_config_guess=$ac_aux_dir/config.guess
-ac_config_sub=$ac_aux_dir/config.sub
-ac_configure=$ac_aux_dir/configure # This should be Cygnus configure.
-
-toplevel_srcdir=\${top_srcdir}/$toprel
-
-
-
-
-# Do some error checking and defaulting for the host and target type.
-# The inputs are:
-#    configure --host=HOST --target=TARGET --build=BUILD NONOPT
-#
-# The rules are:
-# 1. You are not allowed to specify --host, --target, and nonopt at the
-#    same time.
-# 2. Host defaults to nonopt.
-# 3. If nonopt is not specified, then host defaults to the current host,
-#    as determined by config.guess.
-# 4. Target and build default to nonopt.
-# 5. If nonopt is not specified, then target and build default to host.
-
-# The aliases save the names the user supplied, while $host etc.
-# will get canonicalized.
-case $host---$target---$nonopt in
-NONE---*---* | *---NONE---* | *---*---NONE) ;;
-*) { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; } ;;
-esac
-
-
-# Make sure we can run config.sub.
-if ${CONFIG_SHELL-/bin/sh} $ac_config_sub sun4 >/dev/null 2>&1; then :
-else { echo "configure: error: can not run $ac_config_sub" 1>&2; exit 1; }
-fi
-
-echo $ac_n "checking host system type""... $ac_c" 1>&6
-echo "configure:635: checking host system type" >&5
-
-host_alias=$host
-case "$host_alias" in
-NONE)
-  case $nonopt in
-  NONE)
-    if host_alias=`${CONFIG_SHELL-/bin/sh} $ac_config_guess`; then :
-    else { echo "configure: error: can not guess host type; you must specify one" 1>&2; exit 1; }
-    fi ;;
-  *) host_alias=$nonopt ;;
-  esac ;;
-esac
-
-host=`${CONFIG_SHELL-/bin/sh} $ac_config_sub $host_alias`
-host_cpu=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
-host_vendor=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
-host_os=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
-echo "$ac_t""$host" 1>&6
-
-echo $ac_n "checking target system type""... $ac_c" 1>&6
-echo "configure:656: checking target system type" >&5
-
-target_alias=$target
-case "$target_alias" in
-NONE)
-  case $nonopt in
-  NONE) target_alias=$host_alias ;;
-  *) target_alias=$nonopt ;;
-  esac ;;
-esac
-
-target=`${CONFIG_SHELL-/bin/sh} $ac_config_sub $target_alias`
-target_cpu=`echo $target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
-target_vendor=`echo $target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
-target_os=`echo $target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
-echo "$ac_t""$target" 1>&6
-
-echo $ac_n "checking build system type""... $ac_c" 1>&6
-echo "configure:674: checking build system type" >&5
-
-build_alias=$build
-case "$build_alias" in
-NONE)
-  case $nonopt in
-  NONE) build_alias=$host_alias ;;
-  *) build_alias=$nonopt ;;
-  esac ;;
-esac
-
-build=`${CONFIG_SHELL-/bin/sh} $ac_config_sub $build_alias`
-build_cpu=`echo $build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
-build_vendor=`echo $build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
-build_os=`echo $build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
-echo "$ac_t""$build" 1>&6
-
-test "$host_alias" != "$target_alias" &&
-  test "$program_prefix$program_suffix$program_transform_name" = \
-    NONENONEs,x,x, &&
-  program_prefix=${target_alias}-
-
-target_alias=${target_alias-$target}
-
-
-if test $host != $build; then
-  ac_tool_prefix=${host_alias}-
-else
-  ac_tool_prefix=
-fi
-
-echo $ac_n "checking for Cygwin environment""... $ac_c" 1>&6
-echo "configure:706: checking for Cygwin environment" >&5
-if eval "test \"`echo '$''{'ac_cv_cygwin'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_cygwin=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_cygwin=no
-fi
-rm -f conftest*
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_cygwin" 1>&6
-CYGWIN=
-test "$ac_cv_cygwin" = yes && CYGWIN=yes
-echo $ac_n "checking for mingw32 environment""... $ac_c" 1>&6
-echo "configure:739: checking for mingw32 environment" >&5
-if eval "test \"`echo '$''{'ac_cv_mingw32'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_mingw32=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_mingw32=no
-fi
-rm -f conftest*
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_mingw32" 1>&6
-MINGW32=
-test "$ac_cv_mingw32" = yes && MINGW32=yes
-
-# Export build and source directories.
-# These need to be absolute paths, yet at the same time need to
-# canonicalize only relative paths, because then amd will not unmount
-# drives. Thus the use of PWDCMD: set it to 'pawd' or 'amq -w' if using amd.
-glibcpp_builddir=`${PWDCMD-pwd}`
-case $srcdir in
-\\/$* | ?:\\/*) glibcpp_srcdir=${srcdir} ;;
-*) glibcpp_srcdir=`cd "$srcdir" && ${PWDCMD-pwd} || echo "$srcdir"` ;;
-esac
-
-
-
-
-
-# Will set LN_S to either 'ln -s' or 'ln'.  With autoconf 2.50+, can also
-# be 'cp -p' if linking isn't available.
-#ac_cv_prog_LN_S='cp -p'
-echo $ac_n "checking whether ln -s works""... $ac_c" 1>&6
-echo "configure:786: checking whether ln -s works" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_LN_S'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  rm -f conftestdata
-if ln -s X conftestdata 2>/dev/null
-then
-  rm -f conftestdata
-  ac_cv_prog_LN_S="ln -s"
-else
-  ac_cv_prog_LN_S=ln
-fi
-fi
-LN_S="$ac_cv_prog_LN_S"
-if test "$ac_cv_prog_LN_S" = "ln -s"; then
-  echo "$ac_t""yes" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-# We use these options to decide which functions to include.
-# Check whether --with-target-subdir or --without-target-subdir was given.
-if test "${with_target_subdir+set}" = set; then
-  withval="$with_target_subdir"
-  :
-fi
-
-# Check whether --with-cross-host or --without-cross-host was given.
-if test "${with_cross_host+set}" = set; then
-  withval="$with_cross_host"
-  :
-fi
-
-
-  # Never versions of autoconf add an underscore to these functions.
-  # Prevent future problems ...
-  
-  
-  
-  
-
-#  AC_PROG_CC
-
-# FIXME: We temporarily define our own version of AC_PROG_CC.  This is
-# copied from autoconf 2.12, but does not call AC_PROG_CC_WORKS.  We
-# are probably using a cross compiler, which will not be able to fully
-# link an executable.  This should really be fixed in autoconf
-# itself.
-
-
-
-
-# Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:842: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="gcc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:872: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_prog_rejected=no
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then
-        ac_prog_rejected=yes
-	continue
-      fi
-      ac_cv_prog_CC="cc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# -gt 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    set dummy "$ac_dir/$ac_word" "$@"
-    shift
-    ac_cv_prog_CC="$@"
-  fi
-fi
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-  test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
-fi
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:921: checking whether we are using GNU C" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.c <&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gcc=yes
-else
-  ac_cv_prog_gcc=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gcc" 1>&6
-
-if test $ac_cv_prog_gcc = yes; then
-  GCC=yes
-  ac_test_CFLAGS="${CFLAGS+set}"
-  ac_save_CFLAGS="$CFLAGS"
-  CFLAGS=
-  echo $ac_n "checking whether ${CC-cc} accepts -g""... $ac_c" 1>&6
-echo "configure:945: checking whether ${CC-cc} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cc_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.c
-if test -z "`${CC-cc} -g -c conftest.c 2>&1`"; then
-  ac_cv_prog_cc_g=yes
-else
-  ac_cv_prog_cc_g=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
-  if test "$ac_test_CFLAGS" = set; then
-    CFLAGS="$ac_save_CFLAGS"
-  elif test $ac_cv_prog_cc_g = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-O2"
-  fi
-else
-  GCC=
-  test "${CFLAGS+set}" = set || CFLAGS="-g"
-fi
-
-
-  # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args.
-set dummy ${ac_tool_prefix}as; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:976: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_AS'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$AS"; then
-  ac_cv_prog_AS="$AS" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_AS="${ac_tool_prefix}as"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_AS" && ac_cv_prog_AS="as"
-fi
-fi
-AS="$ac_cv_prog_AS"
-if test -n "$AS"; then
-  echo "$ac_t""$AS" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-
-  # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ar; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1008: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_AR'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$AR"; then
-  ac_cv_prog_AR="$AR" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_AR="${ac_tool_prefix}ar"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_AR" && ac_cv_prog_AR="ar"
-fi
-fi
-AR="$ac_cv_prog_AR"
-if test -n "$AR"; then
-  echo "$ac_t""$AR" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1040: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-if test -z "$ac_cv_prog_RANLIB"; then
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1072: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_RANLIB="ranlib"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB="ranlib-not-found-in-path-error"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-else
-  RANLIB="ranlib-not-found-in-path-error"
-fi
-fi
-
-  # Find a good install program.  We prefer a C program (faster),
-# so one script is as good as another.  But avoid the broken or
-# incompatible versions:
-# SysV /etc/install, /usr/sbin/install
-# SunOS /usr/etc/install
-# IRIX /sbin/install
-# AIX /bin/install
-# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
-# AFS /usr/afsws/bin/install, which mishandles nonexistent args
-# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
-# ./install, which can be erroneously created by make from ./install.sh.
-echo $ac_n "checking for a BSD compatible install""... $ac_c" 1>&6
-echo "configure:1116: checking for a BSD compatible install" >&5
-if test -z "$INSTALL"; then
-if eval "test \"`echo '$''{'ac_cv_path_install'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-    IFS="${IFS= 	}"; ac_save_IFS="$IFS"; IFS=":"
-  for ac_dir in $PATH; do
-    # Account for people who put trailing slashes in PATH elements.
-    case "$ac_dir/" in
-    /|./|.//|/etc/*|/usr/sbin/*|/usr/etc/*|/sbin/*|/usr/afsws/bin/*|/usr/ucb/*) ;;
-    *)
-      # OSF1 and SCO ODT 3.0 have their own names for install.
-      # Don't use installbsd from OSF since it installs stuff as root
-      # by default.
-      for ac_prog in ginstall scoinst install; do
-        if test -f $ac_dir/$ac_prog; then
-	  if test $ac_prog = install &&
-            grep dspmsg $ac_dir/$ac_prog >/dev/null 2>&1; then
-	    # AIX install.  It has an incompatible calling convention.
-	    :
-	  else
-	    ac_cv_path_install="$ac_dir/$ac_prog -c"
-	    break 2
-	  fi
-	fi
-      done
-      ;;
-    esac
-  done
-  IFS="$ac_save_IFS"
-
-fi
-  if test "${ac_cv_path_install+set}" = set; then
-    INSTALL="$ac_cv_path_install"
-  else
-    # As a last resort, use the slow shell script.  We don't cache a
-    # path for INSTALL within a source directory, because that will
-    # break other packages using the cache if that directory is
-    # removed, or if the path is relative.
-    INSTALL="$ac_install_sh"
-  fi
-fi
-echo "$ac_t""$INSTALL" 1>&6
-
-# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
-# It thinks the first close brace ends the variable substitution.
-test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
-
-test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL_PROGRAM}'
-
-test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
-
-
-  # We need AC_EXEEXT to keep automake happy in cygnus mode.  However,
-  # at least currently, we never actually build a program, so we never
-  # need to use $(EXEEXT).  Moreover, the test for EXEEXT normally
-  # fails, because we are probably configuring with a cross compiler
-  # which can't create executables.  So we include AC_EXEEXT to keep
-  # automake happy, but we don't execute it, since we don't care about
-  # the result.
-  if false; then
-    # autoconf 2.50 runs AC_EXEEXT by default, and the macro expands
-    # to nothing, so nothing would remain between `then' and `fi' if it
-    # were not for the `:' below.
-    :
-    
-
-echo $ac_n "checking for executable suffix""... $ac_c" 1>&6
-echo "configure:1184: checking for executable suffix" >&5
-if eval "test \"`echo '$''{'ac_cv_exeext'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test "$CYGWIN" = yes || test "$MINGW32" = yes; then
-  ac_cv_exeext=.exe
-else
-  rm -f conftest*
-  echo 'int main () { return 0; }' > conftest.$ac_ext
-  ac_cv_exeext=
-  if { (eval echo configure:1194: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; }; then
-    for file in conftest.*; do
-      case $file in
-      *.c | *.o | *.obj) ;;
-      *) ac_cv_exeext=`echo $file | sed -e s/conftest//` ;;
-      esac
-    done
-  else
-    { echo "configure: error: installation or configuration problem: compiler cannot create executables." 1>&2; exit 1; }
-  fi
-  rm -f conftest*
-  test x"${ac_cv_exeext}" = x && ac_cv_exeext=no
-fi
-fi
-
-EXEEXT=""
-test x"${ac_cv_exeext}" != xno && EXEEXT=${ac_cv_exeext}
-echo "$ac_t""${ac_cv_exeext}" 1>&6
-ac_exeext=$EXEEXT
-
-  fi
-
-
-# Assumes glibcpp_builddir, glibcpp_srcdir are alreay set up and
-# exported correctly in GLIBCPP_CONFIGURE.
-glibcpp_toolexecdir=no
-glibcpp_toolexeclibdir=no
-glibcpp_prefixdir=${prefix}
-
-echo $ac_n "checking for interface version number""... $ac_c" 1>&6
-echo "configure:1224: checking for interface version number" >&5
-libstdcxx_interface=$INTERFACE
-echo "$ac_t""$libstdcxx_interface" 1>&6
-
-# Process the option "--enable-version-specific-runtime-libs"
-echo $ac_n "checking for --enable-version-specific-runtime-libs""... $ac_c" 1>&6
-echo "configure:1230: checking for --enable-version-specific-runtime-libs" >&5
-# Check whether --enable-version-specific-runtime-libs or --disable-version-specific-runtime-libs was given.
-if test "${enable_version_specific_runtime_libs+set}" = set; then
-  enableval="$enable_version_specific_runtime_libs"
-  case "$enableval" in
- yes) version_specific_libs=yes ;;
- no)  version_specific_libs=no ;;
- *)   { echo "configure: error: Unknown argument to enable/disable version-specific libs" 1>&2; exit 1; };;
- esac
-else
-  version_specific_libs=no
-fi
-# Option set, now we can test it.
-echo "$ac_t""$version_specific_libs" 1>&6
-
-gcc_version_trigger=${toplevel_srcdir}/gcc/version.c
-gcc_version_full=`grep version_string ${gcc_version_trigger} | sed -e 's/.*\"\([^ \"]*\)[ \"].*/\1/'`
-gcc_version=`echo ${gcc_version_full} | sed -e 's/\(^ *\) .*/\1/'`
-
-
-
-if test $version_specific_libs = yes; then
-  # Need the gcc compiler version to know where to install libraries
-  # and header files if --enable-version-specific-runtime-libs option
-  # is selected.  FIXME: "toolexecdir" is a misnomer, there are no
-  # executables installed there.
-    glibcpp_toolexecdir='$(libdir)/gcc/$(target_alias)'
-  glibcpp_toolexeclibdir='$(toolexecdir)/'${gcc_version}'$(MULTISUBDIR)'
-  fi
-
-# Calculate glibcpp_toolexecdir, glibcpp_toolexeclibdir
-# Install a library built with a cross compiler in tooldir, not libdir.
-if test x"$glibcpp_toolexecdir" = x"no"; then 
-  if test -n "$with_cross_host" &&
-     test x"$with_cross_host" != x"no"; then
-    glibcpp_toolexecdir='$(exec_prefix)/$(target_alias)'
-    glibcpp_toolexeclibdir='$(toolexecdir)/lib'
-  else
-    glibcpp_toolexecdir='$(libdir)/gcc/$(target_alias)'
-    glibcpp_toolexeclibdir='$(libdir)'
-  fi
-  multi_os_directory=`$CC -print-multi-os-directory`
-  case $multi_os_directory in
-    .) ;; # Avoid trailing /.
-    *) glibcpp_toolexeclibdir=$glibcpp_toolexeclibdir/$multi_os_directory ;;
-  esac
-fi
-
-
-
-
-
-
-
-# Check whether --enable-shared or --disable-shared was given.
-if test "${enable_shared+set}" = set; then
-  enableval="$enable_shared"
-  p=${PACKAGE-default}
-case $enableval in
-yes) enable_shared=yes ;;
-no) enable_shared=no ;;
-*)
-  enable_shared=no
-  # Look at the argument we got.  We use all the common list separators.
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:,"
-  for pkg in $enableval; do
-    if test "X$pkg" = "X$p"; then
-      enable_shared=yes
-    fi
-  done
-  IFS="$ac_save_ifs"
-  ;;
-esac
-else
-  enable_shared=yes
-fi
-
-# Check whether --enable-static or --disable-static was given.
-if test "${enable_static+set}" = set; then
-  enableval="$enable_static"
-  p=${PACKAGE-default}
-case $enableval in
-yes) enable_static=yes ;;
-no) enable_static=no ;;
-*)
-  enable_static=no
-  # Look at the argument we got.  We use all the common list separators.
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:,"
-  for pkg in $enableval; do
-    if test "X$pkg" = "X$p"; then
-      enable_static=yes
-    fi
-  done
-  IFS="$ac_save_ifs"
-  ;;
-esac
-else
-  enable_static=yes
-fi
-
-# Check whether --enable-fast-install or --disable-fast-install was given.
-if test "${enable_fast_install+set}" = set; then
-  enableval="$enable_fast_install"
-  p=${PACKAGE-default}
-case $enableval in
-yes) enable_fast_install=yes ;;
-no) enable_fast_install=no ;;
-*)
-  enable_fast_install=no
-  # Look at the argument we got.  We use all the common list separators.
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:,"
-  for pkg in $enableval; do
-    if test "X$pkg" = "X$p"; then
-      enable_fast_install=yes
-    fi
-  done
-  IFS="$ac_save_ifs"
-  ;;
-esac
-else
-  enable_fast_install=yes
-fi
-
-# Check whether --with-gnu-ld or --without-gnu-ld was given.
-if test "${with_gnu_ld+set}" = set; then
-  withval="$with_gnu_ld"
-  test "$withval" = no || with_gnu_ld=yes
-else
-  with_gnu_ld=no
-fi
-
-ac_prog=ld
-if test "$GCC" = yes; then
-  # Check if gcc -print-prog-name=ld gives a path.
-  echo $ac_n "checking for ld used by GCC""... $ac_c" 1>&6
-echo "configure:1365: checking for ld used by GCC" >&5
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [\\/]* | [A-Za-z]:[\\/]*)
-      re_direlt='/[^/][^/]*/\.\./'
-      # Canonicalize the path of ld
-      ac_prog=`echo $ac_prog| sed 's%\\\\%/%g'`
-      while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=`echo $ac_prog| sed "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD="$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=ld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=unknown
-    ;;
-  esac
-elif test "$with_gnu_ld" = yes; then
-  echo $ac_n "checking for GNU ld""... $ac_c" 1>&6
-echo "configure:1395: checking for GNU ld" >&5
-else
-  echo $ac_n "checking for non-GNU ld""... $ac_c" 1>&6
-echo "configure:1398: checking for non-GNU ld" >&5
-fi
-if eval "test \"`echo '$''{'lt_cv_path_LD'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -z "$LD"; then
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}${PATH_SEPARATOR-:}"
-  for ac_dir in $PATH; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some GNU ld's only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      if "$lt_cv_path_LD" -v 2>&1 < /dev/null | egrep '(GNU|with BFD)' > /dev/null; then
-	test "$with_gnu_ld" != no && break
-      else
-	test "$with_gnu_ld" != yes && break
-      fi
-    fi
-  done
-  IFS="$ac_save_ifs"
-else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
-fi
-fi
-
-LD="$lt_cv_path_LD"
-if test -n "$LD"; then
-  echo "$ac_t""$LD" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-test -z "$LD" && { echo "configure: error: no acceptable ld found in \$PATH" 1>&2; exit 1; }
-echo $ac_n "checking if the linker ($LD) is GNU ld""... $ac_c" 1>&6
-echo "configure:1433: checking if the linker ($LD) is GNU ld" >&5
-if eval "test \"`echo '$''{'lt_cv_prog_gnu_ld'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  # I'd rather use --version here, but apparently some GNU ld's only accept -v.
-if $LD -v 2>&1 &5; then
-  lt_cv_prog_gnu_ld=yes
-else
-  lt_cv_prog_gnu_ld=no
-fi
-fi
-
-echo "$ac_t""$lt_cv_prog_gnu_ld" 1>&6
-with_gnu_ld=$lt_cv_prog_gnu_ld
-
-
-echo $ac_n "checking for $LD option to reload object files""... $ac_c" 1>&6
-echo "configure:1450: checking for $LD option to reload object files" >&5
-if eval "test \"`echo '$''{'lt_cv_ld_reload_flag'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  lt_cv_ld_reload_flag='-r'
-fi
-
-echo "$ac_t""$lt_cv_ld_reload_flag" 1>&6
-reload_flag=$lt_cv_ld_reload_flag
-test -n "$reload_flag" && reload_flag=" $reload_flag"
-
-echo $ac_n "checking for BSD-compatible nm""... $ac_c" 1>&6
-echo "configure:1462: checking for BSD-compatible nm" >&5
-if eval "test \"`echo '$''{'lt_cv_path_NM'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM="$NM"
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}${PATH_SEPARATOR-:}"
-  for ac_dir in $PATH /usr/ccs/bin /usr/ucb /bin; do
-    test -z "$ac_dir" && ac_dir=.
-    tmp_nm=$ac_dir/${ac_tool_prefix}nm
-    if test -f $tmp_nm || test -f $tmp_nm$ac_exeext ; then
-      # Check to see if the nm accepts a BSD-compat flag.
-      # Adding the `sed 1q' prevents false positives on HP-UX, which says:
-      #   nm: unknown option "B" ignored
-      # Tru64's nm complains that /dev/null is an invalid object file
-      if ($tmp_nm -B /dev/null 2>&1 | sed '1q'; exit 0) | egrep '(/dev/null|Invalid file or object type)' >/dev/null; then
-	lt_cv_path_NM="$tmp_nm -B"
-	break
-      elif ($tmp_nm -p /dev/null 2>&1 | sed '1q'; exit 0) | egrep /dev/null >/dev/null; then
-	lt_cv_path_NM="$tmp_nm -p"
-	break
-      else
-	lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	continue # so that we can try to find one that supports BSD flags
-      fi
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
-fi
-fi
-
-NM="$lt_cv_path_NM"
-echo "$ac_t""$NM" 1>&6
-
-echo $ac_n "checking how to recognise dependant libraries""... $ac_c" 1>&6
-echo "configure:1500: checking how to recognise dependant libraries" >&5
-if eval "test \"`echo '$''{'lt_cv_deplibs_check_method'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  lt_cv_file_magic_cmd='$MAGIC_CMD'
-lt_cv_file_magic_test_file=
-lt_cv_deplibs_check_method='unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [regex]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given egrep regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-beos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-bsdi4*)
-  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  ;;
-
-cygwin* | mingw* |pw32*)
-  lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
-  lt_cv_file_magic_cmd='$OBJDUMP -f'
-  ;;
-
-darwin* | rhapsody*)
-  # this will be overwritten by pass_all, but leave it in just in case
-  lt_cv_deplibs_check_method='file_magic Mach-O dynamically linked shared library'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  case "$host_os" in
-  rhapsody* | darwin1.012)
-    lt_cv_file_magic_test_file='/System/Library/Frameworks/System.framework/System'
-    ;;
-  *) # Darwin 1.3 on
-    lt_cv_file_magic_test_file='/usr/lib/libSystem.dylib'
-    ;;
-  esac
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-freebsd* )
-  if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD)/i[3-9]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=/usr/bin/file
-      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=pass_all
-  fi
-  ;;
-
-gnu*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-hpux10.20*|hpux11*)
-  case $host_cpu in
-  hppa*)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9].[0-9]) shared library'
-    lt_cv_file_magic_cmd=/usr/bin/file
-    lt_cv_file_magic_test_file=/usr/lib/libc.sl
-    ;;
-  ia64*)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
-    lt_cv_file_magic_cmd=/usr/bin/file
-    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
-    ;;
-  esac
-  ;;
-
-irix5* | irix6*)
-  case $host_os in
-  irix5*)
-    # this will be overridden with pass_all, but let us keep it just in case
-    lt_cv_deplibs_check_method="file_magic ELF 32-bit MSB dynamic lib MIPS - version 1"
-    ;;
-  *)
-    case $LD in
-    *-32|*"-32 ") libmagic=32-bit;;
-    *-n32|*"-n32 ") libmagic=N32;;
-    *-64|*"-64 ") libmagic=64-bit;;
-    *) libmagic=never-match;;
-    esac
-    # this will be overridden with pass_all, but let us keep it just in case
-    lt_cv_deplibs_check_method="file_magic ELF ${libmagic} MSB mips-[1234] dynamic lib MIPS - version 1"
-    ;;
-  esac
-  lt_cv_file_magic_test_file=`echo /lib${libsuff}/libc.so*`
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-# This must be Linux ELF.
-linux-gnu*)
-  case $host_cpu in
-  alpha* | mips* | hppa* | i*86 | powerpc* | sparc* | ia64* | sh* )
-    lt_cv_deplibs_check_method=pass_all ;;
-  *)
-    # glibc up to 2.1.1 does not perform some relocations on ARM
-    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;;
-  esac
-  lt_cv_file_magic_test_file=`echo /lib/libc.so* /lib/libc-*.so`
-  ;;
-
-netbsd*)
-  if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method='match_pattern /lib[^/\.]+\.so\.[0-9]+\.[0-9]+$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[^/\.]+\.so$'
-  fi
-  ;;
-
-newsos6)
-  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=/usr/bin/file
-  lt_cv_file_magic_test_file=/usr/lib/libnls.so
-  ;;
-
-osf3* | osf4* | osf5*)
-  # this will be overridden with pass_all, but let us keep it just in case
-  lt_cv_deplibs_check_method='file_magic COFF format alpha shared library'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sco3.2v5*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-solaris*)
-  lt_cv_deplibs_check_method=pass_all
-  lt_cv_file_magic_test_file=/lib/libc.so
-  ;;
-
-sysv5uw[78]* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-  case $host_vendor in
-  ncr)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  motorola)
-    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
-    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
-    ;;
-  esac
-  ;;
-esac
-
-fi
-
-echo "$ac_t""$lt_cv_deplibs_check_method" 1>&6
-file_magic_cmd=$lt_cv_file_magic_cmd
-deplibs_check_method=$lt_cv_deplibs_check_method
-
-echo $ac_n "checking for object suffix""... $ac_c" 1>&6
-echo "configure:1675: checking for object suffix" >&5
-if eval "test \"`echo '$''{'ac_cv_objext'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  rm -f conftest*
-echo 'int i = 1;' > conftest.$ac_ext
-if { (eval echo configure:1681: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  for ac_file in conftest.*; do
-    case $ac_file in
-    *.c) ;;
-    *) ac_cv_objext=`echo $ac_file | sed -e s/conftest.//` ;;
-    esac
-  done
-else
-  { echo "configure: error: installation or configuration problem; compiler does not work" 1>&2; exit 1; }
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_objext" 1>&6
-OBJEXT=$ac_cv_objext
-ac_objext=$ac_cv_objext
-
-# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers!
-
-# Only perform the check for file, if the check method requires it
-case $deplibs_check_method in
-file_magic*)
-  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
-    echo $ac_n "checking for ${ac_tool_prefix}file""... $ac_c" 1>&6
-echo "configure:1705: checking for ${ac_tool_prefix}file" >&5
-if eval "test \"`echo '$''{'lt_cv_path_MAGIC_CMD'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  case $MAGIC_CMD in
-  /*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-  ?:/*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a dos path.
-  ;;
-  *)
-  ac_save_MAGIC_CMD="$MAGIC_CMD"
-  IFS="${IFS=   }"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="/usr/bin:$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/${ac_tool_prefix}file; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`"
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    egrep "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  MAGIC_CMD="$ac_save_MAGIC_CMD"
-  ;;
-esac
-fi
-
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  echo "$ac_t""$MAGIC_CMD" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-if test -z "$lt_cv_path_MAGIC_CMD"; then
-  if test -n "$ac_tool_prefix"; then
-    echo $ac_n "checking for file""... $ac_c" 1>&6
-echo "configure:1767: checking for file" >&5
-if eval "test \"`echo '$''{'lt_cv_path_MAGIC_CMD'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  case $MAGIC_CMD in
-  /*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-  ?:/*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a dos path.
-  ;;
-  *)
-  ac_save_MAGIC_CMD="$MAGIC_CMD"
-  IFS="${IFS=   }"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="/usr/bin:$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/file; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/file"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`"
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    egrep "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  MAGIC_CMD="$ac_save_MAGIC_CMD"
-  ;;
-esac
-fi
-
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  echo "$ac_t""$MAGIC_CMD" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-  else
-    MAGIC_CMD=:
-  fi
-fi
-
-  fi
-  ;;
-esac
-
-# Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1838: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-if test -z "$ac_cv_prog_RANLIB"; then
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1870: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_RANLIB="ranlib"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-else
-  RANLIB=":"
-fi
-fi
-
-# Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
-set dummy ${ac_tool_prefix}strip; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1905: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_STRIP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_STRIP="${ac_tool_prefix}strip"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-STRIP="$ac_cv_prog_STRIP"
-if test -n "$STRIP"; then
-  echo "$ac_t""$STRIP" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-if test -z "$ac_cv_prog_STRIP"; then
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "strip", so it can be a program name with args.
-set dummy strip; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:1937: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_STRIP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_STRIP="strip"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_STRIP" && ac_cv_prog_STRIP=":"
-fi
-fi
-STRIP="$ac_cv_prog_STRIP"
-if test -n "$STRIP"; then
-  echo "$ac_t""$STRIP" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-else
-  STRIP=":"
-fi
-fi
-
-
-# Check for any special flags to pass to ltconfig.
-libtool_flags="--cache-file=$cache_file"
-test "$enable_shared" = no && libtool_flags="$libtool_flags --disable-shared"
-test "$enable_static" = no && libtool_flags="$libtool_flags --disable-static"
-test "$enable_fast_install" = no && libtool_flags="$libtool_flags --disable-fast-install"
-test "$GCC" = yes && libtool_flags="$libtool_flags --with-gcc"
-test "$lt_cv_prog_gnu_ld" = yes && libtool_flags="$libtool_flags --with-gnu-ld"
-
-
-# Check whether --enable-libtool-lock or --disable-libtool-lock was given.
-if test "${enable_libtool_lock+set}" = set; then
-  enableval="$enable_libtool_lock"
-  :
-fi
-
-test "x$enable_libtool_lock" = xno && libtool_flags="$libtool_flags --disable-lock"
-test x"$silent" = xyes && libtool_flags="$libtool_flags --silent"
-
-# Check whether --with-pic or --without-pic was given.
-if test "${with_pic+set}" = set; then
-  withval="$with_pic"
-  pic_mode="$withval"
-else
-  pic_mode=default
-fi
-
-test x"$pic_mode" = xyes && libtool_flags="$libtool_flags --prefer-pic"
-test x"$pic_mode" = xno && libtool_flags="$libtool_flags --prefer-non-pic"
-
-# Some flags need to be propagated to the compiler or linker for good
-# libtool support.
-case $host in
-*-*-irix6*)
-  # Find out which ABI we are using.
-  echo '#line 2004 "configure"' > conftest.$ac_ext
-  if { (eval echo configure:2005: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-   if test "$lt_cv_prog_gnu_ld" = yes; then
-    case `/usr/bin/file conftest.$ac_objext` in
-    *32-bit*)
-      LD="${LD-ld} -melf32bsmip"
-      ;;
-    *N32*)
-      LD="${LD-ld} -melf32bmipn32"
-      ;;
-    *64-bit*)
-      LD="${LD-ld} -melf64bmip"
-      ;;
-    esac
-   else
-    case `/usr/bin/file conftest.$ac_objext` in
-    *32-bit*)
-      LD="${LD-ld} -32"
-      ;;
-    *N32*)
-      LD="${LD-ld} -n32"
-      ;;
-    *64-bit*)
-      LD="${LD-ld} -64"
-      ;;
-    esac
-   fi
-  fi
-  rm -rf conftest*
-  ;;
-
-ia64-*-hpux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if { (eval echo configure:2038: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-    case "`/usr/bin/file conftest.o`" in
-    *ELF-32*)
-      HPUX_IA64_MODE="32"
-      ;;
-    *ELF-64*)
-      HPUX_IA64_MODE="64"
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if { (eval echo configure:2054: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-    case "`/usr/bin/file conftest.o`" in
-    *32-bit*)
-      case $host in
-        x86_64-*linux*)
-          LD="${LD-ld} -m elf_i386"
-          ;;
-        ppc64-*linux*|powerpc64-*linux*)
-          LD="${LD-ld} -m elf32ppclinux"
-          ;;
-        s390x-*linux*)
-          LD="${LD-ld} -m elf_s390"
-          ;;
-        sparc64-*linux*)
-          LD="${LD-ld} -m elf32_sparc"
-          ;;
-      esac
-      ;;
-    *64-bit*)
-      case $host in
-        x86_64-*linux*)
-          LD="${LD-ld} -m elf_x86_64"
-          ;;
-        ppc*-*linux*|powerpc*-*linux*)
-          LD="${LD-ld} -m elf64ppc"
-          ;;
-        s390*-*linux*)
-          LD="${LD-ld} -m elf64_s390"
-          ;;
-        sparc*-*linux*)
-          LD="${LD-ld} -m elf64_sparc"
-          ;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-*-*-sco3.2v5*)
-  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS -belf"
-  echo $ac_n "checking whether the C compiler needs -belf""... $ac_c" 1>&6
-echo "configure:2098: checking whether the C compiler needs -belf" >&5
-if eval "test \"`echo '$''{'lt_cv_cc_needs_belf'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  
-     ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-     cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  lt_cv_cc_needs_belf=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  lt_cv_cc_needs_belf=no
-fi
-rm -f conftest*
-     ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-fi
-
-echo "$ac_t""$lt_cv_cc_needs_belf" 1>&6
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
-    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
-  fi
-  ;;
-
-
-esac
-
-
-# Save cache, so that ltconfig can load it
-cat > confcache <<\EOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs.  It is not useful on other systems.
-# If it contains results you don't want to keep, you may remove or edit it.
-#
-# By default, configure uses ./config.cache as the cache file,
-# creating it if it does not exist already.  You can give configure
-# the --cache-file=FILE option to use a different cache file; that is
-# what configure does when it calls configure scripts in
-# subdirectories, so they share the cache.
-# Giving --cache-file=/dev/null disables caching, for debugging configure.
-# config.status only pays attention to the cache file if you give it the
-# --recheck option to rerun configure.
-#
-EOF
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(set) 2>&1 |
-  case `(ac_space=' '; set | grep ac_space) 2>&1` in
-  *ac_space=\ *)
-    # `set' does not quote correctly, so add quotes (double-quote substitution
-    # turns \\\\ into \\, and sed turns \\ into \).
-    sed -n \
-      -e "s/'/'\\\\''/g" \
-      -e "s/^\\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\\)=\\(.*\\)/\\1=\${\\1='\\2'}/p"
-    ;;
-  *)
-    # `set' quotes correctly as required by POSIX, so do not add quotes.
-    sed -n -e 's/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=${\1=\2}/p'
-    ;;
-  esac >> confcache
-if cmp -s $cache_file confcache; then
-  :
-else
-  if test -w $cache_file; then
-    echo "updating cache $cache_file"
-    cat confcache > $cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
-
-
-# Actually configure libtool.  ac_aux_dir is where install-sh is found.
-AR="$AR" LTCC="$CC" CC="$CC" CFLAGS="$CFLAGS" CPPFLAGS="$CPPFLAGS" \
-MAGIC_CMD="$MAGIC_CMD" LD="$LD" LDFLAGS="$LDFLAGS" LIBS="$LIBS" \
-LN_S="$LN_S" NM="$NM" RANLIB="$RANLIB" STRIP="$STRIP" \
-AS="$AS" DLLTOOL="$DLLTOOL" OBJDUMP="$OBJDUMP" \
-objext="$OBJEXT" exeext="$EXEEXT" reload_flag="$reload_flag" \
-deplibs_check_method="$deplibs_check_method" file_magic_cmd="$file_magic_cmd" \
-${CONFIG_SHELL-/bin/sh} $ac_aux_dir/ltconfig --no-reexec \
-$libtool_flags --no-verify --build="$build" $ac_aux_dir/ltmain.sh $host \
-|| { echo "configure: error: libtool configure failed" 1>&2; exit 1; }
-
-# Reload cache, that may have been modified by ltconfig
-if test -r "$cache_file"; then
-  echo "loading cache $cache_file"
-  . $cache_file
-else
-  echo "creating cache $cache_file"
-  > $cache_file
-fi
-
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ac_aux_dir/ltconfig $ac_aux_dir/ltmain.sh $ac_aux_dir/ltcf-c.sh"
-
-# Always use our own libtool.
-LIBTOOL='$(SHELL) $(top_builddir)/libtool'
-
-# Redirect the config.log output again, so that the ltconfig log is not
-# clobbered by the next message.
-exec 5>>./config.log
-
-  
-
-  
-	 
-	 
-
-test "$AR" || AR=ar
-
-if test "$RANLIB"; then :
-  
-else
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:2242: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_RANLIB="ranlib"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-fi
-# Find a good install program.  We prefer a C program (faster),
-# so one script is as good as another.  But avoid the broken or
-# incompatible versions:
-# SysV /etc/install, /usr/sbin/install
-# SunOS /usr/etc/install
-# IRIX /sbin/install
-# AIX /bin/install
-# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
-# AFS /usr/afsws/bin/install, which mishandles nonexistent args
-# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
-# ./install, which can be erroneously created by make from ./install.sh.
-echo $ac_n "checking for a BSD compatible install""... $ac_c" 1>&6
-echo "configure:2282: checking for a BSD compatible install" >&5
-if test -z "$INSTALL"; then
-if eval "test \"`echo '$''{'ac_cv_path_install'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-    IFS="${IFS= 	}"; ac_save_IFS="$IFS"; IFS=":"
-  for ac_dir in $PATH; do
-    # Account for people who put trailing slashes in PATH elements.
-    case "$ac_dir/" in
-    /|./|.//|/etc/*|/usr/sbin/*|/usr/etc/*|/sbin/*|/usr/afsws/bin/*|/usr/ucb/*) ;;
-    *)
-      # OSF1 and SCO ODT 3.0 have their own names for install.
-      # Don't use installbsd from OSF since it installs stuff as root
-      # by default.
-      for ac_prog in ginstall scoinst install; do
-        if test -f $ac_dir/$ac_prog; then
-	  if test $ac_prog = install &&
-            grep dspmsg $ac_dir/$ac_prog >/dev/null 2>&1; then
-	    # AIX install.  It has an incompatible calling convention.
-	    :
-	  else
-	    ac_cv_path_install="$ac_dir/$ac_prog -c"
-	    break 2
-	  fi
-	fi
-      done
-      ;;
-    esac
-  done
-  IFS="$ac_save_IFS"
-
-fi
-  if test "${ac_cv_path_install+set}" = set; then
-    INSTALL="$ac_cv_path_install"
-  else
-    # As a last resort, use the slow shell script.  We don't cache a
-    # path for INSTALL within a source directory, because that will
-    # break other packages using the cache if that directory is
-    # removed, or if the path is relative.
-    INSTALL="$ac_install_sh"
-  fi
-fi
-echo "$ac_t""$INSTALL" 1>&6
-
-# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
-# It thinks the first close brace ends the variable substitution.
-test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
-
-test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL_PROGRAM}'
-
-test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:2335: checking whether ${MAKE-make} sets \${MAKE}" >&5
-set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_prog_make_${ac_make}_set'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftestmake <<\EOF
-all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
-# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
-eval `${MAKE-make} -f conftestmake 2>/dev/null | grep temp=`
-if test -n "$ac_maketemp"; then
-  eval ac_cv_prog_make_${ac_make}_set=yes
-else
-  eval ac_cv_prog_make_${ac_make}_set=no
-fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  SET_MAKE=
-else
-  echo "$ac_t""no" 1>&6
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-
-# Sanity check for the cross-compilation case:
-echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:2364: checking how to run the C preprocessor" >&5
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-    # This must be in double quotes, not single quotes, because CPP may get
-  # substituted into the Makefile and "${CC-cc}" will confuse make.
-  CPP="${CC-cc} -E"
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp.
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2385: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -E -traditional-cpp"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2402: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -nologo -E"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2419: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP=/lib/cpp
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-  ac_cv_prog_CPP="$CPP"
-fi
-  CPP="$ac_cv_prog_CPP"
-else
-  ac_cv_prog_CPP="$CPP"
-fi
-echo "$ac_t""$CPP" 1>&6
-
-ac_safe=`echo "stdio.h" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for stdio.h""... $ac_c" 1>&6
-echo "configure:2445: checking for stdio.h" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:2455: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=yes"
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  :
-else
-  echo "$ac_t""no" 1>&6
-{ echo "configure: error: Can't find stdio.h.
-You must have a usable C system for the target already installed, at least
-including headers and, preferably, the library, before you can configure
-the G77 runtime system.  If necessary, install gcc now with \`LANGUAGES=c',
-then the target library, then build with \`LANGUAGES=f77'." 1>&2; exit 1; }
-fi
-
-
-echo $ac_n "checking for built-in g77 integer types""... $ac_c" 1>&6
-echo "configure:2483: checking for built-in g77 integer types" >&5
-if eval "test \"`echo '$''{'libf2c_cv_has_g77_builtin_types'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  libf2c_cv_has_g77_builtin_types=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  libf2c_cv_has_g77_builtin_types=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$libf2c_cv_has_g77_builtin_types" 1>&6
-if test $libf2c_cv_has_g77_builtin_types = no; then
-  { echo "configure: error: gcc doesn't define all of the built in types __g77_integer,
-__g77_uinteger, __g77_longint, and __g77_ulongint.  You may not be using
-a new enough version of gcc, or your target may not have type sizes which
-accommodate those types." 1>&2; exit 1; }
-fi
-
-# avoid confusion in case the `makefile's from the f2c distribution have
-# got put here
-test -f libF77/makefile && mv libF77/makefile  libF77/makefile.ori
-test -f libI77/makefile && mv libI77/makefile  libI77/makefile.ori
-test -f libU77/makefile && mv libU77/makefile  libU77/makefile.ori
-
-subdirs="libU77 libI77 libF77"
-
-# Do Makefile first since g2c.h depends on it and shouldn't get an
-# earlier timestamp.  Of course, it does when the multilib gunk below
-# edits Makefile, sigh; see additional touch below.
-trap '' 1 2 15
-cat > confcache <<\EOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs.  It is not useful on other systems.
-# If it contains results you don't want to keep, you may remove or edit it.
-#
-# By default, configure uses ./config.cache as the cache file,
-# creating it if it does not exist already.  You can give configure
-# the --cache-file=FILE option to use a different cache file; that is
-# what configure does when it calls configure scripts in
-# subdirectories, so they share the cache.
-# Giving --cache-file=/dev/null disables caching, for debugging configure.
-# config.status only pays attention to the cache file if you give it the
-# --recheck option to rerun configure.
-#
-EOF
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(set) 2>&1 |
-  case `(ac_space=' '; set | grep ac_space) 2>&1` in
-  *ac_space=\ *)
-    # `set' does not quote correctly, so add quotes (double-quote substitution
-    # turns \\\\ into \\, and sed turns \\ into \).
-    sed -n \
-      -e "s/'/'\\\\''/g" \
-      -e "s/^\\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\\)=\\(.*\\)/\\1=\${\\1='\\2'}/p"
-    ;;
-  *)
-    # `set' quotes correctly as required by POSIX, so do not add quotes.
-    sed -n -e 's/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=${\1=\2}/p'
-    ;;
-  esac >> confcache
-if cmp -s $cache_file confcache; then
-  :
-else
-  if test -w $cache_file; then
-    echo "updating cache $cache_file"
-    cat confcache > $cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Any assignment to VPATH causes Sun make to only execute
-# the first set of double-colon rules, so remove it if not needed.
-# If there is a colon in the path, we need to keep it.
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[ 	]*VPATH[ 	]*=[^:]*$/d'
-fi
-
-trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15
-
-# Transform confdefs.h into DEFS.
-# Protect against shell expansion while executing Makefile rules.
-# Protect against Makefile macro expansion.
-cat > conftest.defs <<\EOF
-s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%-D\1=\2%g
-s%[ 	`~#$^&*(){}\\|;'"<>?]%\\&%g
-s%\[%\\&%g
-s%\]%\\&%g
-s%\$%$$%g
-EOF
-DEFS=`sed -f conftest.defs confdefs.h | tr '\012' ' '`
-rm -f conftest.defs
-
-
-# Without the "./", some shells look in PATH for config.status.
-: ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS </dev/null | sed 1q`:
-#
-# $0 $ac_configure_args
-#
-# Compiler output produced by configure, useful for debugging
-# configure, is in ./config.log if it exists.
-
-ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
-for ac_option
-do
-  case "\$ac_option" in
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion"
-    exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;;
-  -version | --version | --versio | --versi | --vers | --ver | --ve | --v)
-    echo "$CONFIG_STATUS generated by autoconf version 2.13"
-    exit 0 ;;
-  -help | --help | --hel | --he | --h)
-    echo "\$ac_cs_usage"; exit 0 ;;
-  *) echo "\$ac_cs_usage"; exit 1 ;;
-  esac
-done
-
-ac_given_srcdir=$srcdir
-ac_given_INSTALL="$INSTALL"
-
-trap 'rm -fr `echo "Makefile g2c.h:g2c.hin" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15
-EOF
-cat >> $CONFIG_STATUS < conftest.subs <<\\CEOF
-$ac_vpsub
-$extrasub
-s%@SHELL@%$SHELL%g
-s%@CFLAGS@%$CFLAGS%g
-s%@CPPFLAGS@%$CPPFLAGS%g
-s%@CXXFLAGS@%$CXXFLAGS%g
-s%@FFLAGS@%$FFLAGS%g
-s%@DEFS@%$DEFS%g
-s%@LDFLAGS@%$LDFLAGS%g
-s%@LIBS@%$LIBS%g
-s%@exec_prefix@%$exec_prefix%g
-s%@prefix@%$prefix%g
-s%@program_transform_name@%$program_transform_name%g
-s%@bindir@%$bindir%g
-s%@sbindir@%$sbindir%g
-s%@libexecdir@%$libexecdir%g
-s%@datadir@%$datadir%g
-s%@sysconfdir@%$sysconfdir%g
-s%@sharedstatedir@%$sharedstatedir%g
-s%@localstatedir@%$localstatedir%g
-s%@libdir@%$libdir%g
-s%@includedir@%$includedir%g
-s%@oldincludedir@%$oldincludedir%g
-s%@infodir@%$infodir%g
-s%@mandir@%$mandir%g
-s%@toplevel_srcdir@%$toplevel_srcdir%g
-s%@host@%$host%g
-s%@host_alias@%$host_alias%g
-s%@host_cpu@%$host_cpu%g
-s%@host_vendor@%$host_vendor%g
-s%@host_os@%$host_os%g
-s%@target@%$target%g
-s%@target_alias@%$target_alias%g
-s%@target_cpu@%$target_cpu%g
-s%@target_vendor@%$target_vendor%g
-s%@target_os@%$target_os%g
-s%@build@%$build%g
-s%@build_alias@%$build_alias%g
-s%@build_cpu@%$build_cpu%g
-s%@build_vendor@%$build_vendor%g
-s%@build_os@%$build_os%g
-s%@glibcpp_builddir@%$glibcpp_builddir%g
-s%@glibcpp_srcdir@%$glibcpp_srcdir%g
-s%@LN_S@%$LN_S%g
-s%@CC@%$CC%g
-s%@AS@%$AS%g
-s%@AR@%$AR%g
-s%@RANLIB@%$RANLIB%g
-s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g
-s%@INSTALL_SCRIPT@%$INSTALL_SCRIPT%g
-s%@INSTALL_DATA@%$INSTALL_DATA%g
-s%@EXEEXT@%$EXEEXT%g
-s%@gcc_version@%$gcc_version%g
-s%@gcc_version_trigger@%$gcc_version_trigger%g
-s%@glibcpp_prefixdir@%$glibcpp_prefixdir%g
-s%@glibcpp_toolexecdir@%$glibcpp_toolexecdir%g
-s%@glibcpp_toolexeclibdir@%$glibcpp_toolexeclibdir%g
-s%@OBJEXT@%$OBJEXT%g
-s%@STRIP@%$STRIP%g
-s%@LIBTOOL@%$LIBTOOL%g
-s%@SET_MAKE@%$SET_MAKE%g
-s%@CPP@%$CPP%g
-s%@subdirs@%$subdirs%g
-
-CEOF
-EOF
-
-cat >> $CONFIG_STATUS <<\EOF
-
-# Split the substitutions into bite-sized pieces for seds with
-# small command number limits, like on Digital OSF/1 and HP-UX.
-ac_max_sed_cmds=90 # Maximum number of lines to put in a sed script.
-ac_file=1 # Number of current file.
-ac_beg=1 # First line for current file.
-ac_end=$ac_max_sed_cmds # Line after last line for current file.
-ac_more_lines=:
-ac_sed_cmds=""
-while $ac_more_lines; do
-  if test $ac_beg -gt 1; then
-    sed "1,${ac_beg}d; ${ac_end}q" conftest.subs > conftest.s$ac_file
-  else
-    sed "${ac_end}q" conftest.subs > conftest.s$ac_file
-  fi
-  if test ! -s conftest.s$ac_file; then
-    ac_more_lines=false
-    rm -f conftest.s$ac_file
-  else
-    if test -z "$ac_sed_cmds"; then
-      ac_sed_cmds="sed -f conftest.s$ac_file"
-    else
-      ac_sed_cmds="$ac_sed_cmds | sed -f conftest.s$ac_file"
-    fi
-    ac_file=`expr $ac_file + 1`
-    ac_beg=$ac_end
-    ac_end=`expr $ac_end + $ac_max_sed_cmds`
-  fi
-done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
-fi
-EOF
-
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case "$ac_file" in
-  *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
-       ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
-  *) ac_file_in="${ac_file}.in" ;;
-  esac
-
-  # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
-
-  # Remove last slash and all that follows it.  Not all systems have dirname.
-  ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
-  if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
-    # The file is in a subdirectory.
-    test ! -d "$ac_dir" && mkdir "$ac_dir"
-    ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`"
-    # A "../" for each directory in $ac_dir_suffix.
-    ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'`
-  else
-    ac_dir_suffix= ac_dots=
-  fi
-
-  case "$ac_given_srcdir" in
-  .)  srcdir=.
-      if test -z "$ac_dots"; then top_srcdir=.
-      else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;;
-  /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;;
-  *) # Relative path.
-    srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix"
-    top_srcdir="$ac_dots$ac_given_srcdir" ;;
-  esac
-
-  case "$ac_given_INSTALL" in
-  [/$]*) INSTALL="$ac_given_INSTALL" ;;
-  *) INSTALL="$ac_dots$ac_given_INSTALL" ;;
-  esac
-
-  echo creating "$ac_file"
-  rm -f "$ac_file"
-  configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure."
-  case "$ac_file" in
-  *Makefile*) ac_comsub="1i\\
-# $configure_input" ;;
-  *) ac_comsub= ;;
-  esac
-
-  ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
-  sed -e "$ac_comsub
-s%@configure_input@%$configure_input%g
-s%@srcdir@%$srcdir%g
-s%@top_srcdir@%$top_srcdir%g
-s%@INSTALL@%$INSTALL%g
-" $ac_file_inputs | (eval "$ac_sed_cmds") > $ac_file
-fi; done
-rm -f conftest.s*
-
-EOF
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-test -z "$CONFIG_HEADERS" || echo timestamp > stamp-h
-if test -n "$CONFIG_FILES"; then
-  LD="${ORIGINAL_LD_FOR_MULTILIBS}"
-  if test -n "${with_target_subdir}"; then
-    # FIXME: We shouldn't need to set ac_file
-    ac_file=Makefile
-    . ${toplevel_srcdir}/config-ml.in
-    touch g2c.h   # to keep it more recent than Makefile
-  fi
-fi
-exit 0
-EOF
-chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
-if test "$no_recursion" != yes; then
-
-  # Remove --cache-file and --srcdir arguments so they do not pile up.
-  ac_sub_configure_args=
-  ac_prev=
-  for ac_arg in $ac_configure_args; do
-    if test -n "$ac_prev"; then
-      ac_prev=
-      continue
-    fi
-    case "$ac_arg" in
-    -cache-file | --cache-file | --cache-fil | --cache-fi \
-    | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-      ac_prev=cache_file ;;
-    -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-    | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-      ;;
-    -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-      ac_prev=srcdir ;;
-    -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-      ;;
-    *) ac_sub_configure_args="$ac_sub_configure_args $ac_arg" ;;
-    esac
-  done
-
-  for ac_config_dir in libU77 libI77 libF77; do
-
-    # Do not complain, so a configure script can configure whichever
-    # parts of a large source tree are present.
-    if test ! -d $srcdir/$ac_config_dir; then
-      continue
-    fi
-
-    echo configuring in $ac_config_dir
-
-    case "$srcdir" in
-    .) ;;
-    *)
-      if test -d ./$ac_config_dir || mkdir ./$ac_config_dir; then :;
-      else
-        { echo "configure: error: can not create `pwd`/$ac_config_dir" 1>&2; exit 1; }
-      fi
-      ;;
-    esac
-
-    ac_popdir=`pwd`
-    cd $ac_config_dir
-
-      # A "../" for each directory in /$ac_config_dir.
-      ac_dots=`echo $ac_config_dir|sed -e 's%^\./%%' -e 's%[^/]$%&/%' -e 's%[^/]*/%../%g'`
-
-    case "$srcdir" in
-    .) # No --srcdir option.  We are building in place.
-      ac_sub_srcdir=$srcdir ;;
-    /*) # Absolute path.
-      ac_sub_srcdir=$srcdir/$ac_config_dir ;;
-    *) # Relative path.
-      ac_sub_srcdir=$ac_dots$srcdir/$ac_config_dir ;;
-    esac
-
-    # Check for guested configure; otherwise get Cygnus style configure.
-    if test -f $ac_sub_srcdir/configure; then
-      ac_sub_configure=$ac_sub_srcdir/configure
-    elif test -f $ac_sub_srcdir/configure.in; then
-      ac_sub_configure=$ac_configure
-    else
-      echo "configure: warning: no configuration information is in $ac_config_dir" 1>&2
-      ac_sub_configure=
-    fi
-
-    # The recursion is here.
-    if test -n "$ac_sub_configure"; then
-
-      # Make the cache file name correct relative to the subdirectory.
-      case "$cache_file" in
-      /*) ac_sub_cache_file=$cache_file ;;
-      *) # Relative path.
-        ac_sub_cache_file="$ac_dots$cache_file" ;;
-      esac
-  case "$ac_given_INSTALL" in
-        [/$]*) INSTALL="$ac_given_INSTALL" ;;
-        *) INSTALL="$ac_dots$ac_given_INSTALL" ;;
-        esac
-
-      echo "running ${CONFIG_SHELL-/bin/sh} $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_sub_srcdir"
-      # The eval makes quoting arguments work.
-      if eval ${CONFIG_SHELL-/bin/sh} $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_sub_srcdir
-      then :
-      else
-        { echo "configure: error: $ac_sub_configure failed for $ac_config_dir" 1>&2; exit 1; }
-      fi
-    fi
-
-    cd $ac_popdir
-  done
-fi
-
-
-
diff --git a/contrib/libf2c/configure.in b/contrib/libf2c/configure.in
deleted file mode 100644
index 50016b261df..00000000000
--- a/contrib/libf2c/configure.in
+++ /dev/null
@@ -1,121 +0,0 @@
-# Process this file with autoconf to produce a configure script.
-#   Copyright (C) 1995, 1997, 1998, 1999, 2002, 2003
-#    Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of GNU Fortran.
-#
-#GNU Fortran is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-AC_PREREQ(2.13)
-AC_INIT(libF77/Version.c)
-
-# This works around the fact that libtool configuration may change LD
-# for this particular configuration, but some shells, instead of
-# keeping the changes in LD private, export them just because LD is
-# exported.
-ORIGINAL_LD_FOR_MULTILIBS=$LD
-
-GLIBCPP_TOPREL_CONFIGURE
-
-AC_CANONICAL_SYSTEM
-target_alias=${target_alias-$target}
-AC_SUBST(target_alias)
-
-GLIBCPP_CONFIGURE(.)
-GLIBCPP_EXPORT_INSTALL_INFO
-
-dnl Checks for programs.
-
-AM_PROG_LIBTOOL
-
-dnl These should be inherited in the recursive make, but ensure they are
-dnl defined:
-test "$AR" || AR=ar
-AC_SUBST(AR)
-if test "$RANLIB"; then :
-  AC_SUBST(RANLIB)
-else
-  AC_PROG_RANLIB
-fi
-AC_PROG_INSTALL
-AC_PROG_MAKE_SET
-
-dnl Checks for header files.
-# Sanity check for the cross-compilation case:
-AC_CHECK_HEADER(stdio.h,:,
-  [AC_MSG_ERROR([Can't find stdio.h.
-You must have a usable C system for the target already installed, at least
-including headers and, preferably, the library, before you can configure
-the G77 runtime system.  If necessary, install gcc now with \`LANGUAGES=c',
-then the target library, then build with \`LANGUAGES=f77'.])])
-
-dnl Checks for g77 integer types built into gcc's C front end.
-AC_MSG_CHECKING(for built-in g77 integer types)
-AC_CACHE_VAL(libf2c_cv_has_g77_builtin_types,
-[AC_TRY_COMPILE(,
-  [__g77_integer g77i;
-__g77_uinteger g77ui;
-__g77_longint g77l;
-__g77_ulongint g77ul;],
-  libf2c_cv_has_g77_builtin_types=yes,
-  libf2c_cv_has_g77_builtin_types=no)])
-AC_MSG_RESULT($libf2c_cv_has_g77_builtin_types)
-if test $libf2c_cv_has_g77_builtin_types = no; then
-  AC_MSG_ERROR([gcc doesn't define all of the built in types __g77_integer,
-__g77_uinteger, __g77_longint, and __g77_ulongint.  You may not be using
-a new enough version of gcc, or your target may not have type sizes which
-accommodate those types.])
-fi
-
-# avoid confusion in case the `makefile's from the f2c distribution have
-# got put here
-test -f libF77/makefile && mv libF77/makefile  libF77/makefile.ori
-test -f libI77/makefile && mv libI77/makefile  libI77/makefile.ori
-test -f libU77/makefile && mv libU77/makefile  libU77/makefile.ori
-
-AC_CONFIG_SUBDIRS(libU77 libI77 libF77)
-# Do Makefile first since g2c.h depends on it and shouldn't get an
-# earlier timestamp.  Of course, it does when the multilib gunk below
-# edits Makefile, sigh; see additional touch below.
-AC_OUTPUT(Makefile g2c.h:g2c.hin,
- [test -z "$CONFIG_HEADERS" || echo timestamp > stamp-h
-if test -n "$CONFIG_FILES"; then
-  LD="${ORIGINAL_LD_FOR_MULTILIBS}"
-  if test -n "${with_target_subdir}"; then
-    # FIXME: We shouldn't need to set ac_file
-    ac_file=Makefile
-    . ${toplevel_srcdir}/config-ml.in
-    touch g2c.h   # to keep it more recent than Makefile
-  fi
-fi],
-srcdir=${srcdir}
-host=${host}
-target=${target}
-with_target_subdir=${with_target_subdir}
-with_multisubdir=${with_multisubdir}
-ac_configure_args="--enable-multilib ${ac_configure_args}"
-toplevel_srcdir=${toplevel_srcdir}
-CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
-ORIGINAL_LD_FOR_MULTILIBS="${ORIGINAL_LD_FOR_MULTILIBS}"
-)
-
-
-dnl Local Variables:
-dnl comment-start: "dnl "
-dnl comment-end: ""
-dnl comment-start-skip: "\\bdnl\\b\\s *"
-dnl End:
diff --git a/contrib/libf2c/disclaimer.netlib b/contrib/libf2c/disclaimer.netlib
deleted file mode 100644
index a11108f83db..00000000000
--- a/contrib/libf2c/disclaimer.netlib
+++ /dev/null
@@ -1,15 +0,0 @@
-f2c is a Fortran to C converter under development since 1990 by
-	David M. Gay (then AT&T Bell Labs, now Bell Labs, Lucent Technologies)
-	Stu Feldman (then at Bellcore, now at IBM)
-	Mark Maimone (Carnegie-Mellon University)
-	Norm Schryer (then AT&T Bell Labs, now AT&T Labs)
-Please send bug reports to dmg@research.bell-labs.com .
-
-AT&T, Bellcore and Lucent disclaim all warranties with regard to this
-software, including all implied warranties of merchantability
-and fitness.  In no event shall AT&T, Bellcore or Lucent be liable for
-any special, indirect or consequential damages or any damages
-whatsoever resulting from loss of use, data or profits, whether
-in an action of contract, negligence or other tortious action,
-arising out of or in connection with the use or performance of
-this software.
diff --git a/contrib/libf2c/f2c.h b/contrib/libf2c/f2c.h
deleted file mode 100644
index 71e53616497..00000000000
--- a/contrib/libf2c/f2c.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/* f2c.h file for GNU Fortran run-time library
-   Copyright (C) 1998 Free Software Foundation, Inc.
-   Contributed by James Craig Burley.
-
-This file is part of GNU Fortran.
-
-GNU Fortran is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Fortran; see the file COPYING.  If not, write to
-the Free Software Foundation, 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-/* This file currently is just a stub through which g77's copy
-   of netlib's libf2c, which g77 builds and installs as libg2c.a
-   (to avoid conflict), #include's g77's version of f2c.h, named
-   g2c.h.  That file is, in turn, produced via g77's library
-   configuration process from g2c.h.in.
-
-   By going through this extra "hoop", it is easy to provide for
-   libg2c-specific configuration and typedefs that aren't appropriate
-   in g2c.h itself (since that is intended to be installed so it can
-   be shared with f2c users), without changing the libf2c (libg2c)
-   routines themselves.  (They continue to #include "f2c.h", just
-   like they do in netlib's version.)  */
-
-#include "g2c.h"
-
-/* For GNU Fortran (g77), we always enable the following behaviors for
-   libf2c, to make things easy on the programmer.  The alternate
-   behaviors have their uses, and g77 might provide them as compiler,
-   rather than library, options, so only a single copy of a shared libf2c
-   need be built for a system.  */
-
-/* This makes unformatted I/O more consistent in relation to other
-   systems.  It is not required by the F77 standard.  */
-
-#define Pad_UDread
-
-/* This makes ERR= and IOSTAT= returns work properly in disk-full
-   situations, making things work more as expected.  It slows things
-   down, so g77 will probably someday choose the original implementation
-   on a case-by-case basis when it can be shown to not be necessary
-   (e.g. no ERR= or IOSTAT=) or when it is given the appropriate
-   compile-time option or, perhaps, source-code directive.
-
-   (No longer defined, since it really slows down NFS access too much.)  */
-
-/* #define ALWAYS_FLUSH */
-
-/* Most Fortran implementations do this, so to make it easier
-   to compare the output of g77-compiled programs to those compiled
-   by most other compilers, tell libf2c to put leading zeros in
-   appropriate places on output.  */
-
-#define WANT_LEAD_0
diff --git a/contrib/libf2c/f2cext.c b/contrib/libf2c/f2cext.c
deleted file mode 100644
index 69d12b6ea64..00000000000
--- a/contrib/libf2c/f2cext.c
+++ /dev/null
@@ -1,582 +0,0 @@
-/* Copyright (C) 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran run-time library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#include 		/* for j0 et al */
-#include 
-typedef void *sig_proc;	/* For now, this will have to do. */
-
-#ifdef Labort
-int abort_ (void) {
-    extern int G77_abort_0 (void);
-    return G77_abort_0 ();
-}
-#endif
-
-#ifdef Lderf
-double derf_ (doublereal *x) {
-    extern double G77_derf_0 (doublereal *x);
-    return G77_derf_0 (x);
-}
-#endif
-
-#ifdef Lderfc
-double derfc_ (doublereal *x) {
-    extern double G77_derfc_0 (doublereal *x);
-    return G77_derfc_0 (x);
-}
-#endif
-
-#ifdef Lef1asc
-int ef1asc_ (ftnint *a, ftnlen *la, ftnint *b, ftnlen *lb) {
-    extern int G77_ef1asc_0 (ftnint *a, ftnlen *la, ftnint *b, ftnlen *lb);
-    return G77_ef1asc_0 (a, la, b, lb);
-}
-#endif
-
-#ifdef Lef1cmc
-integer ef1cmc_ (ftnint *a, ftnlen *la, ftnint *b, ftnlen *lb) {
-    extern integer G77_ef1cmc_0 (ftnint *a, ftnlen *la, ftnint *b, ftnlen *lb);
-    return G77_ef1cmc_0 (a, la, b, lb);
-}
-#endif
-
-#ifdef Lerf
-double erf_ (real *x) {
-    extern double G77_erf_0 (real *x);
-    return G77_erf_0 (x);
-}
-#endif
-
-#ifdef Lerfc
-double erfc_ (real *x) {
-    extern double G77_erfc_0 (real *x);
-    return G77_erfc_0 (x);
-}
-#endif
-
-#ifdef Lexit
-void exit_ (integer *rc) {
-    extern void G77_exit_0 (integer *rc);
-    G77_exit_0 (rc);
-}
-#endif
-
-#ifdef Lgetarg
-void getarg_ (ftnint *n, char *s, ftnlen ls) {
-    extern void G77_getarg_0 (ftnint *n, char *s, ftnlen ls);
-    G77_getarg_0 (n, s, ls);
-}
-#endif
-
-#ifdef Lgetenv
-void getenv_ (char *fname, char *value, ftnlen flen, ftnlen vlen) {
-    extern void G77_getenv_0 (char *fname, char *value, ftnlen flen, ftnlen vlen);
-    G77_getenv_0 (fname, value, flen, vlen);
-}
-#endif
-
-#ifdef Liargc
-ftnint iargc_ (void) {
-    extern ftnint G77_iargc_0 (void);
-    return G77_iargc_0 ();
-}
-#endif
-
-#ifdef Lsignal
-void *signal_ (integer *sigp, sig_proc proc) {
-    extern void *G77_signal_0 (integer *sigp, sig_proc proc);
-    return G77_signal_0 (sigp, proc);
-}
-#endif
-
-#ifdef Lsystem
-integer system_ (char *s, ftnlen n) {
-    extern integer G77_system_0 (char *s, ftnlen n);
-    return G77_system_0 (s, n);
-}
-#endif
-
-#ifdef Lflush
-int flush_ (void) {
-    extern int G77_flush_0 (void);
-    return G77_flush_0 ();
-}
-#endif
-
-#ifdef Lftell
-integer ftell_ (integer *Unit) {
-    extern integer G77_ftell_0 (integer *Unit);
-    return G77_ftell_0 (Unit);
-}
-#endif
-
-#ifdef Lfseek
-integer fseek_ (integer *Unit, integer *offset, integer *xwhence) {
-    extern integer G77_fseek_0 (integer *Unit, integer *offset, integer *xwhence);
-    return G77_fseek_0 (Unit, offset, xwhence);
-}
-#endif
-
-#ifdef Laccess
-integer access_ (const char *name, const char *mode, ftnlen Lname, ftnlen Lmode) {
-    extern integer G77_access_0 (const char *name, const char *mode, ftnlen Lname, ftnlen Lmode);
-    return G77_access_0 (name, mode, Lname, Lmode);
-}
-#endif
-
-#ifdef Lalarm
-integer alarm_ (integer *seconds, sig_proc proc,
-		integer *status __attribute__ ((__unused__))) {
-    extern integer G77_alarm_0 (integer *seconds, sig_proc proc);
-    return G77_alarm_0 (seconds, proc);
-}
-#endif
-
-#ifdef Lbesj0
-double besj0_ (const real *x) {
-    return j0 (*x);
-}
-#endif
-
-#ifdef Lbesj1
-double besj1_ (const real *x) {
-    return j1 (*x);
-}
-#endif
-
-#ifdef Lbesjn
-double besjn_ (const integer *n, real *x) {
-    return jn (*n, *x);
-}
-#endif
-
-#ifdef Lbesy0
-double besy0_ (const real *x) {
-    return y0 (*x);
-}
-#endif
-
-#ifdef Lbesy1
-double besy1_ (const real *x) {
-    return y1 (*x);
-}
-#endif
-
-#ifdef Lbesyn
-double besyn_ (const integer *n, real *x) {
-    return yn (*n, *x);
-}
-#endif
-
-#ifdef Lchdir
-integer chdir_ (const char *name, const ftnlen Lname) {
-    extern integer G77_chdir_0 (const char *name, const ftnlen Lname);
-    return G77_chdir_0 (name, Lname);
-}
-#endif
-
-#ifdef Lchmod
-integer chmod_ (const char *name, const char *mode, const ftnlen Lname, const ftnlen Lmode) {
-    extern integer G77_chmod_0 (const char *name, const char *mode, const ftnlen Lname, const ftnlen Lmode);
-    return G77_chmod_0 (name, mode, Lname, Lmode);
-}
-#endif
-
-#ifdef Lctime
-void ctime_ (char *chtime, const ftnlen Lchtime, longint *xstime) {
-    extern void G77_ctime_0 (char *chtime, const ftnlen Lchtime, longint *xstime);
-    G77_ctime_0 (chtime, Lchtime, xstime);
-}
-#endif
-
-#ifdef Ldate_y2kbuggy
-int date_ (char *buf, ftnlen buf_len) {
-  /* Fail to link, so user sees attempt to invoke non-Y2K-compliant
-     routine.  */
-    extern int G77_date_y2kbuggy_0 (char *buf, ftnlen buf_len);
-    return G77_date_y2kbuggy_0 (buf, buf_len);
-}
-#endif
-
-#ifdef Ldate_y2kbug
-int date_y2kbug__ (char *buf, ftnlen buf_len) {
-  /* If user wants to invoke the non-Y2K-compliant routine via
-     an `EXTERNAL' interface, avoiding the warning via g77's
-     `INTRINSIC' interface, force coding of "y2kbug" string in
-     user's program.  */
-    extern int G77_date_y2kbug_0 (char *buf, ftnlen buf_len);
-    return G77_date_y2kbug_0 (buf, buf_len);
-}
-#endif
-
-#ifdef Ldbesj0
-double dbesj0_ (const double *x) {
-    return j0 (*x);
-}
-#endif
-
-#ifdef Ldbesj1
-double dbesj1_ (const double *x) {
-    return j1 (*x);
-}
-#endif
-
-#ifdef Ldbesjn
-double dbesjn_ (const integer *n, double *x) {
-    return jn (*n, *x);
-}
-#endif
-
-#ifdef Ldbesy0
-double dbesy0_ (const double *x) {
-    return y0 (*x);
-}
-#endif
-
-#ifdef Ldbesy1
-double dbesy1_ (const double *x) {
-    return y1 (*x);
-}
-#endif
-
-#ifdef Ldbesyn
-double dbesyn_ (const integer *n, double *x) {
-    return yn (*n, *x);
-}
-#endif
-
-#ifdef Ldtime
-double dtime_ (real tarray[2]) {
-    extern double G77_dtime_0 (real tarray[2]);
-    return G77_dtime_0 (tarray);
-}
-#endif
-
-#ifdef Letime
-double etime_ (real tarray[2]) {
-    extern double G77_etime_0 (real tarray[2]);
-    return G77_etime_0 (tarray);
-}
-#endif
-
-#ifdef Lfdate
-void fdate_ (char *ret_val, ftnlen ret_val_len) {
-    extern void G77_fdate_0 (char *ret_val, ftnlen ret_val_len);
-    G77_fdate_0 (ret_val, ret_val_len);
-}
-#endif
-
-#ifdef Lfgetc
-integer fgetc_ (const integer *lunit, char *c, ftnlen Lc) {
-    extern integer G77_fgetc_0 (const integer *lunit, char *c, ftnlen Lc);
-    return G77_fgetc_0 (lunit, c, Lc);
-}
-#endif
-
-#ifdef Lfget
-integer fget_ (char *c, const ftnlen Lc) {
-    extern integer G77_fget_0 (char *c, const ftnlen Lc);
-    return G77_fget_0 (c, Lc);
-}
-#endif
-
-#ifdef Lflush1
-int flush1_ (const integer *lunit) {
-    extern int G77_flush1_0 (const integer *lunit);
-    return G77_flush1_0 (lunit);
-}
-#endif
-
-#ifdef Lfnum
-integer fnum_ (integer *lunit) {
-    extern integer G77_fnum_0 (integer *lunit);
-    return G77_fnum_0 (lunit);
-}
-#endif
-
-#ifdef Lfputc
-integer fputc_ (const integer *lunit, const char *c, const ftnlen Lc) {
-    extern integer G77_fputc_0 (const integer *lunit, const char *c, const ftnlen Lc);
-    return G77_fputc_0 (lunit, c, Lc);
-}
-#endif
-
-#ifdef Lfput
-integer fput_ (const char *c, const ftnlen Lc) {
-    extern integer G77_fput_0 (const char *c, const ftnlen Lc);
-    return G77_fput_0 (c, Lc);
-}
-#endif
-
-#ifdef Lfstat
-integer fstat_ (const integer *lunit, integer statb[13]) {
-    extern integer G77_fstat_0 (const integer *lunit, integer statb[13]);
-    return G77_fstat_0 (lunit, statb);
-}
-#endif
-
-#ifdef Lgerror
-int gerror_ (char *str, ftnlen Lstr) {
-    extern int G77_gerror_0 (char *str, ftnlen Lstr);
-    return G77_gerror_0 (str,  Lstr);
-}
-#endif
-
-#ifdef Lgetcwd
-integer getcwd_ (char *str, const ftnlen Lstr) {
-    extern integer G77_getcwd_0 (char *str, const ftnlen Lstr);
-    return G77_getcwd_0 (str, Lstr);
-}
-#endif
-
-#ifdef Lgetgid
-integer getgid_ (void) {
-    extern integer G77_getgid_0 (void);
-    return G77_getgid_0 ();
-}
-#endif
-
-#ifdef Lgetlog
-int getlog_ (char *str, const ftnlen Lstr) {
-    extern int G77_getlog_0 (char *str, const ftnlen Lstr);
-    return G77_getlog_0 (str, Lstr);
-}
-#endif
-
-#ifdef Lgetpid
-integer getpid_ (void) {
-    extern integer G77_getpid_0 (void);
-    return G77_getpid_0 ();
-}
-#endif
-
-#ifdef Lgetuid
-integer getuid_ (void) {
-    extern integer G77_getuid_0 (void);
-    return G77_getuid_0 ();
-}
-#endif
-
-#ifdef Lgmtime
-int gmtime_ (const integer *stime, integer tarray[9]) {
-    extern int G77_gmtime_0 (const integer *stime, integer tarray[9]);
-    return G77_gmtime_0 (stime, tarray);
-}
-#endif
-
-#ifdef Lhostnm
-integer hostnm_ (char *name, ftnlen Lname) {
-    extern integer G77_hostnm_0 (char *name, ftnlen Lname);
-    return G77_hostnm_0 (name, Lname);
-}
-#endif
-
-#ifdef Lidate
-int idate_ (int iarray[3]) {
-    extern int G77_idate_0 (int iarray[3]);
-    return G77_idate_0 (iarray);
-}
-#endif
-
-#ifdef Lierrno
-integer ierrno_ (void) {
-    extern integer G77_ierrno_0 (void);
-    return G77_ierrno_0 ();
-}
-#endif
-
-#ifdef Lirand
-integer irand_ (integer *flag) {
-    extern integer G77_irand_0 (integer *flag);
-    return G77_irand_0 (flag);
-}
-#endif
-
-#ifdef Lisatty
-logical isatty_ (integer *lunit) {
-    extern logical G77_isatty_0 (integer *lunit);
-    return G77_isatty_0 (lunit);
-}
-#endif
-
-#ifdef Litime
-int itime_ (integer tarray[3]) {
-    extern int G77_itime_0 (integer tarray[3]);
-    return G77_itime_0 (tarray);
-}
-#endif
-
-#ifdef Lkill
-integer kill_ (const integer *pid, const integer *signum) {
-    extern integer G77_kill_0 (const integer *pid, const integer *signum);
-    return G77_kill_0 (pid, signum);
-}
-#endif
-
-#ifdef Llink
-integer link_ (const char *path1, const char *path2, const ftnlen Lpath1, const ftnlen Lpath2) {
-    extern integer G77_link_0 (const char *path1, const char *path2, const ftnlen Lpath1, const ftnlen Lpath2);
-    return G77_link_0 (path1, path2, Lpath1, Lpath2);
-}
-#endif
-
-#ifdef Llnblnk
-integer lnblnk_ (char *str, ftnlen str_len) {
-    extern integer G77_lnblnk_0 (char *str, ftnlen str_len);
-    return G77_lnblnk_0 (str, str_len);
-}
-#endif
-
-#ifdef Llstat
-integer lstat_ (const char *name, integer statb[13], const ftnlen Lname) {
-    extern integer G77_lstat_0 (const char *name, integer statb[13], const ftnlen Lname);
-    return G77_lstat_0 (name, statb, Lname);
-}
-#endif
-
-#ifdef Lltime
-int ltime_ (const integer *stime, integer tarray[9]) {
-    extern int G77_ltime_0 (const integer *stime, integer tarray[9]);
-    return G77_ltime_0 (stime, tarray);
-}
-#endif
-
-#ifdef Lmclock
-longint mclock_ (void) {
-    extern longint G77_mclock_0 (void);
-    return G77_mclock_0 ();
-}
-#endif
-
-#ifdef Lperror
-int perror_ (const char *str, const ftnlen Lstr) {
-    extern int G77_perror_0 (const char *str, const ftnlen Lstr);
-    return G77_perror_0 (str, Lstr);
-}
-#endif
-
-#ifdef Lrand
-double rand_ (integer *flag) {
-    extern double G77_rand_0 (integer *flag);
-    return G77_rand_0 (flag);
-}
-#endif
-
-#ifdef Lrename
-integer rename_ (const char *path1, const char *path2, const ftnlen Lpath1, const ftnlen Lpath2) {
-    extern integer G77_rename_0 (const char *path1, const char *path2, const ftnlen Lpath1, const ftnlen Lpath2);
-    return G77_rename_0 (path1, path2, Lpath1, Lpath2);
-}
-#endif
-
-#ifdef Lsecnds
-double secnds_ (real *r) {
-    extern double G77_secnds_0 (real *r);
-    return G77_secnds_0 (r);
-}
-#endif
-
-#ifdef Lsecond
-double second_ () {
-    extern double G77_second_0 ();
-    return G77_second_0 ();
-}
-#endif
-
-#ifdef Lsleep
-int sleep_ (const integer *seconds) {
-    extern int G77_sleep_0 (const integer *seconds);
-    return G77_sleep_0 (seconds);
-}
-#endif
-
-#ifdef Lsrand
-int srand_ (const integer *seed) {
-    extern int G77_srand_0 (const integer *seed);
-    return G77_srand_0 (seed);
-}
-#endif
-
-#ifdef Lstat
-integer stat_ (const char *name, integer statb[13], const ftnlen Lname) {
-    extern integer G77_stat_0 (const char *name, integer statb[13], const ftnlen Lname);
-    return G77_stat_0 (name, statb, Lname);
-}
-#endif
-
-#ifdef Lsymlnk
-integer symlnk_ (const char *path1, const char *path2, const ftnlen Lpath1, const ftnlen Lpath2) {
-    extern integer G77_symlnk_0 (const char *path1, const char *path2, const ftnlen Lpath1, const ftnlen Lpath2);
-    return G77_symlnk_0 (path1, path2, Lpath1, Lpath2);
-}
-#endif
-
-#ifdef Ltime
-longint time_ (void) {
-    extern longint G77_time_0 (void);
-    return G77_time_0 ();
-}
-#endif
-
-#ifdef Lttynam
-void ttynam_ (char *ret_val, ftnlen ret_val_len, integer *lunit) {
-    extern void G77_ttynam_0 (char *ret_val, ftnlen ret_val_len, integer *lunit);
-    G77_ttynam_0 (ret_val, ret_val_len, lunit);
-}
-#endif
-
-#ifdef Lumask
-integer umask_ (integer *mask) {
-    extern integer G77_umask_0 (integer *mask);
-    return G77_umask_0 (mask);
-}
-#endif
-
-#ifdef Lunlink
-integer unlink_ (const char *str, const ftnlen Lstr) {
-    extern integer G77_unlink_0 (const char *str, const ftnlen Lstr);
-    return G77_unlink_0 (str, Lstr);
-}
-#endif
-
-#ifdef Lvxtidt_y2kbuggy
-int vxtidate_ (integer *m, integer *d, integer *y) {
-  /* Fail to link, so user sees attempt to invoke non-Y2K-compliant
-     routine.  */
-    extern int G77_vxtidate_y2kbuggy_0 (integer *m, integer *d, integer *y);
-    return G77_vxtidate_y2kbuggy_0 (m, d, y);
-}
-#endif
-
-#ifdef Lvxtidt_y2kbug
-int vxtidate_y2kbug__ (integer *m, integer *d, integer *y) {
-  /* If user wants to invoke the non-Y2K-compliant routine via
-     an `EXTERNAL' interface, avoiding the warning via g77's
-     `INTRINSIC' interface, force coding of "y2kbug" string in
-     user's program.  */
-    extern int G77_vxtidate_y2kbug_0 (integer *m, integer *d, integer *y);
-    return G77_vxtidate_y2kbug_0 (m, d, y);
-}
-#endif
-
-#ifdef Lvxttim
-void vxttime_ (char chtime[8], const ftnlen Lchtime) {
-    extern void G77_vxttime_0 (char chtime[8], const ftnlen Lchtime);
-    G77_vxttime_0 (chtime, Lchtime);
-}
-#endif
diff --git a/contrib/libf2c/g2c.hin b/contrib/libf2c/g2c.hin
deleted file mode 100644
index 577ea2b1a8d..00000000000
--- a/contrib/libf2c/g2c.hin
+++ /dev/null
@@ -1,234 +0,0 @@
-/* g2c.h  --  g77 version of f2c (Standard Fortran to C header file) */
-
-/* This file is generated by the g77 libg2c configuration process from a
-   file named g2c.hin.  This process sets up the appropriate types,
-   defines the appropriate macros, and so on.  The resulting g2c.h file
-   is used to build g77's copy of libf2c, named libg2c, and also can
-   be used when compiling C code produced by f2c to link the resulting
-   object file(s) with those produced by the same version of g77 that
-   produced this file, allowing inter-operability of f2c-compiled and
-   g77-compiled code.  */
-
-/**  barf  [ba:rf]  2.  "He suggested using FORTRAN, and everybody barfed."
-
-	- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
-
-#ifndef F2C_INCLUDE
-#define F2C_INCLUDE
-
-/* F2C_INTEGER will normally be `int' but would be `long' on 16-bit systems */
-/* we assume short, float are OK */
-typedef __g77_integer integer;
-typedef __g77_uinteger uinteger;
-typedef char *address;
-typedef short int shortint;
-typedef float real;
-typedef double doublereal;
-typedef struct { real r, i; } complex;
-typedef struct { doublereal r, i; } doublecomplex;
-typedef __g77_integer logical;
-typedef short int shortlogical;
-typedef char logical1;
-typedef char integer1;
-typedef __g77_longint longint;			/* system-dependent */
-typedef __g77_ulongint ulongint;		/* system-dependent */
-#define qbit_clear(a,b)	((a) & ~((ulongint)1 << (b)))
-#define qbit_set(a,b)	((a) |  ((ulongint)1 << (b)))
-
-#define TRUE_ (1)
-#define FALSE_ (0)
-
-/* Extern is for use with -E */
-#ifndef Extern
-#define Extern extern
-#endif
-
-/* I/O stuff */
-
-#ifdef f2c_i2
-#error "f2c_i2 will not work with g77!!!!"
-/* for -i2 */
-typedef short flag;
-typedef short ftnlen;
-typedef short ftnint;
-#else
-typedef __g77_integer flag;
-typedef __g77_integer ftnlen;
-typedef __g77_integer ftnint;
-#endif
-
-/*external read, write*/
-typedef struct
-{	flag cierr;
-	ftnint ciunit;
-	flag ciend;
-	char *cifmt;
-	ftnint cirec;
-} cilist;
-
-/*internal read, write*/
-typedef struct
-{	flag icierr;
-	char *iciunit;
-	flag iciend;
-	char *icifmt;
-	ftnint icirlen;
-	ftnint icirnum;
-} icilist;
-
-/*open*/
-typedef struct
-{	flag oerr;
-	ftnint ounit;
-	char *ofnm;
-	ftnlen ofnmlen;
-	char *osta;
-	char *oacc;
-	char *ofm;
-	ftnint orl;
-	char *oblnk;
-} olist;
-
-/*close*/
-typedef struct
-{	flag cerr;
-	ftnint cunit;
-	char *csta;
-} cllist;
-
-/*rewind, backspace, endfile*/
-typedef struct
-{	flag aerr;
-	ftnint aunit;
-} alist;
-
-/* inquire */
-typedef struct
-{	flag inerr;
-	ftnint inunit;
-	char *infile;
-	ftnlen infilen;
-	ftnint	*inex;	/*parameters in standard's order*/
-	ftnint	*inopen;
-	ftnint	*innum;
-	ftnint	*innamed;
-	char	*inname;
-	ftnlen	innamlen;
-	char	*inacc;
-	ftnlen	inacclen;
-	char	*inseq;
-	ftnlen	inseqlen;
-	char 	*indir;
-	ftnlen	indirlen;
-	char	*infmt;
-	ftnlen	infmtlen;
-	char	*inform;
-	ftnint	informlen;
-	char	*inunf;
-	ftnlen	inunflen;
-	ftnint	*inrecl;
-	ftnint	*innrec;
-	char	*inblank;
-	ftnlen	inblanklen;
-} inlist;
-
-union Multitype {	/* for multiple entry points */
-	integer1 g;
-	shortint h;
-	integer i;
-	/* longint j; */
-	real r;
-	doublereal d;
-	complex c;
-	doublecomplex z;
-	};
-
-typedef union Multitype Multitype;
-
-/*typedef long int Long;*/	/* No longer used; formerly in Namelist */
-
-struct Vardesc {	/* for Namelist */
-	char *name;
-	char *addr;
-	ftnlen *dims;
-	int  type;
-	};
-typedef struct Vardesc Vardesc;
-
-struct Namelist {
-	char *name;
-	Vardesc **vars;
-	int nvars;
-	};
-typedef struct Namelist Namelist;
-
-#define abs(x) ((x) >= 0 ? (x) : -(x))
-#define dabs(x) (doublereal)abs(x)
-#define min(a,b) ((a) <= (b) ? (a) : (b))
-#define max(a,b) ((a) >= (b) ? (a) : (b))
-#define dmin(a,b) (doublereal)min(a,b)
-#define dmax(a,b) (doublereal)max(a,b)
-#define bit_test(a,b)	((a) >> (b) & 1)
-#define bit_clear(a,b)	((a) & ~((uinteger)1 << (b)))
-#define bit_set(a,b)	((a) |  ((uinteger)1 << (b)))
-
-/* procedure parameter types for -A and -C++ */
-
-#define F2C_proc_par_types 1
-#ifdef __cplusplus
-typedef int /* Unknown procedure type */ (*U_fp)(...);
-typedef shortint (*J_fp)(...);
-typedef integer (*I_fp)(...);
-typedef real (*R_fp)(...);
-typedef doublereal (*D_fp)(...), (*E_fp)(...);
-typedef /* Complex */ void (*C_fp)(...);
-typedef /* Double Complex */ void (*Z_fp)(...);
-typedef logical (*L_fp)(...);
-typedef shortlogical (*K_fp)(...);
-typedef /* Character */ void (*H_fp)(...);
-typedef /* Subroutine */ int (*S_fp)(...);
-#else
-typedef int /* Unknown procedure type */ (*U_fp)();
-typedef shortint (*J_fp)();
-typedef integer (*I_fp)();
-typedef real (*R_fp)();
-typedef doublereal (*D_fp)(), (*E_fp)();
-typedef /* Complex */ void (*C_fp)();
-typedef /* Double Complex */ void (*Z_fp)();
-typedef logical (*L_fp)();
-typedef shortlogical (*K_fp)();
-typedef /* Character */ void (*H_fp)();
-typedef /* Subroutine */ int (*S_fp)();
-#endif
-/* E_fp is for real functions when -R is not specified */
-typedef void C_f;	/* complex function */
-typedef void H_f;	/* character function */
-typedef void Z_f;	/* double complex function */
-typedef doublereal E_f;	/* real function with -R not specified */
-
-/* undef any lower-case symbols that your C compiler predefines, e.g.: */
-
-#ifndef Skip_f2c_Undefs
-/* (No such symbols should be defined in a strict ANSI C compiler.
-   We can avoid trouble with f2c-translated code by using
-   gcc -ansi [-traditional].) */
-#undef cray
-#undef gcos
-#undef mc68010
-#undef mc68020
-#undef mips
-#undef pdp11
-#undef sgi
-#undef sparc
-#undef sun
-#undef sun2
-#undef sun3
-#undef sun4
-#undef u370
-#undef u3b
-#undef u3b2
-#undef u3b5
-#undef unix
-#undef vax
-#endif
-#endif
diff --git a/contrib/libf2c/libF77/F77_aloc.c b/contrib/libf2c/libF77/F77_aloc.c
deleted file mode 100644
index b2861029198..00000000000
--- a/contrib/libf2c/libF77/F77_aloc.c
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "f2c.h"
-#undef abs
-#undef min
-#undef max
-#include 
-
-static integer memfailure = 3;
-
-#include 
-extern void G77_exit_0 (integer *);
-
-char *
-F77_aloc (integer Len, char *whence)
-{
-  char *rv;
-  unsigned int uLen = (unsigned int) Len;	/* for K&R C */
-
-  if (!(rv = (char *) malloc (uLen)))
-    {
-      fprintf (stderr, "malloc(%u) failure in %s\n", uLen, whence);
-      G77_exit_0 (&memfailure);
-    }
-  return rv;
-}
diff --git a/contrib/libf2c/libF77/Makefile.in b/contrib/libf2c/libF77/Makefile.in
deleted file mode 100644
index 07af6eb2773..00000000000
--- a/contrib/libf2c/libF77/Makefile.in
+++ /dev/null
@@ -1,255 +0,0 @@
-# Makefile for GNU F77 compiler runtime.
-# Copyright 1990 - 1994 by AT&T Bell Laboratories and Bellcore (see the
-# file `Notice').
-# Portions of this file Copyright (C) 1995-1998, 2001 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of GNU Fortran.
-#
-#GNU Fortran is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-#### Start of system configuration section. ####
-
-# $(srcdir) must be set to the g77 runtime libF77 source directory.
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-# configure sets this to all the -D options appropriate for the
-# configuration.
-DEFS = @DEFS@
-
-F2C_H_DIR = @srcdir@/..
-G2C_H_DIR = ..
-CC = @CC@
-CFLAGS = @CFLAGS@
-CPPFLAGS = @CPPFLAGS@
-AR = @AR@
-ARFLAGS = rc
-RANLIB = @RANLIB@
-@SET_MAKE@
-
-SHELL = @SHELL@
-
-#### End of system configuration section. ####
-
-ALL_CFLAGS = -I. -I$(srcdir) -I$(G2C_H_DIR) -I$(F2C_H_DIR) $(CPPFLAGS) $(DEFS) $(WARN_CFLAGS) $(CFLAGS)
-
-.SUFFIXES:
-.SUFFIXES: .c .lo
-
-.c.lo:
-	@LIBTOOL@ --mode=compile $(CC) -c -DSkip_f2c_Undefs $(ALL_CFLAGS) $<
-
-MISC =	F77_aloc.lo VersionF.lo s_rnge.lo abort_.lo getarg_.lo iargc_.lo\
-	getenv_.lo signal_.lo s_stop.lo s_paus.lo system_.lo cabs.lo\
-	derf_.lo derfc_.lo erf_.lo erfc_.lo sig_die.lo exit_.lo setarg.lo setsig.lo
-POW =	pow_ci.lo pow_dd.lo pow_di.lo pow_hh.lo pow_ii.lo  pow_ri.lo pow_zi.lo pow_zz.lo \
-	pow_qq.lo
-CX =	c_abs.lo c_cos.lo c_div.lo c_exp.lo c_log.lo c_sin.lo c_sqrt.lo
-DCX =	z_abs.lo z_cos.lo z_div.lo z_exp.lo z_log.lo z_sin.lo z_sqrt.lo
-REAL =	r_abs.lo r_acos.lo r_asin.lo r_atan.lo r_atn2.lo r_cnjg.lo r_cos.lo\
-	r_cosh.lo r_dim.lo r_exp.lo r_imag.lo r_int.lo\
-	r_lg10.lo r_log.lo r_mod.lo r_nint.lo r_sign.lo\
-	r_sin.lo r_sinh.lo r_sqrt.lo r_tan.lo r_tanh.lo
-DBL =	d_abs.lo d_acos.lo d_asin.lo d_atan.lo d_atn2.lo\
-	d_cnjg.lo d_cos.lo d_cosh.lo d_dim.lo d_exp.lo\
-	d_imag.lo d_int.lo d_lg10.lo d_log.lo d_mod.lo\
-	d_nint.lo d_prod.lo d_sign.lo d_sin.lo d_sinh.lo\
-	d_sqrt.lo d_tan.lo d_tanh.lo
-INT =	i_abs.lo i_dim.lo i_dnnt.lo i_indx.lo i_len.lo i_mod.lo i_nint.lo i_sign.lo
-HALF =	h_abs.lo h_dim.lo h_dnnt.lo h_indx.lo h_len.lo h_mod.lo  h_nint.lo h_sign.lo
-CMP =	l_ge.lo l_gt.lo l_le.lo l_lt.lo hl_ge.lo hl_gt.lo hl_le.lo hl_lt.lo
-EFL =	ef1asc_.lo ef1cmc_.lo
-CHAR =	s_cat.lo s_cmp.lo s_copy.lo
-F90BIT = lbitbits.lo lbitshft.lo qbitbits.lo qbitshft.lo
-
-OBJS = $(MISC) $(POW) $(CX) $(DCX) $(REAL) $(DBL) $(INT) \
-	 $(HALF) $(CMP) $(EFL) $(CHAR) $(F90BIT)
-
-all: ../s-libf77 ../libfrtbegin.a
-
-../s-libf77: $(OBJS)
-	-rm -f $@.T $@
-	objs='$(OBJS)'; for name in $$objs; do \
-	  echo libF77/$${name} >> $@.T; done
-	mv $@.T $@
-
-Makefile: Makefile.in config.status
-	$(SHELL) config.status
-
-config.status: configure
-	rm -f config.cache
-	CONFIG_SITE=no-such-file CC='$(CC)' AR='$(AR)' CFLAGS='$(CFLAGS)' \
-	  CPPFLAGS='$(CPPFLAGS)' $(SHELL) config.status --recheck
-
-${srcdir}/configure: configure.in
-	rm -f config.cache
-	cd ${srcdir} && autoconf
-
-VersionF.lo: Version.c
-	@LIBTOOL@ --mode=compile $(CC) -c $(ALL_CFLAGS) $(srcdir)/Version.c -o $@
-
-frtbegin.o : main.c
-	$(CC) -c $(ALL_CFLAGS) $(srcdir)/main.c -o $@
-
-../libfrtbegin.a: frtbegin.o
-	-rm -f $@
-	$(AR) $(ARFLAGS) $@ frtbegin.o
-	$(RANLIB) $@
-
-F77_aloc.lo: F77_aloc.c
-s_rnge.lo: s_rnge.c
-abort_.lo: abort_.c
-getarg_.lo: getarg_.c
-iargc_.lo: iargc_.c
-getenv_.lo: getenv_.c
-signal_.lo: signal_.c
-s_stop.lo: s_stop.c
-s_paus.lo: s_paus.c
-system_.lo: system_.c
-cabs.lo: cabs.c
-derf_.lo: derf_.c
-derfc_.lo: derfc_.c
-erf_.lo: erf_.c
-erfc_.lo: erfc_.c
-sig_die.lo: sig_die.c
-exit_.lo: exit_.c
-setarg.lo: setarg.c
-setsig.lo: setsig.c
-pow_ci.lo: pow_ci.c
-pow_dd.lo: pow_dd.c
-pow_di.lo: pow_di.c
-pow_hh.lo: pow_hh.c
-pow_ii.lo: pow_ii.c
-pow_ri.lo:  pow_ri.c
-pow_zi.lo: pow_zi.c
-pow_zz.lo: pow_zz.c
-pow_qq.lo:  pow_qq.c
-c_abs.lo: c_abs.c
-c_cos.lo: c_cos.c
-c_div.lo: c_div.c
-c_exp.lo: c_exp.c
-c_log.lo: c_log.c
-c_sin.lo: c_sin.c
-c_sqrt.lo: c_sqrt.c
-z_abs.lo: z_abs.c
-z_cos.lo: z_cos.c
-z_div.lo: z_div.c
-z_exp.lo: z_exp.c
-z_log.lo: z_log.c
-	@LIBTOOL@ --mode=compile $(CC) -c -DSkip_f2c_Undefs $(ALL_CFLAGS) -ffloat-store $(srcdir)/z_log.c
-z_sin.lo: z_sin.c
-z_sqrt.lo: z_sqrt.c
-r_abs.lo: r_abs.c
-r_acos.lo: r_acos.c
-r_asin.lo: r_asin.c
-r_atan.lo: r_atan.c
-r_atn2.lo: r_atn2.c
-r_cnjg.lo: r_cnjg.c
-r_cos.lo: r_cos.c
-r_cosh.lo: r_cosh.c
-r_dim.lo: r_dim.c
-r_exp.lo: r_exp.c
-r_imag.lo: r_imag.c
-r_int.lo: r_int.c
-r_lg10.lo: r_lg10.c
-r_log.lo: r_log.c
-r_mod.lo: r_mod.c
-r_nint.lo: r_nint.c
-r_sign.lo: r_sign.c
-r_sin.lo: r_sin.c
-r_sinh.lo: r_sinh.c
-r_sqrt.lo: r_sqrt.c
-r_tan.lo: r_tan.c
-r_tanh.lo: r_tanh.c
-d_abs.lo: d_abs.c
-d_acos.lo: d_acos.c
-d_asin.lo: d_asin.c
-d_atan.lo: d_atan.c
-d_atn2.lo: d_atn2.c
-d_cnjg.lo: d_cnjg.c
-d_cos.lo: d_cos.c
-d_cosh.lo: d_cosh.c
-d_dim.lo: d_dim.c
-d_exp.lo: d_exp.c
-d_imag.lo: d_imag.c
-d_int.lo: d_int.c
-d_lg10.lo: d_lg10.c
-d_log.lo: d_log.c
-d_mod.lo: d_mod.c
-d_nint.lo: d_nint.c
-d_prod.lo: d_prod.c
-d_sign.lo: d_sign.c
-d_sin.lo: d_sin.c
-d_sinh.lo: d_sinh.c
-d_sqrt.lo: d_sqrt.c
-d_tan.lo: d_tan.c
-d_tanh.lo: d_tanh.c
-i_abs.lo: i_abs.c
-i_dim.lo: i_dim.c
-i_dnnt.lo: i_dnnt.c
-i_indx.lo: i_indx.c
-i_len.lo: i_len.c
-i_mod.lo: i_mod.c
-i_nint.lo: i_nint.c
-i_sign.lo: i_sign.c
-h_abs.lo:  h_abs.c
-h_dim.lo: h_dim.c
-h_dnnt.lo: h_dnnt.c
-h_indx.lo: h_indx.c
-h_len.lo: h_len.c
-h_mod.lo: h_mod.c
-h_nint.lo:  h_nint.c
-h_sign.lo: h_sign.c
-l_ge.lo: l_ge.c
-l_gt.lo: l_gt.c
-l_le.lo: l_le.c
-l_lt.lo: l_lt.c
-hl_ge.lo: hl_ge.c
-hl_gt.lo: hl_gt.c
-hl_le.lo: hl_le.c
-hl_lt.lo: hl_lt.c
-ef1asc_.lo: ef1asc_.c
-ef1cmc_.lo: ef1cmc_.c
-s_cat.lo: s_cat.c
-s_cmp.lo: s_cmp.c
-s_copy.lo: s_copy.c
-lbitbits.lo: lbitbits.c
-lbitshft.lo: lbitshft.c
-qbitbits.lo: qbitbits.c
-qbitshft.lo: qbitshft.c
-
-# Not quite all these actually do depend on f2c.h...
-$(MISC) $(POW) $(CX) $(DCX) $(REAL) $(DBL) $(INT) $(HALF) $(CMP) $(EFL) \
-  $(CHAR) $(F90BIT): $(F2C_H_DIR)/f2c.h $(G2C_H_DIR)/g2c.h
-
-check install uninstall install-strip dist installcheck installdirs:
-
-mostlyclean:
-	rm -f *.o *.lo ../libfrtbegin.a
-	rm -rf .libs
-
-clean: mostlyclean
-	rm -f config.log
-	rm -f ../s-libf77
-
-distclean: clean
-	rm -f config.cache config.status Makefile ../s-libf77 configure
-
-maintainer-clean:
-
-.PHONY: mostlyclean clean distclean maintainer-clean all check uninstall \
-        install-strip dist installcheck installdirs archive
diff --git a/contrib/libf2c/libF77/Notice b/contrib/libf2c/libF77/Notice
deleted file mode 100644
index 261b719bc57..00000000000
--- a/contrib/libf2c/libF77/Notice
+++ /dev/null
@@ -1,23 +0,0 @@
-/****************************************************************
-Copyright 1990 - 1997 by AT&T, Lucent Technologies and Bellcore.
-
-Permission to use, copy, modify, and distribute this software
-and its documentation for any purpose and without fee is hereby
-granted, provided that the above copyright notice appear in all
-copies and that both that the copyright notice and this
-permission notice and warranty disclaimer appear in supporting
-documentation, and that the names of AT&T, Bell Laboratories,
-Lucent or Bellcore or any of their entities not be used in
-advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.
-
-AT&T, Lucent and Bellcore disclaim all warranties with regard to
-this software, including all implied warranties of
-merchantability and fitness.  In no event shall AT&T, Lucent or
-Bellcore be liable for any special, indirect or consequential
-damages or any damages whatsoever resulting from loss of use,
-data or profits, whether in an action of contract, negligence or
-other tortious action, arising out of or in connection with the
-use or performance of this software.
-****************************************************************/
-
diff --git a/contrib/libf2c/libF77/README.netlib b/contrib/libf2c/libF77/README.netlib
deleted file mode 100644
index 5e532ee0990..00000000000
--- a/contrib/libf2c/libF77/README.netlib
+++ /dev/null
@@ -1,112 +0,0 @@
-If your compiler does not recognize ANSI C headers,
-compile with KR_headers defined:  either add -DKR_headers
-to the definition of CFLAGS in the makefile, or insert
-
-#define KR_headers
-
-at the top of f2c.h , cabs.c , main.c , and sig_die.c .
-
-Under MS-DOS, compile s_paus.c with -DMSDOS.
-
-If you have a really ancient K&R C compiler that does not understand
-void, add -Dvoid=int to the definition of CFLAGS in the makefile.
-
-If you use a C++ compiler, first create a local f2c.h by appending
-f2ch.add to the usual f2c.h, e.g., by issuing the command
-	make f2c.h
-which assumes f2c.h is installed in /usr/include .
-
-If your system lacks onexit() and you are not using an ANSI C
-compiler, then you should compile main.c, s_paus.c, s_stop.c, and
-sig_die.c with NO_ONEXIT defined.  See the comments about onexit in
-the makefile.
-
-If your system has a double drem() function such that drem(a,b)
-is the IEEE remainder function (with double a, b), then you may
-wish to compile r_mod.c and d_mod.c with IEEE_drem defined.
-On some systems, you may also need to compile with -Ddrem=remainder .
-
-To check for transmission errors, issue the command
-	make check
-This assumes you have the xsum program whose source, xsum.c,
-is distributed as part of "all from f2c/src".  If you do not
-have xsum, you can obtain xsum.c by sending the following E-mail
-message to netlib@netlib.bell-labs.com
-	send xsum.c from f2c/src
-
-The makefile assumes you have installed f2c.h in a standard
-place (and does not cause recompilation when f2c.h is changed);
-f2c.h comes with "all from f2c" (the source for f2c) and is
-available separately ("f2c.h from f2c").
-
-Most of the routines in libF77 are support routines for Fortran
-intrinsic functions or for operations that f2c chooses not
-to do "in line".  There are a few exceptions, summarized below --
-functions and subroutines that appear to your program as ordinary
-external Fortran routines.
-
-1.	CALL ABORT prints a message and causes a core dump.
-
-2.	ERF(r) and DERF(d) and the REAL and DOUBLE PRECISION
-	error functions (with x REAL and d DOUBLE PRECISION);
-	DERF must be declared DOUBLE PRECISION in your program.
-	Both ERF and DERF assume your C library provides the
-	underlying erf() function (which not all systems do).
-
-3.	ERFC(r) and DERFC(d) are the complementary error functions:
-	ERFC(r) = 1 - ERF(r) and DERFC(d) = 1.d0 - DERFC(d)
-	(except that their results may be more accurate than
-	explicitly evaluating the above formulae would give).
-	Again, ERFC and r are REAL, and DERFC and d are DOUBLE
-	PRECISION (and must be declared as such in your program),
-	and ERFC and DERFC rely on your system's erfc().
-
-4.	CALL GETARG(n,s), where n is an INTEGER and s is a CHARACTER
-	variable, sets s to the n-th command-line argument (or to
-	all blanks if there are fewer than n command-line arguments);
-	CALL GETARG(0,s) sets s to the name of the program (on systems
-	that support this feature).  See IARGC below.
-
-5.	CALL GETENV(name, value), where name and value are of type
-	CHARACTER, sets value to the environment value, $name, of
-	name (or to blanks if $name has not been set).
-
-6.	NARGS = IARGC() sets NARGS to the number of command-line
-	arguments (an INTEGER value).
-
-7.	CALL SIGNAL(n,func), where n is an INTEGER and func is an
-	EXTERNAL procedure, arranges for func to be invoked when
-	signal n occurs (on systems where this makes sense).
-
-8.	CALL SYSTEM(cmd), where cmd is of type CHARACTER, passes
-	cmd to the system's command processor (on systems where
-	this can be done).
-
-The makefile does not attempt to compile pow_qq.c, qbitbits.c,
-and qbitshft.c, which are meant for use with INTEGER*8.  To use
-INTEGER*8, you must modify f2c.h to declare longint and ulongint
-appropriately; then add pow_qq.o to the POW = line in the makefile,
-and add " qbitbits.o qbitshft.o" to the makefile's F90BIT = line.
-
-Following Fortran 90, s_cat.c and s_copy.c allow the target of a
-(character string) assignment to be appear on its right-hand, at
-the cost of some extra overhead for all run-time concatenations.
-If you prefer the  extra efficiency that comes with the Fortran 77
-requirement that the left-hand side of a character assignment not
-be involved in the right-hand side, compile s_cat.c and s_copy.c
-with -DNO_OVERWRITE .
-
-If your system lacks a ranlib command, you don't need it.
-Either comment out the makefile's ranlib invocation, or install
-a harmless "ranlib" command somewhere in your PATH, such as the
-one-line shell script
-
-	exit 0
-
-or (on some systems)
-
-	exec /usr/bin/ar lts $1 >/dev/null
-
-If your compiler complains about the signal calls in main.c, s_paus.c,
-and signal_.c, you may need to adjust signal1.h suitably.  See the
-comments in signal1.h.
diff --git a/contrib/libf2c/libF77/Version.c b/contrib/libf2c/libF77/Version.c
deleted file mode 100644
index a27b0df7696..00000000000
--- a/contrib/libf2c/libF77/Version.c
+++ /dev/null
@@ -1,94 +0,0 @@
-const char __LIBF77_VERSION__[] = "@(#) LIBF77 VERSION 20000929\n";
-extern const char __LIBI77_VERSION__[];
-extern const char __LIBU77_VERSION__[];
-
-/*
-2.00	11 June 1980.  File version.c added to library.
-2.01	31 May 1988.  s_paus() flushes stderr; names of hl_* fixed
-	[ d]erf[c ] added
-	 8 Aug. 1989: #ifdefs for f2c -i2 added to s_cat.c
-	29 Nov. 1989: s_cmp returns long (for f2c)
-	30 Nov. 1989: arg types from f2c.h
-	12 Dec. 1989: s_rnge allows long names
-	19 Dec. 1989: getenv_ allows unsorted environment
-	28 Mar. 1990: add exit(0) to end of main()
-	 2 Oct. 1990: test signal(...) == SIG_IGN rather than & 01 in main
-	17 Oct. 1990: abort() calls changed to sig_die(...,1)
-	22 Oct. 1990: separate sig_die from main
-	25 Apr. 1991: minor, theoretically invisible tweaks to s_cat, sig_die
-	31 May  1991: make system_ return status
-	18 Dec. 1991: change long to ftnlen (for -i2) many places
-	28 Feb. 1992: repair z_sqrt.c (scribbled on input, gave wrong answer)
-	18 July 1992: for n < 0, repair handling of 0**n in pow_[dr]i.c
-			and m**n in pow_hh.c and pow_ii.c;
-			catch SIGTRAP in main() for error msg before abort
-	23 July 1992: switch to ANSI prototypes unless KR_headers is #defined
-	23 Oct. 1992: fix botch in signal_.c (erroneous deref of 2nd arg);
-			change Cabs to f__cabs.
-	12 March 1993: various tweaks for C++
-	 2 June 1994: adjust so abnormal terminations invoke f_exit just once
-	16 Sept. 1994: s_cmp: treat characters as unsigned in comparisons.
-	19 Sept. 1994: s_paus: flush after end of PAUSE; add -DMSDOS
-	12 Jan. 1995:	pow_[dhiqrz][hiq]: adjust x**i to work on machines
-			that sign-extend right shifts when i is the most
-			negative integer.
-	26 Jan. 1995: adjust s_cat.c, s_copy.c to permit the left-hand side
-			of character assignments to appear on the right-hand
-			side (unless compiled with -DNO_OVERWRITE).
-	27 Jan. 1995: minor tweak to s_copy.c: copy forward whenever
-			possible (for better cache behavior).
-	30 May 1995:  added subroutine exit(rc) integer rc. Version not changed.
-	29 Aug. 1995: add F77_aloc.c; use it in s_cat.c and system_.c.
-	6 Sept. 1995: fix return type of system_ under -DKR_headers.
-	19 Dec. 1995: s_cat.c: fix bug when 2nd or later arg overlaps lhs.
-	19 Mar. 1996: s_cat.c: supply missing break after overlap detection.
-	13 May 1996:  add [lq]bitbits.c and [lq]bitshft.c (f90 bit intrinsics).
-	19 June 1996: add casts to unsigned in [lq]bitshft.c.
-	26 Feb. 1997: adjust functions with a complex output argument
-			to permit aliasing it with input arguments.
-			(For now, at least, this is just for possible
-			benefit of g77.)
-	4 April 1997: [cz]_div.c: tweaks invisible on most systems (that may
-			affect systems using gratuitous extra precision).
-	19 Sept. 1997: [de]time_.c (Unix systems only): change return
-			type to double.
-	2 May 1999:	getenv_.c: omit environ in favor of getenv().
-			c_cos.c, c_exp.c, c_sin.c, d_cnjg.c, r_cnjg.c,
-			z_cos.c, z_exp.c, z_log.c, z_sin.c: cope fully with
-			overlapping arguments caused by equivalence.
-	3 May 1999:	"invisible" tweaks to omit compiler warnings in
-			abort_.c, ef1asc_.c, s_rnge.c, s_stop.c.
-	7 Sept. 1999: [cz]_div.c: arrange for compilation under
-			-DIEEE_COMPLEX_DIVIDE to make these routines
-			avoid calling sig_die when the denominator
-			vanishes; instead, they return pairs of NaNs
-			or Infinities, depending whether the numerator
-			also vanishes or not.  VERSION not changed.
-	15 Nov. 1999: s_rnge.c: add casts for the case of
-			sizeof(ftnint) == sizeof(int) < sizeof(long).
-	10 March 2000: z_log.c: improve accuracy of Real(log(z)) for, e.g.,
-			z near (+-1,eps) with |eps| small.  For the old
-			evaluation, compile with -DPre20000310 .
-	20 April 2000: s_cat.c: tweak argument types to accord with
-			calls by f2c when ftnint and ftnlen are of
-			different sizes (different numbers of bits).
-	4 July 2000: adjustments to permit compilation by C++ compilers;
-			VERSION string remains unchanged. NOT APPLIED FOR G77.
-	29 Sept. 2000: dtime_.c, etime_.c: use floating-point divide.
-			dtime_.d, erf_.c, erfc_.c, etime.c: for use with
-			"f2c -R", compile with -DREAL=float.
-*/
-
-#include 
-
-void
-g77__fvers__ ()
-{
-  fputs ("GNU Fortran library.\n", stderr);
-#if defined __GNUC__ && defined __VERSION__
-  fprintf (stderr, "Compiled by GCC %s\n", __VERSION__);
-#endif
-  fputs (__LIBF77_VERSION__, stderr);
-  fputs (__LIBI77_VERSION__, stderr);
-  fputs (__LIBU77_VERSION__, stderr);
-}
diff --git a/contrib/libf2c/libF77/abort_.c b/contrib/libf2c/libF77/abort_.c
deleted file mode 100644
index 761bc3bd6e9..00000000000
--- a/contrib/libf2c/libF77/abort_.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include 
-#include "f2c.h"
-
-extern void sig_die (char *, int);
-
-int
-G77_abort_0 (void)
-{
-  sig_die ("Fortran abort routine called", 1);
-  return 0;			/* not reached */
-}
diff --git a/contrib/libf2c/libF77/c_abs.c b/contrib/libf2c/libF77/c_abs.c
deleted file mode 100644
index 3fc4d7c0a6a..00000000000
--- a/contrib/libf2c/libF77/c_abs.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-extern double f__cabs (double, double);
-
-double
-c_abs (complex * z)
-{
-  return (f__cabs (z->r, z->i));
-}
diff --git a/contrib/libf2c/libF77/c_cos.c b/contrib/libf2c/libF77/c_cos.c
deleted file mode 100644
index 59659754978..00000000000
--- a/contrib/libf2c/libF77/c_cos.c
+++ /dev/null
@@ -1,12 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-
-void
-c_cos (complex * r, complex * z)
-{
-  double zi = z->i, zr = z->r;
-  r->r = cos (zr) * cosh (zi);
-  r->i = -sin (zr) * sinh (zi);
-}
diff --git a/contrib/libf2c/libF77/c_div.c b/contrib/libf2c/libF77/c_div.c
deleted file mode 100644
index b5ede0eb801..00000000000
--- a/contrib/libf2c/libF77/c_div.c
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "f2c.h"
-
-extern void sig_die (char *, int);
-void
-c_div (complex * c, complex * a, complex * b)
-{
-  double ratio, den;
-  double abr, abi, cr;
-
-  if ((abr = b->r) < 0.)
-    abr = -abr;
-  if ((abi = b->i) < 0.)
-    abi = -abi;
-  if (abr <= abi)
-    {
-      if (abi == 0)
-	{
-#ifdef IEEE_COMPLEX_DIVIDE
-	  float af, bf;
-	  af = bf = abr;
-	  if (a->i != 0 || a->r != 0)
-	    af = 1.;
-	  c->i = c->r = af / bf;
-	  return;
-#else
-	  sig_die ("complex division by zero", 1);
-#endif
-	}
-      ratio = (double) b->r / b->i;
-      den = b->i * (1 + ratio * ratio);
-      cr = (a->r * ratio + a->i) / den;
-      c->i = (a->i * ratio - a->r) / den;
-    }
-
-  else
-    {
-      ratio = (double) b->i / b->r;
-      den = b->r * (1 + ratio * ratio);
-      cr = (a->r + a->i * ratio) / den;
-      c->i = (a->i - a->r * ratio) / den;
-    }
-  c->r = cr;
-}
diff --git a/contrib/libf2c/libF77/c_exp.c b/contrib/libf2c/libF77/c_exp.c
deleted file mode 100644
index 56a8695420c..00000000000
--- a/contrib/libf2c/libF77/c_exp.c
+++ /dev/null
@@ -1,14 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-
-void
-c_exp (complex * r, complex * z)
-{
-  double expx, zi = z->i;
-
-  expx = exp (z->r);
-  r->r = expx * cos (zi);
-  r->i = expx * sin (zi);
-}
diff --git a/contrib/libf2c/libF77/c_log.c b/contrib/libf2c/libF77/c_log.c
deleted file mode 100644
index 7d5b9513167..00000000000
--- a/contrib/libf2c/libF77/c_log.c
+++ /dev/null
@@ -1,13 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-extern double f__cabs (double, double);
-
-void
-c_log (complex * r, complex * z)
-{
-  double zi, zr;
-  r->i = atan2 (zi = z->i, zr = z->r);
-  r->r = log (f__cabs (zr, zi));
-}
diff --git a/contrib/libf2c/libF77/c_sin.c b/contrib/libf2c/libF77/c_sin.c
deleted file mode 100644
index 44bce9f7739..00000000000
--- a/contrib/libf2c/libF77/c_sin.c
+++ /dev/null
@@ -1,12 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-
-void
-c_sin (complex * r, complex * z)
-{
-  double zi = z->i, zr = z->r;
-  r->r = sin (zr) * cosh (zi);
-  r->i = cos (zr) * sinh (zi);
-}
diff --git a/contrib/libf2c/libF77/c_sqrt.c b/contrib/libf2c/libF77/c_sqrt.c
deleted file mode 100644
index 81b72fc372e..00000000000
--- a/contrib/libf2c/libF77/c_sqrt.c
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-extern double f__cabs (double, double);
-
-void
-c_sqrt (complex * r, complex * z)
-{
-  double mag, t;
-  double zi = z->i, zr = z->r;
-
-  if ((mag = f__cabs (zr, zi)) == 0.)
-    r->r = r->i = 0.;
-  else if (zr > 0)
-    {
-      r->r = t = sqrt (0.5 * (mag + zr));
-      t = zi / t;
-      r->i = 0.5 * t;
-    }
-  else
-    {
-      t = sqrt (0.5 * (mag - zr));
-      if (zi < 0)
-	t = -t;
-      r->i = t;
-      t = zi / t;
-      r->r = 0.5 * t;
-    }
-}
diff --git a/contrib/libf2c/libF77/cabs.c b/contrib/libf2c/libF77/cabs.c
deleted file mode 100644
index 5d2142e1825..00000000000
--- a/contrib/libf2c/libF77/cabs.c
+++ /dev/null
@@ -1,24 +0,0 @@
-#undef abs
-#include 
-double
-f__cabs (double real, double imag)
-{
-  double temp;
-
-  if (real < 0)
-    real = -real;
-  if (imag < 0)
-    imag = -imag;
-  if (imag > real)
-    {
-      temp = real;
-      real = imag;
-      imag = temp;
-    }
-  if ((real + imag) == real)
-    return (real);
-
-  temp = imag / real;
-  temp = real * sqrt (1.0 + temp * temp);	/*overflow!! */
-  return (temp);
-}
diff --git a/contrib/libf2c/libF77/configure b/contrib/libf2c/libF77/configure
deleted file mode 100755
index 4e198c87c8f..00000000000
--- a/contrib/libf2c/libF77/configure
+++ /dev/null
@@ -1,1568 +0,0 @@
-#! /bin/sh
-
-# Guess values for system-dependent variables and create Makefiles.
-# Generated automatically using autoconf version 2.13 
-# Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc.
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-
-# Defaults:
-ac_help=
-ac_default_prefix=/usr/local
-# Any additions from configure.in:
-
-# Initialize some variables set by options.
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
-exec_prefix=NONE
-host=NONE
-no_create=
-nonopt=NONE
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-target=NONE
-verbose=
-x_includes=NONE
-x_libraries=NONE
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
-
-# Initialize some other variables.
-subdirs=
-MFLAGS= MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-# Maximum number of lines to put in a shell here document.
-ac_max_here_lines=12
-
-ac_prev=
-for ac_option
-do
-
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
-    ac_prev=
-    continue
-  fi
-
-  case "$ac_option" in
-  -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
-  *) ac_optarg= ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case "$ac_option" in
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file="$ac_optarg" ;;
-
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
-
-  -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    eval "enable_${ac_feature}=no" ;;
-
-  -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "enable_${ac_feature}='$ac_optarg'" ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he)
-    # Omit some internal or obsolete options to make the list less imposing.
-    # This message is too long to be a string in the A/UX 3.1 sh.
-    cat << EOF
-Usage: configure [options] [host]
-Options: [defaults in brackets after descriptions]
-Configuration:
-  --cache-file=FILE       cache test results in FILE
-  --help                  print this message
-  --no-create             do not create output files
-  --quiet, --silent       do not print \`checking...' messages
-  --version               print the version of autoconf that created configure
-Directory and file names:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [same as prefix]
-  --bindir=DIR            user executables in DIR [EPREFIX/bin]
-  --sbindir=DIR           system admin executables in DIR [EPREFIX/sbin]
-  --libexecdir=DIR        program executables in DIR [EPREFIX/libexec]
-  --datadir=DIR           read-only architecture-independent data in DIR
-                          [PREFIX/share]
-  --sysconfdir=DIR        read-only single-machine data in DIR [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data in DIR
-                          [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data in DIR [PREFIX/var]
-  --libdir=DIR            object code libraries in DIR [EPREFIX/lib]
-  --includedir=DIR        C header files in DIR [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc in DIR [/usr/include]
-  --infodir=DIR           info documentation in DIR [PREFIX/info]
-  --mandir=DIR            man documentation in DIR [PREFIX/man]
-  --srcdir=DIR            find the sources in DIR [configure dir or ..]
-  --program-prefix=PREFIX prepend PREFIX to installed program names
-  --program-suffix=SUFFIX append SUFFIX to installed program names
-  --program-transform-name=PROGRAM
-                          run sed PROGRAM on installed program names
-EOF
-    cat << EOF
-Host type:
-  --build=BUILD           configure for building on BUILD [BUILD=HOST]
-  --host=HOST             configure for HOST [guessed]
-  --target=TARGET         configure for TARGET [TARGET=HOST]
-Features and packages:
-  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
-  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --x-includes=DIR        X include files are in DIR
-  --x-libraries=DIR       X library files are in DIR
-EOF
-    if test -n "$ac_help"; then
-      echo "--enable and --with options recognized:$ac_help"
-    fi
-    exit 0 ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir="$ac_optarg" ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir="$ac_optarg" ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix="$ac_optarg" ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix="$ac_optarg" ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir="$ac_optarg" ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers)
-    echo "configure generated by autoconf version 2.13"
-    exit 0 ;;
-
-  -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "with_${ac_package}='$ac_optarg'" ;;
-
-  -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    eval "with_${ac_package}=no" ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes="$ac_optarg" ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries="$ac_optarg" ;;
-
-  -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
-    ;;
-
-  *)
-    if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then
-      echo "configure: warning: $ac_option: invalid host type" 1>&2
-    fi
-    if test "x$nonopt" != xNONE; then
-      { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; }
-    fi
-    nonopt="$ac_option"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; }
-fi
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-# File descriptor usage:
-# 0 standard input
-# 1 file creation
-# 2 errors and warnings
-# 3 some systems may open it to /dev/tty
-# 4 used on the Kubota Titan
-# 6 checking for... messages and results
-# 5 compiler messages saved in config.log
-if test "$silent" = yes; then
-  exec 6>/dev/null
-else
-  exec 6>&1
-fi
-exec 5>./config.log
-
-echo "\
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-" 1>&5
-
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Also quote any args containing shell metacharacters.
-ac_configure_args=
-for ac_arg
-do
-  case "$ac_arg" in
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c) ;;
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;;
-  *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
-  ac_configure_args="$ac_configure_args '$ac_arg'" ;;
-  *) ac_configure_args="$ac_configure_args $ac_arg" ;;
-  esac
-done
-
-# NLS nuisances.
-# Only set these to C if already set.  These must not be set unconditionally
-# because not all systems understand e.g. LANG=C (notably SCO).
-# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
-# Non-C LC_CTYPE values break the ctype check.
-if test "${LANG+set}"   = set; then LANG=C;   export LANG;   fi
-if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
-if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
-if test "${LC_CTYPE+set}"    = set; then LC_CTYPE=C;    export LC_CTYPE;    fi
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo > confdefs.h
-
-# A filename unique to this package, relative to the directory that
-# configure is in, which we can look for to find out if srcdir is correct.
-ac_unique_file=getarg_.c
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_prog=$0
-  ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'`
-  test "x$ac_confdir" = "x$ac_prog" && ac_confdir=.
-  srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; }
-  else
-    { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; }
-  fi
-fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
-fi
-for ac_site_file in $CONFIG_SITE; do
-  if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
-    . "$ac_site_file"
-  fi
-done
-
-if test -r "$cache_file"; then
-  echo "loading cache $cache_file"
-  . $cache_file
-else
-  echo "creating cache $cache_file"
-  > $cache_file
-fi
-
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-ac_exeext=
-ac_objext=o
-if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
-  # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu.
-  if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
-    ac_n= ac_c='
-' ac_t='	'
-  else
-    ac_n=-n ac_c= ac_t=
-  fi
-else
-  ac_n= ac_c='\c' ac_t=
-fi
-
-
-
-
-
-
-# For g77 we'll set CC to point at the built gcc, but this will get it into
-# the makefiles
-# Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:534: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="gcc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:564: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_prog_rejected=no
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then
-        ac_prog_rejected=yes
-	continue
-      fi
-      ac_cv_prog_CC="cc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# -gt 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    set dummy "$ac_dir/$ac_word" "$@"
-    shift
-    ac_cv_prog_CC="$@"
-  fi
-fi
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-  if test -z "$CC"; then
-    case "`uname -s`" in
-    *win32* | *WIN32*)
-      # Extract the first word of "cl", so it can be a program name with args.
-set dummy cl; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:615: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="cl"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
- ;;
-    esac
-  fi
-  test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
-fi
-
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:648: checking whether we are using GNU C" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.c <&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gcc=yes
-else
-  ac_cv_prog_gcc=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gcc" 1>&6
-
-if test $ac_cv_prog_gcc = yes; then
-  GCC=yes
-else
-  GCC=
-fi
-
-ac_test_CFLAGS="${CFLAGS+set}"
-ac_save_CFLAGS="$CFLAGS"
-CFLAGS=
-echo $ac_n "checking whether ${CC-cc} accepts -g""... $ac_c" 1>&6
-echo "configure:676: checking whether ${CC-cc} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cc_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.c
-if test -z "`${CC-cc} -g -c conftest.c 2>&1`"; then
-  ac_cv_prog_cc_g=yes
-else
-  ac_cv_prog_cc_g=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS="$ac_save_CFLAGS"
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-
-
-LIBTOOL='$(SHELL) ../libtool'
-
-
-test "$AR" || AR=ar
-
-if test "$RANLIB"; then :
-  
-else
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:719: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_RANLIB="ranlib"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":"
-fi
-fi
-RANLIB="$ac_cv_prog_RANLIB"
-if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-fi
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:748: checking whether ${MAKE-make} sets \${MAKE}" >&5
-set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_prog_make_${ac_make}_set'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftestmake <<\EOF
-all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
-# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
-eval `${MAKE-make} -f conftestmake 2>/dev/null | grep temp=`
-if test -n "$ac_maketemp"; then
-  eval ac_cv_prog_make_${ac_make}_set=yes
-else
-  eval ac_cv_prog_make_${ac_make}_set=no
-fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  SET_MAKE=
-else
-  echo "$ac_t""no" 1>&6
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-
-
-# Sanity check for the cross-compilation case:
-echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:778: checking how to run the C preprocessor" >&5
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-    # This must be in double quotes, not single quotes, because CPP may get
-  # substituted into the Makefile and "${CC-cc}" will confuse make.
-  CPP="${CC-cc} -E"
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp.
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:799: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -E -traditional-cpp"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:816: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -nologo -E"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:833: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP=/lib/cpp
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-  ac_cv_prog_CPP="$CPP"
-fi
-  CPP="$ac_cv_prog_CPP"
-else
-  ac_cv_prog_CPP="$CPP"
-fi
-echo "$ac_t""$CPP" 1>&6
-
-ac_safe=`echo "stdio.h" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for stdio.h""... $ac_c" 1>&6
-echo "configure:859: checking for stdio.h" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:869: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=yes"
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  :
-else
-  echo "$ac_t""no" 1>&6
-{ echo "configure: error: Can't find stdio.h.
-You must have a usable C system for the target already installed, at least
-including headers and, preferably, the library, before you can configure
-the G77 runtime system.  If necessary, install gcc now with \`LANGUAGES=c',
-then the target library, then build with \`LANGUAGES=f77'." 1>&2; exit 1; }
-fi
-
-
-echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6
-echo "configure:897: checking for ANSI C header files" >&5
-if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#include 
-#include 
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:910: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  ac_cv_header_stdc=yes
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-cat > conftest.$ac_ext <
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "memchr" >/dev/null 2>&1; then
-  :
-else
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-cat > conftest.$ac_ext <
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "free" >/dev/null 2>&1; then
-  :
-else
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-if test "$cross_compiling" = yes; then
-  :
-else
-  cat > conftest.$ac_ext <
-#define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-#define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int main () { int i; for (i = 0; i < 256; i++)
-if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) exit(2);
-exit (0); }
-
-EOF
-if { (eval echo configure:977: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
-  :
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -fr conftest*
-  ac_cv_header_stdc=no
-fi
-rm -fr conftest*
-fi
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_header_stdc" 1>&6
-if test $ac_cv_header_stdc = yes; then
-  cat >> confdefs.h <<\EOF
-#define STDC_HEADERS 1
-EOF
-
-fi
-
-echo $ac_n "checking for posix""... $ac_c" 1>&6
-echo "configure:1001: checking for posix" >&5
-if eval "test \"`echo '$''{'g77_cv_header_posix'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#ifdef _POSIX_VERSION
-  yes
-#endif
-
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  g77_cv_header_posix=yes
-else
-  rm -rf conftest*
-  g77_cv_header_posix=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$g77_cv_header_posix" 1>&6
-
-# We can rely on the GNU library being posix-ish.  I guess checking the 
-# header isn't actually like checking the functions, though...
-echo $ac_n "checking for GNU library""... $ac_c" 1>&6
-echo "configure:1032: checking for GNU library" >&5
-if eval "test \"`echo '$''{'g77_cv_lib_gnu'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#ifdef __GNU_LIBRARY__
-  yes
-#endif
-
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  g77_cv_lib_gnu=yes
-else
-  rm -rf conftest*
-  g77_cv_lib_gnu=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$g77_cv_lib_gnu" 1>&6
-
-echo $ac_n "checking return type of signal handlers""... $ac_c" 1>&6
-echo "configure:1060: checking return type of signal handlers" >&5
-if eval "test \"`echo '$''{'ac_cv_type_signal'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#ifdef signal
-#undef signal
-#endif
-#ifdef __cplusplus
-extern "C" void (*signal (int, void (*)(int)))(int);
-#else
-void (*signal ()) ();
-#endif
-
-int main() {
-int i;
-; return 0; }
-EOF
-if { (eval echo configure:1082: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_type_signal=void
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_type_signal=int
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_type_signal" 1>&6
-cat >> confdefs.h <&6
-echo "configure:1103: checking for atexit" >&5
-if eval "test \"`echo '$''{'ac_cv_func_atexit'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char atexit();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_atexit) || defined (__stub___atexit)
-choke me
-#else
-atexit();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1131: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_atexit=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_atexit=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'atexit`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  cat >> confdefs.h <<\EOF
-#define onexit atexit
-EOF
-
-else
-  echo "$ac_t""no" 1>&6
-  cat >> confdefs.h <<\EOF
-#define NO_ONEXIT 1
-EOF
-
-  echo $ac_n "checking for onexit""... $ac_c" 1>&6
-echo "configure:1156: checking for onexit" >&5
-if eval "test \"`echo '$''{'ac_cv_func_onexit'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char onexit();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_onexit) || defined (__stub___onexit)
-choke me
-#else
-onexit();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1184: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_onexit=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_onexit=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'onexit`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  :
-else
-  echo "$ac_t""no" 1>&6
-echo $ac_n "checking for on_exit""... $ac_c" 1>&6
-echo "configure:1202: checking for on_exit" >&5
-if eval "test \"`echo '$''{'ac_cv_func_on_exit'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char on_exit();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_on_exit) || defined (__stub___on_exit)
-choke me
-#else
-on_exit();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1230: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_on_exit=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_on_exit=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'on_exit`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  cat >> confdefs.h <<\EOF
-#define onexit on_exit
-EOF
-
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-fi
-
-fi
-
-else true
-fi
-
-echo $ac_n "checking for drem in -lm""... $ac_c" 1>&6
-echo "configure:1260: checking for drem in -lm" >&5
-ac_lib_var=`echo m'_'drem | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  ac_save_LIBS="$LIBS"
-LIBS="-lm  $LIBS"
-cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_lib_$ac_lib_var=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  cat >> confdefs.h <<\EOF
-#define IEEE_drem 1
-EOF
-
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-cat >> confdefs.h <<\EOF
-#define Skip_f2c_Undefs 1
-EOF
-
-cat >> confdefs.h <<\EOF
-#define IEEE_COMPLEX_DIVIDE 1
-EOF
-
-
-trap '' 1 2 15
-cat > confcache <<\EOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs.  It is not useful on other systems.
-# If it contains results you don't want to keep, you may remove or edit it.
-#
-# By default, configure uses ./config.cache as the cache file,
-# creating it if it does not exist already.  You can give configure
-# the --cache-file=FILE option to use a different cache file; that is
-# what configure does when it calls configure scripts in
-# subdirectories, so they share the cache.
-# Giving --cache-file=/dev/null disables caching, for debugging configure.
-# config.status only pays attention to the cache file if you give it the
-# --recheck option to rerun configure.
-#
-EOF
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(set) 2>&1 |
-  case `(ac_space=' '; set | grep ac_space) 2>&1` in
-  *ac_space=\ *)
-    # `set' does not quote correctly, so add quotes (double-quote substitution
-    # turns \\\\ into \\, and sed turns \\ into \).
-    sed -n \
-      -e "s/'/'\\\\''/g" \
-      -e "s/^\\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\\)=\\(.*\\)/\\1=\${\\1='\\2'}/p"
-    ;;
-  *)
-    # `set' quotes correctly as required by POSIX, so do not add quotes.
-    sed -n -e 's/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=${\1=\2}/p'
-    ;;
-  esac >> confcache
-if cmp -s $cache_file confcache; then
-  :
-else
-  if test -w $cache_file; then
-    echo "updating cache $cache_file"
-    cat confcache > $cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Any assignment to VPATH causes Sun make to only execute
-# the first set of double-colon rules, so remove it if not needed.
-# If there is a colon in the path, we need to keep it.
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[ 	]*VPATH[ 	]*=[^:]*$/d'
-fi
-
-trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15
-
-# Transform confdefs.h into DEFS.
-# Protect against shell expansion while executing Makefile rules.
-# Protect against Makefile macro expansion.
-cat > conftest.defs <<\EOF
-s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%-D\1=\2%g
-s%[ 	`~#$^&*(){}\\|;'"<>?]%\\&%g
-s%\[%\\&%g
-s%\]%\\&%g
-s%\$%$$%g
-EOF
-DEFS=`sed -f conftest.defs confdefs.h | tr '\012' ' '`
-rm -f conftest.defs
-
-
-# Without the "./", some shells look in PATH for config.status.
-: ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS </dev/null | sed 1q`:
-#
-# $0 $ac_configure_args
-#
-# Compiler output produced by configure, useful for debugging
-# configure, is in ./config.log if it exists.
-
-ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
-for ac_option
-do
-  case "\$ac_option" in
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion"
-    exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;;
-  -version | --version | --versio | --versi | --vers | --ver | --ve | --v)
-    echo "$CONFIG_STATUS generated by autoconf version 2.13"
-    exit 0 ;;
-  -help | --help | --hel | --he | --h)
-    echo "\$ac_cs_usage"; exit 0 ;;
-  *) echo "\$ac_cs_usage"; exit 1 ;;
-  esac
-done
-
-ac_given_srcdir=$srcdir
-
-trap 'rm -fr `echo "Makefile" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15
-EOF
-cat >> $CONFIG_STATUS < conftest.subs <<\\CEOF
-$ac_vpsub
-$extrasub
-s%@SHELL@%$SHELL%g
-s%@CFLAGS@%$CFLAGS%g
-s%@CPPFLAGS@%$CPPFLAGS%g
-s%@CXXFLAGS@%$CXXFLAGS%g
-s%@FFLAGS@%$FFLAGS%g
-s%@DEFS@%$DEFS%g
-s%@LDFLAGS@%$LDFLAGS%g
-s%@LIBS@%$LIBS%g
-s%@exec_prefix@%$exec_prefix%g
-s%@prefix@%$prefix%g
-s%@program_transform_name@%$program_transform_name%g
-s%@bindir@%$bindir%g
-s%@sbindir@%$sbindir%g
-s%@libexecdir@%$libexecdir%g
-s%@datadir@%$datadir%g
-s%@sysconfdir@%$sysconfdir%g
-s%@sharedstatedir@%$sharedstatedir%g
-s%@localstatedir@%$localstatedir%g
-s%@libdir@%$libdir%g
-s%@includedir@%$includedir%g
-s%@oldincludedir@%$oldincludedir%g
-s%@infodir@%$infodir%g
-s%@mandir@%$mandir%g
-s%@CC@%$CC%g
-s%@LIBTOOL@%$LIBTOOL%g
-s%@AR@%$AR%g
-s%@RANLIB@%$RANLIB%g
-s%@SET_MAKE@%$SET_MAKE%g
-s%@CPP@%$CPP%g
-
-CEOF
-EOF
-
-cat >> $CONFIG_STATUS <<\EOF
-
-# Split the substitutions into bite-sized pieces for seds with
-# small command number limits, like on Digital OSF/1 and HP-UX.
-ac_max_sed_cmds=90 # Maximum number of lines to put in a sed script.
-ac_file=1 # Number of current file.
-ac_beg=1 # First line for current file.
-ac_end=$ac_max_sed_cmds # Line after last line for current file.
-ac_more_lines=:
-ac_sed_cmds=""
-while $ac_more_lines; do
-  if test $ac_beg -gt 1; then
-    sed "1,${ac_beg}d; ${ac_end}q" conftest.subs > conftest.s$ac_file
-  else
-    sed "${ac_end}q" conftest.subs > conftest.s$ac_file
-  fi
-  if test ! -s conftest.s$ac_file; then
-    ac_more_lines=false
-    rm -f conftest.s$ac_file
-  else
-    if test -z "$ac_sed_cmds"; then
-      ac_sed_cmds="sed -f conftest.s$ac_file"
-    else
-      ac_sed_cmds="$ac_sed_cmds | sed -f conftest.s$ac_file"
-    fi
-    ac_file=`expr $ac_file + 1`
-    ac_beg=$ac_end
-    ac_end=`expr $ac_end + $ac_max_sed_cmds`
-  fi
-done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
-fi
-EOF
-
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case "$ac_file" in
-  *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
-       ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
-  *) ac_file_in="${ac_file}.in" ;;
-  esac
-
-  # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
-
-  # Remove last slash and all that follows it.  Not all systems have dirname.
-  ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
-  if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
-    # The file is in a subdirectory.
-    test ! -d "$ac_dir" && mkdir "$ac_dir"
-    ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`"
-    # A "../" for each directory in $ac_dir_suffix.
-    ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'`
-  else
-    ac_dir_suffix= ac_dots=
-  fi
-
-  case "$ac_given_srcdir" in
-  .)  srcdir=.
-      if test -z "$ac_dots"; then top_srcdir=.
-      else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;;
-  /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;;
-  *) # Relative path.
-    srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix"
-    top_srcdir="$ac_dots$ac_given_srcdir" ;;
-  esac
-
-
-  echo creating "$ac_file"
-  rm -f "$ac_file"
-  configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure."
-  case "$ac_file" in
-  *Makefile*) ac_comsub="1i\\
-# $configure_input" ;;
-  *) ac_comsub= ;;
-  esac
-
-  ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
-  sed -e "$ac_comsub
-s%@configure_input@%$configure_input%g
-s%@srcdir@%$srcdir%g
-s%@top_srcdir@%$top_srcdir%g
-" $ac_file_inputs | (eval "$ac_sed_cmds") > $ac_file
-fi; done
-rm -f conftest.s*
-
-EOF
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
-chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
-
diff --git a/contrib/libf2c/libF77/configure.in b/contrib/libf2c/libF77/configure.in
deleted file mode 100644
index b9f0f222fd7..00000000000
--- a/contrib/libf2c/libF77/configure.in
+++ /dev/null
@@ -1,111 +0,0 @@
-# Process this file with autoconf to produce a configure script.
-#   Copyright (C) 1995, 1997, 1998, 2001 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of GNU Fortran.
-#
-#GNU Fortran is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-AC_PREREQ(2.13)
-AC_INIT(getarg_.c)
-
-dnl Checks for programs.
-
-dnl FIXME AC_PROG_CC wants CC to be able to link things, but it may
-dnl not be able to.
-define([AC_PROG_CC_WORKS],[])
-
-# For g77 we'll set CC to point at the built gcc, but this will get it into
-# the makefiles
-AC_PROG_CC
-
-LIBTOOL='$(SHELL) ../libtool'
-AC_SUBST(LIBTOOL)
-
-test "$AR" || AR=ar
-AC_SUBST(AR)
-if test "$RANLIB"; then :
-  AC_SUBST(RANLIB)
-else
-  AC_PROG_RANLIB
-fi
-AC_PROG_MAKE_SET
-
-dnl Checks for libraries.
-
-dnl Checks for header files.
-# Sanity check for the cross-compilation case:
-AC_CHECK_HEADER(stdio.h,:,
-  [AC_MSG_ERROR([Can't find stdio.h.
-You must have a usable C system for the target already installed, at least
-including headers and, preferably, the library, before you can configure
-the G77 runtime system.  If necessary, install gcc now with \`LANGUAGES=c',
-then the target library, then build with \`LANGUAGES=f77'.])])
-
-AC_HEADER_STDC
-AC_MSG_CHECKING(for posix)
-AC_CACHE_VAL(g77_cv_header_posix,
-  AC_EGREP_CPP(yes,
-  [#include 
-#include 
-#ifdef _POSIX_VERSION
-  yes
-#endif
-], 
-  g77_cv_header_posix=yes,
-  g77_cv_header_posix=no))
-AC_MSG_RESULT($g77_cv_header_posix)
-
-# We can rely on the GNU library being posix-ish.  I guess checking the 
-# header isn't actually like checking the functions, though...
-AC_MSG_CHECKING(for GNU library)
-AC_CACHE_VAL(g77_cv_lib_gnu,
-  AC_EGREP_CPP(yes,
-    [#include 
-#ifdef __GNU_LIBRARY__
-  yes
-#endif
-], 
-  g77_cv_lib_gnu=yes, g77_cv_lib_gnu=no))
-AC_MSG_RESULT($g77_cv_lib_gnu)
-
-dnl Checks for library functions.
-AC_TYPE_SIGNAL
-# we'll get atexit by default
-if test $ac_cv_header_stdc != yes; then
-AC_CHECK_FUNC(atexit,
-  AC_DEFINE(onexit,atexit),dnl just in case
-  [AC_DEFINE(NO_ONEXIT)
-  AC_CHECK_FUNC(onexit,,
-    [AC_CHECK_FUNC(on_exit,
-     AC_DEFINE(onexit,on_exit),)])])
-else true
-fi
-
-dnl perhaps should check also for remainder
-dnl Unfortunately, the message implies we're just checking for -lm...
-AC_CHECK_LIB(m,drem,AC_DEFINE(IEEE_drem))
-
-AC_DEFINE(Skip_f2c_Undefs)
-AC_DEFINE(IEEE_COMPLEX_DIVIDE)
-
-AC_OUTPUT(Makefile)
-
-dnl Local Variables:
-dnl comment-start: "dnl "
-dnl comment-end: ""
-dnl comment-start-skip: "\\bdnl\\b\\s *"
-dnl End:
diff --git a/contrib/libf2c/libF77/d_abs.c b/contrib/libf2c/libF77/d_abs.c
deleted file mode 100644
index a43a5c7f0a8..00000000000
--- a/contrib/libf2c/libF77/d_abs.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-double
-d_abs (doublereal * x)
-{
-  if (*x >= 0)
-    return (*x);
-  return (-*x);
-}
diff --git a/contrib/libf2c/libF77/d_acos.c b/contrib/libf2c/libF77/d_acos.c
deleted file mode 100644
index 41c4f172c65..00000000000
--- a/contrib/libf2c/libF77/d_acos.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_acos (doublereal * x)
-{
-  return (acos (*x));
-}
diff --git a/contrib/libf2c/libF77/d_asin.c b/contrib/libf2c/libF77/d_asin.c
deleted file mode 100644
index 65603891501..00000000000
--- a/contrib/libf2c/libF77/d_asin.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_asin (doublereal * x)
-{
-  return (asin (*x));
-}
diff --git a/contrib/libf2c/libF77/d_atan.c b/contrib/libf2c/libF77/d_atan.c
deleted file mode 100644
index e25fa2e4177..00000000000
--- a/contrib/libf2c/libF77/d_atan.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_atan (doublereal * x)
-{
-  return (atan (*x));
-}
diff --git a/contrib/libf2c/libF77/d_atn2.c b/contrib/libf2c/libF77/d_atn2.c
deleted file mode 100644
index e0b217863a5..00000000000
--- a/contrib/libf2c/libF77/d_atn2.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_atn2 (doublereal * x, doublereal * y)
-{
-  return (atan2 (*x, *y));
-}
diff --git a/contrib/libf2c/libF77/d_cnjg.c b/contrib/libf2c/libF77/d_cnjg.c
deleted file mode 100644
index bc46ae69598..00000000000
--- a/contrib/libf2c/libF77/d_cnjg.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-void
-d_cnjg (doublecomplex * r, doublecomplex * z)
-{
-  doublereal zi = z->i;
-  r->r = z->r;
-  r->i = -zi;
-}
diff --git a/contrib/libf2c/libF77/d_cos.c b/contrib/libf2c/libF77/d_cos.c
deleted file mode 100644
index 010db6b5421..00000000000
--- a/contrib/libf2c/libF77/d_cos.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_cos (doublereal * x)
-{
-  return (cos (*x));
-}
diff --git a/contrib/libf2c/libF77/d_cosh.c b/contrib/libf2c/libF77/d_cosh.c
deleted file mode 100644
index 00938bda13e..00000000000
--- a/contrib/libf2c/libF77/d_cosh.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_cosh (doublereal * x)
-{
-  return (cosh (*x));
-}
diff --git a/contrib/libf2c/libF77/d_dim.c b/contrib/libf2c/libF77/d_dim.c
deleted file mode 100644
index a4274ca6859..00000000000
--- a/contrib/libf2c/libF77/d_dim.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-double
-d_dim (doublereal * a, doublereal * b)
-{
-  return (*a > *b ? *a - *b : 0);
-}
diff --git a/contrib/libf2c/libF77/d_exp.c b/contrib/libf2c/libF77/d_exp.c
deleted file mode 100644
index 7b4f3e529c4..00000000000
--- a/contrib/libf2c/libF77/d_exp.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_exp (doublereal * x)
-{
-  return (exp (*x));
-}
diff --git a/contrib/libf2c/libF77/d_imag.c b/contrib/libf2c/libF77/d_imag.c
deleted file mode 100644
index cc937644b75..00000000000
--- a/contrib/libf2c/libF77/d_imag.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-double
-d_imag (doublecomplex * z)
-{
-  return (z->i);
-}
diff --git a/contrib/libf2c/libF77/d_int.c b/contrib/libf2c/libF77/d_int.c
deleted file mode 100644
index f7ab8b0cb6a..00000000000
--- a/contrib/libf2c/libF77/d_int.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_int (doublereal * x)
-{
-  return ((*x > 0) ? floor (*x) : -floor (-*x));
-}
diff --git a/contrib/libf2c/libF77/d_lg10.c b/contrib/libf2c/libF77/d_lg10.c
deleted file mode 100644
index d0f86e554d0..00000000000
--- a/contrib/libf2c/libF77/d_lg10.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "f2c.h"
-
-#define log10e 0.43429448190325182765
-
-#undef abs
-#include 
-double
-d_lg10 (doublereal * x)
-{
-  return (log10e * log (*x));
-}
diff --git a/contrib/libf2c/libF77/d_log.c b/contrib/libf2c/libF77/d_log.c
deleted file mode 100644
index 95dc767fb2a..00000000000
--- a/contrib/libf2c/libF77/d_log.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_log (doublereal * x)
-{
-  return (log (*x));
-}
diff --git a/contrib/libf2c/libF77/d_mod.c b/contrib/libf2c/libF77/d_mod.c
deleted file mode 100644
index 15cedefadd1..00000000000
--- a/contrib/libf2c/libF77/d_mod.c
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "f2c.h"
-
-#ifdef IEEE_drem
-double drem (double, double);
-#else
-#undef abs
-#include 
-#endif
-double
-d_mod (doublereal * x, doublereal * y)
-{
-#ifdef IEEE_drem
-  double xa, ya, z;
-  if ((ya = *y) < 0.)
-    ya = -ya;
-  z = drem (xa = *x, ya);
-  if (xa > 0)
-    {
-      if (z < 0)
-	z += ya;
-    }
-  else if (z > 0)
-    z -= ya;
-  return z;
-#else
-  double quotient;
-  if ((quotient = *x / *y) >= 0)
-    quotient = floor (quotient);
-  else
-    quotient = -floor (-quotient);
-  return (*x - (*y) * quotient);
-#endif
-}
diff --git a/contrib/libf2c/libF77/d_nint.c b/contrib/libf2c/libF77/d_nint.c
deleted file mode 100644
index 8be42758644..00000000000
--- a/contrib/libf2c/libF77/d_nint.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_nint (doublereal * x)
-{
-  return ((*x) >= 0 ? floor (*x + .5) : -floor (.5 - *x));
-}
diff --git a/contrib/libf2c/libF77/d_prod.c b/contrib/libf2c/libF77/d_prod.c
deleted file mode 100644
index 11fe2c7f68e..00000000000
--- a/contrib/libf2c/libF77/d_prod.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-double
-d_prod (real * x, real * y)
-{
-  return ((*x) * (*y));
-}
diff --git a/contrib/libf2c/libF77/d_sign.c b/contrib/libf2c/libF77/d_sign.c
deleted file mode 100644
index da8d24ba7a1..00000000000
--- a/contrib/libf2c/libF77/d_sign.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-double
-d_sign (doublereal * a, doublereal * b)
-{
-  double x;
-  x = (*a >= 0 ? *a : -*a);
-  return (*b >= 0 ? x : -x);
-}
diff --git a/contrib/libf2c/libF77/d_sin.c b/contrib/libf2c/libF77/d_sin.c
deleted file mode 100644
index 24b37a439e5..00000000000
--- a/contrib/libf2c/libF77/d_sin.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_sin (doublereal * x)
-{
-  return (sin (*x));
-}
diff --git a/contrib/libf2c/libF77/d_sinh.c b/contrib/libf2c/libF77/d_sinh.c
deleted file mode 100644
index dc9dc439073..00000000000
--- a/contrib/libf2c/libF77/d_sinh.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_sinh (doublereal * x)
-{
-  return (sinh (*x));
-}
diff --git a/contrib/libf2c/libF77/d_sqrt.c b/contrib/libf2c/libF77/d_sqrt.c
deleted file mode 100644
index 0a458823318..00000000000
--- a/contrib/libf2c/libF77/d_sqrt.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_sqrt (doublereal * x)
-{
-  return (sqrt (*x));
-}
diff --git a/contrib/libf2c/libF77/d_tan.c b/contrib/libf2c/libF77/d_tan.c
deleted file mode 100644
index 370c1b85fef..00000000000
--- a/contrib/libf2c/libF77/d_tan.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_tan (doublereal * x)
-{
-  return (tan (*x));
-}
diff --git a/contrib/libf2c/libF77/d_tanh.c b/contrib/libf2c/libF77/d_tanh.c
deleted file mode 100644
index df81ea0df22..00000000000
--- a/contrib/libf2c/libF77/d_tanh.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-d_tanh (doublereal * x)
-{
-  return (tanh (*x));
-}
diff --git a/contrib/libf2c/libF77/derf_.c b/contrib/libf2c/libF77/derf_.c
deleted file mode 100644
index b78fde0e9b4..00000000000
--- a/contrib/libf2c/libF77/derf_.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern double erf (double);
-double
-G77_derf_0 (doublereal * x)
-{
-  return (erf (*x));
-}
diff --git a/contrib/libf2c/libF77/derfc_.c b/contrib/libf2c/libF77/derfc_.c
deleted file mode 100644
index 78e8e889c38..00000000000
--- a/contrib/libf2c/libF77/derfc_.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-extern double erfc (double);
-
-double
-G77_derfc_0 (doublereal * x)
-{
-  return (erfc (*x));
-}
diff --git a/contrib/libf2c/libF77/dtime_.c b/contrib/libf2c/libF77/dtime_.c
deleted file mode 100644
index e2ea1c6b5d6..00000000000
--- a/contrib/libf2c/libF77/dtime_.c
+++ /dev/null
@@ -1,49 +0,0 @@
-#include "time.h"
-
-#ifdef MSDOS
-#undef USE_CLOCK
-#define USE_CLOCK
-#endif
-
-#ifndef USE_CLOCK
-#define _INCLUDE_POSIX_SOURCE	/* for HP-UX */
-#define _INCLUDE_XOPEN_SOURCE	/* for HP-UX */
-#include "sys/types.h"
-#include "sys/times.h"
-#endif
-
-#undef Hz
-#ifdef CLK_TCK
-#define Hz CLK_TCK
-#else
-#ifdef HZ
-#define Hz HZ
-#else
-#define Hz 60
-#endif
-#endif
-
-double
-dtime_ (float *tarray)
-{
-#ifdef USE_CLOCK
-#ifndef CLOCKS_PER_SECOND
-#define CLOCKS_PER_SECOND Hz
-#endif
-  static double t0;
-  double t = clock ();
-  tarray[1] = 0;
-  tarray[0] = (t - t0) / CLOCKS_PER_SECOND;
-  t0 = t;
-  return tarray[0];
-#else
-  struct tms t;
-  static struct tms t0;
-
-  times (&t);
-  tarray[0] = (double) (t.tms_utime - t0.tms_utime) / Hz;
-  tarray[1] = (double) (t.tms_stime - t0.tms_stime) / Hz;
-  t0 = t;
-  return tarray[0] + tarray[1];
-#endif
-}
diff --git a/contrib/libf2c/libF77/ef1asc_.c b/contrib/libf2c/libF77/ef1asc_.c
deleted file mode 100644
index d9bea344e4f..00000000000
--- a/contrib/libf2c/libF77/ef1asc_.c
+++ /dev/null
@@ -1,15 +0,0 @@
-/* EFL support routine to copy string b to string a */
-
-#include "f2c.h"
-
-
-#define M	( (long) (sizeof(long) - 1) )
-#define EVEN(x)	( ( (x)+ M) & (~M) )
-
-extern void s_copy (char *, char *, ftnlen, ftnlen);
-int
-G77_ef1asc_0 (ftnint * a, ftnlen * la, ftnint * b, ftnlen * lb)
-{
-  s_copy ((char *) a, (char *) b, EVEN (*la), *lb);
-  return 0;			/* ignored return value */
-}
diff --git a/contrib/libf2c/libF77/ef1cmc_.c b/contrib/libf2c/libF77/ef1cmc_.c
deleted file mode 100644
index 2e102fb6b5d..00000000000
--- a/contrib/libf2c/libF77/ef1cmc_.c
+++ /dev/null
@@ -1,10 +0,0 @@
-/* EFL support routine to compare two character strings */
-
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-integer
-G77_ef1cmc_0 (ftnint * a, ftnlen * la, ftnint * b, ftnlen * lb)
-{
-  return (s_cmp ((char *) a, (char *) b, *la, *lb));
-}
diff --git a/contrib/libf2c/libF77/erf_.c b/contrib/libf2c/libF77/erf_.c
deleted file mode 100644
index fadbfaf038a..00000000000
--- a/contrib/libf2c/libF77/erf_.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern double erf (double);
-double
-G77_erf_0 (real * x)
-{
-  return (erf (*x));
-}
diff --git a/contrib/libf2c/libF77/erfc_.c b/contrib/libf2c/libF77/erfc_.c
deleted file mode 100644
index 7f3ff8a5dbd..00000000000
--- a/contrib/libf2c/libF77/erfc_.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern double erfc (double);
-double
-G77_erfc_0 (real * x)
-{
-  return (erfc (*x));
-}
diff --git a/contrib/libf2c/libF77/etime_.c b/contrib/libf2c/libF77/etime_.c
deleted file mode 100644
index cc64612c8d9..00000000000
--- a/contrib/libf2c/libF77/etime_.c
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "time.h"
-
-#ifdef MSDOS
-#undef USE_CLOCK
-#define USE_CLOCK
-#endif
-
-#ifndef USE_CLOCK
-#define _INCLUDE_POSIX_SOURCE	/* for HP-UX */
-#define _INCLUDE_XOPEN_SOURCE	/* for HP-UX */
-#include "sys/types.h"
-#include "sys/times.h"
-#endif
-
-#undef Hz
-#ifdef CLK_TCK
-#define Hz CLK_TCK
-#else
-#ifdef HZ
-#define Hz HZ
-#else
-#define Hz 60
-#endif
-#endif
-
-double
-etime_ (float *tarray)
-{
-#ifdef USE_CLOCK
-#ifndef CLOCKS_PER_SECOND
-#define CLOCKS_PER_SECOND Hz
-#endif
-  double t = clock ();
-  tarray[1] = 0;
-  return tarray[0] = t / CLOCKS_PER_SECOND;
-#else
-  struct tms t;
-
-  times (&t);
-  return (tarray[0] = (double) t.tms_utime / Hz)
-    + (tarray[1] = (double) t.tms_stime / Hz);
-#endif
-}
diff --git a/contrib/libf2c/libF77/exit_.c b/contrib/libf2c/libF77/exit_.c
deleted file mode 100644
index adf3d859274..00000000000
--- a/contrib/libf2c/libF77/exit_.c
+++ /dev/null
@@ -1,25 +0,0 @@
-/* This gives the effect of
-
-	subroutine exit(rc)
-	integer*4 rc
-	stop
-	end
-
- * with the added side effect of supplying rc as the program's exit code.
- */
-
-#include "f2c.h"
-#undef abs
-#undef min
-#undef max
-#include 
-extern void f_exit (void);
-
-void
-G77_exit_0 (integer * rc)
-{
-#ifdef NO_ONEXIT
-  f_exit ();
-#endif
-  exit (*rc);
-}
diff --git a/contrib/libf2c/libF77/f2ch.add b/contrib/libf2c/libF77/f2ch.add
deleted file mode 100644
index 04b13e8de5d..00000000000
--- a/contrib/libf2c/libF77/f2ch.add
+++ /dev/null
@@ -1,163 +0,0 @@
-/* If you are using a C++ compiler, append the following to f2c.h
-   for compiling libF77 and libI77. */
-
-#ifdef __cplusplus
-extern "C"
-{
-  extern int abort_ (void);
-  extern double c_abs (complex *);
-  extern void c_cos (complex *, complex *);
-  extern void c_div (complex *, complex *, complex *);
-  extern void c_exp (complex *, complex *);
-  extern void c_log (complex *, complex *);
-  extern void c_sin (complex *, complex *);
-  extern void c_sqrt (complex *, complex *);
-  extern double d_abs (double *);
-  extern double d_acos (double *);
-  extern double d_asin (double *);
-  extern double d_atan (double *);
-  extern double d_atn2 (double *, double *);
-  extern void d_cnjg (doublecomplex *, doublecomplex *);
-  extern double d_cos (double *);
-  extern double d_cosh (double *);
-  extern double d_dim (double *, double *);
-  extern double d_exp (double *);
-  extern double d_imag (doublecomplex *);
-  extern double d_int (double *);
-  extern double d_lg10 (double *);
-  extern double d_log (double *);
-  extern double d_mod (double *, double *);
-  extern double d_nint (double *);
-  extern double d_prod (float *, float *);
-  extern double d_sign (double *, double *);
-  extern double d_sin (double *);
-  extern double d_sinh (double *);
-  extern double d_sqrt (double *);
-  extern double d_tan (double *);
-  extern double d_tanh (double *);
-  extern double derf_ (double *);
-  extern double derfc_ (double *);
-  extern integer do_fio (ftnint *, char *, ftnlen);
-  extern integer do_lio (ftnint *, ftnint *, char *, ftnlen);
-  extern integer do_uio (ftnint *, char *, ftnlen);
-  extern integer e_rdfe (void);
-  extern integer e_rdue (void);
-  extern integer e_rsfe (void);
-  extern integer e_rsfi (void);
-  extern integer e_rsle (void);
-  extern integer e_rsli (void);
-  extern integer e_rsue (void);
-  extern integer e_wdfe (void);
-  extern integer e_wdue (void);
-  extern integer e_wsfe (void);
-  extern integer e_wsfi (void);
-  extern integer e_wsle (void);
-  extern integer e_wsli (void);
-  extern integer e_wsue (void);
-  extern int ef1asc_ (ftnint *, ftnlen *, ftnint *, ftnlen *);
-  extern integer ef1cmc_ (ftnint *, ftnlen *, ftnint *, ftnlen *);
-  extern double erf (double);
-  extern double erf_ (float *);
-  extern double erfc (double);
-  extern double erfc_ (float *);
-  extern integer f_back (alist *);
-  extern integer f_clos (cllist *);
-  extern integer f_end (alist *);
-  extern void f_exit (void);
-  extern integer f_inqu (inlist *);
-  extern integer f_open (olist *);
-  extern integer f_rew (alist *);
-  extern int flush_ (void);
-  extern void getarg_ (integer *, char *, ftnlen);
-  extern void getenv_ (char *, char *, ftnlen, ftnlen);
-  extern short h_abs (short *);
-  extern short h_dim (short *, short *);
-  extern short h_dnnt (double *);
-  extern short h_indx (char *, char *, ftnlen, ftnlen);
-  extern short h_len (char *, ftnlen);
-  extern short h_mod (short *, short *);
-  extern short h_nint (float *);
-  extern short h_sign (short *, short *);
-  extern short hl_ge (char *, char *, ftnlen, ftnlen);
-  extern short hl_gt (char *, char *, ftnlen, ftnlen);
-  extern short hl_le (char *, char *, ftnlen, ftnlen);
-  extern short hl_lt (char *, char *, ftnlen, ftnlen);
-  extern integer i_abs (integer *);
-  extern integer i_dim (integer *, integer *);
-  extern integer i_dnnt (double *);
-  extern integer i_indx (char *, char *, ftnlen, ftnlen);
-  extern integer i_len (char *, ftnlen);
-  extern integer i_mod (integer *, integer *);
-  extern integer i_nint (float *);
-  extern integer i_sign (integer *, integer *);
-  extern integer iargc_ (void);
-  extern ftnlen l_ge (char *, char *, ftnlen, ftnlen);
-  extern ftnlen l_gt (char *, char *, ftnlen, ftnlen);
-  extern ftnlen l_le (char *, char *, ftnlen, ftnlen);
-  extern ftnlen l_lt (char *, char *, ftnlen, ftnlen);
-  extern void pow_ci (complex *, complex *, integer *);
-  extern double pow_dd (double *, double *);
-  extern double pow_di (double *, integer *);
-  extern short pow_hh (short *, shortint *);
-  extern integer pow_ii (integer *, integer *);
-  extern double pow_ri (float *, integer *);
-  extern void pow_zi (doublecomplex *, doublecomplex *, integer *);
-  extern void pow_zz (doublecomplex *, doublecomplex *, doublecomplex *);
-  extern double r_abs (float *);
-  extern double r_acos (float *);
-  extern double r_asin (float *);
-  extern double r_atan (float *);
-  extern double r_atn2 (float *, float *);
-  extern void r_cnjg (complex *, complex *);
-  extern double r_cos (float *);
-  extern double r_cosh (float *);
-  extern double r_dim (float *, float *);
-  extern double r_exp (float *);
-  extern double r_imag (complex *);
-  extern double r_int (float *);
-  extern double r_lg10 (float *);
-  extern double r_log (float *);
-  extern double r_mod (float *, float *);
-  extern double r_nint (float *);
-  extern double r_sign (float *, float *);
-  extern double r_sin (float *);
-  extern double r_sinh (float *);
-  extern double r_sqrt (float *);
-  extern double r_tan (float *);
-  extern double r_tanh (float *);
-  extern void s_cat (char *, char **, integer *, integer *, ftnlen);
-  extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-  extern void s_copy (char *, char *, ftnlen, ftnlen);
-  extern int s_paus (char *, ftnlen);
-  extern integer s_rdfe (cilist *);
-  extern integer s_rdue (cilist *);
-  extern integer s_rnge (char *, integer, char *, integer);
-  extern integer s_rsfe (cilist *);
-  extern integer s_rsfi (icilist *);
-  extern integer s_rsle (cilist *);
-  extern integer s_rsli (icilist *);
-  extern integer s_rsne (cilist *);
-  extern integer s_rsni (icilist *);
-  extern integer s_rsue (cilist *);
-  extern int s_stop (char *, ftnlen);
-  extern integer s_wdfe (cilist *);
-  extern integer s_wdue (cilist *);
-  extern integer s_wsfe (cilist *);
-  extern integer s_wsfi (icilist *);
-  extern integer s_wsle (cilist *);
-  extern integer s_wsli (icilist *);
-  extern integer s_wsne (cilist *);
-  extern integer s_wsni (icilist *);
-  extern integer s_wsue (cilist *);
-  extern void sig_die (char *, int);
-  extern integer signal_ (integer *, void (*)(int));
-  extern integer system_ (char *, ftnlen);
-  extern double z_abs (doublecomplex *);
-  extern void z_cos (doublecomplex *, doublecomplex *);
-  extern void z_div (doublecomplex *, doublecomplex *, doublecomplex *);
-  extern void z_exp (doublecomplex *, doublecomplex *);
-  extern void z_log (doublecomplex *, doublecomplex *);
-  extern void z_sin (doublecomplex *, doublecomplex *);
-  extern void z_sqrt (doublecomplex *, doublecomplex *);
-}
-#endif
diff --git a/contrib/libf2c/libF77/getarg_.c b/contrib/libf2c/libF77/getarg_.c
deleted file mode 100644
index b35043b4a48..00000000000
--- a/contrib/libf2c/libF77/getarg_.c
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "f2c.h"
-
-/*
- * subroutine getarg(k, c)
- * returns the kth unix command argument in fortran character
- * variable argument c
-*/
-
-void
-G77_getarg_0 (ftnint * n, register char *s, ftnlen ls)
-{
-  extern int f__xargc;
-  extern char **f__xargv;
-  register char *t;
-  register int i;
-
-  if (*n >= 0 && *n < f__xargc)
-    t = f__xargv[*n];
-  else
-    t = "";
-  for (i = 0; i < ls && *t != '\0'; ++i)
-    *s++ = *t++;
-  for (; i < ls; ++i)
-    *s++ = ' ';
-}
diff --git a/contrib/libf2c/libF77/getenv_.c b/contrib/libf2c/libF77/getenv_.c
deleted file mode 100644
index 4067b8ce214..00000000000
--- a/contrib/libf2c/libF77/getenv_.c
+++ /dev/null
@@ -1,49 +0,0 @@
-#include "f2c.h"
-#undef abs
-#include 
-#include 
-extern char *F77_aloc (ftnlen, char *);
-
-/*
- * getenv - f77 subroutine to return environment variables
- *
- * called by:
- *	call getenv (ENV_NAME, char_var)
- * where:
- *	ENV_NAME is the name of an environment variable
- *	char_var is a character variable which will receive
- *		the current value of ENV_NAME, or all blanks
- *		if ENV_NAME is not defined
- */
-
-void
-G77_getenv_0 (char *fname, char *value, ftnlen flen, ftnlen vlen)
-{
-  char buf[256], *ep, *fp;
-  integer i;
-
-  if (flen <= 0)
-    goto add_blanks;
-  for (i = 0; i < (integer) sizeof (buf); i++)
-    {
-      if (i == flen || (buf[i] = fname[i]) == ' ')
-	{
-	  buf[i] = 0;
-	  ep = getenv (buf);
-	  goto have_ep;
-	}
-    }
-  while (i < flen && fname[i] != ' ')
-    i++;
-  strncpy (fp = F77_aloc (i + 1, "getenv_"), fname, (int) i);
-  fp[i] = 0;
-  ep = getenv (fp);
-  free (fp);
-have_ep:
-  if (ep)
-    while (*ep && vlen-- > 0)
-      *value++ = *ep++;
-add_blanks:
-  while (vlen-- > 0)
-    *value++ = ' ';
-}
diff --git a/contrib/libf2c/libF77/h_abs.c b/contrib/libf2c/libF77/h_abs.c
deleted file mode 100644
index 9db19ca34e9..00000000000
--- a/contrib/libf2c/libF77/h_abs.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-shortint
-h_abs (shortint * x)
-{
-  if (*x >= 0)
-    return (*x);
-  return (-*x);
-}
diff --git a/contrib/libf2c/libF77/h_dim.c b/contrib/libf2c/libF77/h_dim.c
deleted file mode 100644
index 1519478747d..00000000000
--- a/contrib/libf2c/libF77/h_dim.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-shortint
-h_dim (shortint * a, shortint * b)
-{
-  return (*a > *b ? *a - *b : 0);
-}
diff --git a/contrib/libf2c/libF77/h_dnnt.c b/contrib/libf2c/libF77/h_dnnt.c
deleted file mode 100644
index 46c83bbd28e..00000000000
--- a/contrib/libf2c/libF77/h_dnnt.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-shortint
-h_dnnt (doublereal * x)
-{
-  return (shortint) (*x >= 0. ? floor (*x + .5) : -floor (.5 - *x));
-}
diff --git a/contrib/libf2c/libF77/h_indx.c b/contrib/libf2c/libF77/h_indx.c
deleted file mode 100644
index 2353b2b143a..00000000000
--- a/contrib/libf2c/libF77/h_indx.c
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "f2c.h"
-
-shortint
-h_indx (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  ftnlen i, n;
-  char *s, *t, *bend;
-
-  n = la - lb + 1;
-  bend = b + lb;
-
-  for (i = 0; i < n; ++i)
-    {
-      s = a + i;
-      t = b;
-      while (t < bend)
-	if (*s++ != *t++)
-	  goto no;
-      return ((shortint) i + 1);
-    no:;
-    }
-  return (0);
-}
diff --git a/contrib/libf2c/libF77/h_len.c b/contrib/libf2c/libF77/h_len.c
deleted file mode 100644
index 506016e67d9..00000000000
--- a/contrib/libf2c/libF77/h_len.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-shortint
-h_len (char *s __attribute__ ((__unused__)), ftnlen n)
-{
-  return (n);
-}
diff --git a/contrib/libf2c/libF77/h_mod.c b/contrib/libf2c/libF77/h_mod.c
deleted file mode 100644
index c04e0df823b..00000000000
--- a/contrib/libf2c/libF77/h_mod.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-shortint
-h_mod (short *a, short *b)
-{
-  return (*a % *b);
-}
diff --git a/contrib/libf2c/libF77/h_nint.c b/contrib/libf2c/libF77/h_nint.c
deleted file mode 100644
index a8c366a41be..00000000000
--- a/contrib/libf2c/libF77/h_nint.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-shortint
-h_nint (real * x)
-{
-  return (shortint) (*x >= 0 ? floor (*x + .5) : -floor (.5 - *x));
-}
diff --git a/contrib/libf2c/libF77/h_sign.c b/contrib/libf2c/libF77/h_sign.c
deleted file mode 100644
index 70402325be2..00000000000
--- a/contrib/libf2c/libF77/h_sign.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-shortint
-h_sign (shortint * a, shortint * b)
-{
-  shortint x;
-  x = (*a >= 0 ? *a : -*a);
-  return (*b >= 0 ? x : -x);
-}
diff --git a/contrib/libf2c/libF77/hl_ge.c b/contrib/libf2c/libF77/hl_ge.c
deleted file mode 100644
index 988686d8d1d..00000000000
--- a/contrib/libf2c/libF77/hl_ge.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-shortlogical
-hl_ge (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) >= 0);
-}
diff --git a/contrib/libf2c/libF77/hl_gt.c b/contrib/libf2c/libF77/hl_gt.c
deleted file mode 100644
index 0024ca7a0d2..00000000000
--- a/contrib/libf2c/libF77/hl_gt.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-shortlogical
-hl_gt (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) > 0);
-}
diff --git a/contrib/libf2c/libF77/hl_le.c b/contrib/libf2c/libF77/hl_le.c
deleted file mode 100644
index 76aa3e12da7..00000000000
--- a/contrib/libf2c/libF77/hl_le.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-shortlogical
-hl_le (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) <= 0);
-}
diff --git a/contrib/libf2c/libF77/hl_lt.c b/contrib/libf2c/libF77/hl_lt.c
deleted file mode 100644
index 68a47fa98eb..00000000000
--- a/contrib/libf2c/libF77/hl_lt.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-shortlogical
-hl_lt (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) < 0);
-}
diff --git a/contrib/libf2c/libF77/i_abs.c b/contrib/libf2c/libF77/i_abs.c
deleted file mode 100644
index 2ed183a6225..00000000000
--- a/contrib/libf2c/libF77/i_abs.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-integer
-i_abs (integer * x)
-{
-  if (*x >= 0)
-    return (*x);
-  return (-*x);
-}
diff --git a/contrib/libf2c/libF77/i_dim.c b/contrib/libf2c/libF77/i_dim.c
deleted file mode 100644
index 66ef7c99fb4..00000000000
--- a/contrib/libf2c/libF77/i_dim.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-integer
-i_dim (integer * a, integer * b)
-{
-  return (*a > *b ? *a - *b : 0);
-}
diff --git a/contrib/libf2c/libF77/i_dnnt.c b/contrib/libf2c/libF77/i_dnnt.c
deleted file mode 100644
index 7a3783d29e2..00000000000
--- a/contrib/libf2c/libF77/i_dnnt.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-integer
-i_dnnt (doublereal * x)
-{
-  return (integer) (*x >= 0. ? floor (*x + .5) : -floor (.5 - *x));
-}
diff --git a/contrib/libf2c/libF77/i_indx.c b/contrib/libf2c/libF77/i_indx.c
deleted file mode 100644
index 5b8e13693ba..00000000000
--- a/contrib/libf2c/libF77/i_indx.c
+++ /dev/null
@@ -1,23 +0,0 @@
-#include "f2c.h"
-
-integer
-i_indx (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  ftnlen i, n;
-  char *s, *t, *bend;
-
-  n = la - lb + 1;
-  bend = b + lb;
-
-  for (i = 0; i < n; ++i)
-    {
-      s = a + i;
-      t = b;
-      while (t < bend)
-	if (*s++ != *t++)
-	  goto no;
-      return (i + 1);
-    no:;
-    }
-  return (0);
-}
diff --git a/contrib/libf2c/libF77/i_len.c b/contrib/libf2c/libF77/i_len.c
deleted file mode 100644
index 2d5a3a4381a..00000000000
--- a/contrib/libf2c/libF77/i_len.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-integer
-i_len (char *s __attribute__ ((__unused__)), ftnlen n)
-{
-  return (n);
-}
diff --git a/contrib/libf2c/libF77/i_mod.c b/contrib/libf2c/libF77/i_mod.c
deleted file mode 100644
index 7ed7b391c19..00000000000
--- a/contrib/libf2c/libF77/i_mod.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-integer
-i_mod (integer * a, integer * b)
-{
-  return (*a % *b);
-}
diff --git a/contrib/libf2c/libF77/i_nint.c b/contrib/libf2c/libF77/i_nint.c
deleted file mode 100644
index c4eaff48d33..00000000000
--- a/contrib/libf2c/libF77/i_nint.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-integer
-i_nint (real * x)
-{
-  return (integer) (*x >= 0 ? floor (*x + .5) : -floor (.5 - *x));
-}
diff --git a/contrib/libf2c/libF77/i_sign.c b/contrib/libf2c/libF77/i_sign.c
deleted file mode 100644
index cf090086d00..00000000000
--- a/contrib/libf2c/libF77/i_sign.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-integer
-i_sign (integer * a, integer * b)
-{
-  integer x;
-  x = (*a >= 0 ? *a : -*a);
-  return (*b >= 0 ? x : -x);
-}
diff --git a/contrib/libf2c/libF77/iargc_.c b/contrib/libf2c/libF77/iargc_.c
deleted file mode 100644
index c3165709a53..00000000000
--- a/contrib/libf2c/libF77/iargc_.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-ftnint
-G77_iargc_0 (void)
-{
-  extern int f__xargc;
-  return (f__xargc - 1);
-}
diff --git a/contrib/libf2c/libF77/l_ge.c b/contrib/libf2c/libF77/l_ge.c
deleted file mode 100644
index 78af8d04f5e..00000000000
--- a/contrib/libf2c/libF77/l_ge.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-logical
-l_ge (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) >= 0);
-}
diff --git a/contrib/libf2c/libF77/l_gt.c b/contrib/libf2c/libF77/l_gt.c
deleted file mode 100644
index be7e4894719..00000000000
--- a/contrib/libf2c/libF77/l_gt.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-logical
-l_gt (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) > 0);
-}
diff --git a/contrib/libf2c/libF77/l_le.c b/contrib/libf2c/libF77/l_le.c
deleted file mode 100644
index d2886fb7d48..00000000000
--- a/contrib/libf2c/libF77/l_le.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-logical
-l_le (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) <= 0);
-}
diff --git a/contrib/libf2c/libF77/l_lt.c b/contrib/libf2c/libF77/l_lt.c
deleted file mode 100644
index ff151f890a2..00000000000
--- a/contrib/libf2c/libF77/l_lt.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-logical
-l_lt (char *a, char *b, ftnlen la, ftnlen lb)
-{
-  return (s_cmp (a, b, la, lb) < 0);
-}
diff --git a/contrib/libf2c/libF77/lbitbits.c b/contrib/libf2c/libF77/lbitbits.c
deleted file mode 100644
index 3b28ae97aba..00000000000
--- a/contrib/libf2c/libF77/lbitbits.c
+++ /dev/null
@@ -1,58 +0,0 @@
-#include "f2c.h"
-
-#ifndef LONGBITS
-#define LONGBITS 32
-#endif
-
-integer
-lbit_bits (integer a, integer b, integer len)
-{
-  /* Assume 2's complement arithmetic */
-
-  unsigned long x, y;
-
-  x = (unsigned long) a;
-  y = (unsigned long) -1L;
-  x >>= b;
-  y <<= len;
-  return (integer) (x & ~y);
-}
-
-integer
-lbit_cshift (integer a, integer b, integer len)
-{
-  unsigned long x, y, z;
-
-  x = (unsigned long) a;
-  if (len <= 0)
-    {
-      if (len == 0)
-	return 0;
-      goto full_len;
-    }
-  if (len >= LONGBITS)
-    {
-    full_len:
-      if (b >= 0)
-	{
-	  b %= LONGBITS;
-	  return (integer) (x << b | x >> (LONGBITS - b));
-	}
-      b = -b;
-      b %= LONGBITS;
-      return (integer) (x << (LONGBITS - b) | x >> b);
-    }
-  y = z = (unsigned long) -1;
-  y <<= len;
-  z &= ~y;
-  y &= x;
-  x &= z;
-  if (b >= 0)
-    {
-      b %= len;
-      return (integer) (y | (z & (x << b | x >> (len - b))));
-    }
-  b = -b;
-  b %= len;
-  return (integer) (y | (z & (x >> b | x << (len - b))));
-}
diff --git a/contrib/libf2c/libF77/lbitshft.c b/contrib/libf2c/libF77/lbitshft.c
deleted file mode 100644
index bfbb7c01833..00000000000
--- a/contrib/libf2c/libF77/lbitshft.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-integer
-lbit_shift (integer a, integer b)
-{
-  return b >= 0 ? a << b : (integer) ((uinteger) a >> -b);
-}
diff --git a/contrib/libf2c/libF77/main.c b/contrib/libf2c/libF77/main.c
deleted file mode 100644
index a3955cbc1a7..00000000000
--- a/contrib/libf2c/libF77/main.c
+++ /dev/null
@@ -1,35 +0,0 @@
-/* STARTUP PROCEDURE FOR UNIX FORTRAN PROGRAMS */
-
-#include 
-#include "signal1.h"
-
-#include 
-
-extern void f_exit (void);
-#ifndef NO_ONEXIT
-#define ONEXIT atexit
-extern int atexit (void (*)(void));
-#endif
-
-extern void f_init (void);
-extern int MAIN__ (void);
-extern void f_setarg (int, char **);
-extern void f_setsig (void);
-
-int
-main (int argc, char **argv)
-{
-  f_setarg (argc, argv);
-  f_setsig ();
-  f_init ();
-#ifndef NO_ONEXIT
-  ONEXIT (f_exit);
-#endif
-  MAIN__ ();
-#ifdef NO_ONEXIT
-  f_exit ();
-#endif
-  exit (0);			/* exit(0) rather than return(0) to bypass Cray bug */
-  return 0;			/* For compilers that complain of missing return values; */
-  /* others will complain that this is unreachable code. */
-}
diff --git a/contrib/libf2c/libF77/makefile.netlib b/contrib/libf2c/libF77/makefile.netlib
deleted file mode 100644
index 230ca7e9f93..00000000000
--- a/contrib/libf2c/libF77/makefile.netlib
+++ /dev/null
@@ -1,103 +0,0 @@
-.SUFFIXES: .c .o
-CC = cc
-SHELL = /bin/sh
-CFLAGS = -O
-
-# If your system lacks onexit() and you are not using an
-# ANSI C compiler, then you should add -DNO_ONEXIT to CFLAGS,
-# e.g., by changing the above "CFLAGS =" line to
-# CFLAGS = -O -DNO_ONEXIT
-
-# On at least some Sun systems, it is more appropriate to change the
-# "CFLAGS =" line to
-# CFLAGS = -O -Donexit=on_exit
-
-# compile, then strip unnecessary symbols
-.c.o:
-	$(CC) -c -DSkip_f2c_Undefs $(CFLAGS) $*.c
-	ld -r -x -o $*.xxx $*.o
-	mv $*.xxx $*.o
-## Under Solaris (and other systems that do not understand ld -x),
-## omit -x in the ld line above.
-## If your system does not have the ld command, comment out
-## or remove both the ld and mv lines above.
-
-MISC =	F77_aloc.o Version.o main.o s_rnge.o abort_.o getarg_.o iargc_.o \
-	getenv_.o signal_.o s_stop.o s_paus.o system_.o cabs.o\
-	derf_.o derfc_.o erf_.o erfc_.o sig_die.o exit_.o
-POW =	pow_ci.o pow_dd.o pow_di.o pow_hh.o pow_ii.o  pow_ri.o pow_zi.o pow_zz.o
-CX =	c_abs.o c_cos.o c_div.o c_exp.o c_log.o c_sin.o c_sqrt.o
-DCX =	z_abs.o z_cos.o z_div.o z_exp.o z_log.o z_sin.o z_sqrt.o
-REAL =	r_abs.o r_acos.o r_asin.o r_atan.o r_atn2.o r_cnjg.o r_cos.o\
-	r_cosh.o r_dim.o r_exp.o r_imag.o r_int.o\
-	r_lg10.o r_log.o r_mod.o r_nint.o r_sign.o\
-	r_sin.o r_sinh.o r_sqrt.o r_tan.o r_tanh.o
-DBL =	d_abs.o d_acos.o d_asin.o d_atan.o d_atn2.o\
-	d_cnjg.o d_cos.o d_cosh.o d_dim.o d_exp.o\
-	d_imag.o d_int.o d_lg10.o d_log.o d_mod.o\
-	d_nint.o d_prod.o d_sign.o d_sin.o d_sinh.o\
-	d_sqrt.o d_tan.o d_tanh.o
-INT =	i_abs.o i_dim.o i_dnnt.o i_indx.o i_len.o i_mod.o i_nint.o i_sign.o
-HALF =	h_abs.o h_dim.o h_dnnt.o h_indx.o h_len.o h_mod.o  h_nint.o h_sign.o
-CMP =	l_ge.o l_gt.o l_le.o l_lt.o hl_ge.o hl_gt.o hl_le.o hl_lt.o
-EFL =	ef1asc_.o ef1cmc_.o
-CHAR =	F77_aloc.o s_cat.o s_cmp.o s_copy.o
-F90BIT = lbitbits.o lbitshft.o
-QINT =	pow_qq.o qbitbits.o qbitshft.o
-TIME =	dtime_.o etime_.o
-
-all: signal1.h libF77.a
-
-# You may need to adjust signal1.h suitably for your system...
-signal1.h: signal1.h0
-	cp signal1.h0 signal1.h
-
-# If you get an error compiling dtime_.c or etime_.c, try adding
-# -DUSE_CLOCK to the CFLAGS assignment above; if that does not work,
-# omit $(TIME) from the dependency list for libF77.a below.
-
-# For INTEGER*8 support (which requires system-dependent adjustments to
-# f2c.h), add $(QINT) to the libf2c.a dependency list below...
-
-libF77.a : $(MISC) $(POW) $(CX) $(DCX) $(REAL) $(DBL) $(INT) \
-	$(HALF) $(CMP) $(EFL) $(CHAR) $(F90BIT) $(TIME)
-	ar r libF77.a $?
-	-ranlib libF77.a
-
-### If your system lacks ranlib, you don't need it; see README.
-
-Version.o: Version.c
-	$(CC) -c Version.c
-
-# To compile with C++, first "make f2c.h"
-f2c.h: f2ch.add
-	cat /usr/include/f2c.h f2ch.add >f2c.h
-
-install:	libF77.a
-	mv libF77.a /usr/lib
-	ranlib /usr/lib/libF77.a
-
-clean:
-	rm -f libF77.a *.o
-
-check:
-	xsum F77_aloc.c Notice README Version.c abort_.c c_abs.c c_cos.c \
-	c_div.c c_exp.c c_log.c c_sin.c c_sqrt.c cabs.c d_abs.c d_acos.c \
-	d_asin.c d_atan.c d_atn2.c d_cnjg.c d_cos.c d_cosh.c d_dim.c \
-	d_exp.c d_imag.c d_int.c d_lg10.c d_log.c d_mod.c d_nint.c \
-	d_prod.c d_sign.c d_sin.c d_sinh.c d_sqrt.c d_tan.c d_tanh.c \
-	derf_.c derfc_.c dtime_.c \
-	ef1asc_.c ef1cmc_.c erf_.c erfc_.c etime_.c exit_.c f2ch.add \
-	getarg_.c getenv_.c h_abs.c h_dim.c h_dnnt.c h_indx.c h_len.c \
-	h_mod.c h_nint.c h_sign.c hl_ge.c hl_gt.c hl_le.c hl_lt.c \
-	i_abs.c i_dim.c i_dnnt.c i_indx.c i_len.c i_mod.c i_nint.c \
-	i_sign.c iargc_.c l_ge.c l_gt.c l_le.c l_lt.c lbitbits.c lbitshft.c \
-	main.c makefile pow_ci.c pow_dd.c pow_di.c pow_hh.c pow_ii.c \
-	pow_qq.c pow_ri.c pow_zi.c pow_zz.c qbitbits.c qbitshft.c \
-	r_abs.c r_acos.c r_asin.c r_atan.c r_atn2.c \
-	r_cnjg.c r_cos.c r_cosh.c r_dim.c r_exp.c r_imag.c r_int.c r_lg10.c \
-	r_log.c r_mod.c r_nint.c r_sign.c r_sin.c r_sinh.c r_sqrt.c \
-	r_tan.c r_tanh.c s_cat.c s_cmp.c s_copy.c \
-	s_paus.c s_rnge.c s_stop.c sig_die.c signal1.h0 signal_.c system_.c \
-	z_abs.c z_cos.c z_div.c z_exp.c z_log.c z_sin.c z_sqrt.c >zap
-	cmp zap libF77.xsum && rm zap || diff libF77.xsum zap
diff --git a/contrib/libf2c/libF77/pow_ci.c b/contrib/libf2c/libF77/pow_ci.c
deleted file mode 100644
index 1df3eb34b00..00000000000
--- a/contrib/libf2c/libF77/pow_ci.c
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "f2c.h"
-
-extern void pow_zi (doublecomplex *, doublecomplex *, integer *);
-void
-pow_ci (complex * p, complex * a, integer * b)	/* p = a**b  */
-{
-  doublecomplex p1, a1;
-
-  a1.r = a->r;
-  a1.i = a->i;
-
-  pow_zi (&p1, &a1, b);
-
-  p->r = p1.r;
-  p->i = p1.i;
-}
diff --git a/contrib/libf2c/libF77/pow_dd.c b/contrib/libf2c/libF77/pow_dd.c
deleted file mode 100644
index 0ab208ebf62..00000000000
--- a/contrib/libf2c/libF77/pow_dd.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-pow_dd (doublereal * ap, doublereal * bp)
-{
-  return (pow (*ap, *bp));
-}
diff --git a/contrib/libf2c/libF77/pow_di.c b/contrib/libf2c/libF77/pow_di.c
deleted file mode 100644
index d2298a0a1f0..00000000000
--- a/contrib/libf2c/libF77/pow_di.c
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "f2c.h"
-
-double
-pow_di (doublereal * ap, integer * bp)
-{
-  double pow, x;
-  integer n;
-  unsigned long u;
-
-  pow = 1;
-  x = *ap;
-  n = *bp;
-
-  if (n != 0)
-    {
-      if (n < 0)
-	{
-	  n = -n;
-	  x = 1 / x;
-	}
-      for (u = n;;)
-	{
-	  if (u & 01)
-	    pow *= x;
-	  if (u >>= 1)
-	    x *= x;
-	  else
-	    break;
-	}
-    }
-  return (pow);
-}
diff --git a/contrib/libf2c/libF77/pow_hh.c b/contrib/libf2c/libF77/pow_hh.c
deleted file mode 100644
index 3379d8a7f7c..00000000000
--- a/contrib/libf2c/libF77/pow_hh.c
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "f2c.h"
-
-shortint
-pow_hh (shortint * ap, shortint * bp)
-{
-  shortint pow, x, n;
-  unsigned u;
-
-  x = *ap;
-  n = *bp;
-
-  if (n <= 0)
-    {
-      if (n == 0 || x == 1)
-	return 1;
-      if (x != -1)
-	return x == 0 ? 1 / x : 0;
-      n = -n;
-    }
-  u = n;
-  for (pow = 1;;)
-    {
-      if (u & 01)
-	pow *= x;
-      if (u >>= 1)
-	x *= x;
-      else
-	break;
-    }
-  return (pow);
-}
diff --git a/contrib/libf2c/libF77/pow_ii.c b/contrib/libf2c/libF77/pow_ii.c
deleted file mode 100644
index 92347453fb0..00000000000
--- a/contrib/libf2c/libF77/pow_ii.c
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "f2c.h"
-
-integer
-pow_ii (integer * ap, integer * bp)
-{
-  integer pow, x, n;
-  unsigned long u;
-
-  x = *ap;
-  n = *bp;
-
-  if (n <= 0)
-    {
-      if (n == 0 || x == 1)
-	return 1;
-      if (x != -1)
-	return x == 0 ? 1 / x : 0;
-      n = -n;
-    }
-  u = n;
-  for (pow = 1;;)
-    {
-      if (u & 01)
-	pow *= x;
-      if (u >>= 1)
-	x *= x;
-      else
-	break;
-    }
-  return (pow);
-}
diff --git a/contrib/libf2c/libF77/pow_qq.c b/contrib/libf2c/libF77/pow_qq.c
deleted file mode 100644
index 0cec5ca7d8c..00000000000
--- a/contrib/libf2c/libF77/pow_qq.c
+++ /dev/null
@@ -1,31 +0,0 @@
-#include "f2c.h"
-
-longint
-pow_qq (longint * ap, longint * bp)
-{
-  longint pow, x, n;
-  unsigned long long u;		/* system-dependent */
-
-  x = *ap;
-  n = *bp;
-
-  if (n <= 0)
-    {
-      if (n == 0 || x == 1)
-	return 1;
-      if (x != -1)
-	return x == 0 ? 1 / x : 0;
-      n = -n;
-    }
-  u = n;
-  for (pow = 1;;)
-    {
-      if (u & 01)
-	pow *= x;
-      if (u >>= 1)
-	x *= x;
-      else
-	break;
-    }
-  return (pow);
-}
diff --git a/contrib/libf2c/libF77/pow_ri.c b/contrib/libf2c/libF77/pow_ri.c
deleted file mode 100644
index 792db0c2018..00000000000
--- a/contrib/libf2c/libF77/pow_ri.c
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "f2c.h"
-
-double
-pow_ri (real * ap, integer * bp)
-{
-  double pow, x;
-  integer n;
-  unsigned long u;
-
-  pow = 1;
-  x = *ap;
-  n = *bp;
-
-  if (n != 0)
-    {
-      if (n < 0)
-	{
-	  n = -n;
-	  x = 1 / x;
-	}
-      for (u = n;;)
-	{
-	  if (u & 01)
-	    pow *= x;
-	  if (u >>= 1)
-	    x *= x;
-	  else
-	    break;
-	}
-    }
-  return (pow);
-}
diff --git a/contrib/libf2c/libF77/pow_zi.c b/contrib/libf2c/libF77/pow_zi.c
deleted file mode 100644
index 214db3d7a0f..00000000000
--- a/contrib/libf2c/libF77/pow_zi.c
+++ /dev/null
@@ -1,50 +0,0 @@
-#include "f2c.h"
-
-extern void z_div (doublecomplex *, doublecomplex *, doublecomplex *);
-void
-pow_zi (doublecomplex * p, doublecomplex * a, integer * b)	/* p = a**b  */
-{
-  integer n;
-  unsigned long u;
-  double t;
-  doublecomplex q, x;
-  static doublecomplex one = { 1.0, 0.0 };
-
-  n = *b;
-  q.r = 1;
-  q.i = 0;
-
-  if (n == 0)
-    goto done;
-  if (n < 0)
-    {
-      n = -n;
-      z_div (&x, &one, a);
-    }
-  else
-    {
-      x.r = a->r;
-      x.i = a->i;
-    }
-
-  for (u = n;;)
-    {
-      if (u & 01)
-	{
-	  t = q.r * x.r - q.i * x.i;
-	  q.i = q.r * x.i + q.i * x.r;
-	  q.r = t;
-	}
-      if (u >>= 1)
-	{
-	  t = x.r * x.r - x.i * x.i;
-	  x.i = 2 * x.r * x.i;
-	  x.r = t;
-	}
-      else
-	break;
-    }
-done:
-  p->i = q.i;
-  p->r = q.r;
-}
diff --git a/contrib/libf2c/libF77/pow_zz.c b/contrib/libf2c/libF77/pow_zz.c
deleted file mode 100644
index d5cfbf3d931..00000000000
--- a/contrib/libf2c/libF77/pow_zz.c
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-extern double f__cabs (double, double);
-void
-pow_zz (doublecomplex * r, doublecomplex * a, doublecomplex * b)
-{
-  double logr, logi, x, y;
-
-  if (a->r == 0.0 && a->i == 0.0)
-    {
-	/* Algorithm below doesn't cope.  */
-        r->r = r->i = 0.0;
-        return;
-    }
-  logr = log (f__cabs (a->r, a->i));
-  logi = atan2 (a->i, a->r);
-
-  x = exp (logr * b->r - logi * b->i);
-  y = logr * b->i + logi * b->r;
-
-  r->r = x * cos (y);
-  r->i = x * sin (y);
-}
diff --git a/contrib/libf2c/libF77/qbitbits.c b/contrib/libf2c/libF77/qbitbits.c
deleted file mode 100644
index f72858e7a33..00000000000
--- a/contrib/libf2c/libF77/qbitbits.c
+++ /dev/null
@@ -1,62 +0,0 @@
-#include "f2c.h"
-
-#ifndef LONGBITS
-#define LONGBITS 32
-#endif
-
-#ifndef LONG8BITS
-#define LONG8BITS (2*LONGBITS)
-#endif
-
-integer
-qbit_bits (longint a, integer b, integer len)
-{
-  /* Assume 2's complement arithmetic */
-
-  ulongint x, y;
-
-  x = (ulongint) a;
-  y = (ulongint) - 1L;
-  x >>= b;
-  y <<= len;
-  return (longint) (x & y);
-}
-
-longint
-qbit_cshift (longint a, integer b, integer len)
-{
-  ulongint x, y, z;
-
-  x = (ulongint) a;
-  if (len <= 0)
-    {
-      if (len == 0)
-	return 0;
-      goto full_len;
-    }
-  if (len >= LONG8BITS)
-    {
-    full_len:
-      if (b >= 0)
-	{
-	  b %= LONG8BITS;
-	  return (longint) (x << b | x >> (LONG8BITS - b));
-	}
-      b = -b;
-      b %= LONG8BITS;
-      return (longint) (x << (LONG8BITS - b) | x >> b);
-    }
-  y = z = (unsigned long) -1;
-  y <<= len;
-  z &= ~y;
-  y &= x;
-  x &= z;
-  if (b >= 0)
-    {
-      b %= len;
-      return (longint) (y | (z & (x << b | x >> (len - b))));
-    }
-  b = -b;
-  b %= len;
-  return (longint) (y | (z & (x >> b | x << (len - b))));
-}
diff --git a/contrib/libf2c/libF77/qbitshft.c b/contrib/libf2c/libF77/qbitshft.c
deleted file mode 100644
index ce740edde19..00000000000
--- a/contrib/libf2c/libF77/qbitshft.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-longint
-qbit_shift (longint a, integer b)
-{
-  return b >= 0 ? a << b : (longint) ((ulongint) a >> -b);
-}
diff --git a/contrib/libf2c/libF77/r_abs.c b/contrib/libf2c/libF77/r_abs.c
deleted file mode 100644
index 6f62724ef17..00000000000
--- a/contrib/libf2c/libF77/r_abs.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-double
-r_abs (real * x)
-{
-  if (*x >= 0)
-    return (*x);
-  return (-*x);
-}
diff --git a/contrib/libf2c/libF77/r_acos.c b/contrib/libf2c/libF77/r_acos.c
deleted file mode 100644
index d761cfdc5c8..00000000000
--- a/contrib/libf2c/libF77/r_acos.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_acos (real * x)
-{
-  return (acos (*x));
-}
diff --git a/contrib/libf2c/libF77/r_asin.c b/contrib/libf2c/libF77/r_asin.c
deleted file mode 100644
index b8c73c786af..00000000000
--- a/contrib/libf2c/libF77/r_asin.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_asin (real * x)
-{
-  return (asin (*x));
-}
diff --git a/contrib/libf2c/libF77/r_atan.c b/contrib/libf2c/libF77/r_atan.c
deleted file mode 100644
index 33a6589fda9..00000000000
--- a/contrib/libf2c/libF77/r_atan.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_atan (real * x)
-{
-  return (atan (*x));
-}
diff --git a/contrib/libf2c/libF77/r_atn2.c b/contrib/libf2c/libF77/r_atn2.c
deleted file mode 100644
index 076d8743b1e..00000000000
--- a/contrib/libf2c/libF77/r_atn2.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_atn2 (real * x, real * y)
-{
-  return (atan2 (*x, *y));
-}
diff --git a/contrib/libf2c/libF77/r_cnjg.c b/contrib/libf2c/libF77/r_cnjg.c
deleted file mode 100644
index 5f849291b20..00000000000
--- a/contrib/libf2c/libF77/r_cnjg.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-void
-r_cnjg (complex * r, complex * z)
-{
-  real zi = z->i;
-  r->r = z->r;
-  r->i = -zi;
-}
diff --git a/contrib/libf2c/libF77/r_cos.c b/contrib/libf2c/libF77/r_cos.c
deleted file mode 100644
index ed556e81e87..00000000000
--- a/contrib/libf2c/libF77/r_cos.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_cos (real * x)
-{
-  return (cos (*x));
-}
diff --git a/contrib/libf2c/libF77/r_cosh.c b/contrib/libf2c/libF77/r_cosh.c
deleted file mode 100644
index b22e0cf0a3d..00000000000
--- a/contrib/libf2c/libF77/r_cosh.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_cosh (real * x)
-{
-  return (cosh (*x));
-}
diff --git a/contrib/libf2c/libF77/r_dim.c b/contrib/libf2c/libF77/r_dim.c
deleted file mode 100644
index 48d2fc7f767..00000000000
--- a/contrib/libf2c/libF77/r_dim.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-double
-r_dim (real * a, real * b)
-{
-  return (*a > *b ? *a - *b : 0);
-}
diff --git a/contrib/libf2c/libF77/r_exp.c b/contrib/libf2c/libF77/r_exp.c
deleted file mode 100644
index 7c1ceea5895..00000000000
--- a/contrib/libf2c/libF77/r_exp.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_exp (real * x)
-{
-  return (exp (*x));
-}
diff --git a/contrib/libf2c/libF77/r_imag.c b/contrib/libf2c/libF77/r_imag.c
deleted file mode 100644
index 784abc8434b..00000000000
--- a/contrib/libf2c/libF77/r_imag.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "f2c.h"
-
-double
-r_imag (complex * z)
-{
-  return (z->i);
-}
diff --git a/contrib/libf2c/libF77/r_int.c b/contrib/libf2c/libF77/r_int.c
deleted file mode 100644
index 3c1b28ea4c7..00000000000
--- a/contrib/libf2c/libF77/r_int.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_int (real * x)
-{
-  return ((*x > 0) ? floor (*x) : -floor (-*x));
-}
diff --git a/contrib/libf2c/libF77/r_lg10.c b/contrib/libf2c/libF77/r_lg10.c
deleted file mode 100644
index 563e73c4d8c..00000000000
--- a/contrib/libf2c/libF77/r_lg10.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "f2c.h"
-
-#define log10e 0.43429448190325182765
-
-#undef abs
-#include 
-double
-r_lg10 (real * x)
-{
-  return (log10e * log (*x));
-}
diff --git a/contrib/libf2c/libF77/r_log.c b/contrib/libf2c/libF77/r_log.c
deleted file mode 100644
index eaaecc836f2..00000000000
--- a/contrib/libf2c/libF77/r_log.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_log (real * x)
-{
-  return (log (*x));
-}
diff --git a/contrib/libf2c/libF77/r_mod.c b/contrib/libf2c/libF77/r_mod.c
deleted file mode 100644
index 9518d66ce99..00000000000
--- a/contrib/libf2c/libF77/r_mod.c
+++ /dev/null
@@ -1,33 +0,0 @@
-#include "f2c.h"
-
-#ifdef IEEE_drem
-double drem (double, double);
-#else
-#undef abs
-#include 
-#endif
-double
-r_mod (real * x, real * y)
-{
-#ifdef IEEE_drem
-  double xa, ya, z;
-  if ((ya = *y) < 0.)
-    ya = -ya;
-  z = drem (xa = *x, ya);
-  if (xa > 0)
-    {
-      if (z < 0)
-	z += ya;
-    }
-  else if (z > 0)
-    z -= ya;
-  return z;
-#else
-  double quotient;
-  if ((quotient = (double) *x / *y) >= 0)
-    quotient = floor (quotient);
-  else
-    quotient = -floor (-quotient);
-  return (*x - (*y) * quotient);
-#endif
-}
diff --git a/contrib/libf2c/libF77/r_nint.c b/contrib/libf2c/libF77/r_nint.c
deleted file mode 100644
index f2713d588b1..00000000000
--- a/contrib/libf2c/libF77/r_nint.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_nint (real * x)
-{
-  return ((*x) >= 0 ? floor (*x + .5) : -floor (.5 - *x));
-}
diff --git a/contrib/libf2c/libF77/r_sign.c b/contrib/libf2c/libF77/r_sign.c
deleted file mode 100644
index f53c6bf9220..00000000000
--- a/contrib/libf2c/libF77/r_sign.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-double
-r_sign (real * a, real * b)
-{
-  double x;
-  x = (*a >= 0 ? *a : -*a);
-  return (*b >= 0 ? x : -x);
-}
diff --git a/contrib/libf2c/libF77/r_sin.c b/contrib/libf2c/libF77/r_sin.c
deleted file mode 100644
index 5a5ef136a8c..00000000000
--- a/contrib/libf2c/libF77/r_sin.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_sin (real * x)
-{
-  return (sin (*x));
-}
diff --git a/contrib/libf2c/libF77/r_sinh.c b/contrib/libf2c/libF77/r_sinh.c
deleted file mode 100644
index 723c7ab29c3..00000000000
--- a/contrib/libf2c/libF77/r_sinh.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_sinh (real * x)
-{
-  return (sinh (*x));
-}
diff --git a/contrib/libf2c/libF77/r_sqrt.c b/contrib/libf2c/libF77/r_sqrt.c
deleted file mode 100644
index ed832ba70e1..00000000000
--- a/contrib/libf2c/libF77/r_sqrt.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_sqrt (real * x)
-{
-  return (sqrt (*x));
-}
diff --git a/contrib/libf2c/libF77/r_tan.c b/contrib/libf2c/libF77/r_tan.c
deleted file mode 100644
index 4ef913e6522..00000000000
--- a/contrib/libf2c/libF77/r_tan.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_tan (real * x)
-{
-  return (tan (*x));
-}
diff --git a/contrib/libf2c/libF77/r_tanh.c b/contrib/libf2c/libF77/r_tanh.c
deleted file mode 100644
index 6f2552a9f97..00000000000
--- a/contrib/libf2c/libF77/r_tanh.c
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include 
-double
-r_tanh (real * x)
-{
-  return (tanh (*x));
-}
diff --git a/contrib/libf2c/libF77/s_cat.c b/contrib/libf2c/libF77/s_cat.c
deleted file mode 100644
index 4e8da1b3fdb..00000000000
--- a/contrib/libf2c/libF77/s_cat.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Unless compiled with -DNO_OVERWRITE, this variant of s_cat allows the
- * target of a concatenation to appear on its right-hand side (contrary
- * to the Fortran 77 Standard, but in accordance with Fortran 90).
- */
-
-#include "f2c.h"
-#ifndef NO_OVERWRITE
-#include 
-#undef abs
-#undef min
-#undef max
-#include 
-extern char *F77_aloc (ftnlen, char *);
-#include 
-#endif /* NO_OVERWRITE */
-
-void
-s_cat (char *lp, char *rpp[], ftnint rnp[], ftnint * np, ftnlen ll)
-{
-  ftnlen i, nc;
-  char *rp;
-  ftnlen n = *np;
-#ifndef NO_OVERWRITE
-  ftnlen L, m;
-  char *lp0, *lp1;
-
-  lp0 = 0;
-  lp1 = lp;
-  L = ll;
-  i = 0;
-  while (i < n)
-    {
-      rp = rpp[i];
-      m = rnp[i++];
-      if (rp >= lp1 || rp + m <= lp)
-	{
-	  if ((L -= m) <= 0)
-	    {
-	      n = i;
-	      break;
-	    }
-	  lp1 += m;
-	  continue;
-	}
-      lp0 = lp;
-      lp = lp1 = F77_aloc (L = ll, "s_cat");
-      break;
-    }
-  lp1 = lp;
-#endif /* NO_OVERWRITE */
-  for (i = 0; i < n; ++i)
-    {
-      nc = ll;
-      if (rnp[i] < nc)
-	nc = rnp[i];
-      ll -= nc;
-      rp = rpp[i];
-      while (--nc >= 0)
-	*lp++ = *rp++;
-    }
-  while (--ll >= 0)
-    *lp++ = ' ';
-#ifndef NO_OVERWRITE
-  if (lp0)
-    {
-      memcpy (lp0, lp1, L);
-      free (lp1);
-    }
-#endif
-}
diff --git a/contrib/libf2c/libF77/s_cmp.c b/contrib/libf2c/libF77/s_cmp.c
deleted file mode 100644
index 5b43c9edb9c..00000000000
--- a/contrib/libf2c/libF77/s_cmp.c
+++ /dev/null
@@ -1,49 +0,0 @@
-#include "f2c.h"
-
-/* compare two strings */
-
-integer
-s_cmp (char *a0, char *b0, ftnlen la, ftnlen lb)
-{
-  register unsigned char *a, *aend, *b, *bend;
-  a = (unsigned char *) a0;
-  b = (unsigned char *) b0;
-  aend = a + la;
-  bend = b + lb;
-
-  if (la <= lb)
-    {
-      while (a < aend)
-	if (*a != *b)
-	  return (*a - *b);
-	else
-	  {
-	    ++a;
-	    ++b;
-	  }
-
-      while (b < bend)
-	if (*b != ' ')
-	  return (' ' - *b);
-	else
-	  ++b;
-    }
-
-  else
-    {
-      while (b < bend)
-	if (*a == *b)
-	  {
-	    ++a;
-	    ++b;
-	  }
-	else
-	  return (*a - *b);
-      while (a < aend)
-	if (*a != ' ')
-	  return (*a - ' ');
-	else
-	  ++a;
-    }
-  return (0);
-}
diff --git a/contrib/libf2c/libF77/s_copy.c b/contrib/libf2c/libF77/s_copy.c
deleted file mode 100644
index a91071eccab..00000000000
--- a/contrib/libf2c/libF77/s_copy.c
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Unless compiled with -DNO_OVERWRITE, this variant of s_copy allows the
- * target of an assignment to appear on its right-hand side (contrary
- * to the Fortran 77 Standard, but in accordance with Fortran 90),
- * as in  a(2:5) = a(4:7) .
- */
-
-#include "f2c.h"
-
-/* assign strings:  a = b */
-
-void
-s_copy (register char *a, register char *b, ftnlen la, ftnlen lb)
-{
-  register char *aend, *bend;
-
-  aend = a + la;
-
-  if (la <= lb)
-#ifndef NO_OVERWRITE
-    if (a <= b || a >= b + la)
-#endif
-      while (a < aend)
-	*a++ = *b++;
-#ifndef NO_OVERWRITE
-    else
-      for (b += la; a < aend;)
-	*--aend = *--b;
-#endif
-
-  else
-    {
-      bend = b + lb;
-#ifndef NO_OVERWRITE
-      if (a <= b || a >= bend)
-#endif
-	while (b < bend)
-	  *a++ = *b++;
-#ifndef NO_OVERWRITE
-      else
-	{
-	  a += lb;
-	  while (b < bend)
-	    *--a = *--bend;
-	  a += lb;
-	}
-#endif
-      while (a < aend)
-	*a++ = ' ';
-    }
-}
diff --git a/contrib/libf2c/libF77/s_paus.c b/contrib/libf2c/libF77/s_paus.c
deleted file mode 100644
index 79691366e6f..00000000000
--- a/contrib/libf2c/libF77/s_paus.c
+++ /dev/null
@@ -1,71 +0,0 @@
-#include 
-#include "f2c.h"
-#define PAUSESIG 15
-
-#include "signal1.h"
-#undef abs
-#undef min
-#undef max
-#include 
-extern int getpid (void), isatty (int), pause (void);
-
-extern void f_exit (void);
-
-static void
-waitpause (Sigarg)
-{
-  Use_Sigarg;
-  return;
-}
-
-static void
-s_1paus (FILE * fin)
-{
-  fprintf (stderr,
-	   "To resume execution, type go.  Other input will terminate the job.\n");
-  fflush (stderr);
-  if (getc (fin) != 'g' || getc (fin) != 'o' || getc (fin) != '\n')
-    {
-      fprintf (stderr, "STOP\n");
-#ifdef NO_ONEXIT
-      f_exit ();
-#endif
-      exit (0);
-    }
-}
-
-int
-s_paus (char *s, ftnlen n)
-{
-  fprintf (stderr, "PAUSE ");
-  if (n > 0)
-    fprintf (stderr, " %.*s", (int) n, s);
-  fprintf (stderr, " statement executed\n");
-  if (isatty (fileno (stdin)))
-    s_1paus (stdin);
-  else
-    {
-#if (defined (MSDOS) && !defined (GO32)) || defined (_WIN32)
-      FILE *fin;
-      fin = fopen ("con", "r");
-      if (!fin)
-	{
-	  fprintf (stderr, "s_paus: can't open con!\n");
-	  fflush (stderr);
-	  exit (1);
-	}
-      s_1paus (fin);
-      fclose (fin);
-#else
-      fprintf (stderr,
-	       "To resume execution, execute a   kill -%d %d   command\n",
-	       PAUSESIG, getpid ());
-      signal1 (PAUSESIG, waitpause);
-      fflush (stderr);
-      pause ();
-#endif
-    }
-  fprintf (stderr, "Execution resumes after PAUSE.\n");
-  fflush (stderr);
-  return 0;			/* NOT REACHED */
-}
diff --git a/contrib/libf2c/libF77/s_rnge.c b/contrib/libf2c/libF77/s_rnge.c
deleted file mode 100644
index 6c054c707f5..00000000000
--- a/contrib/libf2c/libF77/s_rnge.c
+++ /dev/null
@@ -1,22 +0,0 @@
-#include 
-#include "f2c.h"
-
-/* called when a subscript is out of range */
-
-extern void sig_die (char *, int);
-integer
-s_rnge (char *varn, ftnint offset, char *procn, ftnint line)
-{
-  register int i;
-
-  fprintf (stderr, "Subscript out of range on file line %ld, procedure ",
-	   (long) line);
-  while ((i = *procn) && i != '_' && i != ' ')
-    putc (*procn++, stderr);
-  fprintf (stderr, ".\nAttempt to access the %ld-th element of variable ",
-	   (long) offset + 1);
-  while ((i = *varn) && i != ' ')
-    putc (*varn++, stderr);
-  sig_die (".", 1);
-  return 0;			/* not reached */
-}
diff --git a/contrib/libf2c/libF77/s_stop.c b/contrib/libf2c/libF77/s_stop.c
deleted file mode 100644
index 571416be7bb..00000000000
--- a/contrib/libf2c/libF77/s_stop.c
+++ /dev/null
@@ -1,32 +0,0 @@
-#include 
-#include "f2c.h"
-
-#undef abs
-#undef min
-#undef max
-#include 
-void f_exit (void);
-
-int
-s_stop (char *s, ftnlen n)
-{
-  int i;
-
-  if (n > 0)
-    {
-      fprintf (stderr, "STOP ");
-      for (i = 0; i < n; ++i)
-	putc (*s++, stderr);
-      fprintf (stderr, " statement executed\n");
-    }
-#ifdef NO_ONEXIT
-  f_exit ();
-#endif
-  exit (0);
-
-/* We cannot avoid (useless) compiler diagnostics here:		*/
-/* some compilers complain if there is no return statement,	*/
-/* and others complain that this one cannot be reached.		*/
-
-  return 0;			/* NOT REACHED */
-}
diff --git a/contrib/libf2c/libF77/setarg.c b/contrib/libf2c/libF77/setarg.c
deleted file mode 100644
index 49515746f48..00000000000
--- a/contrib/libf2c/libF77/setarg.c
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Set up the global argc/argv info for use by getarg_, iargc_, and
-   g77's inlined intrinsic equivalents.  */
-
-#include 
-
-int f__xargc;
-char **f__xargv;
-
-void
-f_setarg (int argc, char **argv)
-{
-  f__xargc = argc;
-  f__xargv = argv;
-}
diff --git a/contrib/libf2c/libF77/setsig.c b/contrib/libf2c/libF77/setsig.c
deleted file mode 100644
index 96826be94fd..00000000000
--- a/contrib/libf2c/libF77/setsig.c
+++ /dev/null
@@ -1,86 +0,0 @@
-/* Set up the signal behavior.  */
-
-#include 
-#include "signal1.h"
-
-#ifndef SIGIOT
-#ifdef SIGABRT
-#define SIGIOT SIGABRT
-#endif
-#endif
-
-#include 
-
-extern void sig_die (char *, int);
-
-static void
-sigfdie (Sigarg)
-{
-  Use_Sigarg;
-  sig_die ("Floating Exception", 1);
-}
-
-
-static void
-sigidie (Sigarg)
-{
-  Use_Sigarg;
-  sig_die ("IOT Trap", 1);
-}
-
-#ifdef SIGQUIT
-static void
-sigqdie (Sigarg)
-{
-  Use_Sigarg;
-  sig_die ("Quit signal", 1);
-}
-#endif
-
-
-static void
-sigindie (Sigarg)
-{
-  Use_Sigarg;
-  sig_die ("Interrupt", 0);
-}
-
-static void
-sigtdie (Sigarg)
-{
-  Use_Sigarg;
-  sig_die ("Killed", 0);
-}
-
-#ifdef SIGTRAP
-static void
-sigtrdie (Sigarg)
-{
-  Use_Sigarg;
-  sig_die ("Trace trap", 1);
-}
-#endif
-
-
-void
-f_setsig ()
-{
-  signal1 (SIGFPE, sigfdie);	/* ignore underflow, enable overflow */
-#ifdef SIGIOT
-  signal1 (SIGIOT, sigidie);
-#endif
-#ifdef SIGTRAP
-  signal1 (SIGTRAP, sigtrdie);
-#endif
-#ifdef SIGQUIT
-  if (signal1 (SIGQUIT, sigqdie) == SIG_IGN)
-    signal1 (SIGQUIT, SIG_IGN);
-#endif
-  if (signal1 (SIGINT, sigindie) == SIG_IGN)
-    signal1 (SIGINT, SIG_IGN);
-  signal1 (SIGTERM, sigtdie);
-
-#ifdef pdp11
-  ldfps (01200);		/* detect overflow as an exception */
-#endif
-}
diff --git a/contrib/libf2c/libF77/sig_die.c b/contrib/libf2c/libF77/sig_die.c
deleted file mode 100644
index 622462e248b..00000000000
--- a/contrib/libf2c/libF77/sig_die.c
+++ /dev/null
@@ -1,37 +0,0 @@
-#include 
-#include 
-
-#ifndef SIGIOT
-#ifdef SIGABRT
-#define SIGIOT SIGABRT
-#endif
-#endif
-
-#include 
-extern void f_exit (void);
-
-void
-sig_die (register char *s, int kill)
-{
-  /* print error message, then clear buffers */
-  fprintf (stderr, "%s\n", s);
-
-  if (kill)
-    {
-      fflush (stderr);
-      f_exit ();
-      fflush (stderr);
-      /* now get a core */
-#ifdef SIGIOT
-      signal (SIGIOT, SIG_DFL);
-#endif
-      abort ();
-    }
-  else
-    {
-#ifdef NO_ONEXIT
-      f_exit ();
-#endif
-      exit (1);
-    }
-}
diff --git a/contrib/libf2c/libF77/signal1.h b/contrib/libf2c/libF77/signal1.h
deleted file mode 100644
index b559211e8e4..00000000000
--- a/contrib/libf2c/libF77/signal1.h
+++ /dev/null
@@ -1,5 +0,0 @@
-/* The g77 implementation of libf2c directly includes signal1.h0,
-   instead of copying it to signal1.h, since that seems easier to
-   cope with at this point.  */
-
-#include "signal1.h0"
diff --git a/contrib/libf2c/libF77/signal1.h0 b/contrib/libf2c/libF77/signal1.h0
deleted file mode 100644
index 0e2fcf2c1e6..00000000000
--- a/contrib/libf2c/libF77/signal1.h0
+++ /dev/null
@@ -1,26 +0,0 @@
-/* You may need to adjust the definition of signal1 to supply a */
-/* cast to the correct argument type.  This detail is system- and */
-/* compiler-dependent.   The #define below assumes signal.h declares */
-/* type SIG_PF for the signal function's second argument. */
-
-/* For some C++ compilers, "#define Sigarg_t ..." may be appropriate. */
-
-#include 
-
-#ifndef Sigret_t
-#define Sigret_t void
-#endif
-#ifndef Sigarg_t
-#define Sigarg_t int
-#endif /*Sigarg_t */
-
-#ifdef USE_SIG_PF		/* compile with -DUSE_SIG_PF under IRIX */
-#define sig_pf SIG_PF
-#else
-typedef Sigret_t (*sig_pf) (Sigarg_t);
-#endif
-
-#define signal1(a,b) signal(a,(sig_pf)b)
-
-#define Sigarg int n
-#define Use_Sigarg n = n	/* shut up compiler warning */
diff --git a/contrib/libf2c/libF77/signal_.c b/contrib/libf2c/libF77/signal_.c
deleted file mode 100644
index f67831c3c43..00000000000
--- a/contrib/libf2c/libF77/signal_.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "f2c.h"
-#include "signal1.h"
-
-void *
-G77_signal_0 (integer * sigp, sig_pf proc)
-{
-  int sig;
-  sig = (int) *sigp;
-
-  return (void *) signal (sig, proc);
-}
diff --git a/contrib/libf2c/libF77/system_.c b/contrib/libf2c/libF77/system_.c
deleted file mode 100644
index dbbd0bea9ec..00000000000
--- a/contrib/libf2c/libF77/system_.c
+++ /dev/null
@@ -1,28 +0,0 @@
-/* f77 interface to system routine */
-
-#include "f2c.h"
-
-#undef abs
-#undef min
-#undef max
-#include 
-extern char *F77_aloc (ftnlen, char *);
-
-integer
-G77_system_0 (register char *s, ftnlen n)
-{
-  char buff0[256], *buff;
-  register char *bp, *blast;
-  integer rv;
-
-  buff = bp = n < (ftnlen) sizeof (buff0) ? buff0 : F77_aloc (n + 1, "system_");
-  blast = bp + n;
-
-  while (bp < blast && *s)
-    *bp++ = *s++;
-  *bp = 0;
-  rv = system (buff);
-  if (buff != buff0)
-    free (buff);
-  return rv;
-}
diff --git a/contrib/libf2c/libF77/z_abs.c b/contrib/libf2c/libF77/z_abs.c
deleted file mode 100644
index 2419c0eac49..00000000000
--- a/contrib/libf2c/libF77/z_abs.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "f2c.h"
-
-double f__cabs (double, double);
-double
-z_abs (doublecomplex * z)
-{
-  return (f__cabs (z->r, z->i));
-}
diff --git a/contrib/libf2c/libF77/z_cos.c b/contrib/libf2c/libF77/z_cos.c
deleted file mode 100644
index 0f4cd71bd5a..00000000000
--- a/contrib/libf2c/libF77/z_cos.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-void
-z_cos (doublecomplex * r, doublecomplex * z)
-{
-  double zi = z->i, zr = z->r;
-  r->r = cos (zr) * cosh (zi);
-  r->i = -sin (zr) * sinh (zi);
-}
diff --git a/contrib/libf2c/libF77/z_div.c b/contrib/libf2c/libF77/z_div.c
deleted file mode 100644
index a5fc527bdc2..00000000000
--- a/contrib/libf2c/libF77/z_div.c
+++ /dev/null
@@ -1,41 +0,0 @@
-#include "f2c.h"
-
-extern void sig_die (char *, int);
-void
-z_div (doublecomplex * c, doublecomplex * a, doublecomplex * b)
-{
-  double ratio, den;
-  double abr, abi, cr;
-
-  if ((abr = b->r) < 0.)
-    abr = -abr;
-  if ((abi = b->i) < 0.)
-    abi = -abi;
-  if (abr <= abi)
-    {
-      if (abi == 0)
-	{
-#ifdef IEEE_COMPLEX_DIVIDE
-	  if (a->i != 0 || a->r != 0)
-	    abi = 1.;
-	  c->i = c->r = abi / abr;
-	  return;
-#else
-	  sig_die ("complex division by zero", 1);
-#endif
-	}
-      ratio = b->r / b->i;
-      den = b->i * (1 + ratio * ratio);
-      cr = (a->r * ratio + a->i) / den;
-      c->i = (a->i * ratio - a->r) / den;
-    }
-
-  else
-    {
-      ratio = b->i / b->r;
-      den = b->r * (1 + ratio * ratio);
-      cr = (a->r + a->i * ratio) / den;
-      c->i = (a->i - a->r * ratio) / den;
-    }
-  c->r = cr;
-}
diff --git a/contrib/libf2c/libF77/z_exp.c b/contrib/libf2c/libF77/z_exp.c
deleted file mode 100644
index 16f51e74a45..00000000000
--- a/contrib/libf2c/libF77/z_exp.c
+++ /dev/null
@@ -1,13 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-void
-z_exp (doublecomplex * r, doublecomplex * z)
-{
-  double expx, zi = z->i;
-
-  expx = exp (z->r);
-  r->r = expx * cos (zi);
-  r->i = expx * sin (zi);
-}
diff --git a/contrib/libf2c/libF77/z_log.c b/contrib/libf2c/libF77/z_log.c
deleted file mode 100644
index f56b12ed7e3..00000000000
--- a/contrib/libf2c/libF77/z_log.c
+++ /dev/null
@@ -1,59 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-extern double f__cabs (double, double);
-void
-z_log (doublecomplex * r, doublecomplex * z)
-{
-  double s, s0, t, t2, u, v;
-  double zi = z->i, zr = z->r;
-
-  r->i = atan2 (zi, zr);
-#ifdef Pre20000310
-  r->r = log (f__cabs (zr, zi));
-#else
-  if (zi < 0)
-    zi = -zi;
-  if (zr < 0)
-    zr = -zr;
-  if (zr < zi)
-    {
-      t = zi;
-      zi = zr;
-      zr = t;
-    }
-  t = zi / zr;
-  s = zr * sqrt (1 + t * t);
-  /* now s = f__cabs(zi,zr), and zr = |zr| >= |zi| = zi */
-  if ((t = s - 1) < 0)
-    t = -t;
-  if (t > .01)
-    r->r = log (s);
-  else
-    {
-
-#ifdef Comment
-
-      log (1 + x) = x - x ^ 2 / 2 + x ^ 3 / 3 - x ^ 4 / 4 + -...
-	= x (1 - x / 2 + x ^ 2 / 3 - +...)
-	[sqrt (y ^ 2 + z ^ 2) - 1] *[sqrt (y ^ 2 + z ^ 2) + 1] =
-	y ^ 2 + z ^ 2 - 1, so sqrt (y ^ 2 + z ^ 2) - 1 =
-	(y ^ 2 + z ^ 2 - 1) /[sqrt (y ^ 2 + z ^ 2) + 1]
-#endif /*Comment */
-	t = ((zr * zr - 1.) + zi * zi) / (s + 1);
-      t2 = t * t;
-      s = 1. - 0.5 * t;
-      u = v = 1;
-      do
-	{
-	  s0 = s;
-	  u *= t2;
-	  v += 2;
-	  s += u / v - t * u / (v + 1);
-	}
-      while (s > s0);
-      r->r = s * t;
-    }
-#endif
-}
diff --git a/contrib/libf2c/libF77/z_sin.c b/contrib/libf2c/libF77/z_sin.c
deleted file mode 100644
index 8cb44cf53ca..00000000000
--- a/contrib/libf2c/libF77/z_sin.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-void
-z_sin (doublecomplex * r, doublecomplex * z)
-{
-  double zi = z->i, zr = z->r;
-  r->r = sin (zr) * cosh (zi);
-  r->i = cos (zr) * sinh (zi);
-}
diff --git a/contrib/libf2c/libF77/z_sqrt.c b/contrib/libf2c/libF77/z_sqrt.c
deleted file mode 100644
index 954c2fa1889..00000000000
--- a/contrib/libf2c/libF77/z_sqrt.c
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "f2c.h"
-
-#undef abs
-#include "math.h"
-extern double f__cabs (double, double);
-void
-z_sqrt (doublecomplex * r, doublecomplex * z)
-{
-  double mag, zi = z->i, zr = z->r;
-
-  if ((mag = f__cabs (zr, zi)) == 0.)
-    r->r = r->i = 0.;
-  else if (zr > 0)
-    {
-      r->r = sqrt (0.5 * (mag + zr));
-      r->i = zi / r->r / 2;
-    }
-  else
-    {
-      r->i = sqrt (0.5 * (mag - zr));
-      if (zi < 0)
-	r->i = -r->i;
-      r->r = zi / r->i / 2;
-    }
-}
diff --git a/contrib/libf2c/libI77/Makefile.in b/contrib/libf2c/libI77/Makefile.in
deleted file mode 100644
index d6abf7030a3..00000000000
--- a/contrib/libf2c/libI77/Makefile.in
+++ /dev/null
@@ -1,169 +0,0 @@
-# Makefile for GNU F77 compiler runtime.
-# Copyright 1990 - 1994 by AT&T Bell Laboratories and Bellcore (see the
-# file `Notice').
-# Portions of this file Copyright (C) 1995, 1996, 1998, 2001 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of GNU Fortran.
-#
-#GNU Fortran is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-#### Start of system configuration section. ####
-
-# $(srcdir) must be set to the g77 runtime libI77 source directory.
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-# configure sets this to all the -D options appropriate for the
-# configuration.
-DEFS = @DEFS@
-
-F2C_H_DIR = @srcdir@/..
-G2C_H_DIR = ..
-CC = @CC@
-CFLAGS = @CFLAGS@
-CPPFLAGS = @CPPFLAGS@
-@SET_MAKE@
-
-SHELL = @SHELL@
-
-#### End of system configuration section. ####
-
-ALL_CFLAGS = -I. -I$(srcdir) -I$(G2C_H_DIR) -I$(F2C_H_DIR) $(CPPFLAGS) \
-             $(DEFS) $(WARN_CFLAGS) $(CFLAGS)
-
-.SUFFIXES:
-.SUFFIXES: .c .lo
-
-.c.lo:
-	@LIBTOOL@ --mode=compile $(CC) -c -DSkip_f2c_Undefs -DAllow_TYQUAD $(ALL_CFLAGS) $<
-
-OBJS =	VersionI.lo backspace.lo close.lo dfe.lo dolio.lo due.lo endfile.lo err.lo \
-	fmt.lo fmtlib.lo iio.lo ilnw.lo inquire.lo lread.lo lwrite.lo open.lo \
-	rdfmt.lo rewind.lo rsfe.lo rsli.lo rsne.lo sfe.lo sue.lo typesize.lo uio.lo \
-	util.lo wref.lo wrtfmt.lo wsfe.lo wsle.lo wsne.lo xwsne.lo \
-	ftell_.lo
-
-all: ../s-libi77
-
-../s-libi77: $(OBJS)
-	-rm -f $@.T $@
-	objs='$(OBJS)'; for name in $$objs; do \
-	  echo libI77/$${name} >> $@.T; done
-	mv $@.T $@
-
-Makefile: Makefile.in config.status
-	$(SHELL) config.status
-
-config.status: configure
-	rm -f config.cache
-	CONFIG_SITE=no-such-file CC='$(CC)' CFLAGS='$(CFLAGS)' \
-	  CPPFLAGS='$(CPPFLAGS)' $(SHELL) config.status --recheck
-
-${srcdir}/configure: configure.in
-	rm -f config.cache
-	cd ${srcdir} && autoconf
-
-# autoheader might not change config.h.in, so touch a stamp file.
-${srcdir}/config.h.in: stamp-h.in; @true
-${srcdir}/stamp-h.in: configure.in
-	(cd ${srcdir} && autoheader)
-	@rm -f ${srcdir}/stamp-h.in
-	echo timestamp > ${srcdir}/stamp-h.in
-
-config.h: stamp-h; @true
-stamp-h: config.h.in config.status
-	CONFIG_FILES= CONFIG_HEADERS=config.h $(SHELL) config.status
-	echo timestamp > stamp-h
-
-VersionI.lo: Version.c
-	@LIBTOOL@ --mode=compile $(CC) -c $(ALL_CFLAGS) $(srcdir)/Version.c -o $@
-
-backspace.lo:	backspace.c fio.h config.h
-close.lo:	close.c fio.h config.h
-dfe.lo:		fio.h config.h
-dfe.lo:		dfe.c fmt.h
-dolio.lo:	dolio.c config.h
-due.lo:		due.c fio.h config.h
-endfile.lo:	endfile.c fio.h config.h
-err.lo:		err.c fio.h config.h
-fmt.lo:		fio.h config.h
-fmt.lo:		fmt.c fmt.h
-fmtlib.lo:	fmtlib.c config.h
-ftell_.lo:	ftell_.c fio.h config.h
-iio.lo:		fio.h
-iio.lo:		iio.c fmt.h
-ilnw.lo:		fio.h config.h
-ilnw.lo:		ilnw.c lio.h
-inquire.lo:	inquire.c fio.h config.h
-lread.lo:	fio.h config.h
-lread.lo:	fmt.h
-lread.lo:	lio.h
-lread.lo:	lread.c fp.h
-lwrite.lo:	fio.h
-lwrite.lo:	fmt.h
-lwrite.lo:	lwrite.c lio.h
-open.lo:		open.c fio.h config.h
-rdfmt.lo:	fio.h config.h
-rdfmt.lo:	fmt.h
-rdfmt.lo:	rdfmt.c fp.h
-rewind.lo:	rewind.c fio.h config.h
-rsfe.lo:		fio.h config.h
-rsfe.lo:		rsfe.c fmt.h
-rsli.lo:		fio.h
-rsli.lo:		rsli.c lio.h
-rsne.lo:		fio.h config.h
-rsne.lo:		rsne.c lio.h
-sfe.lo:		sfe.c fio.h config.h
-sue.lo:		sue.c fio.h config.h
-typesize.lo:	typesize.c config.h
-uio.lo:		uio.c fio.h
-util.lo:		util.c fio.h config.h
-wref.lo:		fio.h
-wref.lo:		fmt.h
-wref.lo:		wref.c fp.h
-wrtfmt.lo:	fio.h config.h
-wrtfmt.lo:	wrtfmt.c fmt.h
-wsfe.lo:		fio.h config.h
-wsfe.lo:		wsfe.c fmt.h
-wsle.lo:		fio.h config.h
-wsle.lo:		fmt.h
-wsle.lo:		wsle.c lio.h
-wsne.lo:		fio.h
-wsne.lo:		wsne.c lio.h
-xwsne.lo:	fio.h config.h
-xwsne.lo:	lio.h
-xwsne.lo:	xwsne.c fmt.h
-
-# May be pessimistic:
-$(OBJS): $(F2C_H_DIR)/f2c.h $(G2C_H_DIR)/g2c.h
-
-check install uninstall install-strip dist installcheck installdirs:
-
-mostlyclean:
-	rm -f *.o *.lo
-	rm -rf .libs
-
-clean: mostlyclean
-	rm -f config.log ../s-libi77
-
-distclean: clean
-	rm -f config.cache config.status Makefile ../s-libi77 configure
-
-maintainer-clean:
-
-.PHONY: mostlyclean clean distclean maintainer-clean all check uninstall \
-        install-strip dist installcheck installdirs archive
diff --git a/contrib/libf2c/libI77/Notice b/contrib/libf2c/libI77/Notice
deleted file mode 100644
index 261b719bc57..00000000000
--- a/contrib/libf2c/libI77/Notice
+++ /dev/null
@@ -1,23 +0,0 @@
-/****************************************************************
-Copyright 1990 - 1997 by AT&T, Lucent Technologies and Bellcore.
-
-Permission to use, copy, modify, and distribute this software
-and its documentation for any purpose and without fee is hereby
-granted, provided that the above copyright notice appear in all
-copies and that both that the copyright notice and this
-permission notice and warranty disclaimer appear in supporting
-documentation, and that the names of AT&T, Bell Laboratories,
-Lucent or Bellcore or any of their entities not be used in
-advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.
-
-AT&T, Lucent and Bellcore disclaim all warranties with regard to
-this software, including all implied warranties of
-merchantability and fitness.  In no event shall AT&T, Lucent or
-Bellcore be liable for any special, indirect or consequential
-damages or any damages whatsoever resulting from loss of use,
-data or profits, whether in an action of contract, negligence or
-other tortious action, arising out of or in connection with the
-use or performance of this software.
-****************************************************************/
-
diff --git a/contrib/libf2c/libI77/README.netlib b/contrib/libf2c/libI77/README.netlib
deleted file mode 100644
index 30dd5b5223d..00000000000
--- a/contrib/libf2c/libI77/README.netlib
+++ /dev/null
@@ -1,225 +0,0 @@
-If your compiler does not recognize ANSI C headers,
-compile with KR_headers defined:  either add -DKR_headers
-to the definition of CFLAGS in the makefile, or insert
-
-#define KR_headers
-
-at the top of f2c.h and fmtlib.c .
-
-
-If you have a really ancient K&R C compiler that does not understand
-void, add -Dvoid=int to the definition of CFLAGS in the makefile.
-
-If you use a C++ compiler, first create a local f2c.h by appending
-f2ch.add to the usual f2c.h, e.g., by issuing the command
-	make f2c.h
-which assumes f2c.h is installed in /usr/include .
-
-If your system lacks /usr/include/fcntl.h , then you
-should simply create an empty fcntl.h in this directory.
-If your compiler then complains about creat and open not
-having a prototype, compile with OPEN_DECL defined.
-On many systems, open and creat are declared in fcntl.h .
-
-If your system has /usr/include/fcntl.h, you may need to add
--D_POSIX_SOURCE to the makefile's definition of CFLAGS.
-
-If your system's sprintf does not work the way ANSI C
-specifies -- specifically, if it does not return the
-number of characters transmitted -- then insert the line
-
-#define USE_STRLEN
-
-at the end of fmt.h .  This is necessary with
-at least some versions of Sun and DEC software.
-In particular, if you get a warning about an improper
-pointer/integer combination in compiling wref.c, then
-you need to compile with -DUSE_STRLEN .
-
-If your system's fopen does not like the ANSI binary
-reading and writing modes "rb" and "wb", then you should
-compile open.c with NON_ANSI_RW_MODES #defined.
-
-If you get error messages about references to cf->_ptr
-and cf->_base when compiling wrtfmt.c and wsfe.c or to
-stderr->_flag when compiling err.c, then insert the line
-
-#define NON_UNIX_STDIO
-
-at the beginning of fio.h, and recompile everything (or
-at least those modules that contain NON_UNIX_STDIO).
-
-Unformatted sequential records consist of a length of record
-contents, the record contents themselves, and the length of
-record contents again (for backspace).  Prior to 17 Oct. 1991,
-the length was of type int; now it is of type long, but you
-can change it back to int by inserting
-
-#define UIOLEN_int
-
-at the beginning of fio.h.  This affects only sue.c and uio.c .
-
-On VAX, Cray, or Research Tenth-Edition Unix systems, you may
-need to add -DVAX, -DCRAY, or -DV10 (respectively) to CFLAGS
-to make fp.h work correctly.  Alternatively, you may need to
-edit fp.h to suit your machine.
-
-You may need to supply the following non-ANSI routines:
-
-  fstat(int fileds, struct stat *buf) is similar
-to stat(char *name, struct stat *buf), except that
-the first argument, fileds, is the file descriptor
-returned by open rather than the name of the file.
-fstat is used in the system-dependent routine
-canseek (in the libI77 source file err.c), which
-is supposed to return 1 if it's possible to issue
-seeks on the file in question, 0 if it's not; you may
-need to suitably modify err.c .  On non-UNIX systems,
-you can avoid references to fstat and stat by compiling
-with NON_UNIX_STDIO defined; in that case, you may need
-to supply access(char *Name,0), which is supposed to
-return 0 if file Name exists, nonzero otherwise.
-
-  char * mktemp(char *buf) is supposed to replace the
-6 trailing X's in buf with a unique number and then
-return buf.  The idea is to get a unique name for
-a temporary file.
-
-On non-UNIX systems, you may need to change a few other,
-e.g.: the form of name computed by mktemp() in endfile.c and
-open.c; the use of the open(), close(), and creat() system
-calls in endfile.c, err.c, open.c; and the modes in calls on
-fopen() and fdopen() (and perhaps the use of fdopen() itself
--- it's supposed to return a FILE* corresponding to a given
-an integer file descriptor) in err.c and open.c (component ufmt
-of struct unit is 1 for formatted I/O -- text mode on some systems
--- and 0 for unformatted I/O -- binary mode on some systems).
-Compiling with -DNON_UNIX_STDIO omits all references to creat()
-and almost all references to open() and close(), the exception
-being in the function f__isdev() (in open.c).
-
-For MS-DOS, compile all of libI77 with -DMSDOS (which implies
--DNON_UNIX_STDIO).  You may need to make other compiler-dependent
-adjustments; for example, for Turbo C++ you need to adjust the mktemp
-invocations and to #undef ungetc in lread.c and rsne.c .
-
-If you want to be able to load against libI77 but not libF77,
-then you will need to add sig_die.o (from libF77) to libI77.
-
-If you wish to use translated Fortran that has funny notions
-of record length for direct unformatted I/O (i.e., that assumes
-RECL= values in OPEN statements are not bytes but rather counts
-of some other units -- e.g., 4-character words for VMS), then you
-should insert an appropriate #define for url_Adjust at the
-beginning of open.c .  For VMS Fortran, for example,
-#define url_Adjust(x) x *= 4
-would suffice.
-
-To check for transmission errors, issue the command
-	make check
-This assumes you have the xsum program whose source, xsum.c,
-is distributed as part of "all from f2c/src".  If you do not
-have xsum, you can obtain xsum.c by sending the following E-mail
-message to netlib@netlib.bell-labs.com
-	send xsum.c from f2c/src
-
-The makefile assumes you have installed f2c.h in a standard
-place (and does not cause recompilation when f2c.h is changed);
-f2c.h comes with "all from f2c" (the source for f2c) and is
-available separately ("f2c.h from f2c").
-
-By default, Fortran I/O units 5, 6, and 0 are pre-connected to
-stdin, stdout, and stderr, respectively.  You can change this
-behavior by changing f_init() in err.c to suit your needs.
-Note that f2c assumes READ(*... means READ(5... and WRITE(*...
-means WRITE(6... .  Moreover, an OPEN(n,... statement that does
-not specify a file name (and does not specify STATUS='SCRATCH')
-assumes FILE='fort.n' .  You can change this by editing open.c
-and endfile.c suitably.
-
-Unless you adjust the "#define MXUNIT" line in fio.h, Fortran units
-0, 1, ..., 99 are available, i.e., the highest allowed unit number
-is MXUNIT - 1.
-
-Lines protected from compilation by #ifdef Allow_TYQUAD
-are for a possible extension to 64-bit integers in which
-integer = int = 32 bits and longint = long = 64 bits.
-
-Extensions (Feb. 1993) to NAMELIST processing:
- 1. Reading a ? instead of &name (the start of a namelist) causes
-the namelist being sought to be written to stdout (unit 6);
-to omit this feature, compile rsne.c with -DNo_Namelist_Questions.
- 2. Reading the wrong namelist name now leads to an error message
-and an attempt to skip input until the right namelist name is found;
-to omit this feature, compile rsne.c with -DNo_Bad_Namelist_Skip.
- 3. Namelist writes now insert newlines before each variable; to omit
-this feature, compile xwsne.c with -DNo_Extra_Namelist_Newlines.
- 4. (Sept. 1995) When looking for the &name that starts namelist
-input, lines whose first non-blank character is something other
-than &, $, or ? are treated as comment lines and ignored, unless
-rsne.c is compiled with -DNo_Namelist_Comments.
-
-Nonstandard extension (Feb. 1993) to open: for sequential files,
-ACCESS='APPEND' (or access='anything else starting with "A" or "a"')
-causes the file to be positioned at end-of-file, so a write will
-append to the file.
-
-Some buggy Fortran programs use unformatted direct I/O to write
-an incomplete record and later read more from that record than
-they have written.  For records other than the last, the unwritten
-portion of the record reads as binary zeros.  The last record is
-a special case: attempting to read more from it than was written
-gives end-of-file -- which may help one find a bug.  Some other
-Fortran I/O libraries treat the last record no differently than
-others and thus give no help in finding the bug of reading more
-than was written.  If you wish to have this behavior, compile
-uio.c with -DPad_UDread .
-
-If you want to be able to catch write failures (e.g., due to a
-disk being full) with an ERR= specifier, compile dfe.c, due.c,
-sfe.c, sue.c, and wsle.c with -DALWAYS_FLUSH.  This will lead to
-slower execution and more I/O, but should make ERR= work as
-expected, provided fflush returns an error return when its
-physical write fails.
-
-Carriage controls are meant to be interpreted by the UNIX col
-program (or a similar program).  Sometimes it's convenient to use
-only ' ' as the carriage control character (normal single spacing).
-If you compile lwrite.c and wsfe.c with -DOMIT_BLANK_CC, formatted
-external output lines will have an initial ' ' quietly omitted,
-making use of the col program unnecessary with output that only
-has ' ' for carriage control.
-
-The Fortran 77 Standard leaves it up to the implementation whether
-formatted writes of floating-point numbers of absolute value < 1 have
-a zero before the decimal point.  By default, libI77 omits such
-superfluous zeros, but you can cause them to appear by compiling
-lwrite.c, wref.c, and wrtfmt.c with -DWANT_LEAD_0 .
-
-If your system lacks a ranlib command, you don't need it.
-Either comment out the makefile's ranlib invocation, or install
-a harmless "ranlib" command somewhere in your PATH, such as the
-one-line shell script
-
-	exit 0
-
-or (on some systems)
-
-	exec /usr/bin/ar lts $1 >/dev/null
-
-Most of the routines in libI77 are support routines for Fortran
-I/O.  There are a few exceptions, summarized below -- I/O related
-functions and subroutines that appear to your program as ordinary
-external Fortran routines.
-
-1.	CALL FLUSH flushes all buffers.
-
-2.	FTELL(i) is an INTEGER function that returns the current
-	offset of Fortran unit i (or -1 if unit i is not open).
-
-3.	CALL FSEEK(i, offset, whence, *errlab) attemps to move
-	Fortran unit i to the specified offset: absolute offset
-	if whence = 0; relative to the current offset if whence = 1;
-	relative to the end of the file if whence = 2.  It branches
-	to label errlab if unit i is not open or if the call
-	otherwise fails.
diff --git a/contrib/libf2c/libI77/Version.c b/contrib/libf2c/libI77/Version.c
deleted file mode 100644
index f6b3d5d8a5e..00000000000
--- a/contrib/libf2c/libI77/Version.c
+++ /dev/null
@@ -1,324 +0,0 @@
-const char __LIBI77_VERSION__[] = "@(#) LIBI77 VERSION pjw,dmg-mods 20001205\n";
-
-/*
-2.01	$ format added
-2.02	Coding bug in open.c repaired
-2.03	fixed bugs in lread.c (read * with negative f-format) and lio.c
-	and lio.h (e-format conforming to spec)
-2.04	changed open.c and err.c (fopen and freopen respectively) to
-	update to new c-library (append mode)
-2.05	added namelist capability
-2.06	allow internal list and namelist I/O
-*/
-
-/*
-close.c:
-	allow upper-case STATUS= values
-endfile.c
-	create fort.nnn if unit nnn not open;
-	else if (file length == 0) use creat() rather than copy;
-	use local copy() rather than forking /bin/cp;
-	rewind, fseek to clear buffer (for no reading past EOF)
-err.c
-	use neither setbuf nor setvbuf; make stderr buffered
-fio.h
-	#define _bufend
-inquire.c
-	upper case responses;
-	omit byfile test from SEQUENTIAL=
-	answer "YES" to DIRECT= for unopened file (open to debate)
-lio.c
-	flush stderr, stdout at end of each stmt
-	space before character strings in list output only at line start
-lio.h
-	adjust LEW, LED consistent with old libI77
-lread.c
-	use atof()
-	allow "nnn*," when reading complex constants
-open.c
-	try opening for writing when open for read fails, with
-	special uwrt value (2) delaying creat() to first write;
-	set curunit so error messages don't drop core;
-	no file name ==> fort.nnn except for STATUS='SCRATCH'
-rdfmt.c
-	use atof(); trust EOF == end-of-file (so don't read past
-	end-of-file after endfile stmt)
-sfe.c
-	flush stderr, stdout at end of each stmt
-wrtfmt.c:
-	use upper case
-	put wrt_E and wrt_F into wref.c, use sprintf()
-		rather than ecvt() and fcvt() [more accurate on VAX]
-*/
-
-/* 16 Oct. 1988: uwrt = 3 after write, rewind, so close won't zap the file. */
-
-/* 10 July 1989: change _bufend to buf_end in fio.h, wsfe.c, wrtfmt.c */
-
-/* 28 Nov. 1989: corrections for IEEE and Cray arithmetic */
-/* 29 Nov. 1989: change various int return types to long for f2c */
-/* 30 Nov. 1989: various types from f2c.h */
-/*  6 Dec. 1989: types corrected various places */
-/* 19 Dec. 1989: make iostat= work right for internal I/O */
-/*  8 Jan. 1990: add rsne, wsne -- routines for handling NAMELIST */
-/* 28 Jan. 1990: have NAMELIST read treat $ as &, general white
-		 space as blank */
-/* 27 Mar. 1990: change an = to == in rd_L(rdfmt.c) so formatted reads
-		 of logical values reject letters other than fFtT;
-		 have nowwriting reset cf */
-/* 14 Aug. 1990: adjust lread.c to treat tabs as spaces in list input */
-/* 17 Aug. 1990: adjust open.c to recognize blank='Z...' as well as
-		 blank='z...' when reopening an open file */
-/* 30 Aug. 1990: prevent embedded blanks in list output of complex values;
-		 omit exponent field in list output of values of
-		 magnitude between 10 and 1e8; prevent writing stdin
-		 and reading stdout or stderr; don't close stdin, stdout,
-		 or stderr when reopening units 5, 6, 0. */
-/* 18 Sep. 1990: add component udev to unit and consider old == new file
-		 iff uinode and udev values agree; use stat rather than
-		 access to check existence of file (when STATUS='OLD')*/
-/* 2 Oct. 1990:  adjust rewind.c so two successive rewinds after a write
-		 don't clobber the file. */
-/* 9 Oct. 1990:  add #include "fcntl.h" to endfile.c, err.c, open.c;
-		 adjust g_char in util.c for segmented memories. */
-/* 17 Oct. 1990: replace abort() and _cleanup() with calls on
-		 sig_die(...,1) (defined in main.c). */
-/* 5 Nov. 1990:  changes to open.c: complain if new= is specified and the
-		 file already exists; allow file= to be omitted in open stmts
-		 and allow status='replace' (Fortran 90 extensions). */
-/* 11 Dec. 1990: adjustments for POSIX. */
-/* 15 Jan. 1991: tweak i_ungetc in rsli.c to allow reading from
-		 strings in read-only memory. */
-/* 25 Apr. 1991: adjust namelist stuff to work with f2c -i2 */
-/* 26 Apr. 1991: fix some bugs with NAMELIST read of multi-dim. arrays */
-/* 16 May 1991:  increase LEFBL in lio.h to bypass NeXT bug */
-/* 17 Oct. 1991: change type of length field in sequential unformatted
-		 records from int to long (for systems where sizeof(int)
-		 can vary, depending on the compiler or compiler options). */
-/* 14 Nov. 1991: change uint to Uint in fmt.h, rdfmt.c, wrtfmt.c. */
-/* 25 Nov. 1991: change uint to Uint in lwrite.c; change sizeof(int) to
-		 sizeof(uioint) in fseeks in sue.c (missed on 17 Oct.). */
-/* 1 Dec. 1991:  uio.c: add test for read failure (seq. unformatted reads);
-		 adjust an error return from EOF to off end of record */
-/* 12 Dec. 1991: rsli.c: fix bug with internal list input that caused
-		 the last character of each record to be ignored.
-		 iio.c: adjust error message in internal formatted
-		 input from "end-of-file" to "off end of record" if
-		 the format specifies more characters than the
-		 record contains. */
-/* 17 Jan. 1992: lread.c, rsne.c: in list and namelist input,
-		 treat "r* ," and "r*," alike (where r is a
-		 positive integer constant), and fix a bug in
-		 handling null values following items with repeat
-		 counts (e.g., 2*1,,3); for namelist reading
-		 of a numeric array, allow a new name-value subsequence
-		 to terminate the current one (as though the current
-		 one ended with the right number of null values).
-		 lio.h, lwrite.c: omit insignificant zeros in
-		 list and namelist output. To get the old
-		 behavior, compile with -DOld_list_output . */
-/* 18 Jan. 1992: make list output consistent with F format by
-		 printing .1 rather than 0.1 (introduced yesterday). */
-/* 3 Feb. 1992:  rsne.c: fix namelist read bug that caused the
-		 character following a comma to be ignored. */
-/* 19 May 1992:  adjust iio.c, ilnw.c, rdfmt.c and rsli.c to make err=
-		 work with internal list and formatted I/O. */
-/* 18 July 1992: adjust rsne.c to allow namelist input to stop at
-		 an & (e.g. &end). */
-/* 23 July 1992: switch to ANSI prototypes unless KR_headers is #defined ;
-		 recognize Z format (assuming 8-bit bytes). */
-/* 14 Aug. 1992: tweak wrt_E in wref.c to avoid -NaN */
-/* 23 Oct. 1992: Supply missing l_eof = 0 assignment to s_rsne() in rsne.c
-		 (so end-of-file on other files won't confuse namelist
-		 reads of external files).  Prepend f__ to external
-		 names that are only of internal interest to lib[FI]77. */
-/* 1 Feb. 1993:  backspace.c: fix bug that bit when last char of 2nd
-		 buffer == '\n'.
-		 endfile.c: guard against tiny L_tmpnam; close and reopen
-		 files in t_runc().
-		 lio.h: lengthen LINTW (buffer size in lwrite.c).
-		 err.c, open.c: more prepending of f__ (to [rw]_mode). */
-/* 5 Feb. 1993:  tweaks to NAMELIST: rsne.c: ? prints the namelist being
-		 sought; namelists of the wrong name are skipped (after
-		 an error message; xwsne.c: namelist writes have a
-		 newline before each new variable.
-		 open.c: ACCESS='APPEND' positions sequential files
-		 at EOF (nonstandard extension -- that doesn't require
-		 changing data structures). */
-/* 9 Feb. 1993:  Change some #ifdef MSDOS lines to #ifdef NON_UNIX_STDIO.
-		 err.c: under NON_UNIX_STDIO, avoid close(creat(name,0666))
-		 when the unit has another file descriptor for name. */
-/* 4 March 1993: err.c, open.c: take declaration of fdopen from rawio.h;
-		 open.c: always give f__w_mode[] 4 elements for use
-		 in t_runc (in endfile.c -- for change of 1 Feb. 1993). */
-/* 6 March 1993: uio.c: adjust off-end-of-record test for sequential
-		 unformatted reads to respond to err= rather than end=. */
-/* 12 March 1993: various tweaks for C++ */
-/* 6 April 1993: adjust error returns for formatted inputs to flush
-		 the current input line when err=label is specified.
-		 To restore the old behavior (input left mid-line),
-		 either adjust the #definition of errfl in fio.h or
-		 omit the invocation of f__doend in err__fl (in err.c).	*/
-/* 23 June 1993: iio.c: fix bug in format reversions for internal writes. */
-/* 5 Aug. 1993:  lread.c: fix bug in handling repetition counts for
-		 logical data (during list or namelist input).
-		 Change struct f__syl to struct syl (for buggy compilers). */
-/* 7 Aug. 1993:  lread.c: fix bug in namelist reading of incomplete
-		 logical arrays. */
-/* 9 Aug. 1993:  lread.c: fix bug in namelist reading of an incomplete
-		 array of numeric data followed by another namelist
-		 item whose name starts with 'd', 'D', 'e', or 'E'. */
-/* 8 Sept. 1993: open.c: protect #include "sys/..." with
-		 #ifndef NON_UNIX_STDIO; Version date not changed. */
-/* 10 Nov. 1993: backspace.c: add nonsense for #ifdef MSDOS */
-/* 8 Dec. 1993:  iio.c: adjust internal formatted reads to treat
-		 short records as though padded with blanks
-		 (rather than causing an "off end of record" error). */
-/* 22 Feb. 1994: lread.c: check that realloc did not return NULL. */
-/* 6 June 1994:  Under NON_UNIX_STDIO, use binary mode for direct
-		 formatted files (avoiding any confusion regarding \n). */
-/* 5 July 1994:  Fix bug (introduced 6 June 1994?) in reopening files
-		 under NON_UNIX_STDIO. */
-/* 6 July 1994:  wref.c: protect with #ifdef GOOD_SPRINTF_EXPONENT an
-		 optimization that requires exponents to have 2 digits
-		 when 2 digits suffice.
-		 lwrite.c wsfe.c (list and formatted external output):
-		 omit ' ' carriage-control when compiled with
-		 -DOMIT_BLANK_CC .  Off-by-one bug fixed in character
-		 count for list output of character strings.
-		 Omit '.' in list-directed printing of Nan, Infinity. */
-/* 12 July 1994: wrtfmt.c: under G11.4, write 0. as "  .0000    " rather
-		 than "  .0000E+00". */
-/* 3 Aug. 1994:  lwrite.c: do not insert a newline when appending an
-		 oversize item to an empty line. */
-/* 12 Aug. 1994: rsli.c rsne.c: fix glitch (reset nml_read) that kept
-		 ERR= (in list- or format-directed input) from working
-		 after a NAMELIST READ. */
-/* 7 Sept. 1994: typesize.c: adjust to allow types LOGICAL*1, LOGICAL*2,
-		 INTEGER*1, and (under -DAllow_TYQUAD) INTEGER*8
-		 in NAMELISTs. */
-/* 6 Oct. 1994:  util.c: omit f__mvgbt, as it is never used. */
-/* 2 Nov. 1994:  add #ifdef ALWAYS_FLUSH logic. */
-/* 26 Jan. 1995: wref.c: fix glitch in printing the exponent of 0 when
-		 GOOD_SPRINTF_EXPONENT is not #defined. */
-/* 24 Feb. 1995: iio.c: z_getc: insert (unsigned char *) to allow
-		 internal reading of characters with high-bit set
-		 (on machines that sign-extend characters). */
-/* 14 March 1995:lread.c and rsfe.c: adjust s_rsle and s_rsfe to
-		 check for end-of-file (to prevent infinite loops
-		 with empty read statements). */
-/* 26 May 1995:  iio.c: z_wnew: fix bug in handling T format items
-		 in internal writes whose last item is written to
-		 an earlier position than some previous item. */
-/* 29 Aug. 1995: backspace.c: adjust MSDOS logic. */
-/* 6 Sept. 1995: Adjust namelist input to treat a subscripted name
-		 whose subscripts do not involve colons similarly
-		 to the name without a subscript: accept several
-		 values, stored in successive elements starting at
-		 the indicated subscript.  Adjust namelist output
-		 to quote character strings (avoiding confusion with
-		 arrays of character strings).  Adjust f_init calls
-		 for people who don't use libF77's main(); now open and
-		 namelist read statements invoke f_init if needed. */
-/* 7 Sept. 1995: Fix some bugs with -DAllow_TYQUAD (for integer*8).
-		 Add -DNo_Namelist_Comments lines to rsne.c. */
-/* 5 Oct. 1995:  wrtfmt.c: fix bug with t editing (f__cursor was not
-		 always zeroed in mv_cur). */
-/* 11 Oct. 1995: move defs of f__hiwater, f__svic, f__icptr from wrtfmt.c
-		 to err.c */
-/* 15 Mar. 1996: lread.c, rsfe.c: honor END= in READ stmt with empty iolist */
-
-/* 13 May 1996:  add ftell_.c and fseek_.c */
-/* 9 June 1996:  Adjust rsli.c and lread.c so internal list input with
-		 too few items in the input string will honor end= . */
-/* 12 Sept. 1995:fmtlib.c: fix glitch in printing the most negative integer. */
-/* 25 Sept. 1995:fmt.h: for formatted writes of negative integer*1 values,
-		 make ic signed on ANSI systems.  If formatted writes of
-		 integer*1 values trouble you when using a K&R C compiler,
-		 switch to an ANSI compiler or use a compiler flag that
-		 makes characters signed. */
-/* 9 Dec. 1996:	 d[fu]e.c, err.c: complain about non-positive rec=
-		 in direct read and write statements.
-		 ftell_.c: change param "unit" to "Unit" for -DKR_headers. */
-/* 26 Feb. 1997: ftell_.c: on systems that define SEEK_SET, etc., use
-		 SEEK_SET, SEEK_CUR, SEEK_END for *whence = 0, 1, 2. */
-/* 7 Apr. 1997:	 fmt.c: adjust to complain at missing numbers in formats
-		 (but still treat missing ".nnn" as ".0"). */
-/* 11 Apr. 1997: err.c: attempt to make stderr line buffered rather
-		 than fully buffered.  (Buffering is needed for format
-		 items T and TR.) */
-/* 27 May 1997:  ftell_.c: fix typo (that caused the third argument to be
-		 treated as 2 on some systems). */
-/* 5 Aug. 1997:  lread.c: adjust to accord with a change to the Fortran 8X
-		 draft (in 1990 or 1991) that rescinded permission to elide
-		 quote marks in namelist input of character data; compile
-		 with -DF8X_NML_ELIDE_QUOTES to get the old behavior.
-		 wrtfmt.o: wrt_G: tweak to print the right number of 0's
-		 for zero under G format. */
-/* 16 Aug. 1997: iio.c: fix bug in internal writes to an array of character
-		 strings that sometimes caused one more array element than
-		 required by the format to be blank-filled.  Example:
-		 format(1x). */
-/* 16 Sept. 1997:fmt.[ch] rdfmt.c wrtfmt.c: tweak struct syl for machines
-		 with 64-bit pointers and 32-bit ints that did not 64-bit
-		 align struct syl (e.g., Linux on the DEC Alpha). */
-/* 19 Jan. 1998: backspace.c: for b->ufmt==0, change sizeof(int) to
-		 sizeof(uiolen).  On machines where this would make a
-		 difference, it is best for portability to compile libI77 with
-		 -DUIOLEN_int (which will render the change invisible). */
-/* 4 March 1998: open.c: fix glitch in comparing file names under
-		-DNON_UNIX_STDIO */
-/* 17 March 1998: endfile.c, open.c: acquire temporary files from tmpfile(),
-		 unless compiled with -DNON_ANSI_STDIO, which uses mktemp().
-		 New buffering scheme independent of NON_UNIX_STDIO for
-		 handling T format items.  Now -DNON_UNIX_STDIO is no
-		 longer be necessary for Linux, and libf2c no longer
-		 causes stderr to be buffered -- the former setbuf or
-		 setvbuf call for stderr was to make T format items work.
-		 open.c: use the Posix access() function to check existence
-		 or nonexistence of files, except under -DNON_POSIX_STDIO,
-		 where trial fopen calls are used. */
-/* 5 April 1998: wsfe.c: make $ format item work: this was lost in the
-		 changes of 17 March 1998. */
-/* 28 May 1998:	 backspace.c dfe.c due.c iio.c lread.c rsfe.c sue.c wsfe.c:
-		 set f__curunit sooner so various error messages will
-		 correctly identify the I/O unit involved. */
-/* 17 June 1998: lread.c: unless compiled with
-		 ALLOW_FLOAT_IN_INTEGER_LIST_INPUT #defined, treat
-		 floating-point numbers (containing either a decimal point
-		 or an exponent field) as errors when they appear as list
-		 input for integer data. */
-/* 7 Sept. 1998: move e_wdfe from sfe.c to dfe.c, where it was originally.
-		 Why did it ever move to sfe.c? */
-/* 2 May 1999:	 open.c: set f__external (to get "external" versus "internal"
-		 right in the error message if we cannot open the file).
-		 err.c: cast a pointer difference to (int) for %d.
-		 rdfmt.c: omit fixed-length buffer that could be overwritten
-		 by formats Inn or Lnn with nn > 83. */
-/* 3 May 1999:	open.c: insert two casts for machines with 64-bit longs. */
-/* 18 June 1999: backspace.c: allow for b->ufd changing in t_runc */
-/* 27 June 1999: rsne.c: fix bug in namelist input: a misplaced increment */
-/*		 could cause wrong array elements to be assigned; e.g.,	*/
-/*		 "&input k(5)=10*1 &end" assigned k(5) and k(15..23)	*/
-/* 15 Nov. 1999: endfile.c: set state to writing (b->uwrt = 1) when an */
-/*		endfile statement requires copying the file. */
-/*		(Otherwise an immediately following rewind statement */
-/*		could make the file appear empty.)  Also, supply a */
-/*		missing (long) cast in the sprintf call. */
-/*		 sfe.c: add #ifdef ALWAYS_FLUSH logic, for formatted I/O: */
-/*		Compiling libf2c with -DALWAYS_FLUSH should prevent losing */
-/*		any data in buffers should the program fault.  It also */
-/*		makes the program run more slowly. */
-/* 20 April 2000: rsne.c, xwsne.c: tweaks that only matter if ftnint and */
-/*		ftnlen are of different fundamental types (different numbers */
-/*		of bits).  Since these files will not compile when this */
-/*		change matters, the above VERSION string remains unchanged. */
-/* 4 July 2000: adjustments to permit compilation by C++ compilers; */
-/*		VERSION string remains unchanged. NOT APPLIED FOR G77 */
-/* 5 Dec. 2000: lread.c: under namelist input, when reading a logical array, */
-/*		treat Tstuff= and Fstuff= as new assignments rather than as */
-/*		logical constants. */
-
-/* Changes for GNU Fortran (g77) version of libf2c:  */
-
-/* 17 June 1997: detect recursive I/O and call f__fatal explaining it. */
diff --git a/contrib/libf2c/libI77/backspace.c b/contrib/libf2c/libI77/backspace.c
deleted file mode 100644
index c31e71147b5..00000000000
--- a/contrib/libf2c/libI77/backspace.c
+++ /dev/null
@@ -1,81 +0,0 @@
-#include "config.h"
-#include 
-#include "f2c.h"
-#include "fio.h"
-integer
-f_back (alist * a)
-{
-  unit *b;
-  off_t v, w, x, y, z;
-  uiolen n;
-  FILE *f;
-
-  f__curunit = b = &f__units[a->aunit];	/* curunit for error messages */
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  if (a->aunit >= MXUNIT || a->aunit < 0)
-    err (a->aerr, 101, "backspace");
-  if (b->useek == 0)
-    err (a->aerr, 106, "backspace");
-  if (b->ufd == NULL)
-    {
-      fk_open (1, 1, a->aunit);
-      return (0);
-    }
-  if (b->uend == 1)
-    {
-      b->uend = 0;
-      return (0);
-    }
-  if (b->uwrt)
-    {
-      t_runc (a);
-      if (f__nowreading (b))
-	err (a->aerr, errno, "backspace");
-    }
-  f = b->ufd;			/* may have changed in t_runc() */
-  if (b->url > 0)
-    {
-      x = FTELL (f);
-      y = x % b->url;
-      if (y == 0)
-	x--;
-      x /= b->url;
-      x *= b->url;
-      FSEEK (f, x, SEEK_SET);
-      return (0);
-    }
-
-  if (b->ufmt == 0)
-    {
-      FSEEK (f, -(off_t) sizeof (uiolen), SEEK_CUR);
-      fread ((char *) &n, sizeof (uiolen), 1, f);
-      FSEEK (f, -(off_t) n - 2 * sizeof (uiolen), SEEK_CUR);
-      return (0);
-    }
-  w = x = FTELL (f);
-  z = 0;
-loop:
-  while (x)
-    {
-      x -= x < 64 ? x : 64;
-      FSEEK (f, x, SEEK_SET);
-      for (y = x; y < w; y++)
-	{
-	  if (getc (f) != '\n')
-	    continue;
-	  v = FTELL (f);
-	  if (v == w)
-	    {
-	      if (z)
-		goto break2;
-	      goto loop;
-	    }
-	  z = v;
-	}
-      err (a->aerr, (EOF), "backspace");
-    }
-break2:
-  FSEEK (f, z, SEEK_SET);
-  return 0;
-}
diff --git a/contrib/libf2c/libI77/close.c b/contrib/libf2c/libI77/close.c
deleted file mode 100644
index 769c569f8c5..00000000000
--- a/contrib/libf2c/libI77/close.c
+++ /dev/null
@@ -1,101 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-
-#undef abs
-#undef min
-#undef max
-#include 
-#ifdef NON_UNIX_STDIO
-#ifndef unlink
-#define unlink remove
-#endif
-#else
-#if defined (MSDOS) && !defined (GO32)
-#include "io.h"
-#else
-extern int unlink (const char *);
-#endif
-#endif
-
-integer
-f_clos (cllist * a)
-{
-  unit *b;
-
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  if (a->cunit >= MXUNIT)
-    return (0);
-  b = &f__units[a->cunit];
-  if (b->ufd == NULL)
-    goto done;
-  if (b->uscrtch == 1)
-    goto Delete;
-  if (!a->csta)
-    goto Keep;
-  switch (*a->csta)
-    {
-    default:
-    Keep:
-    case 'k':
-    case 'K':
-      if (b->uwrt == 1)
-	t_runc ((alist *) a);
-      if (b->ufnm)
-	{
-	  fclose (b->ufd);
-	  free (b->ufnm);
-	}
-      break;
-    case 'd':
-    case 'D':
-    Delete:
-      fclose (b->ufd);
-      if (b->ufnm)
-	{
-	  unlink (b->ufnm);
-	  /*SYSDEP*/ free (b->ufnm);
-	}
-    }
-  b->ufd = NULL;
-done:
-  b->uend = 0;
-  b->ufnm = NULL;
-  return (0);
-}
-
-void
-f_exit (void)
-{
-  int i;
-  static cllist xx;
-  if (!(f__init & 1))
-    return;			/* Not initialized, so no open units. */
-  /* I/O no longer in progress.  If, during an I/O operation (such
-     as waiting for the user to enter a line), there is an
-     interrupt (such as ^C to stop the program on a UNIX system),
-     f_exit() is called, but there is no longer any I/O in
-     progress.  Without turning off this flag, f_clos() would
-     think that there is an I/O recursion in this circumstance. */
-  f__init &= ~2;
-  if (!xx.cerr)
-    {
-      xx.cerr = 1;
-      xx.csta = NULL;
-      for (i = 0; i < MXUNIT; i++)
-	{
-	  xx.cunit = i;
-	  (void) f_clos (&xx);
-	}
-    }
-}
-int
-G77_flush_0 (void)
-{
-  int i;
-  for (i = 0; i < MXUNIT; i++)
-    if (f__units[i].ufd != NULL && f__units[i].uwrt)
-      fflush (f__units[i].ufd);
-  return 0;
-}
diff --git a/contrib/libf2c/libI77/config.h.in b/contrib/libf2c/libI77/config.h.in
deleted file mode 100644
index 63aacb5d5e1..00000000000
--- a/contrib/libf2c/libI77/config.h.in
+++ /dev/null
@@ -1,62 +0,0 @@
-/* config.h.in.  Generated automatically from configure.in by autoheader 2.13.  */
-
-/* Define to empty if the keyword does not work.  */
-#undef const
-
-/* Define to `long' if  doesn't define.  */
-#undef off_t
-
-/* Define to `unsigned' if  doesn't define.  */
-#undef size_t
-
-/* Define if you have the ANSI C header files.  */
-#undef STDC_HEADERS
-
-/* Define if you have the fseeko function.  */
-#undef HAVE_FSEEKO
-
-/* Define if you have the ftello function.  */
-#undef HAVE_FTELLO
-
-/* Define if you have the ftruncate function.  */
-#undef HAVE_FTRUNCATE
-
-/* Define if you have the mkstemp function.  */
-#undef HAVE_MKSTEMP
-
-/* Define if you have the tempnam function.  */
-#undef HAVE_TEMPNAM
-
-/* Define if you have the tmpnam function.  */
-#undef HAVE_TMPNAM
-
-/* Get Single Unix Specification semantics */
-#undef _XOPEN_SOURCE
-
-/* Get Single Unix Specification semantics */
-#undef _XOPEN_SOURCE_EXTENDED
-
-/* Solaris extensions */
-#undef __EXTENSIONS__
-
-/* Get 64-bit file size support */
-#undef _FILE_OFFSET_BITS
-
-/* Define for HP-UX ftello and fseeko extension. */
-#undef _LARGEFILE_SOURCE
-
-/* Define if we do not have Unix Stdio. */
-#undef NON_UNIX_STDIO
-
-/* Define if we use strlen. */
-#undef USE_STRLEN
-
-/* Define if we have non ANSI RW modes. */
-#undef NON_ANSI_RW_MODES
-
-/* Always defined. */
-#undef NO_EOF_CHAR_CHECK
-
-/* Define to skip f2c undefs. */
-#undef Skip_f2c_Undefs
-
diff --git a/contrib/libf2c/libI77/configure b/contrib/libf2c/libI77/configure
deleted file mode 100755
index 3d3b6dcdfb5..00000000000
--- a/contrib/libf2c/libI77/configure
+++ /dev/null
@@ -1,2123 +0,0 @@
-#! /bin/sh
-
-# Guess values for system-dependent variables and create Makefiles.
-# Generated automatically using autoconf version 2.13 
-# Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc.
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-
-# Defaults:
-ac_help=
-ac_default_prefix=/usr/local
-# Any additions from configure.in:
-
-# Initialize some variables set by options.
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
-exec_prefix=NONE
-host=NONE
-no_create=
-nonopt=NONE
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-target=NONE
-verbose=
-x_includes=NONE
-x_libraries=NONE
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
-
-# Initialize some other variables.
-subdirs=
-MFLAGS= MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-# Maximum number of lines to put in a shell here document.
-ac_max_here_lines=12
-
-ac_prev=
-for ac_option
-do
-
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
-    ac_prev=
-    continue
-  fi
-
-  case "$ac_option" in
-  -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
-  *) ac_optarg= ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case "$ac_option" in
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file="$ac_optarg" ;;
-
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
-
-  -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    eval "enable_${ac_feature}=no" ;;
-
-  -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "enable_${ac_feature}='$ac_optarg'" ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he)
-    # Omit some internal or obsolete options to make the list less imposing.
-    # This message is too long to be a string in the A/UX 3.1 sh.
-    cat << EOF
-Usage: configure [options] [host]
-Options: [defaults in brackets after descriptions]
-Configuration:
-  --cache-file=FILE       cache test results in FILE
-  --help                  print this message
-  --no-create             do not create output files
-  --quiet, --silent       do not print \`checking...' messages
-  --version               print the version of autoconf that created configure
-Directory and file names:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [same as prefix]
-  --bindir=DIR            user executables in DIR [EPREFIX/bin]
-  --sbindir=DIR           system admin executables in DIR [EPREFIX/sbin]
-  --libexecdir=DIR        program executables in DIR [EPREFIX/libexec]
-  --datadir=DIR           read-only architecture-independent data in DIR
-                          [PREFIX/share]
-  --sysconfdir=DIR        read-only single-machine data in DIR [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data in DIR
-                          [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data in DIR [PREFIX/var]
-  --libdir=DIR            object code libraries in DIR [EPREFIX/lib]
-  --includedir=DIR        C header files in DIR [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc in DIR [/usr/include]
-  --infodir=DIR           info documentation in DIR [PREFIX/info]
-  --mandir=DIR            man documentation in DIR [PREFIX/man]
-  --srcdir=DIR            find the sources in DIR [configure dir or ..]
-  --program-prefix=PREFIX prepend PREFIX to installed program names
-  --program-suffix=SUFFIX append SUFFIX to installed program names
-  --program-transform-name=PROGRAM
-                          run sed PROGRAM on installed program names
-EOF
-    cat << EOF
-Host type:
-  --build=BUILD           configure for building on BUILD [BUILD=HOST]
-  --host=HOST             configure for HOST [guessed]
-  --target=TARGET         configure for TARGET [TARGET=HOST]
-Features and packages:
-  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
-  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --x-includes=DIR        X include files are in DIR
-  --x-libraries=DIR       X library files are in DIR
-EOF
-    if test -n "$ac_help"; then
-      echo "--enable and --with options recognized:$ac_help"
-    fi
-    exit 0 ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir="$ac_optarg" ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir="$ac_optarg" ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix="$ac_optarg" ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix="$ac_optarg" ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir="$ac_optarg" ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers)
-    echo "configure generated by autoconf version 2.13"
-    exit 0 ;;
-
-  -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "with_${ac_package}='$ac_optarg'" ;;
-
-  -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    eval "with_${ac_package}=no" ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes="$ac_optarg" ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries="$ac_optarg" ;;
-
-  -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
-    ;;
-
-  *)
-    if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then
-      echo "configure: warning: $ac_option: invalid host type" 1>&2
-    fi
-    if test "x$nonopt" != xNONE; then
-      { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; }
-    fi
-    nonopt="$ac_option"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; }
-fi
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-# File descriptor usage:
-# 0 standard input
-# 1 file creation
-# 2 errors and warnings
-# 3 some systems may open it to /dev/tty
-# 4 used on the Kubota Titan
-# 6 checking for... messages and results
-# 5 compiler messages saved in config.log
-if test "$silent" = yes; then
-  exec 6>/dev/null
-else
-  exec 6>&1
-fi
-exec 5>./config.log
-
-echo "\
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-" 1>&5
-
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Also quote any args containing shell metacharacters.
-ac_configure_args=
-for ac_arg
-do
-  case "$ac_arg" in
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c) ;;
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;;
-  *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
-  ac_configure_args="$ac_configure_args '$ac_arg'" ;;
-  *) ac_configure_args="$ac_configure_args $ac_arg" ;;
-  esac
-done
-
-# NLS nuisances.
-# Only set these to C if already set.  These must not be set unconditionally
-# because not all systems understand e.g. LANG=C (notably SCO).
-# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
-# Non-C LC_CTYPE values break the ctype check.
-if test "${LANG+set}"   = set; then LANG=C;   export LANG;   fi
-if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
-if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
-if test "${LC_CTYPE+set}"    = set; then LC_CTYPE=C;    export LC_CTYPE;    fi
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo > confdefs.h
-
-# A filename unique to this package, relative to the directory that
-# configure is in, which we can look for to find out if srcdir is correct.
-ac_unique_file=ftell_.c
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_prog=$0
-  ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'`
-  test "x$ac_confdir" = "x$ac_prog" && ac_confdir=.
-  srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; }
-  else
-    { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; }
-  fi
-fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
-fi
-for ac_site_file in $CONFIG_SITE; do
-  if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
-    . "$ac_site_file"
-  fi
-done
-
-if test -r "$cache_file"; then
-  echo "loading cache $cache_file"
-  . $cache_file
-else
-  echo "creating cache $cache_file"
-  > $cache_file
-fi
-
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-ac_exeext=
-ac_objext=o
-if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
-  # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu.
-  if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
-    ac_n= ac_c='
-' ac_t='	'
-  else
-    ac_n=-n ac_c= ac_t=
-  fi
-else
-  ac_n= ac_c='\c' ac_t=
-fi
-
-
-
-
-
-
-# For g77 we'll set CC to point at the built gcc, but this will get it into
-# the makefiles
-# Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:534: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="gcc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:564: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_prog_rejected=no
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then
-        ac_prog_rejected=yes
-	continue
-      fi
-      ac_cv_prog_CC="cc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# -gt 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    set dummy "$ac_dir/$ac_word" "$@"
-    shift
-    ac_cv_prog_CC="$@"
-  fi
-fi
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-  if test -z "$CC"; then
-    case "`uname -s`" in
-    *win32* | *WIN32*)
-      # Extract the first word of "cl", so it can be a program name with args.
-set dummy cl; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:615: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="cl"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
- ;;
-    esac
-  fi
-  test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
-fi
-
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:648: checking whether we are using GNU C" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.c <&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gcc=yes
-else
-  ac_cv_prog_gcc=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gcc" 1>&6
-
-if test $ac_cv_prog_gcc = yes; then
-  GCC=yes
-else
-  GCC=
-fi
-
-ac_test_CFLAGS="${CFLAGS+set}"
-ac_save_CFLAGS="$CFLAGS"
-CFLAGS=
-echo $ac_n "checking whether ${CC-cc} accepts -g""... $ac_c" 1>&6
-echo "configure:676: checking whether ${CC-cc} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cc_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.c
-if test -z "`${CC-cc} -g -c conftest.c 2>&1`"; then
-  ac_cv_prog_cc_g=yes
-else
-  ac_cv_prog_cc_g=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS="$ac_save_CFLAGS"
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-
-
-# These defines are necessary to get 64-bit file size support.
-# NetBSD 1.4 header files does not support XOPEN_SOURCE == 600, but it
-# handles 64-bit file sizes without needing these defines.
-echo $ac_n "checking whether _XOPEN_SOURCE may be defined""... $ac_c" 1>&6
-echo "configure:712: checking whether _XOPEN_SOURCE may be defined" >&5
-cat > conftest.$ac_ext <
-int main() {
-
-; return 0; }
-EOF
-if { (eval echo configure:722: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  may_use_xopen_source=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  may_use_xopen_source=no
-fi
-rm -f conftest*
-echo "$ac_t""$may_use_xopen_source" 1>&6
-if test $may_use_xopen_source = yes; then
-  cat >> confdefs.h <<\EOF
-#define _XOPEN_SOURCE 600L
-EOF
-
-  # The following is needed by irix6.2 so that struct timeval is declared.
-  cat >> confdefs.h <<\EOF
-#define _XOPEN_SOURCE_EXTENDED 1
-EOF
-
-  # The following is needed by Solaris2.5.1 so that struct timeval is declared.
-  cat >> confdefs.h <<\EOF
-#define __EXTENSIONS__ 1
-EOF
-
-  cat >> confdefs.h <<\EOF
-#define _FILE_OFFSET_BITS 64
-EOF
-
-  cat >> confdefs.h <<\EOF
-#define _LARGEFILE_SOURCE 1
-EOF
-
-fi
-
-
-LIBTOOL='$(SHELL) ../libtool'
-
-
-test "$AR" || AR=ar
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:765: checking whether ${MAKE-make} sets \${MAKE}" >&5
-set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_prog_make_${ac_make}_set'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftestmake <<\EOF
-all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
-# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
-eval `${MAKE-make} -f conftestmake 2>/dev/null | grep temp=`
-if test -n "$ac_maketemp"; then
-  eval ac_cv_prog_make_${ac_make}_set=yes
-else
-  eval ac_cv_prog_make_${ac_make}_set=no
-fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  SET_MAKE=
-else
-  echo "$ac_t""no" 1>&6
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-
-
-# Sanity check for the cross-compilation case:
-echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:795: checking how to run the C preprocessor" >&5
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-    # This must be in double quotes, not single quotes, because CPP may get
-  # substituted into the Makefile and "${CC-cc}" will confuse make.
-  CPP="${CC-cc} -E"
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp.
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:816: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -E -traditional-cpp"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:833: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -nologo -E"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:850: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP=/lib/cpp
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-  ac_cv_prog_CPP="$CPP"
-fi
-  CPP="$ac_cv_prog_CPP"
-else
-  ac_cv_prog_CPP="$CPP"
-fi
-echo "$ac_t""$CPP" 1>&6
-
-ac_safe=`echo "stdio.h" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for stdio.h""... $ac_c" 1>&6
-echo "configure:876: checking for stdio.h" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:886: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=yes"
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  :
-else
-  echo "$ac_t""no" 1>&6
-{ echo "configure: error: Can't find stdio.h.
-You must have a usable C system for the target already installed, at least
-including headers and, preferably, the library, before you can configure
-the G77 runtime system.  If necessary, install gcc now with \`LANGUAGES=c',
-then the target library, then build with \`LANGUAGES=f77'." 1>&2; exit 1; }
-fi
-
-
-echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6
-echo "configure:914: checking for ANSI C header files" >&5
-if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#include 
-#include 
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:927: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  ac_cv_header_stdc=yes
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-cat > conftest.$ac_ext <
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "memchr" >/dev/null 2>&1; then
-  :
-else
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-cat > conftest.$ac_ext <
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "free" >/dev/null 2>&1; then
-  :
-else
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-if test "$cross_compiling" = yes; then
-  :
-else
-  cat > conftest.$ac_ext <
-#define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-#define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int main () { int i; for (i = 0; i < 256; i++)
-if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) exit(2);
-exit (0); }
-
-EOF
-if { (eval echo configure:994: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
-  :
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -fr conftest*
-  ac_cv_header_stdc=no
-fi
-rm -fr conftest*
-fi
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_header_stdc" 1>&6
-if test $ac_cv_header_stdc = yes; then
-  cat >> confdefs.h <<\EOF
-#define STDC_HEADERS 1
-EOF
-
-fi
-
-echo $ac_n "checking for posix""... $ac_c" 1>&6
-echo "configure:1018: checking for posix" >&5
-if eval "test \"`echo '$''{'g77_cv_header_posix'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#ifdef _POSIX_VERSION
-  yes
-#endif
-
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  g77_cv_header_posix=yes
-else
-  rm -rf conftest*
-  g77_cv_header_posix=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$g77_cv_header_posix" 1>&6
-
-# We can rely on the GNU library being posix-ish.  I guess checking the 
-# header isn't actually like checking the functions, though...
-echo $ac_n "checking for GNU library""... $ac_c" 1>&6
-echo "configure:1049: checking for GNU library" >&5
-if eval "test \"`echo '$''{'g77_cv_lib_gnu'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#ifdef __GNU_LIBRARY__
-  yes
-#endif
-
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  g77_cv_lib_gnu=yes
-else
-  rm -rf conftest*
-  g77_cv_lib_gnu=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$g77_cv_lib_gnu" 1>&6
-
-# Apparently cygwin needs to be special-cased.
-echo $ac_n "checking for cyg\`win'32""... $ac_c" 1>&6
-echo "configure:1078: checking for cyg\`win'32" >&5
-if eval "test \"`echo '$''{'g77_cv_sys_cygwin32'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  g77_cv_sys_cygwin32=yes
-else
-  rm -rf conftest*
-  g77_cv_sys_cygwin32=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$g77_cv_sys_cygwin32" 1>&6
-
-# ditto for mingw32.
-echo $ac_n "checking for mingw32""... $ac_c" 1>&6
-echo "configure:1106: checking for mingw32" >&5
-if eval "test \"`echo '$''{'g77_cv_sys_mingw32'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  g77_cv_sys_mingw32=yes
-else
-  rm -rf conftest*
-  g77_cv_sys_mingw32=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$g77_cv_sys_mingw32" 1>&6
-
-
-echo $ac_n "checking for working const""... $ac_c" 1>&6
-echo "configure:1134: checking for working const" >&5
-if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <j = 5;
-}
-{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
-  const int foo = 10;
-}
-
-; return 0; }
-EOF
-if { (eval echo configure:1188: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_c_const=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_c_const=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_c_const" 1>&6
-if test $ac_cv_c_const = no; then
-  cat >> confdefs.h <<\EOF
-#define const 
-EOF
-
-fi
-
-echo $ac_n "checking for size_t""... $ac_c" 1>&6
-echo "configure:1209: checking for size_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#if STDC_HEADERS
-#include 
-#include 
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "(^|[^a-zA-Z_0-9])size_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
-  rm -rf conftest*
-  ac_cv_type_size_t=yes
-else
-  rm -rf conftest*
-  ac_cv_type_size_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_size_t" 1>&6
-if test $ac_cv_type_size_t = no; then
-  cat >> confdefs.h <<\EOF
-#define size_t unsigned
-EOF
-
-fi
-
-
-
-# This should always succeed on unix.
-# Apparently positive result on cygwin loses re. NON_UNIX_STDIO
-# (as of cygwin b18). Likewise on mingw.
-echo $ac_n "checking for fstat""... $ac_c" 1>&6
-echo "configure:1247: checking for fstat" >&5
-if eval "test \"`echo '$''{'ac_cv_func_fstat'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char fstat();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_fstat) || defined (__stub___fstat)
-choke me
-#else
-fstat();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1275: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_fstat=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_fstat=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'fstat`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  :
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-echo $ac_n "checking need for NON_UNIX_STDIO""... $ac_c" 1>&6
-echo "configure:1295: checking need for NON_UNIX_STDIO" >&5
-if test $g77_cv_sys_cygwin32 = yes \
-  || test $g77_cv_sys_mingw32 = yes \
-  || test $ac_cv_func_fstat = no; then
-  echo "$ac_t""yes" 1>&6
-  cat >> confdefs.h <<\EOF
-#define NON_UNIX_STDIO 1
-EOF
-
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-for ac_func in fseeko
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1311: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1339: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-for ac_func in ftello
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1366: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1394: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-for ac_func in ftruncate
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1421: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1449: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-for ac_func in mkstemp
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1476: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1504: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-for ac_func in tempnam
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1531: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1559: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-for ac_func in tmpnam
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1586: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1614: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-
-# posix will guarantee the right behaviour for sprintf, else we can't be
-# sure; HEADER_STDC wouldn't be the right check in sunos4, for instance.
-# However, on my sunos4/gcc setup unistd.h leads us wrongly to believe
-# we're posix-conformant, so always do the test.
-echo $ac_n "checking for ansi/posix sprintf result""... $ac_c" 1>&6
-echo "configure:1644: checking for ansi/posix sprintf result" >&5
-if test "$cross_compiling" = yes; then
-  g77_cv_sys_sprintf_ansi=no
-else
-  cat > conftest.$ac_ext <
-    /* does sprintf return the number of chars transferred? */
-    main () {char foo[2]; (sprintf(foo, "1") == 1) ? exit(0) : exit(1);}
-
-EOF
-if { (eval echo configure:1656: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
-  g77_cv_sys_sprintf_ansi=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -fr conftest*
-  g77_cv_sys_sprintf_ansi=no
-fi
-rm -fr conftest*
-fi
-
-if eval "test \"`echo '$''{'g77_cv_sys_sprintf_ansi'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  g77_cv_sys_sprintf_ansi=$g77_cv_sys_sprintf_ansi
-fi
-
-echo "$ac_t""$g77_cv_sys_sprintf_ansi" 1>&6
-
-# The cygwin patch takes steps to avoid defining USE_STRLEN here -- I don't
-# understand why.
-if test $g77_cv_sys_sprintf_ansi != yes; then 
-  cat >> confdefs.h <<\EOF
-#define USE_STRLEN 1
-EOF
-
-fi
-
-# define NON_ANSI_RW_MODES on unix (can't hurt)
-echo $ac_n "checking NON_ANSI_RW_MODES""... $ac_c" 1>&6
-echo "configure:1687: checking NON_ANSI_RW_MODES" >&5
-cat > conftest.$ac_ext <&5 |
-  egrep "yes" >/dev/null 2>&1; then
-  rm -rf conftest*
-  is_unix=yes
-else
-  rm -rf conftest*
-  is_unix=no
-fi
-rm -f conftest*
-
-# NON_ANSI_RW_MODES shouldn't be necessary on cygwin for binary mounts.
-if test $g77_cv_sys_cygwin32 = yes || test $g77_cv_sys_mingw32 = yes; then
-  echo "$ac_t""no" 1>&6
-else
-  if test $is_unix = yes; then
-    cat >> confdefs.h <<\EOF
-#define NON_ANSI_RW_MODES 1
-EOF
-
-    echo "$ac_t""yes" 1>&6
-  else
-    echo "$ac_t""no" 1>&6
-  fi
-fi
-
-# This EOF_CHAR is a misfeature on unix.
-cat >> confdefs.h <<\EOF
-#define NO_EOF_CHAR_CHECK 1
-EOF
-
-
-echo $ac_n "checking for off_t""... $ac_c" 1>&6
-echo "configure:1734: checking for off_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_off_t'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#if STDC_HEADERS
-#include 
-#include 
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "(^|[^a-zA-Z_0-9])off_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
-  rm -rf conftest*
-  ac_cv_type_off_t=yes
-else
-  rm -rf conftest*
-  ac_cv_type_off_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_off_t" 1>&6
-if test $ac_cv_type_off_t = no; then
-  cat >> confdefs.h <<\EOF
-#define off_t long
-EOF
-
-fi
-
-
-cat >> confdefs.h <<\EOF
-#define Skip_f2c_Undefs 1
-EOF
-
-
-trap '' 1 2 15
-cat > confcache <<\EOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs.  It is not useful on other systems.
-# If it contains results you don't want to keep, you may remove or edit it.
-#
-# By default, configure uses ./config.cache as the cache file,
-# creating it if it does not exist already.  You can give configure
-# the --cache-file=FILE option to use a different cache file; that is
-# what configure does when it calls configure scripts in
-# subdirectories, so they share the cache.
-# Giving --cache-file=/dev/null disables caching, for debugging configure.
-# config.status only pays attention to the cache file if you give it the
-# --recheck option to rerun configure.
-#
-EOF
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(set) 2>&1 |
-  case `(ac_space=' '; set | grep ac_space) 2>&1` in
-  *ac_space=\ *)
-    # `set' does not quote correctly, so add quotes (double-quote substitution
-    # turns \\\\ into \\, and sed turns \\ into \).
-    sed -n \
-      -e "s/'/'\\\\''/g" \
-      -e "s/^\\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\\)=\\(.*\\)/\\1=\${\\1='\\2'}/p"
-    ;;
-  *)
-    # `set' quotes correctly as required by POSIX, so do not add quotes.
-    sed -n -e 's/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=${\1=\2}/p'
-    ;;
-  esac >> confcache
-if cmp -s $cache_file confcache; then
-  :
-else
-  if test -w $cache_file; then
-    echo "updating cache $cache_file"
-    cat confcache > $cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Any assignment to VPATH causes Sun make to only execute
-# the first set of double-colon rules, so remove it if not needed.
-# If there is a colon in the path, we need to keep it.
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[ 	]*VPATH[ 	]*=[^:]*$/d'
-fi
-
-trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15
-
-DEFS=-DHAVE_CONFIG_H
-
-# Without the "./", some shells look in PATH for config.status.
-: ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS </dev/null | sed 1q`:
-#
-# $0 $ac_configure_args
-#
-# Compiler output produced by configure, useful for debugging
-# configure, is in ./config.log if it exists.
-
-ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
-for ac_option
-do
-  case "\$ac_option" in
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion"
-    exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;;
-  -version | --version | --versio | --versi | --vers | --ver | --ve | --v)
-    echo "$CONFIG_STATUS generated by autoconf version 2.13"
-    exit 0 ;;
-  -help | --help | --hel | --he | --h)
-    echo "\$ac_cs_usage"; exit 0 ;;
-  *) echo "\$ac_cs_usage"; exit 1 ;;
-  esac
-done
-
-ac_given_srcdir=$srcdir
-
-trap 'rm -fr `echo "Makefile config.h" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15
-EOF
-cat >> $CONFIG_STATUS < conftest.subs <<\\CEOF
-$ac_vpsub
-$extrasub
-s%@SHELL@%$SHELL%g
-s%@CFLAGS@%$CFLAGS%g
-s%@CPPFLAGS@%$CPPFLAGS%g
-s%@CXXFLAGS@%$CXXFLAGS%g
-s%@FFLAGS@%$FFLAGS%g
-s%@DEFS@%$DEFS%g
-s%@LDFLAGS@%$LDFLAGS%g
-s%@LIBS@%$LIBS%g
-s%@exec_prefix@%$exec_prefix%g
-s%@prefix@%$prefix%g
-s%@program_transform_name@%$program_transform_name%g
-s%@bindir@%$bindir%g
-s%@sbindir@%$sbindir%g
-s%@libexecdir@%$libexecdir%g
-s%@datadir@%$datadir%g
-s%@sysconfdir@%$sysconfdir%g
-s%@sharedstatedir@%$sharedstatedir%g
-s%@localstatedir@%$localstatedir%g
-s%@libdir@%$libdir%g
-s%@includedir@%$includedir%g
-s%@oldincludedir@%$oldincludedir%g
-s%@infodir@%$infodir%g
-s%@mandir@%$mandir%g
-s%@CC@%$CC%g
-s%@LIBTOOL@%$LIBTOOL%g
-s%@AR@%$AR%g
-s%@SET_MAKE@%$SET_MAKE%g
-s%@CPP@%$CPP%g
-
-CEOF
-EOF
-
-cat >> $CONFIG_STATUS <<\EOF
-
-# Split the substitutions into bite-sized pieces for seds with
-# small command number limits, like on Digital OSF/1 and HP-UX.
-ac_max_sed_cmds=90 # Maximum number of lines to put in a sed script.
-ac_file=1 # Number of current file.
-ac_beg=1 # First line for current file.
-ac_end=$ac_max_sed_cmds # Line after last line for current file.
-ac_more_lines=:
-ac_sed_cmds=""
-while $ac_more_lines; do
-  if test $ac_beg -gt 1; then
-    sed "1,${ac_beg}d; ${ac_end}q" conftest.subs > conftest.s$ac_file
-  else
-    sed "${ac_end}q" conftest.subs > conftest.s$ac_file
-  fi
-  if test ! -s conftest.s$ac_file; then
-    ac_more_lines=false
-    rm -f conftest.s$ac_file
-  else
-    if test -z "$ac_sed_cmds"; then
-      ac_sed_cmds="sed -f conftest.s$ac_file"
-    else
-      ac_sed_cmds="$ac_sed_cmds | sed -f conftest.s$ac_file"
-    fi
-    ac_file=`expr $ac_file + 1`
-    ac_beg=$ac_end
-    ac_end=`expr $ac_end + $ac_max_sed_cmds`
-  fi
-done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
-fi
-EOF
-
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case "$ac_file" in
-  *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
-       ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
-  *) ac_file_in="${ac_file}.in" ;;
-  esac
-
-  # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
-
-  # Remove last slash and all that follows it.  Not all systems have dirname.
-  ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
-  if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
-    # The file is in a subdirectory.
-    test ! -d "$ac_dir" && mkdir "$ac_dir"
-    ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`"
-    # A "../" for each directory in $ac_dir_suffix.
-    ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'`
-  else
-    ac_dir_suffix= ac_dots=
-  fi
-
-  case "$ac_given_srcdir" in
-  .)  srcdir=.
-      if test -z "$ac_dots"; then top_srcdir=.
-      else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;;
-  /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;;
-  *) # Relative path.
-    srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix"
-    top_srcdir="$ac_dots$ac_given_srcdir" ;;
-  esac
-
-
-  echo creating "$ac_file"
-  rm -f "$ac_file"
-  configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure."
-  case "$ac_file" in
-  *Makefile*) ac_comsub="1i\\
-# $configure_input" ;;
-  *) ac_comsub= ;;
-  esac
-
-  ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
-  sed -e "$ac_comsub
-s%@configure_input@%$configure_input%g
-s%@srcdir@%$srcdir%g
-s%@top_srcdir@%$top_srcdir%g
-" $ac_file_inputs | (eval "$ac_sed_cmds") > $ac_file
-fi; done
-rm -f conftest.s*
-
-# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where
-# NAME is the cpp macro being defined and VALUE is the value it is being given.
-#
-# ac_d sets the value in "#define NAME VALUE" lines.
-ac_dA='s%^\([ 	]*\)#\([ 	]*define[ 	][ 	]*\)'
-ac_dB='\([ 	][ 	]*\)[^ 	]*%\1#\2'
-ac_dC='\3'
-ac_dD='%g'
-# ac_u turns "#undef NAME" with trailing blanks into "#define NAME VALUE".
-ac_uA='s%^\([ 	]*\)#\([ 	]*\)undef\([ 	][ 	]*\)'
-ac_uB='\([ 	]\)%\1#\2define\3'
-ac_uC=' '
-ac_uD='\4%g'
-# ac_e turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
-ac_eA='s%^\([ 	]*\)#\([ 	]*\)undef\([ 	][ 	]*\)'
-ac_eB='$%\1#\2define\3'
-ac_eC=' '
-ac_eD='%g'
-
-if test "${CONFIG_HEADERS+set}" != set; then
-EOF
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-fi
-for ac_file in .. $CONFIG_HEADERS; do if test "x$ac_file" != x..; then
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case "$ac_file" in
-  *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
-       ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
-  *) ac_file_in="${ac_file}.in" ;;
-  esac
-
-  echo creating $ac_file
-
-  rm -f conftest.frag conftest.in conftest.out
-  ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
-  cat $ac_file_inputs > conftest.in
-
-EOF
-
-# Transform confdefs.h into a sed script conftest.vals that substitutes
-# the proper values into config.h.in to produce config.h.  And first:
-# Protect against being on the right side of a sed subst in config.status.
-# Protect against being in an unquoted here document in config.status.
-rm -f conftest.vals
-cat > conftest.hdr <<\EOF
-s/[\\&%]/\\&/g
-s%[\\$`]%\\&%g
-s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD}%gp
-s%ac_d%ac_u%gp
-s%ac_u%ac_e%gp
-EOF
-sed -n -f conftest.hdr confdefs.h > conftest.vals
-rm -f conftest.hdr
-
-# This sed command replaces #undef with comments.  This is necessary, for
-# example, in the case of _POSIX_SOURCE, which is predefined and required
-# on some systems where configure will not decide to define it.
-cat >> conftest.vals <<\EOF
-s%^[ 	]*#[ 	]*undef[ 	][ 	]*[a-zA-Z_][a-zA-Z_0-9]*%/* & */%
-EOF
-
-# Break up conftest.vals because some shells have a limit on
-# the size of here documents, and old seds have small limits too.
-
-rm -f conftest.tail
-while :
-do
-  ac_lines=`grep -c . conftest.vals`
-  # grep -c gives empty output for an empty file on some AIX systems.
-  if test -z "$ac_lines" || test "$ac_lines" -eq 0; then break; fi
-  # Write a limited-size here document to conftest.frag.
-  echo '  cat > conftest.frag <> $CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.vals >> $CONFIG_STATUS
-  echo 'CEOF
-  sed -f conftest.frag conftest.in > conftest.out
-  rm -f conftest.in
-  mv conftest.out conftest.in
-' >> $CONFIG_STATUS
-  sed 1,${ac_max_here_lines}d conftest.vals > conftest.tail
-  rm -f conftest.vals
-  mv conftest.tail conftest.vals
-done
-rm -f conftest.vals
-
-cat >> $CONFIG_STATUS <<\EOF
-  rm -f conftest.frag conftest.h
-  echo "/* $ac_file.  Generated automatically by configure.  */" > conftest.h
-  cat conftest.in >> conftest.h
-  rm -f conftest.in
-  if cmp -s $ac_file conftest.h 2>/dev/null; then
-    echo "$ac_file is unchanged"
-    rm -f conftest.h
-  else
-    # Remove last slash and all that follows it.  Not all systems have dirname.
-      ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
-      if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
-      # The file is in a subdirectory.
-      test ! -d "$ac_dir" && mkdir "$ac_dir"
-    fi
-    rm -f $ac_file
-    mv conftest.h $ac_file
-  fi
-fi; done
-
-EOF
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
-chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
-
-
diff --git a/contrib/libf2c/libI77/configure.in b/contrib/libf2c/libI77/configure.in
deleted file mode 100644
index 71a34d42eda..00000000000
--- a/contrib/libf2c/libI77/configure.in
+++ /dev/null
@@ -1,222 +0,0 @@
-# Process this file with autoconf to produce a configure script.
-#   Copyright (C) 1995, 1997, 1998, 2001, 2002 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of GNU Fortran.
-#
-#GNU Fortran is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-AC_PREREQ(2.13)
-AC_INIT(ftell_.c)
-AC_CONFIG_HEADER(config.h)
-
-dnl FIXME AC_PROG_CC wants CC to be able to link things, but it may
-dnl not be able to.
-define([AC_PROG_CC_WORKS],[])
-
-# For g77 we'll set CC to point at the built gcc, but this will get it into
-# the makefiles
-AC_PROG_CC
-
-# These defines are necessary to get 64-bit file size support.
-# NetBSD 1.4 header files does not support XOPEN_SOURCE == 600, but it
-# handles 64-bit file sizes without needing these defines.
-AC_MSG_CHECKING(whether _XOPEN_SOURCE may be defined)
-AC_TRY_COMPILE([#define _XOPEN_SOURCE 600L
-#include ],,
-may_use_xopen_source=yes,
-may_use_xopen_source=no)
-AC_MSG_RESULT($may_use_xopen_source)
-if test $may_use_xopen_source = yes; then
-  AC_DEFINE(_XOPEN_SOURCE, 600L, [Get Single Unix Specification semantics])
-  # The following is needed by irix6.2 so that struct timeval is declared.
-  AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Get Single Unix Specification semantics])
-  # The following is needed by Solaris2.5.1 so that struct timeval is declared.
-  AC_DEFINE(__EXTENSIONS__, 1, [Solaris extensions])
-  AC_DEFINE(_FILE_OFFSET_BITS, 64, [Get 64-bit file size support])
-  AC_DEFINE(_LARGEFILE_SOURCE, 1, [Define for HP-UX ftello and fseeko extension.])
-fi
-
-dnl Checks for programs.
-
-LIBTOOL='$(SHELL) ../libtool'
-AC_SUBST(LIBTOOL)
-
-test "$AR" || AR=ar
-AC_SUBST(AR)
-AC_PROG_MAKE_SET
-
-dnl Checks for libraries.
-
-dnl Checks for header files.
-# Sanity check for the cross-compilation case:
-AC_CHECK_HEADER(stdio.h,:,
-  [AC_MSG_ERROR([Can't find stdio.h.
-You must have a usable C system for the target already installed, at least
-including headers and, preferably, the library, before you can configure
-the G77 runtime system.  If necessary, install gcc now with \`LANGUAGES=c',
-then the target library, then build with \`LANGUAGES=f77'.])])
-
-AC_HEADER_STDC
-AC_MSG_CHECKING(for posix)
-AC_CACHE_VAL(g77_cv_header_posix,
-  AC_EGREP_CPP(yes,
-  [#include 
-#include 
-#ifdef _POSIX_VERSION
-  yes
-#endif
-], 
-  g77_cv_header_posix=yes,
-  g77_cv_header_posix=no))
-AC_MSG_RESULT($g77_cv_header_posix)
-
-# We can rely on the GNU library being posix-ish.  I guess checking the 
-# header isn't actually like checking the functions, though...
-AC_MSG_CHECKING(for GNU library)
-AC_CACHE_VAL(g77_cv_lib_gnu,
-  AC_EGREP_CPP(yes,
-    [#include 
-#ifdef __GNU_LIBRARY__
-  yes
-#endif
-], 
-  g77_cv_lib_gnu=yes, g77_cv_lib_gnu=no))
-AC_MSG_RESULT($g77_cv_lib_gnu)
-
-# Apparently cygwin needs to be special-cased.
-AC_MSG_CHECKING([for cyg\`win'32])
-AC_CACHE_VAL(g77_cv_sys_cygwin32,
-  AC_EGREP_CPP(yes,
-  [#ifdef __CYGWIN32__
-  yes
-#endif
-],
-  g77_cv_sys_cygwin32=yes,
-  g77_cv_sys_cygwin32=no))
-AC_MSG_RESULT($g77_cv_sys_cygwin32)
-
-# ditto for mingw32.
-AC_MSG_CHECKING([for mingw32])
-AC_CACHE_VAL(g77_cv_sys_mingw32,
-  AC_EGREP_CPP(yes,
-  [#ifdef __MINGW32__
-  yes
-#endif
-],
-  g77_cv_sys_mingw32=yes,
-  g77_cv_sys_mingw32=no))
-AC_MSG_RESULT($g77_cv_sys_mingw32)
-
-
-dnl Checks for typedefs, structures, and compiler characteristics.
-AC_C_CONST
-AC_TYPE_SIZE_T
-
-dnl Checks for library functions.
-
-# This should always succeed on unix.
-# Apparently positive result on cygwin loses re. NON_UNIX_STDIO
-# (as of cygwin b18). Likewise on mingw.
-AC_CHECK_FUNC(fstat)
-AC_MSG_CHECKING([need for NON_UNIX_STDIO])
-if test $g77_cv_sys_cygwin32 = yes \
-  || test $g77_cv_sys_mingw32 = yes \
-  || test $ac_cv_func_fstat = no; then
-  AC_MSG_RESULT(yes)
-  AC_DEFINE(NON_UNIX_STDIO, 1, [Define if we do not have Unix Stdio.])
-else
-  AC_MSG_RESULT(no)
-fi
-
-AC_CHECK_FUNCS(fseeko)
-AC_CHECK_FUNCS(ftello)
-AC_CHECK_FUNCS(ftruncate)
-AC_CHECK_FUNCS(mkstemp)
-AC_CHECK_FUNCS(tempnam)
-AC_CHECK_FUNCS(tmpnam)
-
-# posix will guarantee the right behaviour for sprintf, else we can't be
-# sure; HEADER_STDC wouldn't be the right check in sunos4, for instance.
-# However, on my sunos4/gcc setup unistd.h leads us wrongly to believe
-# we're posix-conformant, so always do the test.
-AC_MSG_CHECKING(for ansi/posix sprintf result)
-dnl This loses if included as an argument to AC_CACHE_VAL because the
-dnl changequote doesn't take effect and the [] vanish.
-dnl fixme: use cached value
-AC_TRY_RUN(changequote(<<, >>)dnl
-  <<#include 
-    /* does sprintf return the number of chars transferred? */
-    main () {char foo[2]; (sprintf(foo, "1") == 1) ? exit(0) : exit(1);}
->>changequote([, ]),
-    g77_cv_sys_sprintf_ansi=yes,
-    g77_cv_sys_sprintf_ansi=no,
-    g77_cv_sys_sprintf_ansi=no)
-AC_CACHE_VAL(g77_cv_sys_sprintf_ansi,
-     g77_cv_sys_sprintf_ansi=$g77_cv_sys_sprintf_ansi)
-dnl We get a misleading `(cached)' message...
-AC_MSG_RESULT($g77_cv_sys_sprintf_ansi)
-
-# The cygwin patch takes steps to avoid defining USE_STRLEN here -- I don't
-# understand why.
-if test $g77_cv_sys_sprintf_ansi != yes; then 
-  AC_DEFINE(USE_STRLEN, 1, [Define if we use strlen.])
-fi
-
-# define NON_ANSI_RW_MODES on unix (can't hurt)
-AC_MSG_CHECKING(NON_ANSI_RW_MODES)
-AC_EGREP_CPP(yes,
-[#ifdef unix
-  yes
-#endif
-#ifdef __unix
-  yes
-#endif
-#ifdef __unix__
-  yes
-#endif
-], is_unix=yes, is_unix=no)
-# NON_ANSI_RW_MODES shouldn't be necessary on cygwin for binary mounts.
-if test $g77_cv_sys_cygwin32 = yes || test $g77_cv_sys_mingw32 = yes; then
-  AC_MSG_RESULT(no)
-else
-  if test $is_unix = yes; then
-    AC_DEFINE(NON_ANSI_RW_MODES, 1, [Define if we have non ANSI RW modes.])
-    AC_MSG_RESULT(yes)
-  else
-    AC_MSG_RESULT(no)
-  fi
-fi
-
-# This EOF_CHAR is a misfeature on unix.
-AC_DEFINE(NO_EOF_CHAR_CHECK, 1, [Always defined.])
-
-AC_TYPE_OFF_T
-
-AC_DEFINE(Skip_f2c_Undefs, 1, [Define to skip f2c undefs.])
-
-AC_OUTPUT(Makefile)
-
-dnl We might have configuration options to:
-dnl * change unit preconnexion in err.c (f_init.c)
-dnl * -DALWAYS_FLUSH
-dnl * -DOMIT_BLANK_CC
-
-dnl Local Variables:
-dnl comment-start: "dnl "
-dnl comment-end: ""
-dnl comment-start-skip: "\\bdnl\\b\\s *"
-dnl End:
diff --git a/contrib/libf2c/libI77/dfe.c b/contrib/libf2c/libI77/dfe.c
deleted file mode 100644
index 5ce0b4cd661..00000000000
--- a/contrib/libf2c/libI77/dfe.c
+++ /dev/null
@@ -1,156 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-
-int
-y_rsk (void)
-{
-  if (f__curunit->uend || f__curunit->url <= f__recpos
-      || f__curunit->url == 1)
-    return 0;
-  do
-    {
-      getc (f__cf);
-    }
-  while (++f__recpos < f__curunit->url);
-  return 0;
-}
-
-int
-y_getc (void)
-{
-  int ch;
-  if (f__curunit->uend)
-    return (-1);
-  if ((ch = getc (f__cf)) != EOF)
-    {
-      f__recpos++;
-      if (f__curunit->url >= f__recpos || f__curunit->url == 1)
-	return (ch);
-      else
-	return (' ');
-    }
-  if (feof (f__cf))
-    {
-      f__curunit->uend = 1;
-      errno = 0;
-      return (-1);
-    }
-  err (f__elist->cierr, errno, "readingd");
-}
-
-static int
-y_rev (void)
-{
-  if (f__recpos < f__hiwater)
-    f__recpos = f__hiwater;
-  if (f__curunit->url > 1)
-    while (f__recpos < f__curunit->url)
-      (*f__putn) (' ');
-  if (f__recpos)
-    f__putbuf (0);
-  f__recpos = 0;
-  return (0);
-}
-
-static int
-y_err (void)
-{
-  err (f__elist->cierr, 110, "dfe");
-}
-
-static int
-y_newrec (void)
-{
-  y_rev ();
-  f__hiwater = f__cursor = 0;
-  return (1);
-}
-
-int
-c_dfe (cilist * a)
-{
-  f__sequential = 0;
-  f__formatted = f__external = 1;
-  f__elist = a;
-  f__cursor = f__scale = f__recpos = 0;
-  f__curunit = &f__units[a->ciunit];
-  if (a->ciunit > MXUNIT || a->ciunit < 0)
-    err (a->cierr, 101, "startchk");
-  if (f__curunit->ufd == NULL && fk_open (DIR, FMT, a->ciunit))
-    err (a->cierr, 104, "dfe");
-  f__cf = f__curunit->ufd;
-  if (!f__curunit->ufmt)
-    err (a->cierr, 102, "dfe");
-  if (!f__curunit->useek)
-    err (a->cierr, 104, "dfe");
-  f__fmtbuf = a->cifmt;
-  if (a->cirec <= 0)
-    err (a->cierr, 130, "dfe");
-  FSEEK (f__cf, (off_t) f__curunit->url * (a->cirec - 1), SEEK_SET);
-  f__curunit->uend = 0;
-  return (0);
-}
-
-integer
-s_rdfe (cilist * a)
-{
-  int n;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__reading = 1;
-  if ((n = c_dfe (a)))
-    return (n);
-  if (f__curunit->uwrt && f__nowreading (f__curunit))
-    err (a->cierr, errno, "read start");
-  f__getn = y_getc;
-  f__doed = rd_ed;
-  f__doned = rd_ned;
-  f__dorevert = f__donewrec = y_err;
-  f__doend = y_rsk;
-  if (pars_f (f__fmtbuf) < 0)
-    err (a->cierr, 100, "read start");
-  fmt_bg ();
-  return (0);
-}
-
-integer
-s_wdfe (cilist * a)
-{
-  int n;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__reading = 0;
-  if ((n = c_dfe (a)))
-    return (n);
-  if (f__curunit->uwrt != 1 && f__nowwriting (f__curunit))
-    err (a->cierr, errno, "startwrt");
-  f__putn = x_putc;
-  f__doed = w_ed;
-  f__doned = w_ned;
-  f__dorevert = y_err;
-  f__donewrec = y_newrec;
-  f__doend = y_rev;
-  if (pars_f (f__fmtbuf) < 0)
-    err (a->cierr, 100, "startwrt");
-  fmt_bg ();
-  return (0);
-}
-
-integer
-e_rdfe (void)
-{
-  f__init = 1;
-  en_fio ();
-  return (0);
-}
-
-integer
-e_wdfe (void)
-{
-  f__init = 1;
-  return en_fio ();
-}
diff --git a/contrib/libf2c/libI77/dolio.c b/contrib/libf2c/libI77/dolio.c
deleted file mode 100644
index e50e9005317..00000000000
--- a/contrib/libf2c/libI77/dolio.c
+++ /dev/null
@@ -1,10 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-
-extern int (*f__lioproc) (ftnint *, char *, ftnlen, ftnint);
-
-integer
-do_lio (ftnint * type, ftnint * number, char *ptr, ftnlen len)
-{
-  return ((*f__lioproc) (number, ptr, len, *type));
-}
diff --git a/contrib/libf2c/libI77/due.c b/contrib/libf2c/libI77/due.c
deleted file mode 100644
index 7c6a801e0f9..00000000000
--- a/contrib/libf2c/libI77/due.c
+++ /dev/null
@@ -1,80 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-
-int
-c_due (cilist * a)
-{
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  if (a->ciunit >= MXUNIT || a->ciunit < 0)
-    err (a->cierr, 101, "startio");
-  f__sequential = f__formatted = f__recpos = 0;
-  f__external = 1;
-  f__curunit = &f__units[a->ciunit];
-  if (a->ciunit >= MXUNIT || a->ciunit < 0)
-    err (a->cierr, 101, "startio");
-  f__elist = a;
-  if (f__curunit->ufd == NULL && fk_open (DIR, UNF, a->ciunit))
-    err (a->cierr, 104, "due");
-  f__cf = f__curunit->ufd;
-  if (f__curunit->ufmt)
-    err (a->cierr, 102, "cdue");
-  if (!f__curunit->useek)
-    err (a->cierr, 104, "cdue");
-  if (f__curunit->ufd == NULL)
-    err (a->cierr, 114, "cdue");
-  if (a->cirec <= 0)
-    err (a->cierr, 130, "due");
-  FSEEK (f__cf, (off_t) (a->cirec - 1) * f__curunit->url, SEEK_SET);
-  f__curunit->uend = 0;
-  return (0);
-}
-
-integer
-s_rdue (cilist * a)
-{
-  int n;
-  f__reading = 1;
-  if ((n = c_due (a)))
-    return (n);
-  if (f__curunit->uwrt && f__nowreading (f__curunit))
-    err (a->cierr, errno, "read start");
-  return (0);
-}
-
-integer
-s_wdue (cilist * a)
-{
-  int n;
-  f__reading = 0;
-  if ((n = c_due (a)))
-    return (n);
-  if (f__curunit->uwrt != 1 && f__nowwriting (f__curunit))
-    err (a->cierr, errno, "write start");
-  return (0);
-}
-
-integer
-e_rdue (void)
-{
-  f__init = 1;
-  if (f__curunit->url == 1 || f__recpos == f__curunit->url)
-    return (0);
-  FSEEK (f__cf, (off_t) (f__curunit->url - f__recpos), SEEK_CUR);
-  if (FTELL (f__cf) % f__curunit->url)
-    err (f__elist->cierr, 200, "syserr");
-  return (0);
-}
-
-integer
-e_wdue (void)
-{
-  f__init = 1;
-#ifdef ALWAYS_FLUSH
-  if (fflush (f__cf))
-    err (f__elist->cierr, errno, "write end");
-#endif
-  return (e_rdue ());
-}
diff --git a/contrib/libf2c/libI77/endfile.c b/contrib/libf2c/libI77/endfile.c
deleted file mode 100644
index 513f2107ef7..00000000000
--- a/contrib/libf2c/libI77/endfile.c
+++ /dev/null
@@ -1,130 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-
-#include 
-#include 
-
-#undef abs
-#undef min
-#undef max
-#include 
-#include 
-
-extern char *f__r_mode[], *f__w_mode[];
-
-integer
-f_end (alist * a)
-{
-  unit *b;
-  FILE *tf;
-
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  if (a->aunit >= MXUNIT || a->aunit < 0)
-    err (a->aerr, 101, "endfile");
-  b = &f__units[a->aunit];
-  if (b->ufd == NULL)
-    {
-      char nbuf[10];
-      sprintf (nbuf, "fort.%ld", (long) a->aunit);
-      if ((tf = fopen (nbuf, f__w_mode[0])))
-	fclose (tf);
-      return (0);
-    }
-  b->uend = 1;
-  return (b->useek ? t_runc (a) : 0);
-}
-
-#ifndef HAVE_FTRUNCATE
-static int
-copy (FILE * from, register long len, FILE * to)
-{
-  int len1;
-  char buf[BUFSIZ];
-
-  while (fread (buf, len1 = len > BUFSIZ ? BUFSIZ : (int) len, 1, from))
-    {
-      if (!fwrite (buf, len1, 1, to))
-	return 1;
-      if ((len -= len1) <= 0)
-	break;
-    }
-  return 0;
-}
-#endif /* !defined(HAVE_FTRUNCATE) */
-
-int
-t_runc (alist * a)
-{
-  off_t loc, len;
-  unit *b;
-  int rc;
-  FILE *bf;
-#ifndef HAVE_FTRUNCATE
-  FILE *tf;
-#endif /* !defined(HAVE_FTRUNCATE) */
-
-  b = &f__units[a->aunit];
-  if (b->url)
-    return (0);			/*don't truncate direct files */
-  loc = FTELL (bf = b->ufd);
-  FSEEK (bf, 0, SEEK_END);
-  len = FTELL (bf);
-  if (loc >= len || b->useek == 0 || b->ufnm == NULL)
-    return (0);
-#ifndef HAVE_FTRUNCATE
-  rc = 0;
-  fclose (b->ufd);
-  if (!loc)
-    {
-      if (!(bf = fopen (b->ufnm, f__w_mode[b->ufmt])))
-	rc = 1;
-      if (b->uwrt)
-	b->uwrt = 1;
-      goto done;
-    }
-  if (!(bf = fopen (b->ufnm, f__r_mode[0])) || !(tf = tmpfile ()))
-    {
-#ifdef NON_UNIX_STDIO
-    bad:
-#endif
-      rc = 1;
-      goto done;
-    }
-  if (copy (bf, loc, tf))
-    {
-    bad1:
-      rc = 1;
-      goto done1;
-    }
-  if (!(bf = freopen (b->ufnm, f__w_mode[0], bf)))
-    goto bad1;
-  FSEEK (tf, 0, SEEK_SET);
-  if (copy (tf, loc, bf))
-    goto bad1;
-  b->uwrt = 1;
-  b->urw = 2;
-#ifdef NON_UNIX_STDIO
-  if (b->ufmt)
-    {
-      fclose (bf);
-      if (!(bf = fopen (b->ufnm, f__w_mode[3])))
-	goto bad;
-      FSEEK (bf, 0, SEEK_END);
-      b->urw = 3;
-    }
-#endif
-done1:
-  fclose (tf);
-done:
-  f__cf = b->ufd = bf;
-#else /* !defined(HAVE_FTRUNCATE) */
-  fflush (b->ufd);
-  rc = ftruncate (fileno (b->ufd), loc);
-  FSEEK (bf, loc, SEEK_SET);
-#endif /* !defined(HAVE_FTRUNCATE) */
-  if (rc)
-    err (a->aerr, 111, "endfile");
-  return 0;
-}
diff --git a/contrib/libf2c/libI77/err.c b/contrib/libf2c/libI77/err.c
deleted file mode 100644
index d643d3b8b68..00000000000
--- a/contrib/libf2c/libI77/err.c
+++ /dev/null
@@ -1,285 +0,0 @@
-#include "config.h"
-#ifndef NON_UNIX_STDIO
-#define _INCLUDE_POSIX_SOURCE	/* for HP-UX */
-#define _INCLUDE_XOPEN_SOURCE	/* for HP-UX */
-#include 
-#include 
-#endif
-#include "f2c.h"
-#undef abs
-#undef min
-#undef max
-#include 
-#include "fio.h"
-#include "fmt.h"		/* for struct syl */
-
-/*global definitions*/
-unit f__units[MXUNIT];		/*unit table */
-int f__init;			/*bit 0: set after initializations;
-				   bit 1: set during I/O involving returns to
-				   caller of library (or calls to user code) */
-cilist *f__elist;		/*active external io list */
-icilist *f__svic;		/*active internal io list */
-flag f__reading;		/*1 if reading, 0 if writing */
-flag f__cplus, f__cblank;
-char *f__fmtbuf;
-int f__fmtlen;
-flag f__external;		/*1 if external io, 0 if internal */
-int (*f__getn) (void);		/* for formatted input */
-void (*f__putn) (int);		/* for formatted output */
-int (*f__doed) (struct syl *, char *, ftnlen), (*f__doned) (struct syl *);
-int (*f__dorevert) (void), (*f__donewrec) (void), (*f__doend) (void);
-flag f__sequential;		/*1 if sequential io, 0 if direct */
-flag f__formatted;		/*1 if formatted io, 0 if unformatted */
-FILE *f__cf;			/*current file */
-unit *f__curunit;		/*current unit */
-int f__recpos;			/*place in current record */
-int f__cursor, f__hiwater, f__scale;
-char *f__icptr;
-
-/*error messages*/
-char *F_err[] = {
-  "error in format",		/* 100 */
-  "illegal unit number",	/* 101 */
-  "formatted io not allowed",	/* 102 */
-  "unformatted io not allowed",	/* 103 */
-  "direct io not allowed",	/* 104 */
-  "sequential io not allowed",	/* 105 */
-  "can't backspace file",	/* 106 */
-  "null file name",		/* 107 */
-  "can't stat file",		/* 108 */
-  "unit not connected",		/* 109 */
-  "off end of record",		/* 110 */
-  "truncation failed in endfile",	/* 111 */
-  "incomprehensible list input",	/* 112 */
-  "out of free space",		/* 113 */
-  "unit not connected",		/* 114 */
-  "read unexpected character",	/* 115 */
-  "bad logical input field",	/* 116 */
-  "bad variable type",		/* 117 */
-  "bad namelist name",		/* 118 */
-  "variable not in namelist",	/* 119 */
-  "no end record",		/* 120 */
-  "variable count incorrect",	/* 121 */
-  "subscript for scalar variable",	/* 122 */
-  "invalid array section",	/* 123 */
-  "substring out of bounds",	/* 124 */
-  "subscript out of bounds",	/* 125 */
-  "can't read file",		/* 126 */
-  "can't write file",		/* 127 */
-  "'new' file exists",		/* 128 */
-  "can't append to file",	/* 129 */
-  "non-positive record number",	/* 130 */
-  "I/O started while already doing I/O",	/* 131 */
-  "Temporary file name (TMPDIR?) too long"	/* 132 */
-};
-#define MAXERR (sizeof(F_err)/sizeof(char *)+100)
-
-int
-f__canseek (FILE * f) /*SYSDEP*/
-{
-#ifdef NON_UNIX_STDIO
-  return !isatty (fileno (f));
-#else
-  struct stat x;
-
-  if (fstat (fileno (f), &x) < 0)
-    return (0);
-#ifdef S_IFMT
-  switch (x.st_mode & S_IFMT)
-    {
-    case S_IFDIR:
-    case S_IFREG:
-      if (x.st_nlink > 0)	/* !pipe */
-	return (1);
-      else
-	return (0);
-    case S_IFCHR:
-      if (isatty (fileno (f)))
-	return (0);
-      return (1);
-#ifdef S_IFBLK
-    case S_IFBLK:
-      return (1);
-#endif
-    }
-#else
-#ifdef S_ISDIR
-  /* POSIX version */
-  if (S_ISREG (x.st_mode) || S_ISDIR (x.st_mode))
-    {
-      if (x.st_nlink > 0)	/* !pipe */
-	return (1);
-      else
-	return (0);
-    }
-  if (S_ISCHR (x.st_mode))
-    {
-      if (isatty (fileno (f)))
-	return (0);
-      return (1);
-    }
-  if (S_ISBLK (x.st_mode))
-    return (1);
-#else
-  Help ! How does fstat work on this system ?
-#endif
-#endif
-    return (0);			/* who knows what it is? */
-#endif
-}
-
-void
-f__fatal (int n, char *s)
-{
-  static int dead = 0;
-
-  if (n < 100 && n >= 0)
-    perror (s);
-  /*SYSDEP*/
-  else if (n >= (int) MAXERR || n < -1)
-    {
-      fprintf (stderr, "%s: illegal error number %d\n", s, n);
-    }
-  else if (n == -1)
-    fprintf (stderr, "%s: end of file\n", s);
-  else
-    fprintf (stderr, "%s: %s\n", s, F_err[n - 100]);
-  if (dead)
-    {
-      fprintf (stderr, "(libf2c f__fatal already called, aborting.)");
-      abort ();
-    }
-  dead = 1;
-  if (f__init & 1)
-    {
-      if (f__curunit)
-	{
-	  fprintf (stderr, "apparent state: unit %d ",
-		   (int) (f__curunit - f__units));
-	  fprintf (stderr, f__curunit->ufnm ? "named %s\n" : "(unnamed)\n",
-		   f__curunit->ufnm);
-	}
-      else
-	fprintf (stderr, "apparent state: internal I/O\n");
-      if (f__fmtbuf)
-	fprintf (stderr, "last format: %.*s\n", f__fmtlen, f__fmtbuf);
-      fprintf (stderr, "lately %s %s %s %s",
-	       f__reading ? "reading" : "writing",
-	       f__sequential ? "sequential" : "direct",
-	       f__formatted ? "formatted" : "unformatted",
-	       f__external ? "external" : "internal");
-    }
-  f__init &= ~2;		/* No longer doing I/O (no more user code to be called). */
-  sig_die (" IO", 1);
-}
-
-/*initialization routine*/
-void
-f_init (void)
-{
-  unit *p;
-
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  f__init = 1;
-  p = &f__units[0];
-  p->ufd = stderr;
-  p->useek = f__canseek (stderr);
-  p->ufmt = 1;
-  p->uwrt = 1;
-  p = &f__units[5];
-  p->ufd = stdin;
-  p->useek = f__canseek (stdin);
-  p->ufmt = 1;
-  p->uwrt = 0;
-  p = &f__units[6];
-  p->ufd = stdout;
-  p->useek = f__canseek (stdout);
-  p->ufmt = 1;
-  p->uwrt = 1;
-}
-
-int
-f__nowreading (unit * x)
-{
-  off_t loc;
-  int ufmt, urw;
-  extern char *f__r_mode[], *f__w_mode[];
-
-  if (x->urw & 1)
-    goto done;
-  if (!x->ufnm)
-    goto cantread;
-  ufmt = x->url ? 0 : x->ufmt;
-  loc = FTELL (x->ufd);
-  urw = 3;
-  if (!freopen (x->ufnm, f__w_mode[ufmt | 2], x->ufd))
-    {
-      urw = 1;
-      if (!freopen (x->ufnm, f__r_mode[ufmt], x->ufd))
-	{
-	cantread:
-	  errno = 126;
-	  return 1;
-	}
-    }
-  FSEEK (x->ufd, loc, SEEK_SET);
-  x->urw = urw;
-done:
-  x->uwrt = 0;
-  return 0;
-}
-
-int
-f__nowwriting (unit * x)
-{
-  off_t loc;
-  int ufmt;
-  extern char *f__w_mode[];
-
-  if (x->urw & 2)
-    {
-      /* Not required according to C99 7.19.5.3, but
-	 this really helps on Solaris.  */
-      if (feof (x->ufd))
-	FSEEK (x->ufd, 0, SEEK_END);
-      goto done;
-    }
-  if (!x->ufnm)
-    goto cantwrite;
-  ufmt = x->url ? 0 : x->ufmt;
-  if (x->uwrt == 3)
-    {				/* just did write, rewind */
-      if (!(f__cf = x->ufd = freopen (x->ufnm, f__w_mode[ufmt], x->ufd)))
-	goto cantwrite;
-      x->urw = 2;
-    }
-  else
-    {
-      loc = FTELL (x->ufd);
-      if (!(f__cf = x->ufd = freopen (x->ufnm, f__w_mode[ufmt |= 2], x->ufd)))
-	{
-	  x->ufd = NULL;
-	cantwrite:
-	  errno = 127;
-	  return (1);
-	}
-      x->urw = 3;
-      FSEEK (x->ufd, loc, SEEK_SET);
-    }
-done:
-  x->uwrt = 1;
-  return 0;
-}
-
-int
-err__fl (int f, int m, char *s)
-{
-  if (!f)
-    f__fatal (m, s);
-  if (f__doend)
-    (*f__doend) ();
-  f__init &= ~2;
-  return errno = m;
-}
diff --git a/contrib/libf2c/libI77/f2ch.add b/contrib/libf2c/libI77/f2ch.add
deleted file mode 100644
index 04b13e8de5d..00000000000
--- a/contrib/libf2c/libI77/f2ch.add
+++ /dev/null
@@ -1,163 +0,0 @@
-/* If you are using a C++ compiler, append the following to f2c.h
-   for compiling libF77 and libI77. */
-
-#ifdef __cplusplus
-extern "C"
-{
-  extern int abort_ (void);
-  extern double c_abs (complex *);
-  extern void c_cos (complex *, complex *);
-  extern void c_div (complex *, complex *, complex *);
-  extern void c_exp (complex *, complex *);
-  extern void c_log (complex *, complex *);
-  extern void c_sin (complex *, complex *);
-  extern void c_sqrt (complex *, complex *);
-  extern double d_abs (double *);
-  extern double d_acos (double *);
-  extern double d_asin (double *);
-  extern double d_atan (double *);
-  extern double d_atn2 (double *, double *);
-  extern void d_cnjg (doublecomplex *, doublecomplex *);
-  extern double d_cos (double *);
-  extern double d_cosh (double *);
-  extern double d_dim (double *, double *);
-  extern double d_exp (double *);
-  extern double d_imag (doublecomplex *);
-  extern double d_int (double *);
-  extern double d_lg10 (double *);
-  extern double d_log (double *);
-  extern double d_mod (double *, double *);
-  extern double d_nint (double *);
-  extern double d_prod (float *, float *);
-  extern double d_sign (double *, double *);
-  extern double d_sin (double *);
-  extern double d_sinh (double *);
-  extern double d_sqrt (double *);
-  extern double d_tan (double *);
-  extern double d_tanh (double *);
-  extern double derf_ (double *);
-  extern double derfc_ (double *);
-  extern integer do_fio (ftnint *, char *, ftnlen);
-  extern integer do_lio (ftnint *, ftnint *, char *, ftnlen);
-  extern integer do_uio (ftnint *, char *, ftnlen);
-  extern integer e_rdfe (void);
-  extern integer e_rdue (void);
-  extern integer e_rsfe (void);
-  extern integer e_rsfi (void);
-  extern integer e_rsle (void);
-  extern integer e_rsli (void);
-  extern integer e_rsue (void);
-  extern integer e_wdfe (void);
-  extern integer e_wdue (void);
-  extern integer e_wsfe (void);
-  extern integer e_wsfi (void);
-  extern integer e_wsle (void);
-  extern integer e_wsli (void);
-  extern integer e_wsue (void);
-  extern int ef1asc_ (ftnint *, ftnlen *, ftnint *, ftnlen *);
-  extern integer ef1cmc_ (ftnint *, ftnlen *, ftnint *, ftnlen *);
-  extern double erf (double);
-  extern double erf_ (float *);
-  extern double erfc (double);
-  extern double erfc_ (float *);
-  extern integer f_back (alist *);
-  extern integer f_clos (cllist *);
-  extern integer f_end (alist *);
-  extern void f_exit (void);
-  extern integer f_inqu (inlist *);
-  extern integer f_open (olist *);
-  extern integer f_rew (alist *);
-  extern int flush_ (void);
-  extern void getarg_ (integer *, char *, ftnlen);
-  extern void getenv_ (char *, char *, ftnlen, ftnlen);
-  extern short h_abs (short *);
-  extern short h_dim (short *, short *);
-  extern short h_dnnt (double *);
-  extern short h_indx (char *, char *, ftnlen, ftnlen);
-  extern short h_len (char *, ftnlen);
-  extern short h_mod (short *, short *);
-  extern short h_nint (float *);
-  extern short h_sign (short *, short *);
-  extern short hl_ge (char *, char *, ftnlen, ftnlen);
-  extern short hl_gt (char *, char *, ftnlen, ftnlen);
-  extern short hl_le (char *, char *, ftnlen, ftnlen);
-  extern short hl_lt (char *, char *, ftnlen, ftnlen);
-  extern integer i_abs (integer *);
-  extern integer i_dim (integer *, integer *);
-  extern integer i_dnnt (double *);
-  extern integer i_indx (char *, char *, ftnlen, ftnlen);
-  extern integer i_len (char *, ftnlen);
-  extern integer i_mod (integer *, integer *);
-  extern integer i_nint (float *);
-  extern integer i_sign (integer *, integer *);
-  extern integer iargc_ (void);
-  extern ftnlen l_ge (char *, char *, ftnlen, ftnlen);
-  extern ftnlen l_gt (char *, char *, ftnlen, ftnlen);
-  extern ftnlen l_le (char *, char *, ftnlen, ftnlen);
-  extern ftnlen l_lt (char *, char *, ftnlen, ftnlen);
-  extern void pow_ci (complex *, complex *, integer *);
-  extern double pow_dd (double *, double *);
-  extern double pow_di (double *, integer *);
-  extern short pow_hh (short *, shortint *);
-  extern integer pow_ii (integer *, integer *);
-  extern double pow_ri (float *, integer *);
-  extern void pow_zi (doublecomplex *, doublecomplex *, integer *);
-  extern void pow_zz (doublecomplex *, doublecomplex *, doublecomplex *);
-  extern double r_abs (float *);
-  extern double r_acos (float *);
-  extern double r_asin (float *);
-  extern double r_atan (float *);
-  extern double r_atn2 (float *, float *);
-  extern void r_cnjg (complex *, complex *);
-  extern double r_cos (float *);
-  extern double r_cosh (float *);
-  extern double r_dim (float *, float *);
-  extern double r_exp (float *);
-  extern double r_imag (complex *);
-  extern double r_int (float *);
-  extern double r_lg10 (float *);
-  extern double r_log (float *);
-  extern double r_mod (float *, float *);
-  extern double r_nint (float *);
-  extern double r_sign (float *, float *);
-  extern double r_sin (float *);
-  extern double r_sinh (float *);
-  extern double r_sqrt (float *);
-  extern double r_tan (float *);
-  extern double r_tanh (float *);
-  extern void s_cat (char *, char **, integer *, integer *, ftnlen);
-  extern integer s_cmp (char *, char *, ftnlen, ftnlen);
-  extern void s_copy (char *, char *, ftnlen, ftnlen);
-  extern int s_paus (char *, ftnlen);
-  extern integer s_rdfe (cilist *);
-  extern integer s_rdue (cilist *);
-  extern integer s_rnge (char *, integer, char *, integer);
-  extern integer s_rsfe (cilist *);
-  extern integer s_rsfi (icilist *);
-  extern integer s_rsle (cilist *);
-  extern integer s_rsli (icilist *);
-  extern integer s_rsne (cilist *);
-  extern integer s_rsni (icilist *);
-  extern integer s_rsue (cilist *);
-  extern int s_stop (char *, ftnlen);
-  extern integer s_wdfe (cilist *);
-  extern integer s_wdue (cilist *);
-  extern integer s_wsfe (cilist *);
-  extern integer s_wsfi (icilist *);
-  extern integer s_wsle (cilist *);
-  extern integer s_wsli (icilist *);
-  extern integer s_wsne (cilist *);
-  extern integer s_wsni (icilist *);
-  extern integer s_wsue (cilist *);
-  extern void sig_die (char *, int);
-  extern integer signal_ (integer *, void (*)(int));
-  extern integer system_ (char *, ftnlen);
-  extern double z_abs (doublecomplex *);
-  extern void z_cos (doublecomplex *, doublecomplex *);
-  extern void z_div (doublecomplex *, doublecomplex *, doublecomplex *);
-  extern void z_exp (doublecomplex *, doublecomplex *);
-  extern void z_log (doublecomplex *, doublecomplex *);
-  extern void z_sin (doublecomplex *, doublecomplex *);
-  extern void z_sqrt (doublecomplex *, doublecomplex *);
-}
-#endif
diff --git a/contrib/libf2c/libI77/fio.h b/contrib/libf2c/libI77/fio.h
deleted file mode 100644
index 7734f0c2f2f..00000000000
--- a/contrib/libf2c/libI77/fio.h
+++ /dev/null
@@ -1,104 +0,0 @@
-#include 
-#include 
-#include 
-#ifndef NULL
-/* ANSI C */
-#include 
-#endif
-#ifdef STDC_HEADERS
-#include 
-#endif
-
-#ifndef SEEK_SET
-#define SEEK_SET 0
-#define SEEK_CUR 1
-#define SEEK_END 2
-#endif
-
-/* Only use fseeko/ftello if they are both there.  */
-
-#if defined (HAVE_FSEEKO) && defined (HAVE_FTELLO)
-#define FSEEK fseeko
-#define FTELL ftello
-#else
-#define FSEEK fseek
-#define FTELL ftell
-#endif
-
-#if defined (MSDOS) && !defined (GO32)
-#ifndef NON_UNIX_STDIO
-#define NON_UNIX_STDIO
-#endif
-#endif
-
-#ifdef UIOLEN_int
-typedef int uiolen;
-#else
-typedef long uiolen;
-#endif
-
-/*units*/
-typedef struct
-{
-  FILE *ufd;			/*0=unconnected */
-  char *ufnm;
-#if !(defined (MSDOS) && !defined (GO32))
-  long uinode;
-  int udev;
-#endif
-  int url;			/*0=sequential */
-  flag useek;			/*true=can backspace, use dir, ... */
-  flag ufmt;
-  flag urw;			/* (1 for can read) | (2 for can write) */
-  flag ublnk;
-  flag uend;
-  flag uwrt;			/*last io was write */
-  flag uscrtch;
-}
-unit;
-
-extern int f__init;
-extern cilist *f__elist;	/*active external io list */
-extern flag f__reading, f__external, f__sequential, f__formatted;
-extern int (*f__getn) (void);	/* for formatted input */
-extern void (*f__putn) (int);	/* for formatted output */
-extern void x_putc (int);
-extern long f__inode (char *, int *);
-extern void sig_die (char *, int);
-extern void f__fatal (int, char *);
-extern int t_runc (alist *);
-extern int f__nowreading (unit *), f__nowwriting (unit *);
-extern int fk_open (int, int, ftnint);
-extern int en_fio (void);
-extern void f_init (void);
-extern int (*f__donewrec) (void), t_putc (int), x_wSL (void);
-extern void b_char (char *, char *, ftnlen), g_char (char *, ftnlen, char *);
-extern int c_sfe (cilist *), z_rnew (void);
-extern int isatty (int);
-extern int err__fl (int, int, char *);
-extern int xrd_SL (void);
-extern int f__putbuf (int);
-extern int (*f__doend) (void);
-extern FILE *f__cf;		/*current file */
-extern unit *f__curunit;	/*current unit */
-extern unit f__units[];
-#define err(f,m,s) do {if(f) {f__init &= ~2; errno= m;} else f__fatal(m,s); return(m);} while(0)
-#define errfl(f,m,s) do {return err__fl((int)f,m,s);} while(0)
-
-/*Table sizes*/
-#define MXUNIT 100
-
-extern int f__recpos;		/*position in current record */
-extern int f__cursor;		/* offset to move to */
-extern int f__hiwater;		/* so TL doesn't confuse us */
-
-#define WRITE	1
-#define READ	2
-#define SEQ	3
-#define DIR	4
-#define FMT	5
-#define UNF	6
-#define EXT	7
-#define INT	8
-
-#define buf_end(x) (x->_flag & _IONBF ? x->_ptr : x->_base + BUFSIZ)
diff --git a/contrib/libf2c/libI77/fmt.c b/contrib/libf2c/libI77/fmt.c
deleted file mode 100644
index fa9b73cd60e..00000000000
--- a/contrib/libf2c/libI77/fmt.c
+++ /dev/null
@@ -1,602 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-#define skip(s) while(*s==' ') s++
-#ifdef interdata
-#define SYLMX 300
-#endif
-#ifdef pdp11
-#define SYLMX 300
-#endif
-#ifdef vax
-#define SYLMX 300
-#endif
-#ifndef SYLMX
-#define SYLMX 300
-#endif
-#define GLITCH '\2'
-	/* special quote character for stu */
-extern int f__cursor, f__scale;
-extern flag f__cblank, f__cplus;	/*blanks in I and compulsory plus */
-static struct syl f__syl[SYLMX];
-int f__parenlvl, f__pc, f__revloc;
-
-static char *
-ap_end (char *s)
-{
-  char quote;
-  quote = *s++;
-  for (; *s; s++)
-    {
-      if (*s != quote)
-	continue;
-      if (*++s != quote)
-	return (s);
-    }
-  if (f__elist->cierr)
-    {
-      errno = 100;
-      return (NULL);
-    }
-  f__fatal (100, "bad string");
-   /*NOTREACHED*/ return 0;
-}
-
-static int
-op_gen (int a, int b, int c, int d)
-{
-  struct syl *p = &f__syl[f__pc];
-  if (f__pc >= SYLMX)
-    {
-      fprintf (stderr, "format too complicated:\n");
-      sig_die (f__fmtbuf, 1);
-    }
-  p->op = a;
-  p->p1 = b;
-  p->p2.i[0] = c;
-  p->p2.i[1] = d;
-  return (f__pc++);
-}
-static char *f_list (char *);
-static char *
-gt_num (char *s, int *n, int n1)
-{
-  int m = 0, f__cnt = 0;
-  char c;
-  for (c = *s;; c = *s)
-    {
-      if (c == ' ')
-	{
-	  s++;
-	  continue;
-	}
-      if (c > '9' || c < '0')
-	break;
-      m = 10 * m + c - '0';
-      f__cnt++;
-      s++;
-    }
-  if (f__cnt == 0)
-    {
-      if (!n1)
-	s = 0;
-      *n = n1;
-    }
-  else
-    *n = m;
-  return (s);
-}
-
-static char *
-f_s (char *s, int curloc)
-{
-  skip (s);
-  if (*s++ != '(')
-    {
-      return (NULL);
-    }
-  if (f__parenlvl++ == 1)
-    f__revloc = curloc;
-  if (op_gen (RET1, curloc, 0, 0) < 0 || (s = f_list (s)) == NULL)
-    {
-      return (NULL);
-    }
-  return (s);
-}
-
-static int
-ne_d (char *s, char **p)
-{
-  int n, x, sign = 0;
-  struct syl *sp;
-  switch (*s)
-    {
-    default:
-      return (0);
-    case ':':
-      (void) op_gen (COLON, 0, 0, 0);
-      break;
-    case '$':
-      (void) op_gen (NONL, 0, 0, 0);
-      break;
-    case 'B':
-    case 'b':
-      if (*++s == 'z' || *s == 'Z')
-	(void) op_gen (BZ, 0, 0, 0);
-      else
-	(void) op_gen (BN, 0, 0, 0);
-      break;
-    case 'S':
-    case 's':
-      if (*(s + 1) == 's' || *(s + 1) == 'S')
-	{
-	  x = SS;
-	  s++;
-	}
-      else if (*(s + 1) == 'p' || *(s + 1) == 'P')
-	{
-	  x = SP;
-	  s++;
-	}
-      else
-	x = S;
-      (void) op_gen (x, 0, 0, 0);
-      break;
-    case '/':
-      (void) op_gen (SLASH, 0, 0, 0);
-      break;
-    case '-':
-      sign = 1;
-    case '+':
-      s++;			/*OUTRAGEOUS CODING TRICK */
-    case '0':
-    case '1':
-    case '2':
-    case '3':
-    case '4':
-    case '5':
-    case '6':
-    case '7':
-    case '8':
-    case '9':
-      if (!(s = gt_num (s, &n, 0)))
-	{
-	bad:*p = 0;
-	  return 1;
-	}
-      switch (*s)
-	{
-	default:
-	  return (0);
-	case 'P':
-	case 'p':
-	  if (sign)
-	    n = -n;
-	  (void) op_gen (P, n, 0, 0);
-	  break;
-	case 'X':
-	case 'x':
-	  (void) op_gen (X, n, 0, 0);
-	  break;
-	case 'H':
-	case 'h':
-	  sp = &f__syl[op_gen (H, n, 0, 0)];
-	  sp->p2.s = s + 1;
-	  s += n;
-	  break;
-	}
-      break;
-    case GLITCH:
-    case '"':
-    case '\'':
-      sp = &f__syl[op_gen (APOS, 0, 0, 0)];
-      sp->p2.s = s;
-      if ((*p = ap_end (s)) == NULL)
-	return (0);
-      return (1);
-    case 'T':
-    case 't':
-      if (*(s + 1) == 'l' || *(s + 1) == 'L')
-	{
-	  x = TL;
-	  s++;
-	}
-      else if (*(s + 1) == 'r' || *(s + 1) == 'R')
-	{
-	  x = TR;
-	  s++;
-	}
-      else
-	x = T;
-      if (!(s = gt_num (s + 1, &n, 0)))
-	goto bad;
-      s--;
-      (void) op_gen (x, n, 0, 0);
-      break;
-    case 'X':
-    case 'x':
-      (void) op_gen (X, 1, 0, 0);
-      break;
-    case 'P':
-    case 'p':
-      (void) op_gen (P, 1, 0, 0);
-      break;
-    }
-  s++;
-  *p = s;
-  return (1);
-}
-
-static int
-e_d (char *s, char **p)
-{
-  int i, im, n, w, d, e, found = 0, x = 0;
-  char *sv = s;
-  s = gt_num (s, &n, 1);
-  (void) op_gen (STACK, n, 0, 0);
-  switch (*s++)
-    {
-    default:
-      break;
-    case 'E':
-    case 'e':
-      x = 1;
-    case 'G':
-    case 'g':
-      found = 1;
-      if (!(s = gt_num (s, &w, 0)))
-	{
-	bad:
-	  *p = 0;
-	  return 1;
-	}
-      if (w == 0)
-	break;
-      if (*s == '.')
-	{
-	  if (!(s = gt_num (s + 1, &d, 0)))
-	    goto bad;
-	}
-      else
-	d = 0;
-      if (*s != 'E' && *s != 'e')
-	(void) op_gen (x == 1 ? E : G, w, d, 0);	/* default is Ew.dE2 */
-      else
-	{
-	  if (!(s = gt_num (s + 1, &e, 0)))
-	    goto bad;
-	  (void) op_gen (x == 1 ? EE : GE, w, d, e);
-	}
-      break;
-    case 'O':
-    case 'o':
-      i = O;
-      im = OM;
-      goto finish_I;
-    case 'Z':
-    case 'z':
-      i = Z;
-      im = ZM;
-      goto finish_I;
-    case 'L':
-    case 'l':
-      found = 1;
-      if (!(s = gt_num (s, &w, 0)))
-	goto bad;
-      if (w == 0)
-	break;
-      (void) op_gen (L, w, 0, 0);
-      break;
-    case 'A':
-    case 'a':
-      found = 1;
-      skip (s);
-      if (*s >= '0' && *s <= '9')
-	{
-	  s = gt_num (s, &w, 1);
-	  if (w == 0)
-	    break;
-	  (void) op_gen (AW, w, 0, 0);
-	  break;
-	}
-      (void) op_gen (A, 0, 0, 0);
-      break;
-    case 'F':
-    case 'f':
-      if (!(s = gt_num (s, &w, 0)))
-	goto bad;
-      found = 1;
-      if (w == 0)
-	break;
-      if (*s == '.')
-	{
-	  if (!(s = gt_num (s + 1, &d, 0)))
-	    goto bad;
-	}
-      else
-	d = 0;
-      (void) op_gen (F, w, d, 0);
-      break;
-    case 'D':
-    case 'd':
-      found = 1;
-      if (!(s = gt_num (s, &w, 0)))
-	goto bad;
-      if (w == 0)
-	break;
-      if (*s == '.')
-	{
-	  if (!(s = gt_num (s + 1, &d, 0)))
-	    goto bad;
-	}
-      else
-	d = 0;
-      (void) op_gen (D, w, d, 0);
-      break;
-    case 'I':
-    case 'i':
-      i = I;
-      im = IM;
-    finish_I:
-      if (!(s = gt_num (s, &w, 0)))
-	goto bad;
-      found = 1;
-      if (w == 0)
-	break;
-      if (*s != '.')
-	{
-	  (void) op_gen (i, w, 0, 0);
-	  break;
-	}
-      if (!(s = gt_num (s + 1, &d, 0)))
-	goto bad;
-      (void) op_gen (im, w, d, 0);
-      break;
-    }
-  if (found == 0)
-    {
-      f__pc--;			/*unSTACK */
-      *p = sv;
-      return (0);
-    }
-  *p = s;
-  return (1);
-}
-static char *
-i_tem (char *s)
-{
-  char *t;
-  int n, curloc;
-  if (*s == ')')
-    return (s);
-  if (ne_d (s, &t))
-    return (t);
-  if (e_d (s, &t))
-    return (t);
-  s = gt_num (s, &n, 1);
-  if ((curloc = op_gen (STACK, n, 0, 0)) < 0)
-    return (NULL);
-  return (f_s (s, curloc));
-}
-
-static char *
-f_list (char *s)
-{
-  for (; *s != 0;)
-    {
-      skip (s);
-      if ((s = i_tem (s)) == NULL)
-	return (NULL);
-      skip (s);
-      if (*s == ',')
-	s++;
-      else if (*s == ')')
-	{
-	  if (--f__parenlvl == 0)
-	    {
-	      (void) op_gen (REVERT, f__revloc, 0, 0);
-	      return (++s);
-	    }
-	  (void) op_gen (GOTO, 0, 0, 0);
-	  return (++s);
-	}
-    }
-  return (NULL);
-}
-
-int
-pars_f (char *s)
-{
-  char *e;
-
-  f__parenlvl = f__revloc = f__pc = 0;
-  if ((e = f_s (s, 0)) == NULL)
-    {
-      /* Try and delimit the format string.  Parens within
-         hollerith and quoted strings have to match for this
-         to work, but it's probably adequate for most needs.
-         Note that this is needed because a valid CHARACTER
-         variable passed for FMT= can contain '(I)garbage',
-         where `garbage' is billions and billions of junk
-         characters, and it's up to the run-time library to
-         know where the format string ends by counting parens.
-         Meanwhile, still treat NUL byte as "hard stop", since
-         f2c still appends that at end of FORMAT-statement
-         strings.  */
-
-      int level = 0;
-
-      for (f__fmtlen = 0;
-	   ((*s != ')') || (--level > 0))
-	   && (*s != '\0') && (f__fmtlen < 80); ++s, ++f__fmtlen)
-	{
-	  if (*s == '(')
-	    ++level;
-	}
-      if (*s == ')')
-	++f__fmtlen;
-      return (-1);
-    }
-  f__fmtlen = e - s;
-  return (0);
-}
-
-#define STKSZ 10
-int f__cnt[STKSZ], f__ret[STKSZ], f__cp, f__rp;
-flag f__workdone, f__nonl;
-
-static int
-type_f (int n)
-{
-  switch (n)
-    {
-    default:
-      return (n);
-    case RET1:
-      return (RET1);
-    case REVERT:
-      return (REVERT);
-    case GOTO:
-      return (GOTO);
-    case STACK:
-      return (STACK);
-    case X:
-    case SLASH:
-    case APOS:
-    case H:
-    case T:
-    case TL:
-    case TR:
-      return (NED);
-    case F:
-    case I:
-    case IM:
-    case A:
-    case AW:
-    case O:
-    case OM:
-    case L:
-    case E:
-    case EE:
-    case D:
-    case G:
-    case GE:
-    case Z:
-    case ZM:
-      return (ED);
-    }
-}
-integer
-do_fio (ftnint * number, char *ptr, ftnlen len)
-{
-  struct syl *p;
-  int n, i;
-  for (i = 0; i < *number; i++, ptr += len)
-    {
-    loop:switch (type_f ((p = &f__syl[f__pc])->op))
-	{
-	default:
-	  fprintf (stderr, "unknown code in do_fio: %d\n%.*s\n",
-		   p->op, f__fmtlen, f__fmtbuf);
-	  err (f__elist->cierr, 100, "do_fio");
-	case NED:
-	  if ((*f__doned) (p))
-	    {
-	      f__pc++;
-	      goto loop;
-	    }
-	  f__pc++;
-	  continue;
-	case ED:
-	  if (f__cnt[f__cp] <= 0)
-	    {
-	      f__cp--;
-	      f__pc++;
-	      goto loop;
-	    }
-	  if (ptr == NULL)
-	    return ((*f__doend) ());
-	  f__cnt[f__cp]--;
-	  f__workdone = 1;
-	  if ((n = (*f__doed) (p, ptr, len)) > 0)
-	    errfl (f__elist->cierr, errno, "fmt");
-	  if (n < 0)
-	    err (f__elist->ciend, (EOF), "fmt");
-	  continue;
-	case STACK:
-	  f__cnt[++f__cp] = p->p1;
-	  f__pc++;
-	  goto loop;
-	case RET1:
-	  f__ret[++f__rp] = p->p1;
-	  f__pc++;
-	  goto loop;
-	case GOTO:
-	  if (--f__cnt[f__cp] <= 0)
-	    {
-	      f__cp--;
-	      f__rp--;
-	      f__pc++;
-	      goto loop;
-	    }
-	  f__pc = 1 + f__ret[f__rp--];
-	  goto loop;
-	case REVERT:
-	  f__rp = f__cp = 0;
-	  f__pc = p->p1;
-	  if (ptr == NULL)
-	    return ((*f__doend) ());
-	  if (!f__workdone)
-	    return (0);
-	  if ((n = (*f__dorevert) ()) != 0)
-	    return (n);
-	  goto loop;
-	case COLON:
-	  if (ptr == NULL)
-	    return ((*f__doend) ());
-	  f__pc++;
-	  goto loop;
-	case NONL:
-	  f__nonl = 1;
-	  f__pc++;
-	  goto loop;
-	case S:
-	case SS:
-	  f__cplus = 0;
-	  f__pc++;
-	  goto loop;
-	case SP:
-	  f__cplus = 1;
-	  f__pc++;
-	  goto loop;
-	case P:
-	  f__scale = p->p1;
-	  f__pc++;
-	  goto loop;
-	case BN:
-	  f__cblank = 0;
-	  f__pc++;
-	  goto loop;
-	case BZ:
-	  f__cblank = 1;
-	  f__pc++;
-	  goto loop;
-	}
-    }
-  return (0);
-}
-
-int
-en_fio (void)
-{
-  ftnint one = 1;
-  return (do_fio (&one, (char *) NULL, (ftnint) 0));
-}
-
-void
-fmt_bg (void)
-{
-  f__workdone = f__cp = f__rp = f__pc = f__cursor = 0;
-  f__cnt[0] = f__ret[0] = 0;
-}
diff --git a/contrib/libf2c/libI77/fmt.h b/contrib/libf2c/libI77/fmt.h
deleted file mode 100644
index bcd84cee40a..00000000000
--- a/contrib/libf2c/libI77/fmt.h
+++ /dev/null
@@ -1,92 +0,0 @@
-struct syl
-{
-  int op;
-  int p1;
-  union
-  {
-    int i[2];
-    char *s;
-  }
-  p2;
-};
-#define RET1 1
-#define REVERT 2
-#define GOTO 3
-#define X 4
-#define SLASH 5
-#define STACK 6
-#define I 7
-#define ED 8
-#define NED 9
-#define IM 10
-#define APOS 11
-#define H 12
-#define TL 13
-#define TR 14
-#define T 15
-#define COLON 16
-#define S 17
-#define SP 18
-#define SS 19
-#define P 20
-#define BN 21
-#define BZ 22
-#define F 23
-#define E 24
-#define EE 25
-#define D 26
-#define G 27
-#define GE 28
-#define L 29
-#define A 30
-#define AW 31
-#define O 32
-#define NONL 33
-#define OM 34
-#define Z 35
-#define ZM 36
-extern int f__pc, f__parenlvl, f__revloc;
-typedef union
-{
-  real pf;
-  doublereal pd;
-}
-ufloat;
-typedef union
-{
-  short is;
-  signed char ic;
-  integer il;
-#ifdef Allow_TYQUAD
-  longint ili;
-#endif
-}
-Uint;
-extern int (*f__doed) (struct syl *, char *, ftnlen),
-  (*f__doned) (struct syl *);
-extern int (*f__dorevert) (void);
-extern void fmt_bg (void);
-extern int pars_f (char *);
-extern int rd_ed (struct syl *, char *, ftnlen), rd_ned (struct syl *);
-extern int w_ed (struct syl *, char *, ftnlen), w_ned (struct syl *);
-extern int wrt_E (ufloat *, int, int, int, ftnlen);
-extern int wrt_F (ufloat *, int, int, ftnlen);
-extern int wrt_L (Uint *, int, ftnlen);
-extern flag f__cblank, f__cplus, f__workdone, f__nonl;
-extern char *f__fmtbuf;
-extern int f__fmtlen;
-extern int f__scale;
-#define GET(x) if((x=(*f__getn)())<0) return(x)
-#define VAL(x) (x!='\n'?x:' ')
-#define PUT(x) (*f__putn)(x)
-extern int f__cursor;
-
-#undef TYQUAD
-#ifndef Allow_TYQUAD
-#undef longint
-#define longint long
-#else
-#define TYQUAD 14
-#endif
-
-extern char *f__icvt (longint, int *, int *, int);
diff --git a/contrib/libf2c/libI77/fmtlib.c b/contrib/libf2c/libI77/fmtlib.c
deleted file mode 100644
index 3d2a299d232..00000000000
--- a/contrib/libf2c/libI77/fmtlib.c
+++ /dev/null
@@ -1,46 +0,0 @@
-/*	@(#)fmtlib.c	1.2	*/
-#define MAXINTLENGTH 23
-#include "config.h"
-
-#include "f2c.h"
-#ifndef Allow_TYQUAD
-#undef longint
-#define longint long
-#undef ulongint
-#define ulongint unsigned long
-#endif
-
-char *
-f__icvt (longint value, int *ndigit, int *sign, int base)
-{
-  static char buf[MAXINTLENGTH + 1];
-  register int i;
-  ulongint uvalue;
-
-  if (value > 0)
-    {
-      uvalue = value;
-      *sign = 0;
-    }
-  else if (value < 0)
-    {
-      uvalue = -value;
-      *sign = 1;
-    }
-  else
-    {
-      *sign = 0;
-      *ndigit = 1;
-      buf[MAXINTLENGTH - 1] = '0';
-      return &buf[MAXINTLENGTH - 1];
-    }
-  i = MAXINTLENGTH;
-  do
-    {
-      buf[--i] = (uvalue % base) + '0';
-      uvalue /= base;
-    }
-  while (uvalue > 0);
-  *ndigit = MAXINTLENGTH - i;
-  return &buf[i];
-}
diff --git a/contrib/libf2c/libI77/fp.h b/contrib/libf2c/libI77/fp.h
deleted file mode 100644
index 2b78ef9cc52..00000000000
--- a/contrib/libf2c/libI77/fp.h
+++ /dev/null
@@ -1,28 +0,0 @@
-#define FMAX 40
-#define EXPMAXDIGS 8
-#define EXPMAX 99999999
-/* FMAX = max number of nonzero digits passed to atof() */
-/* EXPMAX = 10^EXPMAXDIGS - 1 = largest allowed exponent absolute value */
-
-#ifdef V10			/* Research Tenth-Edition Unix */
-#include "local.h"
-#endif
-
-/* MAXFRACDIGS and MAXINTDIGS are for wrt_F -- bounds (not necessarily
-   tight) on the maximum number of digits to the right and left of
- * the decimal point.
- */
-
-#ifdef VAX
-#define MAXFRACDIGS 56
-#define MAXINTDIGS 38
-#else
-#ifdef CRAY
-#define MAXFRACDIGS 9880
-#define MAXINTDIGS 9864
-#else
-/* values that suffice for IEEE double */
-#define MAXFRACDIGS 344
-#define MAXINTDIGS 308
-#endif
-#endif
diff --git a/contrib/libf2c/libI77/ftell_.c b/contrib/libf2c/libI77/ftell_.c
deleted file mode 100644
index 63153420fbc..00000000000
--- a/contrib/libf2c/libI77/ftell_.c
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-
-static FILE *
-unit_chk (integer Unit, char *who)
-{
-  if (Unit >= MXUNIT || Unit < 0)
-    f__fatal (101, who);
-  return f__units[Unit].ufd;
-}
-
-integer
-G77_ftell_0 (integer * Unit)
-{
-  FILE *f;
-  return (f = unit_chk (*Unit, "ftell")) ? (integer) FTELL (f) : -1L;
-}
-
-integer
-G77_fseek_0 (integer * Unit, integer * offset, integer * xwhence)
-{
-  FILE *f;
-  int w = (int) *xwhence;
-#ifdef SEEK_SET
-  static int wohin[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
-#endif
-  if (w < 0 || w > 2)
-    w = 0;
-#ifdef SEEK_SET
-  w = wohin[w];
-#endif
-  return !(f = unit_chk (*Unit, "fseek"))
-    || FSEEK (f, (off_t) * offset, w) ? 1 : 0;
-}
diff --git a/contrib/libf2c/libI77/iio.c b/contrib/libf2c/libI77/iio.c
deleted file mode 100644
index 940cbf82f91..00000000000
--- a/contrib/libf2c/libI77/iio.c
+++ /dev/null
@@ -1,157 +0,0 @@
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-extern char *f__icptr;
-char *f__icend;
-extern icilist *f__svic;
-int f__icnum;
-extern int f__hiwater;
-int
-z_getc (void)
-{
-  if (f__recpos++ < f__svic->icirlen)
-    {
-      if (f__icptr >= f__icend)
-	err (f__svic->iciend, (EOF), "endfile");
-      return (*(unsigned char *) f__icptr++);
-    }
-  return '\n';
-}
-
-void
-z_putc (int c)
-{
-  if (f__recpos++ < f__svic->icirlen && f__icptr < f__icend)
-    *f__icptr++ = c;
-}
-int
-z_rnew (void)
-{
-  f__icptr = f__svic->iciunit + (++f__icnum) * f__svic->icirlen;
-  f__recpos = 0;
-  f__cursor = 0;
-  f__hiwater = 0;
-  return 1;
-}
-
-static int
-z_endp (void)
-{
-  (*f__donewrec) ();
-  return 0;
-}
-
-int
-c_si (icilist * a)
-{
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  f__init |= 2;
-  f__elist = (cilist *) a;
-  f__fmtbuf = a->icifmt;
-  f__curunit = 0;
-  f__sequential = f__formatted = 1;
-  f__external = 0;
-  if (pars_f (f__fmtbuf) < 0)
-    err (a->icierr, 100, "startint");
-  fmt_bg ();
-  f__cblank = f__cplus = f__scale = 0;
-  f__svic = a;
-  f__icnum = f__recpos = 0;
-  f__cursor = 0;
-  f__hiwater = 0;
-  f__icptr = a->iciunit;
-  f__icend = f__icptr + a->icirlen * a->icirnum;
-  f__cf = 0;
-  return (0);
-}
-
-int
-iw_rev (void)
-{
-  if (f__workdone)
-    z_endp ();
-  f__hiwater = f__recpos = f__cursor = 0;
-  return (f__workdone = 0);
-}
-
-integer
-s_rsfi (icilist * a)
-{
-  int n;
-  if ((n = c_si (a)))
-    return (n);
-  f__reading = 1;
-  f__doed = rd_ed;
-  f__doned = rd_ned;
-  f__getn = z_getc;
-  f__dorevert = z_endp;
-  f__donewrec = z_rnew;
-  f__doend = z_endp;
-  return (0);
-}
-
-int
-z_wnew (void)
-{
-  if (f__recpos < f__hiwater)
-    {
-      f__icptr += f__hiwater - f__recpos;
-      f__recpos = f__hiwater;
-    }
-  while (f__recpos++ < f__svic->icirlen)
-    *f__icptr++ = ' ';
-  f__recpos = 0;
-  f__cursor = 0;
-  f__hiwater = 0;
-  f__icnum++;
-  return 1;
-}
-
-integer
-s_wsfi (icilist * a)
-{
-  int n;
-  if ((n = c_si (a)))
-    return (n);
-  f__reading = 0;
-  f__doed = w_ed;
-  f__doned = w_ned;
-  f__putn = z_putc;
-  f__dorevert = iw_rev;
-  f__donewrec = z_wnew;
-  f__doend = z_endp;
-  return (0);
-}
-
-integer
-e_rsfi (void)
-{
-  int n;
-  f__init &= ~2;
-  n = en_fio ();
-  f__fmtbuf = NULL;
-  return (n);
-}
-
-integer
-e_wsfi (void)
-{
-  int n;
-  f__init &= ~2;
-  n = en_fio ();
-  f__fmtbuf = NULL;
-  if (f__svic->icirnum != 1
-      && (f__icnum > f__svic->icirnum
-	  || (f__icnum == f__svic->icirnum && (f__recpos | f__hiwater))))
-    err (f__svic->icierr, 110, "inwrite");
-  if (f__recpos < f__hiwater)
-    f__recpos = f__hiwater;
-  if (f__recpos >= f__svic->icirlen)
-    err (f__svic->icierr, 110, "recend");
-  if (!f__recpos && f__icnum)
-    return n;
-  while (f__recpos++ < f__svic->icirlen)
-    *f__icptr++ = ' ';
-  return n;
-}
diff --git a/contrib/libf2c/libI77/ilnw.c b/contrib/libf2c/libI77/ilnw.c
deleted file mode 100644
index 0a92a0cbac2..00000000000
--- a/contrib/libf2c/libI77/ilnw.c
+++ /dev/null
@@ -1,70 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "lio.h"
-extern char *f__icptr;
-extern char *f__icend;
-extern icilist *f__svic;
-extern int f__icnum;
-extern void z_putc (int);
-
-static int
-z_wSL (void)
-{
-  while (f__recpos < f__svic->icirlen)
-    z_putc (' ');
-  return z_rnew ();
-}
-
-static void
-c_liw (icilist * a)
-{
-  f__reading = 0;
-  f__external = 0;
-  f__formatted = 1;
-  f__putn = z_putc;
-  L_len = a->icirlen;
-  f__donewrec = z_wSL;
-  f__svic = a;
-  f__icnum = f__recpos = 0;
-  f__cursor = 0;
-  f__cf = 0;
-  f__curunit = 0;
-  f__icptr = a->iciunit;
-  f__icend = f__icptr + a->icirlen * a->icirnum;
-  f__elist = (cilist *) a;
-}
-
-integer
-s_wsni (icilist * a)
-{
-  cilist ca;
-
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  c_liw (a);
-  ca.cifmt = a->icifmt;
-  x_wsne (&ca);
-  z_wSL ();
-  return 0;
-}
-
-integer
-s_wsli (icilist * a)
-{
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__lioproc = l_write;
-  c_liw (a);
-  return (0);
-}
-
-integer
-e_wsli (void)
-{
-  f__init = 1;
-  z_wSL ();
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/inquire.c b/contrib/libf2c/libI77/inquire.c
deleted file mode 100644
index dae869cb4bf..00000000000
--- a/contrib/libf2c/libI77/inquire.c
+++ /dev/null
@@ -1,143 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include 
-#if defined (MSDOS) && !defined (GO32)
-#undef abs
-#undef min
-#undef max
-#include "io.h"
-#endif
-integer
-f_inqu (inlist * a)
-{
-  flag byfile;
-  int i, n;
-  unit *p;
-  char buf[256];
-  long x;
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  if (a->infile != NULL)
-    {
-      byfile = 1;
-      g_char (a->infile, a->infilen, buf);
-#ifdef NON_UNIX_STDIO
-      x = access (buf, 0) ? -1 : 0;
-      for (i = 0, p = NULL; i < MXUNIT; i++)
-	if (f__units[i].ufd != NULL
-	    && f__units[i].ufnm != NULL && !strcmp (f__units[i].ufnm, buf))
-	  {
-	    p = &f__units[i];
-	    break;
-	  }
-#else
-      x = f__inode (buf, &n);
-      for (i = 0, p = NULL; i < MXUNIT; i++)
-	if (f__units[i].uinode == x
-	    && f__units[i].ufd != NULL && f__units[i].udev == n)
-	  {
-	    p = &f__units[i];
-	    break;
-	  }
-#endif
-    }
-  else
-    {
-      byfile = 0;
-      if (a->inunit < MXUNIT && a->inunit >= 0)
-	{
-	  p = &f__units[a->inunit];
-	}
-      else
-	{
-	  p = NULL;
-	}
-    }
-  if (a->inex != NULL)
-    {
-      if ((byfile && x != -1) || (!byfile && p != NULL))
-	*a->inex = 1;
-      else
-	*a->inex = 0;
-    }
-  if (a->inopen != NULL)
-    {
-      if (byfile)
-	*a->inopen = (p != NULL);
-      else
-	*a->inopen = (p != NULL && p->ufd != NULL);
-    }
-  if (a->innum != NULL)
-    *a->innum = p - f__units;
-  if (a->innamed != NULL)
-    {
-      if (byfile || (p != NULL && p->ufnm != NULL))
-	*a->innamed = 1;
-      else
-	*a->innamed = 0;
-    }
-  if (a->inname != NULL)
-    {
-      if (byfile)
-	b_char (buf, a->inname, a->innamlen);
-      else if (p != NULL && p->ufnm != NULL)
-	b_char (p->ufnm, a->inname, a->innamlen);
-    }
-  if (a->inacc != NULL && p != NULL && p->ufd != NULL)
-    {
-      if (p->url)
-	b_char ("DIRECT", a->inacc, a->inacclen);
-      else
-	b_char ("SEQUENTIAL", a->inacc, a->inacclen);
-    }
-  if (a->inseq != NULL)
-    {
-      if (p != NULL && p->url)
-	b_char ("NO", a->inseq, a->inseqlen);
-      else
-	b_char ("YES", a->inseq, a->inseqlen);
-    }
-  if (a->indir != NULL)
-    {
-      if (p == NULL || p->url)
-	b_char ("YES", a->indir, a->indirlen);
-      else
-	b_char ("NO", a->indir, a->indirlen);
-    }
-  if (a->infmt != NULL)
-    {
-      if (p != NULL && p->ufmt == 0)
-	b_char ("UNFORMATTED", a->infmt, a->infmtlen);
-      else
-	b_char ("FORMATTED", a->infmt, a->infmtlen);
-    }
-  if (a->inform != NULL)
-    {
-      if (p != NULL && p->ufmt == 0)
-	b_char ("NO", a->inform, a->informlen);
-      else
-	b_char ("YES", a->inform, a->informlen);
-    }
-  if (a->inunf)
-    {
-      if (p != NULL && p->ufmt == 0)
-	b_char ("YES", a->inunf, a->inunflen);
-      else if (p != NULL)
-	b_char ("NO", a->inunf, a->inunflen);
-      else
-	b_char ("UNKNOWN", a->inunf, a->inunflen);
-    }
-  if (a->inrecl != NULL && p != NULL)
-    *a->inrecl = p->url;
-  if (a->innrec != NULL && p != NULL && p->url > 0)
-    *a->innrec = FTELL (p->ufd) / p->url + 1;
-  if (a->inblank && p != NULL && p->ufmt)
-    {
-      if (p->ublnk)
-	b_char ("ZERO", a->inblank, a->inblanklen);
-      else
-	b_char ("NULL", a->inblank, a->inblanklen);
-    }
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/lio.h b/contrib/libf2c/libI77/lio.h
deleted file mode 100644
index 4e17115e8d4..00000000000
--- a/contrib/libf2c/libI77/lio.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*	copy of ftypes from the compiler */
-/* variable types
- * numeric assumptions:
- *	int < reals < complexes
- *	TYDREAL-TYREAL = TYDCOMPLEX-TYCOMPLEX
- */
-
-/* 0-10 retain their old (pre LOGICAL*1, etc.) */
-/* values to allow mixing old and new objects. */
-
-#define TYUNKNOWN 0
-#define TYADDR 1
-#define TYSHORT 2
-#define TYLONG 3
-#define TYREAL 4
-#define TYDREAL 5
-#define TYCOMPLEX 6
-#define TYDCOMPLEX 7
-#define TYLOGICAL 8
-#define TYCHAR 9
-#define TYSUBR 10
-#define TYINT1 11
-#define TYLOGICAL1 12
-#define TYLOGICAL2 13
-#ifdef Allow_TYQUAD
-#undef TYQUAD
-#define TYQUAD 14
-#endif
-
-#define	LINTW	24
-#define	LINE	80
-#define	LLOGW	2
-#ifdef Old_list_output
-#define	LLOW	1.0
-#define	LHIGH	1.e9
-#define	LEFMT	" %# .8E"
-#define	LFFMT	" %# .9g"
-#else
-#define	LGFMT	"%.9G"
-#endif
-/* LEFBL 20 should suffice; 24 overcomes a NeXT bug. */
-#define	LEFBL	24
-
-typedef union
-{
-  signed char flchar;
-  short flshort;
-  ftnint flint;
-#ifdef Allow_TYQUAD
-  longint fllongint;
-#endif
-  real flreal;
-  doublereal fldouble;
-}
-flex;
-extern int f__scale;
-extern int (*f__lioproc) (ftnint *, char *, ftnlen, ftnint);
-extern int l_write (ftnint *, char *, ftnlen, ftnint);
-extern void x_wsne (cilist *);
-extern int c_le (cilist *), (*l_getc) (void), (*l_ungetc) (int, FILE *);
-extern int l_read (ftnint *, char *, ftnlen, ftnint);
-extern integer e_rsle (void), e_wsle (void), s_wsne (cilist *);
-extern int z_rnew (void);
-extern ftnint L_len;
diff --git a/contrib/libf2c/libI77/lread.c b/contrib/libf2c/libI77/lread.c
deleted file mode 100644
index b926367b930..00000000000
--- a/contrib/libf2c/libI77/lread.c
+++ /dev/null
@@ -1,845 +0,0 @@
-#include "config.h"
-#include 
-#include "f2c.h"
-#include "fio.h"
-
-/* Compile with -DF8X_NML_ELIDE_QUOTES to permit eliding quotation */
-/* marks in namelist input a la the Fortran 8X Draft published in  */
-/* the May 1989 issue of Fortran Forum. */
-
-
-extern char *f__fmtbuf;
-extern int f__fmtlen;
-
-#ifdef Allow_TYQUAD
-static longint f__llx;
-#endif
-
-#undef abs
-#undef min
-#undef max
-#include 
-
-#include "fmt.h"
-#include "lio.h"
-#include "fp.h"
-
-int (*f__lioproc) (ftnint *, char *, ftnlen, ftnint), (*l_getc) (void),
-  (*l_ungetc) (int, FILE *);
-
-int l_eof;
-
-#define isblnk(x) (f__ltab[x+1]&B)
-#define issep(x) (f__ltab[x+1]&SX)
-#define isapos(x) (f__ltab[x+1]&AX)
-#define isexp(x) (f__ltab[x+1]&EX)
-#define issign(x) (f__ltab[x+1]&SG)
-#define iswhit(x) (f__ltab[x+1]&WH)
-#define SX 1
-#define B 2
-#define AX 4
-#define EX 8
-#define SG 16
-#define WH 32
-char f__ltab[128 + 1] = {	/* offset one for EOF */
-  0,
-  0, 0, AX, 0, 0, 0, 0, 0, 0, WH | B, SX | WH, 0, 0, 0, 0, 0,
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-  SX | B | WH, 0, AX, 0, 0, 0, 0, AX, 0, 0, 0, SG, SX, SG, 0, SX,
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-  0, 0, 0, 0, EX, EX, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-  AX, 0, 0, 0, EX, EX, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-};
-
-#ifdef ungetc
-static int
-un_getc (int x, FILE * f__cf)
-{
-  return ungetc (x, f__cf);
-}
-#else
-#define un_getc ungetc
-extern int ungetc (int, FILE *);	/* for systems with a buggy stdio.h */
-#endif
-
-int
-t_getc (void)
-{
-  int ch;
-  if (f__curunit->uend)
-    return (EOF);
-  if ((ch = getc (f__cf)) != EOF)
-    return (ch);
-  if (feof (f__cf))
-    f__curunit->uend = l_eof = 1;
-  return (EOF);
-}
-
-integer
-e_rsle (void)
-{
-  int ch;
-  f__init = 1;
-  if (f__curunit->uend)
-    return (0);
-  while ((ch = t_getc ()) != '\n')
-    if (ch == EOF)
-      {
-	if (feof (f__cf))
-	  f__curunit->uend = l_eof = 1;
-	return EOF;
-      }
-  return (0);
-}
-
-flag f__lquit;
-int f__lcount, f__ltype, nml_read;
-char *f__lchar;
-double f__lx, f__ly;
-#define ERR(x) if((n=(x))) {f__init &= ~2; return(n);}
-#define GETC(x) (x=(*l_getc)())
-#define Ungetc(x,y) (*l_ungetc)(x,y)
-
-static int
-l_R (int poststar, int reqint)
-{
-  char s[FMAX + EXPMAXDIGS + 4];
-  register int ch;
-  register char *sp, *spe, *sp1;
-  long e, exp;
-  int havenum, havestar, se;
-
-  if (!poststar)
-    {
-      if (f__lcount > 0)
-	return (0);
-      f__lcount = 1;
-    }
-#ifdef Allow_TYQUAD
-  f__llx = 0;
-#endif
-  f__ltype = 0;
-  exp = 0;
-  havestar = 0;
-retry:
-  sp1 = sp = s;
-  spe = sp + FMAX;
-  havenum = 0;
-
-  switch (GETC (ch))
-    {
-    case '-':
-      *sp++ = ch;
-      sp1++;
-      spe++;
-    case '+':
-      GETC (ch);
-    }
-  while (ch == '0')
-    {
-      ++havenum;
-      GETC (ch);
-    }
-  while (isdigit (ch))
-    {
-      if (sp < spe)
-	*sp++ = ch;
-      else
-	++exp;
-      GETC (ch);
-    }
-  if (ch == '*' && !poststar)
-    {
-      if (sp == sp1 || exp || *s == '-')
-	{
-	  errfl (f__elist->cierr, 112, "bad repetition count");
-	}
-      poststar = havestar = 1;
-      *sp = 0;
-      f__lcount = atoi (s);
-      goto retry;
-    }
-  if (ch == '.')
-    {
-#ifndef ALLOW_FLOAT_IN_INTEGER_LIST_INPUT
-      if (reqint)
-	errfl (f__elist->cierr, 115, "invalid integer");
-#endif
-      GETC (ch);
-      if (sp == sp1)
-	while (ch == '0')
-	  {
-	    ++havenum;
-	    --exp;
-	    GETC (ch);
-	  }
-      while (isdigit (ch))
-	{
-	  if (sp < spe)
-	    {
-	      *sp++ = ch;
-	      --exp;
-	    }
-	  GETC (ch);
-	}
-    }
-  havenum += sp - sp1;
-  se = 0;
-  if (issign (ch))
-    goto signonly;
-  if (havenum && isexp (ch))
-    {
-#ifndef ALLOW_FLOAT_IN_INTEGER_LIST_INPUT
-      if (reqint)
-	errfl (f__elist->cierr, 115, "invalid integer");
-#endif
-      GETC (ch);
-      if (issign (ch))
-	{
-	signonly:
-	  if (ch == '-')
-	    se = 1;
-	  GETC (ch);
-	}
-      if (!isdigit (ch))
-	{
-	bad:
-	  errfl (f__elist->cierr, 112, "exponent field");
-	}
-
-      e = ch - '0';
-      while (isdigit (GETC (ch)))
-	{
-	  e = 10 * e + ch - '0';
-	  if (e > EXPMAX)
-	    goto bad;
-	}
-      if (se)
-	exp -= e;
-      else
-	exp += e;
-    }
-  (void) Ungetc (ch, f__cf);
-  if (sp > sp1)
-    {
-      ++havenum;
-      while (*--sp == '0')
-	++exp;
-      if (exp)
-	sprintf (sp + 1, "e%ld", exp);
-      else
-	sp[1] = 0;
-      f__lx = atof (s);
-#ifdef Allow_TYQUAD
-      if (reqint & 2 && (se = sp - sp1 + exp) > 14 && se < 20)
-	{
-	  /* Assuming 64-bit longint and 32-bit long. */
-	  if (exp < 0)
-	    sp += exp;
-	  if (sp1 <= sp)
-	    {
-	      f__llx = *sp1 - '0';
-	      while (++sp1 <= sp)
-		f__llx = 10 * f__llx + (*sp1 - '0');
-	    }
-	  while (--exp >= 0)
-	    f__llx *= 10;
-	  if (*s == '-')
-	    f__llx = -f__llx;
-	}
-#endif
-    }
-  else
-    f__lx = 0.;
-  if (havenum)
-    f__ltype = TYLONG;
-  else
-    switch (ch)
-      {
-      case ',':
-      case '/':
-	break;
-      default:
-	if (havestar && (ch == ' ' || ch == '\t' || ch == '\n'))
-	  break;
-	if (nml_read > 1)
-	  {
-	    f__lquit = 2;
-	    return 0;
-	  }
-	errfl (f__elist->cierr, 112, "invalid number");
-      }
-  return 0;
-}
-
-static int
-rd_count (register int ch)
-{
-  if (ch < '0' || ch > '9')
-    return 1;
-  f__lcount = ch - '0';
-  while (GETC (ch) >= '0' && ch <= '9')
-    f__lcount = 10 * f__lcount + ch - '0';
-  Ungetc (ch, f__cf);
-  return f__lcount <= 0;
-}
-
-static int
-l_C (void)
-{
-  int ch, nml_save;
-  double lz;
-  if (f__lcount > 0)
-    return (0);
-  f__ltype = 0;
-  GETC (ch);
-  if (ch != '(')
-    {
-      if (nml_read > 1 && (ch < '0' || ch > '9'))
-	{
-	  Ungetc (ch, f__cf);
-	  f__lquit = 2;
-	  return 0;
-	}
-      if (rd_count (ch))
-        {
-	  if (!f__cf || !feof (f__cf))
-	    errfl (f__elist->cierr, 112, "complex format");
-	  else
-	    err (f__elist->cierr, (EOF), "lread");
-	}
-      if (GETC (ch) != '*')
-	{
-	  if (!f__cf || !feof (f__cf))
-	    errfl (f__elist->cierr, 112, "no star");
-	  else
-	    err (f__elist->cierr, (EOF), "lread");
-	}
-      if (GETC (ch) != '(')
-	{
-	  Ungetc (ch, f__cf);
-	  return (0);
-	}
-    }
-  else
-    f__lcount = 1;
-  while (iswhit (GETC (ch)));
-  Ungetc (ch, f__cf);
-  nml_save = nml_read;
-  nml_read = 0;
-  if ((ch = l_R (1, 0)))
-    return ch;
-  if (!f__ltype)
-    errfl (f__elist->cierr, 112, "no real part");
-  lz = f__lx;
-  while (iswhit (GETC (ch)));
-  if (ch != ',')
-    {
-      (void) Ungetc (ch, f__cf);
-      errfl (f__elist->cierr, 112, "no comma");
-    }
-  while (iswhit (GETC (ch)));
-  (void) Ungetc (ch, f__cf);
-  if ((ch = l_R (1, 0)))
-    return ch;
-  if (!f__ltype)
-    errfl (f__elist->cierr, 112, "no imaginary part");
-  while (iswhit (GETC (ch)));
-  if (ch != ')')
-    errfl (f__elist->cierr, 112, "no )");
-  f__ly = f__lx;
-  f__lx = lz;
-#ifdef Allow_TYQUAD
-  f__llx = 0;
-#endif
-  nml_read = nml_save;
-  return (0);
-}
-
-static char nmLbuf[256], *nmL_next;
-static int (*nmL_getc_save) (void);
-static int (*nmL_ungetc_save) (int, FILE *);
-
-static int
-nmL_getc (void)
-{
-  int rv;
-  if ((rv = *nmL_next++))
-    return rv;
-  l_getc = nmL_getc_save;
-  l_ungetc = nmL_ungetc_save;
-  return (*l_getc) ();
-}
-
-static int
-nmL_ungetc (int x, FILE * f)
-{
-  f = f;			/* banish non-use warning */
-  return *--nmL_next = x;
-}
-
-static int
-Lfinish (int ch, int dot, int *rvp)
-{
-  char *s, *se;
-  static char what[] = "namelist input";
-
-  s = nmLbuf + 2;
-  se = nmLbuf + sizeof (nmLbuf) - 1;
-  *s++ = ch;
-  while (!issep (GETC (ch)) && ch != EOF)
-    {
-      if (s >= se)
-	{
-	nmLbuf_ovfl:
-	  return *rvp = err__fl (f__elist->cierr, 131, what);
-	}
-      *s++ = ch;
-      if (ch != '=')
-	continue;
-      if (dot)
-	return *rvp = err__fl (f__elist->cierr, 112, what);
-    got_eq:
-      *s = 0;
-      nmL_getc_save = l_getc;
-      l_getc = nmL_getc;
-      nmL_ungetc_save = l_ungetc;
-      l_ungetc = nmL_ungetc;
-      nmLbuf[1] = *(nmL_next = nmLbuf) = ',';
-      *rvp = f__lcount = 0;
-      return 1;
-    }
-  if (dot)
-    goto done;
-  for (;;)
-    {
-      if (s >= se)
-	goto nmLbuf_ovfl;
-      *s++ = ch;
-      if (!isblnk (ch))
-	break;
-      if (GETC (ch) == EOF)
-	goto done;
-    }
-  if (ch == '=')
-    goto got_eq;
-done:
-  Ungetc (ch, f__cf);
-  return 0;
-}
-
-static int
-l_L (void)
-{
-  int ch, rv, sawdot;
-  if (f__lcount > 0)
-    return (0);
-  f__lcount = 1;
-  f__ltype = 0;
-  GETC (ch);
-  if (isdigit (ch))
-    {
-      rd_count (ch);
-      if (GETC (ch) != '*')
-        {
-	  if (!f__cf || !feof (f__cf))
-	    errfl (f__elist->cierr, 112, "no star");
-	  else
-	    err (f__elist->cierr, (EOF), "lread");
-	}
-      GETC (ch);
-    }
-  sawdot = 0;
-  if (ch == '.')
-    {
-      sawdot = 1;
-      GETC (ch);
-    }
-  switch (ch)
-    {
-    case 't':
-    case 'T':
-      if (nml_read && Lfinish (ch, sawdot, &rv))
-	return rv;
-      f__lx = 1;
-      break;
-    case 'f':
-    case 'F':
-      if (nml_read && Lfinish (ch, sawdot, &rv))
-	return rv;
-      f__lx = 0;
-      break;
-    default:
-      if (isblnk (ch) || issep (ch) || ch == EOF)
-	{
-	  (void) Ungetc (ch, f__cf);
-	  return (0);
-	}
-      if (nml_read > 1)
-	{
-	  Ungetc (ch, f__cf);
-	  f__lquit = 2;
-	  return 0;
-	}
-      errfl (f__elist->cierr, 112, "logical");
-    }
-  f__ltype = TYLONG;
-  while (!issep (GETC (ch)) && ch != EOF);
-  (void) Ungetc (ch, f__cf);
-  return (0);
-}
-
-#define BUFSIZE	128
-
-static int
-l_CHAR (void)
-{
-  int ch, size, i;
-  static char rafail[] = "realloc failure";
-  char quote, *p;
-  if (f__lcount > 0)
-    return (0);
-  f__ltype = 0;
-  if (f__lchar != NULL)
-    free (f__lchar);
-  size = BUFSIZE;
-  p = f__lchar = (char *) malloc ((unsigned int) size);
-  if (f__lchar == NULL)
-    errfl (f__elist->cierr, 113, "no space");
-
-  GETC (ch);
-  if (isdigit (ch))
-    {
-      /* allow Fortran 8x-style unquoted string...    */
-      /* either find a repetition count or the string */
-      f__lcount = ch - '0';
-      *p++ = ch;
-      for (i = 1;;)
-	{
-	  switch (GETC (ch))
-	    {
-	    case '*':
-	      if (f__lcount == 0)
-		{
-		  f__lcount = 1;
-#ifndef F8X_NML_ELIDE_QUOTES
-		  if (nml_read)
-		    goto no_quote;
-#endif
-		  goto noquote;
-		}
-	      p = f__lchar;
-	      goto have_lcount;
-	    case ',':
-	    case ' ':
-	    case '\t':
-	    case '\n':
-	    case '/':
-	      Ungetc (ch, f__cf);
-	      /* no break */
-	    case EOF:
-	      f__lcount = 1;
-	      f__ltype = TYCHAR;
-	      return *p = 0;
-	    }
-	  if (!isdigit (ch))
-	    {
-	      f__lcount = 1;
-#ifndef F8X_NML_ELIDE_QUOTES
-	      if (nml_read)
-		{
-		no_quote:
-		  errfl (f__elist->cierr, 112,
-			 "undelimited character string");
-		}
-#endif
-	      goto noquote;
-	    }
-	  *p++ = ch;
-	  f__lcount = 10 * f__lcount + ch - '0';
-	  if (++i == size)
-	    {
-	      f__lchar = (char *) realloc (f__lchar,
-					   (unsigned int) (size += BUFSIZE));
-	      if (f__lchar == NULL)
-		errfl (f__elist->cierr, 113, rafail);
-	      p = f__lchar + i;
-	    }
-	}
-    }
-  else
-    (void) Ungetc (ch, f__cf);
-have_lcount:
-  if (GETC (ch) == '\'' || ch == '"')
-    quote = ch;
-  else if (isblnk (ch) || (issep (ch) && ch != '\n') || ch == EOF)
-    {
-      Ungetc (ch, f__cf);
-      return 0;
-    }
-#ifndef F8X_NML_ELIDE_QUOTES
-  else if (nml_read > 1)
-    {
-      Ungetc (ch, f__cf);
-      f__lquit = 2;
-      return 0;
-    }
-#endif
-  else
-    {
-      /* Fortran 8x-style unquoted string */
-      *p++ = ch;
-      for (i = 1;;)
-	{
-	  switch (GETC (ch))
-	    {
-	    case ',':
-	    case ' ':
-	    case '\t':
-	    case '\n':
-	    case '/':
-	      Ungetc (ch, f__cf);
-	      /* no break */
-	    case EOF:
-	      f__ltype = TYCHAR;
-	      return *p = 0;
-	    }
-	noquote:
-	  *p++ = ch;
-	  if (++i == size)
-	    {
-	      f__lchar = (char *) realloc (f__lchar,
-					   (unsigned int) (size += BUFSIZE));
-	      if (f__lchar == NULL)
-		errfl (f__elist->cierr, 113, rafail);
-	      p = f__lchar + i;
-	    }
-	}
-    }
-  f__ltype = TYCHAR;
-  for (i = 0;;)
-    {
-      while (GETC (ch) != quote && ch != '\n' && ch != EOF && ++i < size)
-	*p++ = ch;
-      if (i == size)
-	{
-	newone:
-	  f__lchar = (char *) realloc (f__lchar,
-				       (unsigned int) (size += BUFSIZE));
-	  if (f__lchar == NULL)
-	    errfl (f__elist->cierr, 113, rafail);
-	  p = f__lchar + i - 1;
-	  *p++ = ch;
-	}
-      else if (ch == EOF)
-	return (EOF);
-      else if (ch == '\n')
-	{
-	  if (*(p - 1) != '\\')
-	    continue;
-	  i--;
-	  p--;
-	  if (++i < size)
-	    *p++ = ch;
-	  else
-	    goto newone;
-	}
-      else if (GETC (ch) == quote)
-	{
-	  if (++i < size)
-	    *p++ = ch;
-	  else
-	    goto newone;
-	}
-      else
-	{
-	  (void) Ungetc (ch, f__cf);
-	  *p = 0;
-	  return (0);
-	}
-    }
-}
-
-int
-c_le (cilist * a)
-{
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__fmtbuf = "list io";
-  f__curunit = &f__units[a->ciunit];
-  f__fmtlen = 7;
-  if (a->ciunit >= MXUNIT || a->ciunit < 0)
-    err (a->cierr, 101, "stler");
-  f__scale = f__recpos = 0;
-  f__elist = a;
-  if (f__curunit->ufd == NULL && fk_open (SEQ, FMT, a->ciunit))
-    err (a->cierr, 102, "lio");
-  f__cf = f__curunit->ufd;
-  if (!f__curunit->ufmt)
-    err (a->cierr, 103, "lio");
-  return (0);
-}
-
-int
-l_read (ftnint * number, char *ptr, ftnlen len, ftnint type)
-{
-#define Ptr ((flex *)ptr)
-  int i, n, ch;
-  doublereal *yy;
-  real *xx;
-  for (i = 0; i < *number; i++)
-    {
-      if (f__lquit)
-	return (0);
-      if (l_eof)
-	err (f__elist->ciend, EOF, "list in");
-      if (f__lcount == 0)
-	{
-	  f__ltype = 0;
-	  for (;;)
-	    {
-	      GETC (ch);
-	      switch (ch)
-		{
-		case EOF:
-		  err (f__elist->ciend, (EOF), "list in");
-		case ' ':
-		case '\t':
-		case '\n':
-		  continue;
-		case '/':
-		  f__lquit = 1;
-		  goto loopend;
-		case ',':
-		  f__lcount = 1;
-		  goto loopend;
-		default:
-		  (void) Ungetc (ch, f__cf);
-		  goto rddata;
-		}
-	    }
-	}
-    rddata:
-      switch ((int) type)
-	{
-	case TYINT1:
-	case TYSHORT:
-	case TYLONG:
-#ifndef ALLOW_FLOAT_IN_INTEGER_LIST_INPUT
-	  ERR (l_R (0, 1));
-	  break;
-#endif
-	case TYREAL:
-	case TYDREAL:
-	  ERR (l_R (0, 0));
-	  break;
-#ifdef TYQUAD
-	case TYQUAD:
-	  n = l_R (0, 2);
-	  if (n)
-	    return n;
-	  break;
-#endif
-	case TYCOMPLEX:
-	case TYDCOMPLEX:
-	  ERR (l_C ());
-	  break;
-	case TYLOGICAL1:
-	case TYLOGICAL2:
-	case TYLOGICAL:
-	  ERR (l_L ());
-	  break;
-	case TYCHAR:
-	  ERR (l_CHAR ());
-	  break;
-	}
-      while (GETC (ch) == ' ' || ch == '\t');
-      if (ch != ',' || f__lcount > 1)
-	Ungetc (ch, f__cf);
-    loopend:
-      if (f__lquit)
-	return (0);
-      if (f__cf && ferror (f__cf))
-	{
-	  clearerr (f__cf);
-	  errfl (f__elist->cierr, errno, "list in");
-	}
-      if (f__ltype == 0)
-	goto bump;
-      switch ((int) type)
-	{
-	case TYINT1:
-	case TYLOGICAL1:
-	  Ptr->flchar = (char) f__lx;
-	  break;
-	case TYLOGICAL2:
-	case TYSHORT:
-	  Ptr->flshort = (short) f__lx;
-	  break;
-	case TYLOGICAL:
-	case TYLONG:
-	  Ptr->flint = (ftnint) f__lx;
-	  break;
-#ifdef Allow_TYQUAD
-	case TYQUAD:
-	  if (!(Ptr->fllongint = f__llx))
-	    Ptr->fllongint = f__lx;
-	  break;
-#endif
-	case TYREAL:
-	  Ptr->flreal = f__lx;
-	  break;
-	case TYDREAL:
-	  Ptr->fldouble = f__lx;
-	  break;
-	case TYCOMPLEX:
-	  xx = (real *) ptr;
-	  *xx++ = f__lx;
-	  *xx = f__ly;
-	  break;
-	case TYDCOMPLEX:
-	  yy = (doublereal *) ptr;
-	  *yy++ = f__lx;
-	  *yy = f__ly;
-	  break;
-	case TYCHAR:
-	  b_char (f__lchar, ptr, len);
-	  break;
-	}
-    bump:
-      if (f__lcount > 0)
-	f__lcount--;
-      ptr += len;
-      if (nml_read)
-	nml_read++;
-    }
-  return (0);
-#undef Ptr
-}
-
-integer
-s_rsle (cilist * a)
-{
-  int n;
-
-  f__reading = 1;
-  f__external = 1;
-  f__formatted = 1;
-  if ((n = c_le (a)))
-    return (n);
-  f__lioproc = l_read;
-  f__lquit = 0;
-  f__lcount = 0;
-  l_eof = 0;
-  if (f__curunit->uwrt && f__nowreading (f__curunit))
-    err (a->cierr, errno, "read start");
-  if (f__curunit->uend)
-    err (f__elist->ciend, (EOF), "read start");
-  l_getc = t_getc;
-  l_ungetc = un_getc;
-  f__doend = xrd_SL;
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/lwrite.c b/contrib/libf2c/libI77/lwrite.c
deleted file mode 100644
index b910ab19872..00000000000
--- a/contrib/libf2c/libI77/lwrite.c
+++ /dev/null
@@ -1,277 +0,0 @@
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-#include "lio.h"
-
-ftnint L_len;
-int f__Aquote;
-
-static void
-donewrec (void)
-{
-  if (f__recpos)
-    (*f__donewrec) ();
-}
-
-static void
-lwrt_I (longint n)
-{
-  char *p;
-  int ndigit, sign;
-
-  p = f__icvt (n, &ndigit, &sign, 10);
-  if (f__recpos + ndigit >= L_len)
-    donewrec ();
-  PUT (' ');
-  if (sign)
-    PUT ('-');
-  while (*p)
-    PUT (*p++);
-}
-static void
-lwrt_L (ftnint n, ftnlen len)
-{
-  if (f__recpos + LLOGW >= L_len)
-    donewrec ();
-  wrt_L ((Uint *) & n, LLOGW, len);
-}
-static void
-lwrt_A (char *p, ftnlen len)
-{
-  int a;
-  char *p1, *pe;
-
-  a = 0;
-  pe = p + len;
-  if (f__Aquote)
-    {
-      a = 3;
-      if (len > 1 && p[len - 1] == ' ')
-	{
-	  while (--len > 1 && p[len - 1] == ' ');
-	  pe = p + len;
-	}
-      p1 = p;
-      while (p1 < pe)
-	if (*p1++ == '\'')
-	  a++;
-    }
-  if (f__recpos + len + a >= L_len)
-    donewrec ();
-  if (a
-#ifndef OMIT_BLANK_CC
-      || !f__recpos
-#endif
-    )
-    PUT (' ');
-  if (a)
-    {
-      PUT ('\'');
-      while (p < pe)
-	{
-	  if (*p == '\'')
-	    PUT ('\'');
-	  PUT (*p++);
-	}
-      PUT ('\'');
-    }
-  else
-    while (p < pe)
-      PUT (*p++);
-}
-
-static int
-l_g (char *buf, double n)
-{
-#ifdef Old_list_output
-  doublereal absn;
-  char *fmt;
-
-  absn = n;
-  if (absn < 0)
-    absn = -absn;
-  fmt = LLOW <= absn && absn < LHIGH ? LFFMT : LEFMT;
-#ifdef USE_STRLEN
-  sprintf (buf, fmt, n);
-  return strlen (buf);
-#else
-  return sprintf (buf, fmt, n);
-#endif
-
-#else
-  register char *b, c, c1;
-
-  b = buf;
-  *b++ = ' ';
-  if (n < 0)
-    {
-      *b++ = '-';
-      n = -n;
-    }
-  else
-    *b++ = ' ';
-  if (n == 0)
-    {
-      *b++ = '0';
-      *b++ = '.';
-      *b = 0;
-      goto f__ret;
-    }
-  sprintf (b, LGFMT, n);
-  switch (*b)
-    {
-#ifndef WANT_LEAD_0
-    case '0':
-      while (b[0] = b[1])
-	b++;
-      break;
-#endif
-    case 'i':
-    case 'I':
-      /* Infinity */
-    case 'n':
-    case 'N':
-      /* NaN */
-      while (*++b);
-      break;
-
-    default:
-      /* Fortran 77 insists on having a decimal point... */
-      for (;; b++)
-	switch (*b)
-	  {
-	  case 0:
-	    *b++ = '.';
-	    *b = 0;
-	    goto f__ret;
-	  case '.':
-	    while (*++b);
-	    goto f__ret;
-	  case 'E':
-	    for (c1 = '.', c = 'E'; (*b = c1); c1 = c, c = *++b);
-	    goto f__ret;
-	  }
-    }
-f__ret:
-  return b - buf;
-#endif
-}
-
-static void
-l_put (register char *s)
-{
-  register void (*pn) (int) = f__putn;
-  register int c;
-
-  while ((c = *s++))
-    (*pn) (c);
-}
-
-static void
-lwrt_F (double n)
-{
-  char buf[LEFBL];
-
-  if (f__recpos + l_g (buf, n) >= L_len)
-    donewrec ();
-  l_put (buf);
-}
-static void
-lwrt_C (double a, double b)
-{
-  char *ba, *bb, bufa[LEFBL], bufb[LEFBL];
-  int al, bl;
-
-  al = l_g (bufa, a);
-  for (ba = bufa; *ba == ' '; ba++)
-    --al;
-  bl = l_g (bufb, b) + 1;	/* intentionally high by 1 */
-  for (bb = bufb; *bb == ' '; bb++)
-    --bl;
-  if (f__recpos + al + bl + 3 >= L_len)
-    donewrec ();
-#ifdef OMIT_BLANK_CC
-  else
-#endif
-    PUT (' ');
-  PUT ('(');
-  l_put (ba);
-  PUT (',');
-  if (f__recpos + bl >= L_len)
-    {
-      (*f__donewrec) ();
-#ifndef OMIT_BLANK_CC
-      PUT (' ');
-#endif
-    }
-  l_put (bb);
-  PUT (')');
-}
-
-int
-l_write (ftnint * number, char *ptr, ftnlen len, ftnint type)
-{
-#define Ptr ((flex *)ptr)
-  int i;
-  longint x;
-  double y, z;
-  real *xx;
-  doublereal *yy;
-  for (i = 0; i < *number; i++)
-    {
-      switch ((int) type)
-	{
-	default:
-	  f__fatal (204, "unknown type in lio");
-	case TYINT1:
-	  x = Ptr->flchar;
-	  goto xint;
-	case TYSHORT:
-	  x = Ptr->flshort;
-	  goto xint;
-#ifdef Allow_TYQUAD
-	case TYQUAD:
-	  x = Ptr->fllongint;
-	  goto xint;
-#endif
-	case TYLONG:
-	  x = Ptr->flint;
-	xint:lwrt_I (x);
-	  break;
-	case TYREAL:
-	  y = Ptr->flreal;
-	  goto xfloat;
-	case TYDREAL:
-	  y = Ptr->fldouble;
-	xfloat:lwrt_F (y);
-	  break;
-	case TYCOMPLEX:
-	  xx = &Ptr->flreal;
-	  y = *xx++;
-	  z = *xx;
-	  goto xcomplex;
-	case TYDCOMPLEX:
-	  yy = &Ptr->fldouble;
-	  y = *yy++;
-	  z = *yy;
-	xcomplex:
-	  lwrt_C (y, z);
-	  break;
-	case TYLOGICAL1:
-	  x = Ptr->flchar;
-	  goto xlog;
-	case TYLOGICAL2:
-	  x = Ptr->flshort;
-	  goto xlog;
-	case TYLOGICAL:
-	  x = Ptr->flint;
-	xlog:lwrt_L (Ptr->flint, len);
-	  break;
-	case TYCHAR:
-	  lwrt_A (ptr, len);
-	  break;
-	}
-      ptr += len;
-    }
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/makefile.netlib b/contrib/libf2c/libI77/makefile.netlib
deleted file mode 100644
index edba1fe8569..00000000000
--- a/contrib/libf2c/libI77/makefile.netlib
+++ /dev/null
@@ -1,104 +0,0 @@
-.SUFFIXES: .c .o
-CC = cc
-CFLAGS = -O
-SHELL = /bin/sh
-
-# compile, then strip unnecessary symbols
-.c.o:
-	$(CC) -c -DSkip_f2c_Undefs $(CFLAGS) $*.c
-	ld -r -x -o $*.xxx $*.o
-	mv $*.xxx $*.o
-## Under Solaris (and other systems that do not understand ld -x),
-## omit -x in the ld line above.
-## If your system does not have the ld command, comment out
-## or remove both the ld and mv lines above.
-
-OBJ =	Version.o backspace.o close.o dfe.o dolio.o due.o endfile.o err.o \
-	fmt.o fmtlib.o ftell_.o iio.o ilnw.o inquire.o lread.o lwrite.o \
-	open.o rdfmt.o rewind.o rsfe.o rsli.o rsne.o sfe.o sue.o typesize.o \
-	uio.o util.o wref.o wrtfmt.o wsfe.o wsle.o wsne.o xwsne.o
-libI77.a:	$(OBJ)
-		ar r libI77.a $?
-		-ranlib libI77.a
-
-### If your system lacks ranlib, you don't need it; see README.
-
-install:	libI77.a
-	cp libI77.a /usr/lib/libI77.a
-	ranlib /usr/lib/libI77.a
-
-Version.o: Version.c
-	$(CC) -c Version.c
-
-# To compile with C++, first "make f2c.h"
-f2c.h: f2ch.add
-	cat /usr/include/f2c.h f2ch.add >f2c.h
-
-
-clean:
-	rm -f $(OBJ) libI77.a
-
-clobber:	clean
-	rm -f libI77.a
-
-backspace.o:	fio.h
-close.o:	fio.h
-dfe.o:		fio.h
-dfe.o:		fmt.h
-due.o:		fio.h
-endfile.o:	fio.h rawio.h
-err.o:		fio.h rawio.h
-fmt.o:		fio.h
-fmt.o:		fmt.h
-ftell_.o:	fio.h
-iio.o:		fio.h
-iio.o:		fmt.h
-ilnw.o:		fio.h
-ilnw.o:		lio.h
-inquire.o:	fio.h
-lread.o:	fio.h
-lread.o:	fmt.h
-lread.o:	lio.h
-lread.o:	fp.h
-lwrite.o:	fio.h
-lwrite.o:	fmt.h
-lwrite.o:	lio.h
-open.o:		fio.h rawio.h
-rdfmt.o:	fio.h
-rdfmt.o:	fmt.h
-rdfmt.o:	fp.h
-rewind.o:	fio.h
-rsfe.o:		fio.h
-rsfe.o:		fmt.h
-rsli.o:		fio.h
-rsli.o:		lio.h
-rsne.o:		fio.h
-rsne.o:		lio.h
-sfe.o:		fio.h
-sue.o:		fio.h
-uio.o:		fio.h
-util.o:		fio.h
-wref.o:		fio.h
-wref.o:		fmt.h
-wref.o:		fp.h
-wrtfmt.o:	fio.h
-wrtfmt.o:	fmt.h
-wsfe.o:		fio.h
-wsfe.o:		fmt.h
-wsle.o:		fio.h
-wsle.o:		fmt.h
-wsle.o:		lio.h
-wsne.o:		fio.h
-wsne.o:		lio.h
-xwsne.o:	fio.h
-xwsne.o:	lio.h
-xwsne.o:	fmt.h
-
-check:
-	xsum Notice README Version.c backspace.c close.c dfe.c dolio.c \
-	due.c endfile.c err.c f2ch.add fio.h fmt.c fmt.h fmtlib.c fp.h \
-	ftell_.c iio.c ilnw.c inquire.c lio.h lread.c lwrite.c makefile \
-	open.c rawio.h rdfmt.c rewind.c rsfe.c rsli.c rsne.c sfe.c sue.c \
-	typesize.c uio.c util.c wref.c wrtfmt.c wsfe.c wsle.c wsne.c \
-	xwsne.c >zap
-	cmp zap libI77.xsum && rm zap || diff libI77.xsum zap
diff --git a/contrib/libf2c/libI77/open.c b/contrib/libf2c/libI77/open.c
deleted file mode 100644
index ac1e00ec6de..00000000000
--- a/contrib/libf2c/libI77/open.c
+++ /dev/null
@@ -1,301 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include 
-#ifndef NON_POSIX_STDIO
-#ifdef MSDOS
-#include "io.h"
-#else
-#include "unistd.h"		/* for access */
-#endif
-#endif
-
-#undef abs
-#undef min
-#undef max
-#include 
-extern int f__canseek (FILE *);
-extern integer f_clos (cllist *);
-
-#ifdef NON_ANSI_RW_MODES
-char *f__r_mode[2] = { "r", "r" };
-char *f__w_mode[4] = { "w", "w", "r+w", "r+w" };
-#else
-char *f__r_mode[2] = { "rb", "r" };
-char *f__w_mode[4] = { "wb", "w", "r+b", "r+" };
-#endif
-
-static char f__buf0[400], *f__buf = f__buf0;
-int f__buflen = (int) sizeof (f__buf0);
-
-static void
-f__bufadj (int n, int c)
-{
-  unsigned int len;
-  char *nbuf, *s, *t, *te;
-
-  if (f__buf == f__buf0)
-    f__buflen = 1024;
-  while (f__buflen <= n)
-    f__buflen <<= 1;
-  len = (unsigned int) f__buflen;
-  if (len != f__buflen || !(nbuf = (char *) malloc (len)))
-    f__fatal (113, "malloc failure");
-  s = nbuf;
-  t = f__buf;
-  te = t + c;
-  while (t < te)
-    *s++ = *t++;
-  if (f__buf != f__buf0)
-    free (f__buf);
-  f__buf = nbuf;
-}
-
-int
-f__putbuf (int c)
-{
-  char *s, *se;
-  int n;
-
-  if (f__hiwater > f__recpos)
-    f__recpos = f__hiwater;
-  n = f__recpos + 1;
-  if (n >= f__buflen)
-    f__bufadj (n, f__recpos);
-  s = f__buf;
-  se = s + f__recpos;
-  if (c)
-    *se++ = c;
-  *se = 0;
-  for (;;)
-    {
-      fputs (s, f__cf);
-      s += strlen (s);
-      if (s >= se)
-	break;			/* normally happens the first time */
-      putc (*s++, f__cf);
-    }
-  return 0;
-}
-
-void
-x_putc (int c)
-{
-  if (f__recpos >= f__buflen)
-    f__bufadj (f__recpos, f__buflen);
-  f__buf[f__recpos++] = c;
-}
-
-#define opnerr(f,m,s) \
-  do {if(f) {f__init &= ~2; errno= m;} else opn_err(m,s,a); return(m);} while(0)
-
-static void
-opn_err (int m, char *s, olist * a)
-{
-  if (a->ofnm)
-    {
-      /* supply file name to error message */
-      if (a->ofnmlen >= f__buflen)
-	f__bufadj ((int) a->ofnmlen, 0);
-      g_char (a->ofnm, a->ofnmlen, f__curunit->ufnm = f__buf);
-    }
-  f__fatal (m, s);
-}
-
-integer
-f_open (olist * a)
-{
-  unit *b;
-  integer rv;
-  char buf[256], *s, *env;
-  cllist x;
-  int ufmt;
-  FILE *tf;
-  int fd, len;
-#ifndef NON_UNIX_STDIO
-  int n;
-#endif
-  if (f__init != 1)
-    f_init ();
-  f__external = 1;
-  if (a->ounit >= MXUNIT || a->ounit < 0)
-    err (a->oerr, 101, "open");
-  f__curunit = b = &f__units[a->ounit];
-  if (b->ufd)
-    {
-      if (a->ofnm == 0)
-	{
-	same:if (a->oblnk)
-	    b->ublnk = *a->oblnk == 'z' || *a->oblnk == 'Z';
-	  return (0);
-	}
-#ifdef NON_UNIX_STDIO
-      if (b->ufnm
-	  && strlen (b->ufnm) == a->ofnmlen
-	  && !strncmp (b->ufnm, a->ofnm, (unsigned) a->ofnmlen))
-	goto same;
-#else
-      g_char (a->ofnm, a->ofnmlen, buf);
-      if (f__inode (buf, &n) == b->uinode && n == b->udev)
-	goto same;
-#endif
-      x.cunit = a->ounit;
-      x.csta = 0;
-      x.cerr = a->oerr;
-      if ((rv = f_clos (&x)) != 0)
-	return rv;
-    }
-  b->url = (int) a->orl;
-  b->ublnk = a->oblnk && (*a->oblnk == 'z' || *a->oblnk == 'Z');
-  if (a->ofm == 0)
-    if ((a->oacc) && (*a->oacc == 'D' || *a->oacc == 'd'))
-      b->ufmt = 0;
-    else
-      b->ufmt = 1;
-  else if (*a->ofm == 'f' || *a->ofm == 'F')
-    b->ufmt = 1;
-  else
-    b->ufmt = 0;
-  ufmt = b->ufmt;
-#ifdef url_Adjust
-  if (b->url && !ufmt)
-    url_Adjust (b->url);
-#endif
-  if (a->ofnm)
-    {
-      g_char (a->ofnm, a->ofnmlen, buf);
-      if (!buf[0])
-	opnerr (a->oerr, 107, "open");
-    }
-  else
-    sprintf (buf, "fort.%ld", (long) a->ounit);
-  b->uscrtch = 0;
-  b->uend = 0;
-  b->uwrt = 0;
-  b->ufd = 0;
-  b->urw = 3;
-  switch (a->osta ? *a->osta : 'u')
-    {
-    case 'o':
-    case 'O':
-#ifdef NON_POSIX_STDIO
-      if (!(tf = fopen (buf, "r")))
-	opnerr (a->oerr, errno, "open");
-      fclose (tf);
-#else
-      if (access (buf, 0))
-	opnerr (a->oerr, errno, "open");
-#endif
-      break;
-    case 's':
-    case 'S':
-      b->uscrtch = 1;
-#ifdef HAVE_MKSTEMP		/* Allow use of TMPDIR preferentially. */
-      env = getenv ("TMPDIR");
-      if (!env)
-	env = getenv ("TEMP");
-      if (!env)
-	env = "/tmp";
-      len = strlen (env);
-      if (len > 256 - (int) sizeof ("/tmp.FXXXXXX"))
-	err (a->oerr, 132, "open");
-      strcpy (buf, env);
-      strcat (buf, "/tmp.FXXXXXX");
-      fd = mkstemp (buf);
-      if (fd == -1 || close (fd))
-	err (a->oerr, 132, "open");
-#else /* ! defined (HAVE_MKSTEMP) */
-#ifdef HAVE_TEMPNAM		/* Allow use of TMPDIR preferentially. */
-      s = tempnam (0, buf);
-      if (strlen (s) >= sizeof (buf))
-	err (a->oerr, 132, "open");
-      (void) strcpy (buf, s);
-      free (s);
-#else /* ! defined (HAVE_TEMPNAM) */
-#ifdef HAVE_TMPNAM
-      tmpnam (buf);
-#else
-      (void) strcpy (buf, "tmp.FXXXXXX");
-      (void) mktemp (buf);
-#endif
-#endif /* ! defined (HAVE_TEMPNAM) */
-#endif /* ! defined (HAVE_MKSTEMP) */
-      goto replace;
-    case 'n':
-    case 'N':
-#ifdef NON_POSIX_STDIO
-      if ((tf = fopen (buf, "r")) || (tf = fopen (buf, "a")))
-	{
-	  fclose (tf);
-	  opnerr (a->oerr, 128, "open");
-	}
-#else
-      if (!access (buf, 0))
-	opnerr (a->oerr, 128, "open");
-#endif
-      /* no break */
-    case 'r':			/* Fortran 90 replace option */
-    case 'R':
-    replace:
-      if ((tf = fopen (buf, f__w_mode[0])))
-	fclose (tf);
-    }
-
-  b->ufnm = (char *) malloc ((unsigned int) (strlen (buf) + 1));
-  if (b->ufnm == NULL)
-    opnerr (a->oerr, 113, "no space");
-  (void) strcpy (b->ufnm, buf);
-  if ((s = a->oacc) && b->url)
-    ufmt = 0;
-  if (!(tf = fopen (buf, f__w_mode[ufmt | 2])))
-    {
-      if ((tf = fopen (buf, f__r_mode[ufmt])))
-	b->urw = 1;
-      else if ((tf = fopen (buf, f__w_mode[ufmt])))
-	{
-	  b->uwrt = 1;
-	  b->urw = 2;
-	}
-      else
-	err (a->oerr, errno, "open");
-    }
-  b->useek = f__canseek (b->ufd = tf);
-#ifndef NON_UNIX_STDIO
-  if ((b->uinode = f__inode (buf, &b->udev)) == -1)
-    opnerr (a->oerr, 108, "open");
-#endif
-  if (b->useek)
-    {
-      if (a->orl)
-	FSEEK (b->ufd, 0, SEEK_SET);
-      else if ((s = a->oacc) && (*s == 'a' || *s == 'A')
-	       && FSEEK (b->ufd, 0, SEEK_END))
-	opnerr (a->oerr, 129, "open");
-    }
-  return (0);
-}
-
-int
-fk_open (int seq, int fmt, ftnint n)
-{
-  char nbuf[10];
-  olist a;
-  int rtn;
-  int save_init;
-
-  (void) sprintf (nbuf, "fort.%ld", (long) n);
-  a.oerr = 1;
-  a.ounit = n;
-  a.ofnm = nbuf;
-  a.ofnmlen = strlen (nbuf);
-  a.osta = NULL;
-  a.oacc = seq == SEQ ? "s" : "d";
-  a.ofm = fmt == FMT ? "f" : "u";
-  a.orl = seq == DIR ? 1 : 0;
-  a.oblnk = NULL;
-  save_init = f__init;
-  f__init &= ~2;
-  rtn = f_open (&a);
-  f__init = save_init | 1;
-  return rtn;
-}
diff --git a/contrib/libf2c/libI77/rdfmt.c b/contrib/libf2c/libI77/rdfmt.c
deleted file mode 100644
index 8a8818aefb9..00000000000
--- a/contrib/libf2c/libI77/rdfmt.c
+++ /dev/null
@@ -1,615 +0,0 @@
-#include "config.h"
-#include 
-#include "f2c.h"
-#include "fio.h"
-
-extern int f__cursor;
-#undef abs
-#undef min
-#undef max
-#include 
-
-#include "fmt.h"
-#include "fp.h"
-
-static int
-rd_Z (Uint * n, int w, ftnlen len)
-{
-  long x[9];
-  char *s, *s0, *s1, *se, *t;
-  int ch, i, w1, w2;
-  static char hex[256];
-  static int one = 1;
-  int bad = 0;
-
-  if (!hex['0'])
-    {
-      s = "0123456789";
-      while ((ch = *s++))
-	hex[ch] = ch - '0' + 1;
-      s = "ABCDEF";
-      while ((ch = *s++))
-	hex[ch] = hex[ch + 'a' - 'A'] = ch - 'A' + 11;
-    }
-  s = s0 = (char *) x;
-  s1 = (char *) &x[4];
-  se = (char *) &x[8];
-  if (len > 4 * (ftnlen) sizeof (long))
-    return errno = 117;
-  while (w)
-    {
-      GET (ch);
-      if (ch == ',' || ch == '\n')
-	break;
-      w--;
-      if (ch > ' ')
-	{
-	  if (!hex[ch & 0xff])
-	    bad++;
-	  *s++ = ch;
-	  if (s == se)
-	    {
-	      /* discard excess characters */
-	      for (t = s0, s = s1; t < s1;)
-		*t++ = *s++;
-	      s = s1;
-	    }
-	}
-    }
-  if (bad)
-    return errno = 115;
-  w = (int) len;
-  w1 = s - s0;
-  w2 = (w1 + 1) >> 1;
-  t = (char *) n;
-  if (*(char *) &one)
-    {
-      /* little endian */
-      t += w - 1;
-      i = -1;
-    }
-  else
-    i = 1;
-  for (; w > w2; t += i, --w)
-    *t = 0;
-  if (!w)
-    return 0;
-  if (w < w2)
-    s0 = s - (w << 1);
-  else if (w1 & 1)
-    {
-      *t = hex[*s0++ & 0xff] - 1;
-      if (!--w)
-	return 0;
-      t += i;
-    }
-  do
-    {
-      *t = (hex[*s0 & 0xff] - 1) << 4 | (hex[s0[1] & 0xff] - 1);
-      t += i;
-      s0 += 2;
-    }
-  while (--w);
-  return 0;
-}
-
-static int
-rd_I (Uint * n, int w, ftnlen len, register int base)
-{
-  int ch, sign;
-  longint x = 0;
-
-  if (w <= 0)
-    goto have_x;
-  for (;;)
-    {
-      GET (ch);
-      if (ch != ' ')
-	break;
-      if (!--w)
-	goto have_x;
-    }
-  sign = 0;
-  switch (ch)
-    {
-    case ',':
-    case '\n':
-      w = 0;
-      goto have_x;
-    case '-':
-      sign = 1;
-    case '+':
-      break;
-    default:
-      if (ch >= '0' && ch <= '9')
-	{
-	  x = ch - '0';
-	  break;
-	}
-      goto have_x;
-    }
-  while (--w)
-    {
-      GET (ch);
-      if (ch >= '0' && ch <= '9')
-	{
-	  x = x * base + ch - '0';
-	  continue;
-	}
-      if (ch != ' ')
-	{
-	  if (ch == '\n' || ch == ',')
-	    w = 0;
-	  break;
-	}
-      if (f__cblank)
-	x *= base;
-    }
-  if (sign)
-    x = -x;
-have_x:
-  if (len == sizeof (integer))
-    n->il = x;
-  else if (len == sizeof (char))
-    n->ic = (char) x;
-#ifdef Allow_TYQUAD
-  else if (len == sizeof (longint))
-    n->ili = x;
-#endif
-  else
-    n->is = (short) x;
-  if (w)
-    {
-      while (--w)
-	GET (ch);
-      return errno = 115;
-    }
-  return 0;
-}
-
-static int
-rd_L (ftnint * n, int w, ftnlen len)
-{
-  int ch, dot, lv;
-
-  if (w <= 0)
-    goto bad;
-  for (;;)
-    {
-      GET (ch);
-      --w;
-      if (ch != ' ')
-	break;
-      if (!w)
-	goto bad;
-    }
-  dot = 0;
-retry:
-  switch (ch)
-    {
-    case '.':
-      if (dot++ || !w)
-	goto bad;
-      GET (ch);
-      --w;
-      goto retry;
-    case 't':
-    case 'T':
-      lv = 1;
-      break;
-    case 'f':
-    case 'F':
-      lv = 0;
-      break;
-    default:
-    bad:
-      for (; w > 0; --w)
-	GET (ch);
-      /* no break */
-    case ',':
-    case '\n':
-      return errno = 116;
-    }
-  /* The switch statement that was here
-     didn't cut it:  It broke down for targets
-     where sizeof(char) == sizeof(short). */
-  if (len == sizeof (char))
-    *(char *) n = (char) lv;
-  else if (len == sizeof (short))
-    *(short *) n = (short) lv;
-  else
-    *n = lv;
-  while (w-- > 0)
-    {
-      GET (ch);
-      if (ch == ',' || ch == '\n')
-	break;
-    }
-  return 0;
-}
-
-static int
-rd_F (ufloat * p, int w, int d, ftnlen len)
-{
-  char s[FMAX + EXPMAXDIGS + 4];
-  register int ch;
-  register char *sp, *spe, *sp1;
-  double x;
-  int scale1, se;
-  long e, exp;
-
-  sp1 = sp = s;
-  spe = sp + FMAX;
-  exp = -d;
-  x = 0.;
-
-  do
-    {
-      GET (ch);
-      w--;
-    }
-  while (ch == ' ' && w);
-  switch (ch)
-    {
-    case '-':
-      *sp++ = ch;
-      sp1++;
-      spe++;
-    case '+':
-      if (!w)
-	goto zero;
-      --w;
-      GET (ch);
-    }
-  while (ch == ' ')
-    {
-    blankdrop:
-      if (!w--)
-	goto zero;
-      GET (ch);
-    }
-  while (ch == '0')
-    {
-      if (!w--)
-	goto zero;
-      GET (ch);
-    }
-  if (ch == ' ' && f__cblank)
-    goto blankdrop;
-  scale1 = f__scale;
-  while (isdigit (ch))
-    {
-    digloop1:
-      if (sp < spe)
-	*sp++ = ch;
-      else
-	++exp;
-    digloop1e:
-      if (!w--)
-	goto done;
-      GET (ch);
-    }
-  if (ch == ' ')
-    {
-      if (f__cblank)
-	{
-	  ch = '0';
-	  goto digloop1;
-	}
-      goto digloop1e;
-    }
-  if (ch == '.')
-    {
-      exp += d;
-      if (!w--)
-	goto done;
-      GET (ch);
-      if (sp == sp1)
-	{			/* no digits yet */
-	  while (ch == '0')
-	    {
-	    skip01:
-	      --exp;
-	    skip0:
-	      if (!w--)
-		goto done;
-	      GET (ch);
-	    }
-	  if (ch == ' ')
-	    {
-	      if (f__cblank)
-		goto skip01;
-	      goto skip0;
-	    }
-	}
-      while (isdigit (ch))
-	{
-	digloop2:
-	  if (sp < spe)
-	    {
-	      *sp++ = ch;
-	      --exp;
-	    }
-	digloop2e:
-	  if (!w--)
-	    goto done;
-	  GET (ch);
-	}
-      if (ch == ' ')
-	{
-	  if (f__cblank)
-	    {
-	      ch = '0';
-	      goto digloop2;
-	    }
-	  goto digloop2e;
-	}
-    }
-  switch (ch)
-    {
-    default:
-      break;
-    case '-':
-      se = 1;
-      goto signonly;
-    case '+':
-      se = 0;
-      goto signonly;
-    case 'e':
-    case 'E':
-    case 'd':
-    case 'D':
-      if (!w--)
-	goto bad;
-      GET (ch);
-      while (ch == ' ')
-	{
-	  if (!w--)
-	    goto bad;
-	  GET (ch);
-	}
-      se = 0;
-      switch (ch)
-	{
-	case '-':
-	  se = 1;
-	case '+':
-	signonly:
-	  if (!w--)
-	    goto bad;
-	  GET (ch);
-	}
-      while (ch == ' ')
-	{
-	  if (!w--)
-	    goto bad;
-	  GET (ch);
-	}
-      if (!isdigit (ch))
-	goto bad;
-
-      e = ch - '0';
-      for (;;)
-	{
-	  if (!w--)
-	    {
-	      ch = '\n';
-	      break;
-	    }
-	  GET (ch);
-	  if (!isdigit (ch))
-	    {
-	      if (ch == ' ')
-		{
-		  if (f__cblank)
-		    ch = '0';
-		  else
-		    continue;
-		}
-	      else
-		break;
-	    }
-	  e = 10 * e + ch - '0';
-	  if (e > EXPMAX && sp > sp1)
-	    goto bad;
-	}
-      if (se)
-	exp -= e;
-      else
-	exp += e;
-      scale1 = 0;
-    }
-  switch (ch)
-    {
-    case '\n':
-    case ',':
-      break;
-    default:
-    bad:
-      return (errno = 115);
-    }
-done:
-  if (sp > sp1)
-    {
-      while (*--sp == '0')
-	++exp;
-      if (exp -= scale1)
-	sprintf (sp + 1, "e%ld", exp);
-      else
-	sp[1] = 0;
-      x = atof (s);
-    }
-zero:
-  if (len == sizeof (real))
-    p->pf = x;
-  else
-    p->pd = x;
-  return (0);
-}
-
-
-static int
-rd_A (char *p, ftnlen len)
-{
-  int i, ch;
-  for (i = 0; i < len; i++)
-    {
-      GET (ch);
-      *p++ = VAL (ch);
-    }
-  return (0);
-}
-static int
-rd_AW (char *p, int w, ftnlen len)
-{
-  int i, ch;
-  if (w >= len)
-    {
-      for (i = 0; i < w - len; i++)
-	GET (ch);
-      for (i = 0; i < len; i++)
-	{
-	  GET (ch);
-	  *p++ = VAL (ch);
-	}
-      return (0);
-    }
-  for (i = 0; i < w; i++)
-    {
-      GET (ch);
-      *p++ = VAL (ch);
-    }
-  for (i = 0; i < len - w; i++)
-    *p++ = ' ';
-  return (0);
-}
-static int
-rd_H (int n, char *s)
-{
-  int i, ch;
-  for (i = 0; i < n; i++)
-    if ((ch = (*f__getn) ()) < 0)
-      return (ch);
-    else
-      *s++ = ch == '\n' ? ' ' : ch;
-  return (1);
-}
-static int
-rd_POS (char *s)
-{
-  char quote;
-  int ch;
-  quote = *s++;
-  for (; *s; s++)
-    if (*s == quote && *(s + 1) != quote)
-      break;
-    else if ((ch = (*f__getn) ()) < 0)
-      return (ch);
-    else
-      *s = ch == '\n' ? ' ' : ch;
-  return (1);
-}
-
-int
-rd_ed (struct syl * p, char *ptr, ftnlen len)
-{
-  int ch;
-  for (; f__cursor > 0; f__cursor--)
-    if ((ch = (*f__getn) ()) < 0)
-      return (ch);
-  if (f__cursor < 0)
-    {
-      if (f__recpos + f__cursor < 0)	/*err(elist->cierr,110,"fmt") */
-	f__cursor = -f__recpos;	/* is this in the standard? */
-      if (f__external == 0)
-	{
-	  extern char *f__icptr;
-	  f__icptr += f__cursor;
-	}
-      else if (f__curunit && f__curunit->useek)
-	FSEEK (f__cf, (off_t) f__cursor, SEEK_CUR);
-      else
-	err (f__elist->cierr, 106, "fmt");
-      f__recpos += f__cursor;
-      f__cursor = 0;
-    }
-  switch (p->op)
-    {
-    default:
-      fprintf (stderr, "rd_ed, unexpected code: %d\n", p->op);
-      sig_die (f__fmtbuf, 1);
-    case IM:
-    case I:
-      ch = rd_I ((Uint *) ptr, p->p1, len, 10);
-      break;
-
-      /* O and OM don't work right for character, double, complex, */
-      /* or doublecomplex, and they differ from Fortran 90 in */
-      /* showing a minus sign for negative values. */
-
-    case OM:
-    case O:
-      ch = rd_I ((Uint *) ptr, p->p1, len, 8);
-      break;
-    case L:
-      ch = rd_L ((ftnint *) ptr, p->p1, len);
-      break;
-    case A:
-      ch = rd_A (ptr, len);
-      break;
-    case AW:
-      ch = rd_AW (ptr, p->p1, len);
-      break;
-    case E:
-    case EE:
-    case D:
-    case G:
-    case GE:
-    case F:
-      ch = rd_F ((ufloat *) ptr, p->p1, p->p2.i[0], len);
-      break;
-
-      /* Z and ZM assume 8-bit bytes. */
-
-    case ZM:
-    case Z:
-      ch = rd_Z ((Uint *) ptr, p->p1, len);
-      break;
-    }
-  if (ch == 0)
-    return (ch);
-  else if (ch == EOF)
-    return (EOF);
-  if (f__cf)
-    clearerr (f__cf);
-  return (errno);
-}
-
-int
-rd_ned (struct syl * p)
-{
-  switch (p->op)
-    {
-    default:
-      fprintf (stderr, "rd_ned, unexpected code: %d\n", p->op);
-      sig_die (f__fmtbuf, 1);
-    case APOS:
-      return (rd_POS (p->p2.s));
-    case H:
-      return (rd_H (p->p1, p->p2.s));
-    case SLASH:
-      return ((*f__donewrec) ());
-    case TR:
-    case X:
-      f__cursor += p->p1;
-      return (1);
-    case T:
-      f__cursor = p->p1 - f__recpos - 1;
-      return (1);
-    case TL:
-      f__cursor -= p->p1;
-      if (f__cursor < -f__recpos)	/* TL1000, 1X */
-	f__cursor = -f__recpos;
-      return (1);
-    }
-}
diff --git a/contrib/libf2c/libI77/rewind.c b/contrib/libf2c/libI77/rewind.c
deleted file mode 100644
index d7a9b766192..00000000000
--- a/contrib/libf2c/libI77/rewind.c
+++ /dev/null
@@ -1,25 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-integer
-f_rew (alist * a)
-{
-  unit *b;
-  if (f__init & 2)
-    f__fatal (131, "I/O recursion");
-  if (a->aunit >= MXUNIT || a->aunit < 0)
-    err (a->aerr, 101, "rewind");
-  b = &f__units[a->aunit];
-  if (b->ufd == NULL || b->uwrt == 3)
-    return (0);
-  if (!b->useek)
-    err (a->aerr, 106, "rewind");
-  if (b->uwrt)
-    {
-      (void) t_runc (a);
-      b->uwrt = 3;
-    }
-  FSEEK (b->ufd, 0, SEEK_SET);
-  b->uend = 0;
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/rsfe.c b/contrib/libf2c/libI77/rsfe.c
deleted file mode 100644
index 0dcda392ce0..00000000000
--- a/contrib/libf2c/libI77/rsfe.c
+++ /dev/null
@@ -1,97 +0,0 @@
-/* read sequential formatted external */
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-
-int
-xrd_SL (void)
-{
-  int ch;
-  if (!f__curunit->uend)
-    while ((ch = getc (f__cf)) != '\n')
-      if (ch == EOF)
-	{
-	  f__curunit->uend = 1;
-	  break;
-	}
-  f__cursor = f__recpos = 0;
-  return (1);
-}
-
-int
-x_getc (void)
-{
-  int ch;
-  if (f__curunit->uend)
-    return (EOF);
-  ch = getc (f__cf);
-  if (ch != EOF && ch != '\n')
-    {
-      f__recpos++;
-      return (ch);
-    }
-  if (ch == '\n')
-    {
-      (void) ungetc (ch, f__cf);
-      return (ch);
-    }
-  if (f__curunit->uend || feof (f__cf))
-    {
-      errno = 0;
-      f__curunit->uend = 1;
-      return (-1);
-    }
-  return (-1);
-}
-
-int
-x_endp (void)
-{
-  xrd_SL ();
-  return f__curunit->uend == 1 ? EOF : 0;
-}
-
-int
-x_rev (void)
-{
-  (void) xrd_SL ();
-  return (0);
-}
-
-integer
-s_rsfe (cilist * a)		/* start */
-{
-  int n;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__reading = 1;
-  f__sequential = 1;
-  f__formatted = 1;
-  f__external = 1;
-  if ((n = c_sfe (a)))
-    return (n);
-  f__elist = a;
-  f__cursor = f__recpos = 0;
-  f__scale = 0;
-  f__fmtbuf = a->cifmt;
-  f__curunit = &f__units[a->ciunit];
-  f__cf = f__curunit->ufd;
-  if (pars_f (f__fmtbuf) < 0)
-    err (a->cierr, 100, "startio");
-  f__getn = x_getc;
-  f__doed = rd_ed;
-  f__doned = rd_ned;
-  fmt_bg ();
-  f__doend = x_endp;
-  f__donewrec = xrd_SL;
-  f__dorevert = x_rev;
-  f__cblank = f__curunit->ublnk;
-  f__cplus = 0;
-  if (f__curunit->uwrt && f__nowreading (f__curunit))
-    err (a->cierr, errno, "read start");
-  if (f__curunit->uend)
-    err (f__elist->ciend, (EOF), "read start");
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/rsli.c b/contrib/libf2c/libI77/rsli.c
deleted file mode 100644
index c07632a0fca..00000000000
--- a/contrib/libf2c/libI77/rsli.c
+++ /dev/null
@@ -1,99 +0,0 @@
-#include "f2c.h"
-#include "fio.h"
-#include "lio.h"
-#include "fmt.h"		/* for f__doend */
-
-extern flag f__lquit;
-extern int f__lcount;
-extern char *f__icptr;
-extern char *f__icend;
-extern icilist *f__svic;
-extern int f__icnum, f__recpos;
-
-static int
-i_getc (void)
-{
-  if (f__recpos >= f__svic->icirlen)
-    {
-      if (f__recpos++ == f__svic->icirlen)
-	return '\n';
-      z_rnew ();
-    }
-  f__recpos++;
-  if (f__icptr >= f__icend)
-    return EOF;
-  return (*f__icptr++);
-}
-
-static int
-i_ungetc (int ch __attribute__ ((__unused__)),
-	  FILE * f __attribute__ ((__unused__)))
-{
-  if (--f__recpos == f__svic->icirlen)
-    return '\n';
-  if (f__recpos < -1)
-    err (f__svic->icierr, 110, "recend");
-  /* *--icptr == ch, and icptr may point to read-only memory */
-  return *--f__icptr /* = ch */ ;
-}
-
-static void
-c_lir (icilist * a)
-{
-  extern int l_eof;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__reading = 1;
-  f__external = 0;
-  f__formatted = 1;
-  f__svic = a;
-  L_len = a->icirlen;
-  f__recpos = -1;
-  f__icnum = f__recpos = 0;
-  f__cursor = 0;
-  l_getc = i_getc;
-  l_ungetc = i_ungetc;
-  l_eof = 0;
-  f__icptr = a->iciunit;
-  f__icend = f__icptr + a->icirlen * a->icirnum;
-  f__cf = 0;
-  f__curunit = 0;
-  f__elist = (cilist *) a;
-}
-
-
-integer
-s_rsli (icilist * a)
-{
-  f__lioproc = l_read;
-  f__lquit = 0;
-  f__lcount = 0;
-  c_lir (a);
-  f__doend = 0;
-  return (0);
-}
-
-integer
-e_rsli (void)
-{
-  f__init = 1;
-  return 0;
-}
-
-extern int x_rsne (cilist *);
-
-integer
-s_rsni (icilist * a)
-{
-  extern int nml_read;
-  integer rv;
-  cilist ca;
-  ca.ciend = a->iciend;
-  ca.cierr = a->icierr;
-  ca.cifmt = a->icifmt;
-  c_lir (a);
-  rv = x_rsne (&ca);
-  nml_read = 0;
-  return rv;
-}
diff --git a/contrib/libf2c/libI77/rsne.c b/contrib/libf2c/libI77/rsne.c
deleted file mode 100644
index 0975e000c70..00000000000
--- a/contrib/libf2c/libI77/rsne.c
+++ /dev/null
@@ -1,604 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "lio.h"
-
-#define MAX_NL_CACHE 3		/* maximum number of namelist hash tables to cache */
-#define MAXDIM 20		/* maximum number of subscripts */
-
-struct dimen
-{
-  ftnlen extent;
-  ftnlen curval;
-  ftnlen delta;
-  ftnlen stride;
-};
-typedef struct dimen dimen;
-
-struct hashentry
-{
-  struct hashentry *next;
-  char *name;
-  Vardesc *vd;
-};
-typedef struct hashentry hashentry;
-
-struct hashtab
-{
-  struct hashtab *next;
-  Namelist *nl;
-  int htsize;
-  hashentry *tab[1];
-};
-typedef struct hashtab hashtab;
-
-static hashtab *nl_cache;
-static int n_nlcache;
-static hashentry **zot;
-static int colonseen;
-extern ftnlen f__typesize[];
-
-extern flag f__lquit;
-extern int f__lcount, nml_read;
-extern int t_getc (void);
-
-#undef abs
-#undef min
-#undef max
-#include 
-#include 
-
-#ifdef ungetc
-static int
-un_getc (int x, FILE * f__cf)
-{
-  return ungetc (x, f__cf);
-}
-#else
-#define un_getc ungetc
-extern int ungetc (int, FILE *);	/* for systems with a buggy stdio.h */
-#endif
-
-static Vardesc *
-hash (hashtab * ht, register char *s)
-{
-  register int c, x;
-  register hashentry *h;
-  char *s0 = s;
-
-  for (x = 0; (c = *s++); x = x & 0x4000 ? ((x << 1) & 0x7fff) + 1 : x << 1)
-    x += c;
-  for (h = *(zot = ht->tab + x % ht->htsize); h; h = h->next)
-    if (!strcmp (s0, h->name))
-      return h->vd;
-  return 0;
-}
-
-hashtab *
-mk_hashtab (Namelist * nl)
-{
-  int nht, nv;
-  hashtab *ht;
-  Vardesc *v, **vd, **vde;
-  hashentry *he;
-
-  hashtab **x, **x0, *y;
-  for (x = &nl_cache; (y = *x); x0 = x, x = &y->next)
-    if (nl == y->nl)
-      return y;
-  if (n_nlcache >= MAX_NL_CACHE)
-    {
-      /* discard least recently used namelist hash table */
-      y = *x0;
-      free ((char *) y->next);
-      y->next = 0;
-    }
-  else
-    n_nlcache++;
-  nv = nl->nvars;
-  if (nv >= 0x4000)
-    nht = 0x7fff;
-  else
-    {
-      for (nht = 1; nht < nv; nht <<= 1);
-      nht += nht - 1;
-    }
-  ht = (hashtab *) malloc (sizeof (hashtab) + (nht - 1) * sizeof (hashentry *)
-			   + nv * sizeof (hashentry));
-  if (!ht)
-    return 0;
-  he = (hashentry *) & ht->tab[nht];
-  ht->nl = nl;
-  ht->htsize = nht;
-  ht->next = nl_cache;
-  nl_cache = ht;
-  memset ((char *) ht->tab, 0, nht * sizeof (hashentry *));
-  vd = nl->vars;
-  vde = vd + nv;
-  while (vd < vde)
-    {
-      v = *vd++;
-      if (!hash (ht, v->name))
-	{
-	  he->next = *zot;
-	  *zot = he;
-	  he->name = v->name;
-	  he->vd = v;
-	  he++;
-	}
-    }
-  return ht;
-}
-
-static char Alpha[256], Alphanum[256];
-
-static void
-nl_init (void)
-{
-  register char *s;
-  register int c;
-
-  for (s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; (c = *s++);)
-    Alpha[c]
-      = Alphanum[c] = Alpha[c + 'a' - 'A'] = Alphanum[c + 'a' - 'A'] = c;
-  for (s = "0123456789_"; (c = *s++);)
-    Alphanum[c] = c;
-}
-
-#define GETC(x) (x=(*l_getc)())
-#define Ungetc(x,y) (*l_ungetc)(x,y)
-
-static int
-getname (register char *s, int slen)
-{
-  register char *se = s + slen - 1;
-  register int ch;
-
-  GETC (ch);
-  if (!(*s++ = Alpha[ch & 0xff]))
-    {
-      if (ch != EOF)
-	ch = 115;
-      errfl (f__elist->cierr, ch, "namelist read");
-    }
-  while ((*s = Alphanum[GETC (ch) & 0xff]))
-    if (s < se)
-      s++;
-  if (ch == EOF)
-    err (f__elist->cierr, EOF, "namelist read");
-  if (ch > ' ')
-    Ungetc (ch, f__cf);
-  return *s = 0;
-}
-
-static int
-getnum (int *chp, ftnlen * val)
-{
-  register int ch, sign;
-  register ftnlen x;
-
-  while (GETC (ch) <= ' ' && ch >= 0);
-  if (ch == '-')
-    {
-      sign = 1;
-      GETC (ch);
-    }
-  else
-    {
-      sign = 0;
-      if (ch == '+')
-	GETC (ch);
-    }
-  x = ch - '0';
-  if (x < 0 || x > 9)
-    return 115;
-  while (GETC (ch) >= '0' && ch <= '9')
-    x = 10 * x + ch - '0';
-  while (ch <= ' ' && ch >= 0)
-    GETC (ch);
-  if (ch == EOF)
-    return EOF;
-  *val = sign ? -x : x;
-  *chp = ch;
-  return 0;
-}
-
-static int
-getdimen (int *chp, dimen * d, ftnlen delta, ftnlen extent, ftnlen * x1)
-{
-  register int k;
-  ftnlen x2, x3;
-
-  if ((k = getnum (chp, x1)))
-    return k;
-  x3 = 1;
-  if (*chp == ':')
-    {
-      if ((k = getnum (chp, &x2)))
-	return k;
-      x2 -= *x1;
-      if (*chp == ':')
-	{
-	  if ((k = getnum (chp, &x3)))
-	    return k;
-	  if (!x3)
-	    return 123;
-	  x2 /= x3;
-	  colonseen = 1;
-	}
-      if (x2 < 0 || x2 >= extent)
-	return 123;
-      d->extent = x2 + 1;
-    }
-  else
-    d->extent = 1;
-  d->curval = 0;
-  d->delta = delta;
-  d->stride = x3;
-  return 0;
-}
-
-#ifndef No_Namelist_Questions
-static void
-print_ne (cilist * a)
-{
-  flag intext = f__external;
-  int rpsave = f__recpos;
-  FILE *cfsave = f__cf;
-  unit *usave = f__curunit;
-  cilist t;
-  t = *a;
-  t.ciunit = 6;
-  s_wsne (&t);
-  fflush (f__cf);
-  f__external = intext;
-  f__reading = 1;
-  f__recpos = rpsave;
-  f__cf = cfsave;
-  f__curunit = usave;
-  f__elist = a;
-}
-#endif
-
-static char where0[] = "namelist read start ";
-
-int
-x_rsne (cilist * a)
-{
-  int ch, got1, k, n, nd, quote, readall;
-  Namelist *nl;
-  static char where[] = "namelist read";
-  char buf[64];
-  hashtab *ht;
-  Vardesc *v;
-  dimen *dn, *dn0, *dn1;
-  ftnlen *dims, *dims1;
-  ftnlen b, b0, b1, ex, no, nomax, size, span;
-  ftnint no1, type;
-  char *vaddr;
-  long iva, ivae;
-  dimen dimens[MAXDIM], substr;
-  int dollarsign_delimited;
-
-  if (!Alpha['a'])
-    nl_init ();
-  f__reading = 1;
-  f__formatted = 1;
-  got1 = 0;
-top:
-  dollarsign_delimited = 0;
-  for (;;)
-    switch (GETC (ch))
-      {
-      case EOF:
-      eof:
-	err (a->ciend, (EOF), where0);
-      case '$':
-        dollarsign_delimited = 1;
-      case '&':
-	goto have_amp;
-#ifndef No_Namelist_Questions
-      case '?':
-	print_ne (a);
-	continue;
-#endif
-      default:
-	if (ch <= ' ' && ch >= 0)
-	  continue;
-#ifndef No_Namelist_Comments
-	while (GETC (ch) != '\n')
-	  if (ch == EOF)
-	    goto eof;
-#else
-	errfl (a->cierr, 115, where0);
-#endif
-      }
-have_amp:
-  if ((ch = getname (buf, sizeof (buf))))
-    return ch;
-  nl = (Namelist *) a->cifmt;
-  if (strcmp (buf, nl->name))
-#ifdef No_Bad_Namelist_Skip
-    errfl (a->cierr, 118, where0);
-#else
-    {
-      fprintf (stderr,
-	       "Skipping namelist \"%s\": seeking namelist \"%s\".\n",
-	       buf, nl->name);
-      fflush (stderr);
-      for (;;)
-	switch (GETC (ch))
-	  {
-	  case EOF:
-	    err (a->ciend, EOF, where0);
-	  case '/':
-            if (dollarsign_delimited)
-               continue;
-	  case '&':
-	  case '$':
-	    if (f__external)
-	      e_rsle ();
-	    else
-	      z_rnew ();
-	    goto top;
-	  case '"':
-	  case '\'':
-	    quote = ch;
-	  more_quoted:
-	    while (GETC (ch) != quote)
-	      if (ch == EOF)
-		err (a->ciend, EOF, where0);
-	    if (GETC (ch) == quote)
-	      goto more_quoted;
-	    Ungetc (ch, f__cf);
-	  default:
-	    continue;
-	  }
-    }
-#endif
-  ht = mk_hashtab (nl);
-  if (!ht)
-    errfl (f__elist->cierr, 113, where0);
-  for (;;)
-    {
-      for (;;)
-	switch (GETC (ch))
-	  {
-	  case EOF:
-	    if (got1)
-	      return 0;
-	    err (a->ciend, EOF, where0);
-	  case '/':
-	  case '$':
-	  case '&':
-	    return 0;
-	  default:
-	    if ((ch <= ' ' && ch >= 0) || ch == ',')
-	      continue;
-	    Ungetc (ch, f__cf);
-	    if ((ch = getname (buf, sizeof (buf))))
-	      return ch;
-	    goto havename;
-	  }
-    havename:
-      v = hash (ht, buf);
-      if (!v)
-	errfl (a->cierr, 119, where);
-      while (GETC (ch) <= ' ' && ch >= 0);
-      vaddr = v->addr;
-      type = v->type;
-      if (type < 0)
-	{
-	  size = -type;
-	  type = TYCHAR;
-	}
-      else
-	size = f__typesize[type];
-      ivae = size;
-      iva = readall = 0;
-      if (ch == '(' /*) */ )
-	{
-	  dn = dimens;
-	  if (!(dims = v->dims))
-	    {
-	      if (type != TYCHAR)
-		errfl (a->cierr, 122, where);
-	      if ((k = getdimen (&ch, dn, (ftnlen) size, (ftnlen) size, &b)))
-		errfl (a->cierr, k, where);
-	      if (ch != ')')
-		errfl (a->cierr, 115, where);
-	      b1 = dn->extent;
-	      if (--b < 0 || b + b1 > size)
-		return 124;
-	      iva += b;
-	      size = b1;
-	      while (GETC (ch) <= ' ' && ch >= 0);
-	      goto scalar;
-	    }
-	  nd = (int) dims[0];
-	  nomax = span = dims[1];
-	  ivae = iva + size * nomax;
-	  colonseen = 0;
-	  if ((k = getdimen (&ch, dn, size, nomax, &b)))
-	    errfl (a->cierr, k, where);
-	  no = dn->extent;
-	  b0 = dims[2];
-	  dims1 = dims += 3;
-	  ex = 1;
-	  for (n = 1; n++ < nd; dims++)
-	    {
-	      if (ch != ',')
-		errfl (a->cierr, 115, where);
-	      dn1 = dn + 1;
-	      span /= *dims;
-	      if ((k = getdimen (&ch, dn1, dn->delta ** dims, span, &b1)))
-		errfl (a->cierr, k, where);
-	      ex *= *dims;
-	      b += b1 * ex;
-	      no *= dn1->extent;
-	      dn = dn1;
-	    }
-	  if (ch != ')')
-	    errfl (a->cierr, 115, where);
-	  readall = 1 - colonseen;
-	  b -= b0;
-	  if (b < 0 || b >= nomax)
-	    errfl (a->cierr, 125, where);
-	  iva += size * b;
-	  dims = dims1;
-	  while (GETC (ch) <= ' ' && ch >= 0);
-	  no1 = 1;
-	  dn0 = dimens;
-	  if (type == TYCHAR && ch == '(' /*) */ )
-	    {
-	      if ((k = getdimen (&ch, &substr, size, size, &b)))
-		errfl (a->cierr, k, where);
-	      if (ch != ')')
-		errfl (a->cierr, 115, where);
-	      b1 = substr.extent;
-	      if (--b < 0 || b + b1 > size)
-		return 124;
-	      iva += b;
-	      b0 = size;
-	      size = b1;
-	      while (GETC (ch) <= ' ' && ch >= 0);
-	      if (b1 < b0)
-		goto delta_adj;
-	    }
-	  if (readall)
-	    goto delta_adj;
-	  for (; dn0 < dn; dn0++)
-	    {
-	      if (dn0->extent != *dims++ || dn0->stride != 1)
-		break;
-	      no1 *= dn0->extent;
-	    }
-	  if (dn0 == dimens && dimens[0].stride == 1)
-	    {
-	      no1 = dimens[0].extent;
-	      dn0++;
-	    }
-	delta_adj:
-	  ex = 0;
-	  for (dn1 = dn0; dn1 <= dn; dn1++)
-	    ex += (dn1->extent - 1) * (dn1->delta *= dn1->stride);
-	  for (dn1 = dn; dn1 > dn0; dn1--)
-	    {
-	      ex -= (dn1->extent - 1) * dn1->delta;
-	      dn1->delta -= ex;
-	    }
-	}
-      else if ((dims = v->dims))
-	{
-	  no = no1 = dims[1];
-	  ivae = iva + no * size;
-	}
-      else
-      scalar:
-	no = no1 = 1;
-      if (ch != '=')
-	errfl (a->cierr, 115, where);
-      got1 = nml_read = 1;
-      f__lcount = 0;
-    readloop:
-      for (;;)
-	{
-	  if (iva >= ivae || iva < 0)
-	    {
-	      f__lquit = 1;
-	      goto mustend;
-	    }
-	  else if (iva + no1 * size > ivae)
-	    no1 = (ivae - iva) / size;
-	  f__lquit = 0;
-	  if ((k = l_read (&no1, vaddr + iva, size, type)))
-	    return k;
-	  if (f__lquit == 1)
-	    return 0;
-	  if (readall)
-	    {
-	      iva += dn0->delta;
-	      if (f__lcount > 0)
-		{
-		  ftnint no2 = (ivae - iva) / size;
-		  if (no2 > f__lcount)
-		    no2 = f__lcount;
-		  if ((k = l_read (&no2, vaddr + iva, size, type)))
-		    return k;
-		  iva += no2 * dn0->delta;
-		}
-	    }
-	mustend:
-	  GETC (ch);
-	  if (readall)
-	    {
-	      if (iva >= ivae)
-		readall = 0;
-	      else
-		for (;;)
-		  {
-		    switch (ch)
-		      {
-		      case ' ':
-		      case '\t':
-		      case '\n':
-			GETC (ch);
-			continue;
-		      }
-		    break;
-		  }
-	    }
-	  if (ch == '/' || ch == '$' || ch == '&')
-	    {
-	      f__lquit = 1;
-	      return 0;
-	    }
-	  else if (f__lquit)
-	    {
-	      while (ch <= ' ' && ch >= 0)
-		GETC (ch);
-	      Ungetc (ch, f__cf);
-	      if (!Alpha[ch & 0xff] && ch >= 0)
-		errfl (a->cierr, 125, where);
-	      break;
-	    }
-	  Ungetc (ch, f__cf);
-	  if (readall && !Alpha[ch & 0xff])
-	    goto readloop;
-	  if ((no -= no1) <= 0)
-	    break;
-	  for (dn1 = dn0; dn1 <= dn; dn1++)
-	    {
-	      if (++dn1->curval < dn1->extent)
-		{
-		  iva += dn1->delta;
-		  goto readloop;
-		}
-	      dn1->curval = 0;
-	    }
-	  break;
-	}
-    }
-}
-
-integer
-s_rsne (cilist * a)
-{
-  extern int l_eof;
-  int n;
-
-  f__external = 1;
-  l_eof = 0;
-  if ((n = c_le (a)))
-    return n;
-  if (f__curunit->uwrt && f__nowreading (f__curunit))
-    err (a->cierr, errno, where0);
-  l_getc = t_getc;
-  l_ungetc = un_getc;
-  f__doend = xrd_SL;
-  n = x_rsne (a);
-  nml_read = 0;
-  if (n)
-    return n;
-  return e_rsle ();
-}
diff --git a/contrib/libf2c/libI77/sfe.c b/contrib/libf2c/libI77/sfe.c
deleted file mode 100644
index 8f05e480662..00000000000
--- a/contrib/libf2c/libI77/sfe.c
+++ /dev/null
@@ -1,44 +0,0 @@
-/* sequential formatted external common routines*/
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-
-extern char *f__fmtbuf;
-
-integer
-e_rsfe (void)
-{
-  int n;
-  f__init = 1;
-  n = en_fio ();
-  f__fmtbuf = NULL;
-  return (n);
-}
-
-int
-c_sfe (cilist * a)		/* check */
-{
-  unit *p;
-  if (a->ciunit >= MXUNIT || a->ciunit < 0)
-    err (a->cierr, 101, "startio");
-  p = &f__units[a->ciunit];
-  if (p->ufd == NULL && fk_open (SEQ, FMT, a->ciunit))
-    err (a->cierr, 114, "sfe");
-  if (!p->ufmt)
-    err (a->cierr, 102, "sfe");
-  return (0);
-}
-
-integer
-e_wsfe (void)
-{
-  int n;
-  f__init = 1;
-  n = en_fio ();
-  f__fmtbuf = NULL;
-#ifdef ALWAYS_FLUSH
-  if (!n && fflush (f__cf))
-    err (f__elist->cierr, errno, "write end");
-#endif
-  return n;
-}
diff --git a/contrib/libf2c/libI77/stamp-h.in b/contrib/libf2c/libI77/stamp-h.in
deleted file mode 100644
index 9788f70238c..00000000000
--- a/contrib/libf2c/libI77/stamp-h.in
+++ /dev/null
@@ -1 +0,0 @@
-timestamp
diff --git a/contrib/libf2c/libI77/sue.c b/contrib/libf2c/libI77/sue.c
deleted file mode 100644
index a20df66d31f..00000000000
--- a/contrib/libf2c/libI77/sue.c
+++ /dev/null
@@ -1,93 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-extern uiolen f__reclen;
-off_t f__recloc;
-
-int
-c_sue (cilist * a)
-{
-  f__external = f__sequential = 1;
-  f__formatted = 0;
-  f__curunit = &f__units[a->ciunit];
-  if (a->ciunit >= MXUNIT || a->ciunit < 0)
-    err (a->cierr, 101, "startio");
-  f__elist = a;
-  if (f__curunit->ufd == NULL && fk_open (SEQ, UNF, a->ciunit))
-    err (a->cierr, 114, "sue");
-  f__cf = f__curunit->ufd;
-  if (f__curunit->ufmt)
-    err (a->cierr, 103, "sue");
-  if (!f__curunit->useek)
-    err (a->cierr, 103, "sue");
-  return (0);
-}
-
-integer
-s_rsue (cilist * a)
-{
-  int n;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__reading = 1;
-  if ((n = c_sue (a)))
-    return (n);
-  f__recpos = 0;
-  if (f__curunit->uwrt && f__nowreading (f__curunit))
-    err (a->cierr, errno, "read start");
-  if (fread ((char *) &f__reclen, sizeof (uiolen), 1, f__cf) != 1)
-    {
-      if (feof (f__cf))
-	{
-	  f__curunit->uend = 1;
-	  err (a->ciend, EOF, "start");
-	}
-      clearerr (f__cf);
-      err (a->cierr, errno, "start");
-    }
-  return (0);
-}
-
-integer
-s_wsue (cilist * a)
-{
-  int n;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  if ((n = c_sue (a)))
-    return (n);
-  f__reading = 0;
-  f__reclen = 0;
-  if (f__curunit->uwrt != 1 && f__nowwriting (f__curunit))
-    err (a->cierr, errno, "write start");
-  f__recloc = FTELL (f__cf);
-  FSEEK (f__cf, (off_t) sizeof (uiolen), SEEK_CUR);
-  return (0);
-}
-
-integer
-e_wsue (void)
-{
-  off_t loc;
-  f__init = 1;
-  fwrite ((char *) &f__reclen, sizeof (uiolen), 1, f__cf);
-#ifdef ALWAYS_FLUSH
-  if (fflush (f__cf))
-    err (f__elist->cierr, errno, "write end");
-#endif
-  loc = FTELL (f__cf);
-  FSEEK (f__cf, f__recloc, SEEK_SET);
-  fwrite ((char *) &f__reclen, sizeof (uiolen), 1, f__cf);
-  FSEEK (f__cf, loc, SEEK_SET);
-  return (0);
-}
-
-integer
-e_rsue (void)
-{
-  f__init = 1;
-  FSEEK (f__cf, (off_t) (f__reclen - f__recpos + sizeof (uiolen)), SEEK_CUR);
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/typesize.c b/contrib/libf2c/libI77/typesize.c
deleted file mode 100644
index 8e2a74ad195..00000000000
--- a/contrib/libf2c/libI77/typesize.c
+++ /dev/null
@@ -1,14 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-
-ftnlen f__typesize[] = { 0, 0, sizeof (shortint), sizeof (integer),
-  sizeof (real), sizeof (doublereal),
-  sizeof (complex), sizeof (doublecomplex),
-  sizeof (logical), sizeof (char),
-  0, sizeof (integer1),
-  sizeof (logical1), sizeof (shortlogical),
-#ifdef Allow_TYQUAD
-  sizeof (longint),
-#endif
-  0
-};
diff --git a/contrib/libf2c/libI77/uio.c b/contrib/libf2c/libI77/uio.c
deleted file mode 100644
index 706b5dd3d9c..00000000000
--- a/contrib/libf2c/libI77/uio.c
+++ /dev/null
@@ -1,60 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include 
-uiolen f__reclen;
-
-int
-do_us (ftnint * number, char *ptr, ftnlen len)
-{
-  if (f__reading)
-    {
-      f__recpos += (int) (*number * len);
-      if (f__recpos > f__reclen)
-	err (f__elist->cierr, 110, "do_us");
-      if (fread (ptr, (size_t) len, (size_t) (*number), f__cf) != (size_t) *number)
-	err (f__elist->ciend, EOF, "do_us");
-      return (0);
-    }
-  else
-    {
-      f__reclen += *number * len;
-      (void) fwrite (ptr, (size_t) len, (size_t) (*number), f__cf);
-      return (0);
-    }
-}
-integer
-do_ud (ftnint * number, char *ptr, ftnlen len)
-{
-  f__recpos += (int) (*number * len);
-  if (f__recpos > f__curunit->url && f__curunit->url != 1)
-    err (f__elist->cierr, 110, "do_ud");
-  if (f__reading)
-    {
-#ifdef Pad_UDread
-      size_t i;
-      if (!(i = fread (ptr, (size_t) len, (size_t) (*number), f__cf))
-	  && !(f__recpos - *number * len))
-	err (f__elist->cierr, EOF, "do_ud");
-      if (i < (size_t) *number)
-	memset (ptr + i * len, 0, (*number - i) * len);
-      return 0;
-#else
-      if (fread (ptr, (size_t) len, (size_t) (*number), f__cf) != *number)
-	err (f__elist->cierr, EOF, "do_ud");
-      else
-	return (0);
-#endif
-    }
-  (void) fwrite (ptr, (size_t) len, (size_t) (*number), f__cf);
-  return (0);
-}
-
-integer
-do_uio (ftnint * number, char *ptr, ftnlen len)
-{
-  if (f__sequential)
-    return (do_us (number, ptr, len));
-  else
-    return (do_ud (number, ptr, len));
-}
diff --git a/contrib/libf2c/libI77/util.c b/contrib/libf2c/libI77/util.c
deleted file mode 100644
index 6e7c52b14ce..00000000000
--- a/contrib/libf2c/libI77/util.c
+++ /dev/null
@@ -1,52 +0,0 @@
-#include "config.h"
-#ifndef NON_UNIX_STDIO
-#define _INCLUDE_POSIX_SOURCE	/* for HP-UX */
-#define _INCLUDE_XOPEN_SOURCE	/* for HP-UX */
-#include 
-#include 
-#endif
-#include "f2c.h"
-#include "fio.h"
-
-void
-g_char (char *a, ftnlen alen, char *b)
-{
-  char *x = a + alen, *y = b + alen;
-
-  for (;; y--)
-    {
-      if (x <= a)
-	{
-	  *b = 0;
-	  return;
-	}
-      if (*--x != ' ')
-	break;
-    }
-  *y-- = 0;
-  do
-    *y-- = *x;
-  while (x-- > a);
-}
-
-void
-b_char (char *a, char *b, ftnlen blen)
-{
-  int i;
-  for (i = 0; i < blen && *a != 0; i++)
-    *b++ = *a++;
-  for (; i < blen; i++)
-    *b++ = ' ';
-}
-
-#ifndef NON_UNIX_STDIO
-long
-f__inode (char *a, int *dev)
-{
-  struct stat x;
-  if (stat (a, &x) < 0)
-    return (-1);
-  *dev = x.st_dev;
-  return (x.st_ino);
-}
-#endif
diff --git a/contrib/libf2c/libI77/wref.c b/contrib/libf2c/libI77/wref.c
deleted file mode 100644
index 0dc30919da4..00000000000
--- a/contrib/libf2c/libI77/wref.c
+++ /dev/null
@@ -1,306 +0,0 @@
-#include "f2c.h"
-#include "fio.h"
-#ifndef VAX
-#include 
-#endif
-
-#undef abs
-#undef min
-#undef max
-#include 
-#include 
-
-#include "fmt.h"
-#include "fp.h"
-
-int
-wrt_E (ufloat * p, int w, int d, int e, ftnlen len)
-{
-  char buf[FMAX + EXPMAXDIGS + 4], *s, *se;
-  int d1, delta, e1, i, sign, signspace;
-  double dd;
-#ifdef WANT_LEAD_0
-  int insert0 = 0;
-#endif
-#ifndef VAX
-  int e0 = e;
-#endif
-
-  if (e <= 0)
-    e = 2;
-  if (f__scale)
-    {
-      if (f__scale >= d + 2 || f__scale <= -d)
-	goto nogood;
-    }
-  if (f__scale <= 0)
-    --d;
-  if (len == sizeof (real))
-    dd = p->pf;
-  else
-    dd = p->pd;
-  if (dd < 0.)
-    {
-      signspace = sign = 1;
-      dd = -dd;
-    }
-  else
-    {
-      sign = 0;
-      signspace = (int) f__cplus;
-#ifndef VAX
-      if (!dd)
-	dd = 0.;		/* avoid -0 */
-#endif
-    }
-  delta = w - (2		/* for the . and the d adjustment above */
-	       + 2 /* for the E+ */  + signspace + d + e);
-#ifdef WANT_LEAD_0
-  if (f__scale <= 0 && delta > 0)
-    {
-      delta--;
-      insert0 = 1;
-    }
-  else
-#endif
-  if (delta < 0)
-    {
-    nogood:
-      while (--w >= 0)
-	PUT ('*');
-      return (0);
-    }
-  if (f__scale < 0)
-    d += f__scale;
-  if (d > FMAX)
-    {
-      d1 = d - FMAX;
-      d = FMAX;
-    }
-  else
-    d1 = 0;
-  sprintf (buf, "%#.*E", d, dd);
-#ifndef VAX
-  /* check for NaN, Infinity */
-  if (!isdigit ((unsigned char) buf[0]))
-    {
-      switch (buf[0])
-	{
-	case 'n':
-	case 'N':
-	  signspace = 0;	/* no sign for NaNs */
-	}
-      delta = w - strlen (buf) - signspace;
-      if (delta < 0)
-	goto nogood;
-      while (--delta >= 0)
-	PUT (' ');
-      if (signspace)
-	PUT (sign ? '-' : '+');
-      for (s = buf; *s; s++)
-	PUT (*s);
-      return 0;
-    }
-#endif
-  se = buf + d + 3;
-#ifdef GOOD_SPRINTF_EXPONENT	/* When possible, exponent has 2 digits. */
-  if (f__scale != 1 && dd)
-    sprintf (se, "%+.2d", atoi (se) + 1 - f__scale);
-#else
-  if (dd)
-    sprintf (se, "%+.2d", atoi (se) + 1 - f__scale);
-  else
-    strcpy (se, "+00");
-#endif
-  s = ++se;
-  if (e < 2)
-    {
-      if (*s != '0')
-	goto nogood;
-    }
-#ifndef VAX
-  /* accommodate 3 significant digits in exponent */
-  if (s[2])
-    {
-#ifdef Pedantic
-      if (!e0 && !s[3])
-	for (s -= 2, e1 = 2; s[0] = s[1]; s++);
-
-      /* Pedantic gives the behavior that Fortran 77 specifies,       */
-      /* i.e., requires that E be specified for exponent fields       */
-      /* of more than 3 digits.  With Pedantic undefined, we get      */
-      /* the behavior that Cray displays -- you get a bigger          */
-      /* exponent field if it fits.   */
-#else
-      if (!e0)
-	{
-	  for (s -= 2, e1 = 2; (s[0] = s[1]); s++)
-#ifdef CRAY
-	    delta--;
-	  if ((delta += 4) < 0)
-	    goto nogood
-#endif
-	      ;
-	}
-#endif
-      else if (e0 >= 0)
-	goto shift;
-      else
-	e1 = e;
-    }
-  else
-  shift:
-#endif
-    for (s += 2, e1 = 2; *s; ++e1, ++s)
-      if (e1 >= e)
-	goto nogood;
-  while (--delta >= 0)
-    PUT (' ');
-  if (signspace)
-    PUT (sign ? '-' : '+');
-  s = buf;
-  i = f__scale;
-  if (f__scale <= 0)
-    {
-#ifdef WANT_LEAD_0
-      if (insert0)
-	PUT ('0');
-#endif
-      PUT ('.');
-      for (; i < 0; ++i)
-	PUT ('0');
-      PUT (*s);
-      s += 2;
-    }
-  else if (f__scale > 1)
-    {
-      PUT (*s);
-      s += 2;
-      while (--i > 0)
-	PUT (*s++);
-      PUT ('.');
-    }
-  if (d1)
-    {
-      se -= 2;
-      while (s < se)
-	PUT (*s++);
-      se += 2;
-      do
-	PUT ('0');
-      while (--d1 > 0);
-    }
-  while (s < se)
-    PUT (*s++);
-  if (e < 2)
-    PUT (s[1]);
-  else
-    {
-      while (++e1 <= e)
-	PUT ('0');
-      while (*s)
-	PUT (*s++);
-    }
-  return 0;
-}
-
-int
-wrt_F (ufloat * p, int w, int d, ftnlen len)
-{
-  int d1, sign, n;
-  double x;
-  char *b, buf[MAXINTDIGS + MAXFRACDIGS + 4], *s;
-
-  x = (len == sizeof (real) ? p->pf : p->pd);
-  if (d < MAXFRACDIGS)
-    d1 = 0;
-  else
-    {
-      d1 = d - MAXFRACDIGS;
-      d = MAXFRACDIGS;
-    }
-  if (x < 0.)
-    {
-      x = -x;
-      sign = 1;
-    }
-  else
-    {
-      sign = 0;
-#ifndef VAX
-      if (!x)
-	x = 0.;
-#endif
-    }
-
-  if ((n = f__scale))
-    {
-      if (n > 0)
-	do
-	  x *= 10.;
-	while (--n > 0);
-      else
-	do
-	  x *= 0.1;
-	while (++n < 0);
-    }
-
-#ifdef USE_STRLEN
-  sprintf (b = buf, "%#.*f", d, x);
-  n = strlen (b) + d1;
-#else
-  n = sprintf (b = buf, "%#.*f", d, x) + d1;
-#endif
-
-#ifndef WANT_LEAD_0
-  if (buf[0] == '0' && d)
-    {
-      ++b;
-      --n;
-    }
-#endif
-  if (sign)
-    {
-      /* check for all zeros */
-      for (s = b;;)
-	{
-	  while (*s == '0')
-	    s++;
-	  switch (*s)
-	    {
-	    case '.':
-	      s++;
-	      continue;
-	    case 0:
-	      sign = 0;
-	    }
-	  break;
-	}
-    }
-  if (sign || f__cplus)
-    ++n;
-  if (n > w)
-    {
-#ifdef WANT_LEAD_0
-      if (buf[0] == '0' && --n == w)
-	++b;
-      else
-#endif
-	{
-	  while (--w >= 0)
-	    PUT ('*');
-	  return 0;
-	}
-    }
-  for (w -= n; --w >= 0;)
-    PUT (' ');
-  if (sign)
-    PUT ('-');
-  else if (f__cplus)
-    PUT ('+');
-  while ((n = *b++))
-    PUT (n);
-  while (--d1 >= 0)
-    PUT ('0');
-  return 0;
-}
diff --git a/contrib/libf2c/libI77/wrtfmt.c b/contrib/libf2c/libI77/wrtfmt.c
deleted file mode 100644
index 0747f923e24..00000000000
--- a/contrib/libf2c/libI77/wrtfmt.c
+++ /dev/null
@@ -1,407 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-
-extern icilist *f__svic;
-extern char *f__icptr;
-
-static int
-mv_cur (void)			/* shouldn't use fseek because it insists on calling fflush */
-		/* instead we know too much about stdio */
-{
-  int cursor = f__cursor;
-  f__cursor = 0;
-  if (f__external == 0)
-    {
-      if (cursor < 0)
-	{
-	  if (f__hiwater < f__recpos)
-	    f__hiwater = f__recpos;
-	  f__recpos += cursor;
-	  f__icptr += cursor;
-	  if (f__recpos < 0)
-	    err (f__elist->cierr, 110, "left off");
-	}
-      else if (cursor > 0)
-	{
-	  if (f__recpos + cursor >= f__svic->icirlen)
-	    err (f__elist->cierr, 110, "recend");
-	  if (f__hiwater <= f__recpos)
-	    for (; cursor > 0; cursor--)
-	      (*f__putn) (' ');
-	  else if (f__hiwater <= f__recpos + cursor)
-	    {
-	      cursor -= f__hiwater - f__recpos;
-	      f__icptr += f__hiwater - f__recpos;
-	      f__recpos = f__hiwater;
-	      for (; cursor > 0; cursor--)
-		(*f__putn) (' ');
-	    }
-	  else
-	    {
-	      f__icptr += cursor;
-	      f__recpos += cursor;
-	    }
-	}
-      return (0);
-    }
-  if (cursor > 0)
-    {
-      if (f__hiwater <= f__recpos)
-	for (; cursor > 0; cursor--)
-	  (*f__putn) (' ');
-      else if (f__hiwater <= f__recpos + cursor)
-	{
-	  cursor -= f__hiwater - f__recpos;
-	  f__recpos = f__hiwater;
-	  for (; cursor > 0; cursor--)
-	    (*f__putn) (' ');
-	}
-      else
-	{
-	  f__recpos += cursor;
-	}
-    }
-  else if (cursor < 0)
-    {
-      if (cursor + f__recpos < 0)
-	err (f__elist->cierr, 110, "left off");
-      if (f__hiwater < f__recpos)
-	f__hiwater = f__recpos;
-      f__recpos += cursor;
-    }
-  return (0);
-}
-
-static int
-wrt_Z (Uint * n, int w, int minlen, ftnlen len)
-{
-  register char *s, *se;
-  register int i, w1;
-  static int one = 1;
-  static char hex[] = "0123456789ABCDEF";
-  s = (char *) n;
-  --len;
-  if (*(char *) &one)
-    {
-      /* little endian */
-      se = s;
-      s += len;
-      i = -1;
-    }
-  else
-    {
-      se = s + len;
-      i = 1;
-    }
-  for (;; s += i)
-    if (s == se || *s)
-      break;
-  w1 = (i * (se - s) << 1) + 1;
-  if (*s & 0xf0)
-    w1++;
-  if (w1 > w)
-    for (i = 0; i < w; i++)
-      (*f__putn) ('*');
-  else
-    {
-      if ((minlen -= w1) > 0)
-	w1 += minlen;
-      while (--w >= w1)
-	(*f__putn) (' ');
-      while (--minlen >= 0)
-	(*f__putn) ('0');
-      if (!(*s & 0xf0))
-	{
-	  (*f__putn) (hex[*s & 0xf]);
-	  if (s == se)
-	    return 0;
-	  s += i;
-	}
-      for (;; s += i)
-	{
-	  (*f__putn) (hex[*s >> 4 & 0xf]);
-	  (*f__putn) (hex[*s & 0xf]);
-	  if (s == se)
-	    break;
-	}
-    }
-  return 0;
-}
-
-static int
-wrt_I (Uint * n, int w, ftnlen len, register int base)
-{
-  int ndigit, sign, spare, i;
-  longint x;
-  char *ans;
-  if (len == sizeof (integer))
-    x = n->il;
-  else if (len == sizeof (char))
-    x = n->ic;
-#ifdef Allow_TYQUAD
-  else if (len == sizeof (longint))
-    x = n->ili;
-#endif
-  else
-    x = n->is;
-  ans = f__icvt (x, &ndigit, &sign, base);
-  spare = w - ndigit;
-  if (sign || f__cplus)
-    spare--;
-  if (spare < 0)
-    for (i = 0; i < w; i++)
-      (*f__putn) ('*');
-  else
-    {
-      for (i = 0; i < spare; i++)
-	(*f__putn) (' ');
-      if (sign)
-	(*f__putn) ('-');
-      else if (f__cplus)
-	(*f__putn) ('+');
-      for (i = 0; i < ndigit; i++)
-	(*f__putn) (*ans++);
-    }
-  return (0);
-}
-static int
-wrt_IM (Uint * n, int w, int m, ftnlen len, int base)
-{
-  int ndigit, sign, spare, i, xsign;
-  longint x;
-  char *ans;
-  if (sizeof (integer) == len)
-    x = n->il;
-  else if (len == sizeof (char))
-    x = n->ic;
-#ifdef Allow_TYQUAD
-  else if (len == sizeof (longint))
-    x = n->ili;
-#endif
-  else
-    x = n->is;
-  ans = f__icvt (x, &ndigit, &sign, base);
-  if (sign || f__cplus)
-    xsign = 1;
-  else
-    xsign = 0;
-  if (ndigit + xsign > w || m + xsign > w)
-    {
-      for (i = 0; i < w; i++)
-	(*f__putn) ('*');
-      return (0);
-    }
-  if (x == 0 && m == 0)
-    {
-      for (i = 0; i < w; i++)
-	(*f__putn) (' ');
-      return (0);
-    }
-  if (ndigit >= m)
-    spare = w - ndigit - xsign;
-  else
-    spare = w - m - xsign;
-  for (i = 0; i < spare; i++)
-    (*f__putn) (' ');
-  if (sign)
-    (*f__putn) ('-');
-  else if (f__cplus)
-    (*f__putn) ('+');
-  for (i = 0; i < m - ndigit; i++)
-    (*f__putn) ('0');
-  for (i = 0; i < ndigit; i++)
-    (*f__putn) (*ans++);
-  return (0);
-}
-static int
-wrt_AP (char *s)
-{
-  char quote;
-  int i;
-
-  if (f__cursor && (i = mv_cur ()))
-    return i;
-  quote = *s++;
-  for (; *s; s++)
-    {
-      if (*s != quote)
-	(*f__putn) (*s);
-      else if (*++s == quote)
-	(*f__putn) (*s);
-      else
-	return (1);
-    }
-  return (1);
-}
-static int
-wrt_H (int a, char *s)
-{
-  int i;
-
-  if (f__cursor && (i = mv_cur ()))
-    return i;
-  while (a--)
-    (*f__putn) (*s++);
-  return (1);
-}
-
-int
-wrt_L (Uint * n, int len, ftnlen sz)
-{
-  int i;
-  longint x;
-#ifdef Allow_TYQUAD
-  if (sizeof (longint) == sz)
-    x = n->ili;
-  else
-#endif
-  if (sizeof (short ) == sz)
-    x = n->is;
-  else if (sizeof (char) == sz)
-    x = n->ic;
-  else if (sizeof (integer) == sz)
-    x = n->il;
-
-  for (i = 0; i < len - 1; i++)
-    (*f__putn) (' ');
-  if (x)
-    (*f__putn) ('T');
-  else
-    (*f__putn) ('F');
-  return (0);
-}
-static int
-wrt_A (char *p, ftnlen len)
-{
-  while (len-- > 0)
-    (*f__putn) (*p++);
-  return (0);
-}
-static int
-wrt_AW (char *p, int w, ftnlen len)
-{
-  while (w > len)
-    {
-      w--;
-      (*f__putn) (' ');
-    }
-  while (w-- > 0)
-    (*f__putn) (*p++);
-  return (0);
-}
-
-static int
-wrt_G (ufloat * p, int w, int d, int e, ftnlen len)
-{
-  double up = 1, x;
-  int i = 0, oldscale, n, j;
-  x = len == sizeof (real) ? p->pf : p->pd;
-  if (x < 0)
-    x = -x;
-  if (x < .1)
-    {
-      if (x != 0.)
-	return (wrt_E (p, w, d, e, len));
-      i = 1;
-      goto have_i;
-    }
-  for (; i <= d; i++, up *= 10)
-    {
-      if (x >= up)
-	continue;
-    have_i:
-      oldscale = f__scale;
-      f__scale = 0;
-      if (e == 0)
-	n = 4;
-      else
-	n = e + 2;
-      i = wrt_F (p, w - n, d - i, len);
-      for (j = 0; j < n; j++)
-	(*f__putn) (' ');
-      f__scale = oldscale;
-      return (i);
-    }
-  return (wrt_E (p, w, d, e, len));
-}
-
-int
-w_ed (struct syl * p, char *ptr, ftnlen len)
-{
-  int i;
-
-  if (f__cursor && (i = mv_cur ()))
-    return i;
-  switch (p->op)
-    {
-    default:
-      fprintf (stderr, "w_ed, unexpected code: %d\n", p->op);
-      sig_die (f__fmtbuf, 1);
-    case I:
-      return (wrt_I ((Uint *) ptr, p->p1, len, 10));
-    case IM:
-      return (wrt_IM ((Uint *) ptr, p->p1, p->p2.i[0], len, 10));
-
-      /* O and OM don't work right for character, double, complex, */
-      /* or doublecomplex, and they differ from Fortran 90 in */
-      /* showing a minus sign for negative values. */
-
-    case O:
-      return (wrt_I ((Uint *) ptr, p->p1, len, 8));
-    case OM:
-      return (wrt_IM ((Uint *) ptr, p->p1, p->p2.i[0], len, 8));
-    case L:
-      return (wrt_L ((Uint *) ptr, p->p1, len));
-    case A:
-      return (wrt_A (ptr, len));
-    case AW:
-      return (wrt_AW (ptr, p->p1, len));
-    case D:
-    case E:
-    case EE:
-      return (wrt_E ((ufloat *) ptr, p->p1, p->p2.i[0], p->p2.i[1], len));
-    case G:
-    case GE:
-      return (wrt_G ((ufloat *) ptr, p->p1, p->p2.i[0], p->p2.i[1], len));
-    case F:
-      return (wrt_F ((ufloat *) ptr, p->p1, p->p2.i[0], len));
-
-      /* Z and ZM assume 8-bit bytes. */
-
-    case Z:
-      return (wrt_Z ((Uint *) ptr, p->p1, 0, len));
-    case ZM:
-      return (wrt_Z ((Uint *) ptr, p->p1, p->p2.i[0], len));
-    }
-}
-
-int
-w_ned (struct syl * p)
-{
-  switch (p->op)
-    {
-    default:
-      fprintf (stderr, "w_ned, unexpected code: %d\n", p->op);
-      sig_die (f__fmtbuf, 1);
-    case SLASH:
-      return ((*f__donewrec) ());
-    case T:
-      f__cursor = p->p1 - f__recpos - 1;
-      return (1);
-    case TL:
-      f__cursor -= p->p1;
-      if (f__cursor < -f__recpos)	/* TL1000, 1X */
-	f__cursor = -f__recpos;
-      return (1);
-    case TR:
-    case X:
-      f__cursor += p->p1;
-      return (1);
-    case APOS:
-      return (wrt_AP (p->p2.s));
-    case H:
-      return (wrt_H (p->p1, p->p2.s));
-    }
-}
diff --git a/contrib/libf2c/libI77/wsfe.c b/contrib/libf2c/libI77/wsfe.c
deleted file mode 100644
index 46f7a8ffef0..00000000000
--- a/contrib/libf2c/libI77/wsfe.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/*write sequential formatted external*/
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-extern int f__hiwater;
-
-int
-x_wSL (void)
-{
-  int n = f__putbuf ('\n');
-  f__hiwater = f__recpos = f__cursor = 0;
-  return (n == 0);
-}
-
-static int
-xw_end (void)
-{
-  int n;
-
-  if (f__nonl)
-    {
-      f__putbuf (n = 0);
-      fflush (f__cf);
-    }
-  else
-    n = f__putbuf ('\n');
-  f__hiwater = f__recpos = f__cursor = 0;
-  return n;
-}
-
-static int
-xw_rev (void)
-{
-  int n = 0;
-  if (f__workdone)
-    {
-      n = f__putbuf ('\n');
-      f__workdone = 0;
-    }
-  f__hiwater = f__recpos = f__cursor = 0;
-  return n;
-}
-
-integer
-s_wsfe (cilist * a)		/*start */
-{
-  int n;
-  if (f__init != 1)
-    f_init ();
-  f__init = 3;
-  f__reading = 0;
-  f__sequential = 1;
-  f__formatted = 1;
-  f__external = 1;
-  if ((n = c_sfe (a)))
-    return (n);
-  f__elist = a;
-  f__hiwater = f__cursor = f__recpos = 0;
-  f__nonl = 0;
-  f__scale = 0;
-  f__fmtbuf = a->cifmt;
-  f__curunit = &f__units[a->ciunit];
-  f__cf = f__curunit->ufd;
-  if (pars_f (f__fmtbuf) < 0)
-    err (a->cierr, 100, "startio");
-  f__putn = x_putc;
-  f__doed = w_ed;
-  f__doned = w_ned;
-  f__doend = xw_end;
-  f__dorevert = xw_rev;
-  f__donewrec = x_wSL;
-  fmt_bg ();
-  f__cplus = 0;
-  f__cblank = f__curunit->ublnk;
-  if (f__curunit->uwrt != 1 && f__nowwriting (f__curunit))
-    err (a->cierr, errno, "write start");
-  return (0);
-}
diff --git a/contrib/libf2c/libI77/wsle.c b/contrib/libf2c/libI77/wsle.c
deleted file mode 100644
index e9ef172d591..00000000000
--- a/contrib/libf2c/libI77/wsle.c
+++ /dev/null
@@ -1,38 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "fmt.h"
-#include "lio.h"
-#include "string.h"
-
-integer
-s_wsle (cilist * a)
-{
-  int n;
-  if ((n = c_le (a)))
-    return (n);
-  f__reading = 0;
-  f__external = 1;
-  f__formatted = 1;
-  f__putn = x_putc;
-  f__lioproc = l_write;
-  L_len = LINE;
-  f__donewrec = x_wSL;
-  if (f__curunit->uwrt != 1 && f__nowwriting (f__curunit))
-    err (a->cierr, errno, "list output start");
-  return (0);
-}
-
-integer
-e_wsle (void)
-{
-  int n;
-  f__init = 1;
-  n = f__putbuf ('\n');
-  f__recpos = 0;
-#ifdef ALWAYS_FLUSH
-  if (!n && fflush (f__cf))
-    err (f__elist->cierr, errno, "write end");
-#endif
-  return (n);
-}
diff --git a/contrib/libf2c/libI77/wsne.c b/contrib/libf2c/libI77/wsne.c
deleted file mode 100644
index bcf08262de1..00000000000
--- a/contrib/libf2c/libI77/wsne.c
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "f2c.h"
-#include "fio.h"
-#include "lio.h"
-
-integer
-s_wsne (cilist * a)
-{
-  int n;
-
-  if ((n = c_le (a)))
-    return (n);
-  f__reading = 0;
-  f__external = 1;
-  f__formatted = 1;
-  f__putn = x_putc;
-  L_len = LINE;
-  f__donewrec = x_wSL;
-  if (f__curunit->uwrt != 1 && f__nowwriting (f__curunit))
-    err (a->cierr, errno, "namelist output start");
-  x_wsne (a);
-  return e_wsle ();
-}
diff --git a/contrib/libf2c/libI77/xwsne.c b/contrib/libf2c/libI77/xwsne.c
deleted file mode 100644
index 68b606c8276..00000000000
--- a/contrib/libf2c/libI77/xwsne.c
+++ /dev/null
@@ -1,71 +0,0 @@
-#include "config.h"
-#include "f2c.h"
-#include "fio.h"
-#include "lio.h"
-#include "fmt.h"
-
-extern int f__Aquote;
-
-static void
-nl_donewrec (void)
-{
-  (*f__donewrec) ();
-  PUT (' ');
-}
-
-#include 
-
-void
-x_wsne (cilist * a)
-{
-  Namelist *nl;
-  char *s;
-  Vardesc *v, **vd, **vde;
-  ftnint number, type;
-  ftnlen *dims;
-  ftnlen size;
-  extern ftnlen f__typesize[];
-
-  nl = (Namelist *) a->cifmt;
-  PUT ('&');
-  for (s = nl->name; *s; s++)
-    PUT (*s);
-  PUT (' ');
-  f__Aquote = 1;
-  vd = nl->vars;
-  vde = vd + nl->nvars;
-  while (vd < vde)
-    {
-      v = *vd++;
-      s = v->name;
-#ifdef No_Extra_Namelist_Newlines
-      if (f__recpos + strlen (s) + 2 >= L_len)
-#endif
-	nl_donewrec ();
-      while (*s)
-	PUT (*s++);
-      PUT (' ');
-      PUT ('=');
-      number = (dims = v->dims) ? dims[1] : 1;
-      type = v->type;
-      if (type < 0)
-	{
-	  size = -type;
-	  type = TYCHAR;
-	}
-      else
-	size = f__typesize[type];
-      l_write (&number, v->addr, size, type);
-      if (vd < vde)
-	{
-	  if (f__recpos + 2 >= L_len)
-	    nl_donewrec ();
-	  PUT (',');
-	  PUT (' ');
-	}
-      else if (f__recpos + 1 >= L_len)
-	nl_donewrec ();
-    }
-  f__Aquote = 0;
-  PUT ('/');
-}
diff --git a/contrib/libf2c/libU77/COPYING.LIB b/contrib/libf2c/libU77/COPYING.LIB
deleted file mode 100644
index b1e3f5a2638..00000000000
--- a/contrib/libf2c/libU77/COPYING.LIB
+++ /dev/null
@@ -1,504 +0,0 @@
-		  GNU LESSER GENERAL PUBLIC LICENSE
-		       Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
-     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL.  It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
-			    Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
-  This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it.  You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
-  When we speak of free software, we are referring to freedom of use,
-not price.  Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
-  To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights.  These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
-  For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you.  You must make sure that they, too, receive or can get the source
-code.  If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it.  And you must show them these terms so they know their rights.
-
-  We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
-  To protect each distributor, we want to make it very clear that
-there is no warranty for the free library.  Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
-  Finally, software patents pose a constant threat to the existence of
-any free program.  We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder.  Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
-  Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License.  This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License.  We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
-  When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library.  The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom.  The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
-  We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License.  It also provides other free software developers Less
-of an advantage over competing non-free programs.  These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries.  However, the Lesser license provides advantages in certain
-special circumstances.
-
-  For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard.  To achieve this, non-free programs must be
-allowed to use the library.  A more frequent case is that a free
-library does the same job as widely used non-free libraries.  In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
-  In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software.  For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
-  Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.  Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library".  The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
-		  GNU LESSER GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
-  A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
-  The "Library", below, refers to any such software library or work
-which has been distributed under these terms.  A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language.  (Hereinafter, translation is
-included without limitation in the term "modification".)
-
-  "Source code" for a work means the preferred form of the work for
-making modifications to it.  For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
-  Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it).  Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-  
-  1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
-  You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
-  2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) The modified work must itself be a software library.
-
-    b) You must cause the files modified to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    c) You must cause the whole of the work to be licensed at no
-    charge to all third parties under the terms of this License.
-
-    d) If a facility in the modified Library refers to a function or a
-    table of data to be supplied by an application program that uses
-    the facility, other than as an argument passed when the facility
-    is invoked, then you must make a good faith effort to ensure that,
-    in the event an application does not supply such function or
-    table, the facility still operates, and performs whatever part of
-    its purpose remains meaningful.
-
-    (For example, a function in a library to compute square roots has
-    a purpose that is entirely well-defined independent of the
-    application.  Therefore, Subsection 2d requires that any
-    application-supplied function or table used by this function must
-    be optional: if the application does not supply it, the square
-    root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library.  To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License.  (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.)  Do not make any other change in
-these notices.
-
-  Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
-  This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
-  4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
-  If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library".  Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
-  However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library".  The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
-  When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library.  The
-threshold for this to be true is not precisely defined by law.
-
-  If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work.  (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
-  Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
-  6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
-  You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License.  You must supply a copy of this License.  If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License.  Also, you must do one
-of these things:
-
-    a) Accompany the work with the complete corresponding
-    machine-readable source code for the Library including whatever
-    changes were used in the work (which must be distributed under
-    Sections 1 and 2 above); and, if the work is an executable linked
-    with the Library, with the complete machine-readable "work that
-    uses the Library", as object code and/or source code, so that the
-    user can modify the Library and then relink to produce a modified
-    executable containing the modified Library.  (It is understood
-    that the user who changes the contents of definitions files in the
-    Library will not necessarily be able to recompile the application
-    to use the modified definitions.)
-
-    b) Use a suitable shared library mechanism for linking with the
-    Library.  A suitable mechanism is one that (1) uses at run time a
-    copy of the library already present on the user's computer system,
-    rather than copying library functions into the executable, and (2)
-    will operate properly with a modified version of the library, if
-    the user installs one, as long as the modified version is
-    interface-compatible with the version that the work was made with.
-
-    c) Accompany the work with a written offer, valid for at
-    least three years, to give the same user the materials
-    specified in Subsection 6a, above, for a charge no more
-    than the cost of performing this distribution.
-
-    d) If distribution of the work is made by offering access to copy
-    from a designated place, offer equivalent access to copy the above
-    specified materials from the same place.
-
-    e) Verify that the user has already received a copy of these
-    materials or that you have already sent this user a copy.
-
-  For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it.  However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
-  It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system.  Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
-  7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
-    a) Accompany the combined library with a copy of the same work
-    based on the Library, uncombined with any other library
-    facilities.  This must be distributed under the terms of the
-    Sections above.
-
-    b) Give prominent notice with the combined library of the fact
-    that part of it is a work based on the Library, and explaining
-    where to find the accompanying uncombined form of the same work.
-
-  8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License.  Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License.  However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
-  9. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Library or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
-  10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
-  11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded.  In such case, this License incorporates the limitation as if
-written in the body of this License.
-
-  13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation.  If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
-  14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission.  For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this.  Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
-			    NO WARRANTY
-
-  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
-
-           How to Apply These Terms to Your New Libraries
-
-  If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change.  You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
-  To apply these terms, attach the following notices to the library.  It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
-    
-    Copyright (C)   
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the
-  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
-  , 1 April 1990
-  Ty Coon, President of Vice
-
-That's all there is to it!
-
-
diff --git a/contrib/libf2c/libU77/Makefile.in b/contrib/libf2c/libU77/Makefile.in
deleted file mode 100644
index 09b1b2a20c5..00000000000
--- a/contrib/libf2c/libU77/Makefile.in
+++ /dev/null
@@ -1,187 +0,0 @@
-# Makefile for GNU F77 compiler runtime, libc interface.
-# Copyright (C) 1995-1998, 2001 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of the GNU Fortran libU77 library.
-#
-#The GNU Fortran libU77 library is free software; you can redistribute
-#it and/or modify it under the terms of the GNU Library General Public
-#License as published by the Free Software Foundation; either version 2,
-#or (at your option) any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU Library General Public License for more details.
-#
-#You should have received a copy of the GNU General Public License
-#along with GNU Fortran; see the file COPYING.  If not, write to
-#the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
-#02111-1307, USA.
-
-#### Start of system configuration section. ####
-
-# $(srcdir) must be set to the g77 runtime libU77 source directory
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-# configure sets this to all the -D options appropriate for the
-# configuration.
-DEFS = @DEFS@
-LIBS = @LIBS@
-
-F2C_H_DIR = @srcdir@/..
-G2C_H_DIR = ..
-CC = @CC@
-CFLAGS = @CFLAGS@
-CPPFLAGS = @CPPFLAGS@
-@SET_MAKE@
-
-SHELL = @SHELL@
-
-#### End of system configuration section. ####
-
-# fio.h is in libI77.  config.h is in `.'.
-ALL_CFLAGS = -I. -I$(srcdir) -I$(F2C_H_DIR)/libI77 -I$(G2C_H_DIR) \
-             -I$(F2C_H_DIR) $(CPPFLAGS) $(DEFS) $(WARN_CFLAGS) $(CFLAGS)
-
-# This could probably be done more elegantly, but it's currently
-# just for running the u77-test test.
-G77DIR = ../../../gcc/
-
-.SUFFIXES:
-.SUFFIXES: .c .lo
-
-.c.lo:
-	@LIBTOOL@ --mode=compile $(CC) -c -DSkip_f2c_Undefs $(ALL_CFLAGS) $<
-
-OBJS =  VersionU.lo gerror_.lo perror_.lo ierrno_.lo itime_.lo time_.lo \
-	unlink_.lo fnum_.lo getpid_.lo getuid_.lo getgid_.lo kill_.lo rand_.lo \
-	srand_.lo irand_.lo sleep_.lo idate_.lo ctime_.lo etime_.lo \
-	dtime_.lo  isatty_.lo ltime_.lo fstat_.lo stat_.lo \
-	lstat_.lo access_.lo link_.lo getlog_.lo ttynam_.lo getcwd_.lo symlnk_.lo \
-        vxttime_.lo vxtidate_.lo gmtime_.lo fdate_.lo secnds_.lo \
-	chdir_.lo chmod_.lo lnblnk_.lo hostnm_.lo rename_.lo fgetc_.lo fputc_.lo \
-        umask_.lo sys_clock_.lo date_.lo second_.lo flush1_.lo mclock_.lo \
-	alarm_.lo datetime_.lo
-SRCS =  Version.c gerror_.c perror_.c ierrno_.c itime_.c time_.c \
-	unlink_.c fnum_.c getpid_.c getuid_.c getgid_.c kill_.c rand_.c \
-	srand_.c irand_.c sleep_.c idate_.c ctime_.c etime_.c \
-	dtime_.c isatty_.c ltime_.c fstat_.c stat_.c \
-	lstat_.c access_.c link_.c getlog_.c ttynam_.c getcwd_.c symlnk_.c \
-        vxttime_.c vxtidate_.c gmtime_.c fdate_.c secnds_.c \
-	chdir_.c chmod_.c lnblnk_.c hostnm_.c rename_.c fgetc_.c fputc_.c \
-	umask_.c sys_clock_.c date_.c second_.c flush1_.c mclock_.c \
-	alarm_.c datetime_.c
-
-all: ../s-libu77
-
-../s-libu77: $(OBJS)
-	-rm -f $@.T $@
-	objs='$(OBJS)'; for name in $$objs; do \
-	  echo libU77/$${name} >> $@.T; done
-	mv $@.T $@
-
-Makefile: Makefile.in config.status
-	$(SHELL) config.status
-
-config.status: configure
-	rm -f config.cache
-	CONFIG_SITE=no-such-file CC='$(CC)' CFLAGS='$(CFLAGS)' \
-	  CPPFLAGS='$(CPPFLAGS)' $(SHELL) config.status --recheck
-
-${srcdir}/configure: configure.in
-	cd ${srcdir} && autoconf
-
-${srcdir}/config.hin: stamp-h.in
-${srcdir}/stamp-h.in: configure.in acconfig.h
-	cd ${srcdir} && autoheader
-	echo timestamp > ${srcdir}/stamp-h.in
-
-config.h: stamp-h
-stamp-h: config.hin config.status
-	$(SHELL) config.status
-	echo timestamp > stamp-h
-
-VersionU.lo: Version.c
-	@LIBTOOL@ --mode=compile $(CC) -c $(ALL_CFLAGS) $(srcdir)/Version.c -o $@
-
-$(OBJS): $(F2C_H_DIR)/f2c.h $(G2C_H_DIR)/g2c.h config.h
-access_.lo: access_.c
-ctime_.lo: ctime_.c
-dtime_.lo: dtime_.c
-etime_.lo: etime_.c
-fnum_.lo: fnum_.c $(F2C_H_DIR)/libI77/fio.h
-fstat_.lo: fstat_.c
-gerror_.lo: gerror_.c
-getcwd_.lo: getcwd_.c
-getgid_.lo: getgid_.c
-getlog_.lo: getlog_.c
-getpid_.lo: getpid_.c
-getuid_.lo: getuid_.c
-idate_.lo: idate_.c
-ierrno_.lo: ierrno_.c
-irand_.lo: irand_.c
-isatty_.lo: isatty_.c $(F2C_H_DIR)/libI77/fio.h
-itime_.lo: itime_.c
-kill_.lo: kill_.c
-link_.lo: link_.c
-loc_.lo: loc_.c
-lstat_.lo: lstat_.c
-ltime_.lo: ltime_.c
-perror_.lo: perror_.c
-qsort.lo: qsort.c
-qsort_.lo: qsort_.c
-rand_.lo: rand_.c
-rename_.lo: rename_.c
-second_.lo: second_.c
-sleep_.lo: sleep_.c
-srand_.lo: srand_.c
-stat_.lo: stat_.c
-symlnk_.lo: symlnk_.c
-time_.lo: time_.c
-ttynam_.lo: ttynam_.c
-unlink_.lo: unlink_.c
-wait_.lo: wait_.c
-vxttime_.lo: vxttime_.c
-vtxidate_.lo: vxtidate_.c
-fdate_.lo: fdate_.c
-gmtime_.lo: gmtime_.c
-secnds_.lo: secnds_.c
-lnblnk_.lo: lnblnk_.c
-chmod_.lo: chmod_.c
-chdir_.lo: chdir_.c
-hostnm_.lo: hostnm_.c
-rename_.lo: rename_.c
-fputc_.lo: fputc_.c
-fgetc_.lo: fgetc_.c
-sys_clock_.lo: sys_clock_.c
-date_.lo: date_.c
-umask_.lo: umask_.c
-flush1_.lo: flush1_.c
-mclock_.lo: mclock_.c
-alarm_.lo: alarm_.c
-datetime_.lo: datetime_.c
-
-check:
-	-$(G77DIR)g77 -B$(G77DIR) -L.. -g $(srcdir)/u77-test.f \
-	-lg2c $(LIBS) -lm -o a.out && ./a.out
-	rm -f a.out
-
-install uninstall install-strip dist installcheck installdirs:
-
-mostlyclean:
-	rm -f *.o *.lo a.out
-	rm -rf .libs
-
-clean: mostlyclean
-	rm -f config.log ../s-libu77
-
-distclean: clean
-	rm -f config.cache config.status Makefile config.h stamp.h \
-	  ../s-libu77 configure
-
-maintainer-clean:
-
-.PHONY: mostlyclean clean distclean maintainer-clean all check uninstall \
-        install-strip dist installcheck installdirs archive
diff --git a/contrib/libf2c/libU77/PROJECTS b/contrib/libf2c/libU77/PROJECTS
deleted file mode 100644
index 0cf1383cbf9..00000000000
--- a/contrib/libf2c/libU77/PROJECTS
+++ /dev/null
@@ -1,10 +0,0 @@
-                                                    -*- indented-text-*-
-
-* Interface to strget
-
-* Non-blocking (`asynchronous') i/o (per c.l.f. discussion)
-
-* `ioinit'-type routine for various i/o options
-
-* IEEE/VAX/... number format conversion (or XDR interface).  This
-  might be made optionally transparent per logical unit a la DECtran.
diff --git a/contrib/libf2c/libU77/README b/contrib/libf2c/libU77/README
deleted file mode 100644
index bfedb90bd97..00000000000
--- a/contrib/libf2c/libU77/README
+++ /dev/null
@@ -1,40 +0,0 @@
-19970811						    -*-text-*-
-
-g77 libU77
-----------
-
-This directory contains an implementation of most of the `traditional'
-Unix libU77 routines, mostly an interface to libc and libm routines
-and some extra ones for time and date etc.  It's intended for use with
-g77, to whose configuration procedure it's currently tied, but should
-be compatible with f2c otherwise, if using the same f2c.h.
-
-The contents of libU77 and its interfaces aren't consistent across
-implementations.  This one is mostly taken from documentation for (an
-old version of) the Convex implementation and the v2 SunPro one.
-As of g77 version 0.5.20, most of these routines have been made
-into g77 intrinsics.  Some routines have a version with a name prefixed
-by `vxt', corresponding to the VMS Fortran versions, and these should
-be integrated with g77's intrinsics visibility control.
-
-A few routines are currently missing; in the case of `fork', for
-instance, because they're probably not useful, and in the case of
-`qsort' and those for stream-based i/o handling, because they need
-more effort/research.  The configuration should weed out those few
-which correspond to facilities which may not be present on some Unix
-systems, such as symbolic links.  It's unclear whether the interfaces
-to the native library random number routines should be retained, since
-their implementation is likely to be something one should avoid
-assiduously.
-
-This library has been tested it under SunOS4.1.3 and Irix5.2 and there
-has been some feedback from Linux; presumably potential problems lie
-mainly with systems with impoverished native C library support which
-haven't been properly taken care of with autoconf.
-
-There's another GPL'd implementation of this stuff which I only found
-out about recently (despite having looked) and I haven't yet checked
-how they should be amalgamated.
-
-Dave Love   Aug '95
-(minor changes by Craig Burley  Aug '97)
diff --git a/contrib/libf2c/libU77/Version.c b/contrib/libf2c/libU77/Version.c
deleted file mode 100644
index 45b68a6b141..00000000000
--- a/contrib/libf2c/libU77/Version.c
+++ /dev/null
@@ -1 +0,0 @@
-const char __LIBU77_VERSION__[] = "@(#) LIBU77 VERSION 19980709\n";
diff --git a/contrib/libf2c/libU77/access_.c b/contrib/libf2c/libU77/access_.c
deleted file mode 100644
index 0a2dbce9d78..00000000000
--- a/contrib/libf2c/libU77/access_.c
+++ /dev/null
@@ -1,84 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-
-#include 
-#include 
-#include "f2c.h"
-
-#ifndef R_OK			/* for SVR1-2 */
-#  define R_OK 4
-#endif
-#ifndef W_OK
-#  define W_OK 2
-#endif
-#ifndef X_OK
-#  define X_OK 1
-#endif
-#ifndef F_OK
-#  define F_OK 0
-#endif
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_access_0 (const char *name, const char *mode, ftnlen Lname, ftnlen Lmode)
-{
-  char *buff;
-  int amode, i;
-
-  buff = malloc (Lname + 1);
-  if (!buff)
-    return -1;
-  g_char (name, Lname, buff);
-  amode = 0;
-  for (i = 0; i < Lmode; i++)
-    {
-      switch (mode[i])
-	{
-	case 'r':
-	  amode |= R_OK;
-	  break;
-	case 'w':
-	  amode |= W_OK;
-	  break;
-	case 'x':
-	  amode |= X_OK;
-	  break;
-	case ' ':
-	  amode |= F_OK;
-	  break;		/* as per Sun, at least */
-	default:
-	  return EINVAL;
-	}
-    }
-  i = access (buff, amode);
-  free (buff);
-  return i;
-}
diff --git a/contrib/libf2c/libU77/acconfig.h b/contrib/libf2c/libU77/acconfig.h
deleted file mode 100644
index 778e15410c8..00000000000
--- a/contrib/libf2c/libU77/acconfig.h
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Define as the path of the `chmod' program. */
-#undef CHMOD_PATH
-
-/* Define if your sys/time.h defines struct timezone. */
-#undef HAVE_STRUCT_TIMEZONE
-
-/* Define if your gettimeofday takes only one argument. */
-#undef GETTIMEOFDAY_ONE_ARGUMENT
-
-/* Define if your gettimeofday takes a time zome argument. */
-#undef HAVE_TIMEZONE
diff --git a/contrib/libf2c/libU77/aclocal.m4 b/contrib/libf2c/libU77/aclocal.m4
deleted file mode 100644
index 58f6a675899..00000000000
--- a/contrib/libf2c/libU77/aclocal.m4
+++ /dev/null
@@ -1,69 +0,0 @@
-dnl Check:
-dnl * If we have gettimeofday;
-dnl * If we have struct timezone for use in calling it;
-dnl * If calling it with a timezone pointer actually works -- this is deemed
-dnl   obsolete or undefined on some systems which say you should use a null
-dnl   pointer -- and undefine HAVE_TIMEZONE if so;
-dnl * Whether it only takes one arg.
-AC_DEFUN(LIBU77_GETTIMEOFDAY, [
-  AC_CHECK_FUNCS(gettimeofday)
-  if test "$ac_cv_func_gettimeofday" = yes; then
-    AC_CACHE_CHECK([for struct timezone], g77_cv_struct_timezone,
-      [AC_TRY_COMPILE([#include ],
-      [struct timezone tz;],
-      g77_cv_struct_timezone=yes, g77_cv_struct_timezone=no)])
-    if test $g77_cv_struct_timezone = yes; then
-      dnl It may be that we can't call gettimeofday with a non-null pointer.
-      dnl In that case we'll lie about struct timezone.
-      AC_TRY_RUN([
-#ifdef TIME_WITH_SYS_TIME
-#include 
-#include 
-#else
-#ifdef HAVE_SYS_TIME_H
-#include 
-#else
-#include 
-#endif
-#endif
-main ()
-{
-  struct timeval time;
-  struct timezone dummy;
-  if (gettimeofday (&time, &dummy))
-    exit (1);
-  else
-    exit (0);
-}],
-      [AC_DEFINE(HAVE_TIMEZONE)], ,[AC_DEFINE(HAVE_TIMEZONE)])
-    fi
-    AC_REQUIRE([AC_HEADER_TIME])
-    AC_CACHE_CHECK(whether gettimeofday can accept two arguments,
-      emacs_cv_gettimeofday_two_arguments,
-      AC_TRY_LINK([
-#ifdef TIME_WITH_SYS_TIME
-#include 
-#include 
-#else
-#ifdef HAVE_SYS_TIME_H
-#include 
-#else
-#include 
-#endif
-#endif
-      ],
-      [
-      struct timeval time;
-#ifdef HAVE_TIMEZONE
-      struct timezone dummy;
-#define DUMMY &dummy
-#else
-#define DUMMY NULL
-#endif
-      gettimeofday (&time, DUMMY);],
-      emacs_cv_gettimeofday_two_arguments=yes,
-      emacs_cv_gettimeofday_two_arguments=no))
-    if test $emacs_cv_gettimeofday_two_arguments = no; then
-      AC_DEFINE(GETTIMEOFDAY_ONE_ARGUMENT)
-    fi
-  fi])
diff --git a/contrib/libf2c/libU77/alarm_.c b/contrib/libf2c/libU77/alarm_.c
deleted file mode 100644
index d2c93824490..00000000000
--- a/contrib/libf2c/libU77/alarm_.c
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Copyright (C) 1997, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#if HAVE_UNISTD_H
-#  include 
-#endif
-
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-#ifndef RETSIGTYPE
-/* we shouldn't rely on this... */
-#define RETSIGTYPE void
-#endif
-typedef RETSIGTYPE (*sig_type) ();
-
-#include 
-typedef int (*sig_proc) (int);
-
-#ifndef SIG_ERR
-#define SIG_ERR ((sig_type) -1)
-#endif
-
-integer
-G77_alarm_0 (integer * seconds, sig_proc proc)
-{
-  int status;
-#if defined (HAVE_ALARM) && defined (SIGALRM)
-  if (signal (SIGALRM, (sig_type) proc) == SIG_ERR)
-    status = -1;
-  else
-    status = alarm (*seconds);
-#else /* ! HAVE_ALARM || ! SIGALRM */
-  errno = ENOSYS;
-  status = -1;
-#endif
-  return status;
-}
diff --git a/contrib/libf2c/libU77/chdir_.c b/contrib/libf2c/libU77/chdir_.c
deleted file mode 100644
index bebdeb0a0c6..00000000000
--- a/contrib/libf2c/libU77/chdir_.c
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-
-#include 
-#include "f2c.h"
-
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_chdir_0 (const char *name, const ftnlen Lname)
-{
-  char *buff;
-  int i;
-
-  buff = malloc (Lname + 1);
-  if (!buff)
-    return -1;
-  g_char (name, Lname, buff);
-  i = chdir (buff);
-  free (buff);
-  return i ? errno : 0;
-}
diff --git a/contrib/libf2c/libU77/chmod_.c b/contrib/libf2c/libU77/chmod_.c
deleted file mode 100644
index 86e620cbc2f..00000000000
--- a/contrib/libf2c/libU77/chmod_.c
+++ /dev/null
@@ -1,82 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-
-/* This definitely shouldn't be done this way -- should canibalise
-   chmod(1) from GNU or BSD. */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-#if STDC_HEADERS
-#  include 
-#endif
-
-#include "f2c.h"
-
-#ifndef CHMOD_PATH
-#define CHMOD_PATH "/bin/chmod"
-#endif
-
-extern void s_cat (char *lp, char *rpp[], ftnlen rnp[], ftnlen * np,
-		   ftnlen ll);
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_chmod_0 ( /* const */ char *name, /* const */ char *mode,
-	     const ftnlen Lname, const ftnlen Lmode)
-{
-  char *buff;
-  int i;
-  ftnlen l, l2;
-  ftnlen six = 6;
-  address a[6];
-  ftnlen ii[6];
-  char chmod_path[] = CHMOD_PATH;
-  l = strlen (chmod_path);
-  buff = malloc (Lname + Lmode + l + 3 + 13 + 1);
-  if (!buff)
-    return -1;
-  ii[0] = l;
-  a[0] = chmod_path;
-  ii[1] = 1;
-  a[1] = " ";
-  ii[2] = Lmode;
-  a[2] = mode;
-  ii[3] = 2;
-  a[3] = " '";
-  for (l2 = Lname; (l2 > 1) && (name[l2 - 1] == ' ');)
-    l2--;
-  ii[4] = l2;
-  a[4] = name;
-  ii[5] = 13;
-  a[5] = "' 2>/dev/null";
-  s_cat (buff, a, ii, &six, Lname + Lmode + l + 3 + 13);
-  buff[Lname + Lmode + l + 3 + 13] = '\0';
-  i = system (buff);
-  free (buff);
-  return i;
-}
diff --git a/contrib/libf2c/libU77/config.hin b/contrib/libf2c/libU77/config.hin
deleted file mode 100644
index ba32a44d233..00000000000
--- a/contrib/libf2c/libU77/config.hin
+++ /dev/null
@@ -1,128 +0,0 @@
-/* config.hin.  Generated automatically from configure.in by autoheader 2.13.  */
-
-/* Define to empty if the keyword does not work.  */
-#undef const
-
-/* Define if your struct stat has st_blksize.  */
-#undef HAVE_ST_BLKSIZE
-
-/* Define if your struct stat has st_blocks.  */
-#undef HAVE_ST_BLOCKS
-
-/* Define if your struct stat has st_rdev.  */
-#undef HAVE_ST_RDEV
-
-/* Define to `int' if  doesn't define.  */
-#undef mode_t
-
-/* Define to `int' if  doesn't define.  */
-#undef pid_t
-
-/* Define to `unsigned' if  doesn't define.  */
-#undef size_t
-
-/* Define if you have the ANSI C header files.  */
-#undef STDC_HEADERS
-
-/* Define if you can safely include both  and .  */
-#undef TIME_WITH_SYS_TIME
-
-/* Define if your  declares struct tm.  */
-#undef TM_IN_SYS_TIME
-
-/* Define as the path of the `chmod' program. */
-#undef CHMOD_PATH
-
-/* Define if your gettimeofday takes only one argument. */
-#undef GETTIMEOFDAY_ONE_ARGUMENT
-
-/* Define if your gettimeofday takes a time zome argument. */
-#undef HAVE_TIMEZONE
-
-/* Define if you have the alarm function.  */
-#undef HAVE_ALARM
-
-/* Define if you have the clock function.  */
-#undef HAVE_CLOCK
-
-/* Define if you have the getcwd function.  */
-#undef HAVE_GETCWD
-
-/* Define if you have the getgid function.  */
-#undef HAVE_GETGID
-
-/* Define if you have the gethostname function.  */
-#undef HAVE_GETHOSTNAME
-
-/* Define if you have the getlogin function.  */
-#undef HAVE_GETLOGIN
-
-/* Define if you have the getrusage function.  */
-#undef HAVE_GETRUSAGE
-
-/* Define if you have the gettimeofday function.  */
-#undef HAVE_GETTIMEOFDAY
-
-/* Define if you have the getuid function.  */
-#undef HAVE_GETUID
-
-/* Define if you have the getwd function.  */
-#undef HAVE_GETWD
-
-/* Define if you have the kill function.  */
-#undef HAVE_KILL
-
-/* Define if you have the link function.  */
-#undef HAVE_LINK
-
-/* Define if you have the lstat function.  */
-#undef HAVE_LSTAT
-
-/* Define if you have the strerror function.  */
-#undef HAVE_STRERROR
-
-/* Define if you have the symlink function.  */
-#undef HAVE_SYMLINK
-
-/* Define if you have the times function.  */
-#undef HAVE_TIMES
-
-/* Define if you have the ttyname function.  */
-#undef HAVE_TTYNAME
-
-/* Define if you have the  header file.  */
-#undef HAVE_LIMITS_H
-
-/* Define if you have the  header file.  */
-#undef HAVE_STDLIB_H
-
-/* Define if you have the  header file.  */
-#undef HAVE_STRING_H
-
-/* Define if you have the  header file.  */
-#undef HAVE_SYS_PARAM_H
-
-/* Define if you have the  header file.  */
-#undef HAVE_SYS_TIME_H
-
-/* Define if you have the  header file.  */
-#undef HAVE_SYS_TIMES_H
-
-/* Define if you have the  header file.  */
-#undef HAVE_UNISTD_H
-
-/* Get Single Unix Specification semantics */
-#undef _XOPEN_SOURCE
-
-/* Get Single Unix Specification semantics */
-#undef _XOPEN_SOURCE_EXTENDED
-
-/* Solaris extensions */
-#undef __EXTENSIONS__
-
-/* Get 64-bit file size support */
-#undef _FILE_OFFSET_BITS
-
-/* Get GNU extensions */
-#undef _GNU_SOURCE
-
diff --git a/contrib/libf2c/libU77/configure b/contrib/libf2c/libU77/configure
deleted file mode 100755
index afe63fbeab3..00000000000
--- a/contrib/libf2c/libU77/configure
+++ /dev/null
@@ -1,2066 +0,0 @@
-#! /bin/sh
-
-# Guess values for system-dependent variables and create Makefiles.
-# Generated automatically using autoconf version 2.13 
-# Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc.
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-
-# Defaults:
-ac_help=
-ac_default_prefix=/usr/local
-# Any additions from configure.in:
-
-# Initialize some variables set by options.
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
-exec_prefix=NONE
-host=NONE
-no_create=
-nonopt=NONE
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-target=NONE
-verbose=
-x_includes=NONE
-x_libraries=NONE
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
-
-# Initialize some other variables.
-subdirs=
-MFLAGS= MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-# Maximum number of lines to put in a shell here document.
-ac_max_here_lines=12
-
-ac_prev=
-for ac_option
-do
-
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
-    ac_prev=
-    continue
-  fi
-
-  case "$ac_option" in
-  -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
-  *) ac_optarg= ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case "$ac_option" in
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file="$ac_optarg" ;;
-
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
-
-  -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    eval "enable_${ac_feature}=no" ;;
-
-  -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
-    fi
-    ac_feature=`echo $ac_feature| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "enable_${ac_feature}='$ac_optarg'" ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he)
-    # Omit some internal or obsolete options to make the list less imposing.
-    # This message is too long to be a string in the A/UX 3.1 sh.
-    cat << EOF
-Usage: configure [options] [host]
-Options: [defaults in brackets after descriptions]
-Configuration:
-  --cache-file=FILE       cache test results in FILE
-  --help                  print this message
-  --no-create             do not create output files
-  --quiet, --silent       do not print \`checking...' messages
-  --version               print the version of autoconf that created configure
-Directory and file names:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [same as prefix]
-  --bindir=DIR            user executables in DIR [EPREFIX/bin]
-  --sbindir=DIR           system admin executables in DIR [EPREFIX/sbin]
-  --libexecdir=DIR        program executables in DIR [EPREFIX/libexec]
-  --datadir=DIR           read-only architecture-independent data in DIR
-                          [PREFIX/share]
-  --sysconfdir=DIR        read-only single-machine data in DIR [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data in DIR
-                          [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data in DIR [PREFIX/var]
-  --libdir=DIR            object code libraries in DIR [EPREFIX/lib]
-  --includedir=DIR        C header files in DIR [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc in DIR [/usr/include]
-  --infodir=DIR           info documentation in DIR [PREFIX/info]
-  --mandir=DIR            man documentation in DIR [PREFIX/man]
-  --srcdir=DIR            find the sources in DIR [configure dir or ..]
-  --program-prefix=PREFIX prepend PREFIX to installed program names
-  --program-suffix=SUFFIX append SUFFIX to installed program names
-  --program-transform-name=PROGRAM
-                          run sed PROGRAM on installed program names
-EOF
-    cat << EOF
-Host type:
-  --build=BUILD           configure for building on BUILD [BUILD=HOST]
-  --host=HOST             configure for HOST [guessed]
-  --target=TARGET         configure for TARGET [TARGET=HOST]
-Features and packages:
-  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
-  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --x-includes=DIR        X include files are in DIR
-  --x-libraries=DIR       X library files are in DIR
-EOF
-    if test -n "$ac_help"; then
-      echo "--enable and --with options recognized:$ac_help"
-    fi
-    exit 0 ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir="$ac_optarg" ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir="$ac_optarg" ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix="$ac_optarg" ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix="$ac_optarg" ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir="$ac_optarg" ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers)
-    echo "configure generated by autoconf version 2.13"
-    exit 0 ;;
-
-  -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case "$ac_option" in
-      *=*) ;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "with_${ac_package}='$ac_optarg'" ;;
-
-  -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
-    # Reject names that are not valid shell variable names.
-    if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then
-      { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
-    fi
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    eval "with_${ac_package}=no" ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes="$ac_optarg" ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries="$ac_optarg" ;;
-
-  -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
-    ;;
-
-  *)
-    if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then
-      echo "configure: warning: $ac_option: invalid host type" 1>&2
-    fi
-    if test "x$nonopt" != xNONE; then
-      { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; }
-    fi
-    nonopt="$ac_option"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; }
-fi
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-# File descriptor usage:
-# 0 standard input
-# 1 file creation
-# 2 errors and warnings
-# 3 some systems may open it to /dev/tty
-# 4 used on the Kubota Titan
-# 6 checking for... messages and results
-# 5 compiler messages saved in config.log
-if test "$silent" = yes; then
-  exec 6>/dev/null
-else
-  exec 6>&1
-fi
-exec 5>./config.log
-
-echo "\
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-" 1>&5
-
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Also quote any args containing shell metacharacters.
-ac_configure_args=
-for ac_arg
-do
-  case "$ac_arg" in
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c) ;;
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;;
-  *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
-  ac_configure_args="$ac_configure_args '$ac_arg'" ;;
-  *) ac_configure_args="$ac_configure_args $ac_arg" ;;
-  esac
-done
-
-# NLS nuisances.
-# Only set these to C if already set.  These must not be set unconditionally
-# because not all systems understand e.g. LANG=C (notably SCO).
-# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
-# Non-C LC_CTYPE values break the ctype check.
-if test "${LANG+set}"   = set; then LANG=C;   export LANG;   fi
-if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
-if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
-if test "${LC_CTYPE+set}"    = set; then LC_CTYPE=C;    export LC_CTYPE;    fi
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo > confdefs.h
-
-# A filename unique to this package, relative to the directory that
-# configure is in, which we can look for to find out if srcdir is correct.
-ac_unique_file=access_.c
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_prog=$0
-  ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'`
-  test "x$ac_confdir" = "x$ac_prog" && ac_confdir=.
-  srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; }
-  else
-    { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; }
-  fi
-fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
-fi
-for ac_site_file in $CONFIG_SITE; do
-  if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
-    . "$ac_site_file"
-  fi
-done
-
-if test -r "$cache_file"; then
-  echo "loading cache $cache_file"
-  . $cache_file
-else
-  echo "creating cache $cache_file"
-  > $cache_file
-fi
-
-ac_ext=c
-# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-ac_exeext=
-ac_objext=o
-if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
-  # Stardent Vistra SVR4 grep lacks -e, says ghazi@caip.rutgers.edu.
-  if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
-    ac_n= ac_c='
-' ac_t='	'
-  else
-    ac_n=-n ac_c= ac_t=
-  fi
-else
-  ac_n= ac_c='\c' ac_t=
-fi
-
-
-
-
-
-
-# For g77 we'll set CC to point at the built gcc, but this will get it into
-# the makefiles
-# Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:534: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="gcc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:564: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_prog_rejected=no
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then
-        ac_prog_rejected=yes
-	continue
-      fi
-      ac_cv_prog_CC="cc"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# -gt 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    set dummy "$ac_dir/$ac_word" "$@"
-    shift
-    ac_cv_prog_CC="$@"
-  fi
-fi
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-  if test -z "$CC"; then
-    case "`uname -s`" in
-    *win32* | *WIN32*)
-      # Extract the first word of "cl", so it can be a program name with args.
-set dummy cl; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:615: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CC="cl"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
- ;;
-    esac
-  fi
-  test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
-fi
-
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:648: checking whether we are using GNU C" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.c <&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gcc=yes
-else
-  ac_cv_prog_gcc=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gcc" 1>&6
-
-if test $ac_cv_prog_gcc = yes; then
-  GCC=yes
-else
-  GCC=
-fi
-
-ac_test_CFLAGS="${CFLAGS+set}"
-ac_save_CFLAGS="$CFLAGS"
-CFLAGS=
-echo $ac_n "checking whether ${CC-cc} accepts -g""... $ac_c" 1>&6
-echo "configure:676: checking whether ${CC-cc} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cc_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.c
-if test -z "`${CC-cc} -g -c conftest.c 2>&1`"; then
-  ac_cv_prog_cc_g=yes
-else
-  ac_cv_prog_cc_g=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS="$ac_save_CFLAGS"
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-
-
-# These defines are necessary to get 64-bit file size support.
-# NetBSD 1.4 header files does not support XOPEN_SOURCE == 600, but it
-# handles 64-bit file sizes without needing these defines.
-echo $ac_n "checking whether _XOPEN_SOURCE may be defined""... $ac_c" 1>&6
-echo "configure:712: checking whether _XOPEN_SOURCE may be defined" >&5
-cat > conftest.$ac_ext <
-int main() {
-
-; return 0; }
-EOF
-if { (eval echo configure:722: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  may_use_xopen_source=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  may_use_xopen_source=no
-fi
-rm -f conftest*
-echo "$ac_t""$may_use_xopen_source" 1>&6
-if test $may_use_xopen_source = yes; then
-  cat >> confdefs.h <<\EOF
-#define _XOPEN_SOURCE 600L
-EOF
-
-  # The following is needed by irix6.2 so that struct timeval is declared.
-  cat >> confdefs.h <<\EOF
-#define _XOPEN_SOURCE_EXTENDED 1
-EOF
-
-  # The following is needed by Solaris2.5.1 so that struct timeval is declared.
-  cat >> confdefs.h <<\EOF
-#define __EXTENSIONS__ 1
-EOF
-
-  cat >> confdefs.h <<\EOF
-#define _FILE_OFFSET_BITS 64
-EOF
-
-  # The following is needed by glibc2 so that gethostname is declared.
-  cat >> confdefs.h <<\EOF
-#define _GNU_SOURCE 1
-EOF
-
-fi
-
-
-LIBTOOL='$(SHELL) ../libtool'
-
-
-if test "$CROSS";then
-  ac_cv_c_cross=yes
-else
-  ac_cv_c_cross=no
-fi
-
-test "$AR" || AR=ar
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:772: checking whether ${MAKE-make} sets \${MAKE}" >&5
-set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_prog_make_${ac_make}_set'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftestmake <<\EOF
-all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
-# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
-eval `${MAKE-make} -f conftestmake 2>/dev/null | grep temp=`
-if test -n "$ac_maketemp"; then
-  eval ac_cv_prog_make_${ac_make}_set=yes
-else
-  eval ac_cv_prog_make_${ac_make}_set=no
-fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  SET_MAKE=
-else
-  echo "$ac_t""no" 1>&6
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-
-# Extract the first word of "chmod", so it can be a program name with args.
-set dummy chmod; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:802: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_path_ac_cv_prog_chmod'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  case "$ac_cv_prog_chmod" in
-  /*)
-  ac_cv_path_ac_cv_prog_chmod="$ac_cv_prog_chmod" # Let the user override the test with a path.
-  ;;
-  ?:/*)			 
-  ac_cv_path_ac_cv_prog_chmod="$ac_cv_prog_chmod" # Let the user override the test with a dos path.
-  ;;
-  *)
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS=":"
-  ac_dummy="$PATH"
-  for ac_dir in $ac_dummy; do 
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_path_ac_cv_prog_chmod="$ac_dir/$ac_word"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-  test -z "$ac_cv_path_ac_cv_prog_chmod" && ac_cv_path_ac_cv_prog_chmod="no"
-  ;;
-esac
-fi
-ac_cv_prog_chmod="$ac_cv_path_ac_cv_prog_chmod"
-if test -n "$ac_cv_prog_chmod"; then
-  echo "$ac_t""$ac_cv_prog_chmod" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-if test "$ac_cv_prog_chmod" != no || test "$CROSS"; then
-  MAYBES=chmod_.o
-  cat >> confdefs.h <&6
-echo "configure:846: checking how to run the C preprocessor" >&5
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-    # This must be in double quotes, not single quotes, because CPP may get
-  # substituted into the Makefile and "${CC-cc}" will confuse make.
-  CPP="${CC-cc} -E"
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp.
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:867: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -E -traditional-cpp"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:884: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP="${CC-cc} -nologo -E"
-  cat > conftest.$ac_ext <
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:901: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  :
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP=/lib/cpp
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-fi
-rm -f conftest*
-  ac_cv_prog_CPP="$CPP"
-fi
-  CPP="$ac_cv_prog_CPP"
-else
-  ac_cv_prog_CPP="$CPP"
-fi
-echo "$ac_t""$CPP" 1>&6
-
-echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6
-echo "configure:926: checking for ANSI C header files" >&5
-if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#include 
-#include 
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:939: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  ac_cv_header_stdc=yes
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-cat > conftest.$ac_ext <
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "memchr" >/dev/null 2>&1; then
-  :
-else
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-cat > conftest.$ac_ext <
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "free" >/dev/null 2>&1; then
-  :
-else
-  rm -rf conftest*
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-if test "$cross_compiling" = yes; then
-  :
-else
-  cat > conftest.$ac_ext <
-#define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-#define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int main () { int i; for (i = 0; i < 256; i++)
-if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) exit(2);
-exit (0); }
-
-EOF
-if { (eval echo configure:1006: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
-  :
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -fr conftest*
-  ac_cv_header_stdc=no
-fi
-rm -fr conftest*
-fi
-
-fi
-fi
-
-echo "$ac_t""$ac_cv_header_stdc" 1>&6
-if test $ac_cv_header_stdc = yes; then
-  cat >> confdefs.h <<\EOF
-#define STDC_HEADERS 1
-EOF
-
-fi
-
-echo $ac_n "checking whether time.h and sys/time.h may both be included""... $ac_c" 1>&6
-echo "configure:1030: checking whether time.h and sys/time.h may both be included" >&5
-if eval "test \"`echo '$''{'ac_cv_header_time'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#include 
-int main() {
-struct tm *tp;
-; return 0; }
-EOF
-if { (eval echo configure:1044: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_header_time=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_header_time=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_header_time" 1>&6
-if test $ac_cv_header_time = yes; then
-  cat >> confdefs.h <<\EOF
-#define TIME_WITH_SYS_TIME 1
-EOF
-
-fi
-
-for ac_hdr in limits.h unistd.h sys/time.h string.h stdlib.h \
-  sys/param.h sys/times.h
-do
-ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
-echo "configure:1069: checking for $ac_hdr" >&5
-if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:1079: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
-if test -z "$ac_err"; then
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=yes"
-else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_header_$ac_safe=no"
-fi
-rm -f conftest*
-fi
-if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_hdr=HAVE_`echo $ac_hdr | sed 'y%abcdefghijklmnopqrstuvwxyz./-%ABCDEFGHIJKLMNOPQRSTUVWXYZ___%'`
-  cat >> confdefs.h <&6
-fi
-done
-
-
-echo $ac_n "checking for working const""... $ac_c" 1>&6
-echo "configure:1107: checking for working const" >&5
-if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <j = 5;
-}
-{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
-  const int foo = 10;
-}
-
-; return 0; }
-EOF
-if { (eval echo configure:1161: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_c_const=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_c_const=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_c_const" 1>&6
-if test $ac_cv_c_const = no; then
-  cat >> confdefs.h <<\EOF
-#define const 
-EOF
-
-fi
-
-echo $ac_n "checking for size_t""... $ac_c" 1>&6
-echo "configure:1182: checking for size_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#if STDC_HEADERS
-#include 
-#include 
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "(^|[^a-zA-Z_0-9])size_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
-  rm -rf conftest*
-  ac_cv_type_size_t=yes
-else
-  rm -rf conftest*
-  ac_cv_type_size_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_size_t" 1>&6
-if test $ac_cv_type_size_t = no; then
-  cat >> confdefs.h <<\EOF
-#define size_t unsigned
-EOF
-
-fi
-
-echo $ac_n "checking for mode_t""... $ac_c" 1>&6
-echo "configure:1215: checking for mode_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_mode_t'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#if STDC_HEADERS
-#include 
-#include 
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "(^|[^a-zA-Z_0-9])mode_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
-  rm -rf conftest*
-  ac_cv_type_mode_t=yes
-else
-  rm -rf conftest*
-  ac_cv_type_mode_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_mode_t" 1>&6
-if test $ac_cv_type_mode_t = no; then
-  cat >> confdefs.h <<\EOF
-#define mode_t int
-EOF
-
-fi
-
-
-echo $ac_n "checking for pid_t""... $ac_c" 1>&6
-echo "configure:1249: checking for pid_t" >&5
-if eval "test \"`echo '$''{'ac_cv_type_pid_t'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#if STDC_HEADERS
-#include 
-#include 
-#endif
-EOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  egrep "(^|[^a-zA-Z_0-9])pid_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
-  rm -rf conftest*
-  ac_cv_type_pid_t=yes
-else
-  rm -rf conftest*
-  ac_cv_type_pid_t=no
-fi
-rm -f conftest*
-
-fi
-echo "$ac_t""$ac_cv_type_pid_t" 1>&6
-if test $ac_cv_type_pid_t = no; then
-  cat >> confdefs.h <<\EOF
-#define pid_t int
-EOF
-
-fi
-
-echo $ac_n "checking for st_blksize in struct stat""... $ac_c" 1>&6
-echo "configure:1282: checking for st_blksize in struct stat" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_st_blksize'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-int main() {
-struct stat s; s.st_blksize;
-; return 0; }
-EOF
-if { (eval echo configure:1295: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_struct_st_blksize=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_struct_st_blksize=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_st_blksize" 1>&6
-if test $ac_cv_struct_st_blksize = yes; then
-  cat >> confdefs.h <<\EOF
-#define HAVE_ST_BLKSIZE 1
-EOF
-
-fi
-
-echo $ac_n "checking for st_blocks in struct stat""... $ac_c" 1>&6
-echo "configure:1316: checking for st_blocks in struct stat" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_st_blocks'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-int main() {
-struct stat s; s.st_blocks;
-; return 0; }
-EOF
-if { (eval echo configure:1329: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_struct_st_blocks=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_struct_st_blocks=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_st_blocks" 1>&6
-if test $ac_cv_struct_st_blocks = yes; then
-  cat >> confdefs.h <<\EOF
-#define HAVE_ST_BLOCKS 1
-EOF
-
-else
-  LIBOBJS="$LIBOBJS fileblocks.${ac_objext}"
-fi
-
-echo $ac_n "checking for st_rdev in struct stat""... $ac_c" 1>&6
-echo "configure:1352: checking for st_rdev in struct stat" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_st_rdev'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-int main() {
-struct stat s; s.st_rdev;
-; return 0; }
-EOF
-if { (eval echo configure:1365: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_struct_st_rdev=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_struct_st_rdev=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_st_rdev" 1>&6
-if test $ac_cv_struct_st_rdev = yes; then
-  cat >> confdefs.h <<\EOF
-#define HAVE_ST_RDEV 1
-EOF
-
-fi
-
-echo $ac_n "checking whether struct tm is in sys/time.h or time.h""... $ac_c" 1>&6
-echo "configure:1386: checking whether struct tm is in sys/time.h or time.h" >&5
-if eval "test \"`echo '$''{'ac_cv_struct_tm'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-int main() {
-struct tm *tp; tp->tm_sec;
-; return 0; }
-EOF
-if { (eval echo configure:1399: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  ac_cv_struct_tm=time.h
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  ac_cv_struct_tm=sys/time.h
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$ac_cv_struct_tm" 1>&6
-if test $ac_cv_struct_tm = sys/time.h; then
-  cat >> confdefs.h <<\EOF
-#define TM_IN_SYS_TIME 1
-EOF
-
-fi
-
-
-echo $ac_n "checking for gethostname in -lsocket""... $ac_c" 1>&6
-echo "configure:1421: checking for gethostname in -lsocket" >&5
-ac_lib_var=`echo socket'_'gethostname | sed 'y%./+-%__p_%'`
-if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  ac_save_LIBS="$LIBS"
-LIBS="-lsocket  $LIBS"
-cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_lib_$ac_lib_var=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_lib_$ac_lib_var=no"
-fi
-rm -f conftest*
-LIBS="$ac_save_LIBS"
-
-fi
-if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-  LIBS="$LIBS -lsocket"
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-
-
-for ac_func in symlink getcwd getwd lstat gethostname strerror clock \
-  getrusage times alarm getlogin getgid getuid kill link ttyname
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1466: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1494: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-
-
-  for ac_func in gettimeofday
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1523: checking for $ac_func" >&5
-if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-/* Override any gcc2 internal prototype to avoid an error.  */
-/* We use char because int might match the return type of a gcc2
-    builtin and then its argument prototype would still apply.  */
-char $ac_func();
-
-int main() {
-
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
-choke me
-#else
-$ac_func();
-#endif
-
-; return 0; }
-EOF
-if { (eval echo configure:1551: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=yes"
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  eval "ac_cv_func_$ac_func=no"
-fi
-rm -f conftest*
-fi
-
-if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
-    ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`
-  cat >> confdefs.h <&6
-fi
-done
-
-  if test "$ac_cv_func_gettimeofday" = yes; then
-    echo $ac_n "checking for struct timezone""... $ac_c" 1>&6
-echo "configure:1577: checking for struct timezone" >&5
-if eval "test \"`echo '$''{'g77_cv_struct_timezone'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-int main() {
-struct timezone tz;
-; return 0; }
-EOF
-if { (eval echo configure:1589: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  g77_cv_struct_timezone=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  g77_cv_struct_timezone=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$g77_cv_struct_timezone" 1>&6
-    if test $g77_cv_struct_timezone = yes; then
-                  if test "$cross_compiling" = yes; then
-  cat >> confdefs.h <<\EOF
-#define HAVE_TIMEZONE 1
-EOF
-
-else
-  cat > conftest.$ac_ext <
-#include 
-#else
-#ifdef HAVE_SYS_TIME_H
-#include 
-#else
-#include 
-#endif
-#endif
-main ()
-{
-  struct timeval time;
-  struct timezone dummy;
-  if (gettimeofday (&time, &dummy))
-    exit (1);
-  else
-    exit (0);
-}
-EOF
-if { (eval echo configure:1633: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
-then
-  cat >> confdefs.h <<\EOF
-#define HAVE_TIMEZONE 1
-EOF
-
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-fi
-rm -fr conftest*
-fi
-
-    fi
-    
-    echo $ac_n "checking whether gettimeofday can accept two arguments""... $ac_c" 1>&6
-echo "configure:1649: checking whether gettimeofday can accept two arguments" >&5
-if eval "test \"`echo '$''{'emacs_cv_gettimeofday_two_arguments'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.$ac_ext <
-#include 
-#else
-#ifdef HAVE_SYS_TIME_H
-#include 
-#else
-#include 
-#endif
-#endif
-      
-int main() {
-
-      struct timeval time;
-#ifdef HAVE_TIMEZONE
-      struct timezone dummy;
-#define DUMMY &dummy
-#else
-#define DUMMY NULL
-#endif
-      gettimeofday (&time, DUMMY);
-; return 0; }
-EOF
-if { (eval echo configure:1680: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  rm -rf conftest*
-  emacs_cv_gettimeofday_two_arguments=yes
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  emacs_cv_gettimeofday_two_arguments=no
-fi
-rm -f conftest*
-fi
-
-echo "$ac_t""$emacs_cv_gettimeofday_two_arguments" 1>&6
-    if test $emacs_cv_gettimeofday_two_arguments = no; then
-      cat >> confdefs.h <<\EOF
-#define GETTIMEOFDAY_ONE_ARGUMENT 1
-EOF
-
-    fi
-  fi
-
-test $ac_cv_func_symlink = yes && MAYBES="$MAYBES symlnk_.o"
-test $ac_cv_func_lstat = yes && MAYBES="$MAYBES lstat_.o"
-test $ac_cv_func_gethostname = yes && MAYBES="$MAYBES hostnm_.o"
-test $ac_cv_func_clock = yes && MAYBES="$MAYBES mclock_.o"
-
-
-
-
-
-
-trap '' 1 2 15
-cat > confcache <<\EOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs.  It is not useful on other systems.
-# If it contains results you don't want to keep, you may remove or edit it.
-#
-# By default, configure uses ./config.cache as the cache file,
-# creating it if it does not exist already.  You can give configure
-# the --cache-file=FILE option to use a different cache file; that is
-# what configure does when it calls configure scripts in
-# subdirectories, so they share the cache.
-# Giving --cache-file=/dev/null disables caching, for debugging configure.
-# config.status only pays attention to the cache file if you give it the
-# --recheck option to rerun configure.
-#
-EOF
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(set) 2>&1 |
-  case `(ac_space=' '; set | grep ac_space) 2>&1` in
-  *ac_space=\ *)
-    # `set' does not quote correctly, so add quotes (double-quote substitution
-    # turns \\\\ into \\, and sed turns \\ into \).
-    sed -n \
-      -e "s/'/'\\\\''/g" \
-      -e "s/^\\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\\)=\\(.*\\)/\\1=\${\\1='\\2'}/p"
-    ;;
-  *)
-    # `set' quotes correctly as required by POSIX, so do not add quotes.
-    sed -n -e 's/^\([a-zA-Z0-9_]*_cv_[a-zA-Z0-9_]*\)=\(.*\)/\1=${\1=\2}/p'
-    ;;
-  esac >> confcache
-if cmp -s $cache_file confcache; then
-  :
-else
-  if test -w $cache_file; then
-    echo "updating cache $cache_file"
-    cat confcache > $cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
-
-trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Any assignment to VPATH causes Sun make to only execute
-# the first set of double-colon rules, so remove it if not needed.
-# If there is a colon in the path, we need to keep it.
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[ 	]*VPATH[ 	]*=[^:]*$/d'
-fi
-
-trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15
-
-DEFS=-DHAVE_CONFIG_H
-
-# Without the "./", some shells look in PATH for config.status.
-: ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS </dev/null | sed 1q`:
-#
-# $0 $ac_configure_args
-#
-# Compiler output produced by configure, useful for debugging
-# configure, is in ./config.log if it exists.
-
-ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
-for ac_option
-do
-  case "\$ac_option" in
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion"
-    exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;;
-  -version | --version | --versio | --versi | --vers | --ver | --ve | --v)
-    echo "$CONFIG_STATUS generated by autoconf version 2.13"
-    exit 0 ;;
-  -help | --help | --hel | --he | --h)
-    echo "\$ac_cs_usage"; exit 0 ;;
-  *) echo "\$ac_cs_usage"; exit 1 ;;
-  esac
-done
-
-ac_given_srcdir=$srcdir
-
-trap 'rm -fr `echo "Makefile config.h:config.hin" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15
-EOF
-cat >> $CONFIG_STATUS < conftest.subs <<\\CEOF
-$ac_vpsub
-$extrasub
-s%@SHELL@%$SHELL%g
-s%@CFLAGS@%$CFLAGS%g
-s%@CPPFLAGS@%$CPPFLAGS%g
-s%@CXXFLAGS@%$CXXFLAGS%g
-s%@FFLAGS@%$FFLAGS%g
-s%@DEFS@%$DEFS%g
-s%@LDFLAGS@%$LDFLAGS%g
-s%@LIBS@%$LIBS%g
-s%@exec_prefix@%$exec_prefix%g
-s%@prefix@%$prefix%g
-s%@program_transform_name@%$program_transform_name%g
-s%@bindir@%$bindir%g
-s%@sbindir@%$sbindir%g
-s%@libexecdir@%$libexecdir%g
-s%@datadir@%$datadir%g
-s%@sysconfdir@%$sysconfdir%g
-s%@sharedstatedir@%$sharedstatedir%g
-s%@localstatedir@%$localstatedir%g
-s%@libdir@%$libdir%g
-s%@includedir@%$includedir%g
-s%@oldincludedir@%$oldincludedir%g
-s%@infodir@%$infodir%g
-s%@mandir@%$mandir%g
-s%@CC@%$CC%g
-s%@LIBTOOL@%$LIBTOOL%g
-s%@AR@%$AR%g
-s%@SET_MAKE@%$SET_MAKE%g
-s%@ac_cv_prog_chmod@%$ac_cv_prog_chmod%g
-s%@CPP@%$CPP%g
-s%@LIBOBJS@%$LIBOBJS%g
-s%@MAYBES@%$MAYBES%g
-s%@CROSS@%$CROSS%g
-s%@RANLIB@%$RANLIB%g
-s%@RANLIB_TEST@%$RANLIB_TEST%g
-
-CEOF
-EOF
-
-cat >> $CONFIG_STATUS <<\EOF
-
-# Split the substitutions into bite-sized pieces for seds with
-# small command number limits, like on Digital OSF/1 and HP-UX.
-ac_max_sed_cmds=90 # Maximum number of lines to put in a sed script.
-ac_file=1 # Number of current file.
-ac_beg=1 # First line for current file.
-ac_end=$ac_max_sed_cmds # Line after last line for current file.
-ac_more_lines=:
-ac_sed_cmds=""
-while $ac_more_lines; do
-  if test $ac_beg -gt 1; then
-    sed "1,${ac_beg}d; ${ac_end}q" conftest.subs > conftest.s$ac_file
-  else
-    sed "${ac_end}q" conftest.subs > conftest.s$ac_file
-  fi
-  if test ! -s conftest.s$ac_file; then
-    ac_more_lines=false
-    rm -f conftest.s$ac_file
-  else
-    if test -z "$ac_sed_cmds"; then
-      ac_sed_cmds="sed -f conftest.s$ac_file"
-    else
-      ac_sed_cmds="$ac_sed_cmds | sed -f conftest.s$ac_file"
-    fi
-    ac_file=`expr $ac_file + 1`
-    ac_beg=$ac_end
-    ac_end=`expr $ac_end + $ac_max_sed_cmds`
-  fi
-done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
-fi
-EOF
-
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case "$ac_file" in
-  *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
-       ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
-  *) ac_file_in="${ac_file}.in" ;;
-  esac
-
-  # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
-
-  # Remove last slash and all that follows it.  Not all systems have dirname.
-  ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
-  if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
-    # The file is in a subdirectory.
-    test ! -d "$ac_dir" && mkdir "$ac_dir"
-    ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`"
-    # A "../" for each directory in $ac_dir_suffix.
-    ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'`
-  else
-    ac_dir_suffix= ac_dots=
-  fi
-
-  case "$ac_given_srcdir" in
-  .)  srcdir=.
-      if test -z "$ac_dots"; then top_srcdir=.
-      else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;;
-  /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;;
-  *) # Relative path.
-    srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix"
-    top_srcdir="$ac_dots$ac_given_srcdir" ;;
-  esac
-
-
-  echo creating "$ac_file"
-  rm -f "$ac_file"
-  configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure."
-  case "$ac_file" in
-  *Makefile*) ac_comsub="1i\\
-# $configure_input" ;;
-  *) ac_comsub= ;;
-  esac
-
-  ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
-  sed -e "$ac_comsub
-s%@configure_input@%$configure_input%g
-s%@srcdir@%$srcdir%g
-s%@top_srcdir@%$top_srcdir%g
-" $ac_file_inputs | (eval "$ac_sed_cmds") > $ac_file
-fi; done
-rm -f conftest.s*
-
-# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where
-# NAME is the cpp macro being defined and VALUE is the value it is being given.
-#
-# ac_d sets the value in "#define NAME VALUE" lines.
-ac_dA='s%^\([ 	]*\)#\([ 	]*define[ 	][ 	]*\)'
-ac_dB='\([ 	][ 	]*\)[^ 	]*%\1#\2'
-ac_dC='\3'
-ac_dD='%g'
-# ac_u turns "#undef NAME" with trailing blanks into "#define NAME VALUE".
-ac_uA='s%^\([ 	]*\)#\([ 	]*\)undef\([ 	][ 	]*\)'
-ac_uB='\([ 	]\)%\1#\2define\3'
-ac_uC=' '
-ac_uD='\4%g'
-# ac_e turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
-ac_eA='s%^\([ 	]*\)#\([ 	]*\)undef\([ 	][ 	]*\)'
-ac_eB='$%\1#\2define\3'
-ac_eC=' '
-ac_eD='%g'
-
-if test "${CONFIG_HEADERS+set}" != set; then
-EOF
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-fi
-for ac_file in .. $CONFIG_HEADERS; do if test "x$ac_file" != x..; then
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case "$ac_file" in
-  *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
-       ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
-  *) ac_file_in="${ac_file}.in" ;;
-  esac
-
-  echo creating $ac_file
-
-  rm -f conftest.frag conftest.in conftest.out
-  ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
-  cat $ac_file_inputs > conftest.in
-
-EOF
-
-# Transform confdefs.h into a sed script conftest.vals that substitutes
-# the proper values into config.h.in to produce config.h.  And first:
-# Protect against being on the right side of a sed subst in config.status.
-# Protect against being in an unquoted here document in config.status.
-rm -f conftest.vals
-cat > conftest.hdr <<\EOF
-s/[\\&%]/\\&/g
-s%[\\$`]%\\&%g
-s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD}%gp
-s%ac_d%ac_u%gp
-s%ac_u%ac_e%gp
-EOF
-sed -n -f conftest.hdr confdefs.h > conftest.vals
-rm -f conftest.hdr
-
-# This sed command replaces #undef with comments.  This is necessary, for
-# example, in the case of _POSIX_SOURCE, which is predefined and required
-# on some systems where configure will not decide to define it.
-cat >> conftest.vals <<\EOF
-s%^[ 	]*#[ 	]*undef[ 	][ 	]*[a-zA-Z_][a-zA-Z_0-9]*%/* & */%
-EOF
-
-# Break up conftest.vals because some shells have a limit on
-# the size of here documents, and old seds have small limits too.
-
-rm -f conftest.tail
-while :
-do
-  ac_lines=`grep -c . conftest.vals`
-  # grep -c gives empty output for an empty file on some AIX systems.
-  if test -z "$ac_lines" || test "$ac_lines" -eq 0; then break; fi
-  # Write a limited-size here document to conftest.frag.
-  echo '  cat > conftest.frag <> $CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.vals >> $CONFIG_STATUS
-  echo 'CEOF
-  sed -f conftest.frag conftest.in > conftest.out
-  rm -f conftest.in
-  mv conftest.out conftest.in
-' >> $CONFIG_STATUS
-  sed 1,${ac_max_here_lines}d conftest.vals > conftest.tail
-  rm -f conftest.vals
-  mv conftest.tail conftest.vals
-done
-rm -f conftest.vals
-
-cat >> $CONFIG_STATUS <<\EOF
-  rm -f conftest.frag conftest.h
-  echo "/* $ac_file.  Generated automatically by configure.  */" > conftest.h
-  cat conftest.in >> conftest.h
-  rm -f conftest.in
-  if cmp -s $ac_file conftest.h 2>/dev/null; then
-    echo "$ac_file is unchanged"
-    rm -f conftest.h
-  else
-    # Remove last slash and all that follows it.  Not all systems have dirname.
-      ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
-      if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
-      # The file is in a subdirectory.
-      test ! -d "$ac_dir" && mkdir "$ac_dir"
-    fi
-    rm -f $ac_file
-    mv conftest.h $ac_file
-  fi
-fi; done
-
-EOF
-cat >> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
-chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
diff --git a/contrib/libf2c/libU77/configure.in b/contrib/libf2c/libU77/configure.in
deleted file mode 100644
index f963bb74abe..00000000000
--- a/contrib/libf2c/libU77/configure.in
+++ /dev/null
@@ -1,124 +0,0 @@
-# Process this file with autoconf to produce a configure script.
-#   Copyright (C) 1995, 1998, 1999 Free Software Foundation, Inc.
-#   Contributed by Dave Love (d.love@dl.ac.uk).
-#
-#This file is part of the GNU Fortran libU77 library.
-#
-#This library is free software; you can redistribute it and/or modify
-#it under the terms of the GNU General Public License as published by
-#the Free Software Foundation; either version 2, or (at your option)
-#any later version.
-#
-#GNU Fortran is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#GNU Library General Public License for more details.
-#
-#You should have received a copy of the GNU Library General Public
-#License along with GNU Fortran; see the file COPYING.  If not, write
-#to Software Foundation, 59 Temple Place - Suite 330, Boston, MA  02111-1307,
-#USA.
-
-AC_PREREQ(2.13)
-AC_INIT(access_.c)
-AC_CONFIG_HEADER(config.h:config.hin)
-
-dnl FIXME AC_PROG_CC wants CC to be able to link things, but it may
-dnl not be able to.
-define([AC_PROG_CC_WORKS],[])
-
-# For g77 we'll set CC to point at the built gcc, but this will get it into
-# the makefiles
-AC_PROG_CC
-
-# These defines are necessary to get 64-bit file size support.
-# NetBSD 1.4 header files does not support XOPEN_SOURCE == 600, but it
-# handles 64-bit file sizes without needing these defines.
-AC_MSG_CHECKING(whether _XOPEN_SOURCE may be defined)
-AC_TRY_COMPILE([#define _XOPEN_SOURCE 600L
-#include ],,
-may_use_xopen_source=yes,
-may_use_xopen_source=no)
-AC_MSG_RESULT($may_use_xopen_source)
-if test $may_use_xopen_source = yes; then
-  AC_DEFINE(_XOPEN_SOURCE, 600L, [Get Single Unix Specification semantics])
-  # The following is needed by irix6.2 so that struct timeval is declared.
-  AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Get Single Unix Specification semantics])
-  # The following is needed by Solaris2.5.1 so that struct timeval is declared.
-  AC_DEFINE(__EXTENSIONS__, 1, [Solaris extensions])
-  AC_DEFINE(_FILE_OFFSET_BITS, 64, [Get 64-bit file size support])
-  # The following is needed by glibc2 so that gethostname is declared.
-  AC_DEFINE(_GNU_SOURCE, 1, [Get GNU extensions])
-fi
-
-dnl Checks for programs.
-
-LIBTOOL='$(SHELL) ../libtool'
-AC_SUBST(LIBTOOL)
-
-dnl AC_C_CROSS
-dnl Gives misleading `(cached)' message from the check.
-if test "$CROSS";then
-  ac_cv_c_cross=yes
-else
-  ac_cv_c_cross=no
-fi
-
-test "$AR" || AR=ar
-AC_SUBST(AR)
-AC_PROG_MAKE_SET
-
-dnl This is only because we (horribly) punt the chmod job to the program at
-dnl present.  Note that the result of this test could be wrong in the cross
-dnl case.
-AC_PATH_PROG(ac_cv_prog_chmod, chmod, no)
-if test "$ac_cv_prog_chmod" != no || test "$CROSS"; then
-  MAYBES=chmod_.o
-  AC_DEFINE_UNQUOTED(CHMOD_PATH,"$ac_cv_prog_chmod")
-else
-  MAYBES=""
-fi
-
-dnl Checks for header files.
-AC_HEADER_STDC
-AC_HEADER_TIME
-AC_CHECK_HEADERS(limits.h unistd.h sys/time.h string.h stdlib.h \
-  sys/param.h sys/times.h)
-
-dnl Checks for typedefs, structures, and compiler characteristics.
-AC_C_CONST
-AC_TYPE_SIZE_T
-AC_TYPE_MODE_T
-
-AC_TYPE_PID_T
-dnl The next 3 demand a dummy fileblocks.o (added to LIBOJS).  We don't use
-dnl LIBOJS, though.
-AC_STRUCT_ST_BLKSIZE
-AC_STRUCT_ST_BLOCKS
-AC_STRUCT_ST_RDEV
-AC_STRUCT_TM
-
-dnl Some systems (SVR4, SCO OpenServer) need -lsocket for gethostname()
-AC_CHECK_LIB(socket, gethostname, [LIBS="$LIBS -lsocket"])
-
-dnl Checks for library functions.
-
-AC_CHECK_FUNCS(symlink getcwd getwd lstat gethostname strerror clock \
-  getrusage times alarm getlogin getgid getuid kill link ttyname)
-
-dnl The standard autoconf HAVE_STRUCT_TIMEZONE doesn't actually check
-dnl for struct timezone, as you might think.  We also need to check how
-dnl to call gettimeofday if we have it.
-LIBU77_GETTIMEOFDAY
-
-test $ac_cv_func_symlink = yes && MAYBES="$MAYBES symlnk_.o"
-test $ac_cv_func_lstat = yes && MAYBES="$MAYBES lstat_.o"
-test $ac_cv_func_gethostname = yes && MAYBES="$MAYBES hostnm_.o"
-test $ac_cv_func_clock = yes && MAYBES="$MAYBES mclock_.o"
-AC_SUBST(MAYBES)
-
-AC_SUBST(CROSS)
-AC_SUBST(RANLIB)
-AC_SUBST(RANLIB_TEST)
-
-AC_OUTPUT(Makefile)
diff --git a/contrib/libf2c/libU77/ctime_.c b/contrib/libf2c/libU77/ctime_.c
deleted file mode 100644
index 56e660562b7..00000000000
--- a/contrib/libf2c/libU77/ctime_.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 1995, 1996, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include "f2c.h"
-
-/* may need sys/time.h & long arg for stime (bsd, svr1-3) */
-
-/* Character */ void
-G77_ctime_0 (char *chtime, const ftnlen Lchtime, longint * xstime)
-{
-  int s_copy ();
-  time_t stime = *xstime;
-
-  /* Allow a length other than 24 for compatibility with what other
-     systems do, despite it being documented as 24. */
-  s_copy (chtime, ctime (&stime), Lchtime, 24);
-}
diff --git a/contrib/libf2c/libU77/date_.c b/contrib/libf2c/libU77/date_.c
deleted file mode 100644
index 973d01470f7..00000000000
--- a/contrib/libf2c/libU77/date_.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/* date_.f -- translated by f2c (version 19961001).
-   You must link the resulting object file with the libraries:
-	-lf2c -lm   (in that order)
-*/
-
-#include "f2c.h"
-
-/* Table of constant values */
-
-static integer c__5 = 5;
-
-/* Subroutine */ int
-G77_date_y2kbug_0 (char *buf, ftnlen buf_len)
-{
-  /* System generated locals */
-  address a__1[5];
-  longint i__1;
-  integer i__2[5];
-  char ch__1[24];
-
-  /* Builtin functions */
-  /* Subroutine */ int s_copy (), s_cat ();
-
-  /* Local variables */
-  static char cbuf[24];
-  extern longint G77_time_0 ();
-  extern /* Character */ void G77_ctime_0 ();
-
-  i__1 = G77_time_0 ();
-  G77_ctime_0 (ch__1, 24L, &i__1);
-  s_copy (cbuf, ch__1, 24L, 24L);
-/* Writing concatenation */
-  i__2[0] = 2, a__1[0] = cbuf + 8;
-  i__2[1] = 1, a__1[1] = "-";
-  i__2[2] = 3, a__1[2] = cbuf + 4;
-  i__2[3] = 1, a__1[3] = "-";
-  i__2[4] = 2, a__1[4] = cbuf + 22;
-  s_cat (buf, a__1, i__2, &c__5, buf_len);
-  return 0;
-}				/* date_ */
-
-#ifdef PIC
-#  include 
-
-const char *G77_Non_Y2K_Compliance_Message =
-  "Call to non Y2K compliant subroutine detected.";
-
-int
-G77_date_y2kbuggy_0 (char *buf __attribute__ ((__unused__)),
-		     ftnlen buf_len __attribute__ ((__unused__)))
-{
-  extern int G77_abort_0() __attribute__ ((noreturn));
-  fprintf (stderr, "%s\n", G77_Non_Y2K_Compliance_Message);
-  G77_abort_0 ();
-}
-#endif
diff --git a/contrib/libf2c/libU77/datetime_.c b/contrib/libf2c/libU77/datetime_.c
deleted file mode 100644
index cd7c7ca0a3b..00000000000
--- a/contrib/libf2c/libU77/datetime_.c
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Copyright (C) 1997, 1998, 1999, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#if defined (_WIN32)
-#include 
-#undef min
-#undef max
-#endif
-#include "f2c.h"
-
-void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-
-int
-G77_date_and_time_0 (char *date, char *fftime, char *zone,
-		     integer * values, ftnlen date_len,
-		     ftnlen fftime_len, ftnlen zone_len)
-{
-  time_t lt = time (<);
-  struct tm ltime = *localtime (<), gtime = *gmtime (<);
-  char dat[9], zon[6], ftim[11];
-  int i, vals[8];
-#if defined (_WIN32)
-    struct _SYSTEMTIME wdattim;
-    GetLocalTime(&wdattim);
-    vals[7] = wdattim.wMilliseconds;
-#else
-  vals[7] = 0;                  /* no STDC/POSIX way to get this */
-  /* GNUish way; maybe use `ftime' on other systems. */
-#endif
-
-  vals[0] = 1900 + ltime.tm_year;
-  vals[1] = 1 + ltime.tm_mon;
-  vals[2] = ltime.tm_mday;
-  /* fixme: year boundaries */
-  vals[3] = (ltime.tm_min - gtime.tm_min +
-	     60 * (ltime.tm_hour - gtime.tm_hour +
-		   24 * (ltime.tm_yday - gtime.tm_yday)));
-  vals[4] = ltime.tm_hour;
-  vals[5] = ltime.tm_min;
-  vals[6] = ltime.tm_sec;
-#if HAVE_GETTIMEOFDAY
-  {
-    struct timeval tp;
-#  if GETTIMEOFDAY_ONE_ARGUMENT
-    if (!gettimeofday (&tp))
-#  else
-#    if HAVE_STRUCT_TIMEZONE
-    struct timezone tzp;
-    /* Some systems such as HPUX, do have struct timezone, but
-       gettimeofday takes void* as the 2nd arg.  However, the effect
-       of passing anything other than a null pointer is unspecified on
-       HPUX.  Configure checks if gettimeofday actually fails with a
-       non-NULL arg and pretends that struct timezone is missing if it
-       does fail.  */
-    if (!gettimeofday (&tp, &tzp))
-#    else
-    if (!gettimeofday (&tp, (void *) 0))
-#    endif /* HAVE_STRUCT_TIMEZONE */
-#  endif /* GETTIMEOFDAY_ONE_ARGUMENT */
-      vals[7] = tp.tv_usec / 1000;
-  }
-#endif /* HAVE_GETTIMEOFDAY */
-  if (values)			/* null pointer for missing optional */
-    for (i = 0; i <= 7; i++)
-      values[i] = vals[i];
-  sprintf (dat, "%04d%02d%02d", vals[0], vals[1], vals[2]);
-  s_copy (date, dat, date_len, 8);
-  if (zone)
-    {
-      sprintf (zon, "%+03d%02d", vals[3] / 60, abs (vals[3] % 60));
-      s_copy (zone, zon, zone_len, 5);
-    }
-  if (fftime)
-    {
-      sprintf (ftim, "%02d%02d%02d.%03d", vals[4], vals[5], vals[6], vals[7]);
-      s_copy (fftime, ftim, fftime_len, 10);
-    }
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/dtime_.c b/contrib/libf2c/libU77/dtime_.c
deleted file mode 100644
index dc9a8639df2..00000000000
--- a/contrib/libf2c/libU77/dtime_.c
+++ /dev/null
@@ -1,174 +0,0 @@
-/* Copyright (C) 1995, 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 
-#if HAVE_SYS_TIMES_H
-#  include 
-#endif
-#if HAVE_SYS_PARAM_H
-#  include 
-#endif
-#if HAVE_GETRUSAGE
-#  include 
-#  include 
-#endif
-#if defined (_WIN32)
-#  include 
-#  undef min
-#  undef max
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-double
-G77_dtime_0 (real tarray[2])
-{
-#if defined (_WIN32)
-  static int win32_platform = -1;
-
-  if (win32_platform == -1)
-    {
-      OSVERSIONINFO osv;
-      osv.dwOSVersionInfoSize = sizeof (osv);
-      GetVersionEx (&osv);
-      win32_platform = osv.dwPlatformId;
-    }
-
-  /* We need to use this hack on non-NT platforms, where the first call
-     returns 0.0 and subsequent ones return the correct value. */
-  if (win32_platform != VER_PLATFORM_WIN32_NT)
-    {
-      static unsigned long long clock_freq;
-      static unsigned long long old_count;
-      unsigned long long count;
-      double delta;
-      LARGE_INTEGER counter_val;
-
-      if (clock_freq == 0)
-	{
-	  LARGE_INTEGER freq;
-	  if (!QueryPerformanceFrequency (&freq))
-	    {
-	      errno = ENOSYS;
-	      return 0.0;
-	    }
-	  else
-	    {
-	      clock_freq = ((unsigned long long) freq.HighPart << 32)
-		+ ((unsigned) freq.LowPart);
-	    }
-	}
-
-      if (!QueryPerformanceCounter (&counter_val))
-	return -1.0;
-
-      count = ((unsigned long long) counter_val.HighPart << 32)
-	+ (unsigned) counter_val.LowPart;
-      delta = ((double) (count - old_count)) / clock_freq;
-      tarray[0] = (float) delta;
-      tarray[1] = 0.0;
-      old_count = count;
-    }
-  else
-    {
-      static unsigned long long old_utime, old_stime;
-      unsigned long long utime, stime;
-      FILETIME creation_time, exit_time, kernel_time, user_time;
-
-      GetProcessTimes (GetCurrentProcess (), &creation_time, &exit_time,
-		       &kernel_time, &user_time);
-      utime = ((unsigned long long) user_time.dwHighDateTime << 32)
-	+ (unsigned) user_time.dwLowDateTime;
-      stime = ((unsigned long long) kernel_time.dwHighDateTime << 32)
-	+ (unsigned) kernel_time.dwLowDateTime;
-
-      tarray[0] = (utime - old_utime) / 1.0e7;
-      tarray[1] = (stime - old_stime) / 1.0e7;
-      old_utime = utime;
-      old_stime = stime;
-    }
-  return tarray[0] + tarray[1];
-
-#elif defined (HAVE_GETRUSAGE) || defined (HAVE_TIMES)
-  /* The getrusage version is only the default for convenience. */
-#ifdef HAVE_GETRUSAGE
-  float utime, stime;
-  static float old_utime = 0.0, old_stime = 0.0;
-  struct rusage rbuff;
-
-  if (getrusage (RUSAGE_SELF, &rbuff) != 0)
-    abort ();
-  utime = (float) (rbuff.ru_utime).tv_sec +
-    (float) (rbuff.ru_utime).tv_usec / 1000000.0;
-  tarray[0] = utime - (float) old_utime;
-  stime = (float) (rbuff.ru_stime).tv_sec +
-    (float) (rbuff.ru_stime).tv_usec / 1000000.0;
-  tarray[1] = stime - old_stime;
-#else /* HAVE_GETRUSAGE */
-  /* For dtime, etime we store the clock tick parameter (clk_tck) the
-     first time either of them is invoked rather than each time.  This
-     approach probably speeds up each invocation by avoiding a system
-     call each time, but means that the overhead of the first call is
-     different to all others. */
-  static long clk_tck = 0;
-  time_t utime, stime;
-  static time_t old_utime = 0, old_stime = 0;
-  struct tms buffer;
-
-/* NeXTStep seems to define _SC_CLK_TCK but not to have sysconf;
-   fixme: does using _POSIX_VERSION help? */
-#  if defined _SC_CLK_TCK && defined _POSIX_VERSION
-  if (!clk_tck)
-    clk_tck = sysconf (_SC_CLK_TCK);
-#  elif defined CLOCKS_PER_SECOND
-  if (!clk_tck)
-    clk_tck = CLOCKS_PER_SECOND;
-#  elif defined CLK_TCK
-  if (!clk_tck)
-    clk_tck = CLK_TCK;
-#  elif defined HZ
-  if (!clk_tck)
-    clk_tck = HZ;
-#  elif defined HAVE_GETRUSAGE
-#  else
-#error Dont know clock tick length
-#  endif
-  if (times (&buffer) == (clock_t) - 1)
-    return -1.0;
-  utime = buffer.tms_utime;
-  stime = buffer.tms_stime;
-  tarray[0] = ((float) (utime - old_utime)) / (float) clk_tck;
-  tarray[1] = ((float) (stime - old_stime)) / (float) clk_tck;
-#endif /* HAVE_GETRUSAGE */
-  old_utime = utime;
-  old_stime = stime;
-  return (tarray[0] + tarray[1]);
-#else /* ! HAVE_GETRUSAGE && ! HAVE_TIMES */
-  errno = ENOSYS;
-  return 0.0;
-#endif /* ! HAVE_GETRUSAGE && ! HAVE_TIMES */
-}
diff --git a/contrib/libf2c/libU77/etime_.c b/contrib/libf2c/libU77/etime_.c
deleted file mode 100644
index d0edb2fbcd3..00000000000
--- a/contrib/libf2c/libU77/etime_.c
+++ /dev/null
@@ -1,163 +0,0 @@
-/* Copyright (C) 1995, 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 
-#if HAVE_SYS_TIMES_H
-#  include 
-#endif
-#if HAVE_SYS_PARAM_H
-#  include 
-#endif
-#if HAVE_GETRUSAGE
-#  include 
-#  include 
-#endif
-#if defined (_WIN32)
-#  include 
-#  undef min
-#  undef max
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-double
-G77_etime_0 (real tarray[2])
-{
-#if defined (_WIN32)
-  static int win32_platform = -1;
-  double usertime, systime;
-
-  if (win32_platform == -1)
-    {
-      OSVERSIONINFO osv;
-      osv.dwOSVersionInfoSize = sizeof (osv);
-      GetVersionEx (&osv);
-      win32_platform = osv.dwPlatformId;
-    }
-
-  /* non-NT platforms don't have a clue as to how long a process has
-     been running, so simply return the uptime. Bad judgement call? */
-  if (win32_platform != VER_PLATFORM_WIN32_NT)
-    {
-      static unsigned long long clock_freq;
-      static unsigned long long old_count;
-      unsigned long long count;
-      LARGE_INTEGER counter_val;
-
-      if (clock_freq == 0)
-	{
-	  LARGE_INTEGER freq;
-	  if (!QueryPerformanceFrequency (&freq))
-	    {
-	      errno = ENOSYS;
-	      return 0.0;
-	    }
-	  else
-	    {
-	      clock_freq = ((unsigned long long) freq.HighPart << 32)
-		+ ((unsigned) freq.LowPart);
-	      if (!QueryPerformanceCounter (&counter_val))
-		return -1.0;
-	      old_count = ((unsigned long long) counter_val.HighPart << 32)
-		+ (unsigned) counter_val.LowPart;
-	    }
-	}
-
-      if (!QueryPerformanceCounter (&counter_val))
-	return -1.0;
-
-      count = ((unsigned long long) counter_val.HighPart << 32)
-	+ (unsigned) counter_val.LowPart;
-      tarray[0] = usertime = (double) (count - old_count) / clock_freq;
-      tarray[1] = systime = 0.0;
-    }
-  else
-    {
-      FILETIME creation_time, exit_time, kernel_time, user_time;
-      unsigned long long utime, stime;
-
-      GetProcessTimes (GetCurrentProcess (), &creation_time, &exit_time,
-		       &kernel_time, &user_time);
-      utime = ((unsigned long long) user_time.dwHighDateTime << 32)
-	+ (unsigned) user_time.dwLowDateTime;
-      stime = ((unsigned long long) kernel_time.dwHighDateTime << 32)
-	+ (unsigned) kernel_time.dwLowDateTime;
-
-      tarray[0] = usertime = utime / 1.0e7;
-      tarray[1] = systime = stime / 1.0e7;
-    }
-  return usertime + systime;
-
-#elif defined (HAVE_GETRUSAGE) || defined (HAVE_TIMES)
-  /* The getrusage version is only the default for convenience. */
-#ifdef HAVE_GETRUSAGE
-  struct rusage rbuff;
-
-  if (getrusage (RUSAGE_SELF, &rbuff) != 0)
-    abort ();
-  tarray[0] = ((float) (rbuff.ru_utime).tv_sec +
-	       (float) (rbuff.ru_utime).tv_usec / 1000000.0);
-  tarray[1] = ((float) (rbuff.ru_stime).tv_sec +
-	       (float) (rbuff.ru_stime).tv_usec / 1000000.0);
-#else /* HAVE_GETRUSAGE */
-  /* For dtime, etime we store the clock tick parameter (clk_tck) the
-     first time either of them is invoked rather than each time.  This
-     approach probably speeds up each invocation by avoiding a system
-     call each time, but means that the overhead of the first call is
-     different to all others. */
-  static long clk_tck = 0;
-  struct tms buffer;
-
-/* NeXTStep seems to define _SC_CLK_TCK but not to have sysconf;
-   fixme: does using _POSIX_VERSION help? */
-#  if defined _SC_CLK_TCK && defined _POSIX_VERSION
-  if (!clk_tck)
-    clk_tck = sysconf (_SC_CLK_TCK);
-#  elif defined CLOCKS_PER_SECOND
-  if (!clk_tck)
-    clk_tck = CLOCKS_PER_SECOND;
-#  elif defined CLK_TCK
-  if (!clk_tck)
-    clk_tck = CLK_TCK;
-#  elif defined HZ
-  if (!clk_tck)
-    clk_tck = HZ;
-#  elif defined HAVE_GETRUSAGE
-#  else
-#error Dont know clock tick length
-#  endif
-  if (times (&buffer) == (clock_t) - 1)
-    return -1.0;
-  tarray[0] = (float) buffer.tms_utime / (float) clk_tck;
-  tarray[1] = (float) buffer.tms_stime / (float) clk_tck;
-#endif /* HAVE_GETRUSAGE */
-  return (tarray[0] + tarray[1]);
-#else /* ! HAVE_GETRUSAGE && ! HAVE_TIMES */
-  errno = ENOSYS;
-  return 0.0;
-#endif /* ! HAVE_GETRUSAGE && ! HAVE_TIMES */
-}
diff --git a/contrib/libf2c/libU77/fdate_.c b/contrib/libf2c/libU77/fdate_.c
deleted file mode 100644
index d710a5cb3be..00000000000
--- a/contrib/libf2c/libU77/fdate_.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Copyright (C) 1995, 1996, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-
-#include "f2c.h"
-
-/* NB. this implementation is for a character*24 function.  There's
-   also a subroutine version.  Of course, the calling convention is
-   essentially the same for both. */
-
-/* Character *24 */ void
-G77_fdate_0 (char *ret_val, ftnlen ret_val_len)
-{
-  int s_copy ();
-  time_t tloc;
-  tloc = time (NULL);
-  /* Allow a length other than 24 for compatibility with what other
-     systems do, despite it being documented as 24. */
-  s_copy (ret_val, ctime ((time_t *) & tloc), ret_val_len, 24);
-}
diff --git a/contrib/libf2c/libU77/fgetc_.c b/contrib/libf2c/libU77/fgetc_.c
deleted file mode 100644
index ec94829a6a1..00000000000
--- a/contrib/libf2c/libU77/fgetc_.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Copyright (C) 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include "f2c.h"
-#include "fio.h"
-
-integer
-G77_fgetc_0 (const integer * lunit, char *c, ftnlen Lc)
-{
-  int err;
-  FILE *f = f__units[*lunit].ufd;
-
-  if (*lunit >= MXUNIT || *lunit < 0)
-    return 101;			/* bad unit error */
-  err = getc (f);
-  if (err == EOF)
-    {
-      if (feof (f))
-	return -1;
-      else
-	return ferror (f);
-    }
-  else
-    {
-      if (Lc == 0)
-	return 0;
-
-      c[0] = err;
-      while (--Lc)
-	*++c = ' ';
-      return 0;
-    }
-}
-
-integer
-G77_fget_0 (char *c, const ftnlen Lc)
-{
-  integer five = 5;
-
-  return G77_fgetc_0 (&five, c, Lc);
-}
diff --git a/contrib/libf2c/libU77/flush1_.c b/contrib/libf2c/libU77/flush1_.c
deleted file mode 100644
index 7327593be8f..00000000000
--- a/contrib/libf2c/libU77/flush1_.c
+++ /dev/null
@@ -1,40 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include "f2c.h"
-#include "fio.h"
-
-/* This flushes a single unit, c.f. libI77 version. */
-
-extern integer G77_fnum_0 (integer *);
-
-/* Subroutine */ int
-G77_flush1_0 (const integer * lunit)
-{
-  if (*lunit >= MXUNIT || *lunit < 0)
-    err (1, 101, "flush");
-  /* f__units is a table of descriptions for the unit numbers (defined
-     in io.h) with file descriptors rather than streams */
-  if (f__units[*lunit].ufd != NULL && f__units[*lunit].uwrt)
-    fflush (f__units[*lunit].ufd);
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/fnum_.c b/contrib/libf2c/libU77/fnum_.c
deleted file mode 100644
index 27cadec287a..00000000000
--- a/contrib/libf2c/libU77/fnum_.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include "f2c.h"
-#include "fio.h"
-
-integer
-G77_fnum_0 (integer * lunit)
-{
-  if (*lunit >= MXUNIT || *lunit < 0)
-    err (1, 101, "fnum");
-
-  if (f__units[*lunit].ufd == NULL)
-    err (1, 114, "fnum");
-
-  /* f__units is a table of descriptions for the unit numbers (defined
-     in io.h).  Use file descriptor (ufd) and fileno rather than udev
-     field since udev is unix specific */
-  return fileno (f__units[*lunit].ufd);
-}
diff --git a/contrib/libf2c/libU77/fputc_.c b/contrib/libf2c/libU77/fputc_.c
deleted file mode 100644
index 7e45dd4140c..00000000000
--- a/contrib/libf2c/libU77/fputc_.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Copyright (C) 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include "f2c.h"
-#include "fio.h"
-
-integer
-G77_fputc_0 (const integer * lunit, const char *c,
-	     const ftnlen Lc __attribute__ ((__unused__)))
-{
-  int err;
-  FILE *f = f__units[*lunit].ufd;
-
-  if (*lunit >= MXUNIT || *lunit < 0)
-    return 101;			/* bad unit error */
-  err = putc (c[0], f);
-  if (err == EOF)
-    {
-      if (feof (f))
-	return -1;
-      else
-	return ferror (f);
-    }
-  else
-    return 0;
-}
-
-integer
-G77_fput_0 (const char *c, const ftnlen Lc)
-{
-  integer six = 6;
-
-  return G77_fputc_0 (&six, c, Lc);
-}
diff --git a/contrib/libf2c/libU77/fstat_.c b/contrib/libf2c/libU77/fstat_.c
deleted file mode 100644
index 7fd439c2a40..00000000000
--- a/contrib/libf2c/libU77/fstat_.c
+++ /dev/null
@@ -1,66 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include "f2c.h"
-#include "fio.h"
-#include 
-#include 
-
-extern integer G77_fnum_0 (const integer *);
-
-integer
-G77_fstat_0 (const integer * lunit, integer statb[13])
-{
-  int err;
-  struct stat buf;
-
-  if (f__init != 1) f_init();
-  err = fstat (G77_fnum_0 (lunit), &buf);
-  statb[0] = buf.st_dev;
-  statb[1] = buf.st_ino;
-  statb[2] = buf.st_mode;
-  statb[3] = buf.st_nlink;
-  statb[4] = buf.st_uid;
-  statb[5] = buf.st_gid;
-#if HAVE_ST_RDEV
-  statb[6] = buf.st_rdev;	/* not posix */
-#else
-  statb[6] = 0;
-#endif
-  statb[7] = buf.st_size;
-  statb[8] = buf.st_atime;
-  statb[9] = buf.st_mtime;
-  statb[10] = buf.st_ctime;
-#if HAVE_ST_BLKSIZE
-  statb[11] = buf.st_blksize;	/* not posix */
-#else
-  statb[11] = -1;
-#endif
-#if HAVE_ST_BLOCKS
-  statb[12] = buf.st_blocks;	/* not posix */
-#else
-  statb[12] = -1;
-#endif
-  return err;
-}
diff --git a/contrib/libf2c/libU77/gerror_.c b/contrib/libf2c/libU77/gerror_.c
deleted file mode 100644
index 252440dc85b..00000000000
--- a/contrib/libf2c/libU77/gerror_.c
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include "f2c.h"
-
-#ifndef HAVE_STRERROR
-extern char *sys_errlist[];
-#    define strerror(i) (sys_errlist[i])
-#endif
-extern void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-/* Subroutine */ int
-G77_gerror_0 (char *str, ftnlen Lstr)
-{
-  char *s;
-
-  s = strerror (errno);
-  s_copy (str, s, Lstr, strlen (s));
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/getcwd_.c b/contrib/libf2c/libU77/getcwd_.c
deleted file mode 100644
index 75277af0f74..00000000000
--- a/contrib/libf2c/libU77/getcwd_.c
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Copyright (C) 1995, 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include 		/* for NULL */
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-#if HAVE_GETCWD
-
-#ifdef HAVE_UNISTD_H
-#  include 
-#else
-extern char *getcwd ();
-#endif
-
-extern void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-integer
-G77_getcwd_0 (char *str, const ftnlen Lstr)
-{
-  int i;
-  char *ret;
-
-  ret = getcwd (str, Lstr);
-  if (ret == NULL)
-    return errno;
-  for (i = strlen (str); i < Lstr; i++)
-    str[i] = ' ';
-  return 0;
-}
-
-#elif HAVE_GETWD		/* HAVE_GETCWD */
-
-/* getwd usage taken from SunOS4 man */
-
-#  include 
-extern char *getwd ();
-extern void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-integer
-G77_getcwd_0 (char *str, const ftnlen Lstr)
-{
-  char pathname[MAXPATHLEN];
-  size_t l;
-
-  if (getwd (pathname) == NULL)
-    {
-      return errno;
-    }
-  else
-    {
-      s_copy (str, pathname, Lstr, strlen (str));
-      return 0;
-    }
-}
-
-#else /* !HAVE_GETWD && !HAVE_GETCWD */
-
-extern void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-integer
-G77_getcwd_0 (char *str, const ftnlen Lstr)
-{
-  return errno = ENOSYS;
-}
-
-#endif
diff --git a/contrib/libf2c/libU77/getgid_.c b/contrib/libf2c/libU77/getgid_.c
deleted file mode 100644
index 7dcbdf80b57..00000000000
--- a/contrib/libf2c/libU77/getgid_.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#include 
-#endif
-#include 
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-integer
-G77_getgid_0 (void)
-{
-#if defined (HAVE_GETGID)
-  return getgid ();
-#else
-  errno = ENOSYS;
-  return -1;
-#endif
-}
diff --git a/contrib/libf2c/libU77/getlog_.c b/contrib/libf2c/libU77/getlog_.c
deleted file mode 100644
index 94c5f416067..00000000000
--- a/contrib/libf2c/libU77/getlog_.c
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-#include 
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-/* getlogin not in svr1-3 */
-
-/* SGI also has character*(*) function getlog() */
-
-extern void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-/* Subroutine */ int
-G77_getlog_0 (char *str, const ftnlen Lstr)
-{
-  size_t i;
-  char *p;
-  int status;
-
-#if defined (HAVE_GETLOGIN)
-  p = getlogin ();
-  if (p != NULL)
-    {
-      i = strlen (p);
-      s_copy (str, p, Lstr, i);
-    }
-  else
-    {
-      s_copy (str, " ", Lstr, 1);
-    }
-  status = 0;
-#else
-  errno = ENOSYS;
-  status = -1;
-#endif
-  return status;
-}
diff --git a/contrib/libf2c/libU77/getpid_.c b/contrib/libf2c/libU77/getpid_.c
deleted file mode 100644
index 6f1d8d7eede..00000000000
--- a/contrib/libf2c/libU77/getpid_.c
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#include 
-#endif
-#include 
-#include "f2c.h"
-
-integer
-G77_getpid_0 (void)
-{
-  return getpid ();
-}
diff --git a/contrib/libf2c/libU77/getuid_.c b/contrib/libf2c/libU77/getuid_.c
deleted file mode 100644
index d88b8e2cd9a..00000000000
--- a/contrib/libf2c/libU77/getuid_.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#include 
-#endif
-#include 
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-integer
-G77_getuid_0 (void)
-{
-#if defined (HAVE_GETUID)
-  return getuid ();
-#else
-  errno = ENOSYS;
-  return -1;
-#endif
-}
diff --git a/contrib/libf2c/libU77/gmtime_.c b/contrib/libf2c/libU77/gmtime_.c
deleted file mode 100644
index 9de3c5a8de5..00000000000
--- a/contrib/libf2c/libU77/gmtime_.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Copyright (C) 1995, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-/* fixme: do we need to use TM_IN_SYS_TIME? */
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* Subroutine */ int
-G77_gmtime_0 (const integer * xstime, integer tarray[9])
-{
-  struct tm *lt;
-  time_t stime = *xstime;
-  lt = gmtime (&stime);
-  tarray[0] = lt->tm_sec;
-  tarray[1] = lt->tm_min;
-  tarray[2] = lt->tm_hour;
-  tarray[3] = lt->tm_mday;
-  tarray[4] = lt->tm_mon;
-  tarray[5] = lt->tm_year;
-  tarray[6] = lt->tm_wday;
-  tarray[7] = lt->tm_yday;
-  tarray[8] = lt->tm_isdst;
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/hostnm_.c b/contrib/libf2c/libU77/hostnm_.c
deleted file mode 100644
index 7f511f422bb..00000000000
--- a/contrib/libf2c/libU77/hostnm_.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-integer
-G77_hostnm_0 (char *name, ftnlen Lname)
-{
-  int ret, i;
-
-#if HAVE_GETHOSTNAME
-  ret = gethostname (name, Lname);
-  if (ret == 0)
-    {
-      /* Pad with blanks (assuming gethostname will make an error
-         return if it can't fit in the null). */
-      for (i = strlen (name); i < Lname; i++)
-	name[i] = ' ';
-    }
-  return ret;
-#else
-  return errno = ENOSYS;
-#endif
-}
diff --git a/contrib/libf2c/libU77/idate_.c b/contrib/libf2c/libU77/idate_.c
deleted file mode 100644
index f2bea12e59d..00000000000
--- a/contrib/libf2c/libU77/idate_.c
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright (C) 1995, 1996, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* VMS and Irix versions (at least) differ from libU77 elsewhere */
-
-/* libU77 one: */
-
-/* Subroutine */ int
-G77_idate_0 (int iarray[3])
-{
-  struct tm *lt;
-  time_t tim;
-  tim = time (NULL);
-  lt = localtime (&tim);
-  iarray[0] = lt->tm_mday;
-  iarray[1] = lt->tm_mon + 1;	/* in range 1-12 in SunOS (experimentally) */
-  /* The `+1900' is consistent with SunOS and Irix, but they don't say
-     it's added.  I think I've seen a system where tm_year was since
-     1970, but can't now verify that, so assume the ANSI definition. */
-  iarray[2] = lt->tm_year + 1900;
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/ierrno_.c b/contrib/libf2c/libU77/ierrno_.c
deleted file mode 100644
index 0dc76b0262f..00000000000
--- a/contrib/libf2c/libU77/ierrno_.c
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include "f2c.h"
-
-integer
-G77_ierrno_0 (void)
-{
-  return errno;
-}
diff --git a/contrib/libf2c/libU77/irand_.c b/contrib/libf2c/libU77/irand_.c
deleted file mode 100644
index a9054311515..00000000000
--- a/contrib/libf2c/libU77/irand_.c
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#include "f2c.h"
-
-/* We could presumably do much better than the traditional libc
-   version, though at least the glibc one is reasonable, it seems.
-   For the sake of the innocent, I'm not sure we should really do
-   this... */
-
-/* Note this is per SunOS -- other s may have no arg. */
-
-integer
-G77_irand_0 (integer * flag)
-{
-  switch (*flag)
-    {
-    case 0:
-      break;
-    case 1:
-      srand (0);		/* Arbitrary choice of initialiser. */
-      break;
-    default:
-      srand (*flag);
-    }
-  return rand ();
-}
diff --git a/contrib/libf2c/libU77/isatty_.c b/contrib/libf2c/libU77/isatty_.c
deleted file mode 100644
index a781f757bc5..00000000000
--- a/contrib/libf2c/libU77/isatty_.c
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include "f2c.h"
-#include "fio.h"
-
-extern integer G77_fnum_0 (integer *);
-
-logical
-G77_isatty_0 (integer * lunit)
-{
-  if (f__init != 1) f_init();
-  if (*lunit >= MXUNIT || *lunit < 0)
-    err (1, 101, "isatty");
-  /* f__units is a table of descriptions for the unit numbers (defined
-     in io.h) with file descriptors rather than streams */
-  return (isatty (G77_fnum_0 (lunit)) ? TRUE_ : FALSE_);
-}
diff --git a/contrib/libf2c/libU77/itime_.c b/contrib/libf2c/libU77/itime_.c
deleted file mode 100644
index 12a7864fd97..00000000000
--- a/contrib/libf2c/libU77/itime_.c
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Copyright (C) 1995, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* Subroutine */ int
-G77_itime_0 (integer tarray[3])
-{
-  struct tm *lt;
-  time_t tim;
-
-  tim = time (NULL);
-  lt = localtime (&tim);
-  tarray[0] = lt->tm_hour;
-  tarray[1] = lt->tm_min;
-  tarray[2] = lt->tm_sec;
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/kill_.c b/contrib/libf2c/libU77/kill_.c
deleted file mode 100644
index 41eab152cbf..00000000000
--- a/contrib/libf2c/libU77/kill_.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#include 
-#include "f2c.h"
-
-/* fixme: bsd, svr1-3 use int, not pid_t */
-
-integer
-G77_kill_0 (const integer * pid, const integer * signum)
-{
-#if defined (HAVE_KILL)
-  return kill ((pid_t) * pid, *signum) ? errno : 0;
-#else
-  errno = ENOSYS;
-  return -1;
-#endif
-}
diff --git a/contrib/libf2c/libU77/link_.c b/contrib/libf2c/libU77/link_.c
deleted file mode 100644
index f3070e4b6e9..00000000000
--- a/contrib/libf2c/libU77/link_.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 
-#if HAVE_SYS_PARAM_H
-#  include 
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_link_0 (const char *path1, const char *path2, const ftnlen Lpath1,
-	    const ftnlen Lpath2)
-{
-#if defined (HAVE_LINK)
-  char *buff1, *buff2;
-  int i;
-
-  buff1 = malloc (Lpath1 + 1);
-  if (buff1 == NULL)
-    return -1;
-  g_char (path1, Lpath1, buff1);
-  buff2 = malloc (Lpath2 + 1);
-  if (buff2 == NULL)
-    return -1;
-  g_char (path2, Lpath2, buff2);
-  i = link (buff1, buff2);
-  free (buff1);
-  free (buff2);
-  return i ? errno : 0;
-#else /* ! HAVE_LINK */
-  errno = ENOSYS;
-  return -1;
-#endif
-}
diff --git a/contrib/libf2c/libU77/lnblnk_.c b/contrib/libf2c/libU77/lnblnk_.c
deleted file mode 100644
index f21ac42398b..00000000000
--- a/contrib/libf2c/libU77/lnblnk_.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-
-/* via f2c from Fortran */
-
-#include "f2c.h"
-
-integer
-G77_lnblnk_0 (char *str, ftnlen str_len)
-{
-  integer ret_val;
-  integer i_len ();
-
-  for (ret_val = str_len; ret_val >= 1; --ret_val)
-    {
-      if (*(unsigned char *) &str[ret_val - 1] != ' ')
-	{
-	  return ret_val;
-	}
-    }
-  return ret_val;
-}
diff --git a/contrib/libf2c/libU77/lstat_.c b/contrib/libf2c/libU77/lstat_.c
deleted file mode 100644
index 3914cc64ff4..00000000000
--- a/contrib/libf2c/libU77/lstat_.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#include 
-#include 
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-/* lstat isn't posix */
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_lstat_0 (const char *name, integer statb[13], const ftnlen Lname)
-{
-#if HAVE_LSTAT
-  char *buff;
-  int err;
-  struct stat buf;
-
-  buff = malloc (Lname + 1);
-  if (buff == NULL)
-    return -1;
-  g_char (name, Lname, buff);
-  err = lstat (buff, &buf);
-  free (buff);
-  statb[0] = buf.st_dev;
-  statb[1] = buf.st_ino;
-  statb[2] = buf.st_mode;
-  statb[3] = buf.st_nlink;
-  statb[4] = buf.st_uid;
-  statb[5] = buf.st_gid;
-#if HAVE_ST_RDEV
-  statb[6] = buf.st_rdev;
-#else
-  statb[6] = 0;
-#endif
-  statb[7] = buf.st_size;
-  statb[8] = buf.st_atime;
-  statb[9] = buf.st_mtime;
-  statb[10] = buf.st_ctime;
-#if HAVE_ST_BLKSIZE
-  statb[11] = buf.st_blksize;
-#else
-  statb[11] = -1;
-#endif
-#if HAVE_ST_BLOCKS
-  statb[12] = buf.st_blocks;
-#else
-  statb[12] = -1;
-#endif
-  return err;
-#else /* !HAVE_LSTAT */
-  return errno = ENOSYS;
-#endif /* !HAVE_LSTAT */
-}
diff --git a/contrib/libf2c/libU77/ltime_.c b/contrib/libf2c/libU77/ltime_.c
deleted file mode 100644
index 008df1dd08d..00000000000
--- a/contrib/libf2c/libU77/ltime_.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Copyright (C) 1995, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-/* fixme: do we need to use TM_IN_SYS_TIME? */
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* Subroutine */ int
-G77_ltime_0 (const integer * xstime, integer tarray[9])
-{
-  struct tm *lt;
-  time_t stime = *xstime;
-  lt = localtime (&stime);
-  tarray[0] = lt->tm_sec;
-  tarray[1] = lt->tm_min;
-  tarray[2] = lt->tm_hour;
-  tarray[3] = lt->tm_mday;
-  tarray[4] = lt->tm_mon;
-  tarray[5] = lt->tm_year;
-  tarray[6] = lt->tm_wday;
-  tarray[7] = lt->tm_yday;
-  tarray[8] = lt->tm_isdst;
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/mclock_.c b/contrib/libf2c/libU77/mclock_.c
deleted file mode 100644
index 686c4906751..00000000000
--- a/contrib/libf2c/libU77/mclock_.c
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Copyright (C) 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* Reported by wd42ej@sgi83.wwb.noaa.gov (Russ Jones AUTO-Sun3) on AIX. */
-
-longint
-G77_mclock_0 (void)
-{
-#if HAVE_CLOCK
-  return clock ();
-#else
-  return -1;
-#endif
-}
diff --git a/contrib/libf2c/libU77/perror_.c b/contrib/libf2c/libU77/perror_.c
deleted file mode 100644
index 6fe96aa6fc2..00000000000
--- a/contrib/libf2c/libU77/perror_.c
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include "f2c.h"
-
-/* Subroutine */ int
-G77_perror_0 (const char *str, const ftnlen Lstr)
-{
-  char buff[1000];
-  char *bp, *blast;
-
-  /* same technique as `system' -- what's wrong with malloc? */
-  blast = buff + (Lstr < 1000 ? Lstr : 1000);
-  for (bp = buff; bp < blast && *str != '\0';)
-    *bp++ = *str++;
-  *bp = '\0';
-  perror (buff);
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/rand_.c b/contrib/libf2c/libU77/rand_.c
deleted file mode 100644
index 1592dc5ab38..00000000000
--- a/contrib/libf2c/libU77/rand_.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#include "f2c.h"
-#ifndef RAND_MAX
-#  define RAND_MAX 2147483647	/* from SunOS */
-#endif
-
-/* We could presumably do much better than the traditional libc
-   version, though at least the glibc one is reasonable, it seems.
-   For the sake of the innocent, I'm not sure we should really do
-   this... */
-
-/* Note this is per SunOS -- other s may have no arg. */
-
-double
-G77_rand_0 (integer * flag)
-{
-  switch (*flag)
-    {
-    case 0:
-      break;
-    case 1:
-      srand (0);		/* Arbitrary choice of initialiser. */
-      break;
-    default:
-      srand (*flag);
-    }
-  return (float) rand () / RAND_MAX;
-}
diff --git a/contrib/libf2c/libU77/rename_.c b/contrib/libf2c/libU77/rename_.c
deleted file mode 100644
index 59759bcfb54..00000000000
--- a/contrib/libf2c/libU77/rename_.c
+++ /dev/null
@@ -1,53 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#include 
-#include 
-#include "f2c.h"
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_rename_0 (const char *path1, const char *path2, const ftnlen Lpath1,
-	      const ftnlen Lpath2)
-{
-  char *buff1, *buff2;
-  int i;
-
-  buff1 = malloc (Lpath1 + 1);
-  if (buff1 == NULL)
-    return -1;
-  g_char (path1, Lpath1, buff1);
-  buff2 = malloc (Lpath2 + 1);
-  if (buff2 == NULL)
-    return -1;
-  g_char (path2, Lpath2, buff2);
-  i = rename (buff1, buff2);
-  free (buff1);
-  free (buff2);
-  return i ? errno : 0;
-}
diff --git a/contrib/libf2c/libU77/secnds_.c b/contrib/libf2c/libU77/secnds_.c
deleted file mode 100644
index 1d661a9ad6b..00000000000
--- a/contrib/libf2c/libU77/secnds_.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include 
-
-#include "f2c.h"
-
-/* This is a VMS intrinsic. */
-
-double
-G77_secnds_0 (real * r)
-{
-  struct tm *lt;
-  time_t clock;
-  float f;
-
-  clock = time (NULL);
-  lt = localtime (&clock);
-  f = (3600.0 * ((real) lt->tm_hour) + 60.0 * ((real) lt->tm_min) +
-       (real) lt->tm_sec - *r);
-  return f;
-}
diff --git a/contrib/libf2c/libU77/second_.c b/contrib/libf2c/libU77/second_.c
deleted file mode 100644
index b40474a49a7..00000000000
--- a/contrib/libf2c/libU77/second_.c
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright (C) 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#include "f2c.h"
-
-double
-G77_second_0 ()
-{
-  extern double G77_etime_0 ();
-  real tarray[2];
-
-  return G77_etime_0 (tarray);
-}
diff --git a/contrib/libf2c/libU77/sleep_.c b/contrib/libf2c/libU77/sleep_.c
deleted file mode 100644
index fcf112a1c6a..00000000000
--- a/contrib/libf2c/libU77/sleep_.c
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include "f2c.h"
-
-/* Subroutine */
-int
-G77_sleep_0 (const integer * seconds)
-{
-  (void) sleep ((unsigned int) *seconds);
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/srand_.c b/contrib/libf2c/libU77/srand_.c
deleted file mode 100644
index 822d980dd0f..00000000000
--- a/contrib/libf2c/libU77/srand_.c
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if STDC_HEADERS
-#  include 
-#endif
-#include "f2c.h"
-
-/* Subroutine */
-int
-G77_srand_0 (const integer * seed)
-{
-  srand ((unsigned int) *seed);
-  return 0;
-}
diff --git a/contrib/libf2c/libU77/stamp-h.in b/contrib/libf2c/libU77/stamp-h.in
deleted file mode 100644
index 9788f70238c..00000000000
--- a/contrib/libf2c/libU77/stamp-h.in
+++ /dev/null
@@ -1 +0,0 @@
-timestamp
diff --git a/contrib/libf2c/libU77/stat_.c b/contrib/libf2c/libU77/stat_.c
deleted file mode 100644
index 65a63b7c9f5..00000000000
--- a/contrib/libf2c/libU77/stat_.c
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if HAVE_STDLIB_H
-#  include 
-#endif
-#include 
-#include 
-#include "f2c.h"
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_stat_0 (const char *name, integer statb[13], const ftnlen Lname)
-{
-  char *buff;
-  int err;
-  struct stat buf;
-
-  buff = malloc (Lname + 1);
-  if (buff == NULL)
-    return -1;
-  g_char (name, Lname, buff);
-  err = stat (buff, &buf);
-  free (buff);
-  statb[0] = buf.st_dev;
-  statb[1] = buf.st_ino;
-  statb[2] = buf.st_mode;
-  statb[3] = buf.st_nlink;
-  statb[4] = buf.st_uid;
-  statb[5] = buf.st_gid;
-#if HAVE_ST_RDEV
-  statb[6] = buf.st_rdev;	/* not posix */
-#else
-  statb[6] = 0;
-#endif
-  statb[7] = buf.st_size;
-  statb[8] = buf.st_atime;
-  statb[9] = buf.st_mtime;
-  statb[10] = buf.st_ctime;
-#if HAVE_ST_BLKSIZE
-  statb[11] = buf.st_blksize;	/* not posix */
-#else
-  statb[11] = -1;
-#endif
-#if HAVE_ST_BLOCKS
-  statb[12] = buf.st_blocks;	/* not posix */
-#else
-  statb[12] = -1;
-#endif
-  return err;
-}
diff --git a/contrib/libf2c/libU77/symlnk_.c b/contrib/libf2c/libU77/symlnk_.c
deleted file mode 100644
index 92ec605a423..00000000000
--- a/contrib/libf2c/libU77/symlnk_.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran.
-
-GNU Fortran is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 
-#if HAVE_SYS_PARAM_H
-#  include 
-#endif
-#include "f2c.h"
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_symlnk_0 (const char *path1, const char *path2, const ftnlen Lpath1,
-	      const ftnlen Lpath2)
-{
-#if HAVE_SYMLINK
-  char *buff1, *buff2;
-  int i;
-
-  buff1 = (char *) malloc (Lpath1 + 1);
-  if (buff1 == NULL)
-    return -1;
-  g_char (path1, Lpath1, buff1);
-  buff2 = (char *) malloc (Lpath2 + 1);
-  if (buff2 == NULL)
-    return -1;
-  g_char (path2, Lpath2, buff2);
-  i = symlink (buff1, buff2);
-  free (buff1);
-  free (buff2);
-  return i ? errno : 0;
-#else /* !HAVE_SYMLINK */
-  return errno = ENOSYS;
-#endif /* !HAVE_SYMLINK */
-}
diff --git a/contrib/libf2c/libU77/sys_clock_.c b/contrib/libf2c/libU77/sys_clock_.c
deleted file mode 100644
index ea39eead4f0..00000000000
--- a/contrib/libf2c/libU77/sys_clock_.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Copyright (C) 1996, 1998, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if HAVE_SYS_PARAM_H
-# include 
-#endif
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#if HAVE_SYS_TIMES_H
-#  include 
-#endif
-#include 
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-int
-G77_system_clock_0 (integer * count, integer * count_rate,
-		    integer * count_max)
-{
-#if defined (HAVE_TIMES)
-  struct tms buffer;
-  unsigned long cnt;
-  if (count_rate)
-    {
-#ifdef _SC_CLK_TCK
-      *count_rate = sysconf (_SC_CLK_TCK);
-#elif defined CLOCKS_PER_SECOND
-      *count_rate = CLOCKS_PER_SECOND;
-#elif defined CLK_TCK
-      *count_rate = CLK_TCK;
-#elif defined HZ
-      *count_rate = HZ;
-#else
-#error Dont know clock tick length
-#endif
-    }
-  if (count_max)		/* optional arg present? */
-    *count_max = INT_MAX;	/* dubious */
-  cnt = times (&buffer);
-  if (cnt > (unsigned long) (INT_MAX))
-    *count = INT_MAX;		/* also dubious */
-  else
-    *count = cnt;
-  return 0;
-#else /* ! HAVE_TIMES */
-  errno = ENOSYS;
-  return -1;
-#endif /* ! HAVE_TIMES */
-}
diff --git a/contrib/libf2c/libU77/time_.c b/contrib/libf2c/libU77/time_.c
deleted file mode 100644
index 2eb8a413991..00000000000
--- a/contrib/libf2c/libU77/time_.c
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Copyright (C) 1995 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* As well as this external function some compilers have an intrinsic
-   subroutine which fills a character argument (which is the VMS way)
-   -- caveat emptor. */
-longint
-G77_time_0 (void)
-{
-  /* There are potential problems with the cast of the time_t here. */
-  return time (NULL);
-}
diff --git a/contrib/libf2c/libU77/ttynam_.c b/contrib/libf2c/libU77/ttynam_.c
deleted file mode 100644
index ffdf5bfdf9a..00000000000
--- a/contrib/libf2c/libU77/ttynam_.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Copyright (C) 1995, 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#if STDC_HEADERS
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 		/* POSIX for ttyname */
-#endif
-#include 
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include 		/* for ENOSYS */
-#include "f2c.h"
-
-extern integer G77_fnum_0 (integer * lunit);
-extern void s_copy (register char *a, register char *b, ftnlen la, ftnlen lb);
-/* Character */ void
-G77_ttynam_0 (char *ret_val, ftnlen ret_val_len, integer * lunit)
-{
-#if defined (HAVE_TTYNAME)
-  size_t i;
-  char *p;
-
-  p = ttyname (G77_fnum_0 (lunit));
-  if (p != NULL)
-    {
-      i = strlen (p);
-      s_copy (ret_val, p, ret_val_len, i);
-    }
-  else
-    {
-      s_copy (ret_val, " ", ret_val_len, 1);
-    }
-#else
-  errno = ENOSYS;
-  s_copy (ret_val, " ", ret_val_len, 1);
-#endif
-}
diff --git a/contrib/libf2c/libU77/u77-test.f b/contrib/libf2c/libU77/u77-test.f
deleted file mode 100644
index 3c8151c533d..00000000000
--- a/contrib/libf2c/libU77/u77-test.f
+++ /dev/null
@@ -1,415 +0,0 @@
-***   Some random stuff for testing libU77.  Should be done better.  It's
-*     hard to test things where you can't guarantee the result.  Have a
-*     good squint at what it prints, though detected errors will cause 
-*     starred messages.
-*
-* Currently not tested:
-*   ALARM
-*   CHDIR (func)
-*   CHMOD (func)
-*   FGET (func/subr)
-*   FGETC (func)
-*   FPUT (func/subr)
-*   FPUTC (func)
-*   FSTAT (subr)
-*   GETCWD (subr)
-*   HOSTNM (subr)
-*   IRAND
-*   KILL
-*   LINK (func)
-*   LSTAT (subr)
-*   RENAME (func/subr)
-*   SIGNAL (subr)
-*   SRAND
-*   STAT (subr)
-*   SYMLNK (func/subr)
-*   UMASK (func)
-*   UNLINK (func)
-*
-* NOTE! This is the libU77 version, so it should be a bit more
-* "interactive" than the testsuite version, which is in
-* gcc/testsuite/g77.f-torture/execute/u77-test.f.
-* This version purposely exits with a "failure" status, to test
-* returning of non-zero status, and it doesn't call the ABORT
-* intrinsic (it substitutes an EXTERNAL stub, so the code can be
-* kept nearly the same in both copies).  Also, it goes ahead and
-* tests the HOSTNM intrinsic.  Please keep the other copy up-to-date when
-* you modify this one.
-
-      implicit none
-
-*     external hostnm
-      intrinsic hostnm
-      integer hostnm
-
-      integer i, j, k, ltarray (9), idat (3), count, rate, count_max,
-     +     pid, mask
-      real tarray1(2), tarray2(2), r1, r2
-      double precision d1
-      integer(kind=2) bigi
-      logical issum
-      intrinsic getpid, getuid, getgid, ierrno, gerror, time8,
-     +     fnum, isatty, getarg, access, unlink, fstat, iargc,
-     +     stat, lstat, getcwd, gmtime, etime, chmod, itime, date,
-     +     chdir, fgetc, fputc, system_clock, second, idate, secnds,
-     +     time, ctime, fdate, ttynam, date_and_time, mclock, mclock8,
-     +     cpu_time, dtime, ftell, abort
-      external lenstr, ctrlc
-      integer lenstr
-      logical l
-      character gerr*80, c*1
-      character ctim*25, line*80, lognam*20, wd*1000, line2*80,
-     +     ddate*8, ttime*10, zone*5, ctim2*25
-      integer fstatb (13), statb (13)
-      integer *2 i2zero
-      integer values(8)
-      integer(kind=7) sigret
-
-      i = time ()
-      ctim = ctime (i)
-      WRITE (6,'(A/)') '1 GNU libU77 test at: ' // ctim(:lenstr (ctim))
-      write (6,'(A,I3,'', '',I3)')
-     +     ' Logical units 5 and 6 correspond (FNUM) to'
-     +     // ' Unix i/o units ', fnum(5), fnum(6)
-      if (lnblnk('foo ').ne.3 .or. len_trim('foo ').ne.3) then
-        print *, 'LNBLNK or LEN_TRIM failed'
-        call abort
-      end if
-
-      bigi = time8 ()
-
-      call ctime (i, ctim2)
-      if (ctim .ne. ctim2) then
-        write (6, *) '*** CALL CTIME disagrees with CTIME(): ',
-     +    ctim2(:lenstr (ctim2)), ' vs. ', ctim(:lenstr (ctim))
-        call doabort
-      end if
-
-      j = time ()
-      if (i .gt. bigi .or. bigi .gt. j) then
-        write (6, *) '*** TIME/TIME8/TIME sequence failures: ',
-     +    i, bigi, j
-        call doabort
-      end if
-
-      print *, 'Command-line arguments: ', iargc ()
-      do i = 0, iargc ()
-         call getarg (i, line)
-         print *, 'Arg ', i, ' is: ', line(:lenstr (line))
-      end do
-
-      l= isatty(6)
-      line2 = ttynam(6)
-      if (l) then
-        line = 'and 6 is a tty device (ISATTY) named '//line2
-      else
-        line = 'and 6 isn''t a tty device (ISATTY)'
-      end if
-      write (6,'(1X,A)') line(:lenstr(line))
-      call ttynam (6, line)
-      if (line .ne. line2) then
-        print *, '*** CALL TTYNAM disagrees with TTYNAM: ',
-     +    line(:lenstr (line))
-        call doabort
-      end if
-
-*     regression test for compiler crash fixed by JCB 1998-08-04 com.c
-      sigret = signal(2, ctrlc)
-
-      pid = getpid()
-      WRITE (6,'(A,I10)') ' Process id (GETPID): ', pid
-      WRITE (6,'(A,I10)') ' User id (GETUID): ', GETUID ()
-      WRITE (6,'(A,I10)') ' Group id (GETGID): ', GETGID ()
-      WRITE (6, *) 'If you have the `id'' program, the following call'
-      write (6, *) 'of SYSTEM should agree with the above:'
-      call flush(6)
-      CALL SYSTEM ('echo " " `id`')
-      call flush
-
-      lognam = 'blahblahblah'
-      call getlog (lognam)
-      write (6,*) 'Login name (GETLOG): ', lognam(:lenstr (lognam))
-
-      wd = 'blahblahblah'
-      call getenv ('LOGNAME', wd)
-      write (6,*) 'Login name (GETENV of LOGNAME): ', wd(:lenstr (wd))
-
-      call umask(0, mask)
-      write(6,*) 'UMASK returns', mask
-      call umask(mask)
-
-      ctim = fdate()
-      write (6,*) 'FDATE returns: ', ctim(:lenstr (ctim))
-      call fdate (ctim)
-      write (6,*) 'CALL FDATE returns: ', ctim(:lenstr (ctim))
-
-      j=time()
-      call ltime (j, ltarray)
-      write (6,'(1x,a,9i4)') 'LTIME returns:', ltarray
-      call gmtime (j, ltarray)
-      write (6,'(1x,a,9i4)') 'GMTIME returns:', ltarray
-
-      call system_clock(count)  ! omitting optional args
-      call system_clock(count, rate, count_max)
-      write(6,*) 'SYSTEM_CLOCK returns: ', count, rate, count_max
-
-      call date_and_time(ddate)  ! omitting optional args
-      call date_and_time(ddate, ttime, zone, values)
-      write(6, *) 'DATE_AND_TIME returns: ', ddate, ' ', ttime, ' ',
-     +     zone, ' ', values
-
-      write (6,*) 'Sleeping for 1 second (SLEEP) ...'
-      call sleep (1)
-
-c consistency-check etime vs. dtime for first call
-      r1 = etime (tarray1)
-      r2 = dtime (tarray2)
-      if (abs (r1-r2).gt.1.0) then
-        write (6,*)
-     +       'Results of ETIME and DTIME differ by more than a second:',
-     +       r1, r2
-        call doabort
-      end if
-      if (.not. issum (r1, tarray1(1), tarray1(2))) then
-        write (6,*) '*** ETIME didn''t return sum of the array: ',
-     +       r1, ' /= ', tarray1(1), '+', tarray1(2)
-        call doabort
-      end if
-      if (.not. issum (r2, tarray2(1), tarray2(2))) then
-        write (6,*) '*** DTIME didn''t return sum of the array: ',
-     +       r2, ' /= ', tarray2(1), '+', tarray2(2)
-        call doabort
-      end if
-      write (6, '(A,3F10.3)')
-     +     ' Elapsed total, user, system time (ETIME): ',
-     +     r1, tarray1
-
-c now try to get times to change enough to see in etime/dtime
-      write (6,*) 'Looping until clock ticks at least once...'
-      do i = 1,1000
-      do j = 1,1000
-      end do
-      call dtime (tarray2, r2)
-      if (tarray2(1) .ne. 0. .or. tarray2(2) .ne. 0.) exit
-      end do
-      call etime (tarray1, r1)
-      if (.not. issum (r1, tarray1(1), tarray1(2))) then
-        write (6,*) '*** ETIME didn''t return sum of the array: ',
-     +       r1, ' /= ', tarray1(1), '+', tarray1(2)
-        call doabort
-      end if
-      if (.not. issum (r2, tarray2(1), tarray2(2))) then
-        write (6,*) '*** DTIME didn''t return sum of the array: ',
-     +       r2, ' /= ', tarray2(1), '+', tarray2(2)
-        call doabort
-      end if
-      write (6, '(A,3F10.3)')
-     +     ' Differences in total, user, system time (DTIME): ',
-     +     r2, tarray2
-      write (6, '(A,3F10.3)')
-     +     ' Elapsed total, user, system time (ETIME): ',
-     +     r1, tarray1
-      write (6, *) '(Clock-tick detected after ', i, ' 1K loops.)'
-
-      call idate (i,j,k)
-      call idate (idat)
-      write (6,*) 'IDATE (date,month,year): ',idat
-      print *,  '... and the VXT version (month,date,year): ', i,j,k
-      if (i/=idat(2) .or. j/=idat(1) .or. k/=mod(idat(3),100)) then
-        print *, '*** VXT and U77 versions don''t agree'
-        call doabort
-      end if
-
-      call date (ctim)
-      write (6,*) 'DATE (dd-mmm-yy): ', ctim(:lenstr (ctim))
-
-      call itime (idat)
-      write (6,*) 'ITIME (hour,minutes,seconds): ', idat
-
-      call time(line(:8))
-      print *, 'TIME: ', line(:8)
-
-      write (6,*) 'SECNDS(0.0) returns: ',secnds(0.0)
-
-      write (6,*) 'SECOND returns: ', second()
-      call dumdum(r1)
-      call second(r1)
-      write (6,*) 'CALL SECOND returns: ', r1
-
-*     compiler crash fixed by 1998-10-01 com.c change
-      if (rand(0).lt.0.0 .or. rand(0).gt.1.0) then
-        write (6,*) '*** rand(0) error'
-        call doabort()
-      end if
-
-      i = getcwd(wd)
-      if (i.ne.0) then
-        call perror ('*** getcwd')
-        call doabort
-      else
-        write (6,*) 'Current directory is "'//wd(:lenstr(wd))//'"'
-      end if
-      call chdir ('.',i)
-      if (i.ne.0) then
-        write (6,*) '***CHDIR to ".": ', i
-        call doabort
-      end if
-
-      i=hostnm(wd)
-      if(i.ne.0) then
-        call perror ('*** hostnm')
-        call doabort
-      else
-        write (6,*) 'Host name is ', wd(:lenstr(wd))
-      end if
-
-      i = access('/dev/null ', 'rw')
-      if (i.ne.0) write (6,*) '***Read/write ACCESS to /dev/null: ', i
-      write (6,*) 'Creating file "foo" for testing...'
-      open (3,file='foo',status='UNKNOWN')
-      rewind 3
-      call fputc(3, 'c',i)
-      call fputc(3, 'd',j)      
-      if (i+j.ne.0) write(6,*) '***FPUTC: ', i
-C     why is it necessary to reopen?  (who wrote this?)
-C     the better to test with, my dear!  (-- burley)
-      close(3)
-      open(3,file='foo',status='old')
-      call fseek(3,0,0,*10)
-      go to 20
- 10   write(6,*) '***FSEEK failed'
-      call doabort
- 20   call fgetc(3, c,i)
-      if (i.ne.0) then
-        write(6,*) '***FGETC: ', i
-        call doabort
-      end if
-      if (c.ne.'c') then
-        write(6,*) '***FGETC read the wrong thing: ', ichar(c)
-        call doabort
-      end if
-      i= ftell(3)
-      if (i.ne.1) then
-        write(6,*) '***FTELL offset: ', i
-        call doabort
-      end if
-      call ftell(3, i)
-      if (i.ne.1) then
-        write(6,*) '***CALL FTELL offset: ', i
-        call doabort
-      end if
-      call chmod ('foo', 'a+w',i)
-      if (i.ne.0) then
-        write (6,*) '***CHMOD of "foo": ', i
-        call doabort
-      end if
-      i = fstat (3, fstatb)
-      if (i.ne.0) then
-        write (6,*) '***FSTAT of "foo": ', i
-        call doabort
-      end if
-      i = stat ('foo', statb)
-      if (i.ne.0) then
-        write (6,*) '***STAT of "foo": ', i
-        call doabort
-      end if
-      write (6,*) '  with stat array ', statb
-      if (statb(6) .ne. getgid ()) then
-        write (6,*) 'Note: FSTAT gid wrong (happens on some systems).'
-      end if
-      if (statb(5) .ne. getuid () .or. statb(4) .ne. 1) then
-        write (6,*) '*** FSTAT uid or nlink is wrong'
-        call doabort
-      end if
-      do i=1,13
-        if (fstatb (i) .ne. statb (i)) then
-          write (6,*) '*** FSTAT and STAT don''t agree on '// '
-     +         array element ', i, ' value ', fstatb (i), statb (i)
-          call doabort
-        end if
-      end do
-      i = lstat ('foo', fstatb)
-      do i=1,13
-        if (fstatb (i) .ne. statb (i)) then
-          write (6,*) '*** LSTAT and STAT don''t agree on '//
-     +         'array element ', i, ' value ', fstatb (i), statb (i)
-          call doabort
-        end if
-      end do
-
-C     in case it exists already:
-      call unlink ('bar',i)
-      call link ('foo ', 'bar ',i)
-      if (i.ne.0) then
-        write (6,*) '***LINK "foo" to "bar" failed: ', i
-        call doabort
-      end if
-      call unlink ('foo',i)
-      if (i.ne.0) then
-        write (6,*) '***UNLINK "foo" failed: ', i
-        call doabort
-      end if
-      call unlink ('foo',i)
-      if (i.eq.0) then
-        write (6,*) '***UNLINK "foo" again: ', i
-        call doabort
-      end if
-
-      call gerror (gerr)
-      i = ierrno()
-      write (6,'(A,I3,A/1X,A)') ' The current error number is: ',
-     +     i,
-     +     ' and the corresponding message is:', gerr(:lenstr(gerr))
-      write (6,*) 'This is sent to stderr prefixed by the program name'
-      call getarg (0, line)
-      call perror (line (:lenstr (line)))
-      call unlink ('bar')
-
-      print *, 'MCLOCK returns ', mclock ()
-      print *, 'MCLOCK8 returns ', mclock8 ()
-
-      call cpu_time (d1)
-      print *, 'CPU_TIME returns ', d1
-
-      WRITE (6,*) 'You should see exit status 1'
-      CALL EXIT(1)
- 99   END
-
-* Return length of STR not including trailing blanks, but always > 0.
-      integer function lenstr (str)
-      character*(*) str
-      if (str.eq.' ') then
-        lenstr=1
-      else
-        lenstr = lnblnk (str)
-      end if
-      end
-
-* Just make sure SECOND() doesn't "magically" work the second time.
-      subroutine dumdum(r)
-      r = 3.14159
-      end
-
-* Test whether sum is approximately left+right.
-      logical function issum (sum, left, right)
-      implicit none
-      real sum, left, right
-      real mysum, delta, width
-      mysum = left + right
-      delta = abs (mysum - sum)
-      width = abs (left) + abs (right)
-      issum = (delta .le. .0001 * width)
-      end
-
-* Signal handler
-      subroutine ctrlc
-      print *, 'Got ^C'
-      call doabort
-      end
-
-* A problem has been noticed, so maybe abort the test.
-      subroutine doabort
-* For this version, print out all problems noticed.
-*     intrinsic abort
-*     call abort
-      end
diff --git a/contrib/libf2c/libU77/umask_.c b/contrib/libf2c/libU77/umask_.c
deleted file mode 100644
index 5c4546a83ac..00000000000
--- a/contrib/libf2c/libU77/umask_.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright (C) 1996 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#include "f2c.h"
-
-integer
-G77_umask_0 (integer * mask)
-{
-  return umask ((mode_t) * mask);
-}
diff --git a/contrib/libf2c/libU77/unlink_.c b/contrib/libf2c/libU77/unlink_.c
deleted file mode 100644
index 08222d92749..00000000000
--- a/contrib/libf2c/libU77/unlink_.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 1995, 1997 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#if HAVE_STDLIB_H
-#  include 
-#else
-#  include 
-#endif
-#if HAVE_UNISTD_H
-#  include 
-#endif
-#include 
-#if HAVE_SYS_PARAM_H
-#  include 
-#endif
-#include "f2c.h"
-
-void g_char (const char *a, ftnlen alen, char *b);
-
-integer
-G77_unlink_0 (const char *str, const ftnlen Lstr)
-{
-  char *buff;
-  int i;
-
-  buff = malloc (Lstr + 1);
-  if (buff == NULL)
-    return -1;
-  g_char (str, Lstr, buff);
-  i = unlink (buff);
-  free (buff);
-  return i ? errno : 0;		/* SGI version returns -1 on failure. */
-}
diff --git a/contrib/libf2c/libU77/vxtidate_.c b/contrib/libf2c/libU77/vxtidate_.c
deleted file mode 100644
index fb1395161a3..00000000000
--- a/contrib/libf2c/libU77/vxtidate_.c
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Copyright (C) 1995, 1996, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#include "f2c.h"
-
-/* VMS and Irix versions (at least) differ from libU77 elsewhere */
-
-/* VMS style: */
-
-/* Subroutine */
-int
-G77_vxtidate_y2kbug_0 (integer * m, integer * d, integer * y)
-{
-  struct tm *lt;
-  time_t tim;
-  tim = time (NULL);
-  lt = localtime (&tim);
-  *y = lt->tm_year % 100;
-  *m = lt->tm_mon + 1;
-  *d = lt->tm_mday;
-  return 0;
-}
-
-#ifdef PIC
-extern const char *G77_Non_Y2K_Compliance_Message;
-int
-G77_vxtidate_y2kbuggy_0 (integer * m __attribute__ ((__unused__)),
-			 integer * d __attribute__ ((__unused__)),
-			 integer * y __attribute__ ((__unused__)))
-{
-  extern int G77_abort_0() __attribute__ ((noreturn));
-  fprintf (stderr, "%s\n", G77_Non_Y2K_Compliance_Message);
-  G77_abort_0 ();
-}
-#endif
diff --git a/contrib/libf2c/libU77/vxttime_.c b/contrib/libf2c/libU77/vxttime_.c
deleted file mode 100644
index 5982748583a..00000000000
--- a/contrib/libf2c/libU77/vxttime_.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (C) 1995, 2001 Free Software Foundation, Inc.
-This file is part of GNU Fortran libU77 library.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Library General Public License as published
-by the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-GNU Fortran is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with GNU Fortran; see the file COPYING.LIB.  If
-not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-#include 
-#include 
-#if TIME_WITH_SYS_TIME
-# include 
-# include 
-#else
-# if HAVE_SYS_TIME_H
-#  include 
-# else
-#  include 
-# endif
-#endif
-#if HAVE_STRING_H
-#  include 
-#else
-#  include 
-#endif
-#include "f2c.h"
-
-/* Subroutine */
-void
-G77_vxttime_0 (char chtime[8],
-	       const ftnlen Lchtime __attribute__ ((__unused__)))
-{
-  time_t tim;
-  char *ctim;
-  tim = time (NULL);
-  ctim = ctime (&tim);
-  strncpy (chtime, ctim + 11, 8);
-}
diff --git a/contrib/libf2c/permission.netlib b/contrib/libf2c/permission.netlib
deleted file mode 100644
index 261b719bc57..00000000000
--- a/contrib/libf2c/permission.netlib
+++ /dev/null
@@ -1,23 +0,0 @@
-/****************************************************************
-Copyright 1990 - 1997 by AT&T, Lucent Technologies and Bellcore.
-
-Permission to use, copy, modify, and distribute this software
-and its documentation for any purpose and without fee is hereby
-granted, provided that the above copyright notice appear in all
-copies and that both that the copyright notice and this
-permission notice and warranty disclaimer appear in supporting
-documentation, and that the names of AT&T, Bell Laboratories,
-Lucent or Bellcore or any of their entities not be used in
-advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.
-
-AT&T, Lucent and Bellcore disclaim all warranties with regard to
-this software, including all implied warranties of
-merchantability and fitness.  In no event shall AT&T, Lucent or
-Bellcore be liable for any special, indirect or consequential
-damages or any damages whatsoever resulting from loss of use,
-data or profits, whether in an action of contract, negligence or
-other tortious action, arising out of or in connection with the
-use or performance of this software.
-****************************************************************/
-
diff --git a/contrib/libf2c/readme.netlib b/contrib/libf2c/readme.netlib
deleted file mode 100644
index 1ec98865e5b..00000000000
--- a/contrib/libf2c/readme.netlib
+++ /dev/null
@@ -1,791 +0,0 @@
-
-====== old index for f2c, now "readme from f2c" ============
-
-FILES:
-
-f2c.h	Include file necessary for compiling output of the converter.
-	See the second NOTE below.
-
-f2c.1	Man page for f2c.
-
-f2c.1t	Source for f2c.1 (to be processed by troff -man or nroff -man).
-
-libf77	Library of non I/O support routines the generated C may need.
-	Fortran main programs result in a C function named MAIN__ that
-	is meant to be invoked by the main() in libf77.
-
-libi77	Library of Fortran I/O routines the generated C may need.
-	Note that some vendors (e.g., BSD, Sun and MIPS) provide a
-	libF77 and libI77 that are incompatible with f2c -- they
-	provide some differently named routines or routines with the
-	names that f2c expects, but with different calling sequences.
-	On such systems, the recommended procedure is to merge
-	libf77 and libi77 into a single library, say libf2c, and to
-        install it where you can access it by specifying -lf2c .  The
-        definition of link_msg in sysdep.c assumes this arrangement.
-
-	Both libf77 and libi77 are bundles, meant to be unpacked by the
-	Bourne (or Korn) shell.  MS-DOS users can use the MKS Toolkit
-	to unpack libf77 and libi77.
-
-libf2c.zip
-	Only available by ftp: combination of libf77 and libi77, with
-	Unix and PC makefiles.
-
-f2c.ps	Postscript for a technical report on f2c.  After you strip the
-	mail header, the first line should be "%!PS".
-
-fixes	The complete change log, reporting bug fixes and other changes.
-	(Some recent change-log entries are given below).
-
-fc	A shell script that uses f2c and imitates much of the behavior
-	of commonly found f77 commands.  You will almost certainly
-	need to adjust some of the shell-variable assignments to make
-	this script work on your system.
-
-
-SUBDIRECTORY:
-
-f2c/src	Source for the converter itself, including a file of checksums
-	and source for a program to compute the checksums (to verify
-	correct transmission of the source), is available: ask netlib
-	(e.g., netlib@netlib.bell-labs.com) to
-		send all from f2c/src
-	If the checksums show damage to just a few source files, or if
-	the change log file (see "fixes" below) reports corrections to
-	some source files, you can request those files individually
-	"from f2c/src".  For example, to get defs.h and xsum0.out, you
-	would ask netlib to
-		send defs.h xsum0.out from f2c/src
-	"all from f2c/src" is about 640 kilobytes long; for convenience
-	(and checksums), it includes copies of f2c.h, f2c.1, and f2c.1t.
-
-	Tip: if asked to send over 99,000 bytes in one request, netlib
-	breaks the shipment into 1000 line pieces and sends each piece
-	separately (since otherwise some mailers might gag).  To avoid
-	the hassle of reassembling the pieces, try to keep each request
-	under 99,000 bytes long.  The final number in each line of
-	xsum0.out gives the length of each file in f2c/src.  For
-	example,
-		send exec.c expr.c from f2c/src
-		send format.c format_data.c from f2c/src
-	will give you slightly less hassle than
-		send exec.c expr.c format.c format_data.c from f2c/src
-	Alternatively, if all the mailers in your return path allow
-	long messages, you can supply an appropriate mailsize line in
-	your netlib request, e.g.
-		mailsize 200k
-		send exec.c expr.c format.c format_data.c from f2c/src
-
-	The makefile used to generate gram.c; now we distribute a
-	working gram.c, and you must say
-		make gram1.c
-		mv gram1.c gram.c
-	if you want to generate your own gram.c -- there are just too
-	many broken variants of yacc floating around nowadays for
-	generation of gram.c to be the default.
-
-NOTE:	You may exercise f2c by sending netlib@netlib.bell-labs.com
-	a message whose first line is "execute f2c" and whose remaining
-	lines are the Fortran 77 source that you wish to have converted.
-	Return mail brings you the resulting C, with f2c's error
-	messages between #ifdef uNdEfInEd and #endif at the end.
-	(To understand line numbers in the error messages, regard
-	the "execute f2c" line as line 0.  It is stripped away by
-	the netlib software before f2c sees your Fortran input.)
-	Options described in the man page may be transmitted to
-	netlib by having the first line of input be a comment
-	whose first 6 characters are "c$f2c " and whose remaining
-	characters are the desired options, e.g., "c$f2c -R -u".
-
-	You may say "execute f2c" in the Subject line instead of (but
-	*not* in addition to) in the first line of the message body.
-
-	The incoming Fortran is saved, at least for a while.  Don't
-	send any secrets!
-
-
-BUGS:	Please send bug reports (including the shortest example
-	you can find that illustrates the bug) to research!dmg
-	or dmg@bell-labs.com .  You might first check whether
-	the bug goes away when you turn optimization off.
-
-
-NOTE:	f2c.h defines several types, e.g., real, integer, doublereal.
-	The definitions in f2c.h are suitable for most machines, but if
-	your machine has sizeof(double) > 2*sizeof(long), you may need
-	to adjust f2c.h appropriately.  f2c assumes
-		sizeof(doublecomplex) = 2*sizeof(doublereal)
-		sizeof(doublereal) = sizeof(complex)
-		sizeof(doublereal) = 2*sizeof(real)
-		sizeof(real) = sizeof(integer)
-		sizeof(real) = sizeof(logical)
-		sizeof(real) = 2*sizeof(shortint)
-	EQUIVALENCEs may not be translated correctly if these
-	assumptions are violated.
-
-	On machines, such as those using a DEC Alpha processor, on
-	which sizeof(short) == 2, sizeof(int) == sizeof(float) == 4,
-	and sizeof(long) == sizeof(double) == 8, it suffices to
-	modify f2c.h by removing the first occurrence of "long "
-	on each line containing "long ", e.g., by issuing the
-	commands
-		mv f2c.h f2c.h0
-		sed 's/long //' f2c.h0 >f2c.h
-	On such machines, one can enable INTEGER*8 by uncommenting
-	the typedef of longint in f2c.h, so it reads
-		typedef long longint;
-	by compiling libI77 with -DAllow_TYQUAD, and by adjusting
-	libF77/makefile as described in libF77/README.
-
-	Some machines may have sizeof(int) == 4, sizeof(float) == 8,
-	and sizeof(long long) == 8.  On such machines, adjust f2c.h
-	by changing "long int " to "long long ", e.g., by saying
-		mv f2c.h f2c.h0
-		sed 's/long int /long long /' f2c.h0 >f2c.h
-	One can enable INTEGER*8 on such machines as described
-	above, but with
-		typedef long long longint;
-
-	There exists a C compiler that objects to the lines
-		typedef VOID C_f;	/* complex function */
-		typedef VOID H_f;	/* character function */
-		typedef VOID Z_f;	/* double complex function */
-	in f2c.h .  If yours is such a compiler, do two things:
-	1. Complain to your vendor about this compiler bug.
-	2. Find the line
-		#define VOID void
-	   in f2c.h and change it to
-		#define VOID int
-	(For readability, the f2c.h lines shown above have had two
-	tabs inserted before their first character.)
-
-FTP:	All the material described above is now available by anonymous
-	ftp from netlib.bell-labs.com (login: anonymous; Password: your
-	E-mail address; cd netlib/f2c).  Note that you can say, e.g.,
-
-		cd /netlib/f2c/src
-		binary
-		prompt
-		mget *.gz
-
-	to get all the .gz files in src.  You must uncompress the .gz
-	files once you have a copy of them, e.g., by
-
-		gzip -dN *.gz
-
-	You can also get the entire f2c tree as a tar file:
-
-		ftp://netlib.bell-labs.com/netlib/f2c.tar
-
-	(which is a synthetic file -- created on the fly and not visible
-	to ftp's "ls" or "dir" commands).
-
-	Subdirectory msdos contains two PC versions of f2c,
-	f2c.exe.gz and f2cx.exe.gz; the latter uses extended memory.
-	The README in that directory provides more details.
-
-	Changes appear first in the f2c files available by E-mail
-	from netlib@netlib.bell-labs.com.  If the deamons work right,
-	changed files are available the next day by ftp from
-	netlib.bell-labs.com.  In due course, they reach other netlib servers.
-
-CHANGE NOTIFICATION:
-	Send the E-mail message
-		subscribe f2c
-	to netlib@netlib.bell-labs.com to request notification of new and
-	changed f2c files.  (Beware that automatically sent change
-	notifications may reach you before changes have reached
-	ftp://netlib.bell-labs.com/netlib/f2c or to other netlib servers.)
-	Send the E-mail message
-		unsubscribe f2c
-	to recant your notification request.
-
------------------
-Recent change log (partial)
------------------
-
-Mon May 13 23:35:26 EDT 1996
-  Recognize Fortran 90's /= as a synonym for .NE..  (<> remains a
-synonym for .NE..)
-  Emit an empty int function of no arguments to supply an external
-name to named block data subprograms (so they can be called somewhere
-to force them to be loaded from a library).
-  Fix bug (memory fault) in handling the following illegal Fortran:
-	parameter(i=1)
-	equivalence(i,j)
-	end
-  Treat cdabs, cdcos, cdexp, cdlog, cdsin, and cdsqrt as synonyms for
-the double complex intrinsics zabs, zcos, zexp, zlog, zsin, and zsqrt,
-respectively, unless -cd is specified.
-  Recognize the Fortran 90 bit-manipulation intrinsics btest, iand,
-ibclr, ibits, ibset, ieor, ior, ishft, and ishftc, unless -i90 is
-specified.  Note that iand, ieor, and ior are thus now synonyms for
-"and", "xor", and "or", respectively.
-  Add three macros (bit_test, bit_clear, bit_set) to f2c.h for use
-with btest, ibclr, and ibset, respectively.  Add new functions
-[lq]bit_bits, [lq]bit_shift, and [lq]_bit_cshift to libF77 for
-use with ibits, ishft, and ishftc, respectively.
-  Add integer function ftell(unit) (returning -1 on error) and
-subroutine fseek(unit, offset, whence, *) to libI77 (with branch to
-label * on error).
-
-Tue May 14 23:21:12 EDT 1996
-  Fix glitch (possible memory fault, or worse) in handling multiple
-entry points with names over 28 characters long.
-
-Mon Jun 10 01:20:16 EDT 1996
-  Update netlib E-mail and ftp addresses in f2c/readme and
-f2c/src/readme (which are different files) -- to reflect the upcoming
-breakup of AT&T.
-  libf77: trivial tweaks to F77_aloc.c and system_.c; Version.c not
-changed.
-  libi77: Adjust rsli.c and lread.c so internal list input with too
-few items in the input string will honor end= .
-
-Mon Jun 10 22:59:57 EDT 1996
-  Add Bits_per_Byte to sysdep.h and adjust definition of Table_size
-to depend on Bits_per_Byte (forcing Table_size to be a power of 2); in
-lex.c, change "comstart[c & 0xfff]" to "comstart[c & (Table_size-1)]"
-to avoid an out-of-range subscript on end-of-file.
-
-Wed Jun 12 00:24:28 EDT 1996
-  Fix bug in output.c (dereferencing a freed pointer) revealed in
-	print *		!np in out_call in output.c clobbered by free
-	end		!during out_expr.
-
-Wed Jun 19 08:12:47 EDT 1996
-  f2c.h: add types uinteger, ulongint (for libF77); add qbit_clear
-and qbit_set macros (in a commented-out section) for integer*8.
-  For integer*8, use qbit_clear and qbit_set for ibclr and ibset.
-  libf77: add casts to unsigned in [lq]bitshft.c.
-
-Thu Jun 20 13:30:43 EDT 1996
-  Complain at character*(*) in common (rather than faulting).
-  Fix bug in recognizing hex constants that start with "16#" (e.g.,
-16#1234abcd, which is a synonym for z'1234abcd').
-  Fix bugs in constant folding of expressions involving btest, ibclr,
-and ibset.
-  Fix bug in constant folding of rshift(16#80000000, -31) (on a 32-bit
-machine; more generally, the bug was in constant folding of
-rshift(ibset(0,NBITS-1), 1-NBITS) when f2c runs on a machine with
-long ints having NBITS bits.
-
-Mon Jun 24 07:58:53 EDT 1996
-  Adjust struct Literal and newlabel() function to accommodate huge
-source files (with more than 32767 newlabel() invocations).
-  Omit .c file when the .f file has a missing final end statement.
-
-Wed Jun 26 14:00:02 EDT 1996
-  libi77: Add discussion of MXUNIT (highest allowed Fortran unit number)
-to libI77/README.
-
-Fri Jun 28 14:16:11 EDT 1996
-  Fix glitch with -onetrip: the temporary variable used for nonconstant
-initial loop variable values was recycled too soon.  Example:
-	do i = j+1, k
-		call foo(i+1)	! temp for j+1 was reused here
-		enddo
-	end
-
-Tue Jul  2 16:11:27 EDT 1996
-  formatdata.c: add a 0 to the end of the basetype array (for TYBLANK)
-(an omission that was harmless on most machines).
-  expr.c: fix a dereference of NULL that was only possible with buggy
-input, such as
-	subroutine $sub(s)	! the '$' is erroneous
-	character s*(*)
-	s(1:) = ' '
-	end
-
-Sat Jul  6 00:44:56 EDT 1996
-  Fix glitch in the intrinsic "real" function when applied to a
-complex (or double complex) variable and passed as an argument to
-some intrinsic functions.  Example:
-	complex a
-	b = sqrt(real(a))
-	end
-  Fix glitch (only visible if you do not use f2c's malloc and the
-malloc you do use is defective in the sense that malloc(0) returns 0)
-in handling include files that end with another include (perhaps
-followed by comments).
-  Fix glitch with character*(*) arguments named "h" and "i" when
-the body of the subroutine invokes the intrinsic LEN function.
-  Arrange that after a previous "f2c -P foo.f" has produced foo.P,
-running "f2c foo.P foo.f" will produce valid C when foo.f contains
-	call sub('1234')
-	end
-	subroutine sub(msg)
-	end
-Specifically, the length argument in "call sub" is now suppressed.
-With or without foo.P, it is also now suppressed when the order of
-subprograms in file foo.f is reversed:
-	subroutine sub(msg)
-	end
-	call sub('1234')
-	end
-  Adjust copyright notices to reflect AT&T breakup.
-
-Wed Jul 10 09:25:49 EDT 1996
-  Fix bug (possible memory fault) in handling erroneously placed
-and inconsistent declarations.  Example that faulted:
-	character*1 w(8)
-	call foo(w)
-	end
-	subroutine foo(m)
-	data h /0.5/
-	integer m(2)	! should be before data
-	end
-  Fix bug (possible fault) in handling illegal "if" constructions.
-Example (that faulted):
-	subroutine foo(i,j)
-	if (i) then		! bug: i is integer, not logical
-	else if (j) then	! bug: j is integer, not logical
-	endif
-	end
-  Fix glitch with character*(*) argument named "ret_len" to a
-character*(*) function.
-
-Wed Jul 10 23:04:16 EDT 1996
-  Fix more glitches in the intrinsic "real" function when applied to a
-complex (or double complex) variable and passed as an argument to
-some intrinsic functions.  Example:
-	complex a, b
-	r = sqrt(real(conjg(a))) + sqrt(real(a*b))
-	end
-
-Thu Jul 11 17:27:16 EDT 1996
-  Fix a memory fault associated with complicated, illegal input.
-Example:
-	subroutine goo
-	character a
-	call foo(a)	! inconsistent with subsequent def and call
-	end
-	subroutine foo(a)
-	end
-	call foo(a)
-	end
-
-Wed Jul 17 19:18:28 EDT 1996
-  Fix yet another case of intrinsic "real" applied to a complex
-argument.  Example:
-	complex a(3)
-	x = sqrt(real(a(2)))	! gave error message about bad tag
-	end
-
-Mon Aug 26 11:28:57 EDT 1996
-  Tweak sysdep.c for non-Unix systems in which process ID's can be
-over 5 digits long.
-
-Tue Aug 27 08:31:32 EDT 1996
-  Adjust the ishft intrinsic to use unsigned right shifts.  (Previously,
-a negative constant second operand resulted in a possibly signed shift.)
-
-Thu Sep 12 14:04:07 EDT 1996
-  equiv.c: fix glitch with -DKR_headers.
-  libi77: fmtlib.c: fix bug in printing the most negative integer.
-
-Fri Sep 13 08:54:40 EDT 1996
-  Diagnose some illegal appearances of substring notation.
-
-Tue Sep 17 17:48:09 EDT 1996
-  Fix fault in handling some complex parameters.  Example:
-	subroutine foo(a)
-	double complex a, b
-	parameter(b = (0,1))
-	a = b	! f2c faulted here
-	end
-
-Thu Sep 26 07:47:10 EDT 1996
-  libi77:  fmt.h:  for formatted writes of negative integer*1 values,
-make ic signed on ANSI systems.  If formatted writes of integer*1
-values trouble you when using a K&R C compiler, switch to an ANSI
-compiler or use a compiler flag that makes characters signed.
-
-Tue Oct  1 14:41:36 EDT 1996
-  Give a better error message when dummy arguments appear in data
-statements.
-
-Thu Oct 17 13:37:22 EDT 1996
-  Fix bug in typechecking arguments to character and complex (or
-double complex) functions; the bug could cause length arguments
-for character arguments to be omitted on invocations appearing
-textually after the first invocation.  For example, in
-	subroutine foo
-	character c
-	complex zot
-	call goo(zot(c), zot(c))
-	end
-the length was omitted from the second invocation of zot, and
-there was an erroneous error message about inconsistent calling
-sequences.
-
-Wed Dec  4 13:59:14 EST 1996
-  Fix bug revealed by
-	subroutine test(cdum,rdum)
-	complex cdum
-	rdum=cos(real(cdum))	! "Unexpected tag 3 in opconv_fudge"
-	end
-  Fix glitch in parsing "DO 10 D0 = 1, 10".
-  Fix glitch in parsing
-	real*8 x
-	real*8 x	! erroneous "incompatible type" message
-	call foo(x)
-	end
-  lib[FI]77/makefile: add comment about omitting -x under Solaris.
-
-Mon Dec  9 23:15:02 EST 1996
-  Fix glitch in parameter adjustments for arrays whose lower
-bound depends on a scalar argument.  Example:
-	subroutine bug(p,z,m,n)
-	integer z(*),m,n
-	double precision p(z(m):z(m) + n)	! p_offset botched
-	call foo(p(0), p(n))
-	end
-  libi77: complain about non-positive rec= in direct read and write
-statements.
-  libf77: trivial adjustments; Version.c not changed.
-
-Wed Feb 12 00:18:03 EST 1997
-  output.c: fix (seldom problematic) glitch in out_call: put parens
-around the ... in a test of the form "if (q->tag == TADDR && ...)".
-  vax.c: fix bug revealed in the "psi_offset =" assignment in the
-following example:
-	subroutine foo(psi,m)
-	integer z(100),m
-	common /a/ z
-	double precision psi(z(m):z(m) + 10)
-	call foo(m+1, psi(0),psi(10))
-	end
-
-Mon Feb 24 23:44:54 EST 1997
-  For consistency with f2c's current treatment of adjacent character
-strings in FORMAT statements, recognize a Hollerith string following
-a string (and merge adjacent strings in FORMAT statements).
-
-Wed Feb 26 13:41:11 EST 1997
-  New libf2c.zip, a combination of the libf77 and libi77 bundles (and
-available only by ftp).
-  libf77: adjust functions with a complex output argument to permit
-aliasing it with input arguments.  (For now, at least, this is just
-for possible benefit of g77.)
-  libi77: tweak to ftell_.c for systems with strange definitions of
-SEEK_SET, etc.
-
-Tue Apr  8 20:57:08 EDT 1997
-  libf77: [cz]_div.c: tweaks invisible on most systems (that may
-improve things slightly with optimized compilation on systems that use
-gratuitous extra precision).
-  libi77: fmt.c: adjust to complain at missing numbers in formats
-(but still treat missing ".nnn" as ".0").
-
-Fri Apr 11 14:05:57 EDT 1997
-  libi77: err.c: attempt to make stderr line buffered rather than
-fully buffered.  (Buffering is needed for format items T and TR.)
-
-Thu Apr 17 22:42:43 EDT 1997
- libf77: add F77_aloc.o to makefile (and makefile.u in libf2c.zip).
-
-Fri Apr 25 19:32:09 EDT 1997
- libf77: add [de]time_.c (which may give trouble on some systems).
-
-Tue May 27 09:18:52 EDT 1997
- libi77: ftell_.c: fix typo that caused the third argument to be
-treated as 2 on some systems.
-
-Mon Jun  9 00:04:37 EDT 1997
- libi77 (and libf2c.zip): adjust include order in err.c lread.c wref.c
-rdfmt.c to include fmt.h (etc.) after system includes.  Version.c not
-changed.
-
-Mon Jun  9 14:29:13 EDT 1997
- src/gram.c updated; somehow it did not reflect the change of
-19961001 to gram.dcl.
-
-Mon Jul 21 16:04:54 EDT 1997
-  proc.c: fix glitch in logic for "nonpositive dimension" message.
-  libi77: inquire.c: always include string.h (for possible use with
--DNON_UNIX_STDIO); Version.c not changed.
-
-Thu Jul 24 17:11:23 EDT 1997
-  Tweak "Notice" to reflect the AT&T breakup -- we missed it when
-updating the copyright notices in the source files last summer.
-  Adjust src/makefile so malloc.o is not used by default, but can
-be specified with "make MALLOC=malloc.o".
-  Add comments to src/README about the "CRAY" T3E.
-
-Tue Aug  5 14:53:25 EDT 1997
-  Add definition of calloc to malloc.c; this makes f2c's malloc
-work on some systems where trouble hitherto arose because references
-to calloc brought in the system's malloc.  (On sensible systems,
-calloc is defined separately from malloc.  To avoid confusion on
-other systems, f2c/malloc.c now defines calloc.)
-  libi77: lread.c: adjust to accord with a change to the Fortran 8X
-draft (in 1990 or 1991) that rescinded permission to elide quote marks
-in namelist input of character data; to get the old behavior, compile
-with F8X_NML_ELIDE_QUOTES #defined.  wrtfmt.o: wrt_G: tweak to print
-the right number of 0's for zero under G format.
-
-Sat Aug 16 05:45:32 EDT 1997
-  libi77: iio.c: fix bug in internal writes to an array of character
-strings that sometimes caused one more array element than required by
-the format to be blank-filled.  Example: format(1x).
-
-Wed Sep 17 00:39:29 EDT 1997
-  libi77: fmt.[ch] rdfmt.c wrtfmt.c: tweak struct syl for machines
-with 64-bit pointers and 32-bit ints that did not 64-bit align
-struct syl (e.g., Linux on the DEC Alpha).  This change should be
-invisible on other machines.
-
-Sun Sep 21 22:05:19 EDT 1997
-  libf77: [de]time_.c (Unix systems only): change return type to double.
-
-Thu Dec  4 22:10:09 EST 1997
-  Fix bug with handling large blocks of comments (over 4k); parts of the
-second and subsequent blocks were likely to be lost (not copied into
-comments in the resulting C).  Allow comment lines to be longer before
-breaking them.
-
-Mon Jan 19 17:19:27 EST 1998
-  makefile: change the rule for making gram.c to one for making gram1.c;
-henceforth, asking netlib to "send all from f2c/src" will bring you a
-working gram.c.  Nowadays there are simply too many broken versions of
-yacc floating around.
-  libi77: backspace.c: for b->ufmt==0, change sizeof(int) to
-sizeof(uiolen).  On machines where this would make a difference, it is
-best for portability to compile libI77 with -DUIOLEN_int, which will
-render the change invisible.
-
-Tue Feb 24 08:35:33 EST 1998
-  makefile: remove gram.c from the "make clean" rule.
-
-Wed Feb 25 08:29:39 EST 1998
-  makefile: change CFLAGS assignment to -O; add "veryclean" rule.
-
-Wed Mar  4 13:13:21 EST 1998
-  libi77: open.c: fix glitch in comparing file names under
--DNON_UNIX_STDIO.
-
-Mon Mar  9 23:56:56 EST 1998
-  putpcc.c: omit an unnecessary temporary variable in computing
-(expr)**3.
-  libf77, libi77: minor tweaks to make some C++ compilers happy;
-Version.c not changed.
-
-Wed Mar 18 18:08:47 EST 1998
-  libf77: minor tweaks to [ed]time_.c; Version.c not changed.
-  libi77: endfile.c, open.c: acquire temporary files from tmpfile(),
-unless compiled with -DNON_ANSI_STDIO, which uses mktemp().
-New buffering scheme independent of NON_UNIX_STDIO for handling T
-format items.  Now -DNON_UNIX_STDIO is no longer be necessary for
-Linux, and libf2c no longer causes stderr to be buffered -- the former
-setbuf or setvbuf call for stderr was to make T format items work.
-open.c: use the Posix access() function to check existence or
-nonexistence of files, except under -DNON_POSIX_STDIO, where trial
-fopen calls are used.  In open.c, fix botch in changes of 19980304.
-  libf2c.zip: the PC makefiles are now set for NT/W95, with comments
-about changes for DOS.
-
-Fri Apr  3 17:22:12 EST 1998
-  Adjust fix of 19960913 to again permit substring notation on
-character variables in data statements.
-
-Sun Apr  5 19:26:50 EDT 1998
-  libi77: wsfe.c: make $ format item work: this was lost in the changes
-of 17 March 1998.
-
-Sat May 16 19:08:51 EDT 1998
-  Adjust output of ftnlen constants: rather than appending L,
-prepend (ftnlen).  This should make the resulting C more portable,
-e.g., to systems (such as DEC Alpha Unix systems) on which long
-may be longer than ftnlen.
-  Adjust -r so it also casts REAL expressions passed to intrinsic
-functions to REAL.
-
-Wed May 27 16:02:35 EDT 1998
-  libf2c.zip: tweak description of compiling libf2c for INTEGER*8
-to accord with makefile.u rather than libF77/makefile.
-
-Thu May 28 22:45:59 EDT 1998
-  libi77: backspace.c dfe.c due.c iio.c lread.c rsfe.c sue.c wsfe.c:
-set f__curunit sooner so various error messages will correctly
-identify the I/O unit involved.
-  libf2c.zip: above, plus tweaks to PC makefiles: for some purposes,
-it's still best to compile with -DMSDOS (even for use with NT).
-
-Thu Jun 18 01:22:52 EDT 1998
-  libi77: lread.c: modified so floating-point numbers (containing
-either a decimal point or an exponent field) are treated as errors
-when they appear as list input for integer data.  Compile lread.c with
--DALLOW_FLOAT_IN_INTEGER_LIST_INPUT to restore the old behavior.
-
-Mon Aug 31 10:38:54 EDT 1998
-  formatdata.c: if possible, and assuming doubles must be aligned on
-double boundaries, use existing holes in DATA for common blocks to
-force alignment of the block.  For example,
-	block data
-	common /abc/ a, b
-	double precision a
-	integer b(2)
-	data b(2)/1/
-	end
-used to generate
-	struct {
-	    integer fill_1[3];
-	    integer e_2;
-	    doublereal e_3;
-	    } abc_ = { {0}, 1, 0. };
-and now generates
-	struct {
-	    doublereal fill_1[1];
-	    integer fill_2[1];
-	    integer e_3;
-	    } abc_ = { {0}, {0}, 1 };
-In the old generated C, e_3 was added to force alignment; in the new C,
-fill_1 does this job.
-
-Mon Sep  7 19:48:51 EDT 1998
-  libi77: move e_wdfe from sfe.c to dfe.c, where it was originally.
-Why did it ever move to sfe.c?
-
-Tue Sep  8 10:22:50 EDT 1998
-  Treat dreal as a synonym for dble unless -cd is specified on the
-command line.
-
-Sun Sep 13 22:23:41 EDT 1998
-  format.c: fix bug in writing prototypes under f2c -A ... *.P:
-under some circumstances involving external functions with no known
-type, a null pointer was passed to printf.
-
-Tue Oct 20 23:25:54 EDT 1998
-  Comments added to libf2c/README and libF77/README, pointing out
-the need to modify signal1.h on some systems.
-
-Thu Nov 12 15:34:09 EST 1998
-  libf77, libf2c.zip: minor tweaks to [de]time_.c and the makefiles,
-so makefile.sy, makefile.vc, and makefile.wat deal with [de]time_.c.
-
-Wed Feb 10 22:59:52 EST 1999
-  defs.h lex.c: permit long names (up to at least roughly
-MAX_SHARPLINE_LEN = 1000 characters long) in #line lines (which only
-matters under -g).
-  fc: add -U option; recognize .so files.
-
-Sat Feb 13 10:18:27 EST 1999
-  libf2c: endfile.c, lread.c, signal1.h0: minor tweaks to make some
-(C++) compilers happier; f77_aloc.c: make exit_() visible to C++
-compilers.  Version strings not changed.
-
-Thu Mar 11 23:14:02 EST 1999
-  Modify f2c (exec.c, expr.c) to diagnose incorrect mixing of types
-when (f2c extended) intrinsic functions are involved, as in
-(not(17) .and. 4).  Catching this in the first executable statement
-is a bit tricky, as some checking must be postponed until all statement
-function declarations have been parsed.  Thus there is a chance of
-today's changes introducing bugs under (let us hope) unusual conditions.
-
-Sun Mar 28 13:17:44 EST 1999
-  lex.c: tweak to get the file name right in error messages caused
-by statements just after a # nnn "filename" line emitted by the C
-preprocessor.  (The trouble is that the line following the # nnn line
-must be read to see if it is a continuation of the stuff that preceded
-the # nnn line.)  When # nnn "filename" lines appear among the lines
-for a Fortran statement, the filename reported in an error message for
-the statement should now be the file that was current when the first
-line of the statement was read.
-
-Sun May  2 22:38:25 EDT 1999
-  libf77, libi77, libf2c.zip: make getenv_() more portable (call
-getenv() rather than knowing about char **environ); adjust some
-complex intrinsics to work with overlapping arguments (caused by
-inappropriate use of equivalence); open.c: get "external" versus
-"internal" right in the error message if a file cannot be opened;
-err.c: cast a pointer difference to (int) for %d; rdfmt.c: omit
-fixed-length buffer that could be overwritten by formats Inn or Lnn
-with nn > 83.
-
-Mon May  3 13:14:07 EDT 1999
-  "Invisible" changes to omit a few compiler warnings in f2c and
-libf2c; two new casts in libf2c/open.c that matter with 64-bit longs,
-and one more tweak (libf2c/c_log.c) for pathological equivalences.
-  Minor update to "fc" script: new -L flag and comment correction.
-
-Tue May  4 10:06:26 EDT 1999
-  libf77, libf2c.zip: forgot to copy yesterday's latest updates to
-netlib.
-
-Fri Jun 18 02:33:08 EDT 1999
-  libf2c.zip: rename backspace.c backspac.c, and fix a glitch in it
--- b->ufd may change in t_runc().  (For now, it's still backspace.c
-in the libi77 bundle.)
-
-Sun Jun 27 22:05:47 EDT 1999
-  libf2c.zip, libi77: rsne.c: fix bug in namelist input: a misplaced
-increment could cause wrong array elements to be assigned; e.g.,
-"&input k(5)=10*1 &end" assigned k(5) and k(15 .. 23).
-
-
-Current timestamps of files in "all from f2c/src", sorted by time,
-appear below (mm/dd/year hh:mm:ss).  To bring your source up to date,
-obtain source files with a timestamp later than the time shown in your
-version.c.  Note that the time shown in the current version.c is the
-timestamp of the source module that immediately follows version.c below:
-
- 5/03/1999  12:46:15  version.c
- 5/03/1999  12:39:35  formatdata.c
- 5/03/1999  12:31:14  format.c
- 5/03/1999  12:27:17  p1output.c
- 5/03/1999  12:27:17  data.c
- 5/03/1999  10:01:12  xsum0.out
- 5/03/1999   9:59:36  io.c
- 5/03/1999   9:59:36  misc.c
- 5/03/1999   9:59:36  init.c
- 3/26/1999  23:18:11  lex.c
- 3/11/1999  16:44:17  expr.c
- 3/11/1999  16:42:42  exec.c
- 2/10/1999  17:43:01  defs.h
- 9/08/1998  10:16:51  f2c.1
- 9/08/1998  10:16:48  f2c.1t
- 9/08/1998  10:14:53  intr.c
- 5/16/1998  16:55:49  output.c
- 4/03/1998  17:15:05  gram.c
- 4/03/1998  17:14:59  gram.dcl
- 3/09/1998   0:30:23  putpcc.c
- 2/25/1998   8:18:04  makefile
-12/04/1997  17:44:11  niceprintf.c
- 8/05/1997  10:31:26  malloc.c
- 7/24/1997  17:10:55  README
- 7/24/1997  16:06:19  Notice
- 7/21/1997  12:58:44  proc.c
- 2/11/1997  23:39:14  vax.c
-12/04/1996  13:07:53  gram.exec
- 9/12/1996  12:12:46  equiv.c
- 8/26/1996   9:41:13  sysdep.c
- 7/09/1996  10:40:45  names.c
- 7/04/1996   9:55:45  sysdep.h
- 7/04/1996   9:55:43  put.c
- 7/04/1996   9:55:41  pread.c
- 7/04/1996   9:55:40  parse_args.c
- 7/04/1996   9:55:36  mem.c
- 7/04/1996   9:55:36  memset.c
- 7/04/1996   9:55:35  main.c
- 7/04/1996   9:55:29  error.c
- 7/04/1996   9:55:27  cds.c
- 7/03/1996  15:47:49  xsum.c
- 6/19/1996   7:04:27  f2c.h
- 6/19/1996   2:52:05  defines.h
- 5/13/1996   0:40:32  gram.head
- 2/25/1994   2:07:19  parse.h
- 2/22/1994  19:07:20  iob.h
- 2/22/1994  18:56:53  p1defs.h
- 2/22/1994  18:53:46  output.h
- 2/22/1994  18:51:14  names.h
- 2/22/1994  18:30:41  format.h
- 1/18/1994  18:12:52  tokens
- 3/06/1993  14:13:58  gram.expr
- 1/28/1993   9:03:16  ftypes.h
- 4/06/1990   0:00:57  gram.io
- 2/03/1990   0:58:26  niceprintf.h
- 1/07/1990   1:20:01  usignal.h
-11/27/1989   8:27:37  machdefs.h
- 7/01/1989  11:59:44  pccdefs.h

From c895b6e6ee29238c23b152142851b9f7aaffa259 Mon Sep 17 00:00:00 2001
From: Neel Natu 
Date: Tue, 14 Sep 2010 01:48:01 +0000
Subject: [PATCH 0725/1624] Port r212559 to mips.

Do not explicitly enable interrupts in smp_init_secondary() because it
renders any spinlock protected code after that point to run with
interrupts enabled. This is because the processor is executing in the
context of idlethread whose 'md_spinlock_count' is already set to 1.

Instead just let sched_throw() re-enable interrupts when it releases
the spinlock.

The original powerpc commit log for r212559 is available here:
http://svn.freebsd.org/viewvc/base?view=revision&revision=212559
---
 sys/mips/mips/mp_machdep.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/mips/mips/mp_machdep.c b/sys/mips/mips/mp_machdep.c
index ef2f24c035d..2b993cb9937 100644
--- a/sys/mips/mips/mp_machdep.c
+++ b/sys/mips/mips/mp_machdep.c
@@ -310,8 +310,6 @@ smp_init_secondary(u_int32_t cpuid)
 	while (smp_started == 0)
 		; /* nothing */
 
-	intr_enable();
-
 	/* Start per-CPU event timers. */
 	cpu_initclocks_ap();
 

From 3e5077108665f024058fbc64d290cf3c9c0057c0 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Tue, 14 Sep 2010 01:51:04 +0000
Subject: [PATCH 0726/1624] Avoid repeatedly spamming the console while a timed
 out command is waiting to complete.  Instead, print one message after the
 timeout period expires, and one more when (if) the command eventually
 completes.

MFC after:	1 month
---
 sys/dev/aac/aac.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/sys/dev/aac/aac.c b/sys/dev/aac/aac.c
index b928dba0299..36996177738 100644
--- a/sys/dev/aac/aac.c
+++ b/sys/dev/aac/aac.c
@@ -1129,6 +1129,11 @@ aac_complete(void *context, int pending)
 			AAC_PRINT_FIB(sc, fib);
 			break;
 		}
+		if ((cm->cm_flags & AAC_CMD_TIMEDOUT) != 0)
+			device_printf(sc->aac_dev,
+			    "COMMAND %p COMPLETED AFTER %d SECONDS\n",
+			    cm, (int)(time_uptime-cm->cm_timestamp));
+
 		aac_remove_busy(cm);
 
  		aac_unmap_command(cm);
@@ -2348,7 +2353,7 @@ aac_timeout(struct aac_softc *sc)
 	deadline = time_uptime - AAC_CMD_TIMEOUT;
 	TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
 		if ((cm->cm_timestamp  < deadline)
-			/* && !(cm->cm_flags & AAC_CMD_TIMEDOUT) */) {
+		    && !(cm->cm_flags & AAC_CMD_TIMEDOUT)) {
 			cm->cm_flags |= AAC_CMD_TIMEDOUT;
 			device_printf(sc->aac_dev,
 			    "COMMAND %p (TYPE %d) TIMEOUT AFTER %d SECONDS\n",

From 44633af3c7548fd746bb976a6baa77c116c156c1 Mon Sep 17 00:00:00 2001
From: Peter Grehan 
Date: Tue, 14 Sep 2010 03:18:11 +0000
Subject: [PATCH 0727/1624] Resurrect PSIM support by moving the cacheline
 size-detection warning printf outside of the MMU-disabled region. A call into
 OpenFirmware with the MMU off resulted in an internal PSIM assert.

---
 sys/powerpc/aim/machdep.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/sys/powerpc/aim/machdep.c b/sys/powerpc/aim/machdep.c
index ba06531bc84..a197681072d 100644
--- a/sys/powerpc/aim/machdep.c
+++ b/sys/powerpc/aim/machdep.c
@@ -258,6 +258,7 @@ powerpc_init(vm_offset_t startkernel, vm_offset_t endkernel,
         char		*env;
 	register_t	msr, scratch;
 	uint8_t		*cache_check;
+	int		cacheline_warn;
 	#ifndef __powerpc64__
 	int		ppc64;
 	#endif
@@ -265,6 +266,7 @@ powerpc_init(vm_offset_t startkernel, vm_offset_t endkernel,
 	end = 0;
 	kmdp = NULL;
 	trap_offset = 0;
+	cacheline_warn = 0;
 
 	/*
 	 * Parse metadata if present and fetch parameters.  Must be done
@@ -360,7 +362,8 @@ powerpc_init(vm_offset_t startkernel, vm_offset_t endkernel,
 
 	/*
 	 * Disable translation in case the vector area hasn't been
-	 * mapped (G5).
+	 * mapped (G5). Note that no OFW calls can be made until
+	 * translation is re-enabled.
 	 */
 
 	msr = mfmsr();
@@ -387,7 +390,7 @@ powerpc_init(vm_offset_t startkernel, vm_offset_t endkernel,
 
 	/* Work around psim bug */
 	if (cacheline_size == 0) {
-		printf("WARNING: cacheline size undetermined, setting to 32\n");
+		cacheline_warn = 1;
 		cacheline_size = 32;
 	}
 
@@ -496,6 +499,11 @@ powerpc_init(vm_offset_t startkernel, vm_offset_t endkernel,
 	mtmsr(msr);
 	isync();
 	
+	/* Warn if cachline size was not determined */
+	if (cacheline_warn == 1) {
+		printf("WARNING: cacheline size undetermined, setting to 32\n");
+	}
+
 	/*
 	 * Choose a platform module so we can get the physical memory map.
 	 */

From dd9595e7fa6cb5054f14ebc5fdd2f0a77939b58e Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Tue, 14 Sep 2010 04:48:04 +0000
Subject: [PATCH 0728/1624] Add some foot shooting protection by checking
 singlemul value correctness. Rephrase sysctls descriptions.

Suggested by:	edmaste
---
 sys/kern/kern_clocksource.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/sys/kern/kern_clocksource.c b/sys/kern/kern_clocksource.c
index 29304a496cb..7654acee4e2 100644
--- a/sys/kern/kern_clocksource.c
+++ b/sys/kern/kern_clocksource.c
@@ -105,7 +105,7 @@ static int		profiling = 0;	/* Profiling events enabled. */
 static char		timername[32];	/* Wanted timer. */
 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
 
-static u_int		singlemul = 0;	/* Multiplier for periodic mode. */
+static int		singlemul = 0;	/* Multiplier for periodic mode. */
 TUNABLE_INT("kern.eventtimer.singlemul", &singlemul);
 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RW, &singlemul,
     0, "Multiplier for periodic mode");
@@ -425,6 +425,7 @@ setuptimer(void)
 		periodic = 0;
 	else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
 		periodic = 1;
+	singlemul = MIN(MAX(singlemul, 1), 20);
 	freq = hz * singlemul;
 	while (freq < (profiling ? profhz : stathz))
 		freq += hz;
@@ -614,7 +615,7 @@ cpu_initclocks_bsp(void)
 	 * We want to run stathz in the neighborhood of 128hz.
 	 * We would like profhz to run as often as possible.
 	 */
-	if (singlemul == 0) {
+	if (singlemul <= 0 || singlemul > 20) {
 		if (hz >= 1500 || (hz % 128) == 0)
 			singlemul = 1;
 		else if (hz >= 750)
@@ -844,7 +845,7 @@ sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
 }
 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
     CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
-    0, 0, sysctl_kern_eventtimer_timer, "A", "Kernel event timer");
+    0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
 
 /*
  * Report or change the active event timer periodicity.
@@ -867,6 +868,6 @@ sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
 }
 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
-    0, 0, sysctl_kern_eventtimer_periodic, "I", "Kernel event timer periodic");
+    0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");
 
 #endif

From 4763a8b8c1e4d7e7c8b4511dbed83bb19e143468 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Tue, 14 Sep 2010 04:57:30 +0000
Subject: [PATCH 0729/1624] Replace spin lock with the set of atomics. It is
 impractical for one tc_ticktock() call to wait for another's completion --
 just skip it.

---
 sys/kern/kern_clock.c | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)

diff --git a/sys/kern/kern_clock.c b/sys/kern/kern_clock.c
index ff5747e104c..7fb70d0d11c 100644
--- a/sys/kern/kern_clock.c
+++ b/sys/kern/kern_clock.c
@@ -374,8 +374,7 @@ int	ticks;
 int	psratio;
 
 static DPCPU_DEFINE(int, pcputicks);	/* Per-CPU version of ticks. */
-static struct mtx	global_hardclock_mtx;
-MTX_SYSINIT(global_hardclock_mtx, &global_hardclock_mtx, "ghc_mtx", MTX_SPIN);
+static int global_hardclock_run = 0;
 
 /*
  * Initialize clock frequencies and start both clocks running.
@@ -485,8 +484,10 @@ hardclock_anycpu(int cnt, int usermode)
 	struct thread *td = curthread;
 	struct proc *p = td->td_proc;
 	int *t = DPCPU_PTR(pcputicks);
-	int flags;
-	int global, newticks;
+	int flags, global, newticks;
+#ifdef SW_WATCHDOG
+	int i;
+#endif /* SW_WATCHDOG */
 
 	/*
 	 * Update per-CPU and possibly global ticks values.
@@ -535,19 +536,22 @@ hardclock_anycpu(int cnt, int usermode)
 	callout_tick();
 	/* We are in charge to handle this tick duty. */
 	if (newticks > 0) {
-		mtx_lock_spin(&global_hardclock_mtx);
-		tc_ticktock();
+		/* Dangerous and no need to call these things concurrently. */
+		if (atomic_cmpset_acq_int(&global_hardclock_run, 0, 1)) {
+			tc_ticktock();
 #ifdef DEVICE_POLLING
-		hardclock_device_poll(); /* This is very short and quick. */
+			/* This is very short and quick. */
+			hardclock_device_poll();
 #endif /* DEVICE_POLLING */
+			atomic_store_rel_int(&global_hardclock_run, 0);
+		}
 #ifdef SW_WATCHDOG
 		if (watchdog_enabled > 0) {
-			watchdog_ticks -= newticks;
-			if (watchdog_ticks <= 0)
+			i = atomic_fetchadd_int(&watchdog_ticks, -newticks);
+			if (i > 0 && i <= newticks)
 				watchdog_fire();
 		}
 #endif /* SW_WATCHDOG */
-		mtx_unlock_spin(&global_hardclock_mtx);
 	}
 	if (curcpu == CPU_FIRST())
 		cpu_tick_calibration();

From 0e18987383f8efc7624b61731c42c565293be9d8 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Tue, 14 Sep 2010 08:48:06 +0000
Subject: [PATCH 0730/1624] Make kern_tc.c provide minimum frequency of
 tc_ticktock() calls, required to handle current timecounter wraps. Make
 kern_clocksource.c to honor that requirement, scheduling sleeps on first CPU
 for no more then specified period. Allow other CPUs to sleep up to 1/4 second
 (for any case).

---
 sys/kern/kern_clock.c       | 4 ++--
 sys/kern/kern_clocksource.c | 6 +++++-
 sys/kern/kern_tc.c          | 9 +++++++--
 sys/kern/kern_timeout.c     | 4 ++--
 sys/sys/callout.h           | 2 +-
 sys/sys/timetc.h            | 6 +++++-
 6 files changed, 22 insertions(+), 9 deletions(-)

diff --git a/sys/kern/kern_clock.c b/sys/kern/kern_clock.c
index 7fb70d0d11c..192ec602150 100644
--- a/sys/kern/kern_clock.c
+++ b/sys/kern/kern_clock.c
@@ -457,7 +457,7 @@ hardclock(int usermode, uintfptr_t pc)
 
 	atomic_add_int((volatile int *)&ticks, 1);
 	hardclock_cpu(usermode);
-	tc_ticktock();
+	tc_ticktock(1);
 	cpu_tick_calibration();
 	/*
 	 * If no separate statistics clock is available, run it from here.
@@ -538,7 +538,7 @@ hardclock_anycpu(int cnt, int usermode)
 	if (newticks > 0) {
 		/* Dangerous and no need to call these things concurrently. */
 		if (atomic_cmpset_acq_int(&global_hardclock_run, 0, 1)) {
-			tc_ticktock();
+			tc_ticktock(newticks);
 #ifdef DEVICE_POLLING
 			/* This is very short and quick. */
 			hardclock_device_poll();
diff --git a/sys/kern/kern_clocksource.c b/sys/kern/kern_clocksource.c
index 7654acee4e2..e366ef9583d 100644
--- a/sys/kern/kern_clocksource.c
+++ b/sys/kern/kern_clocksource.c
@@ -49,6 +49,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -247,7 +248,10 @@ getnextcpuevent(struct bintime *event, int idle)
 	state = DPCPU_PTR(timerstate);
 	*event = state->nexthard;
 	if (idle) { /* If CPU is idle - ask callouts for how long. */
-		skip = callout_tickstofirst() - 1;
+		skip = 4;
+		if (curcpu == CPU_FIRST() && tc_min_ticktock_freq > skip)
+			skip = tc_min_ticktock_freq;
+		skip = callout_tickstofirst(hz / skip) - 1;
 		CTR2(KTR_SPARE2, "skip   at %d: %d", curcpu, skip);
 		tmp = hardperiod;
 		bintime_mul(&tmp, skip);
diff --git a/sys/kern/kern_tc.c b/sys/kern/kern_tc.c
index 811b24f30e5..7a34a52470f 100644
--- a/sys/kern/kern_tc.c
+++ b/sys/kern/kern_tc.c
@@ -87,6 +87,8 @@ static struct timehands *volatile timehands = &th0;
 struct timecounter *timecounter = &dummy_timecounter;
 static struct timecounter *timecounters = &dummy_timecounter;
 
+int tc_min_ticktock_freq = 1;
+
 time_t time_second = 1;
 time_t time_uptime = 1;
 
@@ -482,6 +484,8 @@ tc_windup(void)
 	if (th->th_counter != timecounter) {
 		th->th_counter = timecounter;
 		th->th_offset_count = ncount;
+		tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
+		    (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
 	}
 
 	/*-
@@ -767,11 +771,12 @@ static int tc_tick;
 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0, "");
 
 void
-tc_ticktock(void)
+tc_ticktock(int cnt)
 {
 	static int count;
 
-	if (++count < tc_tick)
+	count += cnt;
+	if (count < tc_tick)
 		return;
 	count = 0;
 	tc_windup();
diff --git a/sys/kern/kern_timeout.c b/sys/kern/kern_timeout.c
index 56977923548..89fe544894d 100644
--- a/sys/kern/kern_timeout.c
+++ b/sys/kern/kern_timeout.c
@@ -280,7 +280,7 @@ callout_tick(void)
 }
 
 int
-callout_tickstofirst(void)
+callout_tickstofirst(int limit)
 {
 	struct callout_cpu *cc;
 	struct callout *c;
@@ -291,7 +291,7 @@ callout_tickstofirst(void)
 	cc = CC_SELF();
 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
 	curticks = cc->cc_ticks;
-	while( skip < ncallout && skip < hz/8 ) {
+	while( skip < ncallout && skip < limit ) {
 		sc = &cc->cc_callwheel[ (curticks+skip) & callwheelmask ];
 		/* search scanning ticks */
 		TAILQ_FOREACH( c, sc, c_links.tqe ){
diff --git a/sys/sys/callout.h b/sys/sys/callout.h
index 8fcd06e4f15..c0077a89774 100644
--- a/sys/sys/callout.h
+++ b/sys/sys/callout.h
@@ -96,7 +96,7 @@ int	callout_schedule_on(struct callout *, int, int);
 #define	callout_stop(c)		_callout_stop_safe(c, 0)
 int	_callout_stop_safe(struct callout *, int);
 void	callout_tick(void);
-int	callout_tickstofirst(void);
+int	callout_tickstofirst(int limit);
 extern void (*callout_new_inserted)(int cpu, int ticks);
 
 #endif
diff --git a/sys/sys/timetc.h b/sys/sys/timetc.h
index 3249788563e..dc1dea408c6 100644
--- a/sys/sys/timetc.h
+++ b/sys/sys/timetc.h
@@ -65,11 +65,15 @@ struct timecounter {
 };
 
 extern struct timecounter *timecounter;
+extern int tc_min_ticktock_freq; /*
+				  * Minimal tc_ticktock() call frequency,
+				  * required to handle counter wraps.
+				  */
 
 u_int64_t tc_getfrequency(void);
 void	tc_init(struct timecounter *tc);
 void	tc_setclock(struct timespec *ts);
-void	tc_ticktock(void);
+void	tc_ticktock(int cnt);
 void	cpu_tick_calibration(void);
 
 #ifdef SYSCTL_DECL

From 9aff0c8ff74cc471ba38a43d11d97f2e78fd61d0 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Tue, 14 Sep 2010 10:26:49 +0000
Subject: [PATCH 0731/1624] Fix panic on NULL dereference possible after
 r212541.

---
 sys/kern/kern_timeout.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sys/kern/kern_timeout.c b/sys/kern/kern_timeout.c
index 89fe544894d..98f55da48cc 100644
--- a/sys/kern/kern_timeout.c
+++ b/sys/kern/kern_timeout.c
@@ -672,7 +672,8 @@ retry:
 	c->c_time = ticks + to_ticks;
 	TAILQ_INSERT_TAIL(&cc->cc_callwheel[c->c_time & callwheelmask], 
 			  c, c_links.tqe);
-	if ((c->c_time - cc->cc_firsttick) < 0) {
+	if ((c->c_time - cc->cc_firsttick) < 0 &&
+	    callout_new_inserted != NULL) {
 		cc->cc_firsttick = c->c_time;
 		(*callout_new_inserted)(cpu,
 		    to_ticks + (ticks - cc->cc_ticks));

From 4eeef2e44a92497b2cb17e6fb8e560d202260e2b Mon Sep 17 00:00:00 2001
From: Martin Matuska 
Date: Tue, 14 Sep 2010 10:27:32 +0000
Subject: [PATCH 0732/1624] Add missing vop_vector zfsctl_ops_shares Add
 missing locks around VOP_READDIR and VOP_GETATTR with z_shares_dir

PR:		kern/150544
Approved by:	delphij (mentor)
Obtained from:	perforce (pjd)
MFC after:	1 day
---
 .../uts/common/fs/zfs/zfs_ctldir.c            | 21 +++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
index ab1ba02d705..156c1ee8b81 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
@@ -1101,8 +1101,9 @@ zfsctl_shares_readdir(ap)
 		return (ENOTSUP);
 	}
 	if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &dzp)) == 0) {
+		vn_lock(ZTOV(dzp), LK_SHARED | LK_RETRY);
 		error = VOP_READDIR(ZTOV(dzp), uiop, cr, eofp, ap->a_ncookies, ap->a_cookies);
-		VN_RELE(ZTOV(dzp));
+		VN_URELE(ZTOV(dzp));
 	} else {
 		*eofp = 1;
 		error = ENOENT;
@@ -1149,6 +1150,7 @@ zfsctl_mknode_shares(vnode_t *pvp)
 	    NULL, NULL);
 	sdp = vp->v_data;
 	sdp->zc_cmtime = ((zfsctl_node_t *)pvp->v_data)->zc_cmtime;
+	VOP_UNLOCK(vp, 0);
 	return (vp);
 
 }
@@ -1176,8 +1178,9 @@ zfsctl_shares_getattr(ap)
 		return (ENOTSUP);
 	}
 	if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &dzp)) == 0) {
+		vn_lock(ZTOV(dzp), LK_SHARED | LK_RETRY);
 		error = VOP_GETATTR(ZTOV(dzp), vap, cr);
-		VN_RELE(ZTOV(dzp));
+		VN_URELE(ZTOV(dzp));
 	}
 	ZFS_EXIT(zfsvfs);
 	return (error);
@@ -1253,6 +1256,20 @@ static struct vop_vector zfsctl_ops_snapdir = {
 	.vop_fid =	zfsctl_common_fid,
 };
 
+static struct vop_vector zfsctl_ops_shares = {
+	.vop_default =	&default_vnodeops,
+	.vop_open =	zfsctl_common_open,
+	.vop_close =	zfsctl_common_close,
+	.vop_ioctl =	VOP_EINVAL,
+	.vop_getattr =	zfsctl_shares_getattr,
+	.vop_access =	zfsctl_common_access,
+	.vop_readdir =	zfsctl_shares_readdir,
+	.vop_lookup =	zfsctl_shares_lookup,
+	.vop_inactive =	gfs_vop_inactive,
+	.vop_reclaim =	zfsctl_common_reclaim,
+	.vop_fid =	zfsctl_shares_fid,
+};
+
 /*
  * pvp is the GFS vnode '.zfs/snapshot'.
  *

From 7648b1e9c0cee065d8e5f18a081a9fd84ac52e8a Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 11:13:46 +0000
Subject: [PATCH 0733/1624] Introduce special G_VAL_OPTIONAL define, which when
 given in value field tells geom(8) to ignore it when it is not given and
 don't try to obtain default value.

---
 sbin/geom/class/part/geom_part.c | 16 ++++++++--------
 sbin/geom/core/geom.c            |  5 ++---
 sbin/geom/core/geom.h            |  2 ++
 3 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index 673d90cd161..972e2ffaaf5 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -90,16 +90,16 @@ struct g_command PUBSYM(class_commands)[] = {
 		{ 'b', "start", GPART_AUTOFILL, G_TYPE_STRING },
 		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
 		{ 't', "type", NULL, G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, "", G_TYPE_ASCNUM },
-		{ 'l', "label", "", G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_ASCNUM },
+		{ 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "[-b start] [-s size] -t type [-i index] [-l label] [-f flags] geom"
 	},
 	{ "bootcode", 0, gpart_bootcode, {
-		{ 'b', GPART_PARAM_BOOTCODE, "", G_TYPE_STRING },
-		{ 'p', GPART_PARAM_PARTCODE, "", G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, "", G_TYPE_ASCNUM },
+		{ 'b', GPART_PARAM_BOOTCODE, G_VAL_OPTIONAL, G_TYPE_STRING },
+		{ 'p', GPART_PARAM_PARTCODE, G_VAL_OPTIONAL, G_TYPE_STRING },
+		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_ASCNUM },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "bootcode [-b bootcode] [-p partcode] [-i index] [-f flags] geom"
@@ -109,7 +109,7 @@ struct g_command PUBSYM(class_commands)[] = {
 	},
 	{ "create", 0, gpart_issue, {
 		{ 's', "scheme", NULL, G_TYPE_STRING },
-		{ 'n', "entries", "", G_TYPE_ASCNUM },
+		{ 'n', "entries", G_VAL_OPTIONAL, G_TYPE_ASCNUM },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "-s scheme [-n entries] [-f flags] provider"
@@ -127,8 +127,8 @@ struct g_command PUBSYM(class_commands)[] = {
 	},
 	{ "modify", 0, gpart_issue, {
 		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
-		{ 'l', "label", "", G_TYPE_STRING },
-		{ 't', "type", "", G_TYPE_STRING },
+		{ 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING },
+		{ 't', "type", G_VAL_OPTIONAL, G_TYPE_STRING },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "-i index [-l label] [-t type] [-f flags] geom"
diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index 39731e964a3..d83a232e678 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -374,9 +374,8 @@ parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc,
 				warnx("Option '%c' not specified.",
 				    opt->go_char);
 				usage();
-			} else if (G_OPT_TYPE(opt) == G_TYPE_ASCNUM &&
-			    *(const char *)opt->go_val == '\0') {
-			    	;	/* add nothing. */
+			} else if (opt->go_val == G_VAL_OPTIONAL) {
+				/* add nothing. */
 			} else {
 				set_option(req, opt, opt->go_val);
 			}
diff --git a/sbin/geom/core/geom.h b/sbin/geom/core/geom.h
index c88005ef10a..a148ddaac7a 100644
--- a/sbin/geom/core/geom.h
+++ b/sbin/geom/core/geom.h
@@ -53,6 +53,8 @@
 #define	G_OPT_NUM(opt)		(((opt)->go_type & G_TYPE_NUMMASK) >> G_TYPE_NUMSHIFT)
 #define	G_OPT_NUMINC(opt)	((opt)->go_type += (1 << G_TYPE_NUMSHIFT))
 
+#define	G_VAL_OPTIONAL	((void *)-1)
+
 #define G_OPT_SENTINEL	{ '\0', NULL, NULL, G_TYPE_NONE }
 #define G_NULL_OPTS	{ G_OPT_SENTINEL }
 #define	G_CMD_SENTINEL	{ NULL, 0, NULL, G_NULL_OPTS, NULL }

From f104beb787506157869c5ee4cb479ad27ab093e1 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 11:19:21 +0000
Subject: [PATCH 0734/1624] Remove dot which shouldn't be here, as err(3) will
 attach error message at the end of the string.

---
 sbin/geom/core/geom.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index d83a232e678..1be9b0c37a3 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -262,7 +262,7 @@ set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 	if (G_OPT_TYPE(opt) == G_TYPE_NUMBER ||
 	    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {
 		if (expand_number(val, &number) == -1) {
-			err(EXIT_FAILURE, "Invalid value for '%c' argument.",
+			err(EXIT_FAILURE, "Invalid value for '%c' argument",
 			    opt->go_char);
 		}
 		if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) {

From d1db39d90edd311633f30a743775346a47153570 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 11:36:26 +0000
Subject: [PATCH 0735/1624] All gpart(8) subcommands apart from the 'bootcode'
 subcommand handle given geom/provider names with and without /dev/ prefix.
 Teach the 'bootcode' subcommand to handle /dev/ names as well.

---
 sbin/geom/class/part/geom_part.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index 972e2ffaaf5..a0b84c26826 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -183,6 +183,8 @@ find_geom(struct gclass *classp, const char *name)
 {
 	struct ggeom *gp;
 
+	if (strncmp(name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
+		name += strlen(_PATH_DEV);
 	LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
 		if (strcmp(gp->lg_name, name) == 0)
 			return (gp);

From b312136354e4b1842f94c1c46122ff11cb252673 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 11:42:07 +0000
Subject: [PATCH 0736/1624] Simplify the code a bit.

---
 sys/geom/part/g_part.c | 20 ++++++++------------
 1 file changed, 8 insertions(+), 12 deletions(-)

diff --git a/sys/geom/part/g_part.c b/sys/geom/part/g_part.c
index cedc3ac6461..38f988287cf 100644
--- a/sys/geom/part/g_part.c
+++ b/sys/geom/part/g_part.c
@@ -297,17 +297,14 @@ g_part_new_provider(struct g_geom *gp, struct g_part_table *table,
 }
 
 static int
-g_part_parm_geom(const char *rawname, struct g_geom **v)
+g_part_parm_geom(const char *name, struct g_geom **v)
 {
 	struct g_geom *gp;
-	const char *pname;
 
-	if (strncmp(rawname, _PATH_DEV, strlen(_PATH_DEV)) == 0)
-		pname = rawname + strlen(_PATH_DEV);
-	else
-		pname = rawname;
+	if (strncmp(name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
+		name += strlen(_PATH_DEV);
 	LIST_FOREACH(gp, &g_part_class.geom, geom) {
-		if (!strcmp(pname, gp->name))
+		if (!strcmp(name, gp->name))
 			break;
 	}
 	if (gp == NULL)
@@ -317,14 +314,13 @@ g_part_parm_geom(const char *rawname, struct g_geom **v)
 }
 
 static int
-g_part_parm_provider(const char *pname, struct g_provider **v)
+g_part_parm_provider(const char *name, struct g_provider **v)
 {
 	struct g_provider *pp;
 
-	if (strncmp(pname, _PATH_DEV, strlen(_PATH_DEV)) == 0)
-		pp = g_provider_by_name(pname + strlen(_PATH_DEV));
-	else
-		pp = g_provider_by_name(pname);
+	if (strncmp(name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
+		name += strlen(_PATH_DEV);
+	pp = g_provider_by_name(name);
 	if (pp == NULL)
 		return (EINVAL);
 	*v = pp;

From 75f01cd1041e62c693f83028a6176a9199956ed3 Mon Sep 17 00:00:00 2001
From: Glen Barber 
Date: Tue, 14 Sep 2010 12:12:07 +0000
Subject: [PATCH 0737/1624] Synchronize newfs(8) manual with code.

PR:		61716
Submitted by:	Radim Kolar 
Patch by:	arundel
Approved by:	keramida (mentor)
MFC after:	1 week
---
 sbin/newfs/newfs.8 | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/sbin/newfs/newfs.8 b/sbin/newfs/newfs.8
index f49a730ff50..10631f91ec8 100644
--- a/sbin/newfs/newfs.8
+++ b/sbin/newfs/newfs.8
@@ -28,7 +28,7 @@
 .\"     @(#)newfs.8	8.6 (Berkeley) 5/3/95
 .\" $FreeBSD$
 .\"
-.Dd March 21, 2008
+.Dd September 14, 2010
 .Dt NEWFS 8
 .Os
 .Sh NAME
@@ -125,8 +125,9 @@ and the number of bytes per inode.
 .It Fl d Ar max-extent-size
 The file system may choose to store large files using extents.
 This parameter specifies the largest extent size that may be used.
-It is presently limited to its default value which is 16 times
-the file system blocksize.
+The default value is the file system blocksize.
+It is presently limited to a maximum value of 16 times the
+file system blocksize and a minimum value of the file system blocksize.
 .It Fl e Ar maxbpg
 Indicate the maximum number of blocks any single file can
 allocate out of a cylinder group before it is forced to begin

From 9a13d2e1b3ae17e73e4dea485eab0f716fbafc94 Mon Sep 17 00:00:00 2001
From: Martin Matuska 
Date: Tue, 14 Sep 2010 12:12:18 +0000
Subject: [PATCH 0738/1624] Remove duplicated VFS_HOLD due to a mismerge.

PR:		kern/150544
Approved by:	delphij (mentor)
MFC after:	1 day
---
 .../contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c     | 7 -------
 1 file changed, 7 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
index 15f8767738f..96c973497c1 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
@@ -1226,13 +1226,6 @@ zfs_mount(vfs_t *vfsp)
 	if (error == 0 && ((zfsvfs_t *)vfsp->vfs_data)->z_issnap)
 		VFS_HOLD(mvp->v_vfsp);
 
-	/*
-	 * Add an extra VFS_HOLD on our parent vfs so that it can't
-	 * disappear due to a forced unmount.
-	 */
-	if (error == 0 && ((zfsvfs_t *)vfsp->vfs_data)->z_issnap)
-		VFS_HOLD(mvp->v_vfsp);
-
 out:
 	return (error);
 }

From 56382b5f76bac72dc7ad96066eca62351b15106c Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 16:19:09 +0000
Subject: [PATCH 0739/1624] Update two last places where "arg0" should be used
 instead of "geom".

---
 sbin/geom/class/part/geom_part.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index a0b84c26826..0f2cccaf5bf 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -302,7 +302,7 @@ gpart_autofill_resize(struct gctl_req *req)
 	cp = find_class(&mesh, s);
 	if (cp == NULL)
 		errx(EXIT_FAILURE, "Class %s not found.", s);
-	s = gctl_get_ascii(req, "geom");
+	s = gctl_get_ascii(req, "arg0");
 	if (s == NULL)
 		abort();
 	gp = find_geom(cp, s);
@@ -411,7 +411,7 @@ gpart_autofill(struct gctl_req *req)
 	cp = find_class(&mesh, s);
 	if (cp == NULL)
 		errx(EXIT_FAILURE, "Class %s not found.", s);
-	s = gctl_get_ascii(req, "geom");
+	s = gctl_get_ascii(req, "arg0");
 	if (s == NULL)
 		abort();
 	gp = find_geom(cp, s);

From 8107ecf892d739b480a550a1211b681391ea82b2 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 16:21:13 +0000
Subject: [PATCH 0740/1624] - Change all places where G_TYPE_ASCNUM is used to
 G_TYPE_NUMBER.   It turns out the new type wasn't really needed. - Reorganize
 code a little bit.

---
 sbin/geom/class/part/geom_part.c |  16 +--
 sys/geom/part/g_part.c           | 171 +++++++++++++++++++++----------
 2 files changed, 125 insertions(+), 62 deletions(-)

diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index 0f2cccaf5bf..1a0efba7b84 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -90,7 +90,7 @@ struct g_command PUBSYM(class_commands)[] = {
 		{ 'b', "start", GPART_AUTOFILL, G_TYPE_STRING },
 		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
 		{ 't', "type", NULL, G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER },
 		{ 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
@@ -99,7 +99,7 @@ struct g_command PUBSYM(class_commands)[] = {
 	{ "bootcode", 0, gpart_bootcode, {
 		{ 'b', GPART_PARAM_BOOTCODE, G_VAL_OPTIONAL, G_TYPE_STRING },
 		{ 'p', GPART_PARAM_PARTCODE, G_VAL_OPTIONAL, G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "bootcode [-b bootcode] [-p partcode] [-i index] [-f flags] geom"
@@ -109,13 +109,13 @@ struct g_command PUBSYM(class_commands)[] = {
 	},
 	{ "create", 0, gpart_issue, {
 		{ 's', "scheme", NULL, G_TYPE_STRING },
-		{ 'n', "entries", G_VAL_OPTIONAL, G_TYPE_ASCNUM },
+		{ 'n', "entries", G_VAL_OPTIONAL, G_TYPE_NUMBER },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "-s scheme [-n entries] [-f flags] provider"
 	},
 	{ "delete", 0, gpart_issue, {
-		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "-i index [-f flags] geom"
@@ -126,7 +126,7 @@ struct g_command PUBSYM(class_commands)[] = {
 	    "[-f flags] geom"
 	},
 	{ "modify", 0, gpart_issue, {
-		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
 		{ 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING },
 		{ 't', "type", G_VAL_OPTIONAL, G_TYPE_STRING },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
@@ -135,7 +135,7 @@ struct g_command PUBSYM(class_commands)[] = {
 	},
 	{ "set", 0, gpart_issue, {
 		{ 'a', "attrib", NULL, G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "-a attrib -i index [-f flags] geom"
@@ -151,14 +151,14 @@ struct g_command PUBSYM(class_commands)[] = {
 	},
 	{ "unset", 0, gpart_issue, {
 		{ 'a', "attrib", NULL, G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "-a attrib -i index [-f flags] geom"
 	},
 	{ "resize", 0, gpart_issue, {
 		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
-		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_ASCNUM },
+		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
 		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
 		G_OPT_SENTINEL },
 	    "[-s size] -i index [-f flags] geom"
diff --git a/sys/geom/part/g_part.c b/sys/geom/part/g_part.c
index 38f988287cf..5e1847885cd 100644
--- a/sys/geom/part/g_part.c
+++ b/sys/geom/part/g_part.c
@@ -297,86 +297,155 @@ g_part_new_provider(struct g_geom *gp, struct g_part_table *table,
 }
 
 static int
-g_part_parm_geom(const char *name, struct g_geom **v)
+g_part_parm_geom(struct gctl_req *req, const char *name, struct g_geom **v)
 {
 	struct g_geom *gp;
+	const char *gname;
 
-	if (strncmp(name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
-		name += strlen(_PATH_DEV);
+	gname = gctl_get_asciiparam(req, name);
+	if (gname == NULL)
+		return (ENOATTR);
+	if (strncmp(gname, _PATH_DEV, strlen(_PATH_DEV)) == 0)
+		gname += strlen(_PATH_DEV);
 	LIST_FOREACH(gp, &g_part_class.geom, geom) {
-		if (!strcmp(name, gp->name))
+		if (!strcmp(gname, gp->name))
 			break;
 	}
-	if (gp == NULL)
+	if (gp == NULL) {
+		gctl_error(req, "%d %s '%s'", EINVAL, name, gname);
 		return (EINVAL);
+	}
 	*v = gp;
 	return (0);
 }
 
 static int
-g_part_parm_provider(const char *name, struct g_provider **v)
+g_part_parm_provider(struct gctl_req *req, const char *name,
+    struct g_provider **v)
 {
 	struct g_provider *pp;
+	const char *pname;
 
-	if (strncmp(name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
-		name += strlen(_PATH_DEV);
-	pp = g_provider_by_name(name);
-	if (pp == NULL)
+	pname = gctl_get_asciiparam(req, name);
+	if (pname == NULL)
+		return (ENOATTR);
+	if (strncmp(pname, _PATH_DEV, strlen(_PATH_DEV)) == 0)
+		pname += strlen(_PATH_DEV);
+	pp = g_provider_by_name(pname);
+	if (pp == NULL) {
+		gctl_error(req, "%d %s '%s'", EINVAL, name, pname);
 		return (EINVAL);
+	}
 	*v = pp;
 	return (0);
 }
 
 static int
-g_part_parm_quad(const char *p, quad_t *v)
+g_part_parm_quad(struct gctl_req *req, const char *name, quad_t *v)
 {
+	const char *p;
 	char *x;
 	quad_t q;
 
+	p = gctl_get_asciiparam(req, name);
+	if (p == NULL)
+		return (ENOATTR);
 	q = strtoq(p, &x, 0);
-	if (*x != '\0' || q < 0)
+	if (*x != '\0' || q < 0) {
+		gctl_error(req, "%d %s '%s'", EINVAL, name, p);
 		return (EINVAL);
+	}
 	*v = q;
 	return (0);
 }
 
 static int
-g_part_parm_scheme(const char *p, struct g_part_scheme **v)
+g_part_parm_scheme(struct gctl_req *req, const char *name,
+    struct g_part_scheme **v)
 {
 	struct g_part_scheme *s;
+	const char *p;
 
+	p = gctl_get_asciiparam(req, name);
+	if (p == NULL)
+		return (ENOATTR);
 	TAILQ_FOREACH(s, &g_part_schemes, scheme_list) {
 		if (s == &g_part_null_scheme)
 			continue;
 		if (!strcasecmp(s->name, p))
 			break;
 	}
-	if (s == NULL)
+	if (s == NULL) {
+		gctl_error(req, "%d %s '%s'", EINVAL, name, p);
 		return (EINVAL);
+	}
 	*v = s;
 	return (0);
 }
 
 static int
-g_part_parm_str(const char *p, const char **v)
+g_part_parm_str(struct gctl_req *req, const char *name, const char **v)
 {
+	const char *p;
 
-	if (p[0] == '\0')
+	p = gctl_get_asciiparam(req, name);
+	if (p == NULL)
+		return (ENOATTR);
+	/* An empty label is always valid. */
+	if (strcmp(name, "label") != 0 && p[0] == '\0') {
+		gctl_error(req, "%d %s '%s'", EINVAL, name, p);
 		return (EINVAL);
+	}
 	*v = p;
 	return (0);
 }
 
 static int
-g_part_parm_uint(const char *p, u_int *v)
+g_part_parm_intmax(struct gctl_req *req, const char *name, u_int *v)
 {
-	char *x;
-	long l;
+	const intmax_t *p;
+	int size;
 
-	l = strtol(p, &x, 0);
-	if (*x != '\0' || l < 0 || l > INT_MAX)
+	p = gctl_get_param(req, name, &size);
+	if (p == NULL)
+		return (ENOATTR);
+	if (size != sizeof(*p) || *p < 0 || *p > INT_MAX) {
+		gctl_error(req, "%d %s '%jd'", EINVAL, name, *p);
 		return (EINVAL);
-	*v = (unsigned int)l;
+	}
+	*v = (u_int)*p;
+	return (0);
+}
+
+static int
+g_part_parm_uint32(struct gctl_req *req, const char *name, u_int *v)
+{
+	const uint32_t *p;
+	int size;
+
+	p = gctl_get_param(req, name, &size);
+	if (p == NULL)
+		return (ENOATTR);
+	if (size != sizeof(*p) || *p > INT_MAX) {
+		gctl_error(req, "%d %s '%u'", EINVAL, name, (unsigned int)*p);
+		return (EINVAL);
+	}
+	*v = (u_int)*p;
+	return (0);
+}
+
+static int
+g_part_parm_bootcode(struct gctl_req *req, const char *name, const void **v,
+    unsigned int *s)
+{
+	const void *p;
+	int size;
+
+	p = gctl_get_param(req, name, &size);
+	if (p == NULL)
+		return (ENOATTR);
+	*v = p;
+	*s = size;
 	return (0);
 }
 
@@ -679,7 +748,7 @@ g_part_ctl_create(struct gctl_req *req, struct g_part_parms *gpp)
 	g_topology_assert();
 
 	/* Check that there isn't already a g_part geom on the provider. */
-	error = g_part_parm_geom(pp->name, &gp);
+	error = g_part_parm_geom(req, "provider", &gp);
 	if (!error) {
 		null = gp->softc;
 		if (null->gpt_scheme != &g_part_null_scheme) {
@@ -1225,11 +1294,10 @@ g_part_ctlreq(struct gctl_req *req, struct g_class *mp, const char *verb)
 	struct g_part_parms gpp;
 	struct g_part_table *table;
 	struct gctl_req_arg *ap;
-	const char *p;
 	enum g_part_ctl ctlreq;
 	unsigned int i, mparms, oparms, parm;
 	int auto_commit, close_on_error;
-	int error, len, modifies;
+	int error, modifies;
 
 	G_PART_TRACE((G_T_TOPOLOGY, "%s(%s,%s)", __func__, mp->name, verb));
 	g_topology_assert();
@@ -1381,69 +1449,64 @@ g_part_ctlreq(struct gctl_req *req, struct g_class *mp, const char *verb)
 			gctl_error(req, "%d param '%s'", EINVAL, ap->name);
 			return;
 		}
-		if (parm == G_PART_PARM_BOOTCODE)
-			p = gctl_get_param(req, ap->name, &len);
-		else
-			p = gctl_get_asciiparam(req, ap->name);
-		if (p == NULL) {
-			gctl_error(req, "%d param '%s'", ENOATTR, ap->name);
-			return;
-		}
 		switch (parm) {
 		case G_PART_PARM_ATTRIB:
-			error = g_part_parm_str(p, &gpp.gpp_attrib);
+			error = g_part_parm_str(req, ap->name, &gpp.gpp_attrib);
 			break;
 		case G_PART_PARM_BOOTCODE:
-			gpp.gpp_codeptr = p;
-			gpp.gpp_codesize = len;
-			error = 0;
+			error = g_part_parm_bootcode(req, ap->name,
+			    &gpp.gpp_codeptr, &gpp.gpp_codesize);
 			break;
 		case G_PART_PARM_ENTRIES:
-			error = g_part_parm_uint(p, &gpp.gpp_entries);
+			error = g_part_parm_intmax(req, ap->name,
+			    &gpp.gpp_entries);
 			break;
 		case G_PART_PARM_FLAGS:
-			if (p[0] == '\0')
-				continue;
-			error = g_part_parm_str(p, &gpp.gpp_flags);
+			error = g_part_parm_str(req, ap->name, &gpp.gpp_flags);
 			break;
 		case G_PART_PARM_GEOM:
-			error = g_part_parm_geom(p, &gpp.gpp_geom);
+			error = g_part_parm_geom(req, ap->name, &gpp.gpp_geom);
 			break;
 		case G_PART_PARM_INDEX:
-			error = g_part_parm_uint(p, &gpp.gpp_index);
+			error = g_part_parm_intmax(req, ap->name, &gpp.gpp_index);
 			break;
 		case G_PART_PARM_LABEL:
-			/* An empty label is always valid. */
-			gpp.gpp_label = p;
-			error = 0;
+			error = g_part_parm_str(req, ap->name, &gpp.gpp_label);
 			break;
 		case G_PART_PARM_OUTPUT:
 			error = 0;	/* Write-only parameter */
 			break;
 		case G_PART_PARM_PROVIDER:
-			error = g_part_parm_provider(p, &gpp.gpp_provider);
+			error = g_part_parm_provider(req, ap->name,
+			    &gpp.gpp_provider);
 			break;
 		case G_PART_PARM_SCHEME:
-			error = g_part_parm_scheme(p, &gpp.gpp_scheme);
+			error = g_part_parm_scheme(req, ap->name,
+			    &gpp.gpp_scheme);
 			break;
 		case G_PART_PARM_SIZE:
-			error = g_part_parm_quad(p, &gpp.gpp_size);
+			error = g_part_parm_quad(req, ap->name, &gpp.gpp_size);
 			break;
 		case G_PART_PARM_START:
-			error = g_part_parm_quad(p, &gpp.gpp_start);
+			error = g_part_parm_quad(req, ap->name, &gpp.gpp_start);
 			break;
 		case G_PART_PARM_TYPE:
-			error = g_part_parm_str(p, &gpp.gpp_type);
+			error = g_part_parm_str(req, ap->name, &gpp.gpp_type);
 			break;
 		case G_PART_PARM_VERSION:
-			error = g_part_parm_uint(p, &gpp.gpp_version);
+			error = g_part_parm_uint32(req, ap->name,
+			    &gpp.gpp_version);
 			break;
 		default:
 			error = EDOOFUS;
+			gctl_error(req, "%d %s", error, ap->name);
 			break;
 		}
-		if (error) {
-			gctl_error(req, "%d %s '%s'", error, ap->name, p);
+		if (error != 0) {
+			if (error == ENOATTR) {
+				gctl_error(req, "%d param '%s'", error,
+				    ap->name);
+			}
 			return;
 		}
 		gpp.gpp_parms |= parm;

From fa5383a2609a6c67fdd5ef1255f3e05d8ed68cf5 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 16:22:22 +0000
Subject: [PATCH 0741/1624] Remove now unused G_TYPE_ASCNUM.

---
 sbin/geom/core/geom.c | 3 +--
 sbin/geom/core/geom.h | 1 -
 2 files changed, 1 insertion(+), 3 deletions(-)

diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index 1be9b0c37a3..fae74a6617d 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -259,8 +259,7 @@ set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 		optname = opt->go_name;
 	}
 
-	if (G_OPT_TYPE(opt) == G_TYPE_NUMBER ||
-	    G_OPT_TYPE(opt) == G_TYPE_ASCNUM) {
+	if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) {
 		if (expand_number(val, &number) == -1) {
 			err(EXIT_FAILURE, "Invalid value for '%c' argument",
 			    opt->go_char);
diff --git a/sbin/geom/core/geom.h b/sbin/geom/core/geom.h
index a148ddaac7a..3b0a8eb3c32 100644
--- a/sbin/geom/core/geom.h
+++ b/sbin/geom/core/geom.h
@@ -38,7 +38,6 @@
 #define	G_TYPE_BOOL	0x01
 #define	G_TYPE_STRING	0x02
 #define	G_TYPE_NUMBER	0x03
-#define	G_TYPE_ASCNUM	0x04
 #define	G_TYPE_MASK	0x0f
 #define	G_TYPE_DONE	0x10
 #define	G_TYPE_MULTI	0x20

From cb1d2fe2cddeea45de3a4f29cb413b9e91b21019 Mon Sep 17 00:00:00 2001
From: "Kenneth D. Merry" 
Date: Tue, 14 Sep 2010 17:22:06 +0000
Subject: [PATCH 0742/1624] MFp4: (//depot/projects/mps/...)

Report data overruns properly.

Submitted by:	scottl
---
 sys/dev/mps/mps_sas.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/sys/dev/mps/mps_sas.c b/sys/dev/mps/mps_sas.c
index fd7e21d1f25..b4f1e4c163d 100644
--- a/sys/dev/mps/mps_sas.c
+++ b/sys/dev/mps/mps_sas.c
@@ -1219,11 +1219,9 @@ mpssas_scsiio_complete(struct mps_softc *sc, struct mps_command *cm)
 		ccb->ccb_h.status = CAM_REQ_CMP;
 		break;
 	case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
-		/*
-		 * XXX any way to report this?
-		 */
+		/* resid is ignored for this condition */
 		ccb->csio.resid = 0;
-		ccb->ccb_h.status = CAM_REQ_CMP;
+		ccb->ccb_h.status = CAM_DATA_RUN_ERR;
 		break;
 	case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
 	case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:

From c0b2efce9e62195b13fc5399dba3858005403ed9 Mon Sep 17 00:00:00 2001
From: Kirk McKusick 
Date: Tue, 14 Sep 2010 18:04:05 +0000
Subject: [PATCH 0743/1624] Update comments in soft updates code to more fully
 describe the addition of journalling. Only functional change is to tighten a
 KASSERT.

Reviewed by:	jeff Roberson
---
 sys/ufs/ffs/ffs_softdep.c |  18 ++---
 sys/ufs/ffs/fs.h          |   2 +-
 sys/ufs/ffs/softdep.h     | 163 ++++++++++++++++++++++----------------
 3 files changed, 103 insertions(+), 80 deletions(-)

diff --git a/sys/ufs/ffs/ffs_softdep.c b/sys/ufs/ffs/ffs_softdep.c
index b666c0fcf78..58366af0267 100644
--- a/sys/ufs/ffs/ffs_softdep.c
+++ b/sys/ufs/ffs/ffs_softdep.c
@@ -2378,7 +2378,8 @@ remove_from_journal(wk)
 	/*
 	 * We emulate a TAILQ to save space in most structures which do not
 	 * require TAILQ semantics.  Here we must update the tail position
-	 * when removing the tail which is not the final entry.
+	 * when removing the tail which is not the final entry. This works
+	 * only if the worklist linkage are at the beginning of the structure.
 	 */
 	if (ump->softdep_journal_tail == wk)
 		ump->softdep_journal_tail =
@@ -2605,7 +2606,7 @@ jremref_write(jremref, jseg, data)
 	inoref_write(&jremref->jr_ref, jseg, rec);
 }
 
-static	void
+static void
 jmvref_write(jmvref, jseg, data)
 	struct jmvref *jmvref;
 	struct jseg *jseg;
@@ -2906,9 +2907,9 @@ complete_jseg(jseg)
 		waiting = wk->wk_state & IOWAITING;
 		wk->wk_state &= ~(IOSTARTED | IOWAITING);
 		wk->wk_state |= COMPLETE;
-		KASSERT(i < jseg->js_cnt,
+		KASSERT(i++ < jseg->js_cnt,
 		    ("handle_written_jseg: overflow %d >= %d",
-		    i, jseg->js_cnt));
+		    i - 1, jseg->js_cnt));
 		switch (wk->wk_type) {
 		case D_JADDREF:
 			handle_written_jaddref(WK_JADDREF(wk));
@@ -7492,7 +7493,7 @@ handle_written_sbdep(sbdep, bp)
 	if (inodedep_lookup(mp, fs->fs_sujfree, 0, &inodedep) == 0)
 		panic("handle_written_sbdep: lost inodedep");
 	/*
-	 * Now that we have a record of this indode in stable store allow it
+	 * Now that we have a record of this inode in stable store allow it
 	 * to be written to free up pending work.  Inodes may see a lot of
 	 * write activity after they are unlinked which we must not hold up.
 	 */
@@ -7509,8 +7510,7 @@ handle_written_sbdep(sbdep, bp)
 }
 
 /*
- * Mark an inodedep has unlinked and insert it into the in-memory unlinked
- * list.
+ * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
  */
 static void
 unlinked_inodedep(mp, inodedep)
@@ -7576,7 +7576,7 @@ clear_unlinked_inodedep(inodedep)
 		 * link before us, whether it be the superblock or an inode.
 		 * Unfortunately the list may change while we're waiting
 		 * on the buf lock for either resource so we must loop until
-		 * we lock. the right one.  If both the superblock and an
+		 * we lock the right one.  If both the superblock and an
 		 * inode point to this inode we must clear the inode first
 		 * followed by the superblock.
 		 */
@@ -9094,7 +9094,7 @@ handle_jwork(wkhd)
 /*
  * Handle the bufwait list on an inode when it is safe to release items
  * held there.  This normally happens after an inode block is written but
- * may be delayed and handle later if there are pending journal items that
+ * may be delayed and handled later if there are pending journal items that
  * are not yet safe to be released.
  */
 static struct freefile *
diff --git a/sys/ufs/ffs/fs.h b/sys/ufs/ffs/fs.h
index e863b961c62..42c4cfe60c4 100644
--- a/sys/ufs/ffs/fs.h
+++ b/sys/ufs/ffs/fs.h
@@ -661,7 +661,7 @@ lbn_level(ufs_lbn_t lbn)
 
 /*
  * Size of the segment record header.  There is at most one for each disk
- * block n the journal.  The segment header is followed by an array of
+ * block in the journal.  The segment header is followed by an array of
  * records.  fsck depends on the first element in each record being 'op'
  * and the second being 'ino'.  Segments may span multiple disk blocks but
  * the header is present on each.
diff --git a/sys/ufs/ffs/softdep.h b/sys/ufs/ffs/softdep.h
index 23afbf789a1..f584e91f37a 100644
--- a/sys/ufs/ffs/softdep.h
+++ b/sys/ufs/ffs/softdep.h
@@ -107,6 +107,15 @@
  *
  * The ONWORKLIST flag shows whether the structure is currently linked
  * onto a worklist.
+ *
+ * The UNLINK* flags track the progress of updating the on-disk linked
+ * list of active but unlinked inodes. When an inode is first unlinked
+ * it is marked as UNLINKED. When its on-disk di_freelink has been
+ * written its UNLINKNEXT flags is set. When its predecessor in the
+ * list has its di_freelink pointing at us its UNLINKPREV is set.
+ * When the on-disk list can reach it from the superblock, its
+ * UNLINKONLIST flag is set. Once all of these flags are set, it
+ * is safe to let its last name be removed.
  */
 #define	ATTACHED	0x000001
 #define	UNDONE		0x000002
@@ -353,20 +362,22 @@ struct bmsafemap {
  * or fragment is allocated from a cylinder group. Its state is set to
  * DEPCOMPLETE when its cylinder group map is written. It is converted to
  * an allocdirect or allocindir allocation once the allocator calls the
- * appropriate setup function.
+ * appropriate setup function. It will initially be linked onto a bmsafemap
+ * list. Once converted it can be linked onto the lists described for
+ * allocdirect or allocindir as described below.
  */ 
 struct newblk {
-	struct	worklist nb_list;
+	struct	worklist nb_list;	/* See comment above. */
 #	define	nb_state nb_list.wk_state
-	LIST_ENTRY(newblk) nb_hash;	/* hashed lookup */
-	LIST_ENTRY(newblk) nb_deps; /* bmsafemap's list of newblks */
+	LIST_ENTRY(newblk) nb_hash;	/* Hashed lookup. */
+	LIST_ENTRY(newblk) nb_deps;	/* Bmsafemap's list of newblks. */
 	struct	jnewblk *nb_jnewblk;	/* New block journal entry. */
-	struct	bmsafemap *nb_bmsafemap;/* cylgrp dep (if pending) */
-	struct	freefrag *nb_freefrag;	/* fragment to be freed (if any) */
+	struct	bmsafemap *nb_bmsafemap;/* Cylgrp dep (if pending). */
+	struct	freefrag *nb_freefrag;	/* Fragment to be freed (if any). */
 	struct	indirdephd nb_indirdeps; /* Children indirect blocks. */
-	struct	workhead nb_newdirblk;	/* dir block to notify when written */
+	struct	workhead nb_newdirblk;	/* Dir block to notify when written. */
 	struct	workhead nb_jwork;	/* Journal work pending. */
-	ufs2_daddr_t	nb_newblkno;	/* new value of block pointer */
+	ufs2_daddr_t	nb_newblkno;	/* New value of block pointer. */
 };
 
 /*
@@ -517,16 +528,16 @@ struct freeblks {
 /*
  * A "freework" structure handles the release of a tree of blocks or a single
  * block.  Each indirect block in a tree is allocated its own freework
- * structure so that the indrect block may be freed only when all of its
+ * structure so that the indirect block may be freed only when all of its
  * children are freed.  In this way we enforce the rule that an allocated
  * block must have a valid path to a root that is journaled.  Each child
  * block acquires a reference and when the ref hits zero the parent ref
  * is decremented.  If there is no parent the freeblks ref is decremented.
  */
 struct freework {
-	struct	worklist fw_list;
+	struct	worklist fw_list;		/* Delayed worklist. */
 #	define	fw_state fw_list.wk_state
-	LIST_ENTRY(freework) fw_next;		/* Queue for freeblksk. */
+	LIST_ENTRY(freework) fw_next;		/* Queue for freeblk list. */
 	struct	freeblks *fw_freeblks;		/* Root of operation. */
 	struct	freework *fw_parent;		/* Parent indirect. */
 	ufs2_daddr_t	 fw_blkno;		/* Our block #. */
@@ -545,7 +556,7 @@ struct freework {
  * to be freed as well.
  */
 struct freedep {
-	struct	worklist fd_list;
+	struct	worklist fd_list;	/* Delayed worklist. */
 	struct	freework *fd_freework;	/* Parent freework. */
 };
 
@@ -705,10 +716,10 @@ struct newdirblk {
  * so they may easily be queued in-order on the inodedep.
  */
 struct inoref {
-	struct	worklist if_list;
+	struct	worklist if_list;	/* Journal pending or jseg entries. */
 #	define	if_state if_list.wk_state
 	TAILQ_ENTRY(inoref) if_deps;	/* Links for inodedep. */
-	struct	jsegdep	*if_jsegdep;
+	struct	jsegdep	*if_jsegdep;	/* Will track our journal record. */
 	off_t		if_diroff;	/* Directory offset. */
 	ino_t		if_ino;		/* Inode number. */
 	ino_t		if_parent;	/* Parent inode number. */
@@ -731,8 +742,8 @@ struct inoref {
  * ultimately released when the file is freed or the link is dropped again.
  */
 struct jaddref {
-	struct	inoref	ja_ref;
-#	define	ja_list	ja_ref.if_list	/* Journal pending or jseg entries. */
+	struct	inoref	ja_ref;		/* see inoref above. */
+#	define	ja_list	ja_ref.if_list	/* Jrnl pending, id_inowait, dm_jwork.*/
 #	define	ja_state ja_ref.if_list.wk_state
 	LIST_ENTRY(jaddref) ja_bmdeps;	/* Links for bmsafemap. */
 	union {
@@ -754,21 +765,28 @@ struct jaddref {
  * may proceed as normal. 
  */
 struct jremref {
-	struct	inoref	jr_ref;
-#	define	jr_list	jr_ref.if_list	/* Journal pending or jseg entries. */
+	struct	inoref	jr_ref;		/* see inoref above. */
+#	define	jr_list	jr_ref.if_list	/* Linked to softdep_journal_pending. */
 #	define	jr_state jr_ref.if_list.wk_state
-	LIST_ENTRY(jremref) jr_deps;	/* Links for pagdep. */
+	LIST_ENTRY(jremref) jr_deps;	/* Links for dirrem. */
 	struct	dirrem	*jr_dirrem;	/* Back pointer to dirrem. */
 };
 
+/*
+ * A "jmvref" structure tracks a name relocations within the same
+ * directory block that occur as a result of directory compaction.
+ * It prevents the updated directory entry from being written to disk
+ * until the journal entry is written. Once the journal has been
+ * written the compacted directory may be written to disk.
+ */
 struct jmvref {
-	struct	worklist jm_list;
-	LIST_ENTRY(jmvref) jm_deps;
-	struct pagedep	*jm_pagedep;
-	ino_t		jm_parent;
-	ino_t		jm_ino;
-	off_t		jm_oldoff;
-	off_t		jm_newoff;
+	struct	worklist jm_list;	/* Linked to softdep_journal_pending. */
+	LIST_ENTRY(jmvref) jm_deps;	/* Jmvref on pagedep. */
+	struct pagedep	*jm_pagedep;	/* Back pointer to pagedep. */
+	ino_t		jm_parent;	/* Containing directory inode number. */
+	ino_t		jm_ino;		/* Inode number of our entry. */
+	off_t		jm_oldoff;	/* Our old offset in directory. */
+	off_t		jm_newoff;	/* Our new offset in directory. */
 };
 
 /*
@@ -780,36 +798,37 @@ struct jmvref {
  * write the jnewblk structure is maintained to prevent the bitmaps from
  * reaching the disk.  Ultimately the jnewblk structure will be passed
  * to the free routine as the in memory cg is modified back to the free
- * state at which time it can be released.
+ * state at which time it can be released. It may be held on any of the
+ * fx_jwork, fw_jwork, fb_jwork, ff_jwork, nb_jwork, or ir_jwork lists.
  */
 struct jnewblk {
-	struct	worklist jn_list;
+	struct	worklist jn_list;	/* See lists above. */
 #	define	jn_state jn_list.wk_state
-	struct	jsegdep	*jn_jsegdep;
-	LIST_ENTRY(jnewblk) jn_deps;		/* All jnewblks on bmsafemap */
-	struct	newblk	*jn_newblk;
-	ino_t		jn_ino;
-	ufs_lbn_t	jn_lbn;
-	ufs2_daddr_t	jn_blkno;
-	int		jn_oldfrags;
-	int		jn_frags;
+	struct	jsegdep	*jn_jsegdep;	/* Will track our journal record. */
+	LIST_ENTRY(jnewblk) jn_deps;	/* Jnewblks on sm_jnewblkhd. */
+	struct	newblk	*jn_newblk;	/* Back pointer to newblk. */
+	ino_t		jn_ino;		/* Ino to which allocated. */
+	ufs_lbn_t	jn_lbn;		/* Lbn to which allocated. */
+	ufs2_daddr_t	jn_blkno;	/* Blkno allocated */
+	int		jn_oldfrags;	/* Previous fragments when extended. */
+	int		jn_frags;	/* Number of fragments. */
 };
 
 /*
  * A "jfreeblk" structure tracks the journal write for freeing a block
  * or tree of blocks.  The block pointer must not be cleared in the inode
- * or indirect prior to the jfreeblk being written.
+ * or indirect prior to the jfreeblk being written to the journal.
  */
 struct jfreeblk {
-	struct	worklist jf_list;
+	struct	worklist jf_list;	/* Linked to softdep_journal_pending. */
 #	define	jf_state jf_list.wk_state
-	struct	jsegdep	*jf_jsegdep;
-	struct freeblks	*jf_freeblks;
-	LIST_ENTRY(jfreeblk) jf_deps;
-	ino_t		jf_ino;
-	ufs_lbn_t	jf_lbn;
-	ufs2_daddr_t	jf_blkno;
-	int		jf_frags;
+	struct	jsegdep	*jf_jsegdep;	/* Will track our journal record. */
+	struct freeblks	*jf_freeblks;	/* Back pointer to freeblks. */
+	LIST_ENTRY(jfreeblk) jf_deps;	/* Jfreeblk on fb_jfreeblkhd. */
+	ino_t		jf_ino;		/* Ino from which blocks freed. */
+	ufs_lbn_t	jf_lbn;		/* Lbn from which blocks freed. */
+	ufs2_daddr_t	jf_blkno;	/* Blkno being freed. */
+	int		jf_frags;	/* Number of frags being freed. */
 };
 
 /*
@@ -818,14 +837,14 @@ struct jfreeblk {
  * freeblks operation.
  */
 struct jfreefrag {
-	struct	worklist fr_list;
+	struct	worklist fr_list;	/* Linked to softdep_journal_pending. */
 #	define	fr_state fr_list.wk_state
-	struct	jsegdep	*fr_jsegdep;
-	struct freefrag	*fr_freefrag;
-	ino_t		fr_ino;
-	ufs_lbn_t	fr_lbn;
-	ufs2_daddr_t	fr_blkno;
-	int		fr_frags;
+	struct	jsegdep	*fr_jsegdep;	/* Will track our journal record. */
+	struct freefrag	*fr_freefrag;	/* Back pointer to freefrag. */
+	ino_t		fr_ino;		/* Ino from which frag freed. */
+	ufs_lbn_t	fr_lbn;		/* Lbn from which frag freed. */
+	ufs2_daddr_t	fr_blkno;	/* Blkno being freed. */
+	int		fr_frags;	/* Size of frag being freed. */
 };
 
 /*
@@ -835,42 +854,45 @@ struct jfreefrag {
  * is complete and the truncated inode is fsync'd.
  */
 struct jtrunc {
-	struct	worklist jt_list;
-	struct	jsegdep	*jt_jsegdep;
-	ino_t		 jt_ino;
-	off_t		 jt_size;
-	int		 jt_extsize;
+	struct	worklist jt_list;	/* Linked to softdep_journal_pending. */
+	struct	jsegdep	*jt_jsegdep;	/* Will track our journal record. */
+	ino_t		 jt_ino;	/* Ino being truncated. */
+	off_t		 jt_size;	/* Final file size. */
+	int		 jt_extsize;	/* Final extent size. */
 };
 
 /*
  * A "jsegdep" structure tracks a single reference to a written journal
  * segment so the journal space can be reclaimed when all dependencies
- * have been written.
+ * have been written. It can hang off of id_inowait, dm_jwork, da_jwork,
+ * nb_jwork, ff_jwork, or fb_jwork lists.
  */
 struct jsegdep {
-	struct	worklist jd_list;
+	struct	worklist jd_list;	/* See above for lists. */
 #	define	jd_state jd_list.wk_state
-	struct	jseg	*jd_seg;
+	struct	jseg	*jd_seg;	/* Our journal record. */
 };
 
 /*
  * A "jseg" structure contains all of the journal records written in a
- * single disk write.  jaddref and jremref structures are linked into
+ * single disk write.  The jaddref and jremref structures are linked into
  * js_entries so thay may be completed when the write completes.  The
- * js_deps array contains as many entries as there are ref counts to
- * reduce the number of allocations required per journal write to one.
+ * js_entries also include the write dependency structures: jmvref,
+ * jnewblk, jfreeblk, jfreefrag, and jtrunc.  The js_refs field counts
+ * the number of entries on the js_entries list. Thus there is a single
+ * jseg entry to describe each journal write.
  */
 struct jseg {
 	struct	worklist js_list;	/* b_deps link for journal */
 #	define	js_state js_list.wk_state
 	struct	workhead js_entries;	/* Entries awaiting write */
-	TAILQ_ENTRY(jseg) js_next;
+	TAILQ_ENTRY(jseg) js_next;	/* List of all unfinished segments. */
 	struct	jblocks *js_jblocks;	/* Back pointer to block/seg list */
 	struct	buf *js_buf;		/* Buffer while unwritten */
-	uint64_t js_seq;
-	int	js_size;		/* Allocated size in bytes */
-	int	js_cnt;			/* Total items allocated */
-	int	js_refs;		/* Count of items pending completion */
+	uint64_t js_seq;		/* Journal record sequence number. */
+	int	js_size;		/* Size of journal record in bytes. */
+	int	js_cnt;			/* Total items allocated. */
+	int	js_refs;		/* Count of js_entries items. */
 };
 
 /*
@@ -878,10 +900,11 @@ struct jseg {
  * superblock writes.  This makes sure the superblock is always pointing at
  * the first possible unlinked inode for the suj recovery process.  If a
  * block write completes and we discover a new head is available the buf
- * is dirtied and the dep is kept.
+ * is dirtied and the dep is kept. See the description of the UNLINK*
+ * flags above for more details.
  */
 struct sbdep {
 	struct	worklist sb_list;	/* b_dep linkage */
 	struct	fs	*sb_fs;		/* Filesystem pointer within buf. */
-	struct	ufsmount *sb_ump;
+	struct	ufsmount *sb_ump;	/* Our mount structure */
 };

From 418f1e7b2941c3ccfa48c2e03092f4f80611deea Mon Sep 17 00:00:00 2001
From: Konstantin Belousov 
Date: Tue, 14 Sep 2010 18:58:51 +0000
Subject: [PATCH 0744/1624] Rename the field to not confuse readers. The bytes
 are actually used.

Discussed with:	rmacklem
MFC after:	1 week
---
 sys/sys/mount.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/sys/mount.h b/sys/sys/mount.h
index f68e95dbac9..d9b6ff4ed66 100644
--- a/sys/sys/mount.h
+++ b/sys/sys/mount.h
@@ -56,7 +56,7 @@ typedef struct fsid { int32_t val[2]; } fsid_t;	/* filesystem id type */
 
 struct fid {
 	u_short		fid_len;		/* length of data in bytes */
-	u_short		fid_reserved;		/* force longword alignment */
+	u_short		fid_data0;		/* force longword alignment */
 	char		fid_data[MAXFIDSZ];	/* data (variable length) */
 };
 

From 9ab2708c521aad137d40dbbf5f504b3d89165935 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Tue, 14 Sep 2010 19:35:43 +0000
Subject: [PATCH 0745/1624] Remove redundant raising of the PIL to PIL_TICK as
 the respective locore code already did that.

---
 sys/sparc64/sparc64/machdep.c    | 1 -
 sys/sparc64/sparc64/mp_machdep.c | 1 -
 2 files changed, 2 deletions(-)

diff --git a/sys/sparc64/sparc64/machdep.c b/sys/sparc64/sparc64/machdep.c
index 90da7c62be3..193da2f4b67 100644
--- a/sys/sparc64/sparc64/machdep.c
+++ b/sys/sparc64/sparc64/machdep.c
@@ -587,7 +587,6 @@ sparc64_init(caddr_t mdp, u_long o1, u_long o2, u_long o3, ofw_vec_t *vec)
 	 * enable them.
 	 */
 	intr_init2();
-	wrpr(pil, 0, PIL_TICK);
 	wrpr(pstate, 0, PSTATE_KERNEL);
 
 	/*
diff --git a/sys/sparc64/sparc64/mp_machdep.c b/sys/sparc64/sparc64/mp_machdep.c
index e5a9fb3eeb6..29c74340d46 100644
--- a/sys/sparc64/sparc64/mp_machdep.c
+++ b/sys/sparc64/sparc64/mp_machdep.c
@@ -446,7 +446,6 @@ cpu_mp_bootstrap(struct pcpu *pc)
 	cpu_setregs(pc);
 
 	/* Enable interrupts. */
-	wrpr(pil, 0, PIL_TICK);
 	wrpr(pstate, 0, PSTATE_KERNEL);
 
 	smp_cpus++;

From 4c206df38f2ecc5bea310752b19ff3ccea580691 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Tue, 14 Sep 2010 20:31:09 +0000
Subject: [PATCH 0746/1624] Remove a KASSERT which will also trigger for
 perfectly valid combinations of small maxsize and "large" (including
 BUS_SPACE_UNRESTRICTED) nsegments parameters. Generally using a presz of 0
 (which indeed might indicate the use of bogus parameters for DMA tag
 creation) is not fatal, it just means that no additional DVMA space will be
 preallocated.

---
 sys/sparc64/sparc64/iommu.c | 3 ---
 sys/sun4v/sun4v/hviommu.c   | 3 ---
 2 files changed, 6 deletions(-)

diff --git a/sys/sparc64/sparc64/iommu.c b/sys/sparc64/sparc64/iommu.c
index 9d31303c673..a638e526d77 100644
--- a/sys/sparc64/sparc64/iommu.c
+++ b/sys/sparc64/sparc64/iommu.c
@@ -874,9 +874,6 @@ iommu_dvmamap_create(bus_dma_tag_t dt, int flags, bus_dmamap_t *mapp)
 	 */
 	maxpre = imin(dt->dt_nsegments, IOMMU_MAX_PRE_SEG);
 	presz = dt->dt_maxsize / maxpre;
-	KASSERT(presz != 0, ("%s: bogus preallocation size , nsegments = %d, "
-	    "maxpre = %d, maxsize = %lu", __func__, dt->dt_nsegments, maxpre,
-	    dt->dt_maxsize));
 	for (i = 1; i < maxpre && totsz < IOMMU_MAX_PRE; i++) {
 		currsz = round_io_page(ulmin(presz, IOMMU_MAX_PRE - totsz));
 		error = iommu_dvma_valloc(dt, is, *mapp, currsz);
diff --git a/sys/sun4v/sun4v/hviommu.c b/sys/sun4v/sun4v/hviommu.c
index 5724d752c0e..78076e372be 100644
--- a/sys/sun4v/sun4v/hviommu.c
+++ b/sys/sun4v/sun4v/hviommu.c
@@ -513,9 +513,6 @@ hviommu_dvmamap_create(bus_dma_tag_t dt, int flags, bus_dmamap_t *mapp)
 	 */
 	maxpre = imin(dt->dt_nsegments, IOMMU_MAX_PRE_SEG);
 	presz = dt->dt_maxsize / maxpre;
-	KASSERT(presz != 0, ("hviommu_dvmamap_create: bogus preallocation size "
-	    ", nsegments = %d, maxpre = %d, maxsize = %lu", dt->dt_nsegments,
-	    maxpre, dt->dt_maxsize));
 	for (i = 1; i < maxpre && totsz < IOMMU_MAX_PRE; i++) {
 		currsz = round_io_page(ulmin(presz, IOMMU_MAX_PRE - totsz));
 		error = hviommu_dvma_valloc(dt, him, *mapp, currsz);

From 6c3c4d7109a8d1412297ea302b220eb51a53ef55 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Tue, 14 Sep 2010 20:41:06 +0000
Subject: [PATCH 0747/1624] Use saner nsegments and maxsegsz parameters when
 creating certain DMA tags; tags for 1-byte allocations cannot possibly be
 split across 2 segments and maxsegsz must not exceed maxsize.

---
 sys/dev/usb/usb_busdma.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/dev/usb/usb_busdma.c b/sys/dev/usb/usb_busdma.c
index 45482e25da7..a2856946cc1 100644
--- a/sys/dev/usb/usb_busdma.c
+++ b/sys/dev/usb/usb_busdma.c
@@ -366,9 +366,9 @@ usb_dma_tag_create(struct usb_dma_tag *udt,
 	     /* filter    */ NULL,
 	     /* filterarg */ NULL,
 	     /* maxsize   */ size,
-	     /* nsegments */ (align == 1) ?
+	     /* nsegments */ (align == 1 && size > 1) ?
 	    (2 + (size / USB_PAGE_SIZE)) : 1,
-	     /* maxsegsz  */ (align == 1) ?
+	     /* maxsegsz  */ (align == 1 && size > USB_PAGE_SIZE) ?
 	    USB_PAGE_SIZE : size,
 	     /* flags     */ BUS_DMA_KEEP_PG_OFFSET,
 	     /* lockfn    */ &usb_dma_lock_cb,

From 628ec6d34472e09b9a4bb8974a306da0ba65a4d4 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Tue, 14 Sep 2010 20:54:22 +0000
Subject: [PATCH 0748/1624] Remove dead code.

---
 sbin/geom/core/geom.c | 21 ++++++---------------
 1 file changed, 6 insertions(+), 15 deletions(-)

diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c
index fae74a6617d..0a583ef1261 100644
--- a/sbin/geom/core/geom.c
+++ b/sbin/geom/core/geom.c
@@ -264,21 +264,12 @@ set_option(struct gctl_req *req, struct g_option *opt, const char *val)
 			err(EXIT_FAILURE, "Invalid value for '%c' argument",
 			    opt->go_char);
 		}
-		if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) {
-			ptr = malloc(sizeof(intmax_t));
-			if (ptr == NULL)
-				errx(EXIT_FAILURE, "No memory.");
-			*(intmax_t *)ptr = number;
-			opt->go_val = ptr;
-			gctl_ro_param(req, optname, sizeof(intmax_t),
-			    opt->go_val);
-		} else {
-			asprintf((void *)(&ptr), "%jd", number);
-			if (ptr == NULL)
-				errx(EXIT_FAILURE, "No memory.");
-			opt->go_val = ptr;
-			gctl_ro_param(req, optname, -1, opt->go_val);
-		}
+		ptr = malloc(sizeof(intmax_t));
+		if (ptr == NULL)
+			errx(EXIT_FAILURE, "No memory.");
+		*(intmax_t *)ptr = number;
+		opt->go_val = ptr;
+		gctl_ro_param(req, optname, sizeof(intmax_t), opt->go_val);
 	} else if (G_OPT_TYPE(opt) == G_TYPE_STRING) {
 		gctl_ro_param(req, optname, -1, val);
 	} else if (G_OPT_TYPE(opt) == G_TYPE_BOOL) {

From 2fff0b4f02bc5d35739145f64e2f1167793231dc Mon Sep 17 00:00:00 2001
From: "Kenneth D. Merry" 
Date: Tue, 14 Sep 2010 21:40:29 +0000
Subject: [PATCH 0750/1624] MFp4 (//depot/projects/mps/...)

Add a man page for the mps(4) driver, and reference it in the
mpt(4) driver man page.

Sponsored by:	Spectra Logic Corporation
---
 share/man/man4/Makefile |   1 +
 share/man/man4/mps.4    | 159 ++++++++++++++++++++++++++++++++++++++++
 share/man/man4/mpt.4    |   1 +
 3 files changed, 161 insertions(+)
 create mode 100644 share/man/man4/mps.4

diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile
index 80f6837b705..8db969f3734 100644
--- a/share/man/man4/Makefile
+++ b/share/man/man4/Makefile
@@ -219,6 +219,7 @@ MAN=	aac.4 \
 	mmcsd.4 \
 	mn.4 \
 	mouse.4 \
+	mps.4 \
 	mpt.4 \
 	msk.4 \
 	mtio.4 \
diff --git a/share/man/man4/mps.4 b/share/man/man4/mps.4
new file mode 100644
index 00000000000..684347f3a3d
--- /dev/null
+++ b/share/man/man4/mps.4
@@ -0,0 +1,159 @@
+.\" 
+.\" Copyright (c) 2010 Spectra Logic Corporation
+.\" 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,
+.\"    without modification.
+.\" 2. Redistributions in binary form must reproduce at minimum a disclaimer
+.\"    substantially similar to the "NO WARRANTY" disclaimer below
+.\"    ("Disclaimer") and any redistribution must be conditioned upon
+.\"    including a substantially similar Disclaimer requirement for further
+.\"    binary redistribution.
+.\" 
+.\" NO WARRANTY
+.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+.\" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+.\" LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
+.\" A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+.\" HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
+.\" 
+.\" mps driver man page.
+.\"
+.\" Author: Ken Merry 
+.\"
+.\" $Id: //depot/SpectraBSD/head/share/man/man4/mps.4#1 $
+.\" $FreeBSD$
+.\"
+.Dd September 13, 2010
+.Dt MPS 4
+.Os
+.Sh NAME
+.Nm mps
+.Nd LSI Fusion-MPT 2 Serial Attached SCSI driver
+.Sh SYNOPSIS
+To compile this driver into your kernel,
+place the following lines in your kernel configuration file:
+.Bd -ragged -offset indent
+.Cd "device scbus"
+.Cd "device mps"
+.Ed
+.Pp
+Or, to load the driver as a module at boot, place the following line in
+.Xr loader.conf 5 :
+.Bd -literal -offset indent
+mpt_load="YES"
+.Ed
+.Sh DESCRIPTION
+The
+.Nm
+driver provides support for LSI Logic Fusion-MPT 2
+.Tn SAS
+controllers.
+.Sh HARDWARE
+The following controllers are supported by the
+.Nm
+driver
+.Pp
+.Bl -bullet -compact
+.It
+LSI Logic SAS2004 (4 Port
+.Tn SAS )
+.It
+LSI Logic SAS2008 (8 Port
+.Tn SAS )
+.It
+LSI Logic SAS2108 (8 Port
+.Tn SAS )
+.It
+LSI Logic SAS2116 (16 Port
+.Tn SAS )
+.It
+LSI Logic SAS2208 (8 Port
+.Tn SAS )
+.El
+.Sh CONFIGURATION
+To disable MSI interrupts for all
+.Nm
+driver instances, set the following tunable value in
+.Xr loader.conf 5 :
+.Bd -literal -offset indent
+hw.mps.disable_msi=1
+.Ed
+.Pp
+To disable MSI-X interrupts for all
+.Nm
+driver instances, set the following tunable value in
+.Xr loader.conf 5 :
+.Bd -literal -offset indent
+hw.mps.disable_msix=1
+.Ed
+.Sh DEBUGGING
+To enable debugging prints from the
+.Nm
+driver, set the
+.Bd -literal -offset indent
+hw.mps.X.debug_level
+.Ed
+.Pp
+variable, where X is the adapter number, either in
+.Xr loader.conf 5
+or via
+.Xr sysctl 8 .
+The following bits have the described effects:
+.Bl -tag -offset indent
+.It 0x01
+Enable informational prints.
+.It 0x02
+Enable tracing prints.
+.It 0x04
+Enable prints for driver faults.
+.It 0x08
+Enable prints for controller events.
+.El
+.Sh SEE ALSO
+.Xr cd 4 ,
+.Xr ch 4 ,
+.Xr da 4 ,
+.Xr mpt 4 ,
+.Xr pci 4 ,
+.Xr sa 4 ,
+.Xr scsi 4 ,
+.Xr targ 4
+.Sh BUGS
+This driver is still in development, it has only been tested on the amd64
+architecture and has some known shortcomings:
+.Bl -bullet -compact
+.It
+No IR (Integrated RAID) support.
+.It 
+No userland utility support (e.g.
+.Xr mptutil 8).
+.It
+Sometimes the driver gets into a state where devices arrive and depart multiple
+times, without user intervention.
+.It
+The error recovery code isn't complete.
+.El
+.Sh HISTORY
+The
+.Nm
+driver first appeared in
+.Fx 9.0 .
+.Sh AUTHORS
+.An -nosplit
+The
+.Nm
+driver was originally written by
+.An Scott Long Aq scottl@FreeBSD.org .
+This man page was written by
+.An Ken Merry Aq ken@FreeBSD.org .
diff --git a/share/man/man4/mpt.4 b/share/man/man4/mpt.4
index f355fd21562..50ae0c6713a 100644
--- a/share/man/man4/mpt.4
+++ b/share/man/man4/mpt.4
@@ -152,6 +152,7 @@ can take on - no separate compilation is required.
 .Xr cd 4 ,
 .Xr ch 4 ,
 .Xr da 4 ,
+.Xr mps 4 ,
 .Xr pci 4 ,
 .Xr sa 4 ,
 .Xr scsi 4 ,

From efe89589278343237997a06d51bc265f050c4756 Mon Sep 17 00:00:00 2001
From: Weongyo Jeong 
Date: Tue, 14 Sep 2010 23:27:06 +0000
Subject: [PATCH 0751/1624] Fixes spellings and uses the better sentence. 
 While I'm here bumps date.

Pointed by:	imp, Ruslan Mahmatkhanov 
---
 share/man/man4/bwn.4 | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)

diff --git a/share/man/man4/bwn.4 b/share/man/man4/bwn.4
index 856012eb241..8e2592ae0dd 100644
--- a/share/man/man4/bwn.4
+++ b/share/man/man4/bwn.4
@@ -24,7 +24,7 @@
 .\"
 .\" $FreeBSD$
 .\"
-.Dd September 11, 2010
+.Dd September 14, 2010
 .Dt BWN 4
 .Os
 .Sh NAME
@@ -93,12 +93,11 @@ driver supports Broadcom BCM43xx based wireless devices, including:
 .It "US Robotics 5411	BCM4318	CardBus	b/g"
 .El
 .Pp
-However if the device chipset is one of BCM4301, BCM4303 and BCM4306 rev 2,
-uses
+Users of older Broadcom chipsets (BCM4301, BCM4303 and BCM4306 rev 2)
+must use
 .Xr bwi 4
-instead of
-.Xr bwn 4
-because the vendor dropped the firmware support.
+because the v4 version of the firmware does not support these chips.
+The newer firmware is too big to fit into these old chips.
 .Sh EXAMPLES
 Join an existing BSS network (i.e., connect to an access point):
 .Pp

From 33529b98d5cc8b18867ac51f216c4b9bc69e98e1 Mon Sep 17 00:00:00 2001
From: Peter Grehan 
Date: Wed, 15 Sep 2010 00:17:52 +0000
Subject: [PATCH 0752/1624] Introduce inheritance into the PowerPC MMU kobj
 interface.

include/mmuvar.h - Change the MMU_DEF macro to also create the class
definition as well as define the DATA_SET. Add a macro, MMU_DEF_INHERIT,
which has an extra parameter specifying the MMU class to inherit methods
from. Update the comments at the start of the header file to describe the
new macros.

booke/pmap.c
aim/mmu_oea.c
aim/mmu_oea64.c - Collapse mmu_def_t declaration into updated MMU_DEF macro

The MMU_DEF_INHERIT macro will be used in the PS3 MMU implementation to
allow it to inherit the stock powerpc64 MMU methods.

Reviewed by:	nwhitehorn
---
 sys/powerpc/aim/mmu_oea.c    |  8 ++------
 sys/powerpc/aim/mmu_oea64.c  |  7 +------
 sys/powerpc/booke/pmap.c     |  7 +------
 sys/powerpc/include/mmuvar.h | 38 ++++++++++++++++++++++++++++--------
 4 files changed, 34 insertions(+), 26 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea.c b/sys/powerpc/aim/mmu_oea.c
index 2ade00ffdfc..a31e072d5e8 100644
--- a/sys/powerpc/aim/mmu_oea.c
+++ b/sys/powerpc/aim/mmu_oea.c
@@ -379,12 +379,8 @@ static mmu_method_t moea_methods[] = {
 	{ 0, 0 }
 };
 
-static mmu_def_t oea_mmu = {
-	MMU_TYPE_OEA,
-	moea_methods,
-	0
-};
-MMU_DEF(oea_mmu);
+MMU_DEF(oea_mmu, MMU_TYPE_OEA, moea_methods, 0);
+
 
 static void
 tlbie(vm_offset_t va)
diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index dc055a38699..6328e570103 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -474,12 +474,7 @@ static mmu_method_t moea64_methods[] = {
 	{ 0, 0 }
 };
 
-static mmu_def_t oea64_mmu = {
-	MMU_TYPE_G5,
-	moea64_methods,
-	0
-};
-MMU_DEF(oea64_mmu);
+MMU_DEF(oea64_mmu, MMU_TYPE_G5, moea64_methods, 0);
 
 static __inline u_int
 va_to_pteg(uint64_t vsid, vm_offset_t addr, int large)
diff --git a/sys/powerpc/booke/pmap.c b/sys/powerpc/booke/pmap.c
index 7f2feb947dc..c5e285c8f72 100644
--- a/sys/powerpc/booke/pmap.c
+++ b/sys/powerpc/booke/pmap.c
@@ -384,12 +384,7 @@ static mmu_method_t mmu_booke_methods[] = {
 	{ 0, 0 }
 };
 
-static mmu_def_t booke_mmu = {
-	MMU_TYPE_BOOKE,
-	mmu_booke_methods,
-	0
-};
-MMU_DEF(booke_mmu);
+MMU_DEF(booke_mmu, MMU_TYPE_BOOKE, mmu_booke_methods, 0);
 
 static inline void
 tlb_miss_lock(void)
diff --git a/sys/powerpc/include/mmuvar.h b/sys/powerpc/include/mmuvar.h
index 6e5a213536b..821a49774d5 100644
--- a/sys/powerpc/include/mmuvar.h
+++ b/sys/powerpc/include/mmuvar.h
@@ -31,7 +31,8 @@
 
 /*
  * A PowerPC MMU implementation is declared with a kernel object and
- * an associated method table, similar to a device driver.
+ * an associated method table. The MMU_DEF macro is used to declare
+ * the class, and also links it to the global MMU class list.
  *
  * e.g.
  *
@@ -44,13 +45,12 @@
  *	{ 0, 0 }
  * };
  *
- * static mmu_def_t ppc8xx_mmu = {
- * 	"ppc8xx",
- *	ppc8xx_methods,
- *	sizeof(ppc8xx_mmu_softc),	// or 0 if no softc
- * };
+ * MMU_DEF(ppc8xx, MMU_TYPE_8xx, ppc8xx_methods, sizeof(ppc8xx_mmu_softc));
  *
- * MMU_DEF(ppc8xx_mmu);
+ * A single level of inheritance is supported in a similar fashion to
+ * kobj inheritance e.g.
+ *
+ * MMU_DEF_1(ppc860c, MMU_TYPE_860c, ppc860c_methods, 0, ppc8xx);
  */
 
 #include 
@@ -84,7 +84,29 @@ typedef struct kobj_class	mmu_def_t;
 
 #define MMUMETHOD	KOBJMETHOD
 
-#define MMU_DEF(name)	DATA_SET(mmu_set, name)
+#define MMU_DEF(name, ident, methods, size)	\
+						\
+mmu_def_t name = {				\
+	ident, methods, size, NULL		\
+};						\
+DATA_SET(mmu_set, name)
+
+#define MMU_DEF_INHERIT(name, ident, methods, size, base1)	\
+						\
+static kobj_class_t name ## _baseclasses[] =	\
+       	{ &base1, NULL };			\
+mmu_def_t name = {                              \
+	ident, methods, size, name ## _baseclasses	\
+};                                              \
+DATA_SET(mmu_set, name)
+
+
+#if 0
+mmu_def_t name = {				\
+	ident, methods, size, name ## _baseclasses	\
+};						
+DATA_SET(mmu_set, name)
+#endif
 
 /*
  * Known MMU names

From 435c8a15cf5db54328ca0d4baa46dd5413033f82 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Wed, 15 Sep 2010 01:19:11 +0000
Subject: [PATCH 0753/1624] Add some enums and constants from Adaptec's latest
 driver (build 17911).

---
 sys/dev/aac/aacreg.h | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/sys/dev/aac/aacreg.h b/sys/dev/aac/aacreg.h
index ccec8b214b7..1030dbc1158 100644
--- a/sys/dev/aac/aacreg.h
+++ b/sys/dev/aac/aacreg.h
@@ -306,7 +306,9 @@ struct aac_adapter_init {
 	u_int32_t	HostElapsedSeconds;
 	/* ADAPTER_INIT_STRUCT_REVISION_4 begins here */
 	u_int32_t	InitFlags;			/* flags for supported features */
-#define AAC_INITFLAGS_NEW_COMM_SUPPORTED	1
+#define	AAC_INITFLAGS_NEW_COMM_SUPPORTED	1
+#define	AAC_INITFLAGS_DRIVER_USES_UTC_TIME	0x10
+#define	AAC_INITFLAGS_DRIVER_SUPPORTS_PM	0x20
 	u_int32_t	MaxIoCommands;		/* max outstanding commands */
 	u_int32_t	MaxIoSize;			/* largest I/O command */
 	u_int32_t	MaxFibSize;			/* largest FIB to adapter */
@@ -885,6 +887,17 @@ typedef enum {
 	AifEnBatteryNeedsRecond,	/* The battery needs reconditioning */
 	AifEnClusterEvent,		/* Some cluster event */
 	AifEnDiskSetEvent,		/* A disk set event occured. */
+	AifEnContainerScsiEvent,	/* a container event with no. and scsi id */
+	AifEnPicBatteryEvent,	/* An event gen. by pic_battery.c for an ABM */
+	AifEnExpEvent,		/* Exp. Event Type to replace CTPopUp messages */
+	AifEnRAID6RebuildDone,	/* RAID6 rebuild finished */
+	AifEnSensorOverHeat,	/* Heat Sensor indicate overheat */
+	AifEnSensorCoolDown,	/* Heat Sensor ind. cooled down after overheat */
+	AifFeatureKeysModified,	/* notif. of updated feature keys */
+	AifApplicationExpirationEvent,	/* notif. on app. expiration status */
+	AifEnBackgroundConsistencyCheck,/* BCC notif. for NEC - DDTS 94700 */
+	AifEnAddJBOD,		/* A new JBOD type drive was created (30) */
+	AifEnDeleteJBOD,	/* A JBOD type drive was deleted (31) */
 	AifDriverNotifyStart=199,	/* Notifies for host driver go here */
 	/* Host driver notifications start here */
 	AifDenMorphComplete, 		/* A morph operation completed */

From 707ee8154d2ff1439326ecc497ff3160ecc51999 Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 15 Sep 2010 01:21:30 +0000
Subject: [PATCH 0754/1624] Move back IN_GCLIST flag into field tlflags, since
 thread list and gc list still share same lock.

---
 lib/libthr/thread/thr_private.h | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index aff59a2224e..fd5a2af95e6 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -415,13 +415,13 @@ struct pthread {
 #define THR_FLAGS_PRIVATE	0x0001
 #define	THR_FLAGS_NEED_SUSPEND	0x0002	/* thread should be suspended */
 #define	THR_FLAGS_SUSPENDED	0x0004	/* thread is suspended */
-#define	THR_FLAGS_IN_GCLIST	0x0008	/* thread in gc list */
-#define	THR_FLAGS_DETACHED	0x0010	/* thread is detached */
+#define	THR_FLAGS_DETACHED	0x0008	/* thread is detached */
 
 	/* Thread list flags; only set with thread list lock held. */
 	int			tlflags;
 #define	TLFLAGS_GC_SAFE		0x0001	/* thread safe for cleaning */
 #define	TLFLAGS_IN_TDLIST	0x0002	/* thread in all thread list */
+#define	TLFLAGS_IN_GCLIST	0x0004	/* thread in gc list */
 
 	/* Queue of currently owned NORMAL or PRIO_INHERIT type mutexes. */
 	struct mutex_queue	mutexq;
@@ -559,16 +559,16 @@ do {								\
 	}							\
 } while (0)
 #define	THR_GCLIST_ADD(thrd) do {				\
-	if (((thrd)->flags & THR_FLAGS_IN_GCLIST) == 0) {	\
+	if (((thrd)->tlflags & TLFLAGS_IN_GCLIST) == 0) {	\
 		TAILQ_INSERT_HEAD(&_thread_gc_list, thrd, gcle);\
-		(thrd)->flags |= THR_FLAGS_IN_GCLIST;		\
+		(thrd)->tlflags |= TLFLAGS_IN_GCLIST;		\
 		_gc_count++;					\
 	}							\
 } while (0)
 #define	THR_GCLIST_REMOVE(thrd) do {				\
-	if (((thrd)->flags & THR_FLAGS_IN_GCLIST) != 0) {	\
+	if (((thrd)->tlflags & TLFLAGS_IN_GCLIST) != 0) {	\
 		TAILQ_REMOVE(&_thread_gc_list, thrd, gcle);	\
-		(thrd)->flags &= ~THR_FLAGS_IN_GCLIST;		\
+		(thrd)->tlflags &= ~TLFLAGS_IN_GCLIST;		\
 		_gc_count--;					\
 	}							\
 } while (0)

From 3832fd24f1e8e607d4acce7dc001ff09944ebafc Mon Sep 17 00:00:00 2001
From: David Xu 
Date: Wed, 15 Sep 2010 02:56:32 +0000
Subject: [PATCH 0755/1624] add code to support stack unwinding when thread
 exits. note that only defer-mode cancellation works, asynchrnous mode does
 not work because it lacks of libuwind's support. stack unwinding is not
 enabled unless LIBTHR_UNWIND_STACK is defined in Makefile.

---
 lib/libthr/Makefile             |   8 ++
 lib/libthr/thread/thr_clean.c   |   8 ++
 lib/libthr/thread/thr_create.c  |   5 ++
 lib/libthr/thread/thr_exit.c    | 153 +++++++++++++++++++++++++++++++-
 lib/libthr/thread/thr_init.c    |   4 +
 lib/libthr/thread/thr_private.h |   9 ++
 6 files changed, 185 insertions(+), 2 deletions(-)

diff --git a/lib/libthr/Makefile b/lib/libthr/Makefile
index e64a412f56b..8b7af3acc72 100644
--- a/lib/libthr/Makefile
+++ b/lib/libthr/Makefile
@@ -25,6 +25,14 @@ CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf
 CFLAGS+=-I${.CURDIR}/../../libexec/rtld-elf/${MACHINE_CPUARCH}
 CFLAGS+=-I${.CURDIR}/../libthread_db
 CFLAGS+=-Winline
+
+LIBTHR_UNWIND_STACK=yes
+
+.ifdef LIBTHR_UNWIND_STACK
+CFLAGS+=-I${.CURDIR}/../../contrib/gcc -fexceptions 
+CFLAGS+=-D_PTHREAD_FORCED_UNWIND
+.endif
+
 LDFLAGS+=-Wl,-znodelete
 
 VERSION_DEF=${.CURDIR}/../libc/Versions.def
diff --git a/lib/libthr/thread/thr_clean.c b/lib/libthr/thread/thr_clean.c
index 9cef930e32a..b37a1b5014b 100644
--- a/lib/libthr/thread/thr_clean.c
+++ b/lib/libthr/thread/thr_clean.c
@@ -78,6 +78,9 @@ __pthread_cleanup_pop_imp(int execute)
 void
 _pthread_cleanup_push(void (*routine) (void *), void *arg)
 {
+#ifdef _PTHREAD_FORCED_UNWIND
+	PANIC("_pthread_cleanup_push is not supported while stack unwinding is enabled.");
+#else
 	struct pthread	*curthread = _get_curthread();
 	struct pthread_cleanup *newbuf;
 
@@ -89,10 +92,15 @@ _pthread_cleanup_push(void (*routine) (void *), void *arg)
 		newbuf->prev = curthread->cleanup;
 		curthread->cleanup = newbuf;
 	}
+#endif
 }
 
 void
 _pthread_cleanup_pop(int execute)
 {
+#ifdef _PTHREAD_FORCED_UNWIND
+	PANIC("_pthread_cleanup_pop is not supported while stack unwinding is enabled.");
+#else
 	__pthread_cleanup_pop_imp(execute);
+#endif
 }
diff --git a/lib/libthr/thread/thr_create.c b/lib/libthr/thread/thr_create.c
index d4f5a11820e..f0af20b0bad 100644
--- a/lib/libthr/thread/thr_create.c
+++ b/lib/libthr/thread/thr_create.c
@@ -264,6 +264,11 @@ thread_start(struct pthread *curthread)
 		__sys_sigprocmask(SIG_SETMASK, &set, NULL);
 	}
 
+#ifdef _PTHREAD_FORCED_UNWIND
+	curthread->unwind_stackend = (char *)curthread->attr.stackaddr_attr +
+		curthread->attr.stacksize_attr;
+#endif
+
 	/* Run the current thread's start routine with argument: */
 	_pthread_exit(curthread->start_routine(curthread->arg));
 
diff --git a/lib/libthr/thread/thr_exit.c b/lib/libthr/thread/thr_exit.c
index 9e2e0cb7ccf..2ff39530a4f 100644
--- a/lib/libthr/thread/thr_exit.c
+++ b/lib/libthr/thread/thr_exit.c
@@ -31,6 +31,9 @@
 
 #include "namespace.h"
 #include 
+#ifdef _PTHREAD_FORCED_UNWIND
+#include 
+#endif
 #include 
 #include 
 #include 
@@ -43,8 +46,125 @@
 
 void	_pthread_exit(void *status);
 
+static void	exit_thread(void) __dead2;
+
 __weak_reference(_pthread_exit, pthread_exit);
 
+#ifdef _PTHREAD_FORCED_UNWIND
+
+static void thread_unwind(void) __dead2;
+#ifdef PIC
+static void thread_uw_init(void);
+static _Unwind_Reason_Code thread_unwind_stop(int version,
+	_Unwind_Action actions,
+	_Unwind_Exception_Class exc_class,
+	struct _Unwind_Exception *exc_obj,
+	struct _Unwind_Context *context, void *stop_parameter);
+/* unwind library pointers */
+static _Unwind_Reason_Code (*uwl_forcedunwind)(struct _Unwind_Exception *,
+	_Unwind_Stop_Fn, void *);
+static void (*uwl_resume)(struct _Unwind_Exception *exc);
+static _Unwind_Word (*uwl_getcfa)(struct _Unwind_Context *);
+
+static void
+thread_uw_init(void)
+{
+	static int inited = 0;
+	void *handle;
+
+	if (inited)
+		return;
+	inited = 1;
+	handle = RTLD_DEFAULT;
+	if ((uwl_forcedunwind = dlsym(handle, "_Unwind_ForcedUnwind")) == NULL||
+	    (uwl_resume = dlsym(handle, "_Unwind_Resume")) == NULL ||
+	    (uwl_getcfa = dlsym(handle, "_Unwind_GetCFA")) == NULL) {
+		uwl_forcedunwind = NULL;
+		return;
+	}
+}
+
+void
+_Unwind_Resume(struct _Unwind_Exception *ex)
+{
+	(*uwl_resume)(ex);
+}
+ 
+_Unwind_Reason_Code
+_Unwind_ForcedUnwind(struct _Unwind_Exception *ex, _Unwind_Stop_Fn stop_func,
+	void *stop_arg)
+{
+	return (*uwl_forcedunwind)(ex, stop_func, stop_arg);
+}
+
+_Unwind_Word
+_Unwind_GetCFA(struct _Unwind_Context *context)
+{
+	return (*uwl_getcfa)(context);
+}
+#else
+#pragma weak _Unwind_GetCFA
+#pragma weak _Unwind_ForcedUnwind
+#pragma weak _Unwind_Resume
+#endif /* PIC */
+
+static void
+thread_unwind_cleanup(_Unwind_Reason_Code code, struct _Unwind_Exception *e)
+{
+	/*
+	 * Specification said that _Unwind_Resume should not be used here,
+	 * instead, user should rethrow the exception. For C++ user, they
+	 * should put "throw" sentence in catch(...) block.
+	 */
+	PANIC("exception should be rethrown");
+}
+
+static _Unwind_Reason_Code
+thread_unwind_stop(int version, _Unwind_Action actions,
+	_Unwind_Exception_Class exc_class,
+	struct _Unwind_Exception *exc_obj,
+	struct _Unwind_Context *context, void *stop_parameter)
+{
+	struct pthread *curthread = _get_curthread();
+	struct pthread_cleanup *cur;
+	uintptr_t cfa;
+	int done = 0;
+
+	/* XXX assume stack grows down to lower address */
+
+	cfa = _Unwind_GetCFA(context);
+	if (actions & _UA_END_OF_STACK) {
+		done = 1;
+	} else if (cfa >= (uintptr_t)curthread->unwind_stackend) {
+		done = 1;
+	}
+
+	while ((cur = curthread->cleanup) != NULL &&
+	       (done ||
+		((uintptr_t)cur < (uintptr_t)curthread->unwind_stackend &&
+		 (uintptr_t)cur >= cfa))) {
+			__pthread_cleanup_pop_imp(1);
+	}
+
+	if (done)
+		exit_thread(); /* Never return! */
+
+	return (_URC_NO_REASON);
+}
+
+static void
+thread_unwind(void)
+{
+	struct pthread  *curthread = _get_curthread();
+
+	curthread->ex.exception_class = 0;
+	curthread->ex.exception_cleanup = thread_unwind_cleanup;
+	_Unwind_ForcedUnwind(&curthread->ex, thread_unwind_stop, NULL);
+	PANIC("_Unwind_ForcedUnwind returned");
+}
+
+#endif
+
 void
 _thread_exit(const char *fname, int lineno, const char *msg)
 {
@@ -95,9 +215,38 @@ _pthread_exit_mask(void *status, sigset_t *mask)
 	
 	/* Save the return value: */
 	curthread->ret = status;
-	while (curthread->cleanup != NULL) {
-		_pthread_cleanup_pop(1);
+#ifdef _PTHREAD_FORCED_UNWIND
+#ifdef PIC
+	thread_uw_init();
+	if (uwl_forcedunwind != NULL) {
+		thread_unwind();
 	}
+#else
+	if (_Unwind_ForcedUnwind != NULL) {
+		thread_unwind();
+	}
+#endif /* PIC */
+
+ 	else {
+		while (curthread->cleanup != NULL) {
+			__pthread_cleanup_pop_imp(1);
+		}
+		exit_thread();
+	}
+
+#else
+	while (curthread->cleanup != NULL) {
+		__pthread_cleanup_pop_imp(1);
+	}
+
+	exit_thread();
+#endif /* _PTHREAD_FORCED_UNWIND */
+}
+
+static void
+exit_thread(void)
+{
+	struct pthread *curthread = _get_curthread();
 
 	/* Check if there is thread specific data: */
 	if (curthread->specific != NULL) {
diff --git a/lib/libthr/thread/thr_init.c b/lib/libthr/thread/thr_init.c
index c20f3c8d784..56541a869f5 100644
--- a/lib/libthr/thread/thr_init.c
+++ b/lib/libthr/thread/thr_init.c
@@ -413,6 +413,10 @@ init_main_thread(struct pthread *thread)
 		 &sched_param);
 	thread->attr.prio = sched_param.sched_priority;
 
+#ifdef _PTHREAD_FORCED_UNWIND
+	thread->unwind_stackend = _usrstack;
+#endif
+
 	/* Others cleared to zero by thr_alloc() */
 }
 
diff --git a/lib/libthr/thread/thr_private.h b/lib/libthr/thread/thr_private.h
index fd5a2af95e6..c18eb3d8c99 100644
--- a/lib/libthr/thread/thr_private.h
+++ b/lib/libthr/thread/thr_private.h
@@ -70,6 +70,10 @@
 #include "thr_umtx.h"
 #include "thread_db.h"
 
+#ifdef _PTHREAD_FORCED_UNWIND
+#include 
+#endif
+
 typedef TAILQ_HEAD(pthreadlist, pthread) pthreadlist;
 typedef TAILQ_HEAD(atfork_head, pthread_atfork) atfork_head;
 TAILQ_HEAD(mutex_queue, pthread_mutex);
@@ -446,6 +450,11 @@ struct pthread {
 	/* Cleanup handlers Link List */
 	struct pthread_cleanup	*cleanup;
 
+#ifdef _PTHREAD_FORCED_UNWIND
+	struct _Unwind_Exception	ex;
+	void			*unwind_stackend;
+#endif
+
 	/*
 	 * Magic value to help recognize a valid thread structure
 	 * from an invalid one:

From d11087789ed28d8ed14007035f9f935b53912a81 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 15 Sep 2010 04:51:07 +0000
Subject: [PATCH 0756/1624] Add hpet(4) man page.

---
 share/man/man4/Makefile |   2 +
 share/man/man4/hpet.4   | 105 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 107 insertions(+)
 create mode 100644 share/man/man4/hpet.4

diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile
index 8db969f3734..6e3fd709d92 100644
--- a/share/man/man4/Makefile
+++ b/share/man/man4/Makefile
@@ -133,6 +133,7 @@ MAN=	aac.4 \
 	hfa.4 \
 	hifn.4 \
 	hme.4 \
+	hpet.4 \
 	${_hptiop.4} \
 	${_hptmv.4} \
 	${_hptrr.4} \
@@ -544,6 +545,7 @@ MLINKS+=gif.4 if_gif.4
 MLINKS+=gre.4 if_gre.4
 MLINKS+=hatm.4 if_hatm.4
 MLINKS+=hme.4 if_hme.4
+MLINKS+=hpet.4 acpi_hpet.4
 MLINKS+=${_hptrr.4} ${_rr232x.4}
 MLINKS+=idt.4 if_idt.4
 MLINKS+=igb.4 if_igb.4
diff --git a/share/man/man4/hpet.4 b/share/man/man4/hpet.4
new file mode 100644
index 00000000000..a3b20e0a336
--- /dev/null
+++ b/share/man/man4/hpet.4
@@ -0,0 +1,105 @@
+.\" Copyright (c) 2009 Alexander Motin 
+.\" 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. The name of the author may not be used to endorse or promote products
+.\"    derived from this software without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+.\"
+.\" $FreeBSD$
+.\"
+.Dd September 14, 2010
+.Dt HPET 4
+.Os
+.Sh NAME
+.Nm hpet
+.Nd High Precision Event Timer driver
+.Sh SYNOPSIS
+To compile this driver into the kernel,
+place the following lines in your
+kernel configuration file:
+.Bd -ragged -offset indent
+.Cd "device acpi"
+.Ed
+.Pp
+The following tunables are settable from the
+.Xr loader 8 :
+.Bl -ohang
+.It Va hint.hpet. Ns Ar X Ns Va .allowed_irqs
+is a 32bit mask. Each set bit allows driver to use respective IRQ,
+if BIOS also set respective capability bit in comparator's configuration
+register.
+Default value is 0xffff0000, except some known broken hardware.
+.It Va hint.hpet. Ns Ar X Ns Va .clock
+controls event timers functionality support. Setting to 0, disables it.
+Default value is 1.
+.It Va hint.hpet. Ns Ar X Ns Va .legacy_route
+controls "LegacyReplacement Route" mode. If enabled, HPET will steal IRQ0 of
+i8254 timer and IRQ8 of RTC. Before using it, make sure that respective
+drivers are not using interrupts, by setting also:
+.Bd -literal
+hint.attimer.0.clock=0
+hint.atrtc.0.clock=0
+.Ed
+Default value is 0.
+.It Va hint.hpet. Ns Ar X Ns Va .per_cpu
+controls how much per-CPU event timers should driver attempt to register.
+This functionality requires every comparator in a group to have own unshared
+IRQ, so it depends on hardware capabilities and interrupts configuration.
+Default value is 1.
+.El
+.Sh DESCRIPTION
+This driver uses High Precision Event Timer hardware (part of the chipset,
+usually enumerated via ACPI) to supply kernel with one time counter and
+several (usually from 3 to 8) event timers.
+This hardware includes single main counter with known increment frequency
+(10MHz or more), and several programable comparators (optionally with
+automatic reload feature).
+When value of the main counter matches current value of any comparator,
+interrupt can be generated.
+Depending on hardware capabilities and configuration, interrupt can be
+delivered as regular I/O APIC interrupt (ISA or PCI) in range from 0 to 31,
+or as Front Side Bus interrupt, alike to PCI MSI interrupts, or in so called
+"LegacyReplacement Route" HPET can speal IRQ0 of i8254 and IRQ8 of the RTC.
+Interrupt can be either edge- or level-triggered. In last case they could be
+safely shared with PCI IRQs.
+Driver prefers to use FSB interrupts, if supported, to avoid sharing.
+If it is not possible, it uses single sharable IRQ from PCI range.
+Other modes (LegacyReplacement and ISA IRQs) require special care to setup,
+but could be configured manually via device hints.
+.Pp
+Event timers provided by the driver support both one-shot an periodic modes
+and irrelevant to CPU power states.
+.Pp
+Depending on hardware capabilities and configuration, driver can expose each
+comparator as separate event timer or group them into one or several per-CPU
+event timers. In last case interrupt of every of those comparators within
+group is bound to specific CPU core. This is possible only when each
+of these comparators has own unsharable IRQ.
+.Sh SEE ALSO
+.Xr acpi 4 ,
+.Xr eventtimer 4
+.Sh HISTORY
+The
+.Nm
+driver first appeared in
+.Fx 6.3 .
+Support for event timers was added in
+.Fx 9.0 .

From 885b75a559a820a263a079e364f4448794c730b7 Mon Sep 17 00:00:00 2001
From: Neel Natu 
Date: Wed, 15 Sep 2010 05:10:50 +0000
Subject: [PATCH 0757/1624] Make the meaning of the 'mask' argument to
 'set_intr_mask(mask)' consistent with the meaning of IM bits in the status
 register.

Reviewed by:	jmallett, jchandra
---
 sys/mips/cavium/octeon_mp.c  | 2 +-
 sys/mips/include/cpufunc.h   | 2 +-
 sys/mips/mips/machdep.c      | 2 +-
 sys/mips/mips/trap.c         | 2 +-
 sys/mips/sibyte/sb_machdep.c | 2 +-
 5 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/sys/mips/cavium/octeon_mp.c b/sys/mips/cavium/octeon_mp.c
index a0eae2c095f..34de442eedb 100644
--- a/sys/mips/cavium/octeon_mp.c
+++ b/sys/mips/cavium/octeon_mp.c
@@ -96,7 +96,7 @@ platform_init_ap(int cpuid)
 	 */
 	clock_int_mask = hard_int_mask(5);
 	ipi_int_mask = hard_int_mask(platform_ipi_intrnum());
-	set_intr_mask(MIPS_SR_INT_MASK & ~(ipi_int_mask | clock_int_mask));
+	set_intr_mask(ipi_int_mask | clock_int_mask);
 
 	mips_wbflush();
 }
diff --git a/sys/mips/include/cpufunc.h b/sys/mips/include/cpufunc.h
index efaa3f4f94b..a1715c9fdf4 100644
--- a/sys/mips/include/cpufunc.h
+++ b/sys/mips/include/cpufunc.h
@@ -272,7 +272,7 @@ set_intr_mask(uint32_t mask)
 	uint32_t ostatus;
 
 	ostatus = mips_rd_status();
-	mask = (ostatus & ~MIPS_SR_INT_MASK) | (~mask & MIPS_SR_INT_MASK);
+	mask = (ostatus & ~MIPS_SR_INT_MASK) | (mask & MIPS_SR_INT_MASK);
 	mips_wr_status(mask);
 	return (ostatus);
 }
diff --git a/sys/mips/mips/machdep.c b/sys/mips/mips/machdep.c
index 8c16051f3ad..120fde7a792 100644
--- a/sys/mips/mips/machdep.c
+++ b/sys/mips/mips/machdep.c
@@ -356,7 +356,7 @@ mips_vector_init(void)
 	 * Mask all interrupts. Each interrupt will be enabled
 	 * when handler is installed for it
 	 */
-	set_intr_mask(MIPS_SR_INT_MASK);
+	set_intr_mask(0);
 
 	/* Clear BEV in SR so we start handling our own exceptions */
 	mips_wr_status(mips_rd_status() & ~MIPS_SR_BEV);
diff --git a/sys/mips/mips/trap.c b/sys/mips/mips/trap.c
index 2323c668882..009db7caed6 100644
--- a/sys/mips/mips/trap.c
+++ b/sys/mips/mips/trap.c
@@ -304,7 +304,7 @@ trap(struct trapframe *trapframe)
 	 * return to userland.
 	 */
 	if (trapframe->sr & MIPS_SR_INT_IE) {
-		set_intr_mask(~(trapframe->sr & MIPS_SR_INT_MASK));
+		set_intr_mask(trapframe->sr & MIPS_SR_INT_MASK);
 		intr_enable();
 	} else {
 		intr_disable();
diff --git a/sys/mips/sibyte/sb_machdep.c b/sys/mips/sibyte/sb_machdep.c
index 45f39e8c99b..ba4b62e95a6 100644
--- a/sys/mips/sibyte/sb_machdep.c
+++ b/sys/mips/sibyte/sb_machdep.c
@@ -370,7 +370,7 @@ platform_init_ap(int cpuid)
 	 */
 	clock_int_mask = hard_int_mask(5);
 	ipi_int_mask = hard_int_mask(platform_ipi_intrnum());
-	set_intr_mask(MIPS_SR_INT_MASK & ~(ipi_int_mask | clock_int_mask));
+	set_intr_mask(ipi_int_mask | clock_int_mask);
 }
 
 int

From 391da75b41d0d6c78654c5fd055e720ae70aa076 Mon Sep 17 00:00:00 2001
From: Neel Natu 
Date: Wed, 15 Sep 2010 05:29:13 +0000
Subject: [PATCH 0758/1624] Factor out the common parts of the swarm board in
 SWARM_COMMON and start including that in SWARM and SWARM_SMP kernel configs.

---
 sys/mips/conf/SWARM        | 66 +++-----------------------------------
 sys/mips/conf/SWARM_COMMON | 60 ++++++++++++++++++++++++++++++++++
 sys/mips/conf/SWARM_SMP    | 10 +++++-
 3 files changed, 73 insertions(+), 63 deletions(-)
 create mode 100644 sys/mips/conf/SWARM_COMMON

diff --git a/sys/mips/conf/SWARM b/sys/mips/conf/SWARM
index 041c94da983..d4950cb1776 100644
--- a/sys/mips/conf/SWARM
+++ b/sys/mips/conf/SWARM
@@ -2,69 +2,11 @@
 # $FreeBSD$
 #
 
+include		SWARM_COMMON
+
 ident		SWARM
-options		CPU_SB1
 
-files		"../sibyte/files.sibyte"
-hints		"SWARM.hints"
-
-options		CFE
-options		CFE_CONSOLE
-options		CFE_ENV
-options		ALT_BREAK_TO_DEBUGGER
+options		ISA_MIPS32
 
+makeoptions	ARCH_FLAGS="-mabi=32 -march=mips32"
 makeoptions	LDSCRIPT_NAME=	ldscript.mips.cfe
-
-#cpu		CPU_MIPS64
-#options 	ISA_MIPS64
-#makeoptions	ARCH_FLAGS="-march=mips64 -mgp64 -mabi=o64"
-cpu		CPU_MIPS32
-options 	ISA_MIPS32
-makeoptions	ARCH_FLAGS="-march=mips32"
-
-makeoptions	DEBUG=-g		#Build kernel with gdb(1) debug symbols
-makeoptions	MODULES_OVERRIDE=""
-
-options		DDB
-options		KDB
-
-options		SCHED_4BSD		#4BSD scheduler
-options		INET			#InterNETworking
-options		NFSCLIENT		#Network Filesystem Client
-options		NFS_ROOT		#NFS usable as /, requires NFSCLIENT
-options		PSEUDOFS		#Pseudo-filesystem framework
-options		_KPOSIX_PRIORITY_SCHEDULING #Posix P1003_1B real-time extensions
-
-# Debugging for use in -current
-#options 	DEADLKRES
-options		INVARIANTS
-options		INVARIANT_SUPPORT
-options		WITNESS
-
-options 	FFS			#Fast filesystem
-
-options		KTRACE
-
-device		pci
-device		miibus
-device		bge
-device		loop
-device		ether
-device		md
-device		random
-
-options		USB_DEBUG
-device usb
-device ohci
-device uhci
-device ehci
-
-device umass
-
-device scbus
-device da
-
-device		ata
-device		atadisk
-device		atapicd
-options		ATA_STATIC_ID
diff --git a/sys/mips/conf/SWARM_COMMON b/sys/mips/conf/SWARM_COMMON
new file mode 100644
index 00000000000..1d22e3cea18
--- /dev/null
+++ b/sys/mips/conf/SWARM_COMMON
@@ -0,0 +1,60 @@
+#
+# $FreeBSD$
+#
+
+files		"../sibyte/files.sibyte"
+hints		"SWARM.hints"
+
+options		CFE
+options		CFE_CONSOLE
+options		CFE_ENV
+options		ALT_BREAK_TO_DEBUGGER
+
+cpu		CPU_SB1
+
+makeoptions	DEBUG=-g		#Build kernel with gdb(1) debug symbols
+makeoptions	MODULES_OVERRIDE=""
+
+options		DDB
+options		KDB
+
+options		SCHED_4BSD		#4BSD scheduler
+options		INET			#InterNETworking
+options		NFSCLIENT		#Network Filesystem Client
+options		NFS_ROOT		#NFS usable as /, requires NFSCLIENT
+options		PSEUDOFS		#Pseudo-filesystem framework
+options		_KPOSIX_PRIORITY_SCHEDULING #Posix P1003_1B real-time extensions
+
+# Debugging for use in -current
+#options 	DEADLKRES
+options		INVARIANTS
+options		INVARIANT_SUPPORT
+options		WITNESS
+
+options 	FFS			#Fast filesystem
+
+options		KTRACE
+
+device		pci
+device		miibus
+device		bge
+device		loop
+device		ether
+device		md
+device		random
+
+options		USB_DEBUG
+device usb
+device ohci
+device uhci
+device ehci
+
+device umass
+
+device scbus
+device da
+
+device		ata
+device		atadisk
+device		atapicd
+options		ATA_STATIC_ID
diff --git a/sys/mips/conf/SWARM_SMP b/sys/mips/conf/SWARM_SMP
index ec76ce4ac17..534d0856d75 100644
--- a/sys/mips/conf/SWARM_SMP
+++ b/sys/mips/conf/SWARM_SMP
@@ -1,7 +1,15 @@
 #
 # $FreeBSD$
 #
+
+include		SWARM_COMMON
+
+ident		SWARM_SMP
+
 options		SMP
 options		PRINTF_BUFR_SIZE=128
 
-include		SWARM
+options		ISA_MIPS32
+
+makeoptions	ARCH_FLAGS="-mabi=32 -march=mips32"
+makeoptions	LDSCRIPT_NAME=	ldscript.mips.cfe

From 77a9cf6f2a599d0eaa983c59552821f2b353c87b Mon Sep 17 00:00:00 2001
From: Neel Natu 
Date: Wed, 15 Sep 2010 05:32:10 +0000
Subject: [PATCH 0759/1624] Add 64-bit SWARM board kernel configs.

---
 sys/conf/ldscript.mips.64.cfe | 320 ++++++++++++++++++++++++++++++++++
 sys/mips/conf/SWARM64         |  20 +++
 sys/mips/conf/SWARM64_SMP     |  23 +++
 3 files changed, 363 insertions(+)
 create mode 100644 sys/conf/ldscript.mips.64.cfe
 create mode 100644 sys/mips/conf/SWARM64
 create mode 100644 sys/mips/conf/SWARM64_SMP

diff --git a/sys/conf/ldscript.mips.64.cfe b/sys/conf/ldscript.mips.64.cfe
new file mode 100644
index 00000000000..027456de1ca
--- /dev/null
+++ b/sys/conf/ldscript.mips.64.cfe
@@ -0,0 +1,320 @@
+/*-
+ * Copyright (c) 2001, 2004, 2008, Juniper Networks, Inc.
+ * 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. Neither the name of the Juniper Networks, Inc. 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 JUNIPER NETWORKS 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 JUNIPER NETWORKS 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.
+ *
+ *	JNPR: ldscript.mips,v 1.3 2006/10/11 06:12:04
+ * $FreeBSD$
+ */
+
+/*
+ * This linker script is needed to build a kernel for use by Broadcom CFE
+ * when loaded over TFTP; its ELF loader does not support backwards seek
+ * on network I/O streams.
+ * Furthermore, CFE will only load PT_LOAD segments, therefore the dynamic
+ * sections must be placed in their own segment.
+ */
+
+OUTPUT_FORMAT("elf64-tradbigmips", "elf64-tradbigmips", "elf64-tradlittlemips")
+
+OUTPUT_ARCH(mips)
+ENTRY(_start)
+SEARCH_DIR(/usr/lib);
+/* Do we need any of these for elf?
+   __DYNAMIC = 0;
+PROVIDE (_DYNAMIC = 0);
+*/
+
+PHDRS
+{
+ headers PT_PHDR FILEHDR PHDRS ;
+ interp PT_INTERP ;
+ text PT_LOAD ;
+ dynamic PT_LOAD ;
+ data PT_LOAD ;
+}
+
+SECTIONS
+{
+  /* Read-only sections, merged into text segment: */
+  . = KERNLOADADDR ;
+  .interp     : { *(.interp) 	} :interp
+  .hash          : { *(.hash)		} :text
+  .dynsym        : { *(.dynsym)		}
+  .dynstr        : { *(.dynstr)		}
+  .gnu.version   : { *(.gnu.version)	}
+  .gnu.version_d   : { *(.gnu.version_d)	}
+  .gnu.version_r   : { *(.gnu.version_r)	}
+  .rel.init      : { *(.rel.init)	}
+  .rela.init     : { *(.rela.init)	}
+  .rel.text      :
+    {
+      *(.rel.text)
+      *(.rel.text.*)
+      *(.rel.gnu.linkonce.t.*)
+    }
+  .rela.text     :
+    {
+      *(.rela.text)
+      *(.rela.text.*)
+      *(.rela.gnu.linkonce.t.*)
+    }
+  .rel.fini      : { *(.rel.fini)	}
+  .rela.fini     : { *(.rela.fini)	}
+  .rel.rodata    :
+    {
+      *(.rel.rodata)
+      *(.rel.rodata.*)
+      *(.rel.gnu.linkonce.r.*)
+    }
+  .rela.rodata   :
+    {
+      *(.rela.rodata)
+      *(.rela.rodata.*)
+      *(.rela.gnu.linkonce.r.*)
+    }
+  .rel.data      :
+    {
+      *(.rel.data)
+      *(.rel.data.*)
+      *(.rel.gnu.linkonce.d.*)
+    }
+  .rela.data     :
+    {
+      *(.rela.data)
+      *(.rela.data.*)
+      *(.rela.gnu.linkonce.d.*)
+    }
+  .rel.ctors     : { *(.rel.ctors)	}
+  .rela.ctors    : { *(.rela.ctors)	}
+  .rel.dtors     : { *(.rel.dtors)	}
+  .rela.dtors    : { *(.rela.dtors)	}
+  .rel.got       : { *(.rel.got)		}
+  .rela.got      : { *(.rela.got)		}
+  .rel.sdata     :
+    {
+      *(.rel.sdata)
+      *(.rel.sdata.*)
+      *(.rel.gnu.linkonce.s.*)
+    }
+  .rela.sdata     :
+    {
+      *(.rela.sdata)
+      *(.rela.sdata.*)
+      *(.rela.gnu.linkonce.s.*)
+    }
+  .rel.sbss      :
+    { 
+      *(.rel.sbss)
+      *(.rel.sbss.*)
+      *(.rel.gnu.linkonce.sb.*)
+    }
+  .rela.sbss     :
+    {
+      *(.rela.sbss)
+      *(.rela.sbss.*)
+      *(.rel.gnu.linkonce.sb.*)
+    }
+  .rel.sdata2    : 
+    { 
+      *(.rel.sdata2)
+      *(.rel.sdata2.*)
+      *(.rel.gnu.linkonce.s2.*)
+    }
+  .rela.sdata2   : 
+    {
+      *(.rela.sdata2)
+      *(.rela.sdata2.*)
+      *(.rela.gnu.linkonce.s2.*)
+    }
+  .rel.sbss2     : 
+    { 
+      *(.rel.sbss2)	
+      *(.rel.sbss2.*)
+      *(.rel.gnu.linkonce.sb2.*)
+    }
+  .rela.sbss2    : 
+    { 
+      *(.rela.sbss2)	
+      *(.rela.sbss2.*)
+      *(.rela.gnu.linkonce.sb2.*)
+    }
+  .rel.bss       : 
+    { 
+      *(.rel.bss)
+      *(.rel.bss.*)
+      *(.rel.gnu.linkonce.b.*)
+    }
+  .rela.bss      : 
+    { 
+      *(.rela.bss)
+      *(.rela.bss.*)
+      *(.rela.gnu.linkonce.b.*)
+    }
+  .rel.plt       : { *(.rel.plt)		}
+  .rela.plt      : { *(.rela.plt)		}
+  .init          : 
+  { 
+    KEEP (*(.init))
+  } :text =0x1000000
+  .text      :
+  {
+    *(.trap)
+    *(.text)
+    *(.text.*)
+    *(.stub)
+    /* .gnu.warning sections are handled specially by elf32.em.  */
+    *(.gnu.warning)
+    *(.gnu.linkonce.t.*)
+  } =0x1000000
+  .fini      :
+  {
+    KEEP (*(.fini))
+  } =0x1000000
+  PROVIDE (__etext = .);
+  PROVIDE (_etext = .);
+  PROVIDE (etext = .);
+  .rodata   : { *(.rodata) *(.rodata.*) *(.gnu.linkonce.r.*) }
+  .rodata1   : { *(.rodata1) }
+  .reginfo : { *(.reginfo) }
+  .sdata2   : { *(.sdata2) *(.sdata2.*) *(.gnu.linkonce.s2.*) }
+  .sbss2   : { *(.sbss2) *(.sbss2.*) *(.gnu.linkonce.sb2.*) }
+  . = ALIGN(0x2000) + (. & (0x2000 - 1));
+  .data    :
+  {
+    *(.data)
+    *(.data.*)
+    *(.gnu.linkonce.d.*)
+    SORT(CONSTRUCTORS)
+  } :data
+  .data1   : { *(.data1) }
+  .eh_frame : { KEEP (*(.eh_frame)) }
+  .gcc_except_table : { *(.gcc_except_table) }
+  .ctors   : 
+  {
+    /* gcc uses crtbegin.o to find the start of
+       the constructors, so we make sure it is
+       first.  Because this is a wildcard, it
+       doesn't matter if the user does not
+       actually link against crtbegin.o; the
+       linker won't look for a file to match a
+       wildcard.  The wildcard also means that it
+       doesn't matter which directory crtbegin.o
+       is in.  */
+    KEEP (*crtbegin.o(.ctors))
+    /* We don't want to include the .ctor section from
+       from the crtend.o file until after the sorted ctors.
+       The .ctor section from the crtend file contains the
+       end of ctors marker and it must be last */
+    KEEP (*(EXCLUDE_FILE (*crtend.o ) .ctors))
+    KEEP (*(SORT(.ctors.*)))
+    KEEP (*(.ctors))
+  }
+   .dtors         :
+  {
+    KEEP (*crtbegin.o(.dtors))
+    KEEP (*(EXCLUDE_FILE (*crtend.o ) .dtors))
+    KEEP (*(SORT(.dtors.*)))
+    KEEP (*(.dtors))
+  }
+  .plt      : { *(.plt)	}
+  _gp = ALIGN(16) + 0x7ff0;
+  .got		  : { *(.got.plt) *(.got) }
+  .dynamic       : { *(.dynamic) } :dynamic
+  /* We want the small data sections together, so single-instruction offsets
+     can access them all, and initialized data all before uninitialized, so
+     we can shorten the on-disk segment size.  */
+  .sdata     : 
+  {
+    *(.sdata) 
+    *(.sdata.*)
+    *(.gnu.linkonce.s.*)
+  }
+  _edata = .;
+  PROVIDE (edata = .);
+  __bss_start = .;
+  .sbss      :
+  {
+    PROVIDE (__sbss_start = .);
+    PROVIDE (___sbss_start = .);
+    *(.dynsbss)
+    *(.sbss)
+    *(.sbss.*)
+    *(.gnu.linkonce.sb.*)
+    *(.scommon)
+    PROVIDE (__sbss_end = .);
+    PROVIDE (___sbss_end = .);
+  }
+  .bss       :
+  {
+   *(.dynbss)
+   *(.bss)
+   *(.bss.*)
+   *(.gnu.linkonce.b.*)
+   *(COMMON)
+   /* Align here to ensure that the .bss section occupies space up to
+      _end.  Align after .bss to ensure correct alignment even if the
+      .bss section disappears because there are no input sections.  */
+   . = ALIGN(64 / 8);
+  }
+  . = ALIGN(64 / 8);
+  _end = .;
+  PROVIDE (end = .);
+  /* Stabs debugging sections.  */
+  .stab 0 : { *(.stab) }
+  .stabstr 0 : { *(.stabstr) }
+  .stab.excl 0 : { *(.stab.excl) }
+  .stab.exclstr 0 : { *(.stab.exclstr) }
+  .stab.index 0 : { *(.stab.index) }
+  .stab.indexstr 0 : { *(.stab.indexstr) }
+  .comment 0 : { *(.comment) }
+  /* DWARF debug sections.
+     Symbols in the DWARF debugging sections are relative to the beginning
+     of the section so we begin them at 0.  */
+  /* DWARF 1 */
+  .debug          0 : { *(.debug) }
+  .line           0 : { *(.line) }
+  /* GNU DWARF 1 extensions */
+  .debug_srcinfo  0 : { *(.debug_srcinfo) }
+  .debug_sfnames  0 : { *(.debug_sfnames) }
+  /* DWARF 1.1 and DWARF 2 */
+  .debug_aranges  0 : { *(.debug_aranges) }
+  .debug_pubnames 0 : { *(.debug_pubnames) }
+  /* DWARF 2 */
+  .debug_info     0 : { *(.debug_info) *(.gnu.linkonce.wi.*) }
+  .debug_abbrev   0 : { *(.debug_abbrev) }
+  .debug_line     0 : { *(.debug_line) }
+  .debug_frame    0 : { *(.debug_frame) }
+  .debug_str      0 : { *(.debug_str) }
+  .debug_loc      0 : { *(.debug_loc) }
+  .debug_macinfo  0 : { *(.debug_macinfo) }
+  /* SGI/MIPS DWARF 2 extensions */
+  .debug_weaknames 0 : { *(.debug_weaknames) }
+  .debug_funcnames 0 : { *(.debug_funcnames) }
+  .debug_typenames 0 : { *(.debug_typenames) }
+  .debug_varnames  0 : { *(.debug_varnames) }
+  /* These must appear regardless of  .  */
+}
diff --git a/sys/mips/conf/SWARM64 b/sys/mips/conf/SWARM64
new file mode 100644
index 00000000000..72931b5acc7
--- /dev/null
+++ b/sys/mips/conf/SWARM64
@@ -0,0 +1,20 @@
+#
+# $FreeBSD$
+#
+
+include		SWARM_COMMON
+
+ident		SWARM64
+
+makeoptions	ARCH_FLAGS="-mabi=64 -march=mips64"
+makeoptions	LDSCRIPT_NAME=ldscript.mips.64.cfe
+makeoptions	KERNLOADADDR=0xffffffff80001000
+
+#
+# XXX restrict memory to maximum 4GB because page table entries in pmap
+# are still 32 bits wide
+
+#
+# MAXMEM is specified in units of KB
+#
+options		MAXMEM=0x400000
diff --git a/sys/mips/conf/SWARM64_SMP b/sys/mips/conf/SWARM64_SMP
new file mode 100644
index 00000000000..863c0f0f3ab
--- /dev/null
+++ b/sys/mips/conf/SWARM64_SMP
@@ -0,0 +1,23 @@
+#
+# $FreeBSD$
+#
+
+include		SWARM_COMMON
+
+ident		SWARM64_SMP
+
+options		SMP
+options		PRINTF_BUFR_SIZE=128
+
+makeoptions	ARCH_FLAGS="-mabi=64 -march=mips64"
+makeoptions	LDSCRIPT_NAME=ldscript.mips.64.cfe
+makeoptions	KERNLOADADDR=0xffffffff80001000
+
+#
+# XXX restrict memory to maximum 4GB because page table entries in pmap
+# are still 32 bits wide
+
+#
+# MAXMEM is specified in units of KB
+#
+options		MAXMEM=0x400000

From 1adad4c374f253f8f3d22ef3b0ff6d3cecc79ab2 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 15 Sep 2010 07:04:14 +0000
Subject: [PATCH 0760/1624] Add eventtimers(7) man page, briefly describing
 event timers subsystem functionality and configuration options.

---
 share/man/man4/hpet.4        |   2 +-
 share/man/man7/Makefile      |   1 +
 share/man/man7/eventtimers.7 | 131 +++++++++++++++++++++++++++++++++++
 share/man/man7/tuning.7      |   1 +
 4 files changed, 134 insertions(+), 1 deletion(-)
 create mode 100644 share/man/man7/eventtimers.7

diff --git a/share/man/man4/hpet.4 b/share/man/man4/hpet.4
index a3b20e0a336..49970534730 100644
--- a/share/man/man4/hpet.4
+++ b/share/man/man4/hpet.4
@@ -95,7 +95,7 @@ group is bound to specific CPU core. This is possible only when each
 of these comparators has own unsharable IRQ.
 .Sh SEE ALSO
 .Xr acpi 4 ,
-.Xr eventtimer 4
+.Xr eventtimers 7
 .Sh HISTORY
 The
 .Nm
diff --git a/share/man/man7/Makefile b/share/man/man7/Makefile
index 5a57dbb3527..ab7e020aa89 100644
--- a/share/man/man7/Makefile
+++ b/share/man/man7/Makefile
@@ -10,6 +10,7 @@ MAN=	adding_user.7 \
 	c99.7 \
 	development.7 \
 	environ.7 \
+	eventtimers.7 \
 	ffs.7 \
 	firewall.7 \
 	hier.7 \
diff --git a/share/man/man7/eventtimers.7 b/share/man/man7/eventtimers.7
new file mode 100644
index 00000000000..8fb69122bc0
--- /dev/null
+++ b/share/man/man7/eventtimers.7
@@ -0,0 +1,131 @@
+.\" Copyright (c) 2010 Alexander Motin 
+.\" 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.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+.\"
+.\" $FreeBSD$
+.\"
+.Dd September 15, 2010
+.Dt eventtimers 4
+.Os
+.Sh NAME
+.Nm eventtimers
+.Nd kernel event timers subsystem
+.Sh SYNOPSIS
+Kernel uses several types of time-related devices, such as: real time clocks,
+time counters and event timers.
+Real time clocks responsible for tracking real world time, mostly when system
+is down.
+Time counters are responsible for generation of monotonically increasing
+timestamps for precise uptime tracking purposes, when system is running.
+Event timers are responsible for generating interrupts at specified time or
+periodically, to run different time-based events.
+This page is about the last.
+.Sh DESCRIPTION
+Kernel uses time-based events for many different purposes: scheduling,
+statistics, time keeping, profiling and many other things, based on
+.Xr callout 9
+mechanism.
+These purposes now grouped into three main callbacks:
+.Bl -tag
+.It hardclock()
+.Xr callout 9
+and timekeeping events entry. Called with frequency defined by hz variable,
+usually 1000Hz.
+.It statclock()
+statistics and scheduler events entry. Called with frequency about 128Hz.
+.It profclock()
+profiler events entry. When enabled, called with frequency about 8KHz.
+.El
+Different platforms provide different kinds of timer hardware.
+The goal of the event timers subsystem is to provide unified way to control
+that hardware, and to use it, supplying kernel with all required time-based
+events.
+.Pp
+Each driver implementing event timers, registers them at the subsystem.
+It is possible to see the list of present event timers, like this, via
+.Va kern.eventtimer
+sysctl:
+.Bd -literal
+kern.eventtimer.choice: HPET(550) LAPIC(400) i8254(100) RTC(0)
+kern.eventtimer.et.LAPIC.flags: 15
+kern.eventtimer.et.LAPIC.frequency: 0
+kern.eventtimer.et.LAPIC.quality: 400
+kern.eventtimer.et.i8254.flags: 1
+kern.eventtimer.et.i8254.frequency: 1193182
+kern.eventtimer.et.i8254.quality: 100
+kern.eventtimer.et.RTC.flags: 17
+kern.eventtimer.et.RTC.frequency: 32768
+kern.eventtimer.et.RTC.quality: 0
+kern.eventtimer.et.HPET.flags: 7
+kern.eventtimer.et.HPET.frequency: 14318180
+kern.eventtimer.et.HPET.quality: 550
+.Ed
+, where:
+.Bl -tag
+.It Va kern.eventtimer.et. Ns Ar X Ns Va .flags
+bitmask, defining event timer capabilities:
+.Bl -tag -compact
+.It 1
+periodic mode supported,
+.It 2
+one-shot mode supported,
+.It 4
+timer is per-CPU,
+.It 8
+timer may stop when CPU goes to sleep state,
+.It 16
+timer supports only power-of-2 divisors.
+.El
+.It Va kern.eventtimer.et. Ns Ar X Ns Va .frequency
+timer base frequency,
+.It Va kern.eventtimer.et. Ns Ar X Ns Va .quality
+integral value, defining how good is this timer, comparing to others.
+.El
+.Pp
+Timers management code of the kernel chooses one timer from that list.
+Current choice can be read and affected via
+.Va kern.eventtimer.timer
+tunable/sysctl.
+Several other tunables/sysctls are affecting how exactly this timer is used:
+.Bl -tag
+.It Va kern.eventtimer.periodic
+allows to choose periodic and one-shot operation mode.
+In periodic mode, periodic interrupts from timer hardware are taken as the
+only source of time for time events.
+One-shot mode instead uses currently selected time counter to precisely
+schedule all needed events and programs event timer to generate interrupt
+exactly in specified time.
+Default value depends of chosen timer capabilities, but one-shot mode is
+preferred, until other is forced by user or hardware.
+.It Va kern.eventtimer.singlemul
+in periodic mode specifies how much times higher timer frequency should be,
+to not strictly alias hardclock() and statclock() events. Default values are
+1, 2 or 4, depending on configured HZ value.
+.It Va kern.eventtimer.idletick
+makes each CPU to receive every timer interrupt independently of whether they
+busy or not. By default this options is disabled. If chosen timer is per-CPU
+and runs in periodic mode, this option has no effect - all interrupts are
+always generating.
+.El
+.Sh SEE ALSO
+.Xr hpet 4
diff --git a/share/man/man7/tuning.7 b/share/man/man7/tuning.7
index 6f9e9cbd3ba..ccb69b64bb0 100644
--- a/share/man/man7/tuning.7
+++ b/share/man/man7/tuning.7
@@ -1019,6 +1019,7 @@ over services you export from your box (web services, email).
 .Xr rc.conf 5 ,
 .Xr sysctl.conf 5 ,
 .Xr firewall 7 ,
+.Xr eventtimers 7 ,
 .Xr hier 7 ,
 .Xr ports 7 ,
 .Xr boot 8 ,

From 522a3b5fbc0dea64b732a061bc379e3a7d852ba7 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Wed, 15 Sep 2010 07:10:39 +0000
Subject: [PATCH 0761/1624] Change licenses of my manual pages to the
 recommended 2-clause form.

Suggested by:	joel
---
 share/man/man4/ahci.4 | 23 +++++++++++------------
 share/man/man4/hpet.4 | 25 ++++++++++++-------------
 share/man/man4/mvs.4  | 23 +++++++++++------------
 share/man/man4/siis.4 | 23 +++++++++++------------
 4 files changed, 45 insertions(+), 49 deletions(-)

diff --git a/share/man/man4/ahci.4 b/share/man/man4/ahci.4
index e2799639d9b..144d64b831a 100644
--- a/share/man/man4/ahci.4
+++ b/share/man/man4/ahci.4
@@ -9,19 +9,18 @@
 .\" 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. The name of the author may not be used to endorse or promote products
-.\"    derived from this software without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 .\"
 .\" $FreeBSD$
 .\"
diff --git a/share/man/man4/hpet.4 b/share/man/man4/hpet.4
index 49970534730..3a71e71aaa8 100644
--- a/share/man/man4/hpet.4
+++ b/share/man/man4/hpet.4
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2009 Alexander Motin 
+.\" Copyright (c) 2010 Alexander Motin 
 .\" All rights reserved.
 .\"
 .\" Redistribution and use in source and binary forms, with or without
@@ -9,19 +9,18 @@
 .\" 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. The name of the author may not be used to endorse or promote products
-.\"    derived from this software without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 .\"
 .\" $FreeBSD$
 .\"
diff --git a/share/man/man4/mvs.4 b/share/man/man4/mvs.4
index 942c3c4cc17..23eed9dc8ec 100644
--- a/share/man/man4/mvs.4
+++ b/share/man/man4/mvs.4
@@ -9,19 +9,18 @@
 .\" 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. The name of the author may not be used to endorse or promote products
-.\"    derived from this software without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 .\"
 .\" $FreeBSD$
 .\"
diff --git a/share/man/man4/siis.4 b/share/man/man4/siis.4
index 7480f70bfdd..fa6a038f13e 100644
--- a/share/man/man4/siis.4
+++ b/share/man/man4/siis.4
@@ -9,19 +9,18 @@
 .\" 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. The name of the author may not be used to endorse or promote products
-.\"    derived from this software without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 .\"
 .\" $FreeBSD$
 .\"

From d94815546541ca4d8ad58029e04c14ed8bbcffc9 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 10:02:46 +0000
Subject: [PATCH 0762/1624] sys/pcpu.h: remove a workaround for a fixed ld bug

The workaround was incorrectly documented as having something to do with
set_pcpu section's progbits, but in fact it was for incorrect placement
of __start_set_pcpu because of the bug in ld.
The bug was fixed in r210245, see commit message for details.

A side-effect of the workaround was that a zero-size set_pcpu section was
produced for modules, source code of which included pcpu.h but didn't
actually define any dynamic per-cpu variables.
This commit should remove the side-effect.

The same workaround is present sys/net/vnet.h, has an analogous side-effect
and can be removed as well.

An UPDATING entry that warns about a need for recent ld is following.

MFC after:	1 month
---
 sys/sys/pcpu.h | 14 --------------
 1 file changed, 14 deletions(-)

diff --git a/sys/sys/pcpu.h b/sys/sys/pcpu.h
index 7d510c9ae7f..75017d6c6bc 100644
--- a/sys/sys/pcpu.h
+++ b/sys/sys/pcpu.h
@@ -44,24 +44,10 @@
 
 /*
  * Define a set for pcpu data.
- * 
- * We don't use SET_DECLARE because it defines the set as 'a' when we
- * want 'aw'.  gcc considers uninitialized data in a separate section
- * writable, and there is no generic zero initializer that works for
- * structs and scalars.
  */
 extern uintptr_t *__start_set_pcpu;
 extern uintptr_t *__stop_set_pcpu;
 
-__asm__(
-#ifdef __arm__
-	".section set_pcpu, \"aw\", %progbits\n"
-#else
-	".section set_pcpu, \"aw\", @progbits\n"
-#endif
-	"\t.p2align " __XSTRING(CACHE_LINE_SHIFT) "\n"
-	"\t.previous");
-
 /*
  * Array of dynamic pcpu base offsets.  Indexed by id.
  */

From f8fc818b9d23b2c1edd44a409923a8c4beb04757 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 10:04:41 +0000
Subject: [PATCH 0763/1624] UPDATING entry for r212647

---
 UPDATING | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/UPDATING b/UPDATING
index 7a17089717f..2990ccb29d9 100644
--- a/UPDATING
+++ b/UPDATING
@@ -22,6 +22,14 @@ NOTE TO PEOPLE WHO THINK THAT FreeBSD 9.x IS SLOW:
 	machines to maximize performance.  (To disable malloc debugging, run
 	ln -s aj /etc/malloc.conf.)
 
+20100915:
+	A workaround for a fixed ld bug has been removed in kernel code,
+	so make sure that your system ld is built from sources after
+	revision 210245 (r211583 if building head kernel on stable/8,
+	r211584 for stable/7).  A symptom of incorrect ld version is
+	different addresses for set_pcpu section and __start_set_pcpu
+	symbol in kernel and/or modules.
+
 20100913:
 	The $ipv6_prefer variable in rc.conf(5) has been split into
 	$ip6addrctl_policy and $ipv6_activate_all_interfaces.

From 8518caf2a77c3a173637f8aac4af400c9d74ca5c Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Wed, 15 Sep 2010 10:18:18 +0000
Subject: [PATCH 0764/1624] Add a man page for plockstat.

Sponsored by:	The FreeBSD Foundation
---
 cddl/usr.sbin/plockstat/Makefile    |  1 -
 cddl/usr.sbin/plockstat/plockstat.1 | 95 +++++++++++++++++++++++++++++
 2 files changed, 95 insertions(+), 1 deletion(-)
 create mode 100644 cddl/usr.sbin/plockstat/plockstat.1

diff --git a/cddl/usr.sbin/plockstat/Makefile b/cddl/usr.sbin/plockstat/Makefile
index 20683115a43..05929589811 100644
--- a/cddl/usr.sbin/plockstat/Makefile
+++ b/cddl/usr.sbin/plockstat/Makefile
@@ -3,7 +3,6 @@
 .PATH: ${.CURDIR}/../../../cddl/contrib/opensolaris/cmd/plockstat
 
 PROG=		plockstat
-NO_MAN=
 SRCS=		plockstat.c 
 BINDIR?=	/usr/sbin
 
diff --git a/cddl/usr.sbin/plockstat/plockstat.1 b/cddl/usr.sbin/plockstat/plockstat.1
new file mode 100644
index 00000000000..ca97f39a6db
--- /dev/null
+++ b/cddl/usr.sbin/plockstat/plockstat.1
@@ -0,0 +1,95 @@
+.\"
+.\" Copyright (c) 2010 The FreeBSD Foundation 
+.\" All rights reserved. 
+.\" 
+.\" This software was developed by Rui Paulo under sponsorship from the
+.\" FreeBSD Foundation. 
+.\"  
+.\" 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. 
+.\" 
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. 
+.\"
+.\" $FreeBSD$
+.\"
+.Dd September 13, 2010
+.Dt PLOCKSTAT 1
+.Os
+.Sh NAME
+.Nm plockstat
+.Nd Trace pthread lock statistics using DTrace
+.Sh SYNOPSIS
+.Nm
+.Op Fl vACHV
+.Op Fl n Ar count
+.Op Fl s Ar depth
+.Op Fl e Ar secs
+.Op Fl x Ar opt Ns = Ns Ar val
+.Ar command
+.Op arg...
+.Nm
+.Op Fl vACHV
+.Op Fl n Ar count
+.Op Fl s Ar depth
+.Op Fl e Ar secs
+.Op Fl x Ar opt Ns = Ns Ar val
+.Fl p Ar pid 
+.Sh DESCRIPTION
+The
+.Nm
+utility traces pthread locks (mutexes and rwlocks) and prints statistics about
+them.
+You can use
+.Nm
+to investigate bottlenecks in your software.
+.Pp
+The following options are available:
+.Bl -tag -width indent
+.It Fl v
+Be verbose.
+.It Fl A
+Print all statistics.
+.It Fl C
+Print commulative statistics (the default).
+.It Fl H
+Print an histogram.
+.It Fl V
+Print the DTrace script about to be used to stderr.
+.It Fl n Ar count
+Set the aggregation count for the data set.
+.It Fl s Ar depth
+Set the ustack (userland stack) caller depth.
+.It Fl e Ar secs
+Does nothing at the moment.
+.It Fl x Ar opt Ns = Ns Ar val
+Specify DTrace options.
+See the
+.Xr dtrace 1
+man page for more details.
+.El
+.Sh EXIT STATUS
+.Ex -std
+.Sh SEE ALSO
+.Xr dtrace 1 ,
+.Xr pthread 3
+.Sh HISTORY
+The
+.Nm
+utility comes from the OpenSolaris and was first imported into
+.Fx 9.0 .

From 21bd3e2576bae2372049a11bc9f3b033bf1d7d59 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 10:31:27 +0000
Subject: [PATCH 0765/1624] tmpfs, zfs + sendfile: mark page bits as valid
 after populating it with data

Otherwise, adding insult to injury, in addition to double-caching of data
we would always copy the data into a vnode's vm object page from backend.
This is specific to sendfile case only (VOP_READ with UIO_NOCOPY).

PR:		kern/141305
Reported by:	Wiktor Niesiobedzki 
Reviewed by:	alc
Tested by:	tools/regression/sockets/sendfile
MFC after:	2 weeks
---
 sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c | 2 ++
 sys/fs/tmpfs/tmpfs_vnops.c                                 | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 0779a4b050c..4aa68a70e39 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -498,6 +498,8 @@ again:
 				sched_unpin();
 			}
 			VM_OBJECT_LOCK(obj);
+			if (error == 0)
+				vm_page_set_valid(m, off, bytes);
 			vm_page_wakeup(m);
 			if (error == 0)
 				uio->uio_resid -= bytes;
diff --git a/sys/fs/tmpfs/tmpfs_vnops.c b/sys/fs/tmpfs/tmpfs_vnops.c
index d3f1ff569c7..f1768320c74 100644
--- a/sys/fs/tmpfs/tmpfs_vnops.c
+++ b/sys/fs/tmpfs/tmpfs_vnops.c
@@ -562,6 +562,8 @@ lookupvpg:
 		sf_buf_free(sf);
 		sched_unpin();
 		VM_OBJECT_LOCK(vobj);
+		if (error == 0)
+			vm_page_set_valid(m, offset, tlen);
 		vm_page_wakeup(m);
 		VM_OBJECT_UNLOCK(vobj);
 		return	(error);

From 7ed09cd53578ec7c31da1d188056e41a90127593 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Wed, 15 Sep 2010 10:32:32 +0000
Subject: [PATCH 0766/1624] Remove an explicit assignment of the CFLAGS
 variable intended for debugging purposes only.

---
 libexec/tftpd/Makefile | 1 -
 1 file changed, 1 deletion(-)

diff --git a/libexec/tftpd/Makefile b/libexec/tftpd/Makefile
index b9db2a9e0ae..656f5bda956 100644
--- a/libexec/tftpd/Makefile
+++ b/libexec/tftpd/Makefile
@@ -6,7 +6,6 @@ SRCS=	tftpd.c tftp-io.c tftp-utils.c tftp-file.c tftp-transfer.c tftp-options.c
 WARNS=	3
 WFORMAT=0
 MAN=	tftpd.8
-CFLAGS=-g -Wall
 CFLAGS+=-I${.CURDIR}/../../usr.bin/tftp -I${.CURDIR}/../../libexec/tftpd
 .PATH:	${.CURDIR}/../../usr.bin/tftp
 COPTFLAGS = -O

From fbbdb19dcdb7aff94dceb4e4505dcf830bb5fff5 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 10:39:21 +0000
Subject: [PATCH 0767/1624] zfs: catch up with vm_page_sleep_if_busy changes

Reviewed by:	alc
Approved by:	pjd
Tested by:	tools/regression/fsx
MFC after:	2 weeks
---
 .../opensolaris/uts/common/fs/zfs/zfs_vnops.c | 34 +++++++++++++++++--
 1 file changed, 31 insertions(+), 3 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 4aa68a70e39..99565162c75 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -323,8 +323,17 @@ page_lookup(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
 	for (;;) {
 		if ((pp = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
 		    vm_page_is_valid(pp, (vm_offset_t)off, nbytes)) {
-			if (vm_page_sleep_if_busy(pp, FALSE, "zfsmwb"))
+			if ((pp->oflags & VPO_BUSY) != 0) {
+				/*
+				 * Reference the page before unlocking and
+				 * sleeping so that the page daemon is less
+				 * likely to reclaim it.
+				 */
+				vm_page_lock_queues();
+				vm_page_flag_set(pp, PG_REFERENCED);
+				vm_page_sleep(pp, "zfsmwb");
 				continue;
+			}
 			vm_page_busy(pp);
 			vm_page_undirty(pp);
 		} else {
@@ -451,8 +460,18 @@ mappedread(vnode_t *vp, int nbytes, uio_t *uio)
 again:
 		if ((m = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
 		    vm_page_is_valid(m, (vm_offset_t)off, bytes)) {
-			if (vm_page_sleep_if_busy(m, FALSE, "zfsmrb"))
+			if ((m->oflags & VPO_BUSY) != 0) {
+				/*
+				 * Reference the page before unlocking and
+				 * sleeping so that the page daemon is less
+				 * likely to reclaim it.
+				 */
+				vm_page_lock_queues();
+				vm_page_flag_set(m, PG_REFERENCED);
+				vm_page_sleep(m, "zfsmrb");
 				goto again;
+			}
+
 			vm_page_busy(m);
 			VM_OBJECT_UNLOCK(obj);
 			if (dirbytes > 0) {
@@ -478,8 +497,17 @@ again:
 			 * but it pessimize performance of sendfile/UFS, that's
 			 * why I handle this special case in ZFS code.
 			 */
-			if (vm_page_sleep_if_busy(m, FALSE, "zfsmrb"))
+			if ((m->oflags & VPO_BUSY) != 0) {
+				/*
+				 * Reference the page before unlocking and
+				 * sleeping so that the page daemon is less
+				 * likely to reclaim it.
+				 */
+				vm_page_lock_queues();
+				vm_page_flag_set(m, PG_REFERENCED);
+				vm_page_sleep(m, "zfsmrb");
 				goto again;
+			}
 			vm_page_busy(m);
 			VM_OBJECT_UNLOCK(obj);
 			if (dirbytes > 0) {

From c183b9c6832827b1a85058324a1e58be36863763 Mon Sep 17 00:00:00 2001
From: Andre Oppermann 
Date: Wed, 15 Sep 2010 10:39:30 +0000
Subject: [PATCH 0768/1624] Change the default MSS for IPv4 and IPv6 TCP
 connections from an artificial power-of-2 rounded number to their real values
 specified in RFC879 and RFC2460.

From the history and existing comments it appears that the rounded
numbers were intended to be advantageous for the kernel and mbuf
system.  However this hasn't been the case at for at least a long
time.  The mbuf clusters used in tcp_output() have enough space
to hold the larger real value for the default MSS for both IPv4 and
IPv6.  Note that the default MSS is only used when path MTU discovery
is disabled.

Update and expand related comments.

Reviewed by:	lsteward (including some word-smithing)
MFC after:	2 weeks
---
 sys/netinet/tcp.h | 46 +++++++++++++++++++++++++++-------------------
 1 file changed, 27 insertions(+), 19 deletions(-)

diff --git a/sys/netinet/tcp.h b/sys/netinet/tcp.h
index 2929d0d2a92..86c95489284 100644
--- a/sys/netinet/tcp.h
+++ b/sys/netinet/tcp.h
@@ -103,29 +103,37 @@ struct tcphdr {
 
 
 /*
- * Default maximum segment size for TCP.
- * With an IP MTU of 576, this is 536,
- * but 512 is probably more convenient.
- * This should be defined as MIN(512, IP_MSS - sizeof (struct tcpiphdr)).
+ * The default maximum segment size (MSS) to be used for new TCP connections
+ * when path MTU discovery is not enabled.
+ *
+ * RFC879 derives the default MSS from the largest datagram size hosts are
+ * minimally required to handle directly or through IP reassembly minus the
+ * size of the IP and TCP header.  With IPv6 the minimum MTU is specified
+ * in RFC2460.
+ *
+ * For IPv4 the MSS is 576 - sizeof(struct tcpiphdr)
+ * For IPv6 the MSS is IPV6_MMTU - sizeof(struct ip6_hdr) - sizeof(struct tcphdr)
+ *
+ * We use explicit numerical definition here to avoid header pollution.
  */
-#define	TCP_MSS	512
-/*
- * TCP_MINMSS is defined to be 216 which is fine for the smallest
- * link MTU (256 bytes, AX.25 packet radio) in the Internet.
- * However it is very unlikely to come across such low MTU interfaces
- * these days (anno dato 2003).
- * See tcp_subr.c tcp_minmss SYSCTL declaration for more comments.
- * Setting this to "0" disables the minmss check.
- */
-#define	TCP_MINMSS 216
+#define	TCP_MSS		536
+#define	TCP6_MSS	1220
 
 /*
- * Default maximum segment size for TCP6.
- * With an IP6 MSS of 1280, this is 1220,
- * but 1024 is probably more convenient. (xxx kazu in doubt)
- * This should be defined as MIN(1024, IP6_MSS - sizeof (struct tcpip6hdr))
+ * Limit the lowest MSS we accept from path MTU discovery and the TCP SYN MSS
+ * option.  Allowing too low values of MSS can consume significant amounts of
+ * resources and be used as a form of a resource exhaustion attack.
+ * Connections requesting lower MSS values will be rounded up to this value
+ * and the IP_DF flag is cleared to allow fragmentation along the path.
+ *
+ * See tcp_subr.c tcp_minmss SYSCTL declaration for more comments.  Setting
+ * it to "0" disables the minmss check.
+ *
+ * The default value is fine for the smallest official link MTU (256 bytes,
+ * AX.25 packet radio) in the Internet.  However it is very unlikely to come
+ * across such low MTU interfaces these days (anno domini 2003).
  */
-#define	TCP6_MSS	1024
+#define	TCP_MINMSS 216
 
 #define	TCP_MAXWIN	65535	/* largest value for (unscaled) window */
 #define	TTCP_CLIENT_SND_WND	4096	/* dflt send window for T/TCP client */

From c002c3e8c28fe082852c2e435017e07eaf4dd11b Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 10:44:20 +0000
Subject: [PATCH 0769/1624] zfs mappedread: use uiomove_fromphys where possible

Reviewed by:	alc
Approved by:	pjd
Tested by:	tools/regression/fsx
MFC after:	2 weeks
---
 .../contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c  | 10 ++--------
 1 file changed, 2 insertions(+), 8 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 99565162c75..7f3b0a809f5 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -479,14 +479,8 @@ again:
 				    dirbytes);
 				dirbytes = 0;
 			}
-			if (error == 0) {
-				sched_pin();
-				sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
-				va = (caddr_t)sf_buf_kva(sf);
-				error = uiomove(va + off, bytes, UIO_READ, uio);
-				sf_buf_free(sf);
-				sched_unpin();
-			}
+			if (error == 0)
+				uiomove_fromphys(&m, off, bytes, uio);
 			VM_OBJECT_LOCK(obj);
 			vm_page_wakeup(m);
 		} else if (m != NULL && uio->uio_segflg == UIO_NOCOPY) {

From 0b1ca38a69121b67559cedb94e5f2e514058ff72 Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 10:48:16 +0000
Subject: [PATCH 0770/1624] zfs mappedread, update_pages: use int for offset
 and length within a page

uint64_t, int64_t were redundant there

Approved by:	pjd
Tested by:	tools/regression/fsx
MFC after:	2 weeks
---
 .../contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 7f3b0a809f5..24b15568a19 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -387,7 +387,7 @@ update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid,
 {
 	vm_object_t obj;
 	struct sf_buf *sf;
-	int64_t off;
+	int off;
 
 	ASSERT(vp->v_mount != NULL);
 	obj = vp->v_object;
@@ -397,7 +397,7 @@ update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid,
 	VM_OBJECT_LOCK(obj);
 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
 		vm_page_t pp;
-		uint64_t nbytes = MIN(PAGESIZE - off, len);
+		int nbytes = MIN(PAGESIZE - off, len);
 
 		if ((pp = page_lookup(vp, start, off, nbytes)) != NULL) {
 			caddr_t va;
@@ -440,9 +440,10 @@ mappedread(vnode_t *vp, int nbytes, uio_t *uio)
 	vm_object_t obj;
 	vm_page_t m;
 	struct sf_buf *sf;
-	int64_t start, off;
+	int64_t start;
 	caddr_t va;
 	int len = nbytes;
+	int off;
 	int error = 0;
 	uint64_t dirbytes;
 
@@ -455,11 +456,11 @@ mappedread(vnode_t *vp, int nbytes, uio_t *uio)
 	dirbytes = 0;
 	VM_OBJECT_LOCK(obj);
 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
-		uint64_t bytes = MIN(PAGESIZE - off, len);
+		int bytes = MIN(PAGESIZE - off, len);
 
 again:
 		if ((m = vm_page_lookup(obj, OFF_TO_IDX(start))) != NULL &&
-		    vm_page_is_valid(m, (vm_offset_t)off, bytes)) {
+		    vm_page_is_valid(m, off, bytes)) {
 			if ((m->oflags & VPO_BUSY) != 0) {
 				/*
 				 * Reference the page before unlocking and

From 8a3883cfb7b21bc5e01ec7bedb38bc91d416c51c Mon Sep 17 00:00:00 2001
From: Andriy Gapon 
Date: Wed, 15 Sep 2010 11:05:41 +0000
Subject: [PATCH 0771/1624] zfs vn_has_cached_data: take into account
 v_object->cache != NULL

This mirrors code in tmpfs.
This changge shouldn't affect much read path, it may cause unnecessary
vm_page_lookup calls in the case where v_object has no active or inactive
pages but has some cache pages.  I believe this situation to be non-essential.

In write path this change should allow us to properly detect the above
case and free a cache page when we write to a range that corresponds to it.
If this situation is undetected then we could have a discrepancy between
data in page cache and in ARC or on disk.

This change allows us to re-enable vn_has_cached_data() check in zfs_write.

NOTE: strictly speaking resident_page_count and cache fields of v_object
should be exmined under VM_OBJECT_LOCK, but for this particular usage
we may get away with it.

Discussed with:	alc, kib
Approved by:	pjd
Tested with:	tools/regression/fsx
MFC after:	3 weeks
---
 sys/cddl/compat/opensolaris/sys/vnode.h              |  4 +++-
 .../opensolaris/uts/common/fs/zfs/zfs_vnops.c        | 12 +-----------
 2 files changed, 4 insertions(+), 12 deletions(-)

diff --git a/sys/cddl/compat/opensolaris/sys/vnode.h b/sys/cddl/compat/opensolaris/sys/vnode.h
index 1d46956629e..bdf062307a4 100644
--- a/sys/cddl/compat/opensolaris/sys/vnode.h
+++ b/sys/cddl/compat/opensolaris/sys/vnode.h
@@ -69,7 +69,9 @@ vn_is_readonly(vnode_t *vp)
 #define	vn_vfsunlock(vp)	do { } while (0)
 #define	vn_ismntpt(vp)		((vp)->v_type == VDIR && (vp)->v_mountedhere != NULL)
 #define	vn_mountedvfs(vp)	((vp)->v_mountedhere)
-#define	vn_has_cached_data(vp)	((vp)->v_object != NULL && (vp)->v_object->resident_page_count > 0)
+#define	vn_has_cached_data(vp)	\
+	((vp)->v_object != NULL && ((vp)->v_object->resident_page_count > 0 \
+				    || (vp)->v_object->cache != NULL))
 #define	vn_exists(vp)		do { } while (0)
 #define	vn_invalid(vp)		do { } while (0)
 #define	vn_renamepath(tdvp, svp, tnm, lentnm)	do { } while (0)
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index 24b15568a19..d83e8f4217a 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -933,17 +933,7 @@ again:
 			uioskip(uio, tx_bytes);
 		}
 
-		/*
-		 * XXXPJD: There are some cases (triggered by fsx) where
-		 *         vn_has_cached_data(vp) returns false when it should
-		 *         return true. This should be investigated.
-		 */
-#if 0
-		if (tx_bytes && vn_has_cached_data(vp))
-#else
-		if (tx_bytes && vp->v_object != NULL)
-#endif
-		{
+		if (tx_bytes && vn_has_cached_data(vp)) {
 			update_pages(vp, woff, tx_bytes, zfsvfs->z_os,
 			    zp->z_id, uio->uio_segflg, tx);
 		}

From 89d10571dbd835a79c96ba9a6de5b8607c234295 Mon Sep 17 00:00:00 2001
From: Jaakko Heinonen 
Date: Wed, 15 Sep 2010 14:23:55 +0000
Subject: [PATCH 0772/1624] Remove empty devfs directories automatically.

devfs_delete() now recursively removes empty parent directories unless
the DEVFS_DEL_NORECURSE flag is specified. devfs_delete() can't be
called anymore with a parent directory vnode lock held because the
possible parent directory deletion needs to lock the vnode. Thus we
unlock the parent directory vnode in devfs_remove() before calling
devfs_delete().

Call devfs_populate_vp() from devfs_symlink() and devfs_vptocnp() as now
directories can get removed.

Add a check for DE_DOOMED flag to devfs_populate_vp() because
devfs_delete() drops dm_lock before the VI_DOOMED vnode flag gets set.
This ensures that devfs_populate_vp() returns an error for directories
which are in progress of deletion.

Reviewed by:	kib
Discussed on:	freebsd-current (mostly silence)
---
 sys/fs/devfs/devfs.h       |  5 ++-
 sys/fs/devfs/devfs_devs.c  | 79 ++++++++++++++++++++++++++++++++++----
 sys/fs/devfs/devfs_vnops.c | 39 +++++++++++++++----
 3 files changed, 106 insertions(+), 17 deletions(-)

diff --git a/sys/fs/devfs/devfs.h b/sys/fs/devfs/devfs.h
index ee5eafb31c8..87549d222b0 100644
--- a/sys/fs/devfs/devfs.h
+++ b/sys/fs/devfs/devfs.h
@@ -170,12 +170,15 @@ extern unsigned devfs_rule_depth;
 #define DEVFS_DMP_HOLD(dmp)	((dmp)->dm_holdcnt++)
 #define DEVFS_DMP_DROP(dmp)	(--(dmp)->dm_holdcnt == 0)
 
+#define	DEVFS_DEL_VNLOCKED	0x01
+#define	DEVFS_DEL_NORECURSE	0x02
+
 void devfs_rules_apply(struct devfs_mount *dm, struct devfs_dirent *de);
 void devfs_rules_cleanup (struct devfs_mount *dm);
 int devfs_rules_ioctl(struct devfs_mount *dm, u_long cmd, caddr_t data, struct thread *td);
 int devfs_allocv(struct devfs_dirent *de, struct mount *mp, int lockmode,
     struct vnode **vpp);
-void devfs_delete(struct devfs_mount *dm, struct devfs_dirent *de, int vp_locked);
+void devfs_delete(struct devfs_mount *dm, struct devfs_dirent *de, int flags);
 void devfs_dirent_free(struct devfs_dirent *de);
 void devfs_populate (struct devfs_mount *dm);
 void devfs_cleanup (struct devfs_mount *dm);
diff --git a/sys/fs/devfs/devfs_devs.c b/sys/fs/devfs/devfs_devs.c
index a11544f8003..eaaea6876a8 100644
--- a/sys/fs/devfs/devfs_devs.c
+++ b/sys/fs/devfs/devfs_devs.c
@@ -274,18 +274,69 @@ devfs_dirent_free(struct devfs_dirent *de)
 	free(de, M_DEVFS3);
 }
 
+/*
+ * Removes a directory if it is empty. Also empty parent directories are
+ * removed recursively.
+ */
+static void
+devfs_rmdir_empty(struct devfs_mount *dm, struct devfs_dirent *de)
+{
+	struct devfs_dirent *dd, *de_dot, *de_dotdot;
+
+	sx_assert(&dm->dm_lock, SX_XLOCKED);
+
+	for (;;) {
+		KASSERT(de->de_dirent->d_type == DT_DIR,
+		    ("devfs_rmdir_empty: de is not a directory"));
+
+		if ((de->de_flags & DE_DOOMED) != 0 || de == dm->dm_rootdir)
+			return;
+
+		de_dot = TAILQ_FIRST(&de->de_dlist);
+		KASSERT(de_dot != NULL, ("devfs_rmdir_empty: . missing"));
+		de_dotdot = TAILQ_NEXT(de_dot, de_list);
+		KASSERT(de_dotdot != NULL, ("devfs_rmdir_empty: .. missing"));
+		/* Return if the directory is not empty. */
+		if (TAILQ_NEXT(de_dotdot, de_list) != NULL)
+			return;
+
+		dd = devfs_parent_dirent(de);
+		KASSERT(dd != NULL, ("devfs_rmdir_empty: NULL dd"));
+		TAILQ_REMOVE(&dd->de_dlist, de, de_list);
+		DEVFS_DE_HOLD(dd);
+		devfs_delete(dm, de, DEVFS_DEL_NORECURSE);
+		devfs_delete(dm, de_dot, DEVFS_DEL_NORECURSE);
+		devfs_delete(dm, de_dotdot, DEVFS_DEL_NORECURSE);
+		if (DEVFS_DE_DROP(dd)) {
+			devfs_dirent_free(dd);
+			return;
+		}
+
+		de = dd;
+	}
+}
+
 /*
  * The caller needs to hold the dm for the duration of the call since
  * dm->dm_lock may be temporary dropped.
  */
 void
-devfs_delete(struct devfs_mount *dm, struct devfs_dirent *de, int vp_locked)
+devfs_delete(struct devfs_mount *dm, struct devfs_dirent *de, int flags)
 {
+	struct devfs_dirent *dd;
 	struct vnode *vp;
 
 	KASSERT((de->de_flags & DE_DOOMED) == 0,
 		("devfs_delete doomed dirent"));
 	de->de_flags |= DE_DOOMED;
+
+	if ((flags & DEVFS_DEL_NORECURSE) == 0) {
+		dd = devfs_parent_dirent(de);
+		if (dd != NULL)
+			DEVFS_DE_HOLD(dd);
+	} else
+		dd = NULL;
+
 	mtx_lock(&devfs_de_interlock);
 	vp = de->de_vnode;
 	if (vp != NULL) {
@@ -293,12 +344,12 @@ devfs_delete(struct devfs_mount *dm, struct devfs_dirent *de, int vp_locked)
 		mtx_unlock(&devfs_de_interlock);
 		vholdl(vp);
 		sx_unlock(&dm->dm_lock);
-		if (!vp_locked)
+		if ((flags & DEVFS_DEL_VNLOCKED) == 0)
 			vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
 		else
 			VI_UNLOCK(vp);
 		vgone(vp);
-		if (!vp_locked)
+		if ((flags & DEVFS_DEL_VNLOCKED) == 0)
 			VOP_UNLOCK(vp, 0);
 		vdrop(vp);
 		sx_xlock(&dm->dm_lock);
@@ -317,6 +368,13 @@ devfs_delete(struct devfs_mount *dm, struct devfs_dirent *de, int vp_locked)
 	}
 	if (DEVFS_DE_DROP(de))
 		devfs_dirent_free(de);
+
+	if (dd != NULL) {
+		if (DEVFS_DE_DROP(dd))
+			devfs_dirent_free(dd);
+		else
+			devfs_rmdir_empty(dm, dd);
+	}
 }
 
 /*
@@ -331,19 +389,24 @@ devfs_purge(struct devfs_mount *dm, struct devfs_dirent *dd)
 	struct devfs_dirent *de;
 
 	sx_assert(&dm->dm_lock, SX_XLOCKED);
+
+	DEVFS_DE_HOLD(dd);
 	for (;;) {
 		de = TAILQ_FIRST(&dd->de_dlist);
 		if (de == NULL)
 			break;
 		TAILQ_REMOVE(&dd->de_dlist, de, de_list);
-		if (de->de_flags & (DE_DOT|DE_DOTDOT))
-			devfs_delete(dm, de, 0);
+		if (de->de_flags & (DE_DOT | DE_DOTDOT))
+			devfs_delete(dm, de, DEVFS_DEL_NORECURSE);
 		else if (de->de_dirent->d_type == DT_DIR)
 			devfs_purge(dm, de);
-		else 
-			devfs_delete(dm, de, 0);
+		else
+			devfs_delete(dm, de, DEVFS_DEL_NORECURSE);
 	}
-	devfs_delete(dm, dd, 0);
+	if (DEVFS_DE_DROP(dd))
+		devfs_dirent_free(dd);
+	else if ((dd->de_flags & DE_DOOMED) == 0)
+		devfs_delete(dm, dd, DEVFS_DEL_NORECURSE);
 }
 
 /*
diff --git a/sys/fs/devfs/devfs_vnops.c b/sys/fs/devfs/devfs_vnops.c
index 943742e6fc8..2c27b7d8357 100644
--- a/sys/fs/devfs/devfs_vnops.c
+++ b/sys/fs/devfs/devfs_vnops.c
@@ -36,7 +36,6 @@
 
 /*
  * TODO:
- *	remove empty directories
  *	mkdir: want it ?
  */
 
@@ -191,6 +190,7 @@ devfs_clear_cdevpriv(void)
 static int
 devfs_populate_vp(struct vnode *vp)
 {
+	struct devfs_dirent *de;
 	struct devfs_mount *dmp;
 	int locked;
 
@@ -214,7 +214,14 @@ devfs_populate_vp(struct vnode *vp)
 		devfs_unmount_final(dmp);
 		return (EBADF);
 	}
-	if (vp->v_iflag & VI_DOOMED) {
+	if ((vp->v_iflag & VI_DOOMED) != 0) {
+		sx_xunlock(&dmp->dm_lock);
+		return (EBADF);
+	}
+	de = vp->v_data;
+	KASSERT(de != NULL,
+	    ("devfs_populate_vp: vp->v_data == NULL but vnode not doomed"));
+	if ((de->de_flags & DE_DOOMED) != 0) {
 		sx_xunlock(&dmp->dm_lock);
 		return (EBADF);
 	}
@@ -234,11 +241,13 @@ devfs_vptocnp(struct vop_vptocnp_args *ap)
 	int i, error;
 
 	dmp = VFSTODEVFS(vp->v_mount);
+
+	error = devfs_populate_vp(vp);
+	if (error != 0)
+		return (error);
+
 	i = *buflen;
 	dd = vp->v_data;
-	error = 0;
-
-	sx_xlock(&dmp->dm_lock);
 
 	if (vp->v_type == VCHR) {
 		i -= strlen(dd->de_cdp->cdp_c.si_name);
@@ -1271,11 +1280,15 @@ devfs_reclaim(struct vop_reclaim_args *ap)
 static int
 devfs_remove(struct vop_remove_args *ap)
 {
+	struct vnode *dvp = ap->a_dvp;
 	struct vnode *vp = ap->a_vp;
 	struct devfs_dirent *dd;
 	struct devfs_dirent *de, *de_covered;
 	struct devfs_mount *dmp = VFSTODEVFS(vp->v_mount);
 
+	ASSERT_VOP_ELOCKED(dvp, "devfs_remove");
+	ASSERT_VOP_ELOCKED(vp, "devfs_remove");
+
 	sx_xlock(&dmp->dm_lock);
 	dd = ap->a_dvp->v_data;
 	de = vp->v_data;
@@ -1287,11 +1300,19 @@ devfs_remove(struct vop_remove_args *ap)
 			if (de_covered != NULL)
 				de_covered->de_flags &= ~DE_COVERED;
 		}
-		devfs_delete(dmp, de, 1);
+		/* We need to unlock dvp because devfs_delete() may lock it. */
+		VOP_UNLOCK(vp, 0);
+		if (dvp != vp)
+			VOP_UNLOCK(dvp, 0);
+		devfs_delete(dmp, de, 0);
+		sx_xunlock(&dmp->dm_lock);
+		if (dvp != vp)
+			vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
+		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 	} else {
 		de->de_flags |= DE_WHITEOUT;
+		sx_xunlock(&dmp->dm_lock);
 	}
-	sx_xunlock(&dmp->dm_lock);
 	return (0);
 }
 
@@ -1533,6 +1554,9 @@ devfs_symlink(struct vop_symlink_args *ap)
 	if (error)
 		return(error);
 	dmp = VFSTODEVFS(ap->a_dvp->v_mount);
+	if (devfs_populate_vp(ap->a_dvp) != 0)
+		return (ENOENT);
+
 	dd = ap->a_dvp->v_data;
 	de = devfs_newdirent(ap->a_cnp->cn_nameptr, ap->a_cnp->cn_namelen);
 	de->de_uid = 0;
@@ -1544,7 +1568,6 @@ devfs_symlink(struct vop_symlink_args *ap)
 	i = strlen(ap->a_target) + 1;
 	de->de_symlink = malloc(i, M_DEVFS, M_WAITOK);
 	bcopy(ap->a_target, de->de_symlink, i);
-	sx_xlock(&dmp->dm_lock);
 #ifdef MAC
 	mac_devfs_create_symlink(ap->a_cnp->cn_cred, dmp->dm_mount, dd, de);
 #endif

From 04f798ecea0d726407db6fe9435cf10852eee4af Mon Sep 17 00:00:00 2001
From: Attilio Rao 
Date: Wed, 15 Sep 2010 14:24:21 +0000
Subject: [PATCH 0773/1624] Fix bogus busying mechanism from cdevsw callbacks:
 - D_TRACKCLOSE may be used there as d_close() are expected to match up  
 d_open() calls - Replace the hand-crafted counter and flag with the  
 device_busy()/device_unbusy() proper usage.

Sponsored by:	Sandvine Incorporated
Reported by:	Mark Johnston 
Tested by:	Mark Johnston
Reviewed by:	emaste

MFC after:	10 days
---
 sys/dev/aac/aac.c    | 13 +++----------
 sys/dev/aac/aacvar.h |  3 +--
 2 files changed, 4 insertions(+), 12 deletions(-)

diff --git a/sys/dev/aac/aac.c b/sys/dev/aac/aac.c
index 36996177738..4ff1640ab84 100644
--- a/sys/dev/aac/aac.c
+++ b/sys/dev/aac/aac.c
@@ -212,7 +212,7 @@ static struct aac_mntinforesp *
 
 static struct cdevsw aac_cdevsw = {
 	.d_version =	D_VERSION,
-	.d_flags =	D_NEEDGIANT,
+	.d_flags =	D_NEEDGIANT | D_TRACKCLOSE,
 	.d_open =	aac_open,
 	.d_close =	aac_close,
 	.d_ioctl =	aac_ioctl,
@@ -660,9 +660,6 @@ aac_detach(device_t dev)
 	sc = device_get_softc(dev);
 	fwprintf(sc, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, "");
 
-	if (sc->aac_state & AAC_STATE_OPEN)
-		return(EBUSY);
-
 	callout_drain(&sc->aac_daemontime);
 
 	/* Remove the child containers */
@@ -2804,8 +2801,7 @@ aac_open(struct cdev *dev, int flags, int fmt, struct thread *td)
 
 	sc = dev->si_drv1;
 	fwprintf(sc, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, "");
-	sc->aac_open_cnt++;
-	sc->aac_state |= AAC_STATE_OPEN;
+	device_busy(sc->aac_dev);
 
 	return 0;
 }
@@ -2817,10 +2813,7 @@ aac_close(struct cdev *dev, int flags, int fmt, struct thread *td)
 
 	sc = dev->si_drv1;
 	fwprintf(sc, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, "");
-	sc->aac_open_cnt--;
-	/* Mark this unit as no longer open  */
-	if (sc->aac_open_cnt == 0)
-		sc->aac_state &= ~AAC_STATE_OPEN;
+	device_unbusy(sc->aac_dev);
 
 	return 0;
 }
diff --git a/sys/dev/aac/aacvar.h b/sys/dev/aac/aacvar.h
index 29eb8169e02..192616b34de 100644
--- a/sys/dev/aac/aacvar.h
+++ b/sys/dev/aac/aacvar.h
@@ -319,10 +319,9 @@ struct aac_softc
 	/* controller features, limits and status */
 	int			aac_state;
 #define AAC_STATE_SUSPEND	(1<<0)
-#define	AAC_STATE_OPEN		(1<<1)
+#define	AAC_STATE_UNUSED0	(1<<1)
 #define AAC_STATE_INTERRUPTS_ON	(1<<2)
 #define AAC_STATE_AIF_SLEEPER	(1<<3)
-	int			aac_open_cnt;
 	struct FsaRevision		aac_revision;
 
 	/* controller hardware interface */

From 198ec86bf986320fe57cb43c261fa3b4548d7797 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Wed, 15 Sep 2010 15:18:41 +0000
Subject: [PATCH 0774/1624] - Update the comment in swi_vm() regarding busdma
 bounce buffers; it's   unlikely that support for these ever will be
 implemented on sparc64 as   the IOMMUs are able to translate to up to the
 maximum physical address   supported by the respective machine, bypassing the
 IOMMU is affected   by hardware errata and being able to support DMA engines
 which cannot   do at least 32-bit DMA does not justify the costs. - The page
 zeroing in uma_small_alloc() may use the VIS-based block zero   function so
 take advantage of it.

---
 sys/sparc64/sparc64/vm_machdep.c | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)

diff --git a/sys/sparc64/sparc64/vm_machdep.c b/sys/sparc64/sparc64/vm_machdep.c
index 9dc55c675d6..c550717be4c 100644
--- a/sys/sparc64/sparc64/vm_machdep.c
+++ b/sys/sparc64/sparc64/vm_machdep.c
@@ -492,10 +492,7 @@ void
 swi_vm(void *v)
 {
 
-	/*
-	 * Nothing to do here yet - busdma bounce buffers are not yet
-	 * implemented.
-	 */
+	/* Nothing to do here - busdma bounce buffers are not implemented. */
 }
 
 void *
@@ -540,7 +537,7 @@ uma_small_alloc(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
 	}
 	va = (void *)TLB_PHYS_TO_DIRECT(pa);
 	if ((wait & M_ZERO) && (m->flags & PG_ZERO) == 0)
-		bzero(va, PAGE_SIZE);
+		cpu_block_zero(va, PAGE_SIZE);
 	return (va);
 }
 

From 3dc2fd3f1e56f436b0dd7abfd9d319c73f0db4f5 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Wed, 15 Sep 2010 15:38:47 +0000
Subject: [PATCH 0775/1624] Move the pfrom initialization from before the
 setjmp to after the setjmp to avoid warnings on the powerpc build...

---
 libexec/tftpd/tftp-io.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/libexec/tftpd/tftp-io.c b/libexec/tftpd/tftp-io.c
index 28628bab459..8a39abdcd68 100644
--- a/libexec/tftpd/tftp-io.c
+++ b/libexec/tftpd/tftp-io.c
@@ -398,8 +398,6 @@ receive_packet(int peer, char *data, int size, struct sockaddr_storage *from,
 	int n;
 	static int waiting;
 
-	pfrom = (from == NULL) ? &from_local : from;
-
 	if (debug&DEBUG_PACKETS)
 		tftp_log(LOG_DEBUG,
 		    "Waiting %d seconds for packet", timeoutpacket);
@@ -423,6 +421,7 @@ receive_packet(int peer, char *data, int size, struct sockaddr_storage *from,
 	}
 
 	waiting++;
+	pfrom = (from == NULL) ? &from_local : from;
 	fromlen = sizeof(*pfrom);
 	n = recvfrom(peer, data, size, 0, (struct sockaddr *)pfrom, &fromlen);
 

From 67d60b1481ffc66eee8a5cf1aa20157fca883ae9 Mon Sep 17 00:00:00 2001
From: "Kenneth D. Merry" 
Date: Wed, 15 Sep 2010 16:05:51 +0000
Subject: [PATCH 0776/1624] MFp4 (//depot/projects/mps/...)

Fix a typo.

Submitted by:	pluknet at gmail dot com
---
 share/man/man4/mps.4 | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/share/man/man4/mps.4 b/share/man/man4/mps.4
index 684347f3a3d..644e02f4c9f 100644
--- a/share/man/man4/mps.4
+++ b/share/man/man4/mps.4
@@ -51,7 +51,7 @@ place the following lines in your kernel configuration file:
 Or, to load the driver as a module at boot, place the following line in
 .Xr loader.conf 5 :
 .Bd -literal -offset indent
-mpt_load="YES"
+mps_load="YES"
 .Ed
 .Sh DESCRIPTION
 The

From 4539e94b617c78389276d9f0d1984fe42c7e737f Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Wed, 15 Sep 2010 17:11:15 +0000
Subject: [PATCH 0777/1624] Sync with other platforms: - make dflt_lock()
 always panic, - add kludge to use contigmalloc() when the alignment is larger
 than the size   and print a diagnostic when we didn't satisfy the alignment.

---
 sys/sparc64/sparc64/bus_machdep.c | 26 +++++++++++++++++---------
 sys/sun4v/sun4v/bus_machdep.c     | 26 +++++++++++++++++---------
 2 files changed, 34 insertions(+), 18 deletions(-)

diff --git a/sys/sparc64/sparc64/bus_machdep.c b/sys/sparc64/sparc64/bus_machdep.c
index 0bf9b2e4b61..5f5d2a40658 100644
--- a/sys/sparc64/sparc64/bus_machdep.c
+++ b/sys/sparc64/sparc64/bus_machdep.c
@@ -182,11 +182,8 @@ busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
 static void
 dflt_lock(void *arg, bus_dma_lock_op_t op)
 {
-#ifdef INVARIANTS
+
 	panic("driver error: busdma dflt_lock called");
-#else
-	printf("DRIVER_ERROR: busdma dflt_lock called\n");
-#endif
 }
 
 /*
@@ -631,9 +628,18 @@ nexus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
 	if (flags & BUS_DMA_ZERO)
 		mflags |= M_ZERO;
 
-	if ((dmat->dt_maxsize <= PAGE_SIZE)) {
+	/*
+	 * XXX:
+	 * (dmat->dt_alignment < dmat->dt_maxsize) is just a quick hack; the
+	 * exact alignment guarantees of malloc need to be nailed down, and
+	 * the code below should be rewritten to take that into account.
+	 *
+	 * In the meantime, we'll warn the user if malloc gets it wrong.
+	 */
+	if (dmat->dt_maxsize <= PAGE_SIZE &&
+	    dmat->dt_alignment < dmat->dt_maxsize)
 		*vaddr = malloc(dmat->dt_maxsize, M_DEVBUF, mflags);
-	} else {
+	else {
 		/*
 		 * XXX use contigmalloc until it is merged into this
 		 * facility and handles multi-seg allocations.  Nobody
@@ -646,6 +652,8 @@ nexus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
 	}
 	if (*vaddr == NULL)
 		return (ENOMEM);
+	if ((uintptr_t)*vaddr % dmat->dt_alignment)
+		printf("%s: failed to align memory properly.\n", __func__);
 	return (0);
 }
 
@@ -657,11 +665,11 @@ static void
 nexus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
 {
 
-	if ((dmat->dt_maxsize <= PAGE_SIZE))
+	if (dmat->dt_maxsize <= PAGE_SIZE &&
+	    dmat->dt_alignment < dmat->dt_maxsize)
 		free(vaddr, M_DEVBUF);
-	else {
+	else
 		contigfree(vaddr, dmat->dt_maxsize, M_DEVBUF);
-	}
 }
 
 struct bus_dma_methods nexus_dma_methods = {
diff --git a/sys/sun4v/sun4v/bus_machdep.c b/sys/sun4v/sun4v/bus_machdep.c
index 1282b0e79b9..7246f5f73a2 100644
--- a/sys/sun4v/sun4v/bus_machdep.c
+++ b/sys/sun4v/sun4v/bus_machdep.c
@@ -181,11 +181,8 @@ busdma_lock_mutex(void *arg, bus_dma_lock_op_t op)
 static void
 dflt_lock(void *arg, bus_dma_lock_op_t op)
 {
-#ifdef INVARIANTS
+
 	panic("driver error: busdma dflt_lock called");
-#else
-	printf("DRIVER_ERROR: busdma dflt_lock called\n");
-#endif
 }
 
 /*
@@ -647,9 +644,18 @@ nexus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
 	if (flags & BUS_DMA_ZERO)
 		mflags |= M_ZERO;
 
-	if ((dmat->dt_maxsize <= PAGE_SIZE)) {
+	/*
+	 * XXX:
+	 * (dmat->dt_alignment < dmat->dt_maxsize) is just a quick hack; the
+	 * exact alignment guarantees of malloc need to be nailed down, and
+	 * the code below should be rewritten to take that into account.
+	 *
+	 * In the meantime, we'll warn the user if malloc gets it wrong.
+	 */
+	if (dmat->dt_maxsize <= PAGE_SIZE &&
+	    dmat->dt_alignment < dmat->dt_maxsize)
 		*vaddr = malloc(dmat->dt_maxsize, M_DEVBUF, mflags);
-	} else {
+	else {
 		/*
 		 * XXX use contigmalloc until it is merged into this
 		 * facility and handles multi-seg allocations.  Nobody
@@ -662,6 +668,8 @@ nexus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags,
 	}
 	if (*vaddr == NULL)
 		return (ENOMEM);
+	if ((uintptr_t)*vaddr % dmat->dt_alignment)
+		printf("%s: failed to align memory properly.\n", __func__);
 	return (0);
 }
 
@@ -673,11 +681,11 @@ static void
 nexus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)
 {
 
-	if ((dmat->dt_maxsize <= PAGE_SIZE))
+	if (dmat->dt_maxsize <= PAGE_SIZE &&
+	    dmat->dt_alignment < dmat->dt_maxsize)
 		free(vaddr, M_DEVBUF);
-	else {
+	else
 		contigfree(vaddr, dmat->dt_maxsize, M_DEVBUF);
-	}
 }
 
 struct bus_dma_methods nexus_dma_methods = {

From 23aa1a1da8d9216fab38c48a151434bdab1a36c4 Mon Sep 17 00:00:00 2001
From: Andreas Tobler 
Date: Wed, 15 Sep 2010 19:08:41 +0000
Subject: [PATCH 0778/1624] Increase register access delay to deal with the
 high-latency I2C chipset found in some models of Powermac G5.

Approved by:	nwhitehorn (mentor)
---
 sys/powerpc/powermac/kiic.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sys/powerpc/powermac/kiic.c b/sys/powerpc/powermac/kiic.c
index c01987a7981..0b13190aa09 100644
--- a/sys/powerpc/powermac/kiic.c
+++ b/sys/powerpc/powermac/kiic.c
@@ -250,7 +250,7 @@ static void
 kiic_writereg(struct kiic_softc *sc, u_int reg, u_int val)
 {
 	bus_write_4(sc->sc_reg, sc->sc_regstep * reg, val);
-	DELAY(10); /* register access delay */
+	DELAY(100); /* register access delay */
 }
 
 static u_int

From de84241c23f36eb2fb390f6593b08cf6c0bf8012 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Wed, 15 Sep 2010 19:40:08 +0000
Subject: [PATCH 0779/1624] Don't suggest using bwn for the bcm4306 cards in
 the list.  The bcm4306 cards are ambiguous.  BCM4306 rev 2 requires bwi. 
 BCM4306 rev 3 will work with either.  Since we can't easily determine which
 is which, just remove them.

---
 share/man/man4/bwn.4 | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/share/man/man4/bwn.4 b/share/man/man4/bwn.4
index 8e2592ae0dd..679f03e2358 100644
--- a/share/man/man4/bwn.4
+++ b/share/man/man4/bwn.4
@@ -78,18 +78,14 @@ driver supports Broadcom BCM43xx based wireless devices, including:
 .Pp
 .Bl -column -compact "Apple Airport Extreme" "BCM4306" "Mini PCI" "a/b/g" -offset 6n
 .It Em "Card	Chip	Bus	Standard"
-.It "Apple Airport Extreme	BCM4306	PCI	b/g"
 .It "Apple Airport Extreme	BCM4318	PCI	b/g"
 .It "ASUS WL-138g	BCM4318	PCI	b/g"
 .It "Buffalo WLI-CB-G54S	BCM4318	CardBus	b/g"
-.It "Buffalo WLI-PCI-G54S	BCM4306	PCI	b/g"
-.It "Compaq R4035 onboard	BCM4306	PCI	b/g"
 .It "Dell Wireless 1470	BCM4318	Mini PCI	b/g"
 .It "Dell Truemobile 1400	BCM4309	Mini PCI	b/g"
 .It "HP nx6125	BCM4319	PCI	b/g"
 .It "Linksys WPC54G Ver 3	BCM4318	CardBus	b/g"
 .It "Linksys WPC54GS Ver 2	BCM4318	CardBus	b/g"
-.It "TRENDnet TEW-401PCplus	BCM4306	CardBus	b/g"
 .It "US Robotics 5411	BCM4318	CardBus	b/g"
 .El
 .Pp

From 0e2b59be50cccd0655b189e5499b1cc2e3f7b9f8 Mon Sep 17 00:00:00 2001
From: Warner Losh 
Date: Wed, 15 Sep 2010 19:40:42 +0000
Subject: [PATCH 0780/1624] Add note abotu bwn and newer chipsets

---
 share/man/man4/bwi.4 | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/share/man/man4/bwi.4 b/share/man/man4/bwi.4
index 2f286568100..c9f8a391f02 100644
--- a/share/man/man4/bwi.4
+++ b/share/man/man4/bwi.4
@@ -90,6 +90,20 @@ driver supports Broadcom BCM43xx based wireless devices, including:
 .It "TRENDnet TEW-401PCplus	BCM4306	CardBus	b/g"
 .It "US Robotics 5411	BCM4318	CardBus	b/g"
 .El
+.Pp
+The 
+.Nm 
+driver uses the older v3 version of Broadcom's firmware.
+While this older firmware does support most BCM43xx parts, the
+.Xr bwn 4 
+driver works better for the newer chips it supports.
+You must use the 
+.Nm 
+driver if you are using older Broadcom chipsets (BCM4301, BCM4303 and
+BCM4306 rev 2).
+The v4 version of the firmware that 
+.Xr bwn 4 
+uses does not support these chips.
 .Sh EXAMPLES
 Join an existing BSS network (i.e., connect to an access point):
 .Pp

From d1ee63f83680b93c887fa6b6913b7fd5d3421dd3 Mon Sep 17 00:00:00 2001
From: Martin Matuska 
Date: Wed, 15 Sep 2010 19:55:26 +0000
Subject: [PATCH 0781/1624] Fix kernel panic when moving a file to .zfs/shares
 Fix possible loss of correct error return code in ZFS mount

OpenSolaris revisions and Bug IDs:

11824:53128e5db7cf
6863610	ZFS mount can lose correct error return

12079:13822b941977
6939941	problem with moving files in zfs (142901-12)

Approved by:	delphij (mentor)
Obtained from:	OpenSolaris (Bug ID 6863610, 6939941)
MFC after:	3 days
---
 sys/cddl/compat/opensolaris/sys/vnode.h       |  1 +
 .../uts/common/fs/zfs/sys/zfs_ctldir.h        |  4 +--
 .../uts/common/fs/zfs/zfs_ctldir.c            | 14 ++++++--
 .../uts/common/fs/zfs/zfs_vfsops.c            | 10 +++---
 .../opensolaris/uts/common/fs/zfs/zfs_vnops.c | 35 ++++++++++++-------
 5 files changed, 41 insertions(+), 23 deletions(-)

diff --git a/sys/cddl/compat/opensolaris/sys/vnode.h b/sys/cddl/compat/opensolaris/sys/vnode.h
index bdf062307a4..926d0349bdd 100644
--- a/sys/cddl/compat/opensolaris/sys/vnode.h
+++ b/sys/cddl/compat/opensolaris/sys/vnode.h
@@ -76,6 +76,7 @@ vn_is_readonly(vnode_t *vp)
 #define	vn_invalid(vp)		do { } while (0)
 #define	vn_renamepath(tdvp, svp, tnm, lentnm)	do { } while (0)
 #define	vn_free(vp)		do { } while (0)
+#define	vn_matchops(vp, vops)	((vp)->v_op == &(vops))
 
 #define	VN_HOLD(v)	vref(v)
 #define	VN_RELE(v)	vrele(v)
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_ctldir.h b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_ctldir.h
index 25348d6460f..19456869564 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_ctldir.h
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_ctldir.h
@@ -19,8 +19,7 @@
  * CDDL HEADER END
  */
 /*
- * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
- * Use is subject to license terms.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  */
 
 #ifndef	_ZFS_CTLDIR_H
@@ -48,6 +47,7 @@ void zfsctl_destroy(zfsvfs_t *);
 vnode_t *zfsctl_root(znode_t *);
 void zfsctl_init(void);
 void zfsctl_fini(void);
+boolean_t zfsctl_is_node(vnode_t *);
 
 int zfsctl_rename_snapshot(const char *from, const char *to);
 int zfsctl_destroy_snapshot(const char *snapname, int force);
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
index 156c1ee8b81..48c3ebf78a5 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c
@@ -19,8 +19,7 @@
  * CDDL HEADER END
  */
 /*
- * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
- * Use is subject to license terms.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -152,6 +151,17 @@ zfsctl_fini(void)
 {
 }
 
+boolean_t
+zfsctl_is_node(vnode_t *vp)
+{
+	return (vn_matchops(vp, zfsctl_ops_root) ||
+	    vn_matchops(vp, zfsctl_ops_snapdir) ||
+	    vn_matchops(vp, zfsctl_ops_snapshot) ||
+	    vn_matchops(vp, zfsctl_ops_shares) ||
+	    vn_matchops(vp, zfsctl_ops_shares_dir));
+
+}
+
 /*
  * Return the inode number associated with the 'snapshot' or
  * 'shares' directory.
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
index 96c973497c1..30a1b315b3f 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
@@ -1163,8 +1163,7 @@ zfs_mount(vfs_t *vfsp)
 	 */
 	error = secpolicy_fs_mount(cr, mvp, vfsp);
 	if (error) {
-		error = dsl_deleg_access(osname, ZFS_DELEG_PERM_MOUNT, cr);
-		if (error != 0)
+		if (dsl_deleg_access(osname, ZFS_DELEG_PERM_MOUNT, cr) != 0)
 			goto out;
 
 		if (!(vfsp->vfs_flag & MS_REMOUNT)) {
@@ -1178,7 +1177,7 @@ zfs_mount(vfs_t *vfsp)
 			vattr.va_mask = AT_UID;
 
 			vn_lock(mvp, LK_SHARED | LK_RETRY);
-			if (error = VOP_GETATTR(mvp, &vattr, cr)) {
+			if (VOP_GETATTR(mvp, &vattr, cr)) {
 				VOP_UNLOCK(mvp, 0);
 				goto out;
 			}
@@ -1433,9 +1432,8 @@ zfs_umount(vfs_t *vfsp, int fflag)
 
 	ret = secpolicy_fs_unmount(cr, vfsp);
 	if (ret) {
-		ret = dsl_deleg_access((char *)refstr_value(vfsp->vfs_resource),
-		    ZFS_DELEG_PERM_MOUNT, cr);
-		if (ret)
+		if (dsl_deleg_access((char *)refstr_value(vfsp->vfs_resource),
+		    ZFS_DELEG_PERM_MOUNT, cr))
 			return (ret);
 	}
 	/*
diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
index d83e8f4217a..18ff03bb21c 100644
--- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
+++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c
@@ -19,8 +19,7 @@
  * CDDL HEADER END
  */
 /*
- * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
- * Use is subject to license terms.
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Portions Copyright 2007 Jeremy Teo */
@@ -3357,7 +3356,7 @@ zfs_rename(vnode_t *sdvp, char *snm, vnode_t *tdvp, char *tnm, cred_t *cr,
 	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
 		tdvp = realvp;
 
-	if (tdvp->v_vfsp != sdvp->v_vfsp) {
+	if (tdvp->v_vfsp != sdvp->v_vfsp || zfsctl_is_node(tdvp)) {
 		ZFS_EXIT(zfsvfs);
 		return (EXDEV);
 	}
@@ -3875,6 +3874,7 @@ zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
 	vnode_t		*realvp;
 	int		error;
 	int		zf = ZNEW;
+	uint64_t	parent;
 	uid_t		owner;
 
 	ASSERT(tdvp->v_type == VDIR);
@@ -3886,13 +3886,30 @@ zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
 	if (VOP_REALVP(svp, &realvp, ct) == 0)
 		svp = realvp;
 
-	if (svp->v_vfsp != tdvp->v_vfsp) {
+	/*
+	 * POSIX dictates that we return EPERM here.
+	 * Better choices include ENOTSUP or EISDIR.
+	 */
+	if (svp->v_type == VDIR) {
+		ZFS_EXIT(zfsvfs);
+		return (EPERM);
+	}
+
+	if (svp->v_vfsp != tdvp->v_vfsp || zfsctl_is_node(svp)) {
 		ZFS_EXIT(zfsvfs);
 		return (EXDEV);
 	}
+
 	szp = VTOZ(svp);
 	ZFS_VERIFY_ZP(szp);
 
+	/* Prevent links to .zfs/shares files */
+
+	if (szp->z_phys->zp_parent == zfsvfs->z_shares_dir) {
+		ZFS_EXIT(zfsvfs);
+		return (EPERM);
+	}
+
 	if (zfsvfs->z_utf8 && u8_validate(name,
 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
 		ZFS_EXIT(zfsvfs);
@@ -3901,7 +3918,6 @@ zfs_link(vnode_t *tdvp, vnode_t *svp, char *name, cred_t *cr,
 	if (flags & FIGNORECASE)
 		zf |= ZCILOOK;
 
-top:
 	/*
 	 * We do not support links between attributes and non-attributes
 	 * because of the potential security risk of creating links
@@ -3914,14 +3930,6 @@ top:
 		return (EINVAL);
 	}
 
-	/*
-	 * POSIX dictates that we return EPERM here.
-	 * Better choices include ENOTSUP or EISDIR.
-	 */
-	if (svp->v_type == VDIR) {
-		ZFS_EXIT(zfsvfs);
-		return (EPERM);
-	}
 
 	owner = zfs_fuid_map_id(zfsvfs, szp->z_phys->zp_uid, cr, ZFS_OWNER);
 	if (owner != crgetuid(cr) &&
@@ -3935,6 +3943,7 @@ top:
 		return (error);
 	}
 
+top:
 	/*
 	 * Attempt to lock directory; fail if entry already exists.
 	 */

From 15537f41b444170cb3dec4e0c09cf101914c3122 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 20:41:20 +0000
Subject: [PATCH 0782/1624] Remove unused variables.

MFC after: 2 weeks.
---
 sys/netinet6/sctp6_usrreq.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/sys/netinet6/sctp6_usrreq.c b/sys/netinet6/sctp6_usrreq.c
index 8c1405637d6..cc3af664f9e 100644
--- a/sys/netinet6/sctp6_usrreq.c
+++ b/sys/netinet6/sctp6_usrreq.c
@@ -73,7 +73,11 @@ sctp6_input(struct mbuf **i_pak, int *offp, int proto)
 	struct sctp_nets *net;
 	int refcount_up = 0;
 	uint32_t vrf_id = 0;
+
+#ifdef IPSEC
 	struct inpcb *in6p_ip;
+
+#endif
 	struct sctp_chunkhdr *ch;
 	int length, offset, iphlen;
 	uint8_t ecn_bits;
@@ -224,11 +228,11 @@ sctp_skip_csum:
 	} else if (stcb == NULL) {
 		refcount_up = 1;
 	}
-	in6p_ip = (struct inpcb *)in6p;
 #ifdef IPSEC
 	/*
 	 * Check AH/ESP integrity.
 	 */
+	in6p_ip = (struct inpcb *)in6p;
 	if (in6p_ip && (ipsec6_in_reject(m, in6p_ip))) {
 /* XXX */
 		MODULE_GLOBAL(ipsec6stat).in_polvio++;
@@ -813,7 +817,6 @@ sctp6_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
     struct mbuf *control, struct thread *p)
 {
 	struct sctp_inpcb *inp;
-	struct inpcb *in_inp;
 	struct in6pcb *inp6;
 
 #ifdef INET
@@ -832,7 +835,6 @@ sctp6_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP6_USRREQ, EINVAL);
 		return EINVAL;
 	}
-	in_inp = (struct inpcb *)inp;
 	inp6 = (struct in6pcb *)inp;
 	/*
 	 * For the TCP model we may get a NULL addr, if we are a connected

From 09e3e7cd5c7eb44bd5f632149ad28aef7f2d0690 Mon Sep 17 00:00:00 2001
From: Jung-uk Kim 
Date: Wed, 15 Sep 2010 20:49:34 +0000
Subject: [PATCH 0783/1624] Import ACPICA 20100915.

---
 changes.txt                           |  64 +++
 common/adfile.c                       |   6 +-
 common/adisasm.c                      |  12 +-
 common/adwalk.c                       |  16 +-
 common/dmrestag.c                     |   4 +-
 common/getopt.c                       |   5 +-
 compiler/Makefile                     |   4 +
 compiler/aslanalyze.c                 |   5 +-
 compiler/aslcompile.c                 |   8 +-
 compiler/aslcompiler.h                |   4 +
 compiler/aslerror.c                   |   4 +-
 compiler/aslfiles.c                   |   4 +-
 compiler/asllisting.c                 |   4 +-
 compiler/asllookup.c                  |   8 +-
 compiler/aslmain.c                    |  18 +-
 compiler/aslopcodes.c                 |   6 +-
 compiler/aslpredef.c                  |   2 -
 compiler/aslrestype1.c                |   2 -
 compiler/aslrestype2d.c               |  24 +-
 compiler/aslrestype2e.c               |   1 -
 compiler/aslrestype2w.c               |  24 +-
 compiler/aslstartup.c                 |  30 +-
 compiler/dtcompile.c                  |  29 +-
 compiler/dtio.c                       |   2 +-
 debugger/dbexec.c                     |  10 +-
 events/evrgnini.c                     |  13 +-
 executer/exmutex.c                    |   6 +-
 hardware/hwpci.c                      | 531 +++++++++++++++++++++++++
 include/acglobal.h                    |   2 +-
 include/achware.h                     |  10 +
 include/aclocal.h                     |   2 +-
 include/acmacros.h                    |   4 +-
 include/acnamesp.h                    |  16 -
 include/acpiosxf.h                    |  10 -
 include/acpixf.h                      |   3 +-
 include/actypes.h                     |  32 +-
 include/acutils.h                     |  57 ++-
 include/platform/accygwin.h           |   8 +-
 include/platform/acenv.h              |   6 +
 include/platform/acfreebsd.h          |   3 -
 include/platform/acgcc.h              |   2 +
 include/platform/acintel.h            |  22 +-
 include/platform/aclinux.h            |   3 +-
 include/platform/acmsvc.h             |   6 +-
 include/platform/acos2.h              |   6 -
 include/platform/acwin.h              |   2 -
 include/platform/acwin64.h            |   2 +-
 namespace/nsrepair2.c                 | 180 +++++++++
 namespace/nsutils.c                   | 112 ------
 os_specific/service_layers/osunixxf.c |  18 +-
 os_specific/service_layers/oswintbl.c |   3 -
 os_specific/service_layers/oswinxf.c  |  13 +-
 osunixxf.c                            |  18 +-
 tables/tbfadt.c                       |   4 +-
 tools/acpiexec/Makefile               |   8 +
 tools/acpiexec/aecommon.h             |  14 +-
 tools/acpiexec/aeexec.c               | 247 +++++++-----
 tools/acpiexec/aehandlers.c           |  84 ++--
 tools/acpiexec/aemain.c               |  54 +--
 tools/acpiexec/aetables.c             |  66 ++--
 tools/acpisrc/asfile.c                |   5 +-
 tools/acpisrc/astable.c               |   1 +
 tools/acpixtract/acpixtract.c         |  50 +--
 utilities/utdebug.c                   |   7 +-
 utilities/utmath.c                    |  28 +-
 utilities/utmisc.c                    | 194 ---------
 utilities/utmutex.c                   |  24 +-
 utilities/utxferror.c                 | 550 ++++++++++++++++++++++++++
 68 files changed, 1918 insertions(+), 804 deletions(-)
 create mode 100644 hardware/hwpci.c
 create mode 100644 utilities/utxferror.c

diff --git a/changes.txt b/changes.txt
index 6ac171f2fb6..9bb84d4c77b 100644
--- a/changes.txt
+++ b/changes.txt
@@ -1,3 +1,67 @@
+----------------------------------------
+15 September 2010. Summary of changes for version 20100915:
+
+This release is available at www.acpica.org/downloads
+
+1) ACPI CA Core Subsystem:
+
+Removed the AcpiOsDerivePciId OSL interface. The various host implementations 
+of this function were not OS-dependent and are now obsolete and can be 
+removed from all host OSLs. This function has been replaced by 
+AcpiHwDerivePciId, which is now part of the ACPICA core code. 
+AcpiHwDerivePciId has been implemented without recursion. Adds one new 
+module, hwpci.c. ACPICA BZ 857.
+
+Implemented a dynamic repair for _HID and _CID strings. The following 
+problems are now repaired at runtime: 1) Remove a leading asterisk in the 
+string, and 2) the entire string is uppercased. Both repairs are in 
+accordance with the ACPI specification and will simplify host driver code. 
+ACPICA BZ 871.
+
+The ACPI_THREAD_ID type is no longer configurable, internally it is now 
+always UINT64. This simplifies the ACPICA code, especially any printf output. 
+UINT64 is the only common data type for all thread_id types across all 
+operating systems. It is now up to the host OSL to cast the native thread_id 
+type to UINT64 before returning the value to ACPICA (via AcpiOsGetThreadId). 
+Lin Ming, Bob Moore.
+
+Added the ACPI_INLINE type to enhance the ACPICA configuration. The "inline" 
+keyword is not standard across compilers, and this type allows inline to be 
+configured on a per-compiler basis. Lin Ming.
+
+Made the system global AcpiGbl_SystemAwakeAndRunning publically available. 
+Added an extern for this boolean in acpixf.h. Some hosts utilize this value 
+during suspend/restore operations. ACPICA BZ 869.
+
+All code that implements error/warning messages with the "ACPI:" prefix has 
+been moved to a new module, utxferror.c.
+
+The UINT64_OVERLAY was moved to utmath.c, which is the only module where it 
+is used. ACPICA BZ 829. Lin Ming, Bob Moore.
+
+Example Code and Data Size: These are the sizes for the OS-independent 
+acpica.lib produced by the Microsoft Visual C++ 6.0 32-bit compiler. The 
+debug version of the code includes the debug output trace mechanism and has a 
+much larger code and data size.
+
+  Previous Release:
+    Non-Debug Version:  89.1K Code, 19.0K Data, 108.1K Total
+    Debug Version:     165.1K Code, 51.9K Data, 217.0K Total
+  Current Release:
+    Non-Debug Version:  89.9K Code, 19.0K Data, 108.9K Total
+    Debug Version:     166.3K Code, 52.1K Data, 218.4K Total
+
+2) iASL Compiler/Disassembler and Tools:
+
+iASL/Disassembler: Write ACPI errors to stderr instead of the output file. 
+This keeps the output files free of random error messages that may originate 
+from within the namespace/interpreter code. Used this opportunity to merge 
+all ACPI:-style messages into a single new module, utxferror.c. ACPICA BZ 
+866. Lin Ming, Bob Moore.
+
+Tools: update some printfs for ansi warnings on size_t. Handle width change 
+of size_t on 32-bit versus 64-bit generations. Lin Ming.
+
 ----------------------------------------
 06 August 2010. Summary of changes for version 20100806:
 
diff --git a/common/adfile.c b/common/adfile.c
index c7f3dfb4760..629bd535c44 100644
--- a/common/adfile.c
+++ b/common/adfile.c
@@ -126,13 +126,13 @@
 
 /* Local prototypes */
 
-INT32
+static INT32
 AdWriteBuffer (
     char                    *Filename,
     char                    *Buffer,
     UINT32                  Length);
 
-char                        FilenameBuf[20];
+static char                 FilenameBuf[20];
 
 
 /******************************************************************************
@@ -190,7 +190,7 @@ AdGenerateFilename (
  *
  ******************************************************************************/
 
-INT32
+static INT32
 AdWriteBuffer (
     char                    *Filename,
     char                    *Buffer,
diff --git a/common/adisasm.c b/common/adisasm.c
index 79960c9bc27..31985f7f3c3 100644
--- a/common/adisasm.c
+++ b/common/adisasm.c
@@ -147,18 +147,18 @@ LsSetupNsList (
 
 /* Local prototypes */
 
-void
+static void
 AdCreateTableHeader (
     char                    *Filename,
     ACPI_TABLE_HEADER       *Table);
 
-ACPI_STATUS
+static ACPI_STATUS
 AdDeferredParse (
     ACPI_PARSE_OBJECT       *Op,
     UINT8                   *Aml,
     UINT32                  AmlLength);
 
-ACPI_STATUS
+static ACPI_STATUS
 AdParseDeferredOps (
     ACPI_PARSE_OBJECT       *Root);
 
@@ -634,7 +634,7 @@ AdDisassemblerHeader (
  *
  *****************************************************************************/
 
-void
+static void
 AdCreateTableHeader (
     char                    *Filename,
     ACPI_TABLE_HEADER       *Table)
@@ -781,7 +781,7 @@ AdDisplayTables (
  *
  *****************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 AdDeferredParse (
     ACPI_PARSE_OBJECT       *Op,
     UINT8                   *Aml,
@@ -904,7 +904,7 @@ AdDeferredParse (
  *
  *****************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 AdParseDeferredOps (
     ACPI_PARSE_OBJECT       *Root)
 {
diff --git a/common/adwalk.c b/common/adwalk.c
index b07053329cd..e8f580c1c1e 100644
--- a/common/adwalk.c
+++ b/common/adwalk.c
@@ -792,6 +792,7 @@ AcpiDmXrefDescendingOp (
     ACPI_PARSE_OBJECT       *NextOp;
     ACPI_NAMESPACE_NODE     *Node;
     ACPI_OPERAND_OBJECT     *Object;
+    UINT32                  ParamCount = 0;
 
 
     WalkState = Info->WalkState;
@@ -880,18 +881,13 @@ AcpiDmXrefDescendingOp (
         if (Object)
         {
             ObjectType2 = Object->Common.Type;
+            if (ObjectType2 == ACPI_TYPE_METHOD)
+            {
+                ParamCount = Object->Method.ParamCount;
+            }
         }
 
-        if (ObjectType2 == ACPI_TYPE_METHOD)
-        {
-            AcpiDmAddToExternalList (Op, Path, ACPI_TYPE_METHOD,
-                Object->Method.ParamCount);
-        }
-        else
-        {
-            AcpiDmAddToExternalList (Op, Path, (UINT8) ObjectType2, 0);
-        }
-
+        AcpiDmAddToExternalList (Op, Path, (UINT8) ObjectType2, ParamCount);
         Op->Common.Node = Node;
     }
     else
diff --git a/common/dmrestag.c b/common/dmrestag.c
index e1f340d54f1..184a856ed6d 100644
--- a/common/dmrestag.c
+++ b/common/dmrestag.c
@@ -704,8 +704,8 @@ AcpiDmUpdateResourceName (
 
     Name[0] = '_';
     Name[1] = AcpiGbl_Prefix[AcpiGbl_NextPrefix];
-    Name[2] = AcpiUtHexToAsciiChar (AcpiGbl_NextResourceId, 4);
-    Name[3] = AcpiUtHexToAsciiChar (AcpiGbl_NextResourceId, 0);
+    Name[2] = AcpiUtHexToAsciiChar ((UINT64) AcpiGbl_NextResourceId, 4);
+    Name[3] = AcpiUtHexToAsciiChar ((UINT64) AcpiGbl_NextResourceId, 0);
 
     /* Update globals for next name */
 
diff --git a/common/getopt.c b/common/getopt.c
index db1eb167d1f..9a8589c9956 100644
--- a/common/getopt.c
+++ b/common/getopt.c
@@ -126,7 +126,6 @@
 
 int   AcpiGbl_Opterr = 1;
 int   AcpiGbl_Optind = 1;
-int   AcpiGbl_Optopt;
 char  *AcpiGbl_Optarg;
 
 
@@ -171,9 +170,7 @@ AcpiGetopt(
 
     /* Get the option */
 
-    CurrentChar =
-    AcpiGbl_Optopt =
-    argv[AcpiGbl_Optind][CurrentCharPtr];
+    CurrentChar = argv[AcpiGbl_Optind][CurrentCharPtr];
 
     /* Make sure that the option is legal */
 
diff --git a/compiler/Makefile b/compiler/Makefile
index f1f175c5036..3d7028200b3 100644
--- a/compiler/Makefile
+++ b/compiler/Makefile
@@ -151,6 +151,7 @@ OBJS = \
 	utobject.o \
 	utresrc.o \
 	utstate.o \
+	utxferror.o \
 	utxface.o
 
 INTERMEDIATES = \
@@ -565,6 +566,9 @@ utresrc.o :         $(ACPICA_CORE)/utilities/utresrc.c
 utstate.o :         $(ACPICA_CORE)/utilities/utstate.c
 	$(COMPILE)
 
+utxferror.o :       $(ACPICA_CORE)/utilities/utxferror.c
+	$(COMPILE)
+
 utxface.o :         $(ACPICA_CORE)/utilities/utxface.c
 	$(COMPILE)
 
diff --git a/compiler/aslanalyze.c b/compiler/aslanalyze.c
index 9679d904c8c..4846c6b7d07 100644
--- a/compiler/aslanalyze.c
+++ b/compiler/aslanalyze.c
@@ -166,7 +166,7 @@ static UINT32
 AnGetInternalMethodReturnType (
     ACPI_PARSE_OBJECT       *Op);
 
-BOOLEAN
+static BOOLEAN
 AnIsResultUsed (
     ACPI_PARSE_OBJECT       *Op);
 
@@ -1754,7 +1754,7 @@ AnOperandTypecheckWalkEnd (
  *
  ******************************************************************************/
 
-BOOLEAN
+static BOOLEAN
 AnIsResultUsed (
     ACPI_PARSE_OBJECT       *Op)
 {
@@ -1862,6 +1862,7 @@ AnOtherSemanticAnalysisWalkBegin (
             if (Op->Asl.AmlOpcode == AML_DIVIDE_OP)
             {
                 if ((ArgNode->Asl.ParseOpcode == PARSEOP_ZERO) &&
+                    (PrevArgNode) &&
                     (PrevArgNode->Asl.ParseOpcode == PARSEOP_ZERO))
                 {
                     AslError (ASL_WARNING, ASL_MSG_RESULT_NOT_USED, Op, Op->Asl.ExternalName);
diff --git a/compiler/aslcompile.c b/compiler/aslcompile.c
index 5b664ff5e3c..f199c5b9b81 100644
--- a/compiler/aslcompile.c
+++ b/compiler/aslcompile.c
@@ -127,12 +127,12 @@ static void
 CmFlushSourceCode (
     void);
 
-void
+static void
 FlConsumeAnsiComment (
     ASL_FILE_INFO           *FileInfo,
     ASL_FILE_STATUS         *Status);
 
-void
+static void
 FlConsumeNewComment (
     ASL_FILE_INFO           *FileInfo,
     ASL_FILE_STATUS         *Status);
@@ -345,7 +345,7 @@ CmFlushSourceCode (
  *
  ******************************************************************************/
 
-void
+static void
 FlConsumeAnsiComment (
     ASL_FILE_INFO           *FileInfo,
     ASL_FILE_STATUS         *Status)
@@ -389,7 +389,7 @@ FlConsumeAnsiComment (
 }
 
 
-void
+static void
 FlConsumeNewComment (
     ASL_FILE_INFO           *FileInfo,
     ASL_FILE_STATUS         *Status)
diff --git a/compiler/aslcompiler.h b/compiler/aslcompiler.h
index c097feee637..4e97677b56e 100644
--- a/compiler/aslcompiler.h
+++ b/compiler/aslcompiler.h
@@ -686,6 +686,10 @@ ACPI_STATUS
 LsDisplayNamespace (
     void);
 
+void
+LsSetupNsList (
+    void                    *Handle);
+
 
 /*
  * aslutils - common compiler utilites
diff --git a/compiler/aslerror.c b/compiler/aslerror.c
index ff24e62b7aa..59d3d20b6fb 100644
--- a/compiler/aslerror.c
+++ b/compiler/aslerror.c
@@ -304,7 +304,7 @@ AePrintException (
 
             if (Enode->LineNumber)
             {
-                fprintf (OutputFile, "%6u: ", Enode->LineNumber);
+                fprintf (OutputFile, " %6u: ", Enode->LineNumber);
 
                 /*
                  * Seek to the offset in the combined source file, read the source
@@ -358,7 +358,7 @@ AePrintException (
     {
         /* Decode the message ID */
 
-        fprintf (OutputFile, "%s %4.4d -",
+        fprintf (OutputFile, "%s %4.4d - ",
                     AslErrorLevel[Enode->Level],
                     Enode->MessageId + ((Enode->Level+1) * 1000));
 
diff --git a/compiler/aslfiles.c b/compiler/aslfiles.c
index 6ba32ca9f74..281b779b0a0 100644
--- a/compiler/aslfiles.c
+++ b/compiler/aslfiles.c
@@ -122,7 +122,7 @@
 
 /* Local prototypes */
 
-FILE *
+static FILE *
 FlOpenIncludeWithPrefix (
     char                    *PrefixDir,
     char                    *Filename);
@@ -546,7 +546,7 @@ FlAddIncludeDirectory (
  *
  ******************************************************************************/
 
-FILE *
+static FILE *
 FlOpenIncludeWithPrefix (
     char                    *PrefixDir,
     char                    *Filename)
diff --git a/compiler/asllisting.c b/compiler/asllisting.c
index 93f83ad8427..2ad87d42dcd 100644
--- a/compiler/asllisting.c
+++ b/compiler/asllisting.c
@@ -202,7 +202,7 @@ static void
 LsDoHexOutputAsl (
     void);
 
-ACPI_STATUS
+static ACPI_STATUS
 LsTreeWriteWalk (
     ACPI_PARSE_OBJECT       *Op,
     UINT32                  Level,
@@ -222,7 +222,7 @@ LsTreeWriteWalk (
  *
  ******************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 LsTreeWriteWalk (
     ACPI_PARSE_OBJECT       *Op,
     UINT32                  Level,
diff --git a/compiler/asllookup.c b/compiler/asllookup.c
index 7cc72324060..db909fa1c0f 100644
--- a/compiler/asllookup.c
+++ b/compiler/asllookup.c
@@ -180,11 +180,7 @@ LsDoOnePathname (
     void                    *Context,
     void                    **ReturnValue);
 
-void
-LsSetupNsList (
-    void                    *Handle);
-
-ACPI_PARSE_OBJECT *
+static ACPI_PARSE_OBJECT *
 LkGetNameOp (
     ACPI_PARSE_OBJECT       *Op);
 
@@ -623,7 +619,7 @@ LkObjectExists (
  *
  ******************************************************************************/
 
-ACPI_PARSE_OBJECT *
+static ACPI_PARSE_OBJECT *
 LkGetNameOp (
     ACPI_PARSE_OBJECT       *Op)
 {
diff --git a/compiler/aslmain.c b/compiler/aslmain.c
index 39ea7aa399b..90faff739f8 100644
--- a/compiler/aslmain.c
+++ b/compiler/aslmain.c
@@ -214,7 +214,7 @@ Options (
     printf ("  -cr            Disable Resource Descriptor error checking\n");
     printf ("  -r   Override table header Revision (1-255)\n");
 
-    printf ("\nListings:\n");
+    printf ("\nASL Listing Files:\n");
     printf ("  -l             Create mixed listing file (ASL source and AML) (*.lst)\n");
     printf ("  -ln            Create namespace file (*.nsp)\n");
     printf ("  -ls            Create combined source file (expanded includes) (*.src)\n");
@@ -462,6 +462,7 @@ AslDoOptions (
     BOOLEAN                 IsResponseFile)
 {
     int                     j;
+    ACPI_STATUS             Status;
 
 
     /* Get the command line options */
@@ -554,7 +555,12 @@ AslDoOptions (
 
 
     case 'e':
-        AcpiDmAddToExternalFileList (AcpiGbl_Optarg);
+        Status = AcpiDmAddToExternalFileList (AcpiGbl_Optarg);
+        if (ACPI_FAILURE (Status))
+        {
+            printf ("Could not add %s to external list\n", AcpiGbl_Optarg);
+            return (-1);
+        }
         break;
 
 
@@ -601,7 +607,6 @@ AslDoOptions (
             printf ("Unknown option: -h%s\n", AcpiGbl_Optarg);
             return (-1);
         }
-        break;
 
 
     case 'I': /* Add an include file search directory */
@@ -891,6 +896,7 @@ AslCommandLine (
     char                    **argv)
 {
     int                     BadCommandLine = 0;
+    ACPI_STATUS             Status;
 
 
     /* Minimum command line contains at least the command and an input file */
@@ -908,7 +914,11 @@ AslCommandLine (
 
     if (Gbl_DoTemplates)
     {
-        DtCreateTemplates (Gbl_TemplateSignature);
+        Status = DtCreateTemplates (Gbl_TemplateSignature);
+        if (ACPI_FAILURE (Status))
+        {
+            exit (-1);
+        }
         exit (1);
     }
 
diff --git a/compiler/aslopcodes.c b/compiler/aslopcodes.c
index 1c6eef72480..48aaa50c0fe 100644
--- a/compiler/aslopcodes.c
+++ b/compiler/aslopcodes.c
@@ -592,9 +592,9 @@ OpcDoEisaId (
         /* Create ID big-endian first (bits are contiguous) */
 
         BigEndianId =
-            (UINT32) (InString[0] - 0x40) << 26 |
-            (UINT32) (InString[1] - 0x40) << 21 |
-            (UINT32) (InString[2] - 0x40) << 16 |
+            (UINT32) ((UINT8) (InString[0] - 0x40)) << 26 |
+            (UINT32) ((UINT8) (InString[1] - 0x40)) << 21 |
+            (UINT32) ((UINT8) (InString[2] - 0x40)) << 16 |
 
             (UtHexCharToValue (InString[3])) << 12 |
             (UtHexCharToValue (InString[4])) << 8  |
diff --git a/compiler/aslpredef.c b/compiler/aslpredef.c
index 49056edd180..f2c3f5919af 100644
--- a/compiler/aslpredef.c
+++ b/compiler/aslpredef.c
@@ -117,8 +117,6 @@
 
 #include "aslcompiler.h"
 #include "aslcompiler.y.h"
-#include "amlcode.h"
-#include "acparser.h"
 #include "acpredef.h"
 
 
diff --git a/compiler/aslrestype1.c b/compiler/aslrestype1.c
index 381fb53cc25..5c1bd0ed1ac 100644
--- a/compiler/aslrestype1.c
+++ b/compiler/aslrestype1.c
@@ -224,7 +224,6 @@ RsDoMemory24Descriptor (
     ACPI_PARSE_OBJECT       *MinOp = NULL;
     ACPI_PARSE_OBJECT       *MaxOp = NULL;
     ACPI_PARSE_OBJECT       *LengthOp = NULL;
-    ACPI_PARSE_OBJECT       *AlignOp = NULL;
     ASL_RESOURCE_NODE       *Rnode;
     UINT32                  i;
 
@@ -270,7 +269,6 @@ RsDoMemory24Descriptor (
             Descriptor->Memory24.Alignment = (UINT16) InitializerOp->Asl.Value.Integer;
             RsCreateByteField (InitializerOp, ACPI_RESTAG_ALIGNMENT,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory24.Alignment));
-            AlignOp = InitializerOp;
             break;
 
         case 4: /* Length */
diff --git a/compiler/aslrestype2d.c b/compiler/aslrestype2d.c
index 7725bf9a8da..17ce2703981 100644
--- a/compiler/aslrestype2d.c
+++ b/compiler/aslrestype2d.c
@@ -347,10 +347,10 @@ RsDoDwordIoDescriptor (
     /* Validate the Min/Max/Len/Gran values */
 
     RsLargeAddressCheck (
-        Descriptor->Address32.Minimum,
-        Descriptor->Address32.Maximum,
-        Descriptor->Address32.AddressLength,
-        Descriptor->Address32.Granularity,
+        (UINT64) Descriptor->Address32.Minimum,
+        (UINT64) Descriptor->Address32.Maximum,
+        (UINT64) Descriptor->Address32.AddressLength,
+        (UINT64) Descriptor->Address32.Granularity,
         Descriptor->Address32.Flags,
         MinOp, MaxOp, LengthOp, GranOp);
 
@@ -583,10 +583,10 @@ RsDoDwordMemoryDescriptor (
     /* Validate the Min/Max/Len/Gran values */
 
     RsLargeAddressCheck (
-        Descriptor->Address32.Minimum,
-        Descriptor->Address32.Maximum,
-        Descriptor->Address32.AddressLength,
-        Descriptor->Address32.Granularity,
+        (UINT64) Descriptor->Address32.Minimum,
+        (UINT64) Descriptor->Address32.Maximum,
+        (UINT64) Descriptor->Address32.AddressLength,
+        (UINT64) Descriptor->Address32.Granularity,
         Descriptor->Address32.Flags,
         MinOp, MaxOp, LengthOp, GranOp);
 
@@ -801,10 +801,10 @@ RsDoDwordSpaceDescriptor (
     /* Validate the Min/Max/Len/Gran values */
 
     RsLargeAddressCheck (
-        Descriptor->Address32.Minimum,
-        Descriptor->Address32.Maximum,
-        Descriptor->Address32.AddressLength,
-        Descriptor->Address32.Granularity,
+        (UINT64) Descriptor->Address32.Minimum,
+        (UINT64) Descriptor->Address32.Maximum,
+        (UINT64) Descriptor->Address32.AddressLength,
+        (UINT64) Descriptor->Address32.Granularity,
         Descriptor->Address32.Flags,
         MinOp, MaxOp, LengthOp, GranOp);
 
diff --git a/compiler/aslrestype2e.c b/compiler/aslrestype2e.c
index 46f56cec136..e5b2bd9054b 100644
--- a/compiler/aslrestype2e.c
+++ b/compiler/aslrestype2e.c
@@ -116,7 +116,6 @@
 
 
 #include "aslcompiler.h"
-#include "aslcompiler.y.h"
 
 #define _COMPONENT          ACPI_COMPILER
         ACPI_MODULE_NAME    ("aslrestype2e")
diff --git a/compiler/aslrestype2w.c b/compiler/aslrestype2w.c
index 45f1858fccf..a6e6774c028 100644
--- a/compiler/aslrestype2w.c
+++ b/compiler/aslrestype2w.c
@@ -338,10 +338,10 @@ RsDoWordIoDescriptor (
     /* Validate the Min/Max/Len/Gran values */
 
     RsLargeAddressCheck (
-        Descriptor->Address16.Minimum,
-        Descriptor->Address16.Maximum,
-        Descriptor->Address16.AddressLength,
-        Descriptor->Address16.Granularity,
+        (UINT64) Descriptor->Address16.Minimum,
+        (UINT64) Descriptor->Address16.Maximum,
+        (UINT64) Descriptor->Address16.AddressLength,
+        (UINT64) Descriptor->Address16.Granularity,
         Descriptor->Address16.Flags,
         MinOp, MaxOp, LengthOp, GranOp);
 
@@ -544,10 +544,10 @@ RsDoWordBusNumberDescriptor (
     /* Validate the Min/Max/Len/Gran values */
 
     RsLargeAddressCheck (
-        Descriptor->Address16.Minimum,
-        Descriptor->Address16.Maximum,
-        Descriptor->Address16.AddressLength,
-        Descriptor->Address16.Granularity,
+        (UINT64) Descriptor->Address16.Minimum,
+        (UINT64) Descriptor->Address16.Maximum,
+        (UINT64) Descriptor->Address16.AddressLength,
+        (UINT64) Descriptor->Address16.Granularity,
         Descriptor->Address16.Flags,
         MinOp, MaxOp, LengthOp, GranOp);
 
@@ -761,10 +761,10 @@ RsDoWordSpaceDescriptor (
     /* Validate the Min/Max/Len/Gran values */
 
     RsLargeAddressCheck (
-        Descriptor->Address16.Minimum,
-        Descriptor->Address16.Maximum,
-        Descriptor->Address16.AddressLength,
-        Descriptor->Address16.Granularity,
+        (UINT64) Descriptor->Address16.Minimum,
+        (UINT64) Descriptor->Address16.Maximum,
+        (UINT64) Descriptor->Address16.AddressLength,
+        (UINT64) Descriptor->Address16.Granularity,
         Descriptor->Address16.Flags,
         MinOp, MaxOp, LengthOp, GranOp);
 
diff --git a/compiler/aslstartup.c b/compiler/aslstartup.c
index 11c40049306..0d101430da5 100644
--- a/compiler/aslstartup.c
+++ b/compiler/aslstartup.c
@@ -124,9 +124,8 @@
 
 
 #define ASL_MAX_FILES   256
-char                    *FileList[ASL_MAX_FILES];
-int                     FileCount;
-BOOLEAN                 AslToFile = TRUE;
+static char             *FileList[ASL_MAX_FILES];
+static BOOLEAN          AslToFile = TRUE;
 
 
 /* Local prototypes */
@@ -136,7 +135,7 @@ AsDoWildcard (
     char                    *DirectoryPathname,
     char                    *FileSpecifier);
 
-UINT8
+static UINT8
 AslDetectSourceFileType (
     ASL_FILE_INFO           *Info);
 
@@ -210,6 +209,7 @@ AsDoWildcard (
 #ifdef WIN32
     void                    *DirInfo;
     char                    *Filename;
+    int                     FileCount;
 
 
     FileCount = 0;
@@ -277,7 +277,7 @@ AsDoWildcard (
  *
  ******************************************************************************/
 
-UINT8
+static UINT8
 AslDetectSourceFileType (
     ASL_FILE_INFO           *Info)
 {
@@ -397,7 +397,7 @@ AslDoOneFile (
         /* Shutdown compiler and ACPICA subsystem */
 
         AeClearErrorLog ();
-        AcpiTerminate ();
+        (void) AcpiTerminate ();
 
         /*
          * Gbl_Files[ASL_FILE_INPUT].Filename was replaced with the
@@ -487,7 +487,7 @@ AslDoOneFile (
         }
 
         Status = CmDoCompile ();
-        AcpiTerminate ();
+        (void) AcpiTerminate ();
 
         /*
          * Return non-zero exit code if there have been errors, unless the
@@ -533,7 +533,7 @@ AslDoOnePathname (
     ASL_PATHNAME_CALLBACK   PathCallback)
 {
     ACPI_STATUS             Status = AE_OK;
-    char                    **FileList;
+    char                    **WildcardList;
     char                    *Filename;
     char                    *FullPathname;
 
@@ -548,16 +548,16 @@ AslDoOnePathname (
 
     /* Expand possible wildcard into a file list (Windows/DOS only) */
 
-    FileList = AsDoWildcard (Gbl_DirectoryPath, Filename);
-    while (*FileList)
+    WildcardList = AsDoWildcard (Gbl_DirectoryPath, Filename);
+    while (*WildcardList)
     {
         FullPathname = ACPI_ALLOCATE (
-            strlen (Gbl_DirectoryPath) + strlen (*FileList) + 1);
+            strlen (Gbl_DirectoryPath) + strlen (*WildcardList) + 1);
 
         /* Construct a full path to the file */
 
         strcpy (FullPathname, Gbl_DirectoryPath);
-        strcat (FullPathname, *FileList);
+        strcat (FullPathname, *WildcardList);
 
         /*
          * If -p not specified, we will use the input filename as the
@@ -573,9 +573,9 @@ AslDoOnePathname (
         Status |= (*PathCallback) (FullPathname);
 
         ACPI_FREE (FullPathname);
-        ACPI_FREE (*FileList);
-        *FileList = NULL;
-        FileList++;
+        ACPI_FREE (*WildcardList);
+        *WildcardList = NULL;
+        WildcardList++;
     }
 
     ACPI_FREE (Gbl_DirectoryPath);
diff --git a/compiler/dtcompile.c b/compiler/dtcompile.c
index 651bdfa192e..c287c5b7af3 100644
--- a/compiler/dtcompile.c
+++ b/compiler/dtcompile.c
@@ -127,7 +127,7 @@ static char                 VersionString[9];
 
 /* Local prototypes */
 
-static void
+static ACPI_STATUS
 DtInitialize (
     void);
 
@@ -166,7 +166,12 @@ DtDoCompile (
 
     /* Initialize globals */
 
-    DtInitialize ();
+    Status = DtInitialize ();
+    if (ACPI_FAILURE (Status))
+    {
+        printf ("Error during compiler initialization, 0x%X\n", Status);
+        return (Status);
+    }
 
     /*
      * Scan the input file (file is already open) and
@@ -236,26 +241,38 @@ CleanupAndExit:
  *
  * PARAMETERS:  None
  *
- * RETURN:      None
+ * RETURN:      Status
  *
  * DESCRIPTION: Initialize data table compiler globals. Enables multiple
  *              compiles per invocation.
  *
  *****************************************************************************/
 
-static void
+static ACPI_STATUS
 DtInitialize (
     void)
 {
+    ACPI_STATUS             Status;
 
-    AcpiOsInitialize ();
-    AcpiUtInitGlobals ();
+
+    Status = AcpiOsInitialize ();
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    Status = AcpiUtInitGlobals ();
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
 
     Gbl_FieldList = NULL;
     Gbl_RootTable = NULL;
     Gbl_SubtableStack = NULL;
 
     sprintf (VersionString, "%X", (UINT32) ACPI_CA_VERSION);
+    return (AE_OK);
 }
 
 
diff --git a/compiler/dtio.c b/compiler/dtio.c
index 4c19ad0b0c8..a18ab5f7747 100644
--- a/compiler/dtio.c
+++ b/compiler/dtio.c
@@ -158,7 +158,7 @@ DtWriteBinary (
 #define DT_SLASH_SLASH_COMMENT      4
 #define DT_END_COMMENT              5
 
-UINT32  Gbl_NextLineOffset;
+static UINT32  Gbl_NextLineOffset;
 
 
 /******************************************************************************
diff --git a/debugger/dbexec.c b/debugger/dbexec.c
index 3555e8f63d9..56e7de72d35 100644
--- a/debugger/dbexec.c
+++ b/debugger/dbexec.c
@@ -567,14 +567,12 @@ AcpiDbMethodThread (
     if (Info->InitArgs)
     {
         AcpiDbUInt32ToHexString (Info->NumCreated, Info->IndexOfThreadStr);
-        AcpiDbUInt32ToHexString (ACPI_TO_INTEGER (AcpiOsGetThreadId ()),
-            Info->IdOfThreadStr);
+        AcpiDbUInt32ToHexString ((UINT32) AcpiOsGetThreadId (), Info->IdOfThreadStr);
     }
 
     if (Info->Threads && (Info->NumCreated < Info->NumThreads))
     {
-        Info->Threads[Info->NumCreated++] =
-            ACPI_TO_INTEGER (AcpiOsGetThreadId());
+        Info->Threads[Info->NumCreated++] = AcpiOsGetThreadId();
     }
 
     LocalInfo = *Info;
@@ -722,8 +720,8 @@ AcpiDbCreateExecutionThreads (
     /* Array to store IDs of threads */
 
     AcpiGbl_DbMethodInfo.NumThreads = NumThreads;
-    Size = 4 * AcpiGbl_DbMethodInfo.NumThreads;
-    AcpiGbl_DbMethodInfo.Threads = (UINT32 *) AcpiOsAllocate (Size);
+    Size = sizeof (ACPI_THREAD_ID) * AcpiGbl_DbMethodInfo.NumThreads;
+    AcpiGbl_DbMethodInfo.Threads = AcpiOsAllocate (Size);
     if (AcpiGbl_DbMethodInfo.Threads == NULL)
     {
         AcpiOsPrintf ("No memory for thread IDs array\n");
diff --git a/events/evrgnini.c b/events/evrgnini.c
index 1cce564ca8e..9fdda23a58e 100644
--- a/events/evrgnini.c
+++ b/events/evrgnini.c
@@ -395,8 +395,8 @@ AcpiEvPciConfigRegionSetup (
     }
 
     /*
-     * Get the PCI device and function numbers from the _ADR object contained
-     * in the parent's scope.
+     * Get the PCI device and function numbers from the _ADR object
+     * contained in the parent's scope.
      */
     Status = AcpiUtEvaluateNumericObject (METHOD_NAME__ADR,
                 PciDeviceNode, &PciValue);
@@ -429,9 +429,14 @@ AcpiEvPciConfigRegionSetup (
         PciId->Bus = ACPI_LOWORD (PciValue);
     }
 
-    /* Complete this device's PciId */
+    /* Complete/update the PCI ID for this device */
 
-    AcpiOsDerivePciId (PciRootNode, RegionObj->Region.Node, &PciId);
+    Status = AcpiHwDerivePciId (PciId, PciRootNode, RegionObj->Region.Node);
+    if (ACPI_FAILURE (Status))
+    {
+        ACPI_FREE (PciId);
+        return_ACPI_STATUS (Status);
+    }
 
     *RegionContext = PciId;
     return_ACPI_STATUS (AE_OK);
diff --git a/executer/exmutex.c b/executer/exmutex.c
index e9646ca77d9..4f7421d4a23 100644
--- a/executer/exmutex.c
+++ b/executer/exmutex.c
@@ -513,10 +513,10 @@ AcpiExReleaseMutex (
         (ObjDesc != AcpiGbl_GlobalLockMutex))
     {
         ACPI_ERROR ((AE_INFO,
-            "Thread %p cannot release Mutex [%4.4s] acquired by thread %p",
-            ACPI_CAST_PTR (void, WalkState->Thread->ThreadId),
+            "Thread %u cannot release Mutex [%4.4s] acquired by thread %u",
+            (UINT32) WalkState->Thread->ThreadId,
             AcpiUtGetNodeName (ObjDesc->Mutex.Node),
-            ACPI_CAST_PTR (void, OwnerThread->ThreadId)));
+            (UINT32) OwnerThread->ThreadId));
         return_ACPI_STATUS (AE_AML_NOT_OWNER);
     }
 
diff --git a/hardware/hwpci.c b/hardware/hwpci.c
new file mode 100644
index 00000000000..74c5f87a963
--- /dev/null
+++ b/hardware/hwpci.c
@@ -0,0 +1,531 @@
+/*******************************************************************************
+ *
+ * Module Name: hwpci - Obtain PCI bus, device, and function numbers
+ *
+ ******************************************************************************/
+
+/******************************************************************************
+ *
+ * 1. Copyright Notice
+ *
+ * Some or all of this work - Copyright (c) 1999 - 2010, Intel Corp.
+ * All rights reserved.
+ *
+ * 2. License
+ *
+ * 2.1. This is your license from Intel Corp. under its intellectual property
+ * rights.  You may have additional license terms from the party that provided
+ * you this software, covering your right to use that party's intellectual
+ * property rights.
+ *
+ * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
+ * copy of the source code appearing in this file ("Covered Code") an
+ * irrevocable, perpetual, worldwide license under Intel's copyrights in the
+ * base code distributed originally by Intel ("Original Intel Code") to copy,
+ * make derivatives, distribute, use and display any portion of the Covered
+ * Code in any form, with the right to sublicense such rights; and
+ *
+ * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
+ * license (with the right to sublicense), under only those claims of Intel
+ * patents that are infringed by the Original Intel Code, to make, use, sell,
+ * offer to sell, and import the Covered Code and derivative works thereof
+ * solely to the minimum extent necessary to exercise the above copyright
+ * license, and in no event shall the patent license extend to any additions
+ * to or modifications of the Original Intel Code.  No other license or right
+ * is granted directly or by implication, estoppel or otherwise;
+ *
+ * The above copyright and patent license is granted only if the following
+ * conditions are met:
+ *
+ * 3. Conditions
+ *
+ * 3.1. Redistribution of Source with Rights to Further Distribute Source.
+ * Redistribution of source code of any substantial portion of the Covered
+ * Code or modification with rights to further distribute source must include
+ * the above Copyright Notice, the above License, this list of Conditions,
+ * and the following Disclaimer and Export Compliance provision.  In addition,
+ * Licensee must cause all Covered Code to which Licensee contributes to
+ * contain a file documenting the changes Licensee made to create that Covered
+ * Code and the date of any change.  Licensee must include in that file the
+ * documentation of any changes made by any predecessor Licensee.  Licensee
+ * must include a prominent statement that the modification is derived,
+ * directly or indirectly, from Original Intel Code.
+ *
+ * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
+ * Redistribution of source code of any substantial portion of the Covered
+ * Code or modification without rights to further distribute source must
+ * include the following Disclaimer and Export Compliance provision in the
+ * documentation and/or other materials provided with distribution.  In
+ * addition, Licensee may not authorize further sublicense of source of any
+ * portion of the Covered Code, and must include terms to the effect that the
+ * license from Licensee to its licensee is limited to the intellectual
+ * property embodied in the software Licensee provides to its licensee, and
+ * not to intellectual property embodied in modifications its licensee may
+ * make.
+ *
+ * 3.3. Redistribution of Executable. Redistribution in executable form of any
+ * substantial portion of the Covered Code or modification must reproduce the
+ * above Copyright Notice, and the following Disclaimer and Export Compliance
+ * provision in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3.4. Intel retains all right, title, and interest in and to the Original
+ * Intel Code.
+ *
+ * 3.5. Neither the name Intel nor any other trademark owned or controlled by
+ * Intel shall be used in advertising or otherwise to promote the sale, use or
+ * other dealings in products derived from or relating to the Covered Code
+ * without prior written authorization from Intel.
+ *
+ * 4. Disclaimer and Export Compliance
+ *
+ * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
+ * HERE.  ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
+ * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT,  ASSISTANCE,
+ * INSTALLATION, TRAINING OR OTHER SERVICES.  INTEL WILL NOT PROVIDE ANY
+ * UPDATES, ENHANCEMENTS OR EXTENSIONS.  INTEL SPECIFICALLY DISCLAIMS ANY
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
+ * PARTICULAR PURPOSE.
+ *
+ * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
+ * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
+ * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
+ * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
+ * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
+ * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.  THESE LIMITATIONS
+ * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
+ * LIMITED REMEDY.
+ *
+ * 4.3. Licensee shall not export, either directly or indirectly, any of this
+ * software or system incorporating such software without first obtaining any
+ * required license or other approval from the U. S. Department of Commerce or
+ * any other agency or department of the United States Government.  In the
+ * event Licensee exports any such software from the United States or
+ * re-exports any such software from a foreign destination, Licensee shall
+ * ensure that the distribution and export/re-export of the software is in
+ * compliance with all laws, regulations, orders, or other restrictions of the
+ * U.S. Export Administration Regulations. Licensee agrees that neither it nor
+ * any of its subsidiaries will export/re-export any technical data, process,
+ * software, or service, directly or indirectly, to any country for which the
+ * United States government or any agency thereof requires an export license,
+ * other governmental approval, or letter of assurance, without first obtaining
+ * such license, approval or letter.
+ *
+ *****************************************************************************/
+
+#define __HWPCI_C__
+
+#include "acpi.h"
+#include "accommon.h"
+
+
+#define _COMPONENT          ACPI_NAMESPACE
+        ACPI_MODULE_NAME    ("hwpci")
+
+
+/* PCI configuration space values */
+
+#define PCI_CFG_HEADER_TYPE_REG             0x0E
+#define PCI_CFG_PRIMARY_BUS_NUMBER_REG      0x18
+#define PCI_CFG_SECONDARY_BUS_NUMBER_REG    0x19
+
+/* PCI header values */
+
+#define PCI_HEADER_TYPE_MASK                0x7F
+#define PCI_TYPE_BRIDGE                     0x01
+#define PCI_TYPE_CARDBUS_BRIDGE             0x02
+
+typedef struct acpi_pci_device
+{
+    ACPI_HANDLE             Device;
+    struct acpi_pci_device  *Next;
+
+} ACPI_PCI_DEVICE;
+
+
+/* Local prototypes */
+
+static ACPI_STATUS
+AcpiHwBuildPciList (
+    ACPI_HANDLE             RootPciDevice,
+    ACPI_HANDLE             PciRegion,
+    ACPI_PCI_DEVICE         **ReturnListHead);
+
+static ACPI_STATUS
+AcpiHwProcessPciList (
+    ACPI_PCI_ID             *PciId,
+    ACPI_PCI_DEVICE         *ListHead);
+
+static void
+AcpiHwDeletePciList (
+    ACPI_PCI_DEVICE         *ListHead);
+
+static ACPI_STATUS
+AcpiHwGetPciDeviceInfo (
+    ACPI_PCI_ID             *PciId,
+    ACPI_HANDLE             PciDevice,
+    UINT16                  *BusNumber,
+    BOOLEAN                 *IsBridge);
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiHwDerivePciId
+ *
+ * PARAMETERS:  PciId               - Initial values for the PCI ID. May be
+ *                                    modified by this function.
+ *              RootPciDevice       - A handle to a PCI device object. This
+ *                                    object must be a PCI Root Bridge having a
+ *                                    _HID value of either PNP0A03 or PNP0A08
+ *              PciRegion           - A handle to a PCI configuration space
+ *                                    Operation Region being initialized
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: This function derives a full PCI ID for a PCI device,
+ *              consisting of a Segment number, Bus number, Device number,
+ *              and function code.
+ *
+ *              The PCI hardware dynamically configures PCI bus numbers
+ *              depending on the bus topology discovered during system
+ *              initialization. This function is invoked during configuration
+ *              of a PCI_Config Operation Region in order to (possibly) update
+ *              the Bus/Device/Function numbers in the PciId with the actual
+ *              values as determined by the hardware and operating system
+ *              configuration.
+ *
+ *              The PciId parameter is initially populated during the Operation
+ *              Region initialization. This function is then called, and is
+ *              will make any necessary modifications to the Bus, Device, or
+ *              Function number PCI ID subfields as appropriate for the
+ *              current hardware and OS configuration.
+ *
+ * NOTE:        Created 08/2010. Replaces the previous OSL AcpiOsDerivePciId
+ *              interface since this feature is OS-independent. This module
+ *              specifically avoids any use of recursion by building a local
+ *              temporary device list.
+ *
+ ******************************************************************************/
+
+ACPI_STATUS
+AcpiHwDerivePciId (
+    ACPI_PCI_ID             *PciId,
+    ACPI_HANDLE             RootPciDevice,
+    ACPI_HANDLE             PciRegion)
+{
+    ACPI_STATUS             Status;
+    ACPI_PCI_DEVICE         *ListHead = NULL;
+
+
+    ACPI_FUNCTION_TRACE (HwDerivePciId);
+
+
+    if (!PciId)
+    {
+        return_ACPI_STATUS (AE_BAD_PARAMETER);
+    }
+
+    /* Build a list of PCI devices, from PciRegion up to RootPciDevice */
+
+    Status = AcpiHwBuildPciList (RootPciDevice, PciRegion, &ListHead);
+    if (ACPI_SUCCESS (Status))
+    {
+        /* Walk the list, updating the PCI device/function/bus numbers */
+
+        Status = AcpiHwProcessPciList (PciId, ListHead);
+    }
+
+    /* Always delete the list */
+
+    AcpiHwDeletePciList (ListHead);
+    return_ACPI_STATUS (Status);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiHwBuildPciList
+ *
+ * PARAMETERS:  RootPciDevice       - A handle to a PCI device object. This
+ *                                    object is guaranteed to be a PCI Root
+ *                                    Bridge having a _HID value of either
+ *                                    PNP0A03 or PNP0A08
+ *              PciRegion           - A handle to the PCI configuration space
+ *                                    Operation Region
+ *              ReturnListHead      - Where the PCI device list is returned
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Builds a list of devices from the input PCI region up to the
+ *              Root PCI device for this namespace subtree.
+ *
+ ******************************************************************************/
+
+static ACPI_STATUS
+AcpiHwBuildPciList (
+    ACPI_HANDLE             RootPciDevice,
+    ACPI_HANDLE             PciRegion,
+    ACPI_PCI_DEVICE         **ReturnListHead)
+{
+    ACPI_HANDLE             CurrentDevice;
+    ACPI_HANDLE             ParentDevice;
+    ACPI_STATUS             Status;
+    ACPI_PCI_DEVICE         *ListElement;
+    ACPI_PCI_DEVICE         *ListHead = NULL;
+
+
+    /*
+     * Ascend namespace branch until the RootPciDevice is reached, building
+     * a list of device nodes. Loop will exit when either the PCI device is
+     * found, or the root of the namespace is reached.
+     */
+    CurrentDevice = PciRegion;
+    while (1)
+    {
+        Status = AcpiGetParent (CurrentDevice, &ParentDevice);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        /* Finished when we reach the PCI root device (PNP0A03 or PNP0A08) */
+
+        if (ParentDevice == RootPciDevice)
+        {
+            *ReturnListHead = ListHead;
+            return (AE_OK);
+        }
+
+        ListElement = ACPI_ALLOCATE (sizeof (ACPI_PCI_DEVICE));
+        if (!ListElement)
+        {
+            return (AE_NO_MEMORY);
+        }
+
+        /* Put new element at the head of the list */
+
+        ListElement->Next = ListHead;
+        ListElement->Device = ParentDevice;
+        ListHead = ListElement;
+
+        CurrentDevice = ParentDevice;
+    }
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiHwProcessPciList
+ *
+ * PARAMETERS:  PciId               - Initial values for the PCI ID. May be
+ *                                    modified by this function.
+ *              ListHead            - Device list created by
+ *                                    AcpiHwBuildPciList
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Walk downward through the PCI device list, getting the device
+ *              info for each, via the PCI configuration space and updating
+ *              the PCI ID as necessary. Deletes the list during traversal.
+ *
+ ******************************************************************************/
+
+static ACPI_STATUS
+AcpiHwProcessPciList (
+    ACPI_PCI_ID             *PciId,
+    ACPI_PCI_DEVICE         *ListHead)
+{
+    ACPI_STATUS             Status = AE_OK;
+    ACPI_PCI_DEVICE         *Info;
+    UINT16                  BusNumber;
+    BOOLEAN                 IsBridge = TRUE;
+
+
+    ACPI_FUNCTION_NAME (HwProcessPciList);
+
+
+    ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
+        "Input PciId:  Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X\n",
+        PciId->Segment, PciId->Bus, PciId->Device, PciId->Function));
+
+    BusNumber = PciId->Bus;
+
+    /*
+     * Descend down the namespace tree, collecting PCI device, function,
+     * and bus numbers. BusNumber is only important for PCI bridges.
+     * Algorithm: As we descend the tree, use the last valid PCI device,
+     * function, and bus numbers that are discovered, and assign them
+     * to the PCI ID for the target device.
+     */
+    Info = ListHead;
+    while (Info)
+    {
+        Status = AcpiHwGetPciDeviceInfo (PciId, Info->Device,
+            &BusNumber, &IsBridge);
+        if (ACPI_FAILURE (Status))
+        {
+            return_ACPI_STATUS (Status);
+        }
+
+        Info = Info->Next;
+    }
+
+    ACPI_DEBUG_PRINT ((ACPI_DB_OPREGION,
+        "Output PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X "
+        "Status %X BusNumber %X IsBridge %X\n",
+        PciId->Segment, PciId->Bus, PciId->Device, PciId->Function,
+        Status, BusNumber, IsBridge));
+
+    return_ACPI_STATUS (AE_OK);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiHwDeletePciList
+ *
+ * PARAMETERS:  ListHead            - Device list created by
+ *                                    AcpiHwBuildPciList
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Free the entire PCI list.
+ *
+ ******************************************************************************/
+
+static void
+AcpiHwDeletePciList (
+    ACPI_PCI_DEVICE         *ListHead)
+{
+    ACPI_PCI_DEVICE         *Next;
+    ACPI_PCI_DEVICE         *Previous;
+
+
+    Next = ListHead;
+    while (Next)
+    {
+        Previous = Next;
+        Next = Previous->Next;
+        ACPI_FREE (Previous);
+    }
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiHwGetPciDeviceInfo
+ *
+ * PARAMETERS:  PciId               - Initial values for the PCI ID. May be
+ *                                    modified by this function.
+ *              PciDevice           - Handle for the PCI device object
+ *              BusNumber           - Where a PCI bridge bus number is returned
+ *              IsBridge            - Return value, indicates if this PCI
+ *                                    device is a PCI bridge
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Get the device info for a single PCI device object. Get the
+ *              _ADR (contains PCI device and function numbers), and for PCI
+ *              bridge devices, get the bus number from PCI configuration
+ *              space.
+ *
+ ******************************************************************************/
+
+static ACPI_STATUS
+AcpiHwGetPciDeviceInfo (
+    ACPI_PCI_ID             *PciId,
+    ACPI_HANDLE             PciDevice,
+    UINT16                  *BusNumber,
+    BOOLEAN                 *IsBridge)
+{
+    ACPI_STATUS             Status;
+    ACPI_OBJECT_TYPE        ObjectType;
+    UINT64                  ReturnValue;
+    UINT64                  PciValue;
+
+
+    /* We only care about objects of type Device */
+
+    Status = AcpiGetType (PciDevice, &ObjectType);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    if (ObjectType != ACPI_TYPE_DEVICE)
+    {
+        return (AE_OK);
+    }
+
+    /* We need an _ADR. Ignore device if not present */
+
+    Status = AcpiUtEvaluateNumericObject (METHOD_NAME__ADR,
+        PciDevice, &ReturnValue);
+    if (ACPI_FAILURE (Status))
+    {
+        return (AE_OK);
+    }
+
+    /*
+     * From _ADR, get the PCI Device and Function and
+     * update the PCI ID.
+     */
+    PciId->Device = ACPI_HIWORD (ACPI_LODWORD (ReturnValue));
+    PciId->Function = ACPI_LOWORD (ACPI_LODWORD (ReturnValue));
+
+    /*
+     * If the previous device was a bridge, use the previous
+     * device bus number
+     */
+    if (*IsBridge)
+    {
+        PciId->Bus = *BusNumber;
+    }
+
+    /*
+     * Get the bus numbers from PCI Config space:
+     *
+     * First, get the PCI HeaderType
+     */
+    *IsBridge = FALSE;
+    Status = AcpiOsReadPciConfiguration (PciId,
+        PCI_CFG_HEADER_TYPE_REG, &PciValue, 8);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    /* We only care about bridges (1=PciBridge, 2=CardBusBridge) */
+
+    PciValue &= PCI_HEADER_TYPE_MASK;
+
+    if ((PciValue != PCI_TYPE_BRIDGE) &&
+        (PciValue != PCI_TYPE_CARDBUS_BRIDGE))
+    {
+        return (AE_OK);
+    }
+
+    /* Bridge: Get the Primary BusNumber */
+
+    Status = AcpiOsReadPciConfiguration (PciId,
+        PCI_CFG_PRIMARY_BUS_NUMBER_REG, &PciValue, 8);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    *IsBridge = TRUE;
+    PciId->Bus = (UINT16) PciValue;
+
+    /* Bridge: Get the Secondary BusNumber */
+
+    Status = AcpiOsReadPciConfiguration (PciId,
+        PCI_CFG_SECONDARY_BUS_NUMBER_REG, &PciValue, 8);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    *BusNumber = (UINT16) PciValue;
+    return (AE_OK);
+}
diff --git a/include/acglobal.h b/include/acglobal.h
index 581fc76f376..2e158fbf79e 100644
--- a/include/acglobal.h
+++ b/include/acglobal.h
@@ -214,6 +214,7 @@ ACPI_TABLE_FADT             AcpiGbl_FADT;
 UINT32                      AcpiCurrentGpeCount;
 UINT32                      AcpiGbl_TraceFlags;
 ACPI_NAME                   AcpiGbl_TraceMethodName;
+BOOLEAN                     AcpiGbl_SystemAwakeAndRunning;
 
 #endif
 
@@ -334,7 +335,6 @@ ACPI_EXTERN UINT8                       AcpiGbl_DebuggerConfiguration;
 ACPI_EXTERN BOOLEAN                     AcpiGbl_StepToNextCall;
 ACPI_EXTERN BOOLEAN                     AcpiGbl_AcpiHardwarePresent;
 ACPI_EXTERN BOOLEAN                     AcpiGbl_EventsInitialized;
-ACPI_EXTERN BOOLEAN                     AcpiGbl_SystemAwakeAndRunning;
 ACPI_EXTERN UINT8                       AcpiGbl_OsiData;
 ACPI_EXTERN ACPI_INTERFACE_INFO        *AcpiGbl_SupportedInterfaces;
 
diff --git a/include/achware.h b/include/achware.h
index db08293c0af..e63fe3f2152 100644
--- a/include/achware.h
+++ b/include/achware.h
@@ -250,6 +250,16 @@ AcpiHwEnableRuntimeGpeBlock (
     void                    *Context);
 
 
+/*
+ * hwpci - PCI configuration support
+ */
+ACPI_STATUS
+AcpiHwDerivePciId (
+    ACPI_PCI_ID             *PciId,
+    ACPI_HANDLE             RootPciDevice,
+    ACPI_HANDLE             PciRegion);
+
+
 /*
  * hwtimer - ACPI Timer prototypes
  */
diff --git a/include/aclocal.h b/include/aclocal.h
index 39b6616d66c..eec3ffcb473 100644
--- a/include/aclocal.h
+++ b/include/aclocal.h
@@ -1270,7 +1270,7 @@ typedef struct acpi_db_method_info
     ACPI_HANDLE                     MainThreadGate;
     ACPI_HANDLE                     ThreadCompleteGate;
     ACPI_HANDLE                     InfoGate;
-    UINT32                          *Threads;
+    ACPI_THREAD_ID                  *Threads;
     UINT32                          NumThreads;
     UINT32                          NumCreated;
     UINT32                          NumCompleted;
diff --git a/include/acmacros.h b/include/acmacros.h
index e9a6f42cbf2..417cdc3b003 100644
--- a/include/acmacros.h
+++ b/include/acmacros.h
@@ -400,8 +400,8 @@
  * the plist contains a set of parens to allow variable-length lists.
  * These macros are used for both the debug and non-debug versions of the code.
  */
-#define ACPI_ERROR_NAMESPACE(s, e)      AcpiNsReportError (AE_INFO, s, e);
-#define ACPI_ERROR_METHOD(s, n, p, e)   AcpiNsReportMethodError (AE_INFO, s, n, p, e);
+#define ACPI_ERROR_NAMESPACE(s, e)      AcpiUtNamespaceError (AE_INFO, s, e);
+#define ACPI_ERROR_METHOD(s, n, p, e)   AcpiUtMethodError (AE_INFO, s, n, p, e);
 #define ACPI_WARN_PREDEFINED(plist)     AcpiUtPredefinedWarning plist
 #define ACPI_INFO_PREDEFINED(plist)     AcpiUtPredefinedInfo plist
 
diff --git a/include/acnamesp.h b/include/acnamesp.h
index 5895e062fec..5840bbc5861 100644
--- a/include/acnamesp.h
+++ b/include/acnamesp.h
@@ -513,22 +513,6 @@ UINT32
 AcpiNsLocal (
     ACPI_OBJECT_TYPE        Type);
 
-void
-AcpiNsReportError (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *InternalName,
-    ACPI_STATUS             LookupStatus);
-
-void
-AcpiNsReportMethodError (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *Message,
-    ACPI_NAMESPACE_NODE     *Node,
-    const char              *Path,
-    ACPI_STATUS             LookupStatus);
-
 void
 AcpiNsPrintNodePathname (
     ACPI_NAMESPACE_NODE     *Node,
diff --git a/include/acpiosxf.h b/include/acpiosxf.h
index 3b4e112895e..9187a4ab341 100644
--- a/include/acpiosxf.h
+++ b/include/acpiosxf.h
@@ -405,16 +405,6 @@ AcpiOsWritePciConfiguration (
     UINT32                  Width);
 
 
-/*
- * Interim function needed for PCI IRQ routing
- */
-void
-AcpiOsDerivePciId(
-    ACPI_HANDLE             Device,
-    ACPI_HANDLE             Region,
-    ACPI_PCI_ID             **PciId);
-
-
 /*
  * Miscellaneous
  */
diff --git a/include/acpixf.h b/include/acpixf.h
index bf101689063..7fac29fab55 100644
--- a/include/acpixf.h
+++ b/include/acpixf.h
@@ -120,7 +120,7 @@
 
 /* Current ACPICA subsystem version in YYYYMMDD format */
 
-#define ACPI_CA_VERSION                 0x20100806
+#define ACPI_CA_VERSION                 0x20100915
 
 #include "actypes.h"
 #include "actbl.h"
@@ -130,6 +130,7 @@
  */
 extern UINT32               AcpiCurrentGpeCount;
 extern ACPI_TABLE_FADT      AcpiGbl_FADT;
+extern BOOLEAN              AcpiGbl_SystemAwakeAndRunning;
 
 /* Runtime configuration of debug print levels */
 
diff --git a/include/actypes.h b/include/actypes.h
index 0486f8eb63d..e4290ae55d3 100644
--- a/include/actypes.h
+++ b/include/actypes.h
@@ -188,7 +188,6 @@
  *
  * ACPI_SIZE        16/32/64-bit unsigned value
  * ACPI_NATIVE_INT  16/32/64-bit signed value
- *
  */
 
 /*******************************************************************************
@@ -205,6 +204,16 @@ typedef COMPILER_DEPENDENT_INT64        INT64;
 
 /*! [End] no source code translation !*/
 
+/*
+ * Value returned by AcpiOsGetThreadId. There is no standard "thread_id"
+ * across operating systems or even the various UNIX systems. Since ACPICA
+ * only needs the thread ID as a unique thread identifier, we use a UINT64
+ * as the only common data type - it will accommodate any type of pointer or
+ * any type of integer. It is up to the host-dependent OSL to cast the
+ * native thread ID type to a UINT64 (in AcpiOsGetThreadId).
+ */
+#define ACPI_THREAD_ID                  UINT64
+
 
 /*******************************************************************************
  *
@@ -286,12 +295,6 @@ typedef UINT32                          ACPI_PHYSICAL_ADDRESS;
  *
  ******************************************************************************/
 
-/* Value returned by AcpiOsGetThreadId */
-
-#ifndef ACPI_THREAD_ID
-#define ACPI_THREAD_ID                  ACPI_SIZE
-#endif
-
 /* Flags for AcpiOsAcquireLock/AcpiOsReleaseLock */
 
 #ifndef ACPI_CPU_FLAGS
@@ -456,21 +459,6 @@ typedef UINT8                           ACPI_OWNER_ID;
 #define ACPI_OWNER_ID_MAX               0xFF
 
 
-typedef struct uint64_struct
-{
-    UINT32                          Lo;
-    UINT32                          Hi;
-
-} UINT64_STRUCT;
-
-typedef union uint64_overlay
-{
-    UINT64                          Full;
-    UINT64_STRUCT                   Part;
-
-} UINT64_OVERLAY;
-
-
 #define ACPI_INTEGER_BIT_SIZE           64
 #define ACPI_MAX_DECIMAL_DIGITS         20  /* 2^64 = 18,446,744,073,709,551,616 */
 #define ACPI_MAX64_DECIMAL_DIGITS       20
diff --git a/include/acutils.h b/include/acutils.h
index f729399154d..2d73da64fa4 100644
--- a/include/acutils.h
+++ b/include/acutils.h
@@ -818,24 +818,6 @@ AcpiUtStrtoul64 (
     UINT32                  Base,
     UINT64                  *RetInteger);
 
-void ACPI_INTERNAL_VAR_XFACE
-AcpiUtPredefinedWarning (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    char                    *Pathname,
-    UINT8                   NodeFlags,
-    const char              *Format,
-    ...);
-
-void ACPI_INTERNAL_VAR_XFACE
-AcpiUtPredefinedInfo (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    char                    *Pathname,
-    UINT8                   NodeFlags,
-    const char              *Format,
-    ...);
-
 /* Values for Base above (16=Hex, 10=Decimal) */
 
 #define ACPI_ANY_BASE        0
@@ -985,7 +967,44 @@ AcpiUtCreateList (
     UINT16                  ObjectSize,
     ACPI_MEMORY_LIST        **ReturnCache);
 
+#endif /* ACPI_DBG_TRACK_ALLOCATIONS */
 
-#endif
+
+/*
+ * utxferror - various error/warning output functions
+ */
+void ACPI_INTERNAL_VAR_XFACE
+AcpiUtPredefinedWarning (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    char                    *Pathname,
+    UINT8                   NodeFlags,
+    const char              *Format,
+    ...);
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiUtPredefinedInfo (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    char                    *Pathname,
+    UINT8                   NodeFlags,
+    const char              *Format,
+    ...);
+
+void
+AcpiUtNamespaceError (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *InternalName,
+    ACPI_STATUS             LookupStatus);
+
+void
+AcpiUtMethodError (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *Message,
+    ACPI_NAMESPACE_NODE     *Node,
+    const char              *Path,
+    ACPI_STATUS             LookupStatus);
 
 #endif /* _ACUTILS_H */
diff --git a/include/platform/accygwin.h b/include/platform/accygwin.h
index 6936024839e..36c0d6d2ced 100644
--- a/include/platform/accygwin.h
+++ b/include/platform/accygwin.h
@@ -121,7 +121,6 @@
  */
 #define ACPI_USE_SYSTEM_CLIBRARY
 #define ACPI_USE_DO_WHILE_0
-#define ACPI_THREAD_ID              pthread_t
 #define ACPI_FLUSH_CPU_CACHE()
 /*
  * This is needed since sem_timedwait does not appear to work properly
@@ -151,13 +150,12 @@
 #define __cdecl
 #endif
 
-#ifdef _ANSI
-#define inline
-#endif
-
 #define ACPI_ACQUIRE_GLOBAL_LOCK(GLptr, Acq) if (GLptr) Acq=1; else Acq=0;
 #define ACPI_RELEASE_GLOBAL_LOCK(GLptr, Pending) Pending = 1
 
+/* On Cygwin, pthread_t is a pointer */
+
+#define ACPI_CAST_PTHREAD_T(pthread) ((ACPI_THREAD_ID) ACPI_TO_INTEGER (pthread))
 
 /* Cygwin uses GCC */
 
diff --git a/include/platform/acenv.h b/include/platform/acenv.h
index 0567a003c6d..c709f4423eb 100644
--- a/include/platform/acenv.h
+++ b/include/platform/acenv.h
@@ -275,6 +275,12 @@
 #define ACPI_FLUSH_CPU_CACHE()
 #endif
 
+/* "inline" keywords - configurable since inline is not standardized */
+
+#ifndef ACPI_INLINE
+#define ACPI_INLINE
+#endif
+
 /*
  * Configurable calling conventions:
  *
diff --git a/include/platform/acfreebsd.h b/include/platform/acfreebsd.h
index 145b7bb0de6..6c087da084f 100644
--- a/include/platform/acfreebsd.h
+++ b/include/platform/acfreebsd.h
@@ -139,7 +139,6 @@
 
 #include "opt_acpi.h"
 
-#define ACPI_THREAD_ID      lwpid_t
 #define ACPI_MUTEX_TYPE     ACPI_OSL_MUTEX
 
 #ifdef ACPI_DEBUG
@@ -166,8 +165,6 @@
 #include 
 #endif
 
-#define ACPI_THREAD_ID      pthread_t
-
 #define ACPI_USE_STANDARD_HEADERS
 
 #define ACPI_FLUSH_CPU_CACHE()
diff --git a/include/platform/acgcc.h b/include/platform/acgcc.h
index d0098b1800a..9c7c9b94441 100644
--- a/include/platform/acgcc.h
+++ b/include/platform/acgcc.h
@@ -116,6 +116,8 @@
 #ifndef __ACGCC_H__
 #define __ACGCC_H__
 
+#define ACPI_INLINE             __inline__
+
 /* Function name is used for debug output. Non-ANSI, compiler-dependent */
 
 #define ACPI_GET_FUNCTION_NAME          __FUNCTION__
diff --git a/include/platform/acintel.h b/include/platform/acintel.h
index a7e75ec6031..415e9b00df4 100644
--- a/include/platform/acintel.h
+++ b/include/platform/acintel.h
@@ -116,11 +116,11 @@
 #ifndef __ACINTEL_H__
 #define __ACINTEL_H__
 
+/* Configuration specific to Intel 64-bit C compiler */
 
-#define COMPILER_DEPENDENT_INT64   __int64
-#define COMPILER_DEPENDENT_UINT64  unsigned __int64
-
-#define inline                  __inline
+#define COMPILER_DEPENDENT_INT64    __int64
+#define COMPILER_DEPENDENT_UINT64   unsigned __int64
+#define ACPI_INLINE                 __inline
 
 /*
  * Calling conventions:
@@ -135,20 +135,6 @@
 #define ACPI_INTERNAL_XFACE
 #define ACPI_INTERNAL_VAR_XFACE
 
-/*
- * Math helper functions
- */
-#define ACPI_DIV_64_BY_32(n, n_hi, n_lo, d32, q32, r32) \
-{ \
-    q32 = n / d32; \
-    r32 = n % d32; \
-}
-
-#define ACPI_SHIFT_RIGHT_64(n, n_hi, n_lo) \
-{ \
-    n <<= 1; \
-}
-
 /* remark 981 - operands evaluated in no particular order */
 #pragma warning(disable:981)
 
diff --git a/include/platform/aclinux.h b/include/platform/aclinux.h
index 9009689c938..44977468dcf 100644
--- a/include/platform/aclinux.h
+++ b/include/platform/aclinux.h
@@ -147,7 +147,6 @@
 #define ACPI_CACHE_T                struct kmem_cache
 #define ACPI_SPINLOCK               spinlock_t *
 #define ACPI_CPU_FLAGS              unsigned long
-#define ACPI_THREAD_ID              struct task_struct *
 
 #else /* !__KERNEL__ */
 
@@ -160,7 +159,7 @@
 /* Host-dependent types and defines for user-space ACPICA */
 
 #define ACPI_FLUSH_CPU_CACHE()
-#define ACPI_THREAD_ID              pthread_t
+#define ACPI_CAST_PTHREAD_T(pthread) ((ACPI_THREAD_ID) (pthread))
 
 #if defined(__ia64__) || defined(__x86_64__)
 #define ACPI_MACHINE_WIDTH          64
diff --git a/include/platform/acmsvc.h b/include/platform/acmsvc.h
index 62e69d16dc1..28a072780fb 100644
--- a/include/platform/acmsvc.h
+++ b/include/platform/acmsvc.h
@@ -116,8 +116,9 @@
 #ifndef __ACMSVC_H__
 #define __ACMSVC_H__
 
-#define COMPILER_DEPENDENT_INT64   __int64
-#define COMPILER_DEPENDENT_UINT64  unsigned __int64
+#define COMPILER_DEPENDENT_INT64    __int64
+#define COMPILER_DEPENDENT_UINT64   unsigned __int64
+#define ACPI_INLINE                 __inline
 
 /*
  * Calling conventions:
@@ -179,5 +180,4 @@
 /* warn C4131: uses old-style declarator (iASL compiler only) */
 #pragma warning(disable:4131)
 
-
 #endif /* __ACMSVC_H__ */
diff --git a/include/platform/acos2.h b/include/platform/acos2.h
index 90e6b2e4914..95f97eb8124 100644
--- a/include/platform/acos2.h
+++ b/include/platform/acos2.h
@@ -158,12 +158,6 @@ unsigned short OSPMReleaseGlobalLock (void *);
     n_lo = (unsigned long)(val & 0xffffffff); \
 }
 
-/* IBM VAC does not have inline */
-
-#if __IBMC__ || __IBMCPP__
-#define inline
-#endif
-
 #ifndef ACPI_ASL_COMPILER
 #define ACPI_USE_LOCAL_CACHE
 #undef ACPI_DEBUGGER
diff --git a/include/platform/acwin.h b/include/platform/acwin.h
index 583f677b475..a6ae8071a97 100644
--- a/include/platform/acwin.h
+++ b/include/platform/acwin.h
@@ -126,8 +126,6 @@
 
 #define ACPI_MACHINE_WIDTH      32
 
-#define inline                  __inline
-
 #define ACPI_USE_STANDARD_HEADERS
 
 #ifdef ACPI_DEFINE_ALTERNATE_TYPES
diff --git a/include/platform/acwin64.h b/include/platform/acwin64.h
index 64c1f99702a..076f586bd00 100644
--- a/include/platform/acwin64.h
+++ b/include/platform/acwin64.h
@@ -1,6 +1,6 @@
 /******************************************************************************
  *
- * Name: acwin.h - OS specific defines, etc.
+ * Name: acwin64.h - OS specific defines, etc.
  *
  *****************************************************************************/
 
diff --git a/namespace/nsrepair2.c b/namespace/nsrepair2.c
index 6ac7d6c356e..1464a3b2b5d 100644
--- a/namespace/nsrepair2.c
+++ b/namespace/nsrepair2.c
@@ -152,11 +152,21 @@ AcpiNsRepair_ALR (
     ACPI_PREDEFINED_DATA    *Data,
     ACPI_OPERAND_OBJECT     **ReturnObjectPtr);
 
+static ACPI_STATUS
+AcpiNsRepair_CID (
+    ACPI_PREDEFINED_DATA    *Data,
+    ACPI_OPERAND_OBJECT     **ReturnObjectPtr);
+
 static ACPI_STATUS
 AcpiNsRepair_FDE (
     ACPI_PREDEFINED_DATA    *Data,
     ACPI_OPERAND_OBJECT     **ReturnObjectPtr);
 
+static ACPI_STATUS
+AcpiNsRepair_HID (
+    ACPI_PREDEFINED_DATA    *Data,
+    ACPI_OPERAND_OBJECT     **ReturnObjectPtr);
+
 static ACPI_STATUS
 AcpiNsRepair_PSS (
     ACPI_PREDEFINED_DATA    *Data,
@@ -196,8 +206,10 @@ AcpiNsSortList (
  * As necessary:
  *
  * _ALR: Sort the list ascending by AmbientIlluminance
+ * _CID: Strings: uppercase all, remove any leading asterisk
  * _FDE: Convert Buffer of BYTEs to a Buffer of DWORDs
  * _GTM: Convert Buffer of BYTEs to a Buffer of DWORDs
+ * _HID: Strings: uppercase all, remove any leading asterisk
  * _PSS: Sort the list descending by Power
  * _TSS: Sort the list descending by Power
  *
@@ -211,8 +223,10 @@ AcpiNsSortList (
 static const ACPI_REPAIR_INFO       AcpiNsRepairableNames[] =
 {
     {"_ALR", AcpiNsRepair_ALR},
+    {"_CID", AcpiNsRepair_CID},
     {"_FDE", AcpiNsRepair_FDE},
     {"_GTM", AcpiNsRepair_FDE},     /* _GTM has same repair as _FDE */
+    {"_HID", AcpiNsRepair_HID},
     {"_PSS", AcpiNsRepair_PSS},
     {"_TSS", AcpiNsRepair_TSS},
     {{0,0,0,0}, NULL}               /* Table terminator */
@@ -425,6 +439,172 @@ AcpiNsRepair_FDE (
 }
 
 
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiNsRepair_CID
+ *
+ * PARAMETERS:  Data                - Pointer to validation data structure
+ *              ReturnObjectPtr     - Pointer to the object returned from the
+ *                                    evaluation of a method or object
+ *
+ * RETURN:      Status. AE_OK if object is OK or was repaired successfully
+ *
+ * DESCRIPTION: Repair for the _CID object. If a string, ensure that all
+ *              letters are uppercase and that there is no leading asterisk.
+ *              If a Package, ensure same for all string elements.
+ *
+ *****************************************************************************/
+
+static ACPI_STATUS
+AcpiNsRepair_CID (
+    ACPI_PREDEFINED_DATA    *Data,
+    ACPI_OPERAND_OBJECT     **ReturnObjectPtr)
+{
+    ACPI_STATUS             Status;
+    ACPI_OPERAND_OBJECT     *ReturnObject = *ReturnObjectPtr;
+    ACPI_OPERAND_OBJECT     **ElementPtr;
+    ACPI_OPERAND_OBJECT     *OriginalElement;
+    UINT16                  OriginalRefCount;
+    UINT32                  i;
+
+
+    /* Check for _CID as a simple string */
+
+    if (ReturnObject->Common.Type == ACPI_TYPE_STRING)
+    {
+        Status = AcpiNsRepair_HID (Data, ReturnObjectPtr);
+        return (Status);
+    }
+
+    /* Exit if not a Package */
+
+    if (ReturnObject->Common.Type != ACPI_TYPE_PACKAGE)
+    {
+        return (AE_OK);
+    }
+
+    /* Examine each element of the _CID package */
+
+    ElementPtr = ReturnObject->Package.Elements;
+    for (i = 0; i < ReturnObject->Package.Count; i++)
+    {
+        OriginalElement = *ElementPtr;
+        OriginalRefCount = OriginalElement->Common.ReferenceCount;
+
+        Status = AcpiNsRepair_HID (Data, ElementPtr);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        /* Take care with reference counts */
+
+        if (OriginalElement != *ElementPtr)
+        {
+            /* Element was replaced */
+
+            (*ElementPtr)->Common.ReferenceCount =
+                OriginalRefCount;
+
+            AcpiUtRemoveReference (OriginalElement);
+        }
+
+        ElementPtr++;
+    }
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiNsRepair_HID
+ *
+ * PARAMETERS:  Data                - Pointer to validation data structure
+ *              ReturnObjectPtr     - Pointer to the object returned from the
+ *                                    evaluation of a method or object
+ *
+ * RETURN:      Status. AE_OK if object is OK or was repaired successfully
+ *
+ * DESCRIPTION: Repair for the _HID object. If a string, ensure that all
+ *              letters are uppercase and that there is no leading asterisk.
+ *
+ *****************************************************************************/
+
+static ACPI_STATUS
+AcpiNsRepair_HID (
+    ACPI_PREDEFINED_DATA    *Data,
+    ACPI_OPERAND_OBJECT     **ReturnObjectPtr)
+{
+    ACPI_OPERAND_OBJECT     *ReturnObject = *ReturnObjectPtr;
+    ACPI_OPERAND_OBJECT     *NewString;
+    char                    *Source;
+    char                    *Dest;
+
+
+    ACPI_FUNCTION_NAME (NsRepair_HID);
+
+
+    /* We only care about string _HID objects (not integers) */
+
+    if (ReturnObject->Common.Type != ACPI_TYPE_STRING)
+    {
+        return (AE_OK);
+    }
+
+    if (ReturnObject->String.Length == 0)
+    {
+        ACPI_WARN_PREDEFINED ((AE_INFO, Data->Pathname, Data->NodeFlags,
+            "Invalid zero-length _HID or _CID string"));
+
+        /* Return AE_OK anyway, let driver handle it */
+
+        Data->Flags |= ACPI_OBJECT_REPAIRED;
+        return (AE_OK);
+    }
+
+    /* It is simplest to always create a new string object */
+
+    NewString = AcpiUtCreateStringObject (ReturnObject->String.Length);
+    if (!NewString)
+    {
+        return (AE_NO_MEMORY);
+    }
+
+    /*
+     * Remove a leading asterisk if present. For some unknown reason, there
+     * are many machines in the field that contains IDs like this.
+     *
+     * Examples: "*PNP0C03", "*ACPI0003"
+     */
+    Source = ReturnObject->String.Pointer;
+    if (*Source == '*')
+    {
+        Source++;
+        NewString->String.Length--;
+
+        ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR,
+            "%s: Removed invalid leading asterisk\n", Data->Pathname));
+    }
+
+    /*
+     * Copy and uppercase the string. From the ACPI specification:
+     *
+     * A valid PNP ID must be of the form "AAA####" where A is an uppercase
+     * letter and # is a hex digit. A valid ACPI ID must be of the form
+     * "ACPI####" where # is a hex digit.
+     */
+    for (Dest = NewString->String.Pointer; *Source; Dest++, Source++)
+    {
+        *Dest = (char) ACPI_TOUPPER (*Source);
+    }
+
+    AcpiUtRemoveReference (ReturnObject);
+    *ReturnObjectPtr = NewString;
+    return (AE_OK);
+}
+
+
 /******************************************************************************
  *
  * FUNCTION:    AcpiNsRepair_TSS
diff --git a/namespace/nsutils.c b/namespace/nsutils.c
index fc6140c00f1..aee9adcde95 100644
--- a/namespace/nsutils.c
+++ b/namespace/nsutils.c
@@ -137,118 +137,6 @@ AcpiNsFindParentName (
 #endif
 
 
-/*******************************************************************************
- *
- * FUNCTION:    AcpiNsReportError
- *
- * PARAMETERS:  ModuleName          - Caller's module name (for error output)
- *              LineNumber          - Caller's line number (for error output)
- *              InternalName        - Name or path of the namespace node
- *              LookupStatus        - Exception code from NS lookup
- *
- * RETURN:      None
- *
- * DESCRIPTION: Print warning message with full pathname
- *
- ******************************************************************************/
-
-void
-AcpiNsReportError (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *InternalName,
-    ACPI_STATUS             LookupStatus)
-{
-    ACPI_STATUS             Status;
-    UINT32                  BadName;
-    char                    *Name = NULL;
-
-
-    AcpiOsPrintf ("ACPI Error (%s-%04d): ", ModuleName, LineNumber);
-
-    if (LookupStatus == AE_BAD_CHARACTER)
-    {
-        /* There is a non-ascii character in the name */
-
-        ACPI_MOVE_32_TO_32 (&BadName, ACPI_CAST_PTR (UINT32, InternalName));
-        AcpiOsPrintf ("[0x%4.4X] (NON-ASCII)", BadName);
-    }
-    else
-    {
-        /* Convert path to external format */
-
-        Status = AcpiNsExternalizeName (ACPI_UINT32_MAX,
-                    InternalName, NULL, &Name);
-
-        /* Print target name */
-
-        if (ACPI_SUCCESS (Status))
-        {
-            AcpiOsPrintf ("[%s]", Name);
-        }
-        else
-        {
-            AcpiOsPrintf ("[COULD NOT EXTERNALIZE NAME]");
-        }
-
-        if (Name)
-        {
-            ACPI_FREE (Name);
-        }
-    }
-
-    AcpiOsPrintf (" Namespace lookup failure, %s\n",
-        AcpiFormatException (LookupStatus));
-}
-
-
-/*******************************************************************************
- *
- * FUNCTION:    AcpiNsReportMethodError
- *
- * PARAMETERS:  ModuleName          - Caller's module name (for error output)
- *              LineNumber          - Caller's line number (for error output)
- *              Message             - Error message to use on failure
- *              PrefixNode          - Prefix relative to the path
- *              Path                - Path to the node (optional)
- *              MethodStatus        - Execution status
- *
- * RETURN:      None
- *
- * DESCRIPTION: Print warning message with full pathname
- *
- ******************************************************************************/
-
-void
-AcpiNsReportMethodError (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *Message,
-    ACPI_NAMESPACE_NODE     *PrefixNode,
-    const char              *Path,
-    ACPI_STATUS             MethodStatus)
-{
-    ACPI_STATUS             Status;
-    ACPI_NAMESPACE_NODE     *Node = PrefixNode;
-
-
-    AcpiOsPrintf ("ACPI Error (%s-%04d): ", ModuleName, LineNumber);
-
-    if (Path)
-    {
-        Status = AcpiNsGetNode (PrefixNode, Path, ACPI_NS_NO_UPSEARCH,
-                    &Node);
-        if (ACPI_FAILURE (Status))
-        {
-            AcpiOsPrintf ("[Could not get node by pathname]");
-        }
-    }
-
-    AcpiNsPrintNodePathname (Node, Message);
-    AcpiOsPrintf (", %s\n", AcpiFormatException (MethodStatus));
-}
-
-
 /*******************************************************************************
  *
  * FUNCTION:    AcpiNsPrintNodePathname
diff --git a/os_specific/service_layers/osunixxf.c b/os_specific/service_layers/osunixxf.c
index 70c40d845d1..78fa435fec3 100644
--- a/os_specific/service_layers/osunixxf.c
+++ b/os_specific/service_layers/osunixxf.c
@@ -972,16 +972,6 @@ AcpiOsWritePciConfiguration (
     return (AE_OK);
 }
 
-/* TEMPORARY STUB FUNCTION */
-void
-AcpiOsDerivePciId(
-    ACPI_HANDLE             Device,
-    ACPI_HANDLE             Region,
-    ACPI_PCI_ID             **PciId)
-{
-
-}
-
 
 /******************************************************************************
  *
@@ -1168,16 +1158,14 @@ AcpiOsWritable (
  *
  * DESCRIPTION: Get the Id of the current (running) thread
  *
- * NOTE:        The environment header should contain this line:
- *                  #define ACPI_THREAD_ID pthread_t
- *
  *****************************************************************************/
 
 ACPI_THREAD_ID
-AcpiOsGetThreadId (void)
+AcpiOsGetThreadId (
+    void)
 {
 
-    return (pthread_self ());
+    return (ACPI_CAST_PTHREAD_T (pthread_self()));
 }
 
 
diff --git a/os_specific/service_layers/oswintbl.c b/os_specific/service_layers/oswintbl.c
index db609ee99d1..62df4c08762 100644
--- a/os_specific/service_layers/oswintbl.c
+++ b/os_specific/service_layers/oswintbl.c
@@ -116,16 +116,13 @@
 
 #ifdef WIN32
 #pragma warning(disable:4115)   /* warning C4115: (caused by rpcasync.h) */
-
 #include 
-#include 
 
 #elif WIN64
 #include 
 #endif
 
 #include "acpi.h"
-#include "accommon.h"
 
 #define _COMPONENT          ACPI_OS_SERVICES
         ACPI_MODULE_NAME    ("oswintbl")
diff --git a/os_specific/service_layers/oswinxf.c b/os_specific/service_layers/oswinxf.c
index 8a799b00999..cf19603ec28 100644
--- a/os_specific/service_layers/oswinxf.c
+++ b/os_specific/service_layers/oswinxf.c
@@ -1077,7 +1077,7 @@ AcpiOsGetThreadId (
     /* Ensure ID is never 0 */
 
     ThreadId = GetCurrentThreadId ();
-    return (ThreadId + 1);
+    return ((ACPI_THREAD_ID) (ThreadId + 1));
 }
 
 
@@ -1209,17 +1209,6 @@ AcpiOsWritePciConfiguration (
     return (AE_OK);
 }
 
-/* TEMPORARY STUB FUNCTION */
-void
-AcpiOsDerivePciId(
-    ACPI_HANDLE             Device,
-    ACPI_HANDLE             Region,
-    ACPI_PCI_ID             **PciId)
-{
-
-    return;
-}
-
 
 /******************************************************************************
  *
diff --git a/osunixxf.c b/osunixxf.c
index 70c40d845d1..78fa435fec3 100644
--- a/osunixxf.c
+++ b/osunixxf.c
@@ -972,16 +972,6 @@ AcpiOsWritePciConfiguration (
     return (AE_OK);
 }
 
-/* TEMPORARY STUB FUNCTION */
-void
-AcpiOsDerivePciId(
-    ACPI_HANDLE             Device,
-    ACPI_HANDLE             Region,
-    ACPI_PCI_ID             **PciId)
-{
-
-}
-
 
 /******************************************************************************
  *
@@ -1168,16 +1158,14 @@ AcpiOsWritable (
  *
  * DESCRIPTION: Get the Id of the current (running) thread
  *
- * NOTE:        The environment header should contain this line:
- *                  #define ACPI_THREAD_ID pthread_t
- *
  *****************************************************************************/
 
 ACPI_THREAD_ID
-AcpiOsGetThreadId (void)
+AcpiOsGetThreadId (
+    void)
 {
 
-    return (pthread_self ());
+    return (ACPI_CAST_PTHREAD_T (pthread_self()));
 }
 
 
diff --git a/tables/tbfadt.c b/tables/tbfadt.c
index 9ae4669d94a..a86a55cdaa4 100644
--- a/tables/tbfadt.c
+++ b/tables/tbfadt.c
@@ -124,7 +124,7 @@
 
 /* Local prototypes */
 
-static inline void
+static ACPI_INLINE void
 AcpiTbInitGenericAddress (
     ACPI_GENERIC_ADDRESS    *GenericAddress,
     UINT8                   SpaceId,
@@ -273,7 +273,7 @@ static ACPI_FADT_PM_INFO    FadtPmInfoTable[] =
  *
  ******************************************************************************/
 
-static inline void
+static ACPI_INLINE void
 AcpiTbInitGenericAddress (
     ACPI_GENERIC_ADDRESS    *GenericAddress,
     UINT8                   SpaceId,
diff --git a/tools/acpiexec/Makefile b/tools/acpiexec/Makefile
index 5fbe79504be..102c33d5b51 100644
--- a/tools/acpiexec/Makefile
+++ b/tools/acpiexec/Makefile
@@ -89,6 +89,7 @@ OBJS = \
 	getopt.o \
 	hwacpi.o \
 	hwgpe.o \
+	hwpci.o \
 	hwregs.o \
 	hwsleep.o \
 	hwvalid.o \
@@ -158,6 +159,7 @@ OBJS = \
 	utstate.o \
 	uttrack.o \
 	utosi.o \
+	utxferror.o \
 	utxface.o
 
 
@@ -396,6 +398,9 @@ hwacpi.o :          $(ACPICA_CORE)/hardware/hwacpi.c
 hwgpe.o :           $(ACPICA_CORE)/hardware/hwgpe.c
 	$(COMPILE)
 
+hwpci.o :           $(ACPICA_CORE)/hardware/hwpci.c
+	$(COMPILE)
+
 hwregs.o :          $(ACPICA_CORE)/hardware/hwregs.c
 	$(COMPILE)
 
@@ -600,6 +605,9 @@ uttrack.o :         $(ACPICA_CORE)/utilities/uttrack.c
 utosi.o :           $(ACPICA_CORE)/utilities/utosi.c
 	$(COMPILE)
 
+utxferror.o :       $(ACPICA_CORE)/utilities/utxferror.c
+	$(COMPILE)
+
 utxface.o :         $(ACPICA_CORE)/utilities/utxface.c
 	$(COMPILE)
 
diff --git a/tools/acpiexec/aecommon.h b/tools/acpiexec/aecommon.h
index 7608c5de488..3b7d36d9912 100644
--- a/tools/acpiexec/aecommon.h
+++ b/tools/acpiexec/aecommon.h
@@ -139,6 +139,18 @@ extern FILE                 *AcpiGbl_DebugFile;
 extern BOOLEAN              AcpiGbl_IgnoreErrors;
 extern UINT8                AcpiGbl_RegionFillValue;
 
+/* Check for unexpected exceptions */
+
+#define AE_CHECK_STATUS(Name, Status, Expected) \
+    if (Status != Expected) \
+    { \
+        AcpiOsPrintf ("Unexpected %s from %s (%s-%d)\n", \
+            AcpiFormatException (Status), #Name, _AcpiModuleName, __LINE__); \
+    }
+
+/* Check for unexpected non-AE_OK errors */
+
+#define AE_CHECK_OK(Name, Status)   AE_CHECK_STATUS (Name, Status, AE_OK);
 
 typedef struct ae_table_desc
 {
@@ -173,7 +185,7 @@ typedef struct ae_debug_regions
 #define OSD_PRINT(lvl,fp)               TEST_OUTPUT_LEVEL(lvl) {\
                                             AcpiOsPrintf PARAM_LIST(fp);}
 
-void __cdecl
+void ACPI_SYSTEM_XFACE
 AeCtrlCHandler (
     int                     Sig);
 
diff --git a/tools/acpiexec/aeexec.c b/tools/acpiexec/aeexec.c
index 948b2275469..baf1aeb75b1 100644
--- a/tools/acpiexec/aeexec.c
+++ b/tools/acpiexec/aeexec.c
@@ -120,39 +120,39 @@
 
 /* Local prototypes */
 
-ACPI_STATUS
+static ACPI_STATUS
 AeSetupConfiguration (
     void                    *RegionAddr);
 
-void
+static void
 AfInstallGpeBlock (
     void);
 
-void
+static void
 AeTestBufferArgument (
     void);
 
-void
+static void
 AeTestPackageArgument (
     void);
 
-ACPI_STATUS
+static ACPI_STATUS
 AeGetDevices (
     ACPI_HANDLE             ObjHandle,
     UINT32                  NestingLevel,
     void                    *Context,
     void                    **ReturnValue);
 
-ACPI_STATUS
+static ACPI_STATUS
 ExecuteOSI (
     char                    *OsiString,
     UINT32                  ExpectedResult);
 
-void
+static void
 AeHardwareInterfaces (
     void);
 
-void
+static void
 AeGenericRegisters (
     void);
 
@@ -172,11 +172,10 @@ extern unsigned char Ssdt3Code[];
  *
  *****************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 AeSetupConfiguration (
     void                    *RegionAddr)
 {
-    ACPI_STATUS             Status;
     ACPI_OBJECT_LIST        ArgList;
     ACPI_OBJECT             Arg[3];
 
@@ -190,8 +189,7 @@ AeSetupConfiguration (
     Arg[0].Type = ACPI_TYPE_INTEGER;
     Arg[0].Integer.Value = ACPI_TO_INTEGER (RegionAddr);
 
-    Status = AcpiEvaluateObject (NULL, "\\_CFG", &ArgList, NULL);
-
+    (void) AcpiEvaluateObject (NULL, "\\_CFG", &ArgList, NULL);
     return (AE_OK);
 }
 
@@ -209,7 +207,7 @@ AeSetupConfiguration (
  *
  *****************************************************************************/
 
-void
+static void
 AfInstallGpeBlock (
     void)
 {
@@ -235,33 +233,46 @@ AfInstallGpeBlock (
     if (ACPI_SUCCESS (Status))
     {
         Status = AcpiInstallGpeBlock (Handle2, &BlockAddress, 7, 8);
+        AE_CHECK_OK (AcpiInstallGpeBlock, Status);
 
-        AcpiInstallGpeHandler (Handle2, 8, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-        AcpiEnableGpe (Handle2, 8);
+        Status = AcpiInstallGpeHandler (Handle2, 8,
+            ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+        AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+        Status = AcpiEnableGpe (Handle2, 8);
+        AE_CHECK_OK (AcpiEnableGpe, Status);
 
         Status = AcpiGetGpeDevice (0x30, &GpeDevice);
-        Status = AcpiGetGpeDevice (0x42, &GpeDevice);
-        Status = AcpiGetGpeDevice (AcpiCurrentGpeCount-1, &GpeDevice);
-        Status = AcpiGetGpeDevice (AcpiCurrentGpeCount, &GpeDevice);
+        AE_CHECK_OK (AcpiGetGpeDevice, Status);
 
-        AcpiRemoveGpeHandler (Handle2, 8, AeGpeHandler);
+        Status = AcpiGetGpeDevice (0x42, &GpeDevice);
+        AE_CHECK_OK (AcpiGetGpeDevice, Status);
+
+        Status = AcpiGetGpeDevice (AcpiCurrentGpeCount-1, &GpeDevice);
+        AE_CHECK_OK (AcpiGetGpeDevice, Status);
+
+        Status = AcpiGetGpeDevice (AcpiCurrentGpeCount, &GpeDevice);
+        AE_CHECK_STATUS (AcpiGetGpeDevice, Status, AE_NOT_EXIST);
+
+        Status = AcpiRemoveGpeHandler (Handle2, 8, AeGpeHandler);
+        AE_CHECK_OK (AcpiRemoveGpeHandler, Status);
     }
 
     Status = AcpiGetHandle (NULL, "\\GPE3", &Handle3);
     if (ACPI_SUCCESS (Status))
     {
         Status = AcpiInstallGpeBlock (Handle3, &BlockAddress, 8, 11);
+        AE_CHECK_OK (AcpiInstallGpeBlock, Status);
     }
 }
 
 
 /* Test using a Buffer object as a method argument */
 
-void
+static void
 AeTestBufferArgument (
     void)
 {
-    ACPI_STATUS             Status;
     ACPI_OBJECT_LIST        Params;
     ACPI_OBJECT             BufArg;
     UINT8                   Buffer[] = {
@@ -277,26 +288,23 @@ AeTestBufferArgument (
     Params.Count = 1;
     Params.Pointer = &BufArg;
 
-
-    Status = AcpiEvaluateObject (NULL, "\\BUF", &Params, NULL);
+    (void) AcpiEvaluateObject (NULL, "\\BUF", &Params, NULL);
 }
 
 
-ACPI_OBJECT                 PkgArg;
-ACPI_OBJECT                 PkgElements[5];
-ACPI_OBJECT                 Pkg2Elements[5];
-ACPI_OBJECT_LIST            Params;
+static ACPI_OBJECT                 PkgArg;
+static ACPI_OBJECT                 PkgElements[5];
+static ACPI_OBJECT                 Pkg2Elements[5];
+static ACPI_OBJECT_LIST            Params;
 
 
 /*
  * Test using a Package object as an method argument
  */
-void
+static void
 AeTestPackageArgument (
     void)
 {
-    ACPI_STATUS             Status;
-
 
     /* Main package */
 
@@ -335,11 +343,11 @@ AeTestPackageArgument (
     Params.Count = 1;
     Params.Pointer = &PkgArg;
 
-    Status = AcpiEvaluateObject (NULL, "\\_PKG", &Params, NULL);
+    (void) AcpiEvaluateObject (NULL, "\\_PKG", &Params, NULL);
 }
 
 
-ACPI_STATUS
+static ACPI_STATUS
 AeGetDevices (
     ACPI_HANDLE                     ObjHandle,
     UINT32                          NestingLevel,
@@ -364,7 +372,7 @@ AeGetDevices (
  *
  *****************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 ExecuteOSI (
     char                    *OsiString,
     UINT32                  ExpectedResult)
@@ -434,9 +442,9 @@ ExecuteOSI (
  *
  *****************************************************************************/
 
-ACPI_GENERIC_ADDRESS       GenericRegister;
+static ACPI_GENERIC_ADDRESS       GenericRegister;
 
-void
+static void
 AeGenericRegisters (
     void)
 {
@@ -450,14 +458,20 @@ AeGenericRegisters (
     GenericRegister.SpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
 
     Status = AcpiRead (&Value, &GenericRegister);
+    AE_CHECK_OK (AcpiRead, Status);
+
     Status = AcpiWrite (Value, &GenericRegister);
+    AE_CHECK_OK (AcpiWrite, Status);
 
     GenericRegister.Address = 0x12345678;
     GenericRegister.BitOffset = 0;
     GenericRegister.SpaceId = ACPI_ADR_SPACE_SYSTEM_MEMORY;
 
     Status = AcpiRead (&Value, &GenericRegister);
+    AE_CHECK_OK (AcpiRead, Status);
+
     Status = AcpiWrite (Value, &GenericRegister);
+    AE_CHECK_OK (AcpiWrite, Status);
 }
 
 
@@ -469,7 +483,7 @@ AeGenericRegisters (
  *
  *****************************************************************************/
 
-void
+static void
 AeHardwareInterfaces (
     void)
 {
@@ -478,14 +492,29 @@ AeHardwareInterfaces (
 
 
     Status = AcpiWriteBitRegister (ACPI_BITREG_WAKE_STATUS, 1);
+    AE_CHECK_OK (AcpiWriteBitRegister, Status);
+
     Status = AcpiWriteBitRegister (ACPI_BITREG_GLOBAL_LOCK_ENABLE, 1);
+    AE_CHECK_OK (AcpiWriteBitRegister, Status);
+
     Status = AcpiWriteBitRegister (ACPI_BITREG_SLEEP_ENABLE, 1);
+    AE_CHECK_OK (AcpiWriteBitRegister, Status);
+
     Status = AcpiWriteBitRegister (ACPI_BITREG_ARB_DISABLE, 1);
+    AE_CHECK_OK (AcpiWriteBitRegister, Status);
+
 
     Status = AcpiReadBitRegister (ACPI_BITREG_WAKE_STATUS, &Value);
+    AE_CHECK_OK (AcpiReadBitRegister, Status);
+
     Status = AcpiReadBitRegister (ACPI_BITREG_GLOBAL_LOCK_ENABLE, &Value);
+    AE_CHECK_OK (AcpiReadBitRegister, Status);
+
     Status = AcpiReadBitRegister (ACPI_BITREG_SLEEP_ENABLE, &Value);
+    AE_CHECK_OK (AcpiReadBitRegister, Status);
+
     Status = AcpiReadBitRegister (ACPI_BITREG_ARB_DISABLE, &Value);
+    AE_CHECK_OK (AcpiReadBitRegister, Status);
 }
 
 
@@ -519,52 +548,108 @@ AeMiscellaneousTests (
     AeTestPackageArgument ();
 
 
-    AcpiInstallInterface ("");
-    AcpiInstallInterface ("TestString");
-    AcpiInstallInterface ("TestString");
-    AcpiRemoveInterface ("Windows 2006");
-    AcpiRemoveInterface ("TestString");
-    AcpiRemoveInterface ("XXXXXX");
-    AcpiInstallInterface ("AnotherTestString");
+    Status = AcpiInstallInterface ("");
+    AE_CHECK_STATUS (AcpiInstallInterface, Status, AE_BAD_PARAMETER);
 
-    ExecuteOSI ("Windows 2001", 0xFFFFFFFF);
-    ExecuteOSI ("MichiganTerminalSystem", 0);
+    Status = AcpiInstallInterface ("TestString");
+    AE_CHECK_OK (AcpiInstallInterface, Status);
+
+    Status = AcpiInstallInterface ("TestString");
+    AE_CHECK_STATUS (AcpiInstallInterface, Status, AE_ALREADY_EXISTS);
+
+    Status = AcpiRemoveInterface ("Windows 2006");
+    AE_CHECK_OK (AcpiRemoveInterface, Status);
+
+    Status = AcpiRemoveInterface ("TestString");
+    AE_CHECK_OK (AcpiRemoveInterface, Status);
+
+    Status = AcpiRemoveInterface ("XXXXXX");
+    AE_CHECK_STATUS (AcpiRemoveInterface, Status, AE_NOT_EXIST);
+
+    Status = AcpiInstallInterface ("AnotherTestString");
+    AE_CHECK_OK (AcpiInstallInterface, Status);
+
+
+    Status = ExecuteOSI ("Windows 2001", 0xFFFFFFFF);
+    AE_CHECK_OK (ExecuteOSI, Status);
+
+    Status = ExecuteOSI ("MichiganTerminalSystem", 0);
+    AE_CHECK_OK (ExecuteOSI, Status);
 
 
     ReturnBuf.Length = 32;
     ReturnBuf.Pointer = Buffer;
 
-    AcpiGetName (AcpiGbl_RootNode, ACPI_FULL_PATHNAME, &ReturnBuf);
-    AcpiEnableEvent (ACPI_EVENT_GLOBAL, 0);
+    Status = AcpiGetName (AcpiGbl_RootNode, ACPI_FULL_PATHNAME, &ReturnBuf);
+    AE_CHECK_OK (AcpiGetName, Status);
+
+    Status = AcpiEnableEvent (ACPI_EVENT_GLOBAL, 0);
+    AE_CHECK_OK (AcpiEnableEvent, Status);
 
     /*
      * GPEs: Handlers, enable/disable, etc.
      */
-    AcpiInstallGpeHandler (NULL, 0, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-    AcpiEnableGpe (NULL, 0);
-    AcpiRemoveGpeHandler (NULL, 0, AeGpeHandler);
+    Status = AcpiInstallGpeHandler (NULL, 0, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
 
-    AcpiInstallGpeHandler (NULL, 0, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-    AcpiEnableGpe (NULL, 0);
-    AcpiSetGpe (NULL, 0, ACPI_GPE_DISABLE);
-    AcpiSetGpe (NULL, 0, ACPI_GPE_ENABLE);
+    Status = AcpiEnableGpe (NULL, 0);
+    AE_CHECK_OK (AcpiEnableGpe, Status);
 
-    AcpiInstallGpeHandler (NULL, 1, ACPI_GPE_EDGE_TRIGGERED, AeGpeHandler, NULL);
-    AcpiEnableGpe (NULL, 1);
+    Status = AcpiRemoveGpeHandler (NULL, 0, AeGpeHandler);
+    AE_CHECK_OK (AcpiRemoveGpeHandler, Status);
 
-    AcpiInstallGpeHandler (NULL, 2, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-    AcpiEnableGpe (NULL, 2);
+    Status = AcpiInstallGpeHandler (NULL, 0, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
 
-    AcpiInstallGpeHandler (NULL, 3, ACPI_GPE_EDGE_TRIGGERED, AeGpeHandler, NULL);
-    AcpiInstallGpeHandler (NULL, 4, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-    AcpiInstallGpeHandler (NULL, 5, ACPI_GPE_EDGE_TRIGGERED, AeGpeHandler, NULL);
+    Status = AcpiEnableGpe (NULL, 0);
+    AE_CHECK_OK (AcpiEnableGpe, Status);
 
-    AcpiInstallGpeHandler (NULL, 0x19, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-    AcpiEnableGpe (NULL, 0x19);
+    Status = AcpiSetGpe (NULL, 0, ACPI_GPE_DISABLE);
+    AE_CHECK_OK (AcpiSetGpe, Status);
 
-    AcpiInstallGpeHandler (NULL, 0x62, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
-    AcpiEnableGpe (NULL, 0x62);
-    AcpiDisableGpe (NULL, 0x62);
+    Status = AcpiSetGpe (NULL, 0, ACPI_GPE_ENABLE);
+    AE_CHECK_OK (AcpiSetGpe, Status);
+
+
+    Status = AcpiInstallGpeHandler (NULL, 1, ACPI_GPE_EDGE_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+    Status = AcpiEnableGpe (NULL, 1);
+    AE_CHECK_OK (AcpiEnableGpe, Status);
+
+
+    Status = AcpiInstallGpeHandler (NULL, 2, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+    Status = AcpiEnableGpe (NULL, 2);
+    AE_CHECK_OK (AcpiEnableGpe, Status);
+
+
+    Status = AcpiInstallGpeHandler (NULL, 3, ACPI_GPE_EDGE_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+    Status = AcpiInstallGpeHandler (NULL, 4, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+    Status = AcpiInstallGpeHandler (NULL, 5, ACPI_GPE_EDGE_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+
+    Status = AcpiInstallGpeHandler (NULL, 0x19, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+    Status = AcpiEnableGpe (NULL, 0x19);
+    AE_CHECK_OK (AcpiEnableGpe, Status);
+
+
+    Status = AcpiInstallGpeHandler (NULL, 0x62, ACPI_GPE_LEVEL_TRIGGERED, AeGpeHandler, NULL);
+    AE_CHECK_OK (AcpiInstallGpeHandler, Status);
+
+    Status = AcpiEnableGpe (NULL, 0x62);
+    AE_CHECK_OK (AcpiEnableGpe, Status);
+
+    Status = AcpiDisableGpe (NULL, 0x62);
+    AE_CHECK_OK (AcpiDisableGpe, Status);
 
     AfInstallGpeBlock ();
 
@@ -584,41 +669,23 @@ AeMiscellaneousTests (
     /* Test global lock */
 
     Status = AcpiAcquireGlobalLock (0xFFFF, &LockHandle1);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not get GlobalLock, %X\n", Status);
-    }
+    AE_CHECK_OK (AcpiAcquireGlobalLock, Status);
 
     Status = AcpiAcquireGlobalLock (0x5, &LockHandle2);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not get GlobalLock, %X\n", Status);
-    }
+    AE_CHECK_OK (AcpiAcquireGlobalLock, Status);
 
     Status = AcpiReleaseGlobalLock (LockHandle1);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not release GlobalLock, %X\n", Status);
-    }
+    AE_CHECK_OK (AcpiReleaseGlobalLock, Status);
 
     Status = AcpiReleaseGlobalLock (LockHandle2);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not release GlobalLock, %X\n", Status);
-    }
+    AE_CHECK_OK (AcpiReleaseGlobalLock, Status);
 
     /* Get Devices */
 
     Status = AcpiGetDevices (NULL, AeGetDevices, NULL, NULL);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not AcpiGetDevices, %X\n", Status);
-    }
+    AE_CHECK_OK (AcpiGetDevices, Status);
 
     Status = AcpiGetStatistics (&Stats);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not AcpiGetStatistics, %X\n", Status);
-    }
+    AE_CHECK_OK (AcpiGetStatistics, Status);
 }
 
diff --git a/tools/acpiexec/aehandlers.c b/tools/acpiexec/aehandlers.c
index d4749c9afc2..1f9b1f6ec12 100644
--- a/tools/acpiexec/aehandlers.c
+++ b/tools/acpiexec/aehandlers.c
@@ -120,19 +120,19 @@
 
 /* Local prototypes */
 
-void
+static void
 AeNotifyHandler (
     ACPI_HANDLE             Device,
     UINT32                  Value,
     void                    *Context);
 
-void
+static void
 AeDeviceNotifyHandler (
     ACPI_HANDLE             Device,
     UINT32                  Value,
     void                    *Context);
 
-ACPI_STATUS
+static ACPI_STATUS
 AeExceptionHandler (
     ACPI_STATUS             AmlStatus,
     ACPI_NAME               Name,
@@ -140,31 +140,31 @@ AeExceptionHandler (
     UINT32                  AmlOffset,
     void                    *Context);
 
-ACPI_STATUS
+static ACPI_STATUS
 AeTableHandler (
     UINT32                  Event,
     void                    *Table,
     void                    *Context);
 
-ACPI_STATUS
+static ACPI_STATUS
 AeRegionInit (
     ACPI_HANDLE             RegionHandle,
     UINT32                  Function,
     void                    *HandlerContext,
     void                    **RegionContext);
 
-void
+static void
 AeAttachedDataHandler (
     ACPI_HANDLE             Object,
     void                    *Data);
 
-UINT32
+static UINT32
 AeInterfaceHandler (
     ACPI_STRING             InterfaceName,
     UINT32                  Supported);
 
-UINT32                      SigintCount = 0;
-AE_DEBUG_REGIONS            AeRegions;
+static UINT32               SigintCount = 0;
+static AE_DEBUG_REGIONS     AeRegions;
 
 
 /******************************************************************************
@@ -179,7 +179,7 @@ AE_DEBUG_REGIONS            AeRegions;
  *
  *****************************************************************************/
 
-void __cdecl
+void ACPI_SYSTEM_XFACE
 AeCtrlCHandler (
     int                     Sig)
 {
@@ -218,7 +218,7 @@ AeCtrlCHandler (
  *
  *****************************************************************************/
 
-void
+static void
 AeNotifyHandler (
     ACPI_HANDLE                 Device,
     UINT32                      Value,
@@ -268,7 +268,6 @@ AeNotifyHandler (
         (void) AcpiEvaluateObject (Device, "_NOT", NULL, NULL);
         break;
     }
-
 }
 
 
@@ -286,7 +285,7 @@ AeNotifyHandler (
  *
  *****************************************************************************/
 
-void
+static void
 AeDeviceNotifyHandler (
     ACPI_HANDLE                 Device,
     UINT32                      Value,
@@ -317,7 +316,7 @@ AeDeviceNotifyHandler (
  *
  *****************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 AeExceptionHandler (
     ACPI_STATUS             AmlStatus,
     ACPI_NAME               Name,
@@ -361,7 +360,7 @@ AeExceptionHandler (
     Arg[1].String.Length = ACPI_STRLEN (Exception);
 
     Arg[2].Type = ACPI_TYPE_INTEGER;
-    Arg[2].Integer.Value = ACPI_TO_INTEGER (AcpiOsGetThreadId());
+    Arg[2].Integer.Value = AcpiOsGetThreadId();
 
     /* Setup return buffer */
 
@@ -416,14 +415,14 @@ AeExceptionHandler (
  *
  *****************************************************************************/
 
-char                *TableEvents[] =
+static char                *TableEvents[] =
 {
     "LOAD",
     "UNLOAD",
     "UNKNOWN"
 };
 
-ACPI_STATUS
+static ACPI_STATUS
 AeTableHandler (
     UINT32                  Event,
     void                    *Table,
@@ -469,7 +468,7 @@ AeGpeHandler (
  *
  *****************************************************************************/
 
-void
+static void
 AeAttachedDataHandler (
     ACPI_HANDLE             Object,
     void                    *Data)
@@ -490,7 +489,7 @@ AeAttachedDataHandler (
  *
  *****************************************************************************/
 
-UINT32
+static UINT32
 AeInterfaceHandler (
     ACPI_STRING             InterfaceName,
     UINT32                  Supported)
@@ -518,7 +517,7 @@ AeInterfaceHandler (
  *
  *****************************************************************************/
 
-ACPI_STATUS
+static ACPI_STATUS
 AeRegionInit (
     ACPI_HANDLE                 RegionHandle,
     UINT32                      Function,
@@ -530,7 +529,7 @@ AeRegionInit (
      */
     *RegionContext = RegionHandle;
 
-    return AE_OK;
+    return (AE_OK);
 }
 
 
@@ -544,10 +543,13 @@ AeRegionInit (
  *
  * DESCRIPTION: Install handlers for the AcpiExec utility.
  *
+ * Notes:       Don't install handler for PCI_Config, we want to use the
+ *              default handler to exercise that code.
+ *
  *****************************************************************************/
 
-ACPI_ADR_SPACE_TYPE         SpaceId[] = {0, 1, 2, 3, 4, 5, 6, 7, 0x80};
-#define AEXEC_NUM_REGIONS   9
+static ACPI_ADR_SPACE_TYPE  SpaceIdList[] = {0, 1, 3, 4, 5, 6, 7, 0x80};
+#define AEXEC_NUM_REGIONS   8
 
 ACPI_STATUS
 AeInstallHandlers (void)
@@ -620,8 +622,12 @@ AeInstallHandlers (void)
 
         Status = AcpiInstallNotifyHandler (Handle, ACPI_ALL_NOTIFY,
                                             AeNotifyHandler, NULL);
+        AE_CHECK_OK (AcpiInstallNotifyHandler, Status);
+
         Status = AcpiRemoveNotifyHandler (Handle, ACPI_ALL_NOTIFY,
                                             AeNotifyHandler);
+        AE_CHECK_OK (AcpiRemoveNotifyHandler, Status);
+
         Status = AcpiInstallNotifyHandler (Handle, ACPI_ALL_NOTIFY,
                                             AeNotifyHandler, NULL);
         if (ACPI_FAILURE (Status))
@@ -631,8 +637,13 @@ AeInstallHandlers (void)
         }
 
         Status = AcpiAttachData (Handle, AeAttachedDataHandler, Handle);
+        AE_CHECK_OK (AcpiAttachData, Status);
+
         Status = AcpiDetachData (Handle, AeAttachedDataHandler);
+        AE_CHECK_OK (AcpiDetachData, Status);
+
         Status = AcpiAttachData (Handle, AeAttachedDataHandler, Handle);
+        AE_CHECK_OK (AcpiAttachData, Status);
     }
     else
     {
@@ -643,19 +654,21 @@ AeInstallHandlers (void)
 
     for (i = 0; i < AEXEC_NUM_REGIONS; i++)
     {
-        Status = AcpiRemoveAddressSpaceHandler (AcpiGbl_RootNode,
-                        SpaceId[i], AeRegionHandler);
+        /* Remove any existing handler */
+
+        (void) AcpiRemoveAddressSpaceHandler (AcpiGbl_RootNode,
+                    SpaceIdList[i], AeRegionHandler);
 
         /* Install handler at the root object.
          * TBD: all default handlers should be installed here!
          */
         Status = AcpiInstallAddressSpaceHandler (AcpiGbl_RootNode,
-                        SpaceId[i], AeRegionHandler, AeRegionInit, NULL);
+                        SpaceIdList[i], AeRegionHandler, AeRegionInit, NULL);
         if (ACPI_FAILURE (Status))
         {
             ACPI_EXCEPTION ((AE_INFO, Status,
                 "Could not install an OpRegion handler for %s space(%u)",
-                AcpiUtGetRegionName((UINT8) SpaceId[i]), SpaceId[i]));
+                AcpiUtGetRegionName((UINT8) SpaceIdList[i]), SpaceIdList[i]));
             return (Status);
         }
     }
@@ -667,7 +680,7 @@ AeInstallHandlers (void)
     AeRegions.NumberOfRegions = 0;
     AeRegions.RegionList = NULL;
 
-    return Status;
+    return (Status);
 }
 
 
@@ -714,7 +727,7 @@ AeRegionHandler (
      */
     if (RegionObject->Region.Type != ACPI_TYPE_REGION)
     {
-        return AE_OK;
+        return (AE_OK);
     }
 
     /*
@@ -756,10 +769,12 @@ AeRegionHandler (
         {
         case ACPI_READ:
             Status = AcpiHwReadPort (Address, (UINT32 *) Value, BitWidth);
+            AE_CHECK_OK (AcpiHwReadPort, Status);
             break;
 
         case ACPI_WRITE:
             Status = AcpiHwWritePort (Address, (UINT32) *Value, BitWidth);
+            AE_CHECK_OK (AcpiHwWritePort, Status);
             break;
 
         default:
@@ -903,14 +918,14 @@ AeRegionHandler (
         RegionElement = AcpiOsAllocate (sizeof (AE_REGION));
         if (!RegionElement)
         {
-            return AE_NO_MEMORY;
+            return (AE_NO_MEMORY);
         }
 
         RegionElement->Buffer = AcpiOsAllocate (Length);
         if (!RegionElement->Buffer)
         {
             AcpiOsFree (RegionElement);
-            return AE_NO_MEMORY;
+            return (AE_NO_MEMORY);
         }
 
         /* Initialize the region with the default fill value */
@@ -963,7 +978,7 @@ AeRegionHandler (
             ByteWidth, (UINT32)(RegionElement->Address),
             RegionElement->Length));
 
-        return AE_AML_REGION_LIMIT;
+        return (AE_AML_REGION_LIMIT);
     }
 
     /*
@@ -994,9 +1009,10 @@ DoFunction:
         break;
 
     default:
-        return AE_BAD_PARAMETER;
+        return (AE_BAD_PARAMETER);
     }
-    return AE_OK;
+
+    return (AE_OK);
 }
 
 
diff --git a/tools/acpiexec/aemain.c b/tools/acpiexec/aemain.c
index 050ba281025..5773a6917e0 100644
--- a/tools/acpiexec/aemain.c
+++ b/tools/acpiexec/aemain.c
@@ -122,17 +122,18 @@
 #define _COMPONENT          PARSER
         ACPI_MODULE_NAME    ("aemain")
 
-UINT8           AcpiGbl_BatchMode = 0;
-UINT8           AcpiGbl_RegionFillValue = 0;
-BOOLEAN         AcpiGbl_IgnoreErrors = FALSE;
-BOOLEAN         AcpiGbl_DbOpt_NoRegionSupport = FALSE;
-BOOLEAN         AcpiGbl_DebugTimeout = FALSE;
-char            BatchBuffer[128];
-AE_TABLE_DESC   *AeTableListHead = NULL;
+
+UINT8                   AcpiGbl_RegionFillValue = 0;
+BOOLEAN                 AcpiGbl_IgnoreErrors = FALSE;
+BOOLEAN                 AcpiGbl_DbOpt_NoRegionSupport = FALSE;
+BOOLEAN                 AcpiGbl_DebugTimeout = FALSE;
+
+static UINT8            AcpiGbl_BatchMode = 0;
+static char             BatchBuffer[128];
+static AE_TABLE_DESC    *AeTableListHead = NULL;
 
 #define ASL_MAX_FILES   256
-char                    *FileList[ASL_MAX_FILES];
-int                     FileCount;
+static char             *FileList[ASL_MAX_FILES];
 
 
 #define AE_SUPPORTED_OPTIONS    "?b:d:e:f:gm^ovx:"
@@ -203,6 +204,7 @@ AcpiDbRunBatchMode (
     char                    *Cmd = Ptr;
     UINT8                   Run = 0;
 
+
     AcpiGbl_MethodExecuting = FALSE;
     AcpiGbl_StepToNextCall = FALSE;
 
@@ -360,6 +362,7 @@ AsDoWildcard (
 #ifdef WIN32
     void                    *DirInfo;
     char                    *Filename;
+    int                     FileCount;
 
 
     FileCount = 0;
@@ -441,7 +444,7 @@ main (
     ACPI_TABLE_HEADER       *Table = NULL;
     UINT32                  TableCount;
     AE_TABLE_DESC           *TableDesc;
-    char                    **FileList;
+    char                    **WildcardList;
     char                    *Filename;
     char                    *Directory;
     char                    *FullPathname;
@@ -459,7 +462,7 @@ main (
     if (argc < 2)
     {
         usage ();
-        return 0;
+        return (0);
     }
 
     signal (SIGINT, AeCtrlCHandler);
@@ -471,7 +474,8 @@ main (
 
     /* Init ACPI and start debugger thread */
 
-    AcpiInitializeSubsystem ();
+    Status = AcpiInitializeSubsystem ();
+    AE_CHECK_OK (AcpiInitializeSubsystem, Status);
 
     /* Get the command line options */
 
@@ -482,7 +486,7 @@ main (
         {
             printf ("**** The length of command line (%u) exceeded maximum (127)\n",
                 (UINT32) strlen (AcpiGbl_Optarg));
-            return -1;
+            return (-1);
         }
         AcpiGbl_BatchMode = 1;
         strcpy (BatchBuffer, AcpiGbl_Optarg);
@@ -586,7 +590,7 @@ main (
     case 'h':
     default:
         usage();
-        return -1;
+        return (-1);
     }
 
 
@@ -617,21 +621,21 @@ main (
 
             /* Expand wildcards (Windows only) */
 
-            FileList = AsDoWildcard (Directory, Filename);
-            if (!FileList)
+            WildcardList = AsDoWildcard (Directory, Filename);
+            if (!WildcardList)
             {
-                return -1;
+                return (-1);
             }
 
-            while (*FileList)
+            while (*WildcardList)
             {
                 FullPathname = AcpiOsAllocate (
-                    strlen (Directory) + strlen (*FileList) + 1);
+                    strlen (Directory) + strlen (*WildcardList) + 1);
 
                 /* Construct a full path to the file */
 
                 strcpy (FullPathname, Directory);
-                strcat (FullPathname, *FileList);
+                strcat (FullPathname, *WildcardList);
 
                 /* Get one table */
 
@@ -644,9 +648,9 @@ main (
                 }
 
                 AcpiOsFree (FullPathname);
-                AcpiOsFree (*FileList);
-                *FileList = NULL;
-                FileList++;
+                AcpiOsFree (*WildcardList);
+                *WildcardList = NULL;
+                WildcardList++;
 
                 /*
                  * Ignore an FACS or RSDT, we can't use them.
@@ -676,7 +680,7 @@ main (
         Status = AeBuildLocalTables (TableCount, AeTableListHead);
         if (ACPI_FAILURE (Status))
         {
-            return -1;
+            return (-1);
         }
 
         Status = AeInstallTables ();
@@ -730,6 +734,6 @@ enterloop:
         AcpiDbUserCommands (ACPI_DEBUGGER_COMMAND_PROMPT, NULL);
     }
 
-    return 0;
+    return (0);
 }
 
diff --git a/tools/acpiexec/aetables.c b/tools/acpiexec/aetables.c
index e1f61c6e61a..a2ccdab02ea 100644
--- a/tools/acpiexec/aetables.c
+++ b/tools/acpiexec/aetables.c
@@ -135,7 +135,7 @@ AeLocalGetRootPointer (
 
 /* Default DSDT. This will be replaced with the input DSDT */
 
-unsigned char DsdtCode[] =
+static unsigned char DsdtCode[] =
 {
     0x44,0x53,0x44,0x54,0x24,0x00,0x00,0x00,  /* 00000000    "DSDT$..." */
     0x02,0x6F,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    ".oIntel." */
@@ -144,7 +144,7 @@ unsigned char DsdtCode[] =
     0x04,0x12,0x08,0x20,
 };
 
-unsigned char LocalDsdtCode[] =
+static unsigned char LocalDsdtCode[] =
 {
     0x44,0x53,0x44,0x54,0x24,0x00,0x00,0x00,  /* 00000000    "DSDT$..." */
     0x02,0x2C,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    ".,Intel." */
@@ -155,7 +155,7 @@ unsigned char LocalDsdtCode[] =
 
 /* Several example SSDTs */
 
-unsigned char Ssdt1Code[] = /* Has method _T98 */
+static unsigned char Ssdt1Code[] = /* Has method _T98 */
 {
     0x53,0x53,0x44,0x54,0x30,0x00,0x00,0x00,  /* 00000000    "SSDT0..." */
     0x01,0xB8,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    "..Intel." */
@@ -165,7 +165,7 @@ unsigned char Ssdt1Code[] = /* Has method _T98 */
     0x39,0x38,0x00,0x70,0x0A,0x04,0x60,0xA4,  /* 00000028    "98.p..`." */
 };
 
-unsigned char Ssdt2Code[] = /* Has method _T99 */
+static unsigned char Ssdt2Code[] = /* Has method _T99 */
 {
     0x53,0x53,0x44,0x54,0x30,0x00,0x00,0x00,  /* 00000000    "SSDT0..." */
     0x01,0xB7,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    "..Intel." */
@@ -175,7 +175,7 @@ unsigned char Ssdt2Code[] = /* Has method _T99 */
     0x39,0x39,0x00,0x70,0x0A,0x04,0x60,0xA4,  /* 00000028    "99.p..`." */
 };
 
-unsigned char Ssdt3Code[] = /* Has method _T97 */
+unsigned char Ssdt3Code[] =     /* Has method _T97 */
 {
     0x54,0x53,0x44,0x54,0x30,0x00,0x00,0x00,  /* 00000000    "TSDT0..." */
     0x01,0xB8,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    "..Intel." */
@@ -187,7 +187,7 @@ unsigned char Ssdt3Code[] = /* Has method _T97 */
 
 /* Example OEM table */
 
-unsigned char Oem1Code[] =
+static unsigned char Oem1Code[] =
 {
     0x4F,0x45,0x4D,0x31,0x38,0x00,0x00,0x00,  /* 00000000    "OEM18..." */
     0x01,0x4B,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    ".KIntel." */
@@ -200,7 +200,7 @@ unsigned char Oem1Code[] =
 
 /* ASL source for this table is at the end of this file */
 
-unsigned char OemxCode[] =
+static unsigned char OemxCode[] =
 {
     0x4F,0x45,0x4D,0x58,0xB0,0x00,0x00,0x00,  /* 00000000    "OEMX...." */
     0x02,0x54,0x4D,0x79,0x4F,0x45,0x4D,0x00,  /* 00000008    ".TMyOEM." */
@@ -241,7 +241,7 @@ unsigned char OemxCode[] =
  *
  * Compiled byte code below.
  */
-unsigned char MethodCode[] =
+static unsigned char MethodCode[] =
 {
     0x44,0x53,0x44,0x54,0x53,0x00,0x00,0x00,  /* 00000000    "DSDTS..." */
     0x02,0xF9,0x49,0x6E,0x74,0x65,0x6C,0x00,  /* 00000008    "..Intel." */
@@ -262,19 +262,19 @@ unsigned char MethodCode[] =
  * even though the underlying OSD HW access functions don't do
  * anything.
  */
-ACPI_TABLE_HEADER           *DsdtToInstallOverride;
-ACPI_TABLE_RSDP             LocalRSDP;
-ACPI_TABLE_FADT             LocalFADT;
-ACPI_TABLE_FACS             LocalFACS;
-ACPI_TABLE_HEADER           LocalTEST;
-ACPI_TABLE_HEADER           LocalBADTABLE;
-ACPI_TABLE_RSDT             *LocalRSDT;
+static ACPI_TABLE_HEADER        *DsdtToInstallOverride;
+static ACPI_TABLE_RSDP          LocalRSDP;
+static ACPI_TABLE_FADT          LocalFADT;
+static ACPI_TABLE_FACS          LocalFACS;
+static ACPI_TABLE_HEADER        LocalTEST;
+static ACPI_TABLE_HEADER        LocalBADTABLE;
+static ACPI_TABLE_RSDT          *LocalRSDT;
 
-#define BASE_RSDT_TABLES    7
-#define BASE_RSDT_SIZE      (sizeof (ACPI_TABLE_RSDT) + ((BASE_RSDT_TABLES -1) * sizeof (UINT32)))
+#define BASE_RSDT_TABLES        7
+#define BASE_RSDT_SIZE          (sizeof (ACPI_TABLE_RSDT) + ((BASE_RSDT_TABLES -1) * sizeof (UINT32)))
 
-#define ACPI_MAX_INIT_TABLES (32)
-static ACPI_TABLE_DESC      Tables[ACPI_MAX_INIT_TABLES];
+#define ACPI_MAX_INIT_TABLES    (32)
+static ACPI_TABLE_DESC          Tables[ACPI_MAX_INIT_TABLES];
 
 
 /******************************************************************************
@@ -357,7 +357,7 @@ AeBuildLocalTables (
     LocalRSDT = AcpiOsAllocate (RsdtSize);
     if (!LocalRSDT)
     {
-        return AE_NO_MEMORY;
+        return (AE_NO_MEMORY);
     }
 
     ACPI_MEMSET (LocalRSDT, 0, RsdtSize);
@@ -398,7 +398,7 @@ AeBuildLocalTables (
             if (DsdtAddress)
             {
                 printf ("Already found a DSDT, only one allowed\n");
-                return AE_ALREADY_EXISTS;
+                return (AE_ALREADY_EXISTS);
             }
 
             /* The incoming user table is a DSDT */
@@ -488,21 +488,25 @@ AeBuildLocalTables (
         /* Miscellaneous FADT fields */
 
         LocalFADT.Gpe0BlockLength = 16;
+        LocalFADT.Gpe0Block = 0x00001234;
+
         LocalFADT.Gpe1BlockLength = 6;
+        LocalFADT.Gpe1Block = 0x00005678;
         LocalFADT.Gpe1Base = 96;
 
         LocalFADT.Pm1EventLength = 4;
-        LocalFADT.Pm1ControlLength = 2;
-        LocalFADT.PmTimerLength  = 4;
-
-        LocalFADT.Gpe0Block = 0x00001234;
-        LocalFADT.Gpe1Block = 0x00005678;
-
         LocalFADT.Pm1aEventBlock = 0x00001aaa;
         LocalFADT.Pm1bEventBlock = 0x00001bbb;
-        LocalFADT.PmTimerBlock = 0xA0;
+
+        LocalFADT.Pm1ControlLength = 2;
         LocalFADT.Pm1aControlBlock = 0xB0;
 
+        LocalFADT.PmTimerLength = 4;
+        LocalFADT.PmTimerBlock = 0xA0;
+
+        LocalFADT.Pm2ControlBlock = 0xC0;
+        LocalFADT.Pm2ControlLength = 1;
+
         /* Setup one example X-64 field */
 
         LocalFADT.XPm1bEventBlock.SpaceId = ACPI_ADR_SPACE_SYSTEM_IO;
@@ -566,9 +570,15 @@ AeInstallTables (
 {
     ACPI_STATUS             Status;
 
+
     Status = AcpiInitializeTables (Tables, ACPI_MAX_INIT_TABLES, TRUE);
+    AE_CHECK_OK (AcpiInitializeTables, Status);
+
     Status = AcpiReallocateRootTable ();
+    AE_CHECK_OK (AcpiReallocateRootTable, Status);
+
     Status = AcpiLoadTables ();
+    AE_CHECK_OK (AcpiLoadTables, Status);
 
     /*
      * Test run-time control method installation. Do it twice to test code
diff --git a/tools/acpisrc/asfile.c b/tools/acpisrc/asfile.c
index dd249410772..c82a98b30cc 100644
--- a/tools/acpisrc/asfile.c
+++ b/tools/acpisrc/asfile.c
@@ -132,7 +132,7 @@ AsDetectLoneLineFeeds (
     char                    *Filename,
     char                    *Buffer);
 
-static inline int
+static ACPI_INLINE int
 AsMaxInt (int a, int b)
 {
     return (a > b ? a : b);
@@ -409,7 +409,8 @@ AsConvertFile (
 
     Gbl_StructDefs = strstr (FileBuffer, "/* acpisrc:StructDefs");
     Gbl_Files++;
-    VERBOSE_PRINT (("Processing %u bytes\n", strlen (FileBuffer)));
+    VERBOSE_PRINT (("Processing %u bytes\n",
+        (unsigned int) strlen (FileBuffer)));
 
     if (ConversionTable->LowerCaseTable)
     {
diff --git a/tools/acpisrc/astable.c b/tools/acpisrc/astable.c
index 058d5a2b545..c850891095a 100644
--- a/tools/acpisrc/astable.c
+++ b/tools/acpisrc/astable.c
@@ -378,6 +378,7 @@ ACPI_TYPED_IDENTIFIER_TABLE           AcpiIdentifiers[] = {
     {"ACPI_PARSE_STATE",                    SRC_TYPE_STRUCT},
     {"ACPI_PARSE_UPWARDS",                  SRC_TYPE_SIMPLE},
     {"ACPI_PARSE_VALUE",                    SRC_TYPE_UNION},
+    {"ACPI_PCI_DEVICE",                     SRC_TYPE_STRUCT},
     {"ACPI_PCI_ID",                         SRC_TYPE_STRUCT},
     {"ACPI_PCI_ROUTING_TABLE",              SRC_TYPE_STRUCT},
     {"ACPI_PHYSICAL_ADDRESS",               SRC_TYPE_SIMPLE},
diff --git a/tools/acpixtract/acpixtract.c b/tools/acpixtract/acpixtract.c
index e3d6b7529ed..543d0bd8ad2 100644
--- a/tools/acpixtract/acpixtract.c
+++ b/tools/acpixtract/acpixtract.c
@@ -130,46 +130,46 @@
 
 /* Local prototypes */
 
-void
+static void
 CheckAscii (
     char                    *Name,
     int                     Count);
 
-void
+static void
 NormalizeSignature (
     char                    *Signature);
 
-unsigned int
+static unsigned int
 GetNextInstance (
     char                    *InputPathname,
     char                    *Signature);
 
-int
+static int
 ExtractTables (
     char                    *InputPathname,
     char                    *Signature,
     unsigned int            MinimumInstances);
 
-size_t
+static size_t
 GetTableHeader (
     FILE                    *InputFile,
     unsigned char           *OutputData);
 
-unsigned int
+static unsigned int
 CountTableInstances (
     char                    *InputPathname,
     char                    *Signature);
 
-int
+static int
 ListTables (
     char                    *InputPathname);
 
-size_t
+static size_t
 ConvertLine (
     char                    *InputLine,
     unsigned char           *OutputData);
 
-void
+static void
 DisplayUsage (
     void);
 
@@ -196,9 +196,9 @@ struct TableInfo
     struct TableInfo        *Next;
 };
 
-struct TableInfo            *ListHead = NULL;
-char                        Filename[16];
-unsigned char               Data[16];
+static struct TableInfo     *ListHead = NULL;
+static char                 Filename[16];
+static unsigned char        Data[16];
 
 
 /******************************************************************************
@@ -209,7 +209,7 @@ unsigned char               Data[16];
  *
  ******************************************************************************/
 
-void
+static void
 DisplayUsage (
     void)
 {
@@ -240,7 +240,7 @@ DisplayUsage (
  *
  ******************************************************************************/
 
-void
+static void
 CheckAscii (
     char                    *Name,
     int                     Count)
@@ -270,7 +270,7 @@ CheckAscii (
  *
  ******************************************************************************/
 
-void
+static void
 NormalizeSignature (
     char                    *Signature)
 {
@@ -295,7 +295,7 @@ NormalizeSignature (
  *
  ******************************************************************************/
 
-size_t
+static size_t
 ConvertLine (
     char                    *InputLine,
     unsigned char           *OutputData)
@@ -353,7 +353,7 @@ ConvertLine (
  *
  ******************************************************************************/
 
-size_t
+static size_t
 GetTableHeader (
     FILE                    *InputFile,
     unsigned char           *OutputData)
@@ -401,7 +401,7 @@ GetTableHeader (
  *
  ******************************************************************************/
 
-unsigned int
+static unsigned int
 CountTableInstances (
     char                    *InputPathname,
     char                    *Signature)
@@ -459,7 +459,7 @@ CountTableInstances (
  *
  ******************************************************************************/
 
-unsigned int
+static unsigned int
 GetNextInstance (
     char                    *InputPathname,
     char                    *Signature)
@@ -520,7 +520,7 @@ GetNextInstance (
  *
  ******************************************************************************/
 
-int
+static int
 ExtractTables (
     char                    *InputPathname,
     char                    *Signature,
@@ -639,8 +639,8 @@ ExtractTables (
                 OutputFile = NULL;
                 State = FIND_HEADER;
 
-                printf ("Acpi table [%4.4s] - % 7d bytes written to %s\n",
-                    ThisSignature, TotalBytesWritten, Filename);
+                printf ("Acpi table [%4.4s] - %u bytes written to %s\n",
+                    ThisSignature, (unsigned int) TotalBytesWritten, Filename);
                 continue;
             }
 
@@ -684,8 +684,8 @@ CleanupAndExit:
         {
             /* Received an EOF while extracting data */
 
-            printf ("Acpi table [%4.4s] - % 7d bytes written to %s\n",
-                ThisSignature, TotalBytesWritten, Filename);
+            printf ("Acpi table [%4.4s] - %u bytes written to %s\n",
+                ThisSignature, (unsigned int) TotalBytesWritten, Filename);
         }
     }
 
@@ -707,7 +707,7 @@ CleanupAndExit:
  *
  ******************************************************************************/
 
-int
+static int
 ListTables (
     char                    *InputPathname)
 {
diff --git a/utilities/utdebug.c b/utilities/utdebug.c
index 0a91716f24c..ad158465e00 100644
--- a/utilities/utdebug.c
+++ b/utilities/utdebug.c
@@ -279,9 +279,8 @@ AcpiDebugPrint (
         if (ACPI_LV_THREADS & AcpiDbgLevel)
         {
             AcpiOsPrintf (
-                "\n**** Context Switch from TID %p to TID %p ****\n\n",
-                ACPI_CAST_PTR (void, AcpiGbl_PrevThreadId),
-                ACPI_CAST_PTR (void, ThreadId));
+                "\n**** Context Switch from TID %u to TID %u ****\n\n",
+                (UINT32) AcpiGbl_PrevThreadId, (UINT32) ThreadId);
         }
 
         AcpiGbl_PrevThreadId = ThreadId;
@@ -295,7 +294,7 @@ AcpiDebugPrint (
 
     if (ACPI_LV_THREADS & AcpiDbgLevel)
     {
-        AcpiOsPrintf ("[%p] ", ACPI_CAST_PTR (void, ThreadId));
+        AcpiOsPrintf ("[%u] ", (UINT32) ThreadId);
     }
 
     AcpiOsPrintf ("[%02ld] %-22.22s: ",
diff --git a/utilities/utmath.c b/utilities/utmath.c
index 54d492f234f..90f3cd58cc1 100644
--- a/utilities/utmath.c
+++ b/utilities/utmath.c
@@ -124,12 +124,32 @@
         ACPI_MODULE_NAME    ("utmath")
 
 /*
- * Support for double-precision integer divide.  This code is included here
- * in order to support kernel environments where the double-precision math
- * library is not available.
+ * Optional support for 64-bit double-precision integer divide. This code
+ * is configurable and is implemented in order to support 32-bit kernel
+ * environments where a 64-bit double-precision math library is not available.
+ *
+ * Support for a more normal 64-bit divide/modulo (with check for a divide-
+ * by-zero) appears after this optional section of code.
  */
-
 #ifndef ACPI_USE_NATIVE_DIVIDE
+
+/* Structures used only for 64-bit divide */
+
+typedef struct uint64_struct
+{
+    UINT32                          Lo;
+    UINT32                          Hi;
+
+} UINT64_STRUCT;
+
+typedef union uint64_overlay
+{
+    UINT64                          Full;
+    UINT64_STRUCT                   Part;
+
+} UINT64_OVERLAY;
+
+
 /*******************************************************************************
  *
  * FUNCTION:    AcpiUtShortDivide
diff --git a/utilities/utmisc.c b/utilities/utmisc.c
index f3e2d180fcd..1867a31fa9a 100644
--- a/utilities/utmisc.c
+++ b/utilities/utmisc.c
@@ -124,12 +124,6 @@
 #define _COMPONENT          ACPI_UTILITIES
         ACPI_MODULE_NAME    ("utmisc")
 
-/*
- * Common suffix for messages
- */
-#define ACPI_COMMON_MSG_SUFFIX \
-    AcpiOsPrintf (" (%8.8X/%s-%u)\n", ACPI_CA_VERSION, ModuleName, LineNumber)
-
 
 /*******************************************************************************
  *
@@ -1337,191 +1331,3 @@ AcpiUtWalkPackageTree (
 }
 
 
-/*******************************************************************************
- *
- * FUNCTION:    AcpiError, AcpiException, AcpiWarning, AcpiInfo
- *
- * PARAMETERS:  ModuleName          - Caller's module name (for error output)
- *              LineNumber          - Caller's line number (for error output)
- *              Format              - Printf format string + additional args
- *
- * RETURN:      None
- *
- * DESCRIPTION: Print message with module/line/version info
- *
- ******************************************************************************/
-
-void  ACPI_INTERNAL_VAR_XFACE
-AcpiError (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *Format,
-    ...)
-{
-    va_list                 args;
-
-
-    AcpiOsPrintf ("ACPI Error: ");
-
-    va_start (args, Format);
-    AcpiOsVprintf (Format, args);
-    ACPI_COMMON_MSG_SUFFIX;
-    va_end (args);
-}
-
-void  ACPI_INTERNAL_VAR_XFACE
-AcpiException (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    ACPI_STATUS             Status,
-    const char              *Format,
-    ...)
-{
-    va_list                 args;
-
-
-    AcpiOsPrintf ("ACPI Exception: %s, ", AcpiFormatException (Status));
-
-    va_start (args, Format);
-    AcpiOsVprintf (Format, args);
-    ACPI_COMMON_MSG_SUFFIX;
-    va_end (args);
-}
-
-void  ACPI_INTERNAL_VAR_XFACE
-AcpiWarning (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *Format,
-    ...)
-{
-    va_list                 args;
-
-
-    AcpiOsPrintf ("ACPI Warning: ");
-
-    va_start (args, Format);
-    AcpiOsVprintf (Format, args);
-    ACPI_COMMON_MSG_SUFFIX;
-    va_end (args);
-}
-
-void  ACPI_INTERNAL_VAR_XFACE
-AcpiInfo (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    const char              *Format,
-    ...)
-{
-    va_list                 args;
-
-
-    AcpiOsPrintf ("ACPI: ");
-
-    va_start (args, Format);
-    AcpiOsVprintf (Format, args);
-    AcpiOsPrintf ("\n");
-    va_end (args);
-}
-
-ACPI_EXPORT_SYMBOL (AcpiError)
-ACPI_EXPORT_SYMBOL (AcpiException)
-ACPI_EXPORT_SYMBOL (AcpiWarning)
-ACPI_EXPORT_SYMBOL (AcpiInfo)
-
-
-/*******************************************************************************
- *
- * FUNCTION:    AcpiUtPredefinedWarning
- *
- * PARAMETERS:  ModuleName      - Caller's module name (for error output)
- *              LineNumber      - Caller's line number (for error output)
- *              Pathname        - Full pathname to the node
- *              NodeFlags       - From Namespace node for the method/object
- *              Format          - Printf format string + additional args
- *
- * RETURN:      None
- *
- * DESCRIPTION: Warnings for the predefined validation module. Messages are
- *              only emitted the first time a problem with a particular
- *              method/object is detected. This prevents a flood of error
- *              messages for methods that are repeatedly evaluated.
- *
- ******************************************************************************/
-
-void  ACPI_INTERNAL_VAR_XFACE
-AcpiUtPredefinedWarning (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    char                    *Pathname,
-    UINT8                   NodeFlags,
-    const char              *Format,
-    ...)
-{
-    va_list                 args;
-
-
-    /*
-     * Warning messages for this method/object will be disabled after the
-     * first time a validation fails or an object is successfully repaired.
-     */
-    if (NodeFlags & ANOBJ_EVALUATED)
-    {
-        return;
-    }
-
-    AcpiOsPrintf ("ACPI Warning for %s: ", Pathname);
-
-    va_start (args, Format);
-    AcpiOsVprintf (Format, args);
-    ACPI_COMMON_MSG_SUFFIX;
-    va_end (args);
-}
-
-/*******************************************************************************
- *
- * FUNCTION:    AcpiUtPredefinedInfo
- *
- * PARAMETERS:  ModuleName      - Caller's module name (for error output)
- *              LineNumber      - Caller's line number (for error output)
- *              Pathname        - Full pathname to the node
- *              NodeFlags       - From Namespace node for the method/object
- *              Format          - Printf format string + additional args
- *
- * RETURN:      None
- *
- * DESCRIPTION: Info messages for the predefined validation module. Messages
- *              are only emitted the first time a problem with a particular
- *              method/object is detected. This prevents a flood of
- *              messages for methods that are repeatedly evaluated.
- *
- ******************************************************************************/
-
-void  ACPI_INTERNAL_VAR_XFACE
-AcpiUtPredefinedInfo (
-    const char              *ModuleName,
-    UINT32                  LineNumber,
-    char                    *Pathname,
-    UINT8                   NodeFlags,
-    const char              *Format,
-    ...)
-{
-    va_list                 args;
-
-
-    /*
-     * Warning messages for this method/object will be disabled after the
-     * first time a validation fails or an object is successfully repaired.
-     */
-    if (NodeFlags & ANOBJ_EVALUATED)
-    {
-        return;
-    }
-
-    AcpiOsPrintf ("ACPI Info for %s: ", Pathname);
-
-    va_start (args, Format);
-    AcpiOsVprintf (Format, args);
-    ACPI_COMMON_MSG_SUFFIX;
-    va_end (args);
-}
diff --git a/utilities/utmutex.c b/utilities/utmutex.c
index f4d717516a3..92a95e15af7 100644
--- a/utilities/utmutex.c
+++ b/utilities/utmutex.c
@@ -348,16 +348,16 @@ AcpiUtAcquireMutex (
                 if (i == MutexId)
                 {
                     ACPI_ERROR ((AE_INFO,
-                        "Mutex [%s] already acquired by this thread [%p]",
+                        "Mutex [%s] already acquired by this thread [%u]",
                         AcpiUtGetMutexName (MutexId),
-                        ACPI_CAST_PTR (void, ThisThreadId)));
+                        (UINT32) ThisThreadId));
 
                     return (AE_ALREADY_ACQUIRED);
                 }
 
                 ACPI_ERROR ((AE_INFO,
-                    "Invalid acquire order: Thread %p owns [%s], wants [%s]",
-                    ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (i),
+                    "Invalid acquire order: Thread %u owns [%s], wants [%s]",
+                    (UINT32) ThisThreadId, AcpiUtGetMutexName (i),
                     AcpiUtGetMutexName (MutexId)));
 
                 return (AE_ACQUIRE_DEADLOCK);
@@ -367,15 +367,15 @@ AcpiUtAcquireMutex (
 #endif
 
     ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX,
-        "Thread %p attempting to acquire Mutex [%s]\n",
-        ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (MutexId)));
+        "Thread %u attempting to acquire Mutex [%s]\n",
+        (UINT32) ThisThreadId, AcpiUtGetMutexName (MutexId)));
 
     Status = AcpiOsAcquireMutex (AcpiGbl_MutexInfo[MutexId].Mutex,
                 ACPI_WAIT_FOREVER);
     if (ACPI_SUCCESS (Status))
     {
-        ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %p acquired Mutex [%s]\n",
-            ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (MutexId)));
+        ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %u acquired Mutex [%s]\n",
+            (UINT32) ThisThreadId, AcpiUtGetMutexName (MutexId)));
 
         AcpiGbl_MutexInfo[MutexId].UseCount++;
         AcpiGbl_MutexInfo[MutexId].ThreadId = ThisThreadId;
@@ -383,8 +383,8 @@ AcpiUtAcquireMutex (
     else
     {
         ACPI_EXCEPTION ((AE_INFO, Status,
-            "Thread %p could not acquire Mutex [0x%X]",
-            ACPI_CAST_PTR (void, ThisThreadId), MutexId));
+            "Thread %u could not acquire Mutex [0x%X]",
+            (UINT32) ThisThreadId, MutexId));
     }
 
     return (Status);
@@ -414,8 +414,8 @@ AcpiUtReleaseMutex (
 
 
     ThisThreadId = AcpiOsGetThreadId ();
-    ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %p releasing Mutex [%s]\n",
-        ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (MutexId)));
+    ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %u releasing Mutex [%s]\n",
+        (UINT32) ThisThreadId, AcpiUtGetMutexName (MutexId)));
 
     if (MutexId > ACPI_MAX_MUTEX)
     {
diff --git a/utilities/utxferror.c b/utilities/utxferror.c
new file mode 100644
index 00000000000..b397a40c2a7
--- /dev/null
+++ b/utilities/utxferror.c
@@ -0,0 +1,550 @@
+/*******************************************************************************
+ *
+ * Module Name: utxferror - Various error/warning output functions
+ *
+ ******************************************************************************/
+
+/******************************************************************************
+ *
+ * 1. Copyright Notice
+ *
+ * Some or all of this work - Copyright (c) 1999 - 2010, Intel Corp.
+ * All rights reserved.
+ *
+ * 2. License
+ *
+ * 2.1. This is your license from Intel Corp. under its intellectual property
+ * rights.  You may have additional license terms from the party that provided
+ * you this software, covering your right to use that party's intellectual
+ * property rights.
+ *
+ * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
+ * copy of the source code appearing in this file ("Covered Code") an
+ * irrevocable, perpetual, worldwide license under Intel's copyrights in the
+ * base code distributed originally by Intel ("Original Intel Code") to copy,
+ * make derivatives, distribute, use and display any portion of the Covered
+ * Code in any form, with the right to sublicense such rights; and
+ *
+ * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
+ * license (with the right to sublicense), under only those claims of Intel
+ * patents that are infringed by the Original Intel Code, to make, use, sell,
+ * offer to sell, and import the Covered Code and derivative works thereof
+ * solely to the minimum extent necessary to exercise the above copyright
+ * license, and in no event shall the patent license extend to any additions
+ * to or modifications of the Original Intel Code.  No other license or right
+ * is granted directly or by implication, estoppel or otherwise;
+ *
+ * The above copyright and patent license is granted only if the following
+ * conditions are met:
+ *
+ * 3. Conditions
+ *
+ * 3.1. Redistribution of Source with Rights to Further Distribute Source.
+ * Redistribution of source code of any substantial portion of the Covered
+ * Code or modification with rights to further distribute source must include
+ * the above Copyright Notice, the above License, this list of Conditions,
+ * and the following Disclaimer and Export Compliance provision.  In addition,
+ * Licensee must cause all Covered Code to which Licensee contributes to
+ * contain a file documenting the changes Licensee made to create that Covered
+ * Code and the date of any change.  Licensee must include in that file the
+ * documentation of any changes made by any predecessor Licensee.  Licensee
+ * must include a prominent statement that the modification is derived,
+ * directly or indirectly, from Original Intel Code.
+ *
+ * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
+ * Redistribution of source code of any substantial portion of the Covered
+ * Code or modification without rights to further distribute source must
+ * include the following Disclaimer and Export Compliance provision in the
+ * documentation and/or other materials provided with distribution.  In
+ * addition, Licensee may not authorize further sublicense of source of any
+ * portion of the Covered Code, and must include terms to the effect that the
+ * license from Licensee to its licensee is limited to the intellectual
+ * property embodied in the software Licensee provides to its licensee, and
+ * not to intellectual property embodied in modifications its licensee may
+ * make.
+ *
+ * 3.3. Redistribution of Executable. Redistribution in executable form of any
+ * substantial portion of the Covered Code or modification must reproduce the
+ * above Copyright Notice, and the following Disclaimer and Export Compliance
+ * provision in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3.4. Intel retains all right, title, and interest in and to the Original
+ * Intel Code.
+ *
+ * 3.5. Neither the name Intel nor any other trademark owned or controlled by
+ * Intel shall be used in advertising or otherwise to promote the sale, use or
+ * other dealings in products derived from or relating to the Covered Code
+ * without prior written authorization from Intel.
+ *
+ * 4. Disclaimer and Export Compliance
+ *
+ * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
+ * HERE.  ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
+ * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT,  ASSISTANCE,
+ * INSTALLATION, TRAINING OR OTHER SERVICES.  INTEL WILL NOT PROVIDE ANY
+ * UPDATES, ENHANCEMENTS OR EXTENSIONS.  INTEL SPECIFICALLY DISCLAIMS ANY
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
+ * PARTICULAR PURPOSE.
+ *
+ * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
+ * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
+ * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
+ * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
+ * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
+ * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.  THESE LIMITATIONS
+ * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
+ * LIMITED REMEDY.
+ *
+ * 4.3. Licensee shall not export, either directly or indirectly, any of this
+ * software or system incorporating such software without first obtaining any
+ * required license or other approval from the U. S. Department of Commerce or
+ * any other agency or department of the United States Government.  In the
+ * event Licensee exports any such software from the United States or
+ * re-exports any such software from a foreign destination, Licensee shall
+ * ensure that the distribution and export/re-export of the software is in
+ * compliance with all laws, regulations, orders, or other restrictions of the
+ * U.S. Export Administration Regulations. Licensee agrees that neither it nor
+ * any of its subsidiaries will export/re-export any technical data, process,
+ * software, or service, directly or indirectly, to any country for which the
+ * United States government or any agency thereof requires an export license,
+ * other governmental approval, or letter of assurance, without first obtaining
+ * such license, approval or letter.
+ *
+ *****************************************************************************/
+
+#define __UTXFERROR_C__
+
+#include "acpi.h"
+#include "accommon.h"
+#include "acnamesp.h"
+
+
+#define _COMPONENT          ACPI_UTILITIES
+        ACPI_MODULE_NAME    ("utxferror")
+
+/*
+ * This module is used for the in-kernel ACPICA as well as the ACPICA
+ * tools/applications.
+ *
+ * For the iASL compiler case, the output is redirected to stderr so that
+ * any of the various ACPI errors and warnings do not appear in the output
+ * files, for either the compiler or disassembler portions of the tool.
+ */
+#ifdef ACPI_ASL_COMPILER
+#include 
+
+extern FILE                 *AcpiGbl_OutputFile;
+
+#define ACPI_MSG_REDIRECT_BEGIN \
+    FILE                    *OutputFile = AcpiGbl_OutputFile; \
+    AcpiOsRedirectOutput (stderr);
+
+#define ACPI_MSG_REDIRECT_END \
+    AcpiOsRedirectOutput (OutputFile);
+
+#else
+/*
+ * non-iASL case - no redirection, nothing to do
+ */
+#define ACPI_MSG_REDIRECT_BEGIN
+#define ACPI_MSG_REDIRECT_END
+#endif
+
+/*
+ * Common message prefixes
+ */
+#define ACPI_MSG_ERROR          "ACPI Error: "
+#define ACPI_MSG_EXCEPTION      "ACPI Exception: "
+#define ACPI_MSG_WARNING        "ACPI Warning: "
+#define ACPI_MSG_INFO           "ACPI: "
+
+/*
+ * Common message suffix
+ */
+#define ACPI_MSG_SUFFIX \
+    AcpiOsPrintf (" (%8.8X/%s-%u)\n", ACPI_CA_VERSION, ModuleName, LineNumber)
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiError
+ *
+ * PARAMETERS:  ModuleName          - Caller's module name (for error output)
+ *              LineNumber          - Caller's line number (for error output)
+ *              Format              - Printf format string + additional args
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Print "ACPI Error" message with module/line/version info
+ *
+ ******************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiError (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *Format,
+    ...)
+{
+    va_list                 ArgList;
+
+
+    ACPI_MSG_REDIRECT_BEGIN;
+    AcpiOsPrintf (ACPI_MSG_ERROR);
+
+    va_start (ArgList, Format);
+    AcpiOsVprintf (Format, ArgList);
+    ACPI_MSG_SUFFIX;
+    va_end (ArgList);
+
+    ACPI_MSG_REDIRECT_END;
+}
+
+ACPI_EXPORT_SYMBOL (AcpiError)
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiException
+ *
+ * PARAMETERS:  ModuleName          - Caller's module name (for error output)
+ *              LineNumber          - Caller's line number (for error output)
+ *              Status              - Status to be formatted
+ *              Format              - Printf format string + additional args
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Print "ACPI Exception" message with module/line/version info
+ *              and decoded ACPI_STATUS.
+ *
+ ******************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiException (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    ACPI_STATUS             Status,
+    const char              *Format,
+    ...)
+{
+    va_list                 ArgList;
+
+
+    ACPI_MSG_REDIRECT_BEGIN;
+    AcpiOsPrintf (ACPI_MSG_EXCEPTION "%s, ", AcpiFormatException (Status));
+
+    va_start (ArgList, Format);
+    AcpiOsVprintf (Format, ArgList);
+    ACPI_MSG_SUFFIX;
+    va_end (ArgList);
+
+    ACPI_MSG_REDIRECT_END;
+}
+
+ACPI_EXPORT_SYMBOL (AcpiException)
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiWarning
+ *
+ * PARAMETERS:  ModuleName          - Caller's module name (for error output)
+ *              LineNumber          - Caller's line number (for error output)
+ *              Format              - Printf format string + additional args
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Print "ACPI Warning" message with module/line/version info
+ *
+ ******************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiWarning (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *Format,
+    ...)
+{
+    va_list                 ArgList;
+
+
+    ACPI_MSG_REDIRECT_BEGIN;
+    AcpiOsPrintf (ACPI_MSG_WARNING);
+
+    va_start (ArgList, Format);
+    AcpiOsVprintf (Format, ArgList);
+    ACPI_MSG_SUFFIX;
+    va_end (ArgList);
+
+    ACPI_MSG_REDIRECT_END;
+}
+
+ACPI_EXPORT_SYMBOL (AcpiWarning)
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiInfo
+ *
+ * PARAMETERS:  ModuleName          - Caller's module name (for error output)
+ *              LineNumber          - Caller's line number (for error output)
+ *              Format              - Printf format string + additional args
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Print generic "ACPI:" information message. There is no
+ *              module/line/version info in order to keep the message simple.
+ *
+ * TBD: ModuleName and LineNumber args are not needed, should be removed.
+ *
+ ******************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiInfo (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *Format,
+    ...)
+{
+    va_list                 ArgList;
+
+
+    ACPI_MSG_REDIRECT_BEGIN;
+    AcpiOsPrintf (ACPI_MSG_INFO);
+
+    va_start (ArgList, Format);
+    AcpiOsVprintf (Format, ArgList);
+    AcpiOsPrintf ("\n");
+    va_end (ArgList);
+
+    ACPI_MSG_REDIRECT_END;
+}
+
+ACPI_EXPORT_SYMBOL (AcpiInfo)
+
+
+/*
+ * The remainder of this module contains internal error functions that may
+ * be configured out.
+ */
+#if !defined (ACPI_NO_ERROR_MESSAGES) && !defined (ACPI_BIN_APP)
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiUtPredefinedWarning
+ *
+ * PARAMETERS:  ModuleName      - Caller's module name (for error output)
+ *              LineNumber      - Caller's line number (for error output)
+ *              Pathname        - Full pathname to the node
+ *              NodeFlags       - From Namespace node for the method/object
+ *              Format          - Printf format string + additional args
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Warnings for the predefined validation module. Messages are
+ *              only emitted the first time a problem with a particular
+ *              method/object is detected. This prevents a flood of error
+ *              messages for methods that are repeatedly evaluated.
+ *
+ ******************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiUtPredefinedWarning (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    char                    *Pathname,
+    UINT8                   NodeFlags,
+    const char              *Format,
+    ...)
+{
+    va_list                 ArgList;
+
+
+    /*
+     * Warning messages for this method/object will be disabled after the
+     * first time a validation fails or an object is successfully repaired.
+     */
+    if (NodeFlags & ANOBJ_EVALUATED)
+    {
+        return;
+    }
+
+    AcpiOsPrintf (ACPI_MSG_WARNING "For %s: ", Pathname);
+
+    va_start (ArgList, Format);
+    AcpiOsVprintf (Format, ArgList);
+    ACPI_MSG_SUFFIX;
+    va_end (ArgList);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiUtPredefinedInfo
+ *
+ * PARAMETERS:  ModuleName      - Caller's module name (for error output)
+ *              LineNumber      - Caller's line number (for error output)
+ *              Pathname        - Full pathname to the node
+ *              NodeFlags       - From Namespace node for the method/object
+ *              Format          - Printf format string + additional args
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Info messages for the predefined validation module. Messages
+ *              are only emitted the first time a problem with a particular
+ *              method/object is detected. This prevents a flood of
+ *              messages for methods that are repeatedly evaluated.
+ *
+ ******************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiUtPredefinedInfo (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    char                    *Pathname,
+    UINT8                   NodeFlags,
+    const char              *Format,
+    ...)
+{
+    va_list                 ArgList;
+
+
+    /*
+     * Warning messages for this method/object will be disabled after the
+     * first time a validation fails or an object is successfully repaired.
+     */
+    if (NodeFlags & ANOBJ_EVALUATED)
+    {
+        return;
+    }
+
+    AcpiOsPrintf (ACPI_MSG_INFO "For %s: ", Pathname);
+
+    va_start (ArgList, Format);
+    AcpiOsVprintf (Format, ArgList);
+    ACPI_MSG_SUFFIX;
+    va_end (ArgList);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiUtNamespaceError
+ *
+ * PARAMETERS:  ModuleName          - Caller's module name (for error output)
+ *              LineNumber          - Caller's line number (for error output)
+ *              InternalName        - Name or path of the namespace node
+ *              LookupStatus        - Exception code from NS lookup
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Print error message with the full pathname for the NS node.
+ *
+ ******************************************************************************/
+
+void
+AcpiUtNamespaceError (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *InternalName,
+    ACPI_STATUS             LookupStatus)
+{
+    ACPI_STATUS             Status;
+    UINT32                  BadName;
+    char                    *Name = NULL;
+
+
+    ACPI_MSG_REDIRECT_BEGIN;
+    AcpiOsPrintf (ACPI_MSG_ERROR);
+
+    if (LookupStatus == AE_BAD_CHARACTER)
+    {
+        /* There is a non-ascii character in the name */
+
+        ACPI_MOVE_32_TO_32 (&BadName, ACPI_CAST_PTR (UINT32, InternalName));
+        AcpiOsPrintf ("[0x%4.4X] (NON-ASCII)", BadName);
+    }
+    else
+    {
+        /* Convert path to external format */
+
+        Status = AcpiNsExternalizeName (ACPI_UINT32_MAX,
+                    InternalName, NULL, &Name);
+
+        /* Print target name */
+
+        if (ACPI_SUCCESS (Status))
+        {
+            AcpiOsPrintf ("[%s]", Name);
+        }
+        else
+        {
+            AcpiOsPrintf ("[COULD NOT EXTERNALIZE NAME]");
+        }
+
+        if (Name)
+        {
+            ACPI_FREE (Name);
+        }
+    }
+
+    AcpiOsPrintf (" Namespace lookup failure, %s",
+        AcpiFormatException (LookupStatus));
+
+    ACPI_MSG_SUFFIX;
+    ACPI_MSG_REDIRECT_END;
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiUtMethodError
+ *
+ * PARAMETERS:  ModuleName          - Caller's module name (for error output)
+ *              LineNumber          - Caller's line number (for error output)
+ *              Message             - Error message to use on failure
+ *              PrefixNode          - Prefix relative to the path
+ *              Path                - Path to the node (optional)
+ *              MethodStatus        - Execution status
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Print error message with the full pathname for the method.
+ *
+ ******************************************************************************/
+
+void
+AcpiUtMethodError (
+    const char              *ModuleName,
+    UINT32                  LineNumber,
+    const char              *Message,
+    ACPI_NAMESPACE_NODE     *PrefixNode,
+    const char              *Path,
+    ACPI_STATUS             MethodStatus)
+{
+    ACPI_STATUS             Status;
+    ACPI_NAMESPACE_NODE     *Node = PrefixNode;
+
+
+    ACPI_MSG_REDIRECT_BEGIN;
+    AcpiOsPrintf (ACPI_MSG_ERROR);
+
+    if (Path)
+    {
+        Status = AcpiNsGetNode (PrefixNode, Path, ACPI_NS_NO_UPSEARCH,
+                    &Node);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("[Could not get node by pathname]");
+        }
+    }
+
+    AcpiNsPrintNodePathname (Node, Message);
+    AcpiOsPrintf (", %s", AcpiFormatException (MethodStatus));
+
+    ACPI_MSG_SUFFIX;
+    ACPI_MSG_REDIRECT_END;
+}
+
+#endif /* ACPI_NO_ERROR_MESSAGES */

From 107cad7449dc0b00ba7cfcb458f8958ccd1c8d38 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 20:53:20 +0000
Subject: [PATCH 0784/1624] * Use !TAILQ_EMPTY() for checking if a tail queue
 is not empty. * Remove assignment without any effect.

MFC after: 2 weeks.
---
 sys/netinet/sctp_cc_functions.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/sys/netinet/sctp_cc_functions.c b/sys/netinet/sctp_cc_functions.c
index 1cba25a2de3..8d2afc619e4 100644
--- a/sys/netinet/sctp_cc_functions.c
+++ b/sys/netinet/sctp_cc_functions.c
@@ -171,7 +171,7 @@ sctp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 			 * So, first of all do we need to have a Early FR
 			 * timer running?
 			 */
-			if (((TAILQ_FIRST(&asoc->sent_queue)) &&
+			if ((!TAILQ_EMPTY(&asoc->sent_queue) &&
 			    (net->ref_count > 1) &&
 			    (net->flight_size < net->cwnd)) ||
 			    (reneged_all)) {
@@ -656,7 +656,6 @@ sctp_hs_cwnd_decrease(struct sctp_tcb *stcb, struct sctp_nets *net)
 	int old_cwnd = net->cwnd;
 
 	cur_val = net->cwnd >> 10;
-	indx = net->last_hs_used;
 	if (cur_val < sctp_cwnd_adjust[0].cwnd) {
 		/* normal mode */
 		net->ssthresh = net->cwnd / 2;
@@ -793,7 +792,7 @@ sctp_hs_cwnd_update_after_sack(struct sctp_tcb *stcb,
 			 * So, first of all do we need to have a Early FR
 			 * timer running?
 			 */
-			if (((TAILQ_FIRST(&asoc->sent_queue)) &&
+			if ((!TAILQ_EMPTY(&asoc->sent_queue) &&
 			    (net->ref_count > 1) &&
 			    (net->flight_size < net->cwnd)) ||
 			    (reneged_all)) {
@@ -1279,7 +1278,7 @@ sctp_htcp_cwnd_update_after_sack(struct sctp_tcb *stcb,
 			 * So, first of all do we need to have a Early FR
 			 * timer running?
 			 */
-			if (((TAILQ_FIRST(&asoc->sent_queue)) &&
+			if ((!TAILQ_EMPTY(&asoc->sent_queue) &&
 			    (net->ref_count > 1) &&
 			    (net->flight_size < net->cwnd)) ||
 			    (reneged_all)) {

From 2f4e9a099b0bcecd685884b53dd7f6bd597c5228 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 15 Sep 2010 20:59:13 +0000
Subject: [PATCH 0785/1624] Make the message that informs about bootcode being
 written to disk less confusing.

Note there is still no information about 'partcode' being written to disk
(gpart bootcode -p  ).

Maybe in the future all the messages printed by gpart(8) on success could be
hidden under -v?

PR:		bin/150239
Reported by:	Roddi 
Submitted by:	arundel
MFC after:	2 weeks
---
 sys/geom/part/g_part.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sys/geom/part/g_part.c b/sys/geom/part/g_part.c
index 5e1847885cd..b08548d5e8d 100644
--- a/sys/geom/part/g_part.c
+++ b/sys/geom/part/g_part.c
@@ -636,7 +636,7 @@ g_part_ctl_bootcode(struct gctl_req *req, struct g_part_parms *gpp)
 	/* Provide feedback if so requested. */
 	if (gpp->gpp_parms & G_PART_PARM_OUTPUT) {
 		sb = sbuf_new_auto();
-		sbuf_printf(sb, "%s has bootcode\n", gp->name);
+		sbuf_printf(sb, "bootcode written to %s\n", gp->name);
 		sbuf_finish(sb);
 		gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1);
 		sbuf_delete(sb);
@@ -1032,7 +1032,7 @@ g_part_ctl_move(struct gctl_req *req, struct g_part_parms *gpp)
 {
 	gctl_error(req, "%d verb 'move'", ENOSYS);
 	return (ENOSYS);
-} 
+}
 
 static int
 g_part_ctl_recover(struct gctl_req *req, struct g_part_parms *gpp)

From b90b577ff39eb7007c5997cca09eaaa5ac0a38c2 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 21:08:57 +0000
Subject: [PATCH 0786/1624] Remove assignment without effect.

MFC after: 2 weeks.
---
 sys/netinet/sctp_sysctl.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/netinet/sctp_sysctl.c b/sys/netinet/sctp_sysctl.c
index f4b9c772be1..50fbafd1af9 100644
--- a/sys/netinet/sctp_sysctl.c
+++ b/sys/netinet/sctp_sysctl.c
@@ -200,8 +200,6 @@ copy_out_local_addresses(struct sctp_inpcb *inp, struct sctp_tcb *stcb, struct s
 		ipv6_addr_legal = 0;
 	}
 
-	error = 0;
-
 	/* neither Mac OS X nor FreeBSD support mulitple routing functions */
 	if ((vrf = sctp_find_vrf(inp->def_vrf_id)) == NULL) {
 		SCTP_INP_RUNLOCK(inp);

From c1769fad32f77c751e66de199863361052932840 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Wed, 15 Sep 2010 21:11:29 +0000
Subject: [PATCH 0787/1624] Add macros for alternate entry points.

---
 sys/sparc64/include/asm.h | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/sys/sparc64/include/asm.h b/sys/sparc64/include/asm.h
index 8182fe77fe7..dea06c547f9 100644
--- a/sys/sparc64/include/asm.h
+++ b/sys/sparc64/include/asm.h
@@ -76,7 +76,7 @@
 	_ALIGN_TEXT
 
 /*
- * Define a function entry point.
+ * Define function entry and alternate entry points.
  *
  * The compiler produces #function for the .type pseudo-op, but the '#'
  * character has special meaning in cpp macros, so we use @function like
@@ -86,12 +86,19 @@
  * value.  Since this is difficult to predict and its expected that
  * assembler code is already optimized, we leave it out.
  */
+
+#define	_ALTENTRY(x) \
+	.globl	CNAME(x) ; \
+	.type	CNAME(x),@function ; \
+CNAME(x):
+
 #define	_ENTRY(x) \
 	_START_ENTRY ; \
 	.globl	CNAME(x) ; \
 	.type	CNAME(x),@function ; \
 CNAME(x):
 
+#define	ALTENTRY(x)	_ALTENTRY(x)
 #define	ENTRY(x)	_ENTRY(x)
 #define	END(x)		.size x, . - x
 

From 2738b715ea3073fae2bd104603722edf8b02718e Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 15 Sep 2010 21:15:00 +0000
Subject: [PATCH 0788/1624] Change message when setting or unsetting attribute
 less confusing. Before:

	ada0 has  set

After:

	 set on ada0

MFC after:	2 weeks
---
 sys/geom/part/g_part.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/sys/geom/part/g_part.c b/sys/geom/part/g_part.c
index b08548d5e8d..cd1979bb4d9 100644
--- a/sys/geom/part/g_part.c
+++ b/sys/geom/part/g_part.c
@@ -1160,9 +1160,10 @@ g_part_ctl_setunset(struct gctl_req *req, struct g_part_parms *gpp,
 	/* Provide feedback if so requested. */
 	if (gpp->gpp_parms & G_PART_PARM_OUTPUT) {
 		sb = sbuf_new_auto();
-		G_PART_FULLNAME(table, entry, sb, gp->name);
-		sbuf_printf(sb, " has %s %sset\n", gpp->gpp_attrib,
+		sbuf_printf(sb, "%s %sset on ", gpp->gpp_attrib,
 		    (set) ? "" : "un");
+		G_PART_FULLNAME(table, entry, sb, gp->name);
+		sbuf_printf(sb, "\n");
 		sbuf_finish(sb);
 		gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1);
 		sbuf_delete(sb);

From 3c8c191baef12a35ae62d914a60a8027c8a1d9e0 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 21:19:54 +0000
Subject: [PATCH 0789/1624] Remove unused variable/assignment.

MFC after: 2 weeks.
---
 sys/netinet/sctp_bsd_addr.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/sys/netinet/sctp_bsd_addr.c b/sys/netinet/sctp_bsd_addr.c
index 4c5a9aa6c83..90fd9a13443 100644
--- a/sys/netinet/sctp_bsd_addr.c
+++ b/sys/netinet/sctp_bsd_addr.c
@@ -298,7 +298,6 @@ sctp_init_vrf_list(int vrfid)
 void
 sctp_addr_change(struct ifaddr *ifa, int cmd)
 {
-	struct sctp_ifa *ifap = NULL;
 	uint32_t ifa_flags = 0;
 
 	/*
@@ -339,7 +338,7 @@ sctp_addr_change(struct ifaddr *ifa, int cmd)
 		return;
 	}
 	if (cmd == RTM_ADD) {
-		ifap = sctp_add_addr_to_vrf(SCTP_DEFAULT_VRFID, (void *)ifa->ifa_ifp,
+		(void)sctp_add_addr_to_vrf(SCTP_DEFAULT_VRFID, (void *)ifa->ifa_ifp,
 		    ifa->ifa_ifp->if_index, ifa->ifa_ifp->if_type,
 		    ifa->ifa_ifp->if_xname,
 		    (void *)ifa, ifa->ifa_addr, ifa_flags, 1);

From b5b293e37ac2802b1e58a4a3c9c888a0b99542d4 Mon Sep 17 00:00:00 2001
From: Pawel Jakub Dawidek 
Date: Wed, 15 Sep 2010 21:37:26 +0000
Subject: [PATCH 0790/1624] GPART_PARAM_INDEX is now G_TYPE_NUMBER.

---
 sbin/geom/class/part/geom_part.c | 12 ++++--------
 1 file changed, 4 insertions(+), 8 deletions(-)

diff --git a/sbin/geom/class/part/geom_part.c b/sbin/geom/class/part/geom_part.c
index 1a0efba7b84..64abf4c774a 100644
--- a/sbin/geom/class/part/geom_part.c
+++ b/sbin/geom/class/part/geom_part.c
@@ -285,12 +285,10 @@ gpart_autofill_resize(struct gctl_req *req)
 	off_t last, size, start, new_size;
 	off_t lba, new_lba;
 	const char *s;
-	char *val;
 	int error, idx;
 
-	s = gctl_get_ascii(req, GPART_PARAM_INDEX);
-	idx = strtol(s, &val, 10);
-	if (idx < 1 || *s == '\0' || *val != '\0')
+	idx = (int)gctl_get_intmax(req, GPART_PARAM_INDEX);
+	if (idx < 1)
 		errx(EXIT_FAILURE, "invalid partition index");
 
 	error = geom_gettree(&mesh);
@@ -775,7 +773,6 @@ gpart_bootcode(struct gctl_req *req, unsigned int fl)
 	struct gclass *classp;
 	struct ggeom *gp;
 	const char *s;
-	char *sp;
 	void *bootcode, *partcode;
 	size_t bootsize, partsize;
 	int error, idx, vtoc8;
@@ -830,9 +827,8 @@ gpart_bootcode(struct gctl_req *req, unsigned int fl)
 	if (gctl_has_param(req, GPART_PARAM_INDEX)) {
 		if (partcode == NULL)
 			errx(EXIT_FAILURE, "-i is only valid with -p");
-		s = gctl_get_ascii(req, GPART_PARAM_INDEX);
-		idx = strtol(s, &sp, 10);
-		if (idx < 1 || *s == '\0' || *sp != '\0')
+		idx = (int)gctl_get_intmax(req, GPART_PARAM_INDEX);
+		if (idx < 1)
 			errx(EXIT_FAILURE, "invalid partition index");
 		error = gctl_delete_param(req, GPART_PARAM_INDEX);
 		if (error)

From 2c554317214ef935cb5dadad638c3a03078e5e87 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Wed, 15 Sep 2010 21:44:31 +0000
Subject: [PATCH 0791/1624] Add a VIS-based block copy function for SPARC64 V
 and later, which additionally takes advantage of the prefetch cache of these
 CPUs. Unlike the uncommitted US-III version, which provide no measurable
 speedup or even resulted in a slight slowdown on certain CPUs models compared
 to using the US-I version with these, the SPARC64 version actually results in
 a slight improvement.

---
 sys/sparc64/include/md_var.h  |   2 +
 sys/sparc64/sparc64/machdep.c |   7 ++-
 sys/sparc64/sparc64/support.S | 115 +++++++++++++++++++++++++++++++++-
 3 files changed, 122 insertions(+), 2 deletions(-)

diff --git a/sys/sparc64/include/md_var.h b/sys/sparc64/include/md_var.h
index 8f064e7961e..8503b431e2e 100644
--- a/sys/sparc64/include/md_var.h
+++ b/sys/sparc64/include/md_var.h
@@ -58,6 +58,8 @@ struct md_utrap *utrap_hold(struct md_utrap *ut);
 
 cpu_block_copy_t spitfire_block_copy;
 cpu_block_zero_t spitfire_block_zero;
+cpu_block_copy_t zeus_block_copy;
+cpu_block_zero_t zeus_block_zero;
 
 extern	cpu_block_copy_t *cpu_block_copy;
 extern	cpu_block_zero_t *cpu_block_zero;
diff --git a/sys/sparc64/sparc64/machdep.c b/sys/sparc64/sparc64/machdep.c
index 193da2f4b67..a4ed381ccf9 100644
--- a/sys/sparc64/sparc64/machdep.c
+++ b/sys/sparc64/sparc64/machdep.c
@@ -495,7 +495,6 @@ sparc64_init(caddr_t mdp, u_long o1, u_long o2, u_long o3, ofw_vec_t *vec)
 	if (cpu_use_vis) {
 		switch (cpu_impl) {
 		case CPU_IMPL_SPARC64:
-		case CPU_IMPL_SPARC64V:
 		case CPU_IMPL_ULTRASPARCI:
 		case CPU_IMPL_ULTRASPARCII:
 		case CPU_IMPL_ULTRASPARCIIi:
@@ -509,6 +508,12 @@ sparc64_init(caddr_t mdp, u_long o1, u_long o2, u_long o3, ofw_vec_t *vec)
 			cpu_block_copy = spitfire_block_copy;
 			cpu_block_zero = spitfire_block_zero;
 			break;
+		case CPU_IMPL_SPARC64V:
+			cpu_block_copy = zeus_block_copy;
+			cpu_block_zero = zeus_block_zero;
+			cpu_block_copy = spitfire_block_copy;
+			cpu_block_zero = spitfire_block_zero;
+			break;
 		}
 	}
 
diff --git a/sys/sparc64/sparc64/support.S b/sys/sparc64/sparc64/support.S
index d4ca5d332e8..70241d833a0 100644
--- a/sys/sparc64/sparc64/support.S
+++ b/sys/sparc64/sparc64/support.S
@@ -661,8 +661,121 @@ ENTRY(spitfire_block_copy)
 END(spitfire_block_copy)
 
 /*
- * void spitfire_block_zero(void *dst, size_t len)
+ * void zeus_block_copy(void *src, void *dst, size_t len)
  */
+ENTRY(zeus_block_copy)
+	prefetch [%o0 + (0 * 64)], 0
+
+	rdpr	%pil, %o3
+	wrpr	%g0, PIL_TICK, %pil
+
+	wr	%g0, ASI_BLK_S, %asi
+	wr	%g0, FPRS_FEF, %fprs
+
+	sub	PCB_REG, TF_SIZEOF, %o4
+	ldx	[%o4 + TF_FPRS], %o5
+	andcc	%o5, FPRS_FEF, %g0
+	bz,a,pt	%xcc, 1f
+	 nop
+	stda	%f0, [PCB_REG + PCB_UFP + (0 * 64)] %asi
+	stda	%f16, [PCB_REG + PCB_UFP + (1 * 64)] %asi
+	stda	%f32, [PCB_REG + PCB_UFP + (2 * 64)] %asi
+	stda	%f48, [PCB_REG + PCB_UFP + (3 * 64)] %asi
+	membar	#Sync
+
+	andn	%o5, FPRS_FEF, %o5
+	stx	%o5, [%o4 + TF_FPRS]
+	ldx	[PCB_REG + PCB_FLAGS], %o4
+	or	%o4, PCB_FEF, %o4
+	stx	%o4, [PCB_REG + PCB_FLAGS]
+
+1:	wrpr	%o3, 0, %pil
+
+	ldd	[%o0 + (0 * 8)], %f0
+	prefetch [%o0 + (1 * 64)], 0
+	ldd	[%o0 + (1 * 8)], %f2
+	prefetch [%o0 + (2 * 64)], 0
+	fmovd	%f0, %f32
+	ldd	[%o0 + (2 * 8)], %f4
+	prefetch [%o0 + (3 * 64)], 0
+	fmovd	%f2, %f34
+	ldd	[%o0 + (3 * 8)], %f6
+	prefetch [%o0 + (4 * 64)], 1
+	fmovd	%f4, %f36
+	ldd	[%o0 + (4 * 8)], %f8
+	prefetch [%o0 + (8 * 64)], 1
+	fmovd	%f6, %f38
+	ldd	[%o0 + (5 * 8)], %f10
+	prefetch [%o0 + (12 * 64)], 1
+	fmovd	%f8, %f40
+	ldd	[%o0 + (6 * 8)], %f12
+	prefetch [%o0 + (16 * 64)], 1
+	fmovd	%f10, %f42
+	ldd	[%o0 + (7 * 8)], %f14
+	ldd	[%o0 + (8 * 8)], %f0
+	sub	%o2, 64, %o2
+	add	%o0, 64, %o0
+	prefetch [%o0 + (19 * 64)], 1
+	ba,pt	%xcc, 2f
+	 prefetch [%o0 + (23 * 64)], 1
+	.align	32
+
+2:	ldd	[%o0 + (1 * 8)], %f2
+	fmovd	%f12, %f44
+	ldd	[%o0 + (2 * 8)], %f4
+	fmovd	%f14, %f46
+	stda	%f32, [%o1] %asi
+	ldd	[%o0 + (3 * 8)], %f6
+	fmovd	%f0, %f32
+	ldd	[%o0 + (4 * 8)], %f8
+	fmovd	%f2, %f34
+	ldd	[%o0 + (5 * 8)], %f10
+	fmovd	%f4, %f36
+	ldd	[%o0 + (6 * 8)], %f12
+	fmovd	%f6, %f38
+	ldd	[%o0 + (7 * 8)], %f14
+	fmovd	%f8, %f40
+	ldd	[%o0 + (8 * 8)], %f0
+	fmovd	%f10, %f42
+	sub	%o2, 64, %o2
+	prefetch [%o0 + (3 * 64)], 0
+	add	%o1, 64, %o1
+	prefetch [%o0 + (24 * 64)], 1
+	add	%o0, 64, %o0
+	cmp	%o2, 64 + 8
+	bgu,pt	%xcc, 2b
+	 prefetch [%o0 + (12 * 64)], 1
+	ldd	[%o0 + (1 * 8)], %f2
+	fsrc1	%f12, %f44
+	ldd	[%o0 + (2 * 8)], %f4
+	fsrc1	%f14, %f46
+	stda	%f32, [%o1] %asi
+	ldd	[%o0 + (3 * 8)], %f6
+	fsrc1	%f0, %f32
+	ldd	[%o0 + (4 * 8)], %f8
+	fsrc1	%f2, %f34
+	ldd	[%o0 + (5 * 8)], %f10
+	fsrc1	%f4, %f36
+	ldd	[%o0 + (6 * 8)], %f12
+	fsrc1	%f6, %f38
+	ldd	[%o0 + (7 * 8)], %f14
+	fsrc1	%f8, %f40
+	add	%o1, 64, %o1
+	fsrc1	%f10, %f42
+	fsrc1	%f12, %f44
+	fsrc1	%f14, %f46
+	stda	%f32, [%o1] %asi
+	membar	#Sync
+
+	retl
+	 wr	%g0, 0, %fprs
+END(zeus_block_copy)
+
+/*
+ * void spitfire_block_zero(void *dst, size_t len)
+ * void zeus_block_zero(void *dst, size_t len)
+ */
+ALTENTRY(zeus_block_zero)
 ENTRY(spitfire_block_zero)
 	rdpr	%pil, %o3
 	wrpr	%g0, PIL_TICK, %pil

From 225f5b4adc2597ba94537fc976e632fb1f5948c3 Mon Sep 17 00:00:00 2001
From: Navdeep Parhar 
Date: Wed, 15 Sep 2010 21:50:37 +0000
Subject: [PATCH 0792/1624] Fix t3_gate_rx_traffic and t3_open_rx_traffic.
 Parts of them always operated on XGMAC0 instead of the specified XGMAC.

MFC after:	3 days
---
 sys/dev/cxgb/common/cxgb_t3_hw.c | 22 +++++++++++++---------
 1 file changed, 13 insertions(+), 9 deletions(-)

diff --git a/sys/dev/cxgb/common/cxgb_t3_hw.c b/sys/dev/cxgb/common/cxgb_t3_hw.c
index 610a48186bb..6083ad3c777 100644
--- a/sys/dev/cxgb/common/cxgb_t3_hw.c
+++ b/sys/dev/cxgb/common/cxgb_t3_hw.c
@@ -1441,16 +1441,18 @@ static void t3_gate_rx_traffic(struct cmac *mac, u32 *rx_cfg,
 	t3_mac_disable_exact_filters(mac);
 
 	/* stop broadcast, multicast, promiscuous mode traffic */
-	*rx_cfg = t3_read_reg(mac->adapter, A_XGM_RX_CFG);
-	t3_set_reg_field(mac->adapter, A_XGM_RX_CFG, 
+	*rx_cfg = t3_read_reg(mac->adapter, A_XGM_RX_CFG + mac->offset);
+	t3_set_reg_field(mac->adapter, A_XGM_RX_CFG + mac->offset, 
 			 F_ENHASHMCAST | F_DISBCAST | F_COPYALLFRAMES,
 			 F_DISBCAST);
 
-	*rx_hash_high = t3_read_reg(mac->adapter, A_XGM_RX_HASH_HIGH);
-	t3_write_reg(mac->adapter, A_XGM_RX_HASH_HIGH, 0);
+	*rx_hash_high = t3_read_reg(mac->adapter, A_XGM_RX_HASH_HIGH +
+	    mac->offset);
+	t3_write_reg(mac->adapter, A_XGM_RX_HASH_HIGH + mac->offset, 0);
 
-	*rx_hash_low = t3_read_reg(mac->adapter, A_XGM_RX_HASH_LOW);
-	t3_write_reg(mac->adapter, A_XGM_RX_HASH_LOW, 0);
+	*rx_hash_low = t3_read_reg(mac->adapter, A_XGM_RX_HASH_LOW +
+	    mac->offset);
+	t3_write_reg(mac->adapter, A_XGM_RX_HASH_LOW + mac->offset, 0);
 
 	/* Leave time to drain max RX fifo */
 	msleep(1);
@@ -1460,11 +1462,13 @@ static void t3_open_rx_traffic(struct cmac *mac, u32 rx_cfg,
 			       u32 rx_hash_high, u32 rx_hash_low)
 {
 	t3_mac_enable_exact_filters(mac);
-	t3_set_reg_field(mac->adapter, A_XGM_RX_CFG, 
+	t3_set_reg_field(mac->adapter, A_XGM_RX_CFG + mac->offset,
 			 F_ENHASHMCAST | F_DISBCAST | F_COPYALLFRAMES,
 			 rx_cfg);
-	t3_write_reg(mac->adapter, A_XGM_RX_HASH_HIGH, rx_hash_high);
-	t3_write_reg(mac->adapter, A_XGM_RX_HASH_LOW, rx_hash_low);
+	t3_write_reg(mac->adapter, A_XGM_RX_HASH_HIGH + mac->offset,
+	    rx_hash_high);
+	t3_write_reg(mac->adapter, A_XGM_RX_HASH_LOW + mac->offset,
+	    rx_hash_low);
 }
 
 static int t3_detect_link_fault(adapter_t *adapter, int port_id)

From 24f52bbd9b951b8e251bac7052a14f63ba43a990 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 21:53:10 +0000
Subject: [PATCH 0793/1624] Use TAILQ_EMPTY() for testing if a tail queue is
 empty. Set whoFrom to NULL after freeing whoFrom.

---
 sys/netinet/sctp_indata.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/sys/netinet/sctp_indata.c b/sys/netinet/sctp_indata.c
index 12fba8bd60e..6095fe534c2 100644
--- a/sys/netinet/sctp_indata.c
+++ b/sys/netinet/sctp_indata.c
@@ -708,9 +708,10 @@ protocol_error:
 					control->data = NULL;
 					asoc->size_on_all_streams -= control->length;
 					sctp_ucount_decr(asoc->cnt_on_all_streams);
-					if (control->whoFrom)
+					if (control->whoFrom) {
 						sctp_free_remote_addr(control->whoFrom);
-					control->whoFrom = NULL;
+						control->whoFrom = NULL;
+					}
 					sctp_free_a_readq(stcb, control);
 					return;
 				} else {
@@ -4845,7 +4846,7 @@ sctp_handle_sack(struct mbuf *m, int offset_seg, int offset_dup,
 			if (asoc->pr_sctp_cnt != 0)
 				asoc->pr_sctp_cnt--;
 		}
-		if ((TAILQ_FIRST(&asoc->sent_queue) == NULL) &&
+		if (TAILQ_EMPTY(&asoc->sent_queue) &&
 		    (asoc->total_flight > 0)) {
 #ifdef INVARIANTS
 			panic("Warning flight size is postive and should be 0");
@@ -5818,7 +5819,7 @@ sctp_handle_forward_tsn(struct sctp_tcb *stcb,
 	 */
 	sctp_slide_mapping_arrays(stcb);
 
-	if (TAILQ_FIRST(&asoc->reasmqueue)) {
+	if (!TAILQ_EMPTY(&asoc->reasmqueue)) {
 		/* now lets kick out and check for more fragmented delivery */
 		/* sa_ignore NO_NULL_CHK */
 		sctp_deliver_reasm_check(stcb, &stcb->asoc);

From 9eea4a2da7a971d928bce8b472645c4c0b8d6b33 Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 23:10:45 +0000
Subject: [PATCH 0794/1624] Delay the assignment of a path for DATA chunk until
 they hit the sent_queue. Honor a given path when the SCTP_ADDR_OVER flag is
 set.

MFC after: 2 weeks.
---
 sys/netinet/sctp_asconf.c |  47 +----------
 sys/netinet/sctp_asconf.h |   2 -
 sys/netinet/sctp_input.c  |  17 ++--
 sys/netinet/sctp_output.c | 165 ++++++++++++++++++--------------------
 sys/netinet/sctp_output.h |   2 +
 sys/netinet/sctp_pcb.c    |  10 ++-
 sys/netinet/sctp_timer.c  |  49 +----------
 sys/netinet/sctputil.c    |  11 ++-
 8 files changed, 112 insertions(+), 191 deletions(-)

diff --git a/sys/netinet/sctp_asconf.c b/sys/netinet/sctp_asconf.c
index ee5dc0d21b1..288381de413 100644
--- a/sys/netinet/sctp_asconf.c
+++ b/sys/netinet/sctp_asconf.c
@@ -581,8 +581,8 @@ sctp_process_asconf_set_primary(struct mbuf *m,
 			}
 			if (sctp_is_mobility_feature_on(stcb->sctp_ep,
 			    SCTP_MOBILITY_BASE)) {
-				sctp_move_chunks_from_deleted_prim(stcb,
-				    stcb->asoc.primary_destination);
+				sctp_move_chunks_from_net(stcb,
+				    stcb->asoc.deleted_primary);
 			}
 			sctp_delete_prim_timer(stcb->sctp_ep, stcb,
 			    stcb->asoc.deleted_primary);
@@ -1041,47 +1041,6 @@ sctp_asconf_nets_cleanup(struct sctp_tcb *stcb, struct sctp_ifn *ifn)
 	}
 }
 
-void
-sctp_move_chunks_from_deleted_prim(struct sctp_tcb *stcb, struct sctp_nets *dst)
-{
-	struct sctp_association *asoc;
-	struct sctp_stream_out *outs;
-	struct sctp_tmit_chunk *chk;
-	struct sctp_stream_queue_pending *sp;
-
-	if (dst->dest_state & SCTP_ADDR_UNCONFIRMED) {
-		return;
-	}
-	if (stcb->asoc.deleted_primary == NULL) {
-		return;
-	}
-	asoc = &stcb->asoc;
-
-	/*
-	 * now through all the streams checking for chunks sent to our bad
-	 * network.
-	 */
-	TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
-		/* now clean up any chunks here */
-		TAILQ_FOREACH(sp, &outs->outqueue, next) {
-			if (sp->net == asoc->deleted_primary) {
-				sctp_free_remote_addr(sp->net);
-				sp->net = dst;
-				atomic_add_int(&dst->ref_count, 1);
-			}
-		}
-	}
-	/* Now check the pending queue */
-	TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
-		if (chk->whoTo == asoc->deleted_primary) {
-			sctp_free_remote_addr(chk->whoTo);
-			chk->whoTo = dst;
-			atomic_add_int(&dst->ref_count, 1);
-		}
-	}
-
-}
-
 
 void
 sctp_assoc_immediate_retrans(struct sctp_tcb *stcb, struct sctp_nets *dstnet)
@@ -2080,13 +2039,11 @@ sctp_asconf_iterator_ep(struct sctp_inpcb *inp, void *ptr, uint32_t val)
 	struct sctp_asconf_iterator *asc;
 	struct sctp_ifa *ifa;
 	struct sctp_laddr *l;
-	int type;
 	int cnt_invalid = 0;
 
 	asc = (struct sctp_asconf_iterator *)ptr;
 	LIST_FOREACH(l, &asc->list_of_work, sctp_nxt_addr) {
 		ifa = l->ifa;
-		type = l->action;
 		if (ifa->address.sa.sa_family == AF_INET6) {
 			/* invalid if we're not a v6 endpoint */
 			if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
diff --git a/sys/netinet/sctp_asconf.h b/sys/netinet/sctp_asconf.h
index 9622871b966..bf3d5665e54 100644
--- a/sys/netinet/sctp_asconf.h
+++ b/sys/netinet/sctp_asconf.h
@@ -79,8 +79,6 @@ extern void
 sctp_check_address_list(struct sctp_tcb *, struct mbuf *, int, int,
     struct sockaddr *, uint16_t, uint16_t, uint16_t, uint16_t);
 
-extern void
-     sctp_move_chunks_from_deleted_prim(struct sctp_tcb *, struct sctp_nets *);
 extern void
      sctp_assoc_immediate_retrans(struct sctp_tcb *, struct sctp_nets *);
 extern void
diff --git a/sys/netinet/sctp_input.c b/sys/netinet/sctp_input.c
index a7b8e7f7978..8dffd4df963 100644
--- a/sys/netinet/sctp_input.c
+++ b/sys/netinet/sctp_input.c
@@ -232,7 +232,10 @@ sctp_is_there_unsent_data(struct sctp_tcb *stcb)
 				}
 				atomic_subtract_int(&stcb->asoc.stream_queue_cnt, 1);
 				TAILQ_REMOVE(&strq->outqueue, sp, next);
-				sctp_free_remote_addr(sp->net);
+				if (sp->net) {
+					sctp_free_remote_addr(sp->net);
+					sp->net = NULL;
+				}
 				if (sp->data) {
 					sctp_m_freem(sp->data);
 					sp->data = NULL;
@@ -263,7 +266,7 @@ sctp_process_init(struct sctp_init_chunk *cp, struct sctp_tcb *stcb,
 	/* save off parameters */
 	asoc->peer_vtag = ntohl(init->initiate_tag);
 	asoc->peers_rwnd = ntohl(init->a_rwnd);
-	if (TAILQ_FIRST(&asoc->nets)) {
+	if (!TAILQ_EMPTY(&asoc->nets)) {
 		/* update any ssthresh's that may have a default */
 		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
 			lnet->ssthresh = asoc->peers_rwnd;
@@ -318,8 +321,10 @@ sctp_process_init(struct sctp_init_chunk *cp, struct sctp_tcb *stcb,
 						sctp_m_freem(sp->data);
 						sp->data = NULL;
 					}
-					sctp_free_remote_addr(sp->net);
-					sp->net = NULL;
+					if (sp->net) {
+						sctp_free_remote_addr(sp->net);
+						sp->net = NULL;
+					}
 					/* Free the chunk */
 					sctp_free_a_strmoq(stcb, sp);
 					/* sa_ignore FREED_MEMORY */
@@ -650,8 +655,8 @@ sctp_handle_heartbeat_ack(struct sctp_heartbeat_chunk *cp,
 			}
 			if (sctp_is_mobility_feature_on(stcb->sctp_ep,
 			    SCTP_MOBILITY_BASE)) {
-				sctp_move_chunks_from_deleted_prim(stcb,
-				    stcb->asoc.primary_destination);
+				sctp_move_chunks_from_net(stcb,
+				    stcb->asoc.deleted_primary);
 			}
 			sctp_delete_prim_timer(stcb->sctp_ep, stcb,
 			    stcb->asoc.deleted_primary);
diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index d4db0e2f165..ac141bc4363 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -5911,10 +5911,10 @@ sctp_msg_append(struct sctp_tcb *stcb,
 	sp->strseq = 0;
 	if (sp->sinfo_flags & SCTP_ADDR_OVER) {
 		sp->net = net;
+		atomic_add_int(&sp->net->ref_count, 1);
 	} else {
-		sp->net = stcb->asoc.primary_destination;
+		sp->net = NULL;
 	}
-	atomic_add_int(&sp->net->ref_count, 1);
 	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
 	sp->stream = srcv->sinfo_stream;
 	sp->msg_is_complete = 1;
@@ -6513,7 +6513,6 @@ sctp_toss_old_asconf(struct sctp_tcb *stcb)
 
 static void
 sctp_clean_up_datalist(struct sctp_tcb *stcb,
-
     struct sctp_association *asoc,
     struct sctp_tmit_chunk **data_list,
     int bundle_at,
@@ -6524,7 +6523,9 @@ sctp_clean_up_datalist(struct sctp_tcb *stcb,
 
 	for (i = 0; i < bundle_at; i++) {
 		/* off of the send queue */
-		if (i) {
+		TAILQ_REMOVE(&asoc->send_queue, data_list[i], sctp_next);
+		asoc->send_queue_cnt--;
+		if (i > 0) {
 			/*
 			 * Any chunk NOT 0 you zap the time chunk 0 gets
 			 * zapped or set based on if a RTO measurment is
@@ -6535,9 +6536,10 @@ sctp_clean_up_datalist(struct sctp_tcb *stcb,
 		/* record time */
 		data_list[i]->sent_rcv_time = net->last_sent_time;
 		data_list[i]->rec.data.fast_retran_tsn = data_list[i]->rec.data.TSN_seq;
-		TAILQ_REMOVE(&asoc->send_queue,
-		    data_list[i],
-		    sctp_next);
+		if (data_list[i]->whoTo == NULL) {
+			data_list[i]->whoTo = net;
+			atomic_add_int(&net->ref_count, 1);
+		}
 		/* on to the sent queue */
 		tp1 = TAILQ_LAST(&asoc->sent_queue, sctpchunk_listhead);
 		if ((tp1) && (compare_with_wrap(tp1->rec.data.TSN_seq,
@@ -6565,7 +6567,6 @@ sctp_clean_up_datalist(struct sctp_tcb *stcb,
 all_done:
 		/* This does not lower until the cum-ack passes it */
 		asoc->sent_queue_cnt++;
-		asoc->send_queue_cnt--;
 		if ((asoc->peers_rwnd <= 0) &&
 		    (asoc->total_flight == 0) &&
 		    (bundle_at == 1)) {
@@ -6703,7 +6704,7 @@ sctp_can_we_split_this(struct sctp_tcb *stcb,
 }
 
 static uint32_t
-sctp_move_to_outqueue(struct sctp_tcb *stcb, struct sctp_nets *net,
+sctp_move_to_outqueue(struct sctp_tcb *stcb,
     struct sctp_stream_out *strq,
     uint32_t goal_mtu,
     uint32_t frag_point,
@@ -6772,7 +6773,10 @@ one_more_time:
 			}
 			atomic_subtract_int(&asoc->stream_queue_cnt, 1);
 			TAILQ_REMOVE(&strq->outqueue, sp, next);
-			sctp_free_remote_addr(sp->net);
+			if (sp->net) {
+				sctp_free_remote_addr(sp->net);
+				sp->net = NULL;
+			}
 			if (sp->data) {
 				sctp_m_freem(sp->data);
 				sp->data = NULL;
@@ -7089,8 +7093,11 @@ dont_do_it:
 	chk->rec.data.timetodrop = sp->ts;
 	chk->flags = sp->act_flags;
 
-	chk->whoTo = net;
-	atomic_add_int(&chk->whoTo->ref_count, 1);
+	if (sp->net) {
+		chk->whoTo = sp->net;
+		atomic_add_int(&chk->whoTo->ref_count, 1);
+	} else
+		chk->whoTo = NULL;
 
 	if (sp->holds_key_ref) {
 		chk->auth_keyid = sp->auth_keyid;
@@ -7175,7 +7182,10 @@ dont_do_it:
 			send_lock_up = 1;
 		}
 		TAILQ_REMOVE(&strq->outqueue, sp, next);
-		sctp_free_remote_addr(sp->net);
+		if (sp->net) {
+			sctp_free_remote_addr(sp->net);
+			sp->net = NULL;
+		}
 		if (sp->data) {
 			sctp_m_freem(sp->data);
 			sp->data = NULL;
@@ -7248,31 +7258,29 @@ sctp_fill_outqueue(struct sctp_tcb *stcb,
 	goal_mtu &= 0xfffffffc;
 	if (asoc->locked_on_sending) {
 		/* We are stuck on one stream until the message completes. */
-		strqn = strq = asoc->locked_on_sending;
+		strq = asoc->locked_on_sending;
 		locked = 1;
 	} else {
-		strqn = strq = sctp_select_a_stream(stcb, asoc);
+		strq = sctp_select_a_stream(stcb, asoc);
 		locked = 0;
 	}
-
+	strqn = strq;
 	while ((goal_mtu > 0) && strq) {
 		sp = TAILQ_FIRST(&strq->outqueue);
-		/*
-		 * If CMT is off, we must validate that the stream in
-		 * question has the first item pointed towards are network
-		 * destionation requested by the caller. Note that if we
-		 * turn out to be locked to a stream (assigning TSN's then
-		 * we must stop, since we cannot look for another stream
-		 * with data to send to that destination). In CMT's case, by
-		 * skipping this check, we will send one data packet towards
-		 * the requested net.
-		 */
 		if (sp == NULL) {
 			break;
 		}
-		if ((sp->net != net) &&
-		    (asoc->sctp_cmt_on_off == 0)) {
-			/* none for this network */
+		/**
+		 * Honor the users' choice if given. If not given,
+		 * pull it only to the primary path in case of not using
+		 * CMT.
+		 */
+		if (((sp->net != NULL) &&
+		    (sp->net != net)) ||
+		    ((sp->net == NULL) &&
+		    (asoc->sctp_cmt_on_off == 0) &&
+		    (asoc->primary_destination != net))) {
+			/* Do not pull to this network */
 			if (locked) {
 				break;
 			} else {
@@ -7289,7 +7297,7 @@ sctp_fill_outqueue(struct sctp_tcb *stcb,
 		}
 		giveup = 0;
 		bail = 0;
-		moved_how_much = sctp_move_to_outqueue(stcb, net, strq, goal_mtu, frag_point, &locked,
+		moved_how_much = sctp_move_to_outqueue(stcb, strq, goal_mtu, frag_point, &locked,
 		    &giveup, eeor_mode, &bail);
 		if (moved_how_much)
 			asoc->last_out_stream = strq;
@@ -7353,43 +7361,32 @@ sctp_fix_ecn_echo(struct sctp_association *asoc)
 	}
 }
 
-static void
-sctp_move_to_an_alt(struct sctp_tcb *stcb,
-    struct sctp_association *asoc,
-    struct sctp_nets *net)
+void
+sctp_move_chunks_from_net(struct sctp_tcb *stcb, struct sctp_nets *net)
 {
+	struct sctp_association *asoc;
+	struct sctp_stream_out *outs;
 	struct sctp_tmit_chunk *chk;
-	struct sctp_nets *a_net;
+	struct sctp_stream_queue_pending *sp;
 
-	SCTP_TCB_LOCK_ASSERT(stcb);
-	/*
-	 * JRS 5/14/07 - If CMT PF is turned on, find an alternate
-	 * destination using the PF algorithm for finding alternate
-	 * destinations.
-	 */
-	if ((asoc->sctp_cmt_on_off == 1) &&
-	    (asoc->sctp_cmt_pf > 0)) {
-		a_net = sctp_find_alternate_net(stcb, net, 2);
-	} else {
-		a_net = sctp_find_alternate_net(stcb, net, 0);
+	if (net == NULL) {
+		return;
 	}
-	if ((a_net != net) &&
-	    ((a_net->dest_state & SCTP_ADDR_REACHABLE) == SCTP_ADDR_REACHABLE)) {
-		/*
-		 * We only proceed if a valid alternate is found that is not
-		 * this one and is reachable. Here we must move all chunks
-		 * queued in the send queue off of the destination address
-		 * to our alternate.
-		 */
-		TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
-			if (chk->whoTo == net) {
-				/* Move the chunk to our alternate */
-				sctp_free_remote_addr(chk->whoTo);
-				chk->whoTo = a_net;
-				atomic_add_int(&a_net->ref_count, 1);
+	asoc = &stcb->asoc;
+	TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
+		TAILQ_FOREACH(sp, &outs->outqueue, next) {
+			if (sp->net == net) {
+				sctp_free_remote_addr(sp->net);
+				sp->net = NULL;
 			}
 		}
 	}
+	TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
+		if (chk->whoTo == net) {
+			sctp_free_remote_addr(chk->whoTo);
+			chk->whoTo = NULL;
+		}
+	}
 }
 
 int
@@ -7497,7 +7494,8 @@ sctp_med_chunk_output(struct sctp_inpcb *inp,
 			 * copy by reference (we hope).
 			 */
 			net->window_probe = 0;
-			if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) || (net->dest_state & SCTP_ADDR_UNCONFIRMED)) {
+			if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) ||
+			    (net->dest_state & SCTP_ADDR_UNCONFIRMED)) {
 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
 					sctp_log_cwnd(stcb, net, 1,
 					    SCTP_CWND_LOG_FILL_OUTQ_CALLED);
@@ -7505,6 +7503,7 @@ sctp_med_chunk_output(struct sctp_inpcb *inp,
 				continue;
 			}
 			if ((asoc->sctp_cmt_on_off == 0) &&
+			    (asoc->primary_destination != net) &&
 			    (net->ref_count < 2)) {
 				/* nothing can be in queue for this guy */
 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
@@ -7534,9 +7533,9 @@ sctp_med_chunk_output(struct sctp_inpcb *inp,
 	}
 	/* now service each destination and send out what we can for it */
 	/* Nothing to send? */
-	if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
-	    (TAILQ_FIRST(&asoc->asconf_send_queue) == NULL) &&
-	    (TAILQ_FIRST(&asoc->send_queue) == NULL)) {
+	if (TAILQ_EMPTY(&asoc->control_send_queue) &&
+	    TAILQ_EMPTY(&asoc->asconf_send_queue) &&
+	    TAILQ_EMPTY(&asoc->send_queue)) {
 		*reason_code = 8;
 		return (0);
 	}
@@ -7566,15 +7565,17 @@ again_one_more_time:
 			break;
 		}
 		tsns_sent = 0xa;
-		if ((asoc->sctp_cmt_on_off == 0) && (net->ref_count < 2)) {
+		if ((asoc->sctp_cmt_on_off == 0) &&
+		    (asoc->primary_destination != net) &&
+		    (net->ref_count < 2)) {
 			/*
 			 * Ref-count of 1 so we cannot have data or control
 			 * queued to this address. Skip it (non-CMT).
 			 */
 			continue;
 		}
-		if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
-		    (TAILQ_FIRST(&asoc->asconf_send_queue) == NULL) &&
+		if (TAILQ_EMPTY(&asoc->control_send_queue) &&
+		    TAILQ_EMPTY(&asoc->asconf_send_queue) &&
 		    (net->flight_size >= net->cwnd)) {
 			/*
 			 * Nothing on control or asconf and flight is full,
@@ -7778,7 +7779,7 @@ again_one_more_time:
 							 * unreachable
 							 * during this send
 							 */
-							sctp_move_to_an_alt(stcb, asoc, net);
+							sctp_move_chunks_from_net(stcb, net);
 						}
 						*reason_code = 7;
 						continue;
@@ -8001,7 +8002,7 @@ again_one_more_time:
 							 * unreachable
 							 * during this send
 							 */
-							sctp_move_to_an_alt(stcb, asoc, net);
+							sctp_move_chunks_from_net(stcb, net);
 						}
 						*reason_code = 7;
 						continue;
@@ -8102,19 +8103,9 @@ again_one_more_time:
 					break;
 				}
 				nchk = TAILQ_NEXT(chk, sctp_next);
-				if (asoc->sctp_cmt_on_off == 1) {
-					if (chk->whoTo != net) {
-						/*
-						 * For CMT, steal the data
-						 * to this network if its
-						 * not set here.
-						 */
-						sctp_free_remote_addr(chk->whoTo);
-						chk->whoTo = net;
-						atomic_add_int(&chk->whoTo->ref_count, 1);
-					}
-				} else if (chk->whoTo != net) {
-					/* No, not sent to this net */
+				if ((chk->whoTo != NULL) &&
+				    (chk->whoTo != net)) {
+					/* Don't send the chunk on this net */
 					continue;
 				}
 				if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
@@ -8330,7 +8321,7 @@ no_data_fill:
 					 * Destination went unreachable
 					 * during this send
 					 */
-					sctp_move_to_an_alt(stcb, asoc, net);
+					sctp_move_chunks_from_net(stcb, net);
 				}
 				*reason_code = 6;
 				/*-
@@ -9584,7 +9575,7 @@ sctp_chunk_output(struct sctp_inpcb *inp,
 			 * out wheel to this alternate address.
 			 */
 			if (net->ref_count > 1)
-				sctp_move_to_an_alt(stcb, asoc, net);
+				sctp_move_chunks_from_net(stcb, net);
 		} else if ((asoc->sctp_cmt_on_off == 1) &&
 			    (asoc->sctp_cmt_pf > 0) &&
 		    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
@@ -9594,7 +9585,7 @@ sctp_chunk_output(struct sctp_inpcb *inp,
 			 * to an alternate desination.
 			 */
 			if (net->ref_count > 1)
-				sctp_move_to_an_alt(stcb, asoc, net);
+				sctp_move_chunks_from_net(stcb, net);
 		} else {
 			/*-
 			 * if ((asoc->sat_network) || (net->addr_is_local))
@@ -12103,10 +12094,10 @@ skip_copy:
 	} else {
 		if (sp->sinfo_flags & SCTP_ADDR_OVER) {
 			sp->net = net;
+			atomic_add_int(&sp->net->ref_count, 1);
 		} else {
-			sp->net = asoc->primary_destination;
+			sp->net = NULL;
 		}
-		atomic_add_int(&sp->net->ref_count, 1);
 		sctp_set_prsctp_policy(sp);
 	}
 out_now:
diff --git a/sys/netinet/sctp_output.h b/sys/netinet/sctp_output.h
index 6488b1cf739..d655c3aa218 100644
--- a/sys/netinet/sctp_output.h
+++ b/sys/netinet/sctp_output.h
@@ -129,6 +129,8 @@ void sctp_toss_old_asconf(struct sctp_tcb *);
 
 void sctp_fix_ecn_echo(struct sctp_association *);
 
+void sctp_move_chunks_from_net(struct sctp_tcb *stcb, struct sctp_nets *net);
+
 int
 sctp_output(struct sctp_inpcb *, struct mbuf *, struct sockaddr *,
     struct mbuf *, struct thread *, int);
diff --git a/sys/netinet/sctp_pcb.c b/sys/netinet/sctp_pcb.c
index de18c2e203b..e7b55539c4d 100644
--- a/sys/netinet/sctp_pcb.c
+++ b/sys/netinet/sctp_pcb.c
@@ -4843,7 +4843,10 @@ sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfre
 					sp->tail_mbuf = NULL;
 				}
 			}
-			sctp_free_remote_addr(sp->net);
+			if (sp->net) {
+				sctp_free_remote_addr(sp->net);
+				sp->net = NULL;
+			}
 			sctp_free_spbufspace(stcb, asoc, sp);
 			if (sp->holds_key_ref)
 				sctp_auth_key_release(stcb, sp->auth_keyid);
@@ -4914,7 +4917,10 @@ sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfre
 			if (chk->holds_key_ref)
 				sctp_auth_key_release(stcb, chk->auth_keyid);
 			ccnt++;
-			sctp_free_remote_addr(chk->whoTo);
+			if (chk->whoTo) {
+				sctp_free_remote_addr(chk->whoTo);
+				chk->whoTo = NULL;
+			}
 			SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
 			SCTP_DECR_CHK_COUNT();
 			/* sa_ignore FREED_MEMORY */
diff --git a/sys/netinet/sctp_timer.c b/sys/netinet/sctp_timer.c
index 1e0b771708c..6db51935898 100644
--- a/sys/netinet/sctp_timer.c
+++ b/sys/netinet/sctp_timer.c
@@ -969,46 +969,6 @@ start_again:
 	return (0);
 }
 
-static void
-sctp_move_all_chunks_to_alt(struct sctp_tcb *stcb,
-    struct sctp_nets *net,
-    struct sctp_nets *alt)
-{
-	struct sctp_association *asoc;
-	struct sctp_stream_out *outs;
-	struct sctp_tmit_chunk *chk;
-	struct sctp_stream_queue_pending *sp;
-
-	if (net == alt)
-		/* nothing to do */
-		return;
-
-	asoc = &stcb->asoc;
-
-	/*
-	 * now through all the streams checking for chunks sent to our bad
-	 * network.
-	 */
-	TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
-		/* now clean up any chunks here */
-		TAILQ_FOREACH(sp, &outs->outqueue, next) {
-			if (sp->net == net) {
-				sctp_free_remote_addr(sp->net);
-				sp->net = alt;
-				atomic_add_int(&alt->ref_count, 1);
-			}
-		}
-	}
-	/* Now check the pending queue */
-	TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
-		if (chk->whoTo == net) {
-			sctp_free_remote_addr(chk->whoTo);
-			chk->whoTo = alt;
-			atomic_add_int(&alt->ref_count, 1);
-		}
-	}
-
-}
 
 int
 sctp_t3rxt_timer(struct sctp_inpcb *inp,
@@ -1141,7 +1101,7 @@ sctp_t3rxt_timer(struct sctp_inpcb *inp,
 	}
 	if (net->dest_state & SCTP_ADDR_NOT_REACHABLE) {
 		/* Move all pending over too */
-		sctp_move_all_chunks_to_alt(stcb, net, alt);
+		sctp_move_chunks_from_net(stcb, net);
 
 		/*
 		 * Get the address that failed, to force a new src address
@@ -1256,7 +1216,7 @@ sctp_t1init_timer(struct sctp_inpcb *inp,
 
 		alt = sctp_find_alternate_net(stcb, stcb->asoc.primary_destination, 0);
 		if ((alt != NULL) && (alt != stcb->asoc.primary_destination)) {
-			sctp_move_all_chunks_to_alt(stcb, stcb->asoc.primary_destination, alt);
+			sctp_move_chunks_from_net(stcb, stcb->asoc.primary_destination);
 			stcb->asoc.primary_destination = alt;
 		}
 	}
@@ -1396,7 +1356,7 @@ sctp_strreset_timer(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
 		 * If the address went un-reachable, we need to move to
 		 * alternates for ALL chk's in queue
 		 */
-		sctp_move_all_chunks_to_alt(stcb, net, alt);
+		sctp_move_chunks_from_net(stcb, net);
 	}
 	/* mark the retran info */
 	if (strrst->sent != SCTP_DATAGRAM_RESEND)
@@ -1487,8 +1447,7 @@ sctp_asconf_timer(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
 			 * If the address went un-reachable, we need to move
 			 * to the alternate for ALL chunks in queue
 			 */
-			sctp_move_all_chunks_to_alt(stcb, net, alt);
-			net = alt;
+			sctp_move_chunks_from_net(stcb, net);
 		}
 		/* mark the retran info */
 		if (asconf->sent != SCTP_DATAGRAM_RESEND)
diff --git a/sys/netinet/sctputil.c b/sys/netinet/sctputil.c
index b09fe7ec72b..543967abd89 100644
--- a/sys/netinet/sctputil.c
+++ b/sys/netinet/sctputil.c
@@ -2500,7 +2500,6 @@ sctp_mtu_size_reset(struct sctp_inpcb *inp,
 	}
 	eff_mtu = mtu - ovh;
 	TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
-
 		if (chk->send_size > eff_mtu) {
 			chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
 		}
@@ -3763,9 +3762,10 @@ sctp_report_all_outbound(struct sctp_tcb *stcb, int holds_lock, int so_locked
 					sp->data = NULL;
 				}
 			}
-			if (sp->net)
+			if (sp->net) {
 				sctp_free_remote_addr(sp->net);
-			sp->net = NULL;
+				sp->net = NULL;
+			}
 			/* Free the chunk */
 			sctp_free_a_strmoq(stcb, sp);
 			/* sa_ignore FREED_MEMORY */
@@ -4818,7 +4818,10 @@ next_on_sent:
 					chk->rec.data.payloadtype = sp->ppid;
 					chk->rec.data.context = sp->context;
 					chk->flags = sp->act_flags;
-					chk->whoTo = sp->net;
+					if (sp->net)
+						chk->whoTo = sp->net;
+					else
+						chk->whoTo = stcb->asoc.primary_destination;
 					atomic_add_int(&chk->whoTo->ref_count, 1);
 					chk->rec.data.TSN_seq = atomic_fetchadd_int(&stcb->asoc.sending_seq, 1);
 					stcb->asoc.pr_sctp_cnt++;

From 94b0d9699201de2408711f4a82ad08619999635c Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 23:40:36 +0000
Subject: [PATCH 0795/1624] Remove unused variable/assignment.

MFC after: 3 weeks.
---
 sys/netinet/sctputil.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/sys/netinet/sctputil.c b/sys/netinet/sctputil.c
index 543967abd89..888d3f83f99 100644
--- a/sys/netinet/sctputil.c
+++ b/sys/netinet/sctputil.c
@@ -5135,7 +5135,7 @@ sctp_sorecvmsg(struct socket *so,
 	int my_len = 0;
 	int cp_len = 0, error = 0;
 	struct sctp_queued_to_read *control = NULL, *ctl = NULL, *nxt = NULL;
-	struct mbuf *m = NULL, *embuf = NULL;
+	struct mbuf *m = NULL;
 	struct sctp_tcb *stcb = NULL;
 	int wakeup_read_socket = 0;
 	int freecnt_applied = 0;
@@ -5731,7 +5731,6 @@ get_more_data:
 						sctp_sblog(&so->so_rcv,
 						    control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
 					}
-					embuf = m;
 					copied_so_far += cp_len;
 					freed_so_far += cp_len;
 					freed_so_far += MSIZE;
@@ -5783,7 +5782,6 @@ get_more_data:
 						atomic_subtract_int(&stcb->asoc.sb_cc, cp_len);
 					}
 					copied_so_far += cp_len;
-					embuf = m;
 					freed_so_far += cp_len;
 					freed_so_far += MSIZE;
 					if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {

From b3f7949dc59a832b2c227b159e4a533aec93967a Mon Sep 17 00:00:00 2001
From: Michael Tuexen 
Date: Wed, 15 Sep 2010 23:56:25 +0000
Subject: [PATCH 0796/1624] Remove old debug code.

MFC after: 2 weeks.
---
 sys/netinet/sctp_output.c | 11 -----------
 sys/netinet/sctp_pcb.c    | 13 -------------
 sys/netinet/sctp_usrreq.c | 16 ----------------
 sys/netinet/sctputil.c    |  8 --------
 4 files changed, 48 deletions(-)

diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
index ac141bc4363..4d0eb02ebc1 100644
--- a/sys/netinet/sctp_output.c
+++ b/sys/netinet/sctp_output.c
@@ -3803,9 +3803,6 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 					mtu -= sizeof(struct udphdr);
 				}
 				if (mtu && (stcb->asoc.smallest_mtu > mtu)) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-					SCTP_PRINTF("sctp_mtu_size_reset called after ip_output mtu-change:%d\n", mtu);
-#endif
 					sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
 					net->mtu = mtu;
 				}
@@ -4134,10 +4131,6 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 				mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
 				if (mtu &&
 				    (stcb->asoc.smallest_mtu > mtu)) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-					SCTP_PRINTF("sctp_mtu_size_reset called after ip6_output mtu-change:%d\n",
-					    mtu);
-#endif
 					sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
 					net->mtu = mtu;
 					if (net->port) {
@@ -4147,10 +4140,6 @@ sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
 			} else if (ifp) {
 				if (ND_IFINFO(ifp)->linkmtu &&
 				    (stcb->asoc.smallest_mtu > ND_IFINFO(ifp)->linkmtu)) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-					SCTP_PRINTF("sctp_mtu_size_reset called via ifp ND_IFINFO() linkmtu:%d\n",
-					    ND_IFINFO(ifp)->linkmtu);
-#endif
 					sctp_mtu_size_reset(inp,
 					    &stcb->asoc,
 					    ND_IFINFO(ifp)->linkmtu);
diff --git a/sys/netinet/sctp_pcb.c b/sys/netinet/sctp_pcb.c
index e7b55539c4d..57d4ef26df8 100644
--- a/sys/netinet/sctp_pcb.c
+++ b/sys/netinet/sctp_pcb.c
@@ -3916,9 +3916,6 @@ sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
 		} else {
 			net->mtu = 0;
 		}
-#ifdef SCTP_PRINT_FOR_B_AND_M
-		SCTP_PRINTF("We have found an interface mtu of %d\n", net->mtu);
-#endif
 		if (net->mtu == 0) {
 			/* Huh ?? */
 			net->mtu = SCTP_DEFAULT_MTU;
@@ -3926,9 +3923,6 @@ sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
 			uint32_t rmtu;
 
 			rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_rt);
-#ifdef SCTP_PRINT_FOR_B_AND_M
-			SCTP_PRINTF("The route mtu is %d\n", rmtu);
-#endif
 			if (rmtu == 0) {
 				/*
 				 * Start things off to match mtu of
@@ -3946,9 +3940,6 @@ sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
 			}
 		}
 		if (from == SCTP_ALLOC_ASOC) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-			SCTP_PRINTF("New assoc sets mtu to :%d\n", net->mtu);
-#endif
 			stcb->asoc.smallest_mtu = net->mtu;
 		}
 	} else {
@@ -3966,10 +3957,6 @@ sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
 		net->mtu -= sizeof(struct udphdr);
 	}
 	if (stcb->asoc.smallest_mtu > net->mtu) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-		SCTP_PRINTF("new address mtu:%d smaller than smallest:%d\n",
-		    net->mtu, stcb->asoc.smallest_mtu);
-#endif
 		stcb->asoc.smallest_mtu = net->mtu;
 	}
 	/* JRS - Use the congestion control given in the CC module */
diff --git a/sys/netinet/sctp_usrreq.c b/sys/netinet/sctp_usrreq.c
index 2ed66af0433..627d1eecdb4 100644
--- a/sys/netinet/sctp_usrreq.c
+++ b/sys/netinet/sctp_usrreq.c
@@ -111,10 +111,6 @@ sctp_pathmtu_adjustment(struct sctp_inpcb *inp,
 	/* Adjust that too */
 	stcb->asoc.smallest_mtu = nxtsz;
 	/* now off to subtract IP_DF flag if needed */
-#ifdef SCTP_PRINT_FOR_B_AND_M
-	SCTP_PRINTF("sctp_pathmtu_adjust called inp:%p stcb:%p net:%p nxtsz:%d\n",
-	    inp, stcb, net, nxtsz);
-#endif
 	overhead = IP_HDR_SIZE;
 	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks)) {
 		overhead += sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
@@ -215,10 +211,6 @@ sctp_notify_mbuf(struct sctp_inpcb *inp,
 	}
 	/* now what about the ep? */
 	if (stcb->asoc.smallest_mtu > nxtsz) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-		SCTP_PRINTF("notify_mbuf (ICMP) calls sctp_pathmtu_adjust mtu:%d\n",
-		    nxtsz);
-#endif
 		sctp_pathmtu_adjustment(inp, stcb, net, nxtsz);
 	}
 	if (tmr_stopped)
@@ -3806,10 +3798,6 @@ sctp_setopt(struct socket *so, int optname, void *optval, size_t optsize,
 						if (paddrp->spp_pathmtu > SCTP_DEFAULT_MINSEGMENT) {
 							net->mtu = paddrp->spp_pathmtu + ovh;
 							if (net->mtu < stcb->asoc.smallest_mtu) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-								SCTP_PRINTF("SCTP_PMTU_DISABLE calls sctp_pathmtu_adjustment:%d\n",
-								    net->mtu);
-#endif
 								sctp_pathmtu_adjustment(inp, stcb, net, net->mtu);
 							}
 						}
@@ -3854,10 +3842,6 @@ sctp_setopt(struct socket *so, int optname, void *optval, size_t optsize,
 							if (paddrp->spp_pathmtu > SCTP_DEFAULT_MINSEGMENT) {
 								net->mtu = paddrp->spp_pathmtu + ovh;
 								if (net->mtu < stcb->asoc.smallest_mtu) {
-#ifdef SCTP_PRINT_FOR_B_AND_M
-									SCTP_PRINTF("SCTP_PMTU_DISABLE calls sctp_pathmtu_adjustment:%d\n",
-									    net->mtu);
-#endif
 									sctp_pathmtu_adjustment(inp, stcb, net, net->mtu);
 								}
 							}
diff --git a/sys/netinet/sctputil.c b/sys/netinet/sctputil.c
index 888d3f83f99..de9401f0dcc 100644
--- a/sys/netinet/sctputil.c
+++ b/sys/netinet/sctputil.c
@@ -1004,10 +1004,6 @@ sctp_init_asoc(struct sctp_inpcb *m, struct sctp_tcb *stcb,
 	asoc->peers_rwnd = SCTP_SB_LIMIT_RCV(m->sctp_socket);
 
 	asoc->smallest_mtu = m->sctp_frag_point;
-#ifdef SCTP_PRINT_FOR_B_AND_M
-	SCTP_PRINTF("smallest_mtu init'd with asoc to :%d\n",
-	    asoc->smallest_mtu);
-#endif
 	asoc->minrto = m->sctp_ep.sctp_minrto;
 	asoc->maxrto = m->sctp_ep.sctp_maxrto;
 
@@ -2488,10 +2484,6 @@ sctp_mtu_size_reset(struct sctp_inpcb *inp,
 	struct sctp_tmit_chunk *chk;
 	unsigned int eff_mtu, ovh;
 
-#ifdef SCTP_PRINT_FOR_B_AND_M
-	SCTP_PRINTF("sctp_mtu_size_reset(%p, asoc:%p mtu:%d\n",
-	    inp, asoc, mtu);
-#endif
 	asoc->smallest_mtu = mtu;
 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
 		ovh = SCTP_MIN_OVERHEAD;

From 95fa3335e16e6a531578c42a2722bc391eb5116f Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 16 Sep 2010 00:22:25 +0000
Subject: [PATCH 0797/1624] Replace the SLB backing store splay tree used on
 64-bit PowerPC AIM hardware with a lockless sparse tree design. This
 marginally improves the performance of PMAP and allows copyin()/copyout() to
 run without acquiring locks when used on wired mappings.

Submitted by:	mdf
---
 sys/powerpc/aim/copyinout.c |  18 +-
 sys/powerpc/aim/mmu_oea64.c |  25 ++-
 sys/powerpc/aim/slb.c       | 431 ++++++++++++++++++++++++++----------
 sys/powerpc/aim/trap.c      |  42 ++--
 sys/powerpc/include/pcb.h   |   1 +
 sys/powerpc/include/pmap.h  |  19 +-
 6 files changed, 370 insertions(+), 166 deletions(-)

diff --git a/sys/powerpc/aim/copyinout.c b/sys/powerpc/aim/copyinout.c
index 35d0ee4985a..ab2d1f32018 100644
--- a/sys/powerpc/aim/copyinout.c
+++ b/sys/powerpc/aim/copyinout.c
@@ -80,16 +80,28 @@ int	setfault(faultbuf);	/* defined in locore.S */
 static __inline void
 set_user_sr(pmap_t pm, const void *addr)
 {
+	struct slb *slb;
 	register_t esid, vsid, slb1, slb2;
 
 	esid = USER_ADDR >> ADDR_SR_SHFT;
-	PMAP_LOCK(pm);
-	vsid = va_to_vsid(pm, (vm_offset_t)addr);
-	PMAP_UNLOCK(pm);
+
+	/* Try lockless look-up first */
+	slb = user_va_to_slb_entry(pm, (vm_offset_t)addr);
+
+	if (slb == NULL) {
+		/* If it isn't there, we need to pre-fault the VSID */
+		PMAP_LOCK(pm);
+		vsid = va_to_vsid(pm, (vm_offset_t)addr);
+		PMAP_UNLOCK(pm);
+	} else {
+		vsid = slb->slbv >> SLBV_VSID_SHIFT;
+	}
 
 	slb1 = vsid << SLBV_VSID_SHIFT;
 	slb2 = (esid << SLBE_ESID_SHIFT) | SLBE_VALID | USER_SR;
 
+	curthread->td_pcb->pcb_cpu.aim.usr_segm =
+	    (uintptr_t)addr >> ADDR_SR_SHFT;
 	__asm __volatile ("slbie %0; slbmte %1, %2" :: "r"(esid << 28),
 	    "r"(slb1), "r"(slb2));
 	isync();
diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index 6328e570103..f0a6cd69c63 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -2097,7 +2097,7 @@ moea64_pinit(mmu_t mmu, pmap_t pmap)
 {
 	PMAP_LOCK_INIT(pmap);
 
-	SPLAY_INIT(&pmap->pm_slbtree);
+	pmap->pm_slb_tree_root = slb_alloc_tree();
 	pmap->pm_slb = slb_alloc_user_cache();
 }
 #else
@@ -2252,7 +2252,7 @@ moea64_release(mmu_t mmu, pmap_t pmap)
 	 * Free segment registers' VSIDs
 	 */
     #ifdef __powerpc64__
-	free_vsids(pmap);
+	slb_free_tree(pmap);
 	slb_free_user_cache(pmap->pm_slb);
     #else
 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_release: pm_sr[0] = 0"));
@@ -2622,18 +2622,25 @@ moea64_pvo_find_va(pmap_t pm, vm_offset_t va)
 	int		ptegidx;
 	uint64_t	vsid;
 	#ifdef __powerpc64__
-	struct slb	slb;
+	uint64_t	slbv;
 
-	/* The page is not mapped if the segment isn't */
-	if (va_to_slb_entry(pm, va, &slb) != 0)
-		return NULL;
+	if (pm == kernel_pmap) {
+		slbv = kernel_va_to_slbv(va);
+	} else {
+		struct slb *slb;
+		slb = user_va_to_slb_entry(pm, va);
+		/* The page is not mapped if the segment isn't */
+		if (slb == NULL)
+			return NULL;
+		slbv = slb->slbv;
+	}
 
-	vsid = (slb.slbv & SLBV_VSID_MASK) >> SLBV_VSID_SHIFT;
-	if (slb.slbv & SLBV_L)
+	vsid = (slbv & SLBV_VSID_MASK) >> SLBV_VSID_SHIFT;
+	if (slbv & SLBV_L)
 		va &= ~moea64_large_page_mask;
 	else
 		va &= ~ADDR_POFF;
-	ptegidx = va_to_pteg(vsid, va, slb.slbv & SLBV_L);
+	ptegidx = va_to_pteg(vsid, va, slbv & SLBV_L);
 	#else
 	va &= ~ADDR_POFF;
 	vsid = va_to_vsid(pm, va);
diff --git a/sys/powerpc/aim/slb.c b/sys/powerpc/aim/slb.c
index 7ea45931e26..3d3aecddc0d 100644
--- a/sys/powerpc/aim/slb.c
+++ b/sys/powerpc/aim/slb.c
@@ -32,7 +32,6 @@
 #include 
 #include 
 #include 
-#include 
 
 #include 
 #include 
@@ -45,65 +44,212 @@
 
 uintptr_t moea64_get_unique_vsid(void);
 void moea64_release_vsid(uint64_t vsid);
-
-struct slbcontainer {
-	struct slb slb;
-	SPLAY_ENTRY(slbcontainer) slb_node;
-};
-
-static int slb_compare(struct slbcontainer *a, struct slbcontainer *b);
 static void slb_zone_init(void *);
 
-SPLAY_PROTOTYPE(slb_tree, slbcontainer, slb_node, slb_compare);
-SPLAY_GENERATE(slb_tree, slbcontainer, slb_node, slb_compare);
-
-uma_zone_t slb_zone;
+uma_zone_t slbt_zone;
 uma_zone_t slb_cache_zone;
 
 SYSINIT(slb_zone_init, SI_SUB_KMEM, SI_ORDER_ANY, slb_zone_init, NULL);
 
-int
-va_to_slb_entry(pmap_t pm, vm_offset_t va, struct slb *slb)
+struct slbtnode {
+	uint16_t	ua_alloc;
+	uint8_t		ua_level;
+	/* Only 36 bits needed for full 64-bit address space. */
+	uint64_t	ua_base;
+	union {
+		struct slbtnode	*ua_child[16];
+		struct slb	slb_entries[16];
+	} u;
+};
+
+/*
+ * For a full 64-bit address space, there are 36 bits in play in an
+ * esid, so 8 levels, with the leaf being at level 0.
+ *
+ * |3333|3322|2222|2222|1111|1111|11  |    |    |  esid
+ * |5432|1098|7654|3210|9876|5432|1098|7654|3210|  bits
+ * +----+----+----+----+----+----+----+----+----+--------
+ * | 8  | 7  | 6  | 5  | 4  | 3  | 2  | 1  | 0  | level
+ */
+#define UAD_ROOT_LEVEL  8
+#define UAD_LEAF_LEVEL  0
+
+static inline int
+esid2idx(uint64_t esid, int level)
 {
-	struct slbcontainer cont, *found;
-	uint64_t esid;
+	int shift;
+
+	shift = level * 4;
+	return ((esid >> shift) & 0xF);
+}
+
+/*
+ * The ua_base field should have 0 bits after the first 4*(level+1)
+ * bits; i.e. only
+ */
+#define uad_baseok(ua)                          \
+	(esid2base(ua->ua_base, ua->ua_level) == ua->ua_base)
+
+
+static inline uint64_t
+esid2base(uint64_t esid, int level)
+{
+	uint64_t mask;
+	int shift;
+
+	shift = (level + 1) * 4;
+	mask = ~((1ULL << shift) - 1);
+	return (esid & mask);
+}
+
+/*
+ * Allocate a new leaf node for the specified esid/vmhandle from the
+ * parent node.
+ */
+static struct slb *
+make_new_leaf(uint64_t esid, uint64_t slbv, struct slbtnode *parent)
+{
+	struct slbtnode *child;
+	struct slb *retval;
+	int idx;
+
+	idx = esid2idx(esid, parent->ua_level);
+	KASSERT(parent->u.ua_child[idx] == NULL, ("Child already exists!"));
+
+	/* unlock and M_WAITOK and loop? */
+	child = uma_zalloc(slbt_zone, M_NOWAIT | M_ZERO);
+	KASSERT(child != NULL, ("unhandled NULL case"));
+
+	child->ua_level = UAD_LEAF_LEVEL;
+	child->ua_base = esid2base(esid, child->ua_level);
+	idx = esid2idx(esid, child->ua_level);
+	child->u.slb_entries[idx].slbv = slbv;
+	child->u.slb_entries[idx].slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
+	setbit(&child->ua_alloc, idx);
+
+	retval = &child->u.slb_entries[idx];
+
+	/*
+	 * The above stores must be visible before the next one, so
+	 * that a lockless searcher always sees a valid path through
+	 * the tree.
+	 */
+	powerpc_sync();
+
+	idx = esid2idx(esid, parent->ua_level);
+	parent->u.ua_child[idx] = child;
+	setbit(&parent->ua_alloc, idx);
+
+	return (retval);
+}
+
+/*
+ * Allocate a new intermediate node to fit between the parent and
+ * esid.
+ */
+static struct slbtnode*
+make_intermediate(uint64_t esid, struct slbtnode *parent)
+{
+	struct slbtnode *child, *inter;
+	int idx, level;
+
+	idx = esid2idx(esid, parent->ua_level);
+	child = parent->u.ua_child[idx];
+	KASSERT(esid2base(esid, child->ua_level) != child->ua_base,
+	    ("No need for an intermediate node?"));
+
+	/*
+	 * Find the level where the existing child and our new esid
+	 * meet.  It must be lower than parent->ua_level or we would
+	 * have chosen a different index in parent.
+	 */
+	level = child->ua_level + 1;
+	while (esid2base(esid, level) !=
+	    esid2base(child->ua_base, level))
+		level++;
+	KASSERT(level < parent->ua_level,
+	    ("Found splitting level %d for %09jx and %09jx, "
+	    "but it's the same as %p's",
+	    level, esid, child->ua_base, parent));
+
+	/* unlock and M_WAITOK and loop? */
+	inter = uma_zalloc(slbt_zone, M_NOWAIT | M_ZERO);
+	KASSERT(inter != NULL, ("unhandled NULL case"));
+
+	/* Set up intermediate node to point to child ... */
+	inter->ua_level = level;
+	inter->ua_base = esid2base(esid, inter->ua_level);
+	idx = esid2idx(child->ua_base, inter->ua_level);
+	inter->u.ua_child[idx] = child;
+	setbit(&inter->ua_alloc, idx);
+	powerpc_sync();
+
+	/* Set up parent to point to intermediate node ... */
+	idx = esid2idx(inter->ua_base, parent->ua_level);
+	parent->u.ua_child[idx] = inter;
+	setbit(&parent->ua_alloc, idx);
+
+	return (inter);
+}
+
+uint64_t
+kernel_va_to_slbv(vm_offset_t va)
+{
+	uint64_t esid, slbv;
 
 	esid = (uintptr_t)va >> ADDR_SR_SHFT;
-	slb->slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
 
-	if (pm == kernel_pmap) {
-		/* Set kernel VSID to deterministic value */
-		slb->slbv = va_to_vsid(kernel_pmap, va) << SLBV_VSID_SHIFT;
+	/* Set kernel VSID to deterministic value */
+	slbv = va_to_vsid(kernel_pmap, va) << SLBV_VSID_SHIFT;
 
-		/* Figure out if this is a large-page mapping */
-		if (hw_direct_map && va < VM_MIN_KERNEL_ADDRESS) {
-			/*
-			 * XXX: If we have set up a direct map, assumes
-			 * all physical memory is mapped with large pages.
-			 */
-			if (mem_valid(va, 0) == 0)
-				slb->slbv |= SLBV_L;
-		}
-			
-		return (0);
+	/* Figure out if this is a large-page mapping */
+	if (hw_direct_map && va < VM_MIN_KERNEL_ADDRESS) {
+		/*
+		 * XXX: If we have set up a direct map, assumes
+		 * all physical memory is mapped with large pages.
+		 */
+		if (mem_valid(va, 0) == 0)
+			slbv |= SLBV_L;
+	}
+		
+	return (slbv);
+}
+
+struct slb *
+user_va_to_slb_entry(pmap_t pm, vm_offset_t va)
+{
+	uint64_t esid = va >> ADDR_SR_SHFT;
+	struct slbtnode *ua;
+	int idx;
+
+	ua = pm->pm_slb_tree_root;
+
+	for (;;) {
+		KASSERT(uad_baseok(ua), ("uad base %016jx level %d bad!",
+		    ua->ua_base, ua->ua_level));
+		idx = esid2idx(esid, ua->ua_level);
+
+		/*
+		 * This code is specific to ppc64 where a load is
+		 * atomic, so no need for atomic_load macro.
+		 */
+		if (ua->ua_level == UAD_LEAF_LEVEL)
+			return ((ua->u.slb_entries[idx].slbe & SLBE_VALID) ?
+			    &ua->u.slb_entries[idx] : NULL);
+
+		ua = ua->u.ua_child[idx];
+		if (ua == NULL ||
+		    esid2base(esid, ua->ua_level) != ua->ua_base)
+			return (NULL);
 	}
 
-	PMAP_LOCK_ASSERT(pm, MA_OWNED);
-
-	cont.slb.slbe = slb->slbe;
-	found = SPLAY_FIND(slb_tree, &pm->pm_slbtree, &cont);
-
-	if (found == NULL)
-		return (-1);
-
-	slb->slbv = found->slb.slbv;
-	return (0);
+	return (NULL);
 }
 
 uint64_t
 va_to_vsid(pmap_t pm, vm_offset_t va)
 {
-	struct slb entry;
+	struct slb *entry;
 
 	/* Shortcut kernel case */
 	if (pm == kernel_pmap)
@@ -114,56 +260,149 @@ va_to_vsid(pmap_t pm, vm_offset_t va)
 	 * to the PMAP's segment table.
 	 */
 
-	if (va_to_slb_entry(pm, va, &entry) != 0)
+	entry = user_va_to_slb_entry(pm, va);
+
+	if (entry == NULL)
 		return (allocate_vsid(pm, (uintptr_t)va >> ADDR_SR_SHFT, 0));
 
-	return ((entry.slbv & SLBV_VSID_MASK) >> SLBV_VSID_SHIFT);
+	return ((entry->slbv & SLBV_VSID_MASK) >> SLBV_VSID_SHIFT);
 }
 
 uint64_t
 allocate_vsid(pmap_t pm, uint64_t esid, int large)
 {
-	uint64_t vsid;
-	struct slbcontainer *slb_entry, kern_entry;
-	struct slb *prespill;
+	uint64_t vsid, slbv;
+	struct slbtnode *ua, *next, *inter;
+	struct slb *slb;
+	int idx;
 
-	prespill = NULL;
+	KASSERT(pm != kernel_pmap, ("Attempting to allocate a kernel VSID"));
 
-	if (pm == kernel_pmap) {
-		vsid = va_to_vsid(pm, esid << ADDR_SR_SHFT);
-		slb_entry = &kern_entry;
-		prespill = PCPU_GET(slb);
-	} else {
-		vsid = moea64_get_unique_vsid();
-		slb_entry = uma_zalloc(slb_zone, M_NOWAIT);
-
-		if (slb_entry == NULL)
-			panic("Could not allocate SLB mapping!");
-
-		prespill = pm->pm_slb;
-	}
-
-	slb_entry->slb.slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
-	slb_entry->slb.slbv = vsid << SLBV_VSID_SHIFT;
+	PMAP_LOCK_ASSERT(pm, MA_OWNED);
+	vsid = moea64_get_unique_vsid();
 
+	slbv = vsid << SLBV_VSID_SHIFT;
 	if (large)
-		slb_entry->slb.slbv |= SLBV_L;
+		slbv |= SLBV_L;
 
-	if (pm != kernel_pmap) {
-		PMAP_LOCK_ASSERT(pm, MA_OWNED);
-		SPLAY_INSERT(slb_tree, &pm->pm_slbtree, slb_entry);
+	ua = pm->pm_slb_tree_root;
+
+	/* Descend to the correct leaf or NULL pointer. */
+	for (;;) {
+		KASSERT(uad_baseok(ua),
+		   ("uad base %09jx level %d bad!", ua->ua_base, ua->ua_level));
+		idx = esid2idx(esid, ua->ua_level);
+
+		if (ua->ua_level == UAD_LEAF_LEVEL) {
+			ua->u.slb_entries[idx].slbv = slbv;
+			eieio();
+			ua->u.slb_entries[idx].slbe = (esid << SLBE_ESID_SHIFT)
+			    | SLBE_VALID;
+			setbit(&ua->ua_alloc, idx);
+			slb = &ua->u.slb_entries[idx];
+			break;
+		}
+
+		next = ua->u.ua_child[idx];
+		if (next == NULL) {
+			slb = make_new_leaf(esid, slbv, ua);
+			break;
+                }
+
+		/*
+		 * Check if the next item down has an okay ua_base.
+		 * If not, we need to allocate an intermediate node.
+		 */
+		if (esid2base(esid, next->ua_level) != next->ua_base) {
+			inter = make_intermediate(esid, ua);
+			slb = make_new_leaf(esid, slbv, inter);
+			break;
+		}
+
+		ua = next;
 	}
 
 	/*
 	 * Someone probably wants this soon, and it may be a wired
 	 * SLB mapping, so pre-spill this entry.
 	 */
-	if (prespill != NULL)
-		slb_insert(pm, prespill, &slb_entry->slb);
+	eieio();
+	slb_insert(pm, pm->pm_slb, slb);
 
 	return (vsid);
 }
 
+void
+free_vsid(pmap_t pm, uint64_t esid, int large)
+{
+	struct slbtnode *ua;
+	int idx;
+
+	PMAP_LOCK_ASSERT(pm, MA_OWNED);
+
+	ua = pm->pm_slb_tree_root;
+	/* Descend to the correct leaf. */
+	for (;;) {
+		KASSERT(uad_baseok(ua),
+		   ("uad base %09jx level %d bad!", ua->ua_base, ua->ua_level));
+		
+		idx = esid2idx(esid, ua->ua_level);
+		if (ua->ua_level == UAD_LEAF_LEVEL) {
+			ua->u.slb_entries[idx].slbv = 0;
+			eieio();
+			ua->u.slb_entries[idx].slbe = 0;
+			clrbit(&ua->ua_alloc, idx);
+			return;
+		}
+
+		ua = ua->u.ua_child[idx];
+		if (ua == NULL ||
+		    esid2base(esid, ua->ua_level) != ua->ua_base) {
+			/* Perhaps just return instead of assert? */
+			KASSERT(0,
+			    ("Asked to remove an entry that was never inserted!"));
+			return;
+		}
+	}
+}
+
+static void
+free_slb_tree_node(struct slbtnode *ua)
+{
+	int idx;
+
+	for (idx = 0; idx < 16; idx++) {
+		if (ua->ua_level != UAD_LEAF_LEVEL) {
+			if (ua->u.ua_child[idx] != NULL)
+				free_slb_tree_node(ua->u.ua_child[idx]);
+		} else {
+			if (ua->u.slb_entries[idx].slbv != 0)
+				moea64_release_vsid(ua->u.slb_entries[idx].slbv
+				    >> SLBV_VSID_SHIFT);
+		}
+	}
+
+	uma_zfree(slbt_zone, ua);
+}
+
+void
+slb_free_tree(pmap_t pm)
+{
+
+	free_slb_tree_node(pm->pm_slb_tree_root);
+}
+
+struct slbtnode *
+slb_alloc_tree(void)
+{
+	struct slbtnode *root;
+
+	root = uma_zalloc(slbt_zone, M_NOWAIT | M_ZERO);
+	root->ua_level = UAD_ROOT_LEVEL;
+
+	return (root);
+}
+
 /* Lock entries mapping kernel text and stacks */
 
 #define SLB_SPILLABLE(slbe) \
@@ -222,62 +461,12 @@ slb_insert(pmap_t pm, struct slb *slbcache, struct slb *slb_entry)
 	critical_exit();
 }
 
-int
-vsid_to_esid(pmap_t pm, uint64_t vsid, uint64_t *esid)
-{
-	uint64_t slbv;
-	struct slbcontainer *entry;
-
-#ifdef INVARIANTS
-	if (pm == kernel_pmap)
-		panic("vsid_to_esid only works on user pmaps");
-
-	PMAP_LOCK_ASSERT(pm, MA_OWNED);
-#endif
-
-	slbv = vsid << SLBV_VSID_SHIFT;
-
-	SPLAY_FOREACH(entry, slb_tree, &pm->pm_slbtree) {
-		if (slbv == entry->slb.slbv) {
-			*esid = entry->slb.slbe >> SLBE_ESID_SHIFT;
-			return (0);
-		}
-	}
-
-	return (-1);
-}
-
-void
-free_vsids(pmap_t pm)
-{
-	struct slbcontainer *entry;
-
-	while (!SPLAY_EMPTY(&pm->pm_slbtree)) {
-		entry = SPLAY_MIN(slb_tree, &pm->pm_slbtree);
-
-		SPLAY_REMOVE(slb_tree, &pm->pm_slbtree, entry);
-
-		moea64_release_vsid(entry->slb.slbv >> SLBV_VSID_SHIFT);
-		uma_zfree(slb_zone, entry);
-	}
-}
-
-static int
-slb_compare(struct slbcontainer *a, struct slbcontainer *b)
-{
-	if (a->slb.slbe == b->slb.slbe)
-		return (0);
-	else if (a->slb.slbe < b->slb.slbe)
-		return (-1);
-	else
-		return (1);
-}
 
 static void
 slb_zone_init(void *dummy)
 {
 
-	slb_zone = uma_zcreate("SLB segment", sizeof(struct slbcontainer),
+	slbt_zone = uma_zcreate("SLB tree node", sizeof(struct slbtnode),
 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
 	slb_cache_zone = uma_zcreate("SLB cache", 64*sizeof(struct slb),
 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
diff --git a/sys/powerpc/aim/trap.c b/sys/powerpc/aim/trap.c
index 76df6dd9b6f..aafdb6955ca 100644
--- a/sys/powerpc/aim/trap.c
+++ b/sys/powerpc/aim/trap.c
@@ -445,33 +445,37 @@ syscall(struct trapframe *frame)
 static int 
 handle_slb_spill(pmap_t pm, vm_offset_t addr)
 {
-	struct slb slb_entry;
-	int error, i;
+	struct slb kern_entry, *user_entry;
+	uint64_t esid;
+	int i;
+
+	esid = (uintptr_t)addr >> ADDR_SR_SHFT;
 
 	if (pm == kernel_pmap) {
-		error = va_to_slb_entry(pm, addr, &slb_entry);
-		if (error)
-			return (error);
+		kern_entry.slbv = kernel_va_to_slbv(addr);
+		kern_entry.slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
 
-		slb_insert(pm, PCPU_GET(slb), &slb_entry);
+		slb_insert(pm, PCPU_GET(slb), &kern_entry);
 		return (0);
 	}
 
 	PMAP_LOCK(pm);
-	error = va_to_slb_entry(pm, addr, &slb_entry);
-	if (error != 0)
-		(void)allocate_vsid(pm, (uintptr_t)addr >> ADDR_SR_SHFT, 0);
-	else {
+	user_entry = user_va_to_slb_entry(pm, addr);
+
+	if (user_entry == NULL) {
+		/* allocate_vsid auto-spills it */
+		(void)allocate_vsid(pm, esid, 0);
+	} else {
 		/*
 		 * Check that another CPU has not already mapped this.
 		 * XXX: Per-thread SLB caches would be better.
 		 */
 		for (i = 0; i < 64; i++)
-			if (pm->pm_slb[i].slbe == (slb_entry.slbe | i))
+			if (pm->pm_slb[i].slbe == (user_entry->slbe | i))
 				break;
 
 		if (i == 64)
-			slb_insert(pm, pm->pm_slb, &slb_entry);
+			slb_insert(pm, pm->pm_slb, user_entry);
 	}
 	PMAP_UNLOCK(pm);
 
@@ -513,19 +517,7 @@ trap_pfault(struct trapframe *frame, int user)
 			map = &p->p_vmspace->vm_map;
 
 			#ifdef __powerpc64__
-			user_sr = 0;
-			__asm ("slbmfev %0, %1"
-			    : "=r"(user_sr)
-			    : "r"(USER_SR));
-
-			PMAP_LOCK(&p->p_vmspace->vm_pmap);
-			user_sr >>= SLBV_VSID_SHIFT;
-			rv = vsid_to_esid(&p->p_vmspace->vm_pmap, user_sr,
-			    &user_sr);
-			PMAP_UNLOCK(&p->p_vmspace->vm_pmap);
-
-			if (rv != 0) 
-				return (SIGSEGV);
+			user_sr = td->td_pcb->pcb_cpu.aim.usr_segm;
 			#else
 			__asm ("mfsr %0, %1"
 			    : "=r"(user_sr)
diff --git a/sys/powerpc/include/pcb.h b/sys/powerpc/include/pcb.h
index b30b4196816..65e3c1765ac 100644
--- a/sys/powerpc/include/pcb.h
+++ b/sys/powerpc/include/pcb.h
@@ -66,6 +66,7 @@ struct pcb {
 
 	union {
 		struct {
+			vm_offset_t	usr_segm;	/* Base address */
 			register_t	usr_esid;	/* USER_SR segment */
 			register_t	usr_vsid;	/* USER_SR segment */
 		} aim;
diff --git a/sys/powerpc/include/pmap.h b/sys/powerpc/include/pmap.h
index 453964fcc4c..52ec3459365 100644
--- a/sys/powerpc/include/pmap.h
+++ b/sys/powerpc/include/pmap.h
@@ -86,15 +86,13 @@ struct pmap_md {
 #define	NPMAPS		32768
 #endif /* !defined(NPMAPS) */
 
-struct	slbcontainer;
-
-SPLAY_HEAD(slb_tree, slbcontainer);
+struct	slbtnode;
 
 struct	pmap {
 	struct	mtx	pm_mtx;
 	
     #ifdef __powerpc64__
-	struct slb_tree	pm_slbtree;
+	struct slbtnode	*pm_slb_tree_root;
 	struct slb	*pm_slb;
     #else
 	register_t	pm_sr[16];
@@ -139,12 +137,17 @@ struct	md_page {
  * NB: The PMAP MUST be locked already.
  */
 uint64_t va_to_vsid(pmap_t pm, vm_offset_t va);
-int      va_to_slb_entry(pmap_t pm, vm_offset_t va, struct slb *);
+
+/* Lock-free, non-allocating lookup routines */
+uint64_t kernel_va_to_slbv(vm_offset_t va);
+struct slb *user_va_to_slb_entry(pmap_t pm, vm_offset_t va);
 
 uint64_t allocate_vsid(pmap_t pm, uint64_t esid, int large);
-void     slb_insert(pmap_t pm, struct slb *dst, struct slb *);
-int      vsid_to_esid(pmap_t pm, uint64_t vsid, uint64_t *esid);
-void     free_vsids(pmap_t pm);
+void	free_vsid(pmap_t pm, uint64_t esid, int large);
+void	slb_insert(pmap_t pm, struct slb *dst, struct slb *);
+
+struct slbtnode *slb_alloc_tree(void);
+void     slb_free_tree(pmap_t pm);
 struct slb *slb_alloc_user_cache(void);
 void	slb_free_user_cache(struct slb *);
 

From c59528330a3d3dd213df8c818119d3e06b1201f0 Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Thu, 16 Sep 2010 02:59:25 +0000
Subject: [PATCH 0798/1624] Few whitespace cleanups and comments tunings.

Submitted by:	arundel
---
 sys/x86/cpufreq/est.c | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/sys/x86/cpufreq/est.c b/sys/x86/cpufreq/est.c
index 144858c9451..ecca30cf59d 100644
--- a/sys/x86/cpufreq/est.c
+++ b/sys/x86/cpufreq/est.c
@@ -110,14 +110,16 @@ CTASSERT(EST_MAX_SETTINGS <= MAX_SETTINGS);
 #define EST_TRANS_LAT		1000
 
 /*
- * Frequency (MHz) and voltage (mV) settings.  Data from the
- * Intel Pentium M Processor Datasheet (Order Number 252612), Table 5.
+ * Frequency (MHz) and voltage (mV) settings.
  *
  * Dothan processors have multiple VID#s with different settings for
  * each VID#.  Since we can't uniquely identify this info
  * without undisclosed methods from Intel, we can't support newer
  * processors with this table method.  If ACPI Px states are supported,
  * we get info from them.
+ *
+ * Data from the "Intel Pentium M Processor Datasheet",
+ * Order Number 252612-003, Table 5.
  */
 static freq_info PM17_130[] = {
 	/* 130nm 1.70GHz Pentium M */
@@ -217,7 +219,7 @@ static freq_info PM10_ULV_130[] = {
 
 /*
  * Data from "Intel Pentium M Processor on 90nm Process with
- * 2-MB L2 Cache Datasheet", Order Number 302189, Table 5.
+ * 2-MB L2 Cache Datasheet", Order Number 302189-008, Table 5.
  */
 static freq_info PM_765A_90[] = {
 	/* 90 nm 2.10GHz Pentium M, VID #A */
@@ -985,7 +987,7 @@ est_probe(device_t dev)
 	device_t perf_dev;
 	uint64_t msr;
 	int error, type;
-        
+
 	if (resource_disabled("est", 0))
 		return (ENXIO);
 
@@ -1125,7 +1127,7 @@ est_acpi_info(device_t dev, freq_info **freqs)
 		if (sets[i].freq > 0) {
 			error = est_set_id16(dev, sets[i].spec[0], strict);
 			if (error != 0) {
-				if (bootverbose) 
+				if (bootverbose)
 					device_printf(dev, "Invalid freq %u, "
 					    "ignored.\n", sets[i].freq);
 				continue;
@@ -1221,7 +1223,7 @@ est_msr_info(device_t dev, uint64_t msr, freq_info **freqs)
 		device_printf(dev, "Guessed bus clock (low) of %d MHz\n", bus);
 		if (!bus_speed_ok(bus))
 			return (EOPNOTSUPP);
-		
+
 		/* Calculate high frequency. */
 		id = msr >> 32;
 		freq = ((id >> 8) & 0xff) * bus;
@@ -1282,14 +1284,14 @@ est_set_id16(device_t dev, uint16_t id16, int need_check)
 	msr = rdmsr(MSR_PERF_CTL);
 	msr = (msr & ~0xffff) | id16;
 	wrmsr(MSR_PERF_CTL, msr);
-	
+
 	/* Wait a short while for the new setting.  XXX Is this necessary? */
 	DELAY(EST_TRANS_LAT);
-	
+
 	if  (need_check) {
-		est_get_id16(&new_id16);		
+		est_get_id16(&new_id16);
 		if (new_id16 != id16) {
-			if (bootverbose) 
+			if (bootverbose)
 				device_printf(dev, "Invalid id16 (set, cur) "
 				    "= (%u, %u)\n", id16, new_id16);
 			ret = ENXIO;

From 6416b9a85d3c5a08a72bf3de0ee319b021812f38 Mon Sep 17 00:00:00 2001
From: Nathan Whitehorn 
Date: Thu, 16 Sep 2010 03:46:17 +0000
Subject: [PATCH 0799/1624] Split the SLB mirror cache into two kinds of
 object, one for kernel maps which are similar to the previous ones, and one
 for user maps, which are arrays of pointers into the SLB tree. This changes
 makes user SLB updates atomic, closing a window for memory corruption. While
 here, rearrange the allocation functions to make context switches faster.

---
 sys/powerpc/aim/mmu_oea64.c   |  3 +-
 sys/powerpc/aim/slb.c         | 84 ++++++++++++++++++++---------------
 sys/powerpc/aim/trap.c        | 18 ++++----
 sys/powerpc/aim/trap_subr64.S | 66 ++++++++++++++++-----------
 sys/powerpc/include/pcpu.h    |  2 +-
 sys/powerpc/include/pmap.h    | 12 ++---
 sys/powerpc/include/sr.h      |  4 ++
 7 files changed, 110 insertions(+), 79 deletions(-)

diff --git a/sys/powerpc/aim/mmu_oea64.c b/sys/powerpc/aim/mmu_oea64.c
index f0a6cd69c63..11a99576b5d 100644
--- a/sys/powerpc/aim/mmu_oea64.c
+++ b/sys/powerpc/aim/mmu_oea64.c
@@ -838,7 +838,7 @@ moea64_bootstrap_slb_prefault(vm_offset_t va, int large)
 	if (large)
 		entry.slbv |= SLBV_L;
 
-	slb_insert(kernel_pmap, cache, &entry);
+	slb_insert_kernel(entry.slbe, entry.slbv);
 }
 #endif
 
@@ -2099,6 +2099,7 @@ moea64_pinit(mmu_t mmu, pmap_t pmap)
 
 	pmap->pm_slb_tree_root = slb_alloc_tree();
 	pmap->pm_slb = slb_alloc_user_cache();
+	pmap->pm_slb_len = 0;
 }
 #else
 void
diff --git a/sys/powerpc/aim/slb.c b/sys/powerpc/aim/slb.c
index 3d3aecddc0d..e7bdaf85b94 100644
--- a/sys/powerpc/aim/slb.c
+++ b/sys/powerpc/aim/slb.c
@@ -263,13 +263,14 @@ va_to_vsid(pmap_t pm, vm_offset_t va)
 	entry = user_va_to_slb_entry(pm, va);
 
 	if (entry == NULL)
-		return (allocate_vsid(pm, (uintptr_t)va >> ADDR_SR_SHFT, 0));
+		return (allocate_user_vsid(pm,
+		    (uintptr_t)va >> ADDR_SR_SHFT, 0));
 
 	return ((entry->slbv & SLBV_VSID_MASK) >> SLBV_VSID_SHIFT);
 }
 
 uint64_t
-allocate_vsid(pmap_t pm, uint64_t esid, int large)
+allocate_user_vsid(pmap_t pm, uint64_t esid, int large)
 {
 	uint64_t vsid, slbv;
 	struct slbtnode *ua, *next, *inter;
@@ -327,7 +328,7 @@ allocate_vsid(pmap_t pm, uint64_t esid, int large)
 	 * SLB mapping, so pre-spill this entry.
 	 */
 	eieio();
-	slb_insert(pm, pm->pm_slb, slb);
+	slb_insert_user(pm, slb);
 
 	return (vsid);
 }
@@ -410,57 +411,68 @@ slb_alloc_tree(void)
 	    (slbe & SLBE_ESID_MASK) > 16*SEGMENT_LENGTH) || \
 	    (slbe & SLBE_ESID_MASK) > VM_MAX_KERNEL_ADDRESS)
 void
-slb_insert(pmap_t pm, struct slb *slbcache, struct slb *slb_entry)
+slb_insert_kernel(uint64_t slbe, uint64_t slbv)
 {
-	uint64_t slbe, slbv;
-	int i, j, to_spill;
+	struct slb *slbcache;
+	int i, j;
 
 	/* We don't want to be preempted while modifying the kernel map */
 	critical_enter();
 
-	to_spill = -1;
-	slbv = slb_entry->slbv;
-	slbe = slb_entry->slbe;
+	slbcache = PCPU_GET(slb);
 
-	/* Hunt for a likely candidate */
-
-	for (i = mftb() % 64, j = 0; j < 64; j++, i = (i+1) % 64) {
-		if (pm == kernel_pmap && i == USER_SR)
-				continue;
-
-		if (!(slbcache[i].slbe & SLBE_VALID)) {
-			to_spill = i;
-			break;
+	/* Check for an unused slot, abusing the USER_SR slot as a full flag */
+	if (slbcache[USER_SR].slbe == 0) {
+		for (i = 0; i < USER_SR; i++) {
+			if (!(slbcache[i].slbe & SLBE_VALID)) 
+				goto fillkernslb;
 		}
 
-		if (to_spill < 0 && (pm != kernel_pmap ||
-		    SLB_SPILLABLE(slbcache[i].slbe)))
-			to_spill = i;
+		if (i == USER_SR)
+			slbcache[USER_SR].slbe = 1;
 	}
 
-	if (to_spill < 0)
-		panic("SLB spill on ESID %#lx, but no available candidates!\n",
-		   (slbe & SLBE_ESID_MASK) >> SLBE_ESID_SHIFT);
+	for (i = mftb() % 64, j = 0; j < 64; j++, i = (i+1) % 64) {
+		if (i == USER_SR)
+			continue;
 
-	if (slbcache[to_spill].slbe & SLBE_VALID) {
-		/* Invalidate this first to avoid races */
-		slbcache[to_spill].slbe = 0;
-		mb();
+		if (SLB_SPILLABLE(slbcache[i].slbe))
+			break;
 	}
-	slbcache[to_spill].slbv = slbv;
-	slbcache[to_spill].slbe = slbe | (uint64_t)to_spill;
+
+	KASSERT(j < 64, ("All kernel SLB slots locked!"));
+
+fillkernslb:
+	slbcache[i].slbv = slbv;
+	slbcache[i].slbe = slbe | (uint64_t)i;
 
 	/* If it is for this CPU, put it in the SLB right away */
-	if (pm == kernel_pmap && pmap_bootstrapped) {
+	if (pmap_bootstrapped) {
 		/* slbie not required */
 		__asm __volatile ("slbmte %0, %1" :: 
-		    "r"(slbcache[to_spill].slbv),
-		    "r"(slbcache[to_spill].slbe)); 
+		    "r"(slbcache[i].slbv), "r"(slbcache[i].slbe)); 
 	}
 
 	critical_exit();
 }
 
+void
+slb_insert_user(pmap_t pm, struct slb *slb)
+{
+	int i;
+
+	PMAP_LOCK_ASSERT(pm, MA_OWNED);
+
+	if (pm->pm_slb_len < 64) {
+		i = pm->pm_slb_len;
+		pm->pm_slb_len++;
+	} else {
+		i = mftb() % 64;
+	}
+
+	/* Note that this replacement is atomic with respect to trap_subr */
+	pm->pm_slb[i] = slb;
+}
 
 static void
 slb_zone_init(void *dummy)
@@ -468,18 +480,18 @@ slb_zone_init(void *dummy)
 
 	slbt_zone = uma_zcreate("SLB tree node", sizeof(struct slbtnode),
 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
-	slb_cache_zone = uma_zcreate("SLB cache", 64*sizeof(struct slb),
+	slb_cache_zone = uma_zcreate("SLB cache", 64*sizeof(struct slb *),
 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
 }
 
-struct slb *
+struct slb **
 slb_alloc_user_cache(void)
 {
 	return (uma_zalloc(slb_cache_zone, M_ZERO));
 }
 
 void
-slb_free_user_cache(struct slb *slb)
+slb_free_user_cache(struct slb **slb)
 {
 	uma_zfree(slb_cache_zone, slb);
 }
diff --git a/sys/powerpc/aim/trap.c b/sys/powerpc/aim/trap.c
index aafdb6955ca..6130eab746c 100644
--- a/sys/powerpc/aim/trap.c
+++ b/sys/powerpc/aim/trap.c
@@ -445,17 +445,15 @@ syscall(struct trapframe *frame)
 static int 
 handle_slb_spill(pmap_t pm, vm_offset_t addr)
 {
-	struct slb kern_entry, *user_entry;
+	struct slb *user_entry;
 	uint64_t esid;
 	int i;
 
 	esid = (uintptr_t)addr >> ADDR_SR_SHFT;
 
 	if (pm == kernel_pmap) {
-		kern_entry.slbv = kernel_va_to_slbv(addr);
-		kern_entry.slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
-
-		slb_insert(pm, PCPU_GET(slb), &kern_entry);
+		slb_insert_kernel((esid << SLBE_ESID_SHIFT) | SLBE_VALID,
+		    kernel_va_to_slbv(addr));
 		return (0);
 	}
 
@@ -464,18 +462,18 @@ handle_slb_spill(pmap_t pm, vm_offset_t addr)
 
 	if (user_entry == NULL) {
 		/* allocate_vsid auto-spills it */
-		(void)allocate_vsid(pm, esid, 0);
+		(void)allocate_user_vsid(pm, esid, 0);
 	} else {
 		/*
 		 * Check that another CPU has not already mapped this.
 		 * XXX: Per-thread SLB caches would be better.
 		 */
-		for (i = 0; i < 64; i++)
-			if (pm->pm_slb[i].slbe == (user_entry->slbe | i))
+		for (i = 0; i < pm->pm_slb_len; i++)
+			if (pm->pm_slb[i] == user_entry)
 				break;
 
-		if (i == 64)
-			slb_insert(pm, pm->pm_slb, user_entry);
+		if (i == pm->pm_slb_len)
+			slb_insert_user(pm, user_entry);
 	}
 	PMAP_UNLOCK(pm);
 
diff --git a/sys/powerpc/aim/trap_subr64.S b/sys/powerpc/aim/trap_subr64.S
index 680de100707..e0dae3ccb42 100644
--- a/sys/powerpc/aim/trap_subr64.S
+++ b/sys/powerpc/aim/trap_subr64.S
@@ -49,45 +49,59 @@
  * Requires that r28-r31 be scratch, with r28 initialized to the SLB cache
  */
 
-restoresrs: 
+/*
+ * User SRs are loaded through a pointer to the current pmap.
+ */
+restore_usersrs:
+	GET_CPUINFO(%r28);
+	ld	%r28,PC_USERSLB(%r28);
 	li	%r29, 0			/* Set the counter to zero */
 
 	slbia
 	slbmfee	%r31,%r29		
 	clrrdi	%r31,%r31,28
 	slbie	%r31
-instslb:
-	ld	%r31, 8(%r28);		/* Load SLBE */
+instuserslb:
+	ld	%r31, 0(%r28);		/* Load SLB entry pointer */
+	cmpli	0, %r31, 0;		/* If NULL, stop */
+	beqlr;
 
-	cmpli	0, %r31, 0;		/* If SLBE is not valid, get the next */
-	beq	nslb;
-
-	ld	%r30, 0(%r28)		/* Load SLBV */
+	ld	%r30, 0(%r31)		/* Load SLBV */
+	ld	%r31, 8(%r31)		/* Load SLBE */
+	or	%r31, %r31, %r29	/*  Set SLBE slot */
 	slbmte	%r30, %r31;		/* Install SLB entry */
 
-nslb:
-	addi	%r28, %r28, 16;		/* Advance */
+	addi	%r28, %r28, 8;		/* Advance pointer */
 	addi	%r29, %r29, 1;
 	cmpli	0, %r29, 64;		/* Repeat if we are not at the end */
-	blt instslb;
-
+	blt instuserslb;
 	blr;
 
 /*
- * User SRs are loaded through a pointer to the current pmap.
+ * Kernel SRs are loaded directly from the PCPU fields
  */
-#define RESTORE_USER_SRS() \
-	GET_CPUINFO(%r28); \
-	ld	%r28,PC_USERSLB(%r28); \
-	bl	restoresrs;
+restore_kernsrs:
+	GET_CPUINFO(%r28);
+	addi	%r28,%r28,PC_KERNSLB;
+	li	%r29, 0			/* Set the counter to zero */
 
-/*
- * Kernel SRs are loaded directly from kernel_pmap_
- */
-#define RESTORE_KERN_SRS() \
-	GET_CPUINFO(%r28); \
-	addi	%r28,%r28,PC_KERNSLB; \
-	bl	restoresrs;
+	slbia
+	slbmfee	%r31,%r29		
+	clrrdi	%r31,%r31,28
+	slbie	%r31
+instkernslb:
+	ld	%r31, 8(%r28);		/* Load SLBE */
+
+	cmpli	0, %r31, 0;		/* If SLBE is not valid, stop */
+	beqlr;
+	ld	%r30, 0(%r28)		/* Load SLBV  */
+	slbmte	%r30, %r31;		/* Install SLB entry */
+
+	addi	%r28, %r28, 16;		/* Advance pointer */
+	addi	%r29, %r29, 1;
+	cmpli	0, %r29, USER_SR;	/* Repeat if we are not at the end */
+	blt instkernslb;
+	blr;
 
 /*
  * FRAME_SETUP assumes:
@@ -237,7 +251,7 @@ nslb:
 	std	%r30,(savearea+CPUSAVE_R30)(%r3);			\
 	std	%r31,(savearea+CPUSAVE_R31)(%r3);			\
 	mflr	%r27;			/* preserve LR */		\
-	RESTORE_USER_SRS();		/* uses r28-r31 */		\
+	bl	restore_usersrs;	/* uses r28-r31 */		\
 	mtlr	%r27;							\
 	ld	%r31,(savearea+CPUSAVE_R31)(%r3);			\
 	ld	%r30,(savearea+CPUSAVE_R30)(%r3);			\
@@ -432,7 +446,7 @@ realtrap:
 	ld	%r1,PC_CURPCB(%r1)
 	mr	%r27,%r28		/* Save LR, r29 */
 	mtsprg2	%r29
-	RESTORE_KERN_SRS()		/* enable kernel mapping */
+	bl	restore_kernsrs		/* enable kernel mapping */
 	mfsprg2	%r29
 	mr	%r28,%r27
 	ba s_trap
@@ -482,7 +496,7 @@ u_trap:
 	ld	%r1,PC_CURPCB(%r1)
 	mr	%r27,%r28		/* Save LR, r29 */
 	mtsprg2	%r29
-	RESTORE_KERN_SRS() /* enable kernel mapping */
+	bl	restore_kernsrs		/* enable kernel mapping */
 	mfsprg2	%r29
 	mr	%r28,%r27
 
diff --git a/sys/powerpc/include/pcpu.h b/sys/powerpc/include/pcpu.h
index 0d29b506fc9..949bbf39133 100644
--- a/sys/powerpc/include/pcpu.h
+++ b/sys/powerpc/include/pcpu.h
@@ -55,7 +55,7 @@ struct pmap;
 
 #define PCPU_MD_AIM64_FIELDS						\
 	struct slb	pc_slb[64];					\
-	struct slb	*pc_userslb;
+	struct slb	**pc_userslb;
 
 #ifdef __powerpc64__
 #define PCPU_MD_AIM_FIELDS	PCPU_MD_AIM64_FIELDS
diff --git a/sys/powerpc/include/pmap.h b/sys/powerpc/include/pmap.h
index 52ec3459365..f2d2a13c578 100644
--- a/sys/powerpc/include/pmap.h
+++ b/sys/powerpc/include/pmap.h
@@ -93,7 +93,8 @@ struct	pmap {
 	
     #ifdef __powerpc64__
 	struct slbtnode	*pm_slb_tree_root;
-	struct slb	*pm_slb;
+	struct slb	**pm_slb;
+	int		pm_slb_len;
     #else
 	register_t	pm_sr[16];
     #endif
@@ -142,14 +143,15 @@ uint64_t va_to_vsid(pmap_t pm, vm_offset_t va);
 uint64_t kernel_va_to_slbv(vm_offset_t va);
 struct slb *user_va_to_slb_entry(pmap_t pm, vm_offset_t va);
 
-uint64_t allocate_vsid(pmap_t pm, uint64_t esid, int large);
+uint64_t allocate_user_vsid(pmap_t pm, uint64_t esid, int large);
 void	free_vsid(pmap_t pm, uint64_t esid, int large);
-void	slb_insert(pmap_t pm, struct slb *dst, struct slb *);
+void	slb_insert_user(pmap_t pm, struct slb *slb);
+void	slb_insert_kernel(uint64_t slbe, uint64_t slbv);
 
 struct slbtnode *slb_alloc_tree(void);
 void     slb_free_tree(pmap_t pm);
-struct slb *slb_alloc_user_cache(void);
-void	slb_free_user_cache(struct slb *);
+struct slb **slb_alloc_user_cache(void);
+void	slb_free_user_cache(struct slb **);
 
 #else
 
diff --git a/sys/powerpc/include/sr.h b/sys/powerpc/include/sr.h
index ae66314de6d..ed9801a2891 100644
--- a/sys/powerpc/include/sr.h
+++ b/sys/powerpc/include/sr.h
@@ -42,7 +42,11 @@
 #define	SR_VSID_MASK	0x00ffffff	/* Virtual Segment ID mask */
 
 /* Kernel segment register usage */
+#ifdef __powerpc64__
+#define	USER_SR		63
+#else
 #define	USER_SR		12
+#endif
 #define	KERNEL_SR	13
 #define	KERNEL2_SR	14
 #define	KERNEL3_SR	15

From 6e7a4f6c3648f4056b690635ed57d455bf7188f7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= 
Date: Thu, 16 Sep 2010 07:56:34 +0000
Subject: [PATCH 0800/1624] Implement proc/$$/environment.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Submitted by:	Fernando Apesteguía 
MFC after:	3 weeks
---
 sys/compat/linprocfs/linprocfs.c | 112 ++++++++++++++++++++++++++++++-
 1 file changed, 110 insertions(+), 2 deletions(-)

diff --git a/sys/compat/linprocfs/linprocfs.c b/sys/compat/linprocfs/linprocfs.c
index 974f825ea52..c7fe1581982 100644
--- a/sys/compat/linprocfs/linprocfs.c
+++ b/sys/compat/linprocfs/linprocfs.c
@@ -939,15 +939,123 @@ linprocfs_doproccmdline(PFS_FILL_ARGS)
 	return (0);
 }
 
+extern int proc_rwmem(struct proc *p, struct uio *uio);
+
+#define MAX_ARGV_STR	512	/* Max number of argv-like strings */
+#define UIO_CHUNK_SZ	256	/* Max chunk size (bytes) for uiomove */
+
+static int
+linprocfs_doargv(struct thread *td, struct proc *p, struct sbuf *sb,
+	void (*resolver)(const struct ps_strings, u_long *, int *))
+{
+	struct iovec iov;
+	struct uio tmp_uio;
+	struct ps_strings pss;
+	int ret, i, n_elements, found_end;
+	u_long addr;
+	char* env_vector[MAX_ARGV_STR];
+	char env_string[UIO_CHUNK_SZ];
+	char *pbegin;
+
+
+
+#define	UIO_HELPER(uio, iov, base, len, cnt, offset, sz, flg, rw, td)	\
+do {									\
+	iov.iov_base = (caddr_t)(base);					\
+	iov.iov_len = (len); 						\
+	uio.uio_iov = &(iov); 						\
+	uio.uio_iovcnt = (cnt);	 					\
+	uio.uio_offset = (off_t)(offset);				\
+	uio.uio_resid = (sz); 						\
+	uio.uio_segflg = (flg);						\
+	uio.uio_rw = (rw); 						\
+	uio.uio_td = (td);						\
+} while (0)
+
+	UIO_HELPER(tmp_uio, iov, &pss, sizeof(struct ps_strings), 1,
+	    (off_t)(p->p_sysent->sv_psstrings), sizeof(struct ps_strings),
+	    UIO_SYSSPACE, UIO_READ, td);
+
+	ret = proc_rwmem(p, &tmp_uio);
+	if (ret != 0)
+		return ret;
+
+	/* Get the array address and the number of elements */
+	resolver(pss, &addr, &n_elements);
+
+	/* Consistent with lib/libkvm/kvm_proc.c */
+	if (n_elements > MAX_ARGV_STR || (u_long)addr < VM_MIN_ADDRESS ||
+    	    (u_long)addr >= VM_MAXUSER_ADDRESS) {
+		/* What error code should we return? */
+		return 0;
+	}
+
+ 	UIO_HELPER(tmp_uio, iov, env_vector, MAX_ARGV_STR, 1,
+	    (vm_offset_t)(addr), iov.iov_len, UIO_SYSSPACE, UIO_READ, td);
+
+	ret = proc_rwmem(p, &tmp_uio);
+	if (ret != 0)
+		return ret;
+
+	/* Now we can iterate through the list of strings */
+	for (i = 0; i < n_elements; i++) {
+	    found_end = 0;
+	    pbegin = env_vector[i];
+		while(!found_end) {
+		    UIO_HELPER(tmp_uio, iov, env_string, sizeof(env_string), 1,
+			(vm_offset_t) pbegin, iov.iov_len, UIO_SYSSPACE,
+			UIO_READ, td);
+
+			ret = proc_rwmem(p, &tmp_uio);
+			if (ret != 0)
+				return ret;
+
+			if (!strvalid(env_string, UIO_CHUNK_SZ)) {
+			    /*
+			     * We didn't find the end of the string
+			     * Add the string to the buffer and move
+			     * the pointer
+			     */
+			    sbuf_bcat(sb, env_string, UIO_CHUNK_SZ);
+			    pbegin = &(*pbegin) + UIO_CHUNK_SZ;
+			} else {
+			    found_end = 1;
+			}
+		}
+		sbuf_printf(sb, "%s", env_string);
+	}
+
+#undef UIO_HELPER
+
+	return (0);
+}
+
+static void
+ps_string_env(const struct ps_strings ps, u_long *addr, int *n)
+{
+
+	*addr = (u_long) ps.ps_envstr;
+	*n = ps.ps_nenvstr;
+}
+
 /*
  * Filler function for proc/pid/environ
  */
 static int
 linprocfs_doprocenviron(PFS_FILL_ARGS)
 {
+	int ret;
 
-	sbuf_printf(sb, "doprocenviron\n%c", '\0');
-	return (0);
+	PROC_LOCK(p);
+
+	if ((ret = p_cansee(td, p)) != 0) {
+		PROC_UNLOCK(p);
+		return ret;
+	}
+
+	ret = linprocfs_doargv(td, p, sb, ps_string_env);
+	PROC_UNLOCK(p);
+	return (ret);
 }
 
 /*

From 6a5ffa0630f04b82c7586ea7ac5d936f00673f65 Mon Sep 17 00:00:00 2001
From: Brian Somers 
Date: Thu, 16 Sep 2010 08:16:53 +0000
Subject: [PATCH 0801/1624] Add support for identifying a journaled root
 filesystem. Fix support for identifying the given /dev/vinum/root example.

MFC after:	3 weeks
---
 sbin/fdisk/fdisk.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sbin/fdisk/fdisk.c b/sbin/fdisk/fdisk.c
index c53ef8556df..0495a690ea8 100644
--- a/sbin/fdisk/fdisk.c
+++ b/sbin/fdisk/fdisk.c
@@ -1462,6 +1462,7 @@ sanitize_partition(struct dos_partition *partp)
  *   /dev/da0a       => /dev/da0
  *   /dev/vinum/root => /dev/vinum/root
  * A ".eli" part is removed if it exists (see geli(8)).
+ * A ".journal" ending is removed if it exists (see gjournal(8)).
  */
 static char *
 get_rootdisk(void)
@@ -1476,7 +1477,7 @@ get_rootdisk(void)
 	if (statfs("/", &rootfs) == -1)
 		err(1, "statfs(\"/\")");
 
-	if ((rv = regcomp(&re, "^(/dev/[a-z/]+[0-9]+)([sp][0-9]+)?[a-h]?$",
+	if ((rv = regcomp(&re, "^(/dev/[a-z/]+[0-9]*)([sp][0-9]+)?[a-h]?(\\.journal)?$",
 		    REG_EXTENDED)) != 0)
 		errx(1, "regcomp() failed (%d)", rv);
 	strlcpy(dev, rootfs.f_mntfromname, sizeof (dev));

From 65f2c0ff587a41a964b6dc809466bb42fc3a5ab8 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Thu, 16 Sep 2010 09:29:48 +0000
Subject: [PATCH 0802/1624] Merge r207585 from cas(4): - Don't probe for PHYs
 if we already know to use a SERDES. Unlike as with   cas(4) this only serves
 to speed up the the device attach though and can   only be determined via the
 OFW device tree but not from the VPD. - Don't touch the MIF when using a
 SERDES. - Add some missing bus space barriers, mainly in the PCS code path.

---
 sys/dev/gem/if_gem.c      | 36 ++++++++++++++++++++++++++++++++----
 sys/dev/gem/if_gem_pci.c  | 14 +++++++++++++-
 sys/dev/gem/if_gem_sbus.c |  2 ++
 sys/modules/gem/Makefile  |  9 +++++++--
 4 files changed, 54 insertions(+), 7 deletions(-)

diff --git a/sys/dev/gem/if_gem.c b/sys/dev/gem/if_gem.c
index 6edb49e2f85..8be68abaf78 100644
--- a/sys/dev/gem/if_gem.c
+++ b/sys/dev/gem/if_gem.c
@@ -268,10 +268,17 @@ gem_attach(struct gem_softc *sc)
 		sc->sc_rxsoft[i].rxs_mbuf = NULL;
 	}
 
+	/* Bypass probing PHYs if we already know for sure to use a SERDES. */
+	if ((sc->sc_flags & GEM_SERDES) != 0)
+		goto serdes;
+
 	/* Bad things will happen when touching this register on ERI. */
-	if (sc->sc_variant != GEM_SUN_ERI)
+	if (sc->sc_variant != GEM_SUN_ERI) {
 		GEM_BANK1_WRITE_4(sc, GEM_MII_DATAPATH_MODE,
 		    GEM_MII_DATAPATH_MII);
+		GEM_BANK1_BARRIER(sc, GEM_MII_DATAPATH_MODE, 4,
+		    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
+	}
 
 	gem_mifinit(sc);
 
@@ -283,6 +290,8 @@ gem_attach(struct gem_softc *sc)
 	if ((v & GEM_MIF_CONFIG_MDI1) != 0) {
 		v |= GEM_MIF_CONFIG_PHY_SEL;
 		GEM_BANK1_WRITE_4(sc, GEM_MIF_CONFIG, v);
+		GEM_BANK1_BARRIER(sc, GEM_MIF_CONFIG, 4,
+		    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
 		switch (sc->sc_variant) {
 		case GEM_SUN_ERI:
 			sc->sc_phyad = GEM_PHYAD_EXTERNAL;
@@ -304,6 +313,8 @@ gem_attach(struct gem_softc *sc)
 	    ((v & GEM_MIF_CONFIG_MDI0) != 0 || GEM_IS_APPLE(sc))) {
 		v &= ~GEM_MIF_CONFIG_PHY_SEL;
 		GEM_BANK1_WRITE_4(sc, GEM_MIF_CONFIG, v);
+		GEM_BANK1_BARRIER(sc, GEM_MIF_CONFIG, 4,
+		    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
 		switch (sc->sc_variant) {
 		case GEM_SUN_ERI:
 		case GEM_APPLE_K2_GMAC:
@@ -324,17 +335,23 @@ gem_attach(struct gem_softc *sc)
 	 * Try the external PCS SERDES if we didn't find any PHYs.
 	 */
 	if (error != 0 && sc->sc_variant == GEM_SUN_GEM) {
+ serdes:
 		GEM_BANK1_WRITE_4(sc, GEM_MII_DATAPATH_MODE,
 		    GEM_MII_DATAPATH_SERDES);
+		GEM_BANK1_BARRIER(sc, GEM_MII_DATAPATH_MODE, 4,
+		    BUS_SPACE_BARRIER_WRITE);
 		GEM_BANK1_WRITE_4(sc, GEM_MII_SLINK_CONTROL,
 		    GEM_MII_SLINK_LOOPBACK | GEM_MII_SLINK_EN_SYNC_D);
+		GEM_BANK1_BARRIER(sc, GEM_MII_SLINK_CONTROL, 4,
+		    BUS_SPACE_BARRIER_WRITE);
 		GEM_BANK1_WRITE_4(sc, GEM_MII_CONFIG, GEM_MII_CONFIG_ENABLE);
+		GEM_BANK1_BARRIER(sc, GEM_MII_CONFIG, 4,
+		    BUS_SPACE_BARRIER_WRITE);
 		sc->sc_flags |= GEM_SERDES;
 		sc->sc_phyad = GEM_PHYAD_EXTERNAL;
 		error = mii_phy_probe(sc->sc_dev, &sc->sc_miibus,
 		    gem_mediachange, gem_mediastatus);
 	}
-
 	if (error != 0) {
 		device_printf(sc->sc_dev, "PHY probe failed: %d\n", error);
 		goto fail_rxd;
@@ -918,8 +935,9 @@ gem_init_locked(struct gem_softc *sc)
 	    __func__);
 #endif
 
-	/* Re-initialize the MIF. */
-	gem_mifinit(sc);
+	if ((sc->sc_flags & GEM_SERDES) == 0)
+		/* Re-initialize the MIF. */
+		gem_mifinit(sc);
 
 	/* step 3.  Setup data structures in host memory. */
 	if (gem_meminit(sc) != 0)
@@ -1800,6 +1818,8 @@ gem_mifinit(struct gem_softc *sc)
 	/* Configure the MIF in frame mode. */
 	GEM_BANK1_WRITE_4(sc, GEM_MIF_CONFIG,
 	    GEM_BANK1_READ_4(sc, GEM_MIF_CONFIG) & ~GEM_MIF_CONFIG_BB_ENA);
+	GEM_BANK1_BARRIER(sc, GEM_MIF_CONFIG, 4,
+	    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
 }
 
 /*
@@ -1914,10 +1934,16 @@ gem_mii_writereg(device_t dev, int phy, int reg, int val)
 			GEM_BANK1_BARRIER(sc, GEM_MII_CONFIG, 4,
 			    BUS_SPACE_BARRIER_WRITE);
 			GEM_BANK1_WRITE_4(sc, GEM_MII_ANAR, val);
+			GEM_BANK1_BARRIER(sc, GEM_MII_ANAR, 4,
+			    BUS_SPACE_BARRIER_WRITE);
 			GEM_BANK1_WRITE_4(sc, GEM_MII_SLINK_CONTROL,
 			    GEM_MII_SLINK_LOOPBACK | GEM_MII_SLINK_EN_SYNC_D);
+			GEM_BANK1_BARRIER(sc, GEM_MII_SLINK_CONTROL, 4,
+			    BUS_SPACE_BARRIER_WRITE);
 			GEM_BANK1_WRITE_4(sc, GEM_MII_CONFIG,
 			    GEM_MII_CONFIG_ENABLE);
+			GEM_BANK1_BARRIER(sc, GEM_MII_CONFIG, 4,
+			    BUS_SPACE_BARRIER_WRITE);
 			return (0);
 		case MII_ANLPAR:
 			reg = GEM_MII_ANLPAR;
@@ -1928,6 +1954,8 @@ gem_mii_writereg(device_t dev, int phy, int reg, int val)
 			return (0);
 		}
 		GEM_BANK1_WRITE_4(sc, reg, val);
+		GEM_BANK1_BARRIER(sc, reg, 4,
+		    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
 		return (0);
 	}
 
diff --git a/sys/dev/gem/if_gem_pci.c b/sys/dev/gem/if_gem_pci.c
index 051dbcc5bfb..cfea337312c 100644
--- a/sys/dev/gem/if_gem_pci.c
+++ b/sys/dev/gem/if_gem_pci.c
@@ -52,6 +52,7 @@ __FBSDID("$FreeBSD$");
 
 #include 
 #if defined(__powerpc__) || defined(__sparc64__)
+#include 
 #include 
 #include 
 #endif
@@ -140,12 +141,17 @@ static struct resource_spec gem_pci_res_spec[] = {
 	{ -1, 0 }
 };
 
+#define	GEM_SHARED_PINS		"shared-pins"
+#define	GEM_SHARED_PINS_SERDES	"serdes"
+
 static int
 gem_pci_attach(device_t dev)
 {
 	struct gem_softc *sc;
 	int i;
-#if !(defined(__powerpc__) || defined(__sparc64__))
+#if defined(__powerpc__) || defined(__sparc64__)
+	char buf[sizeof(GEM_SHARED_PINS)];
+#else
 	int j;
 #endif
 
@@ -207,6 +213,12 @@ gem_pci_attach(device_t dev)
 
 #if defined(__powerpc__) || defined(__sparc64__)
 	OF_getetheraddr(dev, sc->sc_enaddr);
+	if (OF_getprop(ofw_bus_get_node(dev), GEM_SHARED_PINS, buf,
+	    sizeof(buf)) > 0) {
+		buf[sizeof(buf) - 1] = '\0';
+		if (strcmp(buf, GEM_SHARED_PINS_SERDES) == 0)
+			sc->sc_flags |= GEM_SERDES;
+	}
 #else
 	/*
 	 * Dig out VPD (vital product data) and read NA (network address).
diff --git a/sys/dev/gem/if_gem_sbus.c b/sys/dev/gem/if_gem_sbus.c
index 4402251354e..205285d08e0 100644
--- a/sys/dev/gem/if_gem_sbus.c
+++ b/sys/dev/gem/if_gem_sbus.c
@@ -131,6 +131,8 @@ gem_sbus_attach(device_t dev)
 	sc = device_get_softc(dev);
 	sc->sc_variant = GEM_SUN_GEM;
 	sc->sc_dev = dev;
+	/* All known SBus models use a SERDES. */
+	sc->sc_flags = GEM_SERDES;
 
 	if (bus_alloc_resources(dev, gem_sbus_res_spec, sc->sc_res)) {
 		device_printf(dev, "failed to allocate resources\n");
diff --git a/sys/modules/gem/Makefile b/sys/modules/gem/Makefile
index 94db46251a7..941dc18f4a2 100644
--- a/sys/modules/gem/Makefile
+++ b/sys/modules/gem/Makefile
@@ -3,10 +3,15 @@
 .PATH: ${.CURDIR}/../../dev/gem
 
 KMOD=	if_gem
-SRCS=	bus_if.h device_if.h if_gem.c if_gem_pci.c miibus_if.h pci_if.h
+SRCS=	bus_if.h device_if.h if_gem.c if_gem_pci.c ${if_gem_sbus} miibus_if.h
+SRCS+=	${ofw_bus_if} pci_if.h
 
 .if ${MACHINE} == "sparc64"
-SRCS+=	if_gem_sbus.c ofw_bus_if.h
+if_gem_sbus=	if_gem_sbus.c
+.endif
+
+.if ${MACHINE_CPUARCH} == "powerpc" || ${MACHINE_CPUARCH} == "sparc64"
+ofw_bus_if=	ofw_bus_if.h
 .endif
 
 .include 

From 13e86ef7ee81ca854c82f8bcd8564adf5bb3101a Mon Sep 17 00:00:00 2001
From: Marko Zec 
Date: Thu, 16 Sep 2010 10:53:01 +0000
Subject: [PATCH 0803/1624] Make the format of "Real Memory" and "Virtual
 Memory" lines more consistent with the rest of sysctl vm.vmtotal output.

MFC after:	3 days
---
 sbin/sysctl/sysctl.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sbin/sysctl/sysctl.c b/sbin/sysctl/sysctl.c
index d96450b3bd5..93ff8c62ecf 100644
--- a/sbin/sysctl/sysctl.c
+++ b/sbin/sysctl/sysctl.c
@@ -406,9 +406,9 @@ S_vmtotal(int l2, void *p)
 	    "%hd Sleep: %hd)\n",
 	    v->t_rq, v->t_dw, v->t_pw, v->t_sl);
 	printf(
-	    "Virtual Memory:\t\t(Total: %dK, Active %dK)\n",
+	    "Virtual Memory:\t\t(Total: %dK Active: %dK)\n",
 	    v->t_vm * pageKilo, v->t_avm * pageKilo);
-	printf("Real Memory:\t\t(Total: %dK Active %dK)\n",
+	printf("Real Memory:\t\t(Total: %dK Active: %dK)\n",
 	    v->t_rm * pageKilo, v->t_arm * pageKilo);
 	printf("Shared Virtual Memory:\t(Total: %dK Active: %dK)\n",
 	    v->t_vmshr * pageKilo, v->t_avmshr * pageKilo);

From 836450ab2391fd1f089434e4d4ceb851de6bad24 Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 16 Sep 2010 11:33:31 +0000
Subject: [PATCH 0804/1624] When generating functions to print the arguments of
 system calls with bitwise parameters (e.g. mmap), print the syscall parameter
 value first. The resulting output looks like the %b specifier of printf(9).

Before:
mmap(0,0x8000,PROT_READ|PROT_WRITE,...
After:
mmap(0,0x8000,0x3,...

Submitted by:	Norberto Lopes 
Idea from:	freebsd-arch/2006-April/005116.html
---
 usr.bin/kdump/mksubr | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/usr.bin/kdump/mksubr b/usr.bin/kdump/mksubr
index 797c32c82cd..043d71205ea 100644
--- a/usr.bin/kdump/mksubr
+++ b/usr.bin/kdump/mksubr
@@ -49,6 +49,7 @@ void
 $name (int arg)
 {
 	int	or = 0;
+        printf("%#x<", arg);
 _EOF_
 	egrep "^#[[:space:]]*define[[:space:]]+"${grep}"[[:space:]]*" \
 		$include_dir/$file | \
@@ -58,6 +59,7 @@ _EOF_
 		++i; \
 		printf "\tif(!((arg>0)^((%s)>0)))\n\t\tif_print_or(arg, %s, or);\n", $i, $i }'
 cat <<_EOF_
+        printf(">");
 	if (or == 0)
 		(void)printf("%ld", (long)arg);
 }
@@ -432,6 +434,8 @@ sendrecvflagsname (int flags)
 		(void)printf("0");
 		return;
 	}
+
+        printf("%#x<", flags);
 _EOF_
 egrep "^#[[:space:]]*define[[:space:]]+MSG_[A-Z]+[[:space:]]+0x[0-9]+[[:space:]]*" $include_dir/sys/socket.h | \
 	awk '{ for (i = 1; i <= NF; i++) \
@@ -440,6 +444,7 @@ egrep "^#[[:space:]]*define[[:space:]]+MSG_[A-Z]+[[:space:]]+0x[0-9]+[[:space:]]
 		++i; \
 		printf "\tif(!((flags>0)^((%s)>0)))\n\t\tif_print_or(flags, %s, or);\n", $i, $i }'
 cat <<_EOF_
+        printf(">");
 }
 
 _EOF_

From bd0f1ee24f5ebd65e7deb9bc5ba93654f7469c5d Mon Sep 17 00:00:00 2001
From: Rui Paulo 
Date: Thu, 16 Sep 2010 11:40:41 +0000
Subject: [PATCH 0805/1624] Fix indenting of the previous commit.

---
 usr.bin/kdump/mksubr | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/usr.bin/kdump/mksubr b/usr.bin/kdump/mksubr
index 043d71205ea..42b75e3ad2b 100644
--- a/usr.bin/kdump/mksubr
+++ b/usr.bin/kdump/mksubr
@@ -49,7 +49,7 @@ void
 $name (int arg)
 {
 	int	or = 0;
-        printf("%#x<", arg);
+	printf("%#x<", arg);
 _EOF_
 	egrep "^#[[:space:]]*define[[:space:]]+"${grep}"[[:space:]]*" \
 		$include_dir/$file | \
@@ -59,7 +59,7 @@ _EOF_
 		++i; \
 		printf "\tif(!((arg>0)^((%s)>0)))\n\t\tif_print_or(arg, %s, or);\n", $i, $i }'
 cat <<_EOF_
-        printf(">");
+	printf(">");
 	if (or == 0)
 		(void)printf("%ld", (long)arg);
 }
@@ -435,7 +435,7 @@ sendrecvflagsname (int flags)
 		return;
 	}
 
-        printf("%#x<", flags);
+	printf("%#x<", flags);
 _EOF_
 egrep "^#[[:space:]]*define[[:space:]]+MSG_[A-Z]+[[:space:]]+0x[0-9]+[[:space:]]*" $include_dir/sys/socket.h | \
 	awk '{ for (i = 1; i <= NF; i++) \
@@ -444,7 +444,7 @@ egrep "^#[[:space:]]*define[[:space:]]+MSG_[A-Z]+[[:space:]]+0x[0-9]+[[:space:]]
 		++i; \
 		printf "\tif(!((flags>0)^((%s)>0)))\n\t\tif_print_or(flags, %s, or);\n", $i, $i }'
 cat <<_EOF_
-        printf(">");
+	printf(">");
 }
 
 _EOF_

From fe198baaa646b07b3172f15bd1e19cb9197a70c1 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Thu, 16 Sep 2010 12:05:00 +0000
Subject: [PATCH 0806/1624] Merge from powerpc: - Change putc_func_t to use a
 char instead of an int for the character. - Make functions and variables not
 used outside of this source file static. - Remove unused prototypes and
 variables. - The OFW read and seek methods take 3 and not 4 input arguments.

---
 sys/boot/sparc64/boot1/boot1.c | 60 +++++++++++++++-------------------
 1 file changed, 27 insertions(+), 33 deletions(-)

diff --git a/sys/boot/sparc64/boot1/boot1.c b/sys/boot/sparc64/boot1/boot1.c
index 813da29f4ec..6b9fa30ace4 100644
--- a/sys/boot/sparc64/boot1/boot1.c
+++ b/sys/boot/sparc64/boot1/boot1.c
@@ -26,9 +26,7 @@ __FBSDID("$FreeBSD$");
 #define _PATH_LOADER	"/boot/loader"
 #define _PATH_KERNEL	"/boot/kernel/kernel"
 
-#define BSIZEMAX	16384
-
-typedef int putc_func_t(int c, void *arg);
+typedef int putc_func_t(char c, void *arg);
 typedef int32_t ofwh_t;
 
 struct sp_data {
@@ -44,11 +42,6 @@ static char bootargs[128];
 
 static ofwh_t bootdev;
 
-static struct fs fs;
-static ino_t inomap;
-static char blkbuf[BSIZEMAX];
-static unsigned int fsblks;
-
 static uint32_t fs_off;
 
 int main(int ac, char **av);
@@ -66,14 +59,13 @@ static int mount(const char *device);
 
 static void panic(const char *fmt, ...) __dead2;
 static int printf(const char *fmt, ...);
-static int putchar(int c, void *arg);
+static int putchar(char c, void *arg);
 static int vprintf(const char *fmt, va_list ap);
 static int vsnprintf(char *str, size_t sz, const char *fmt, va_list ap);
 
 static int __printf(const char *fmt, putc_func_t *putc, void *arg, va_list ap);
-static int __putc(int c, void *arg);
 static int __puts(const char *s, putc_func_t *putc, void *arg);
-static int __sputc(int c, void *arg);
+static int __sputc(char c, void *arg);
 static char *__uitoa(char *buf, u_int val, int base);
 static char *__ultoa(char *buf, u_long val, int base);
 
@@ -83,19 +75,18 @@ static char *__ultoa(char *buf, u_long val, int base);
 typedef u_int64_t	ofwcell_t;
 typedef u_int32_t	u_ofwh_t;
 typedef int (*ofwfp_t)(ofwcell_t []);
-ofwfp_t ofw;			/* the prom Open Firmware entry */
+static ofwfp_t ofw;			/* the PROM Open Firmware entry */
 
 void ofw_init(int, int, int, int, ofwfp_t);
-ofwh_t ofw_finddevice(const char *);
-ofwh_t ofw_open(const char *);
-int ofw_getprop(ofwh_t, const char *, void *, size_t);
-int ofw_read(ofwh_t, void *, size_t);
-int ofw_write(ofwh_t, const void *, size_t);
-int ofw_seek(ofwh_t, u_int64_t);
-void ofw_exit(void) __dead2;
+static ofwh_t ofw_finddevice(const char *);
+static ofwh_t ofw_open(const char *);
+static int ofw_getprop(ofwh_t, const char *, void *, size_t);
+static int ofw_read(ofwh_t, void *, size_t);
+static int ofw_write(ofwh_t, const void *, size_t);
+static int ofw_seek(ofwh_t, u_int64_t);
+static void ofw_exit(void) __dead2;
 
-ofwh_t bootdevh;
-ofwh_t stdinh, stdouth;
+static ofwh_t stdinh, stdouth;
 
 /*
  * This has to stay here, as the PROM seems to ignore the
@@ -138,7 +129,7 @@ ofw_init(int d, int d1, int d2, int d3, ofwfp_t ofwaddr)
 	exit(main(ac, av));
 }
 
-ofwh_t
+static ofwh_t
 ofw_finddevice(const char *name)
 {
 	ofwcell_t args[] = {
@@ -156,7 +147,7 @@ ofw_finddevice(const char *name)
 	return (args[4]);
 }
 
-int
+static int
 ofw_getprop(ofwh_t ofwh, const char *name, void *buf, size_t len)
 {
 	ofwcell_t args[] = {
@@ -178,7 +169,7 @@ ofw_getprop(ofwh_t ofwh, const char *name, void *buf, size_t len)
 	return (0);
 }
 
-ofwh_t
+static ofwh_t
 ofw_open(const char *path)
 {
 	ofwcell_t args[] = {
@@ -196,7 +187,7 @@ ofw_open(const char *path)
 	return (args[4]);
 }
 
-int
+static int
 ofw_close(ofwh_t devh)
 {
 	ofwcell_t args[] = {
@@ -213,12 +204,12 @@ ofw_close(ofwh_t devh)
 	return (0);
 }
 
-int
+static int
 ofw_read(ofwh_t devh, void *buf, size_t len)
 {
 	ofwcell_t args[] = {
 		(ofwcell_t)"read",
-		4,
+		3,
 		1,
 		(u_ofwh_t)devh,
 		(ofwcell_t)buf,
@@ -233,7 +224,7 @@ ofw_read(ofwh_t devh, void *buf, size_t len)
 	return (0);
 }
 
-int
+static int
 ofw_write(ofwh_t devh, const void *buf, size_t len)
 {
 	ofwcell_t args[] = {
@@ -253,12 +244,12 @@ ofw_write(ofwh_t devh, const void *buf, size_t len)
 	return (0);
 }
 
-int
+static int
 ofw_seek(ofwh_t devh, u_int64_t off)
 {
 	ofwcell_t args[] = {
 		(ofwcell_t)"seek",
-		4,
+		3,
 		1,
 		(u_ofwh_t)devh,
 		off >> 32,
@@ -273,7 +264,7 @@ ofw_seek(ofwh_t devh, u_int64_t off)
 	return (0);
 }
 
-void
+static void
 ofw_exit(void)
 {
 	ofwcell_t args[3];
@@ -299,6 +290,7 @@ bcopy(const void *src, void *dst, size_t len)
 static void
 memcpy(void *dst, const void *src, size_t len)
 {
+
 	bcopy(src, dst, len);
 }
 
@@ -314,6 +306,7 @@ bzero(void *b, size_t len)
 static int
 strcmp(const char *s1, const char *s2)
 {
+
 	for (; *s1 == *s2 && *s1; s1++, s2++)
 		;
 	return ((u_char)*s1 - (u_char)*s2);
@@ -431,6 +424,7 @@ load(const char *fname)
 static int
 dskread(void *buf, u_int64_t lba, int nblk)
 {
+
 	/*
 	 * The Open Firmware should open the correct partition for us.
 	 * That means, if we read from offset zero on an open instance handle,
@@ -468,7 +462,7 @@ printf(const char *fmt, ...)
 }
 
 static int
-putchar(int c, void *arg)
+putchar(char c, void *arg)
 {
 	char buf;
 
@@ -614,7 +608,7 @@ reswitch:	c = *fmt++;
 }
 
 static int
-__sputc(int c, void *arg)
+__sputc(char c, void *arg)
 {
 	struct sp_data *sp;
 

From 3c141a7e1db965d8a355131800c68c2163ae38e5 Mon Sep 17 00:00:00 2001
From: Marius Strobl 
Date: Thu, 16 Sep 2010 12:05:46 +0000
Subject: [PATCH 0807/1624] Remove accidentally committed test code which
 effectively prevented the use of the SPARC64 V VIS-based block copy function
 added in r212709. Reported by:	Michael Moll

---
 sys/sparc64/sparc64/machdep.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/sys/sparc64/sparc64/machdep.c b/sys/sparc64/sparc64/machdep.c
index a4ed381ccf9..42bdf5ec6e0 100644
--- a/sys/sparc64/sparc64/machdep.c
+++ b/sys/sparc64/sparc64/machdep.c
@@ -511,8 +511,6 @@ sparc64_init(caddr_t mdp, u_long o1, u_long o2, u_long o3, ofw_vec_t *vec)
 		case CPU_IMPL_SPARC64V:
 			cpu_block_copy = zeus_block_copy;
 			cpu_block_zero = zeus_block_zero;
-			cpu_block_copy = spitfire_block_copy;
-			cpu_block_zero = spitfire_block_zero;
 			break;
 		}
 	}

From 2c9879e8d34d8289dac14d8ca2425ec561395016 Mon Sep 17 00:00:00 2001
From: Andre Oppermann 
Date: Thu, 16 Sep 2010 12:13:06 +0000
Subject: [PATCH 0808/1624] Improve comment to TCP_MINMSS by taking the wording
 from lstewart (with a small difference in the last paragraph though) as
 suggested by jhb.

Clarify that the 'reviewed by' in r212653 by lstewart was for the
functional change, not the comments in the committed version.
---
 sys/netinet/tcp.h | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/sys/netinet/tcp.h b/sys/netinet/tcp.h
index 86c95489284..27d45aac2f5 100644
--- a/sys/netinet/tcp.h
+++ b/sys/netinet/tcp.h
@@ -120,18 +120,18 @@ struct tcphdr {
 #define	TCP6_MSS	1220
 
 /*
- * Limit the lowest MSS we accept from path MTU discovery and the TCP SYN MSS
- * option.  Allowing too low values of MSS can consume significant amounts of
- * resources and be used as a form of a resource exhaustion attack.
+ * Limit the lowest MSS we accept for path MTU discovery and the TCP SYN MSS
+ * option.  Allowing low values of MSS can consume significant resources and
+ * be used to mount a resource exhaustion attack.
  * Connections requesting lower MSS values will be rounded up to this value
- * and the IP_DF flag is cleared to allow fragmentation along the path.
+ * and the IP_DF flag will be cleared to allow fragmentation along the path.
  *
  * See tcp_subr.c tcp_minmss SYSCTL declaration for more comments.  Setting
  * it to "0" disables the minmss check.
  *
- * The default value is fine for the smallest official link MTU (256 bytes,
- * AX.25 packet radio) in the Internet.  However it is very unlikely to come
- * across such low MTU interfaces these days (anno domini 2003).
+ * The default value is fine for TCP across the Internet's smallest official
+ * link MTU (256 bytes for AX.25 packet radio).  However, a connection is very
+ * unlikely to come across such low MTU interfaces these days (anno domini 2003).
  */
 #define	TCP_MINMSS 216
 

From bf12976c769659920cf6d1354e3501e55825bd2e Mon Sep 17 00:00:00 2001
From: Alexander Motin 
Date: Thu, 16 Sep 2010 12:39:50 +0000
Subject: [PATCH 0809/1624] Fix panic, when due to some kind of congestion on
 FIS-based switching port multiplier some command triggers false positive
 timeout, but then completes normally.

MFC after:	2 weeks
---
 sys/dev/ahci/ahci.c | 13 ++++++++-----
 sys/dev/mvs/mvs.c   | 13 ++++++++-----
 sys/dev/siis/siis.c | 13 ++++++++-----
 3 files changed, 24 insertions(+), 15 deletions(-)

diff --git a/sys/dev/ahci/ahci.c b/sys/dev/ahci/ahci.c
index 54e787ab1dd..d6357b2edcb 100644
--- a/sys/dev/ahci/ahci.c
+++ b/sys/dev/ahci/ahci.c
@@ -1854,6 +1854,7 @@ ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
 	device_t dev = slot->dev;
 	struct ahci_channel *ch = device_get_softc(dev);
 	union ccb *ccb = slot->ccb;
+	int lastto;
 
 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
 	    BUS_DMASYNC_POSTWRITE);
@@ -1955,11 +1956,6 @@ ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
 	ch->oslots &= ~(1 << slot->slot);
 	ch->rslots &= ~(1 << slot->slot);
 	ch->aslots &= ~(1 << slot->slot);
-	if (et != AHCI_ERR_TIMEOUT) {
-		if (ch->toslots == (1 << slot->slot))
-			xpt_release_simq(ch->sim, TRUE);
-		ch->toslots &= ~(1 << slot->slot);
-	}
 	slot->state = AHCI_SLOT_EMPTY;
 	slot->ccb = NULL;
 	/* Update channel stats. */
@@ -1970,6 +1966,13 @@ ahci_end_transaction(struct ahci_slot *slot, enum ahci_err_type et)
 		ch->numtslots--;
 		ch->numtslotspd[ccb->ccb_h.target_id]--;
 	}
+	/* Cancel timeout state if request completed normally. */
+	if (et != AHCI_ERR_TIMEOUT) {
+		lastto = (ch->toslots == (1 << slot->slot));
+		ch->toslots &= ~(1 << slot->slot);
+		if (lastto)
+			xpt_release_simq(ch->sim, TRUE);
+	}
 	/* If it was first request of reset sequence and there is no error,
 	 * proceed to second request. */
 	if ((ccb->ccb_h.func_code == XPT_ATA_IO) &&
diff --git a/sys/dev/mvs/mvs.c b/sys/dev/mvs/mvs.c
index 6b08222de6a..11a8853d95f 100644
--- a/sys/dev/mvs/mvs.c
+++ b/sys/dev/mvs/mvs.c
@@ -1552,6 +1552,7 @@ mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et)
 	device_t dev = slot->dev;
 	struct mvs_channel *ch = device_get_softc(dev);
 	union ccb *ccb = slot->ccb;
+	int lastto;
 
 //device_printf(dev, "cmd done status %d\n", et);
 	bus_dmamap_sync(ch->dma.workrq_tag, ch->dma.workrq_map,
@@ -1634,11 +1635,6 @@ mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et)
 	ch->oslots &= ~(1 << slot->slot);
 	ch->rslots &= ~(1 << slot->slot);
 	ch->aslots &= ~(1 << slot->slot);
-	if (et != MVS_ERR_TIMEOUT) {
-		if (ch->toslots == (1 << slot->slot))
-			xpt_release_simq(ch->sim, TRUE);
-		ch->toslots &= ~(1 << slot->slot);
-	}
 	slot->state = MVS_SLOT_EMPTY;
 	slot->ccb = NULL;
 	/* Update channel stats. */
@@ -1658,6 +1654,13 @@ mvs_end_transaction(struct mvs_slot *slot, enum mvs_err_type et)
 		ch->numpslots--;
 		ch->basic_dma = 0;
 	}
+	/* Cancel timeout state if request completed normally. */
+	if (et != MVS_ERR_TIMEOUT) {
+		lastto = (ch->toslots == (1 << slot->slot));
+		ch->toslots &= ~(1 << slot->slot);
+		if (lastto)
+			xpt_release_simq(ch->sim, TRUE);
+	}
 	/* If it was our READ LOG command - process it. */
 	if (ch->readlog) {
 		mvs_process_read_log(dev, ccb);
diff --git a/sys/dev/siis/siis.c b/sys/dev/siis/siis.c
index 34a77fc6a7a..0aef7757114 100644
--- a/sys/dev/siis/siis.c
+++ b/sys/dev/siis/siis.c
@@ -1179,6 +1179,7 @@ siis_end_transaction(struct siis_slot *slot, enum siis_err_type et)
 	device_t dev = slot->dev;
 	struct siis_channel *ch = device_get_softc(dev);
 	union ccb *ccb = slot->ccb;
+	int lastto;
 
 	mtx_assert(&ch->mtx, MA_OWNED);
 	bus_dmamap_sync(ch->dma.work_tag, ch->dma.work_map,
@@ -1262,11 +1263,6 @@ siis_end_transaction(struct siis_slot *slot, enum siis_err_type et)
 	ch->oslots &= ~(1 << slot->slot);
 	ch->rslots &= ~(1 << slot->slot);
 	ch->aslots &= ~(1 << slot->slot);
-	if (et != SIIS_ERR_TIMEOUT) {
-		if (ch->toslots == (1 << slot->slot))
-			xpt_release_simq(ch->sim, TRUE);
-		ch->toslots &= ~(1 << slot->slot);
-	}
 	slot->state = SIIS_SLOT_EMPTY;
 	slot->ccb = NULL;
 	/* Update channel stats. */
@@ -1275,6 +1271,13 @@ siis_end_transaction(struct siis_slot *slot, enum siis_err_type et)
 	    (ccb->ataio.cmd.flags & CAM_ATAIO_FPDMA)) {
 		ch->numtslots[ccb->ccb_h.target_id]--;
 	}
+	/* Cancel timeout state if request completed normally. */
+	if (et != SIIS_ERR_TIMEOUT) {
+		lastto = (ch->toslots == (1 << slot->slot));
+		ch->toslots &= ~(1 << slot->slot);
+		if (lastto)
+			xpt_release_simq(ch->sim, TRUE);
+	}
 	/* If it was our READ LOG command - process it. */
 	if (ch->readlog) {
 		siis_process_read_log(dev, ccb);

From 770e4c5bc000751a7620039ca240dad7fa9c4946 Mon Sep 17 00:00:00 2001
From: John Baldwin 
Date: Thu, 16 Sep 2010 16:03:12 +0000
Subject: [PATCH 0810/1624] Only attempt to list extended capabilities for
 devices that have a PCI-express capabilities.  Non-PCI-express PCI devices
 may simply ignore the upper bits in a config register address effectively
 aliasing the device ID register to 0x100 rather than returning 0xFFFFFFFF. 
 Previously the code relied on these reads returning 0xFFFFFFFF.

MFC after:	3 days
---
 usr.sbin/pciconf/cap.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/usr.sbin/pciconf/cap.c b/usr.sbin/pciconf/cap.c
index 9e6a6710121..605add87787 100644
--- a/usr.sbin/pciconf/cap.c
+++ b/usr.sbin/pciconf/cap.c
@@ -460,6 +460,7 @@ cap_pciaf(int fd, struct pci_conf *p, uint8_t ptr)
 void
 list_caps(int fd, struct pci_conf *p)
 {
+	int express;
 	uint16_t sta;
 	uint8_t ptr, cap;
 
@@ -481,6 +482,7 @@ list_caps(int fd, struct pci_conf *p)
 	}
 
 	/* Walk the capability list. */
+	express = 0;
 	ptr = read_config(fd, &p->pc_sel, ptr, 1);
 	while (ptr != 0 && ptr != 0xff) {
 		cap = read_config(fd, &p->pc_sel, ptr + PCICAP_ID, 1);
@@ -514,6 +516,7 @@ list_caps(int fd, struct pci_conf *p)
 			cap_subvendor(fd, p, ptr);
 			break;
 		case PCIY_EXPRESS:
+			express = 1;
 			cap_express(fd, p, ptr);
 			break;
 		case PCIY_MSIX:
@@ -533,7 +536,8 @@ list_caps(int fd, struct pci_conf *p)
 		ptr = read_config(fd, &p->pc_sel, ptr + PCICAP_NEXTPTR, 1);
 	}
 
-	list_ecaps(fd, p);
+	if (express)
+		list_ecaps(fd, p);
 }
 
 /* From . */

From 4e6571599b26002b8f26cc7916056179a222c288 Mon Sep 17 00:00:00 2001
From: Matthew D Fleming 
Date: Thu, 16 Sep 2010 16:13:12 +0000
Subject: [PATCH 0811/1624] Re-add r212370 now that the LOR in powerpc64 has
 been resolved:

Add a drain function for struct sysctl_req, and use it for a variety
of handlers, some of which had to do awkward things to get a large
enough SBUF_FIXEDLEN buffer.

Note that some sysctl handlers were explicitly outputting a trailing
NUL byte.  This behaviour was preserved, though it should not be
necessary.

Reviewed by:    phk (original patch)
---
 sys/dev/cxgb/cxgb_sge.c    | 48 +++++++++++--------------------
 sys/kern/kern_malloc.c     | 58 ++++++--------------------------------
 sys/kern/kern_sysctl.c     | 28 ++++++++++++++++++
 sys/kern/subr_lock.c       | 20 ++++---------
 sys/kern/subr_sbuf.c       |  4 +--
 sys/kern/subr_sleepqueue.c | 14 ++-------
 sys/kern/subr_witness.c    | 17 ++---------
 sys/sys/sysctl.h           |  3 ++
 sys/vm/uma_core.c          | 54 ++++++-----------------------------
 sys/vm/vm_phys.c           | 27 ++++--------------
 sys/vm/vm_reserv.c         |  9 ++----
 11 files changed, 88 insertions(+), 194 deletions(-)

diff --git a/sys/dev/cxgb/cxgb_sge.c b/sys/dev/cxgb/cxgb_sge.c
index 015f8414d12..5fb206b8ba3 100644
--- a/sys/dev/cxgb/cxgb_sge.c
+++ b/sys/dev/cxgb/cxgb_sge.c
@@ -3227,7 +3227,6 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 	struct sge_rspq *rspq;
 	struct sge_qset *qs;
 	int i, err, dump_end, idx;
-	static int multiplier = 1;
 	struct sbuf *sb;
 	struct rsp_desc *rspd;
 	uint32_t data[4];
@@ -3252,8 +3251,8 @@ t3_dump_rspq(SYSCTL_HANDLER_ARGS)
 	err = t3_sge_read_rspq(qs->port->adapter, rspq->cntxt_id, data);
 	if (err)
 		return (err);
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
+
+	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
 
 	sbuf_printf(sb, " \n index=%u size=%u MSI-X/RspQ=%u intr enable=%u intr armed=%u\n",
 	    (data[0] & 0xffff), data[0] >> 16, ((data[2] >> 20) & 0x3f),
@@ -3276,13 +3275,11 @@ retry_sbufops:
 		    rspd->rss_hdr.rss_hash_val, be32toh(rspd->flags),
 		    be32toh(rspd->len_cq), rspd->intr_gen);
 	}
-	if (sbuf_error(sb) != 0) {
-		sbuf_delete(sb);
-		multiplier++;
-		goto retry_sbufops;
-	}
-	sbuf_finish(sb);
-	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+
+	err = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (err == 0)
+		err = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (err);
 }	
@@ -3293,7 +3290,6 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 	struct sge_txq *txq;
 	struct sge_qset *qs;
 	int i, j, err, dump_end;
-	static int multiplier = 1;
 	struct sbuf *sb;
 	struct tx_desc *txd;
 	uint32_t *WR, wr_hi, wr_lo, gen;
@@ -3321,9 +3317,7 @@ t3_dump_txq_eth(SYSCTL_HANDLER_ARGS)
 	if (err)
 		return (err);
 	
-	    
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
 
 	sbuf_printf(sb, " \n credits=%u GTS=%u index=%u size=%u rspq#=%u cmdq#=%u\n",
 	    (data[0] & 0x7fff), ((data[0] >> 15) & 1), (data[0] >> 16), 
@@ -3350,13 +3344,10 @@ retry_sbufops:
 			    WR[j], WR[j + 1], WR[j + 2], WR[j + 3]);
 
 	}
-	if (sbuf_error(sb) != 0) {
-		sbuf_delete(sb);
-		multiplier++;
-		goto retry_sbufops;
-	}
-	sbuf_finish(sb);
-	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	err = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (err == 0)
+		err = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (err);
 }
@@ -3367,7 +3358,6 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 	struct sge_txq *txq;
 	struct sge_qset *qs;
 	int i, j, err, dump_end;
-	static int multiplier = 1;
 	struct sbuf *sb;
 	struct tx_desc *txd;
 	uint32_t *WR, wr_hi, wr_lo, gen;
@@ -3391,8 +3381,7 @@ t3_dump_txq_ctrl(SYSCTL_HANDLER_ARGS)
 		return (EINVAL);
 	}
 
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, QDUMP_SBUF_SIZE*multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, QDUMP_SBUF_SIZE, req);
 	sbuf_printf(sb, " qid=%d start=%d -> end=%d\n", qs->idx,
 	    txq->txq_dump_start,
 	    (txq->txq_dump_start + txq->txq_dump_count) & 255);
@@ -3412,13 +3401,10 @@ retry_sbufops:
 			    WR[j], WR[j + 1], WR[j + 2], WR[j + 3]);
 
 	}
-	if (sbuf_error(sb) != 0) {
-		sbuf_delete(sb);
-		multiplier++;
-		goto retry_sbufops;
-	}
-	sbuf_finish(sb);
-	err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	err = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (err == 0)
+		err = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (err);
 }
diff --git a/sys/kern/kern_malloc.c b/sys/kern/kern_malloc.c
index 1e97b55dc03..6d9b77574a6 100644
--- a/sys/kern/kern_malloc.c
+++ b/sys/kern/kern_malloc.c
@@ -828,25 +828,11 @@ sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
 	struct malloc_type_internal *mtip;
 	struct malloc_type_header mth;
 	struct malloc_type *mtp;
-	int buflen, count, error, i;
+	int error, i;
 	struct sbuf sbuf;
-	char *buffer;
 
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	mtx_lock(&malloc_mtx);
-restart:
-	mtx_assert(&malloc_mtx, MA_OWNED);
-	count = kmemcount;
-	mtx_unlock(&malloc_mtx);
-	buflen = sizeof(mtsh) + count * (sizeof(mth) +
-	    sizeof(struct malloc_type_stats) * MAXCPU) + 1;
-	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
-	mtx_lock(&malloc_mtx);
-	if (count < kmemcount) {
-		free(buffer, M_TEMP);
-		goto restart;
-	}
-
-	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
 
 	/*
 	 * Insert stream header.
@@ -855,11 +841,7 @@ restart:
 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
 	mtsh.mtsh_maxcpus = MAXCPU;
 	mtsh.mtsh_count = kmemcount;
-	if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
-		mtx_unlock(&malloc_mtx);
-		error = ENOMEM;
-		goto out;
-	}
+	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
 
 	/*
 	 * Insert alternating sequence of type headers and type statistics.
@@ -872,30 +854,19 @@ restart:
 		 */
 		bzero(&mth, sizeof(mth));
 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
-		if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
-			mtx_unlock(&malloc_mtx);
-			error = ENOMEM;
-			goto out;
-		}
+		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
 
 		/*
 		 * Insert type statistics for each CPU.
 		 */
 		for (i = 0; i < MAXCPU; i++) {
-			if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
-			    sizeof(mtip->mti_stats[i])) < 0) {
-				mtx_unlock(&malloc_mtx);
-				error = ENOMEM;
-				goto out;
-			}
+			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
+			    sizeof(mtip->mti_stats[i]));
 		}
 	}
 	mtx_unlock(&malloc_mtx);
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
-out:
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(buffer, M_TEMP);
 	return (error);
 }
 
@@ -1005,26 +976,19 @@ DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
 static int
 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
 {
-	int linesize = 64;
 	struct sbuf sbuf;
 	uint64_t count;
 	uint64_t waste;
 	uint64_t mem;
-	int bufsize;
 	int error;
-	char *buf;
 	int rsize;
 	int size;
 	int i;
 
-	bufsize = linesize * (KMEM_ZSIZE + 1);
-	bufsize += 128; 	/* For the stats line */
-	bufsize += 128; 	/* For the banner line */
 	waste = 0;
 	mem = 0;
 
-	buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
-	sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	sbuf_printf(&sbuf, 
 	    "\n  Size                    Requests  Real Size\n");
 	for (i = 0; i < KMEM_ZSIZE; i++) {
@@ -1042,12 +1006,8 @@ sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
 	sbuf_printf(&sbuf,
 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
 	    (unsigned long long)mem, (unsigned long long)waste);
-	sbuf_finish(&sbuf);
-
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
-
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(buf, M_TEMP);
 	return (error);
 }
 
diff --git a/sys/kern/kern_sysctl.c b/sys/kern/kern_sysctl.c
index b83502c2f41..49ccc505278 100644
--- a/sys/kern/kern_sysctl.c
+++ b/sys/kern/kern_sysctl.c
@@ -51,6 +51,7 @@ __FBSDID("$FreeBSD$");
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -1544,3 +1545,30 @@ userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
 	}
 	return (error);
 }
+
+/*
+ * Drain into a sysctl struct.  The user buffer must be wired.
+ */
+static int
+sbuf_sysctl_drain(void *arg, const char *data, int len)
+{
+	struct sysctl_req *req = arg;
+	int error;
+
+	error = SYSCTL_OUT(req, data, len);
+	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
+	return (error == 0 ? len : -error);
+}
+
+struct sbuf *
+sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
+    struct sysctl_req *req)
+{
+
+	/* Wire the user buffer, so we can write without blocking. */
+	sysctl_wire_old_buffer(req, 0);
+
+	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN);
+	sbuf_set_drain(s, sbuf_sysctl_drain, req);
+	return (s);
+}
diff --git a/sys/kern/subr_lock.c b/sys/kern/subr_lock.c
index 0c97052c76e..530ebc5b265 100644
--- a/sys/kern/subr_lock.c
+++ b/sys/kern/subr_lock.c
@@ -191,8 +191,7 @@ struct lock_prof_cpu *lp_cpu[MAXCPU];
 volatile int lock_prof_enable = 0;
 static volatile int lock_prof_resetting;
 
-/* SWAG: sbuf size = avg stat. line size * number of locks */
-#define LPROF_SBUF_SIZE		256 * 400
+#define LPROF_SBUF_SIZE		256
 
 static int lock_prof_rejected;
 static int lock_prof_skipspin;
@@ -384,8 +383,6 @@ lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
 				continue;
 			lock_prof_sum(l, &lp, i, spin, t);
 			lock_prof_output(&lp, sb);
-			if (sbuf_error(sb) != 0)
-				return;
 		}
 	}
 }
@@ -393,13 +390,11 @@ lock_prof_type_stats(struct lock_prof_type *type, struct sbuf *sb, int spin,
 static int
 dump_lock_prof_stats(SYSCTL_HANDLER_ARGS)
 {
-	static int multiplier = 1;
 	struct sbuf *sb;
 	int error, cpu, t;
 	int enabled;
 
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, LPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, LPROF_SBUF_SIZE, req);
 	sbuf_printf(sb, "\n%8s %9s %11s %11s %11s %6s %6s %2s %6s %s\n",
 	    "max", "wait_max", "total", "wait_total", "count", "avg", "wait_avg", "cnt_hold", "cnt_lock", "name");
 	enabled = lock_prof_enable;
@@ -411,16 +406,13 @@ retry_sbufops:
 			continue;
 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[0], sb, 0, t);
 		lock_prof_type_stats(&lp_cpu[cpu]->lpc_types[1], sb, 1, t);
-		if (sbuf_error(sb) != 0) {
-			sbuf_delete(sb);
-			multiplier++;
-			goto retry_sbufops;
-		}
 	}
 	lock_prof_enable = enabled;
 
-	sbuf_finish(sb);
-	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	error = sbuf_finish(sb);
+	/* Output a trailing NUL. */
+	if (error == 0)
+		error = SYSCTL_OUT(req, "", 1);
 	sbuf_delete(sb);
 	return (error);
 }
diff --git a/sys/kern/subr_sbuf.c b/sys/kern/subr_sbuf.c
index e81faa52036..0d083b4b33e 100644
--- a/sys/kern/subr_sbuf.c
+++ b/sys/kern/subr_sbuf.c
@@ -303,8 +303,8 @@ sbuf_drain(struct sbuf *s)
 		s->s_error = -len;
 		return (s->s_error);
 	}
-
-	KASSERT(len > 0, ("Drain must either error or work!"));
+	KASSERT(len > 0 && len <= s->s_len,
+	    ("Bad drain amount %d for sbuf %p", len, s));
 	s->s_len -= len;
 	/*
 	 * Fast path for the expected case where all the data was
diff --git a/sys/kern/subr_sleepqueue.c b/sys/kern/subr_sleepqueue.c
index b8be8f49210..cdf7a47c368 100644
--- a/sys/kern/subr_sleepqueue.c
+++ b/sys/kern/subr_sleepqueue.c
@@ -1018,7 +1018,7 @@ sleepq_abort(struct thread *td, int intrval)
 
 #ifdef SLEEPQUEUE_PROFILING
 #define	SLEEPQ_PROF_LOCATIONS	1024
-#define	SLEEPQ_SBUFSIZE		(40 * 512)
+#define	SLEEPQ_SBUFSIZE		512
 struct sleepq_prof {
 	LIST_ENTRY(sleepq_prof) sp_link;
 	const char	*sp_wmesg;
@@ -1123,15 +1123,13 @@ reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 static int
 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS)
 {
-	static int multiplier = 1;
 	struct sleepq_prof *sp;
 	struct sbuf *sb;
 	int enabled;
 	int error;
 	int i;
 
-retry_sbufops:
-	sb = sbuf_new(NULL, NULL, SLEEPQ_SBUFSIZE * multiplier, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req);
 	sbuf_printf(sb, "\nwmesg\tcount\n");
 	enabled = prof_enabled;
 	mtx_lock_spin(&sleepq_prof_lock);
@@ -1141,19 +1139,13 @@ retry_sbufops:
 		LIST_FOREACH(sp, &sleepq_hash[i], sp_link) {
 			sbuf_printf(sb, "%s\t%ld\n",
 			    sp->sp_wmesg, sp->sp_count);
-			if (sbuf_error(sb) != 0) {
-				sbuf_delete(sb);
-				multiplier++;
-				goto retry_sbufops;
-			}
 		}
 	}
 	mtx_lock_spin(&sleepq_prof_lock);
 	prof_enabled = enabled;
 	mtx_unlock_spin(&sleepq_prof_lock);
 
-	sbuf_finish(sb);
-	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	error = sbuf_finish(sb);
 	sbuf_delete(sb);
 	return (error);
 }
diff --git a/sys/kern/subr_witness.c b/sys/kern/subr_witness.c
index e5aa8dcaa2b..3fec4c420b2 100644
--- a/sys/kern/subr_witness.c
+++ b/sys/kern/subr_witness.c
@@ -154,8 +154,7 @@ __FBSDID("$FreeBSD$");
 #define	MAX_W_NAME	64
 
 #define	BADSTACK_SBUF_SIZE	(256 * WITNESS_COUNT)
-#define	CYCLEGRAPH_SBUF_SIZE	8192
-#define	FULLGRAPH_SBUF_SIZE	32768
+#define	FULLGRAPH_SBUF_SIZE	512
 
 /*
  * These flags go in the witness relationship matrix and describe the
@@ -2545,7 +2544,7 @@ sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
 		return (error);
 	}
 	error = 0;
-	sb = sbuf_new(NULL, NULL, FULLGRAPH_SBUF_SIZE, SBUF_FIXEDLEN);
+	sb = sbuf_new_for_sysctl(NULL, NULL, FULLGRAPH_SBUF_SIZE, req);
 	if (sb == NULL)
 		return (ENOMEM);
 	sbuf_printf(sb, "\n");
@@ -2557,20 +2556,10 @@ sysctl_debug_witness_fullgraph(SYSCTL_HANDLER_ARGS)
 		witness_add_fullgraph(sb, w);
 	mtx_unlock_spin(&w_mtx);
 
-	/*
-	 * While using SBUF_FIXEDLEN, check if the sbuf overflowed.
-	 */
-	if (sbuf_error(sb) != 0) {
-		sbuf_delete(sb);
-		panic("%s: sbuf overflowed, bump FULLGRAPH_SBUF_SIZE value\n",
-		    __func__);
-	}
-
 	/*
 	 * Close the sbuf and return to userland.
 	 */
-	sbuf_finish(sb);
-	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
+	error = sbuf_finish(sb);
 	sbuf_delete(sb);
 
 	return (error);
diff --git a/sys/sys/sysctl.h b/sys/sys/sysctl.h
index 1ee49cab246..fbfd6e84202 100644
--- a/sys/sys/sysctl.h
+++ b/sys/sys/sysctl.h
@@ -710,6 +710,9 @@ void	sysctl_lock(void);
 void	sysctl_unlock(void);
 int	sysctl_wire_old_buffer(struct sysctl_req *req, size_t len);
 
+struct sbuf;
+struct sbuf	*sbuf_new_for_sysctl(struct sbuf *, char *, int,
+		    struct sysctl_req *);
 #else	/* !_KERNEL */
 #include 
 
diff --git a/sys/vm/uma_core.c b/sys/vm/uma_core.c
index 558b4c727e7..23b88ee45c2 100644
--- a/sys/vm/uma_core.c
+++ b/sys/vm/uma_core.c
@@ -3175,36 +3175,16 @@ sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
 	uma_keg_t kz;
 	uma_zone_t z;
 	uma_keg_t k;
-	char *buffer;
-	int buflen, count, error, i;
+	int count, error, i;
+
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 
-	mtx_lock(&uma_mtx);
-restart:
-	mtx_assert(&uma_mtx, MA_OWNED);
 	count = 0;
+	mtx_lock(&uma_mtx);
 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
 			count++;
 	}
-	mtx_unlock(&uma_mtx);
-
-	buflen = sizeof(ush) + count * (sizeof(uth) + sizeof(ups) *
-	    (mp_maxid + 1)) + 1;
-	buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
-
-	mtx_lock(&uma_mtx);
-	i = 0;
-	LIST_FOREACH(kz, &uma_kegs, uk_link) {
-		LIST_FOREACH(z, &kz->uk_zones, uz_link)
-			i++;
-	}
-	if (i > count) {
-		free(buffer, M_TEMP);
-		goto restart;
-	}
-	count =  i;
-
-	sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
 
 	/*
 	 * Insert stream header.
@@ -3213,11 +3193,7 @@ restart:
 	ush.ush_version = UMA_STREAM_VERSION;
 	ush.ush_maxcpus = (mp_maxid + 1);
 	ush.ush_count = count;
-	if (sbuf_bcat(&sbuf, &ush, sizeof(ush)) < 0) {
-		mtx_unlock(&uma_mtx);
-		error = ENOMEM;
-		goto out;
-	}
+	(void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
 
 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
@@ -3250,12 +3226,7 @@ restart:
 			uth.uth_frees = z->uz_frees;
 			uth.uth_fails = z->uz_fails;
 			uth.uth_sleeps = z->uz_sleeps;
-			if (sbuf_bcat(&sbuf, &uth, sizeof(uth)) < 0) {
-				ZONE_UNLOCK(z);
-				mtx_unlock(&uma_mtx);
-				error = ENOMEM;
-				goto out;
-			}
+			(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
 			/*
 			 * While it is not normally safe to access the cache
 			 * bucket pointers while not on the CPU that owns the
@@ -3280,21 +3251,14 @@ restart:
 				ups.ups_allocs = cache->uc_allocs;
 				ups.ups_frees = cache->uc_frees;
 skip:
-				if (sbuf_bcat(&sbuf, &ups, sizeof(ups)) < 0) {
-					ZONE_UNLOCK(z);
-					mtx_unlock(&uma_mtx);
-					error = ENOMEM;
-					goto out;
-				}
+				(void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
 			}
 			ZONE_UNLOCK(z);
 		}
 	}
 	mtx_unlock(&uma_mtx);
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
-out:
-	free(buffer, M_TEMP);
+	error = sbuf_finish(&sbuf);
+	sbuf_delete(&sbuf);
 	return (error);
 }
 
diff --git a/sys/vm/vm_phys.c b/sys/vm/vm_phys.c
index e75c3401acf..26e4981606a 100644
--- a/sys/vm/vm_phys.c
+++ b/sys/vm/vm_phys.c
@@ -123,12 +123,9 @@ sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	struct vm_freelist *fl;
-	char *cbuf;
-	const int cbufsize = vm_nfreelists*(VM_NFREEORDER + 1)*81;
 	int error, flind, oind, pind;
 
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	for (flind = 0; flind < vm_nfreelists; flind++) {
 		sbuf_printf(&sbuf, "\nFREE LIST %d:\n"
 		    "\n  ORDER (SIZE)  |  NUMBER"
@@ -149,10 +146,8 @@ sysctl_vm_phys_free(SYSCTL_HANDLER_ARGS)
 			sbuf_printf(&sbuf, "\n");
 		}
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 
@@ -164,12 +159,9 @@ sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	struct vm_phys_seg *seg;
-	char *cbuf;
-	const int cbufsize = VM_PHYSSEG_MAX*(VM_NFREEORDER + 1)*81;
 	int error, segind;
 
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	for (segind = 0; segind < vm_phys_nsegs; segind++) {
 		sbuf_printf(&sbuf, "\nSEGMENT %d:\n\n", segind);
 		seg = &vm_phys_segs[segind];
@@ -180,10 +172,8 @@ sysctl_vm_phys_segs(SYSCTL_HANDLER_ARGS)
 		sbuf_printf(&sbuf, "domain:    %d\n", seg->domain);
 		sbuf_printf(&sbuf, "free list: %p\n", seg->free_queues);
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 
@@ -195,23 +185,18 @@ static int
 sysctl_vm_phys_lookup_lists(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
-	char *cbuf;
-	const int cbufsize = (vm_nfreelists + 1) * VM_NDOMAIN * 81;
 	int domain, error, flind, ndomains;
 
 	ndomains = vm_nfreelists - VM_NFREELIST + 1;
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	for (domain = 0; domain < ndomains; domain++) {
 		sbuf_printf(&sbuf, "\nDOMAIN %d:\n\n", domain);
 		for (flind = 0; flind < vm_nfreelists; flind++)
 			sbuf_printf(&sbuf, "  [%d]:\t%p\n", flind,
 			    vm_phys_lookup_lists[domain][flind]);
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 #endif
diff --git a/sys/vm/vm_reserv.c b/sys/vm/vm_reserv.c
index d9e908f62a3..aa8e80f7311 100644
--- a/sys/vm/vm_reserv.c
+++ b/sys/vm/vm_reserv.c
@@ -180,12 +180,9 @@ sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf sbuf;
 	vm_reserv_t rv;
-	char *cbuf;
-	const int cbufsize = (VM_NRESERVLEVEL + 1) * 81;
 	int counter, error, level, unused_pages;
 
-	cbuf = malloc(cbufsize, M_TEMP, M_WAITOK | M_ZERO);
-	sbuf_new(&sbuf, cbuf, cbufsize, SBUF_FIXEDLEN);
+	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
 	sbuf_printf(&sbuf, "\nLEVEL     SIZE  NUMBER\n\n");
 	for (level = -1; level <= VM_NRESERVLEVEL - 2; level++) {
 		counter = 0;
@@ -199,10 +196,8 @@ sysctl_vm_reserv_partpopq(SYSCTL_HANDLER_ARGS)
 		sbuf_printf(&sbuf, "%5.5d: %6.6dK, %6.6d\n", level,
 		    unused_pages * (PAGE_SIZE / 1024), counter);
 	}
-	sbuf_finish(&sbuf);
-	error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
+	error = sbuf_finish(&sbuf);
 	sbuf_delete(&sbuf);
-	free(cbuf, M_TEMP);
 	return (error);
 }
 

From 6144c1de6a7674dad94290650e4e14f24d42e421 Mon Sep 17 00:00:00 2001
From: Dimitry Andric 
Date: Thu, 16 Sep 2010 17:02:26 +0000
Subject: [PATCH 0812/1624] Make vendor/llvm/dist exactly the same as
 upstream's r108428.  Some files and directories were already removed in the
 upstream repository, but were not removed here, when the previous snapshot
 was imported.

Approved by:	rpaulo (mentor)
---
 Xcode/LLVM.xcodeproj/project.pbxproj          | 3303 --------
 Xcode/README.txt                              |    1 -
 autoconf/m4/bison.m4                          |   15 -
 autoconf/m4/cxx_bidi_iterator.m4              |   22 -
 autoconf/m4/cxx_fwd_iterator.m4               |   22 -
 autoconf/m4/cxx_namespaces.m4                 |   19 -
 autoconf/m4/cxx_std_iterator.m4               |   26 -
 autoconf/m4/flex.m4                           |   17 -
 docs/AdvancedGetElementPtr.html               |  362 -
 docs/CommandGuide/llvm-db.pod                 |   16 -
 docs/ReleaseNotes-2.6.html                    |  784 --
 docs/tutorial/JITTutorial1.html               |  207 -
 docs/tutorial/JITTutorial2-1.png              |  Bin 59107 -> 0 bytes
 docs/tutorial/JITTutorial2.html               |  200 -
 include/llvm/ADT/iterator.cmake               |   79 -
 include/llvm/ADT/iterator.h.in                |   76 -
 include/llvm/Support/DataTypes.h.cmake        |  152 -
 include/llvm/Support/DataTypes.h.in           |  147 -
 mklib                                         | 7517 -----------------
 runtime/libprofile/BlockProfiling.c           |   45 -
 runtime/libprofile/FunctionProfiling.c        |   42 -
 .../x86_64-pc-linux-gnu_gcc-4.3.3.supp        |   23 -
 win32/Analysis/Analysis.vcproj                |  573 --
 win32/Archive/Archive.vcproj                  |  337 -
 win32/AsmParser/AsmParser.vcproj              |  346 -
 win32/Bitcode/Bitcode.vcproj                  |  422 -
 win32/CBackend/CBackend.vcproj                |  325 -
 win32/CodeGen/CodeGen.vcproj                  |  849 --
 win32/Configure/Configure.vcproj              |  319 -
 win32/ExecutionEngine/ExecutionEngine.vcproj  |  429 -
 win32/Fibonacci/Fibonacci.vcproj              |  386 -
 win32/Linker/Linker.vcproj                    |  337 -
 win32/Support/Support.vcproj                  |  743 --
 win32/System/System.vcproj                    |  462 -
 win32/TableGen/TableGen.vcproj                |  538 --
 win32/Target/Target.vcproj                    |  433 -
 win32/Transforms/Transforms.vcproj            |  759 --
 win32/VMCore/VMCore.vcproj                    |  650 --
 win32/bugpoint/bugpoint.vcproj                |  429 -
 win32/clang.sln                               |  591 --
 win32/common.vsprops                          |   11 -
 win32/config.h                                |   30 -
 win32/dobison.cmd                             |   29 -
 win32/doflex.cmd                              |   20 -
 win32/llc/llc.vcproj                          |  385 -
 win32/lli/lli.vcproj                          |  385 -
 win32/llvm-ar/llvm-ar.vcproj                  |  381 -
 win32/llvm-as/llvm-as.vcproj                  |  381 -
 win32/llvm-bcanalyzer/llvm-bcanalyzer.vcproj  |  381 -
 win32/llvm-dis/llvm-dis.vcproj                |  381 -
 win32/llvm-ld/llvm-ld.vcproj                  |  385 -
 win32/llvm-link/llvm-link.vcproj              |  381 -
 win32/llvm-nm/llvm-nm.vcproj                  |  381 -
 win32/llvm-prof/llvm-prof.vcproj              |  381 -
 win32/llvm-ranlib/llvm-ranlib.vcproj          |  381 -
 win32/llvm.sln                                |  719 --
 win32/opt/opt.vcproj                          |  393 -
 win32/unistd.h                                |    1 -
 win32/x86/x86.vcproj                          |  620 --
 59 files changed, 28029 deletions(-)
 delete mode 100644 Xcode/LLVM.xcodeproj/project.pbxproj
 delete mode 100644 Xcode/README.txt
 delete mode 100644 autoconf/m4/bison.m4
 delete mode 100644 autoconf/m4/cxx_bidi_iterator.m4
 delete mode 100644 autoconf/m4/cxx_fwd_iterator.m4
 delete mode 100644 autoconf/m4/cxx_namespaces.m4
 delete mode 100644 autoconf/m4/cxx_std_iterator.m4
 delete mode 100644 autoconf/m4/flex.m4
 delete mode 100644 docs/AdvancedGetElementPtr.html
 delete mode 100644 docs/CommandGuide/llvm-db.pod
 delete mode 100644 docs/ReleaseNotes-2.6.html
 delete mode 100644 docs/tutorial/JITTutorial1.html
 delete mode 100644 docs/tutorial/JITTutorial2-1.png
 delete mode 100644 docs/tutorial/JITTutorial2.html
 delete mode 100644 include/llvm/ADT/iterator.cmake
 delete mode 100644 include/llvm/ADT/iterator.h.in
 delete mode 100644 include/llvm/Support/DataTypes.h.cmake
 delete mode 100644 include/llvm/Support/DataTypes.h.in
 delete mode 100755 mklib
 delete mode 100644 runtime/libprofile/BlockProfiling.c
 delete mode 100644 runtime/libprofile/FunctionProfiling.c
 delete mode 100644 utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp
 delete mode 100644 win32/Analysis/Analysis.vcproj
 delete mode 100644 win32/Archive/Archive.vcproj
 delete mode 100644 win32/AsmParser/AsmParser.vcproj
 delete mode 100644 win32/Bitcode/Bitcode.vcproj
 delete mode 100644 win32/CBackend/CBackend.vcproj
 delete mode 100644 win32/CodeGen/CodeGen.vcproj
 delete mode 100644 win32/Configure/Configure.vcproj
 delete mode 100644 win32/ExecutionEngine/ExecutionEngine.vcproj
 delete mode 100644 win32/Fibonacci/Fibonacci.vcproj
 delete mode 100644 win32/Linker/Linker.vcproj
 delete mode 100644 win32/Support/Support.vcproj
 delete mode 100644 win32/System/System.vcproj
 delete mode 100644 win32/TableGen/TableGen.vcproj
 delete mode 100644 win32/Target/Target.vcproj
 delete mode 100644 win32/Transforms/Transforms.vcproj
 delete mode 100644 win32/VMCore/VMCore.vcproj
 delete mode 100644 win32/bugpoint/bugpoint.vcproj
 delete mode 100644 win32/clang.sln
 delete mode 100644 win32/common.vsprops
 delete mode 100644 win32/config.h
 delete mode 100755 win32/dobison.cmd
 delete mode 100755 win32/doflex.cmd
 delete mode 100644 win32/llc/llc.vcproj
 delete mode 100644 win32/lli/lli.vcproj
 delete mode 100644 win32/llvm-ar/llvm-ar.vcproj
 delete mode 100644 win32/llvm-as/llvm-as.vcproj
 delete mode 100644 win32/llvm-bcanalyzer/llvm-bcanalyzer.vcproj
 delete mode 100644 win32/llvm-dis/llvm-dis.vcproj
 delete mode 100644 win32/llvm-ld/llvm-ld.vcproj
 delete mode 100644 win32/llvm-link/llvm-link.vcproj
 delete mode 100644 win32/llvm-nm/llvm-nm.vcproj
 delete mode 100644 win32/llvm-prof/llvm-prof.vcproj
 delete mode 100644 win32/llvm-ranlib/llvm-ranlib.vcproj
 delete mode 100644 win32/llvm.sln
 delete mode 100644 win32/opt/opt.vcproj
 delete mode 100644 win32/unistd.h
 delete mode 100644 win32/x86/x86.vcproj

diff --git a/Xcode/LLVM.xcodeproj/project.pbxproj b/Xcode/LLVM.xcodeproj/project.pbxproj
deleted file mode 100644
index e2f40f4cba4..00000000000
--- a/Xcode/LLVM.xcodeproj/project.pbxproj
+++ /dev/null
@@ -1,3303 +0,0 @@
-// !$*UTF8*$!
-{
-	archiveVersion = 1;
-	classes = {
-	};
-	objectVersion = 42;
-	objects = {
-
-/* Begin PBXAggregateTarget section */
-		CF0329BC08D1BE8E0030FD33 /* LLVM full llc */ = {
-			isa = PBXAggregateTarget;
-			buildConfigurationList = CF0329C708D1BEC40030FD33 /* Build configuration list for PBXAggregateTarget "LLVM full llc" */;
-			buildPhases = (
-			);
-			dependencies = (
-				CF0329BE08D1BE970030FD33 /* PBXTargetDependency */,
-				CF0329C008D1BE9B0030FD33 /* PBXTargetDependency */,
-			);
-			name = "LLVM full llc";
-			productName = "LLVM full llc";
-		};
-		CFDF86D00ADE820000D40A3D /* LLVM full llc release */ = {
-			isa = PBXAggregateTarget;
-			buildConfigurationList = CFDF86D50ADE820000D40A3D /* Build configuration list for PBXAggregateTarget "LLVM full llc release" */;
-			buildPhases = (
-			);
-			dependencies = (
-				CFDF86DA0ADE822100D40A3D /* PBXTargetDependency */,
-				CFDF86DC0ADE822100D40A3D /* PBXTargetDependency */,
-			);
-			name = "LLVM full llc release";
-			productName = "LLVM full llc";
-		};
-/* End PBXAggregateTarget section */
-
-/* Begin PBXContainerItemProxy section */
-		CF0329BD08D1BE970030FD33 /* PBXContainerItemProxy */ = {
-			isa = PBXContainerItemProxy;
-			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
-			proxyType = 1;
-			remoteGlobalIDString = CF0329B608D1BE110030FD33;
-			remoteInfo = "LLVM lib";
-		};
-		CF0329BF08D1BE9B0030FD33 /* PBXContainerItemProxy */ = {
-			isa = PBXContainerItemProxy;
-			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
-			proxyType = 1;
-			remoteGlobalIDString = CF0329BB08D1BE5D0030FD33;
-			remoteInfo = "LLVM llc";
-		};
-		CFDF86D90ADE822100D40A3D /* PBXContainerItemProxy */ = {
-			isa = PBXContainerItemProxy;
-			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
-			proxyType = 1;
-			remoteGlobalIDString = CFDF86BD0ADE819D00D40A3D;
-			remoteInfo = "LLVM lib release";
-		};
-		CFDF86DB0ADE822100D40A3D /* PBXContainerItemProxy */ = {
-			isa = PBXContainerItemProxy;
-			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
-			proxyType = 1;
-			remoteGlobalIDString = CFDF86C60ADE81D000D40A3D;
-			remoteInfo = "LLVM llc release";
-		};
-/* End PBXContainerItemProxy section */
-
-/* Begin PBXFileReference section */
-		354CF6D10CD299440059AF3E /* DeserializeAPInt.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DeserializeAPInt.cpp; sourceTree = ""; };
-		354CF6D20CD2994D0059AF3E /* SerializeAPInt.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SerializeAPInt.cpp; sourceTree = ""; };
-		35A9CDED0CD0F6AF008ABC1D /* Deserialize.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Deserialize.h; sourceTree = ""; };
-		35A9CDEE0CD0F6AF008ABC1D /* Serialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Serialization.h; sourceTree = ""; };
-		35A9CDEF0CD0F6AF008ABC1D /* Serialize.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Serialize.h; sourceTree = ""; };
-		35A9CDF00CD0F6D5008ABC1D /* Deserialize.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Deserialize.cpp; sourceTree = ""; };
-		35A9CDF10CD0F6E1008ABC1D /* Serialize.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Serialize.cpp; sourceTree = ""; };
-		35E98A830CBC2ED300C5CDC1 /* DenseSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DenseSet.h; sourceTree = ""; };
-		35E98A840CBC2ED300C5CDC1 /* ImmutableMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImmutableMap.h; sourceTree = ""; };
-		35E98A850CBC2ED300C5CDC1 /* ImmutableSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImmutableSet.h; sourceTree = ""; };
-		754221420D171DFC00DDB61B /* MachineLICM.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MachineLICM.cpp; sourceTree = ""; };
-		84115FFE0B66D87400E1293E /* TargetMachOWriterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetMachOWriterInfo.cpp; sourceTree = ""; };
-		84115FFF0B66D89B00E1293E /* PPCMachOWriterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PPCMachOWriterInfo.cpp; sourceTree = ""; };
-		841160000B66D8AC00E1293E /* PPCMachOWriterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PPCMachOWriterInfo.h; sourceTree = ""; };
-		8443EF210B66B62D00959964 /* TargetMachOWriterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetMachOWriterInfo.h; sourceTree = ""; };
-		9F4B0E5E0D0E02580061F270 /* bitreader_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = bitreader_ocaml.c; sourceTree = ""; };
-		9F4B0E5F0D0E02580061F270 /* llvm_bitreader.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_bitreader.ml; sourceTree = ""; };
-		9F4B0E600D0E02580061F270 /* llvm_bitreader.mli */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_bitreader.mli; sourceTree = ""; };
-		9F4B0E8C0D0E05ED0061F270 /* BitReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BitReader.cpp; sourceTree = ""; };
-		9F4B0E8D0D0E05ED0061F270 /* DeserializeAPFloat.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DeserializeAPFloat.cpp; sourceTree = ""; };
-		9F502ADB0D1D8CA3007939DF /* executionengine_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = executionengine_ocaml.c; sourceTree = ""; };
-		9F502ADC0D1D8CA3007939DF /* llvm_executionengine.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_executionengine.ml; sourceTree = ""; };
-		9F502ADD0D1D8CA3007939DF /* llvm_executionengine.mli */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_executionengine.mli; sourceTree = ""; };
-		9F502AEC0D1D8CF8007939DF /* executionengine.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = executionengine.ml; sourceTree = ""; };
-		9F502B090D1D8D8D007939DF /* ExecutionEngineBindings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ExecutionEngineBindings.cpp; sourceTree = ""; };
-		9F5B90CB0D0CE87100CDFDEA /* StringPool.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StringPool.cpp; sourceTree = ""; };
-		9F5B90CE0D0CE89300CDFDEA /* AlignOf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AlignOf.h; sourceTree = ""; };
-		9F5B90CF0D0CE89300CDFDEA /* Registry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Registry.h; sourceTree = ""; };
-		9F5B90D00D0CE89300CDFDEA /* StringPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StringPool.h; sourceTree = ""; };
-		9F5B90E70D0DF19100CDFDEA /* BitReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BitReader.h; sourceTree = ""; };
-		9F68EB010C77AD02004AA152 /* LoopPass.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoopPass.cpp; sourceTree = ""; };
-		9F68EB020C77AD02004AA152 /* MemoryDependenceAnalysis.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MemoryDependenceAnalysis.cpp; sourceTree = ""; };
-		9F68EB060C77AD2C004AA152 /* BitcodeReader.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BitcodeReader.cpp; sourceTree = ""; };
-		9F68EB070C77AD2C004AA152 /* BitcodeReader.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BitcodeReader.h; sourceTree = ""; };
-		9F68EB120C77AD2C004AA152 /* BitcodeWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BitcodeWriter.cpp; sourceTree = ""; };
-		9F68EB130C77AD2C004AA152 /* BitcodeWriterPass.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BitcodeWriterPass.cpp; sourceTree = ""; };
-		9F68EB250C77AD2C004AA152 /* ValueEnumerator.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ValueEnumerator.cpp; sourceTree = ""; };
-		9F68EB260C77AD2C004AA152 /* ValueEnumerator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ValueEnumerator.h; sourceTree = ""; };
-		9F6B2CC00D0F6E56000F00FD /* bitreader.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = bitreader.ml; sourceTree = ""; };
-		9F70401A0D8D732400FD06FF /* llvm_scalar_opts.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = llvm_scalar_opts.ml; path = transforms/scalar/llvm_scalar_opts.ml; sourceTree = ""; };
-		9F70401B0D8D732400FD06FF /* llvm_scalar_opts.mli */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = llvm_scalar_opts.mli; path = transforms/scalar/llvm_scalar_opts.mli; sourceTree = ""; };
-		9F70401E0D8D735E00FD06FF /* scalar_opts_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = scalar_opts_ocaml.c; path = transforms/scalar/scalar_opts_ocaml.c; sourceTree = ""; };
-		9F7793460C73BC2000551F9C /* CodeGenPrepare.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CodeGenPrepare.cpp; sourceTree = ""; };
-		9F7793470C73BC2000551F9C /* GVN.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GVN.cpp; sourceTree = ""; };
-		9F7793480C73BC2000551F9C /* GVNPRE.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GVNPRE.cpp; sourceTree = ""; };
-		9F7793490C73BC2000551F9C /* LoopIndexSplit.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoopIndexSplit.cpp; sourceTree = ""; };
-		9F77934A0C73BC2000551F9C /* LoopRotation.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoopRotation.cpp; sourceTree = ""; };
-		9F7793500C73BD1500551F9C /* ELFWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ELFWriter.h; sourceTree = ""; };
-		9F7793510C73BD1500551F9C /* IfConversion.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IfConversion.cpp; sourceTree = ""; };
-		9F7793520C73BD1500551F9C /* LowerSubregs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LowerSubregs.cpp; sourceTree = ""; };
-		9F7793530C73BD1500551F9C /* MachOWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachOWriter.h; sourceTree = ""; };
-		9F7793540C73BD1500551F9C /* PostRASchedulerList.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PostRASchedulerList.cpp; sourceTree = ""; };
-		9F7793550C73BD1500551F9C /* RegAllocBigBlock.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RegAllocBigBlock.cpp; sourceTree = ""; };
-		9F7793560C73BD1500551F9C /* RegisterScavenging.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RegisterScavenging.cpp; sourceTree = ""; };
-		9F7793570C73BD1500551F9C /* SimpleRegisterCoalescing.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SimpleRegisterCoalescing.cpp; sourceTree = ""; };
-		9F7793770C73C48A00551F9C /* StripDeadPrototypes.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StripDeadPrototypes.cpp; sourceTree = ""; };
-		9F7793780C73C49A00551F9C /* BasicInliner.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BasicInliner.cpp; sourceTree = ""; };
-		9F7793790C73C49A00551F9C /* CloneLoop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CloneLoop.cpp; sourceTree = ""; };
-		9F77937A0C73C49A00551F9C /* InlineCost.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InlineCost.cpp; sourceTree = ""; };
-		9F77937B0C73C4F400551F9C /* AutoUpgrade.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AutoUpgrade.cpp; path = ../lib/VMCore/AutoUpgrade.cpp; sourceTree = SOURCE_ROOT; };
-		9F77937C0C73C4F400551F9C /* ConstantFold.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ConstantFold.cpp; path = ../lib/VMCore/ConstantFold.cpp; sourceTree = SOURCE_ROOT; };
-		9F77937D0C73C4F400551F9C /* ConstantFold.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ConstantFold.h; path = ../lib/VMCore/ConstantFold.h; sourceTree = SOURCE_ROOT; };
-		9F77937E0C73C53000551F9C /* ParameterAttributes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParameterAttributes.h; sourceTree = ""; };
-		9F7793800C73C54C00551F9C /* Archive.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Archive.h; sourceTree = ""; };
-		9F7793810C73C54C00551F9C /* BitCodes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BitCodes.h; sourceTree = ""; };
-		9F7793820C73C54C00551F9C /* BitstreamReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BitstreamReader.h; sourceTree = ""; };
-		9F7793830C73C54C00551F9C /* BitstreamWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BitstreamWriter.h; sourceTree = ""; };
-		9F7793840C73C54C00551F9C /* LLVMBitCodes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LLVMBitCodes.h; sourceTree = ""; };
-		9F7793850C73C54C00551F9C /* ReaderWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ReaderWriter.h; sourceTree = ""; };
-		9F7793860C73C57100551F9C /* CallingConvLower.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CallingConvLower.h; sourceTree = ""; };
-		9F7793870C73C57100551F9C /* ELFRelocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ELFRelocation.h; sourceTree = ""; };
-		9F7793880C73C57100551F9C /* FileWriters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FileWriters.h; sourceTree = ""; };
-		9F7793890C73C57100551F9C /* MachORelocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachORelocation.h; sourceTree = ""; };
-		9F77938A0C73C57100551F9C /* RegisterScavenging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RegisterScavenging.h; sourceTree = ""; };
-		9F7794140C73CB6100551F9C /* Mips.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Mips.h; sourceTree = ""; };
-		9F7794150C73CB6100551F9C /* Mips.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Mips.td; sourceTree = ""; };
-		9F7794160C73CB6100551F9C /* MipsAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsAsmPrinter.cpp; sourceTree = ""; };
-		9F7794170C73CB6100551F9C /* MipsCallingConv.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = MipsCallingConv.td; sourceTree = ""; };
-		9F7794180C73CB6100551F9C /* MipsInstrFormats.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = MipsInstrFormats.td; sourceTree = ""; };
-		9F7794190C73CB6100551F9C /* MipsInstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsInstrInfo.cpp; sourceTree = ""; };
-		9F77941A0C73CB6100551F9C /* MipsInstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsInstrInfo.h; sourceTree = ""; };
-		9F77941B0C73CB6100551F9C /* MipsInstrInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = MipsInstrInfo.td; sourceTree = ""; };
-		9F77941C0C73CB6100551F9C /* MipsISelDAGToDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsISelDAGToDAG.cpp; sourceTree = ""; };
-		9F77941D0C73CB6100551F9C /* MipsISelLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsISelLowering.cpp; sourceTree = ""; };
-		9F77941E0C73CB6100551F9C /* MipsISelLowering.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsISelLowering.h; sourceTree = ""; };
-		9F77941F0C73CB6100551F9C /* MipsMachineFunction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsMachineFunction.h; sourceTree = ""; };
-		9F7794200C73CB6100551F9C /* MipsRegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsRegisterInfo.cpp; sourceTree = ""; };
-		9F7794210C73CB6100551F9C /* MipsRegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsRegisterInfo.h; sourceTree = ""; };
-		9F7794220C73CB6100551F9C /* MipsRegisterInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = MipsRegisterInfo.td; sourceTree = ""; };
-		9F7794230C73CB6100551F9C /* MipsSubtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsSubtarget.cpp; sourceTree = ""; };
-		9F7794240C73CB6100551F9C /* MipsSubtarget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsSubtarget.h; sourceTree = ""; };
-		9F7794250C73CB6100551F9C /* MipsTargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsTargetAsmInfo.cpp; sourceTree = ""; };
-		9F7794260C73CB6100551F9C /* MipsTargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsTargetAsmInfo.h; sourceTree = ""; };
-		9F7794270C73CB6100551F9C /* MipsTargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MipsTargetMachine.cpp; sourceTree = ""; };
-		9F7794280C73CB6100551F9C /* MipsTargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MipsTargetMachine.h; sourceTree = ""; };
-		9F77942F0C73CB7900551F9C /* MSILWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MSILWriter.cpp; sourceTree = ""; };
-		9F7794300C73CB7900551F9C /* MSILWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MSILWriter.h; sourceTree = ""; };
-		9F7794880C73D51000551F9C /* MemoryBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MemoryBuffer.h; sourceTree = ""; };
-		9F7794890C73D51000551F9C /* Streams.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Streams.h; sourceTree = ""; };
-		9F7C23E50CB81C2100498408 /* Analysis.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Analysis.h; sourceTree = ""; };
-		9F7C23E60CB81C2B00498408 /* Analysis.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Analysis.cpp; sourceTree = ""; };
-		9F7C240C0CB81ECD00498408 /* analysis_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = analysis_ocaml.c; sourceTree = ""; };
-		9F7C240D0CB81ECD00498408 /* llvm_analysis.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_analysis.ml; sourceTree = ""; };
-		9F7C240E0CB81ECD00498408 /* llvm_analysis.mli */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_analysis.mli; sourceTree = ""; };
-		9F7C2C4F0CB9496C00498408 /* analysis.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = analysis.ml; sourceTree = ""; };
-		9F7C2C520CB9496C00498408 /* bitwriter.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = bitwriter.ml; sourceTree = ""; };
-		9F7C2C5D0CB9496C00498408 /* vmcore.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = vmcore.ml; sourceTree = ""; };
-		9FA638D90C77B184007F12AE /* AutoUpgrade.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AutoUpgrade.h; sourceTree = ""; };
-		9FA638DA0C77B184007F12AE /* GlobalAlias.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GlobalAlias.h; sourceTree = ""; };
-		9FA638DB0C77B1AB007F12AE /* APInt.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = APInt.h; sourceTree = ""; };
-		9FA638DC0C77B1AB007F12AE /* APSInt.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = APSInt.h; sourceTree = ""; };
-		9FA638DD0C77B1AB007F12AE /* BitVector.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BitVector.h; sourceTree = ""; };
-		9FA638E00C77B1AB007F12AE /* IndexedMap.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IndexedMap.h; sourceTree = ""; };
-		9FA638E20C77B1AB007F12AE /* SmallPtrSet.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SmallPtrSet.h; sourceTree = ""; };
-		9FA638E30C77B1AB007F12AE /* SmallSet.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SmallSet.h; sourceTree = ""; };
-		9FA638E40C77B1AB007F12AE /* StringMap.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = StringMap.h; sourceTree = ""; };
-		9FA638E50C77B203007F12AE /* LoopPass.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = LoopPass.h; sourceTree = ""; };
-		9FA638E60C77B203007F12AE /* MemoryDependenceAnalysis.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MemoryDependenceAnalysis.h; sourceTree = ""; };
-		9FA638E70C77B222007F12AE /* Disassembler.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Disassembler.h; sourceTree = ""; };
-		9FA638E80C77B231007F12AE /* TargetELFWriterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetELFWriterInfo.h; sourceTree = ""; };
-		9FA638EA0C77B252007F12AE /* InlinerPass.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InlinerPass.h; sourceTree = ""; };
-		9FA638EB0C77B26B007F12AE /* BasicInliner.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BasicInliner.h; sourceTree = ""; };
-		9FA638EC0C77B26B007F12AE /* InlineCost.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InlineCost.h; sourceTree = ""; };
-		9FD3E5710CA0116100E54D15 /* bitwriter_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = bitwriter_ocaml.c; sourceTree = ""; };
-		9FD3E5720CA0116100E54D15 /* llvm_bitwriter.ml */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvm_bitwriter.ml; sourceTree = ""; };
-		9FD3E5730CA0116100E54D15 /* llvm_bitwriter.mli */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvm_bitwriter.mli; sourceTree = ""; };
-		9FD3E57B0CA0116100E54D15 /* llvm.ml */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvm.ml; sourceTree = ""; };
-		9FD3E57C0CA0116100E54D15 /* llvm.mli */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvm.mli; sourceTree = ""; };
-		9FD3E57D0CA0116100E54D15 /* llvm_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = llvm_ocaml.c; sourceTree = ""; };
-		9FD3E58D0CA0125F00E54D15 /* BitWriter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BitWriter.h; sourceTree = ""; };
-		9FD3E58E0CA0125F00E54D15 /* Core.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Core.h; sourceTree = ""; };
-		9FD3E5900CA0129D00E54D15 /* Core.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Core.cpp; path = ../lib/VMCore/Core.cpp; sourceTree = SOURCE_ROOT; };
-		9FD3E5920CA012B300E54D15 /* BitWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BitWriter.cpp; sourceTree = ""; };
-		9FE25D900CAB166D005383FC /* APFloat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APFloat.h; sourceTree = ""; };
-		9FE25D910CAB166D005383FC /* SparseBitVector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SparseBitVector.h; sourceTree = ""; };
-		9FE25D920CAB169F005383FC /* RegisterCoalescer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RegisterCoalescer.h; sourceTree = ""; };
-		9FE25D940CAB16FB005383FC /* RegisterCoalescer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RegisterCoalescer.cpp; sourceTree = ""; };
-		9FE25D950CAB1724005383FC /* APFloat.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = APFloat.cpp; sourceTree = ""; };
-		9FE25D960CAB1759005383FC /* TargetCallingConv.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = TargetCallingConv.td; sourceTree = ""; };
-		9FE4508B0C77A77000C4FEA4 /* ARMCodeEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ARMCodeEmitter.cpp; sourceTree = ""; };
-		9FE4508C0C77A77000C4FEA4 /* ARMGenAsmWriter.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenAsmWriter.inc; sourceTree = ""; };
-		9FE4508D0C77A77000C4FEA4 /* ARMGenDAGISel.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenDAGISel.inc; sourceTree = ""; };
-		9FE4508E0C77A77100C4FEA4 /* ARMGenInstrInfo.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenInstrInfo.inc; sourceTree = ""; };
-		9FE4508F0C77A77100C4FEA4 /* ARMGenInstrNames.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenInstrNames.inc; sourceTree = ""; };
-		9FE450900C77A77100C4FEA4 /* ARMGenRegisterInfo.h.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenRegisterInfo.h.inc; sourceTree = ""; };
-		9FE450910C77A77100C4FEA4 /* ARMGenRegisterInfo.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenRegisterInfo.inc; sourceTree = ""; };
-		9FE450920C77A77100C4FEA4 /* ARMGenRegisterNames.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenRegisterNames.inc; sourceTree = ""; };
-		9FE450930C77A77100C4FEA4 /* ARMGenSubtarget.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = ARMGenSubtarget.inc; sourceTree = ""; };
-		9FE450940C77A77100C4FEA4 /* ARMJITInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ARMJITInfo.cpp; sourceTree = ""; };
-		9FE450950C77A77100C4FEA4 /* ARMJITInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ARMJITInfo.h; sourceTree = ""; };
-		9FE450960C77A77100C4FEA4 /* ARMRelocations.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ARMRelocations.h; sourceTree = ""; };
-		9FE450970C77A77100C4FEA4 /* README-Thumb.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "README-Thumb.txt"; sourceTree = ""; };
-		9FE450980C77A77100C4FEA4 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		9FE4509A0C77A79C00C4FEA4 /* PPCCallingConv.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = PPCCallingConv.td; sourceTree = ""; };
-		9FE4509B0C77A79C00C4FEA4 /* PPCGenCallingConv.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = PPCGenCallingConv.inc; sourceTree = ""; };
-		9FE4509C0C77A7BC00C4FEA4 /* README-MMX.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "README-MMX.txt"; sourceTree = ""; };
-		9FE4509D0C77A7BC00C4FEA4 /* X86CallingConv.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = X86CallingConv.td; sourceTree = ""; };
-		9FE4509F0C77A7BC00C4FEA4 /* X86ELFWriterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86ELFWriterInfo.cpp; sourceTree = ""; };
-		9FE450A00C77A7BC00C4FEA4 /* X86ELFWriterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86ELFWriterInfo.h; sourceTree = ""; };
-		9FE450A10C77A7BC00C4FEA4 /* X86GenCallingConv.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.pascal; path = X86GenCallingConv.inc; sourceTree = ""; };
-		9FE450A20C77A7BC00C4FEA4 /* X86InstrFormats.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = X86InstrFormats.td; sourceTree = ""; };
-		9FE450A50C77AAF000C4FEA4 /* Disassembler.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Disassembler.cpp; sourceTree = ""; };
-		9FE450A60C77AB3200C4FEA4 /* APInt.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = APInt.cpp; sourceTree = ""; };
-		9FE450A70C77AB3200C4FEA4 /* ConstantRange.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ConstantRange.cpp; sourceTree = ""; };
-		9FE450A80C77AB3200C4FEA4 /* MemoryBuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MemoryBuffer.cpp; sourceTree = ""; };
-		9FE450A90C77AB3200C4FEA4 /* SmallPtrSet.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SmallPtrSet.cpp; sourceTree = ""; };
-		9FE450AA0C77AB3200C4FEA4 /* StringMap.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StringMap.cpp; sourceTree = ""; };
-		9FE450AB0C77AB6100C4FEA4 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		9FE450AC0C77AB6E00C4FEA4 /* CallingConvLower.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CallingConvLower.cpp; sourceTree = ""; };
-		9FE450DF0C77ABE400C4FEA4 /* Archive.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Archive.cpp; sourceTree = ""; };
-		9FE450E00C77ABE400C4FEA4 /* ArchiveInternals.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ArchiveInternals.h; sourceTree = ""; };
-		9FE450E10C77ABE400C4FEA4 /* ArchiveReader.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ArchiveReader.cpp; sourceTree = ""; };
-		9FE450E20C77ABE400C4FEA4 /* ArchiveWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ArchiveWriter.cpp; sourceTree = ""; };
-		9FEB8C550D1CD1E200EE46BC /* ExecutionEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ExecutionEngine.h; sourceTree = ""; };
-		9FEDD5F10D8D73AB009F6DF1 /* Scalar.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Scalar.h; sourceTree = ""; };
-		9FEDD5F70D8D797D009F6DF1 /* Scalar.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Scalar.cpp; sourceTree = ""; };
-		9FEDD6140D8D7C3B009F6DF1 /* scalar_opts.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = scalar_opts.ml; sourceTree = ""; };
-		9FEDD6B60D8D83D0009F6DF1 /* Target.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Target.cpp; sourceTree = ""; };
-		9FEDD6B80D8D83EC009F6DF1 /* Target.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Target.h; sourceTree = ""; };
-		9FEDD6BB0D8D8408009F6DF1 /* lto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lto.h; sourceTree = ""; };
-		9FEDD6BD0D8D8426009F6DF1 /* target.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = target.ml; sourceTree = ""; };
-		9FEDD6C10D8D844E009F6DF1 /* llvm_target.ml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_target.ml; sourceTree = ""; };
-		9FEDD6C20D8D844E009F6DF1 /* llvm_target.mli */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = llvm_target.mli; sourceTree = ""; };
-		9FEDD6C40D8D844E009F6DF1 /* target_ocaml.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = target_ocaml.c; sourceTree = ""; };
-		CF1ACC9709C9DE4400D3C5EB /* IntrinsicInst.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = IntrinsicInst.cpp; path = ../lib/VMCore/IntrinsicInst.cpp; sourceTree = ""; };
-		CF26835B09178F5500C5F253 /* TargetInstrItineraries.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TargetInstrItineraries.h; sourceTree = ""; };
-		CF32AF5C0AEE6A4E00D24CD4 /* LLVMTargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LLVMTargetMachine.cpp; sourceTree = ""; };
-		CF33BE160AF62B4200E93805 /* SmallString.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SmallString.h; sourceTree = ""; };
-		CF341DAD0AB07A8B0099B064 /* AlphaTargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AlphaTargetAsmInfo.h; sourceTree = ""; };
-		CF341DAE0AB07A8B0099B064 /* AlphaTargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaTargetAsmInfo.cpp; sourceTree = ""; };
-		CF341E010AB080220099B064 /* PPCTargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCTargetAsmInfo.h; sourceTree = ""; };
-		CF341E020AB080220099B064 /* PPCTargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCTargetAsmInfo.cpp; sourceTree = ""; };
-		CF341E220AB0814B0099B064 /* SparcTargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SparcTargetAsmInfo.h; sourceTree = ""; };
-		CF341E230AB0814B0099B064 /* SparcTargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SparcTargetAsmInfo.cpp; sourceTree = ""; };
-		CF341E320AB082D60099B064 /* X86TargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = X86TargetAsmInfo.h; sourceTree = ""; };
-		CF341E330AB082D60099B064 /* X86TargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = X86TargetAsmInfo.cpp; sourceTree = ""; };
-		CF42B6BF0AF24F5300D5D47C /* FoldingSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FoldingSet.h; sourceTree = ""; };
-		CF42B6C40AF2512000D5D47C /* FoldingSet.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FoldingSet.cpp; sourceTree = ""; };
-		CF47BD380AAF40BC00A8B13E /* TargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TargetAsmInfo.h; sourceTree = ""; };
-		CF47BD860AAF487E00A8B13E /* TargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TargetAsmInfo.cpp; sourceTree = ""; };
-		CF490D14090541D30072DB1C /* TargetSchedule.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = TargetSchedule.td; sourceTree = ""; };
-		CF490D15090541D30072DB1C /* TargetSelectionDAG.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = TargetSelectionDAG.td; sourceTree = ""; };
-		CF490E2F0907BBF80072DB1C /* SubtargetEmitter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SubtargetEmitter.h; sourceTree = ""; };
-		CF490E300907BBF80072DB1C /* SubtargetEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SubtargetEmitter.cpp; sourceTree = ""; };
-		CF4F27E60A7B6E23004359F6 /* MachinePassRegistry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachinePassRegistry.h; sourceTree = ""; };
-		CF4F27F60A7B6FA3004359F6 /* MachinePassRegistry.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MachinePassRegistry.cpp; sourceTree = ""; };
-		CF65223409CA39B800C4B521 /* Intrinsics.gen */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Intrinsics.gen; sourceTree = ""; };
-		CF6527D909D1A53400C4B521 /* MachineLocation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachineLocation.h; sourceTree = ""; };
-		CF6527FA09D1BA3800C4B521 /* DelaySlotFiller.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DelaySlotFiller.cpp; path = ../lib/Target/Sparc/DelaySlotFiller.cpp; sourceTree = SOURCE_ROOT; };
-		CF6527FB09D1BA3800C4B521 /* FPMover.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = FPMover.cpp; path = ../lib/Target/Sparc/FPMover.cpp; sourceTree = SOURCE_ROOT; };
-		CF6527FC09D1BA3800C4B521 /* Makefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.make; name = Makefile; path = ../lib/Target/Sparc/Makefile; sourceTree = SOURCE_ROOT; };
-		CF6527FD09D1BA3800C4B521 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = README.txt; path = ../lib/Target/Sparc/README.txt; sourceTree = SOURCE_ROOT; };
-		CF6527FE09D1BA3800C4B521 /* Sparc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Sparc.h; path = ../lib/Target/Sparc/Sparc.h; sourceTree = SOURCE_ROOT; };
-		CF6527FF09D1BA3800C4B521 /* Sparc.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Sparc.td; path = ../lib/Target/Sparc/Sparc.td; sourceTree = SOURCE_ROOT; };
-		CF65280009D1BA3800C4B521 /* SparcAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SparcAsmPrinter.cpp; path = ../lib/Target/Sparc/SparcAsmPrinter.cpp; sourceTree = SOURCE_ROOT; };
-		CF65280109D1BA3800C4B521 /* SparcGenAsmWriter.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenAsmWriter.inc; path = ../lib/Target/Sparc/SparcGenAsmWriter.inc; sourceTree = SOURCE_ROOT; };
-		CF65280209D1BA3800C4B521 /* SparcGenDAGISel.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenDAGISel.inc; path = ../lib/Target/Sparc/SparcGenDAGISel.inc; sourceTree = SOURCE_ROOT; };
-		CF65280309D1BA3800C4B521 /* SparcGenInstrInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenInstrInfo.inc; path = ../lib/Target/Sparc/SparcGenInstrInfo.inc; sourceTree = SOURCE_ROOT; };
-		CF65280409D1BA3800C4B521 /* SparcGenInstrNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenInstrNames.inc; path = ../lib/Target/Sparc/SparcGenInstrNames.inc; sourceTree = SOURCE_ROOT; };
-		CF65280509D1BA3800C4B521 /* SparcGenRegisterInfo.h.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenRegisterInfo.h.inc; path = ../lib/Target/Sparc/SparcGenRegisterInfo.h.inc; sourceTree = SOURCE_ROOT; };
-		CF65280609D1BA3800C4B521 /* SparcGenRegisterInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenRegisterInfo.inc; path = ../lib/Target/Sparc/SparcGenRegisterInfo.inc; sourceTree = SOURCE_ROOT; };
-		CF65280709D1BA3800C4B521 /* SparcGenRegisterNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenRegisterNames.inc; path = ../lib/Target/Sparc/SparcGenRegisterNames.inc; sourceTree = SOURCE_ROOT; };
-		CF65280809D1BA3800C4B521 /* SparcGenSubtarget.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; name = SparcGenSubtarget.inc; path = ../lib/Target/Sparc/SparcGenSubtarget.inc; sourceTree = SOURCE_ROOT; };
-		CF65280909D1BA3800C4B521 /* SparcInstrFormats.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = SparcInstrFormats.td; path = ../lib/Target/Sparc/SparcInstrFormats.td; sourceTree = SOURCE_ROOT; };
-		CF65280A09D1BA3800C4B521 /* SparcInstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SparcInstrInfo.cpp; path = ../lib/Target/Sparc/SparcInstrInfo.cpp; sourceTree = SOURCE_ROOT; };
-		CF65280B09D1BA3800C4B521 /* SparcInstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SparcInstrInfo.h; path = ../lib/Target/Sparc/SparcInstrInfo.h; sourceTree = SOURCE_ROOT; };
-		CF65280C09D1BA3800C4B521 /* SparcInstrInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = SparcInstrInfo.td; path = ../lib/Target/Sparc/SparcInstrInfo.td; sourceTree = SOURCE_ROOT; };
-		CF65280D09D1BA3800C4B521 /* SparcISelDAGToDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SparcISelDAGToDAG.cpp; path = ../lib/Target/Sparc/SparcISelDAGToDAG.cpp; sourceTree = SOURCE_ROOT; };
-		CF65280E09D1BA3800C4B521 /* SparcRegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SparcRegisterInfo.cpp; path = ../lib/Target/Sparc/SparcRegisterInfo.cpp; sourceTree = SOURCE_ROOT; };
-		CF65280F09D1BA3800C4B521 /* SparcRegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SparcRegisterInfo.h; path = ../lib/Target/Sparc/SparcRegisterInfo.h; sourceTree = SOURCE_ROOT; };
-		CF65281009D1BA3800C4B521 /* SparcRegisterInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = SparcRegisterInfo.td; path = ../lib/Target/Sparc/SparcRegisterInfo.td; sourceTree = SOURCE_ROOT; };
-		CF65281109D1BA3800C4B521 /* SparcSubtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SparcSubtarget.cpp; path = ../lib/Target/Sparc/SparcSubtarget.cpp; sourceTree = SOURCE_ROOT; };
-		CF65281209D1BA3800C4B521 /* SparcSubtarget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SparcSubtarget.h; path = ../lib/Target/Sparc/SparcSubtarget.h; sourceTree = SOURCE_ROOT; };
-		CF65281309D1BA3800C4B521 /* SparcTargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SparcTargetMachine.cpp; path = ../lib/Target/Sparc/SparcTargetMachine.cpp; sourceTree = SOURCE_ROOT; };
-		CF65281409D1BA3800C4B521 /* SparcTargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SparcTargetMachine.h; path = ../lib/Target/Sparc/SparcTargetMachine.h; sourceTree = SOURCE_ROOT; };
-		CF6529A6095B21A8007F884E /* MachineModuleInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MachineModuleInfo.cpp; sourceTree = ""; };
-		CF6B5AFD095C82C300D1EA42 /* DAGCombiner.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DAGCombiner.cpp; sourceTree = ""; };
-		CF6F487109505E1500BC9E82 /* MachineModuleInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachineModuleInfo.h; sourceTree = ""; };
-		CF71B60F0AC45EDA0007F57C /* SmallVector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SmallVector.h; sourceTree = ""; };
-		CF73C0A2098A4FDF00627152 /* InlineAsm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InlineAsm.h; sourceTree = ""; };
-		CF73C0A3098A4FDF00627152 /* TypeSymbolTable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypeSymbolTable.h; sourceTree = ""; };
-		CF73C0A4098A4FDF00627152 /* ValueSymbolTable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ValueSymbolTable.h; sourceTree = ""; };
-		CF73C0A5098A507300627152 /* ConstantFolding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ConstantFolding.h; sourceTree = ""; };
-		CF73C0A9098A50FD00627152 /* config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = config.h; sourceTree = ""; };
-		CF73C0AD098A519400627152 /* DataTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataTypes.h; sourceTree = ""; };
-		CF73C0AE098A51AD00627152 /* Alarm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Alarm.h; sourceTree = ""; };
-		CF73C0AF098A51DD00627152 /* RSProfiling.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RSProfiling.h; sourceTree = ""; };
-		CF73C0B0098A523C00627152 /* ConstantFolding.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConstantFolding.cpp; sourceTree = ""; };
-		CF73C0B7098A546000627152 /* RSProfiling.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RSProfiling.cpp; sourceTree = ""; };
-		CF73C0B8098A546000627152 /* RSProfiling.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RSProfiling.h; sourceTree = ""; };
-		CF73C0B9098A546000627152 /* Reg2Mem.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Reg2Mem.cpp; sourceTree = ""; };
-		CF73C0BD098A551F00627152 /* InlineAsm.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = InlineAsm.cpp; path = ../lib/VMCore/InlineAsm.cpp; sourceTree = SOURCE_ROOT; };
-		CF73C0BE098A551F00627152 /* TypeSymbolTable.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TypeSymbolTable.cpp; path = ../lib/VMCore/TypeSymbolTable.cpp; sourceTree = SOURCE_ROOT; };
-		CF73C0BF098A551F00627152 /* ValueSymbolTable.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ValueSymbolTable.cpp; path = ../lib/VMCore/ValueSymbolTable.cpp; sourceTree = SOURCE_ROOT; };
-		CF79495D09B326D4005ADFCA /* Dwarf.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Dwarf.cpp; sourceTree = ""; };
-		CF7FFA1F0985081C008B0087 /* ScheduleDAGList.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScheduleDAGList.cpp; sourceTree = ""; };
-		CF7FFA2109850864008B0087 /* ScheduleDAG.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScheduleDAG.h; sourceTree = ""; };
-		CF8D62FA09C2226F006017BA /* Intrinsics.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Intrinsics.td; sourceTree = ""; };
-		CF8E00490989162500DA2399 /* Dwarf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Dwarf.h; sourceTree = ""; };
-		CF8F1B410B64F6D100BB4199 /* RuntimeLibcalls.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuntimeLibcalls.h; sourceTree = ""; };
-		CF8F1B420B64F70B00BB4199 /* PassManagers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PassManagers.h; sourceTree = ""; };
-		CF8F1B430B64F74400BB4199 /* Allocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Allocator.h; sourceTree = ""; };
-		CF8F1B440B64F74400BB4199 /* Compiler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Compiler.h; sourceTree = ""; };
-		CF8F1B460B64F74400BB4199 /* ManagedStatic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ManagedStatic.h; sourceTree = ""; };
-		CF8F1B470B64F74400BB4199 /* OutputBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OutputBuffer.h; sourceTree = ""; };
-		CF8F1B490B64F7AB00BB4199 /* LinkTimeOptimizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkTimeOptimizer.h; sourceTree = ""; };
-		CF8F1B4D0B64F80700BB4199 /* AliasDebugger.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AliasDebugger.cpp; sourceTree = ""; };
-		CF8F1B500B64F86A00BB4199 /* ManagedStatic.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ManagedStatic.cpp; sourceTree = ""; };
-		CF8F1B510B64F86A00BB4199 /* Streams.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Streams.cpp; sourceTree = ""; };
-		CF8F1B530B64F8C000BB4199 /* IncludeFile.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IncludeFile.cpp; sourceTree = ""; };
-		CF8F1B540B64F90F00BB4199 /* AlphaBranchSelector.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaBranchSelector.cpp; sourceTree = ""; };
-		CF8F1B550B64F90F00BB4199 /* AlphaLLRP.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaLLRP.cpp; sourceTree = ""; };
-		CF8F1B560B64F98900BB4199 /* CBackend.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CBackend.cpp; sourceTree = ""; };
-		CF8F1B570B64F9AC00BB4199 /* PPCPredicates.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCPredicates.cpp; sourceTree = ""; };
-		CF8F1B580B64F9AC00BB4199 /* PPCPredicates.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCPredicates.h; sourceTree = ""; };
-		CF8F1B590B64F9E100BB4199 /* X86COFF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = X86COFF.h; sourceTree = ""; };
-		CF8F1B5B0B64FA2F00BB4199 /* PredicateSimplifier.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredicateSimplifier.cpp; sourceTree = ""; };
-		CF8F1B5C0B64FA7300BB4199 /* PassManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = PassManager.cpp; path = ../lib/VMCore/PassManager.cpp; sourceTree = SOURCE_ROOT; };
-		CF8F1B680B64FADA00BB4199 /* llvm-upgrade.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "llvm-upgrade.cpp"; sourceTree = ""; };
-		CF8F1B720B64FADA00BB4199 /* UpgradeInternals.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UpgradeInternals.h; sourceTree = ""; };
-		CF8F1B750B64FADA00BB4199 /* UpgradeLexer.l */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.lex; path = UpgradeLexer.l; sourceTree = ""; };
-		CF8F1B7C0B64FADA00BB4199 /* UpgradeParser.y */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.yacc; path = UpgradeParser.y; sourceTree = ""; };
-		CF8F1B7F0B64FADA00BB4199 /* CppWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CppWriter.cpp; sourceTree = ""; };
-		CF8F1B800B64FADA00BB4199 /* CppWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CppWriter.h; sourceTree = ""; };
-		CF8F1B870B64FADA00BB4199 /* llvm2cpp.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = llvm2cpp.cpp; sourceTree = ""; };
-		CF8F1B950B64FB5000BB4199 /* ConfigLexer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConfigLexer.cpp; sourceTree = ""; };
-		CF8F1B9D0B64FB7F00BB4199 /* lto-c.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "lto-c.cpp"; sourceTree = ""; };
-		CF8F1B9E0B64FB7F00BB4199 /* lto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = lto.cpp; sourceTree = ""; };
-		CF8F1BAC0B64FB8000BB4199 /* AnalysisWrappers.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AnalysisWrappers.cpp; sourceTree = ""; };
-		CF8F1BB70B64FB8000BB4199 /* GraphPrinters.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GraphPrinters.cpp; sourceTree = ""; };
-		CF8F1BB90B64FB8000BB4199 /* opt.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = opt.cpp; sourceTree = ""; };
-		CF8F1BBA0B64FB8000BB4199 /* PrintSCC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PrintSCC.cpp; sourceTree = ""; };
-		CF8F1BC90B64FBD500BB4199 /* CodeGenIntrinsics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CodeGenIntrinsics.h; sourceTree = ""; };
-		CF8F1BD10B64FC8A00BB4199 /* ARM.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARM.h; sourceTree = ""; };
-		CF8F1BD20B64FC8A00BB4199 /* ARM.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ARM.td; sourceTree = ""; };
-		CF8F1BD30B64FC8A00BB4199 /* ARMAddressingModes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMAddressingModes.h; sourceTree = ""; };
-		CF8F1BD40B64FC8A00BB4199 /* ARMAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMAsmPrinter.cpp; sourceTree = ""; };
-		CF8F1BD50B64FC8A00BB4199 /* ARMConstantIslandPass.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMConstantIslandPass.cpp; sourceTree = ""; };
-		CF8F1BD60B64FC8A00BB4199 /* ARMConstantPoolValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMConstantPoolValue.cpp; sourceTree = ""; };
-		CF8F1BD70B64FC8A00BB4199 /* ARMConstantPoolValue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMConstantPoolValue.h; sourceTree = ""; };
-		CF8F1BD80B64FC8A00BB4199 /* ARMFrameInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMFrameInfo.h; sourceTree = ""; };
-		CF8F1BD90B64FC8A00BB4199 /* ARMInstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMInstrInfo.cpp; sourceTree = ""; };
-		CF8F1BDA0B64FC8A00BB4199 /* ARMInstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMInstrInfo.h; sourceTree = ""; };
-		CF8F1BDB0B64FC8A00BB4199 /* ARMInstrInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ARMInstrInfo.td; sourceTree = ""; };
-		CF8F1BDC0B64FC8A00BB4199 /* ARMInstrThumb.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ARMInstrThumb.td; sourceTree = ""; };
-		CF8F1BDD0B64FC8A00BB4199 /* ARMInstrVFP.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ARMInstrVFP.td; sourceTree = ""; };
-		CF8F1BDE0B64FC8A00BB4199 /* ARMISelDAGToDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMISelDAGToDAG.cpp; sourceTree = ""; };
-		CF8F1BDF0B64FC8A00BB4199 /* ARMISelLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMISelLowering.cpp; sourceTree = ""; };
-		CF8F1BE00B64FC8A00BB4199 /* ARMISelLowering.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMISelLowering.h; sourceTree = ""; };
-		CF8F1BE10B64FC8A00BB4199 /* ARMLoadStoreOptimizer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMLoadStoreOptimizer.cpp; sourceTree = ""; };
-		CF8F1BE20B64FC8A00BB4199 /* ARMMachineFunctionInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMMachineFunctionInfo.h; sourceTree = ""; };
-		CF8F1BE30B64FC8A00BB4199 /* ARMRegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMRegisterInfo.cpp; sourceTree = ""; };
-		CF8F1BE40B64FC8A00BB4199 /* ARMRegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMRegisterInfo.h; sourceTree = ""; };
-		CF8F1BE50B64FC8A00BB4199 /* ARMRegisterInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ARMRegisterInfo.td; sourceTree = ""; };
-		CF8F1BE60B64FC8A00BB4199 /* ARMSubtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMSubtarget.cpp; sourceTree = ""; };
-		CF8F1BE70B64FC8A00BB4199 /* ARMSubtarget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMSubtarget.h; sourceTree = ""; };
-		CF8F1BE80B64FC8A00BB4199 /* ARMTargetAsmInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMTargetAsmInfo.cpp; sourceTree = ""; };
-		CF8F1BE90B64FC8A00BB4199 /* ARMTargetAsmInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMTargetAsmInfo.h; sourceTree = ""; };
-		CF8F1BEA0B64FC8A00BB4199 /* ARMTargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ARMTargetMachine.cpp; sourceTree = ""; };
-		CF8F1BEB0B64FC8A00BB4199 /* ARMTargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARMTargetMachine.h; sourceTree = ""; };
-		CF9720260A9F39B9002CEEDD /* LinkAllPasses.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkAllPasses.h; sourceTree = ""; };
-		CF9720270A9F39B9002CEEDD /* LinkTimeOptimizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkTimeOptimizer.h; sourceTree = ""; };
-		CF9720340A9F3A41002CEEDD /* IncludeFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IncludeFile.h; sourceTree = ""; };
-		CF9720350A9F3ADC002CEEDD /* MachOWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MachOWriter.cpp; sourceTree = ""; };
-		CF9720370A9F3B1C002CEEDD /* TargetLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TargetLowering.cpp; sourceTree = ""; };
-		CF97208A0A9F3C6F002CEEDD /* LCSSA.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LCSSA.cpp; sourceTree = ""; };
-		CF97208B0A9F3C6F002CEEDD /* LowerAllocations.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LowerAllocations.cpp; sourceTree = ""; };
-		CF97208C0A9F3C6F002CEEDD /* LowerInvoke.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LowerInvoke.cpp; sourceTree = ""; };
-		CF97208E0A9F3C6F002CEEDD /* LowerSwitch.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LowerSwitch.cpp; sourceTree = ""; };
-		CF97208F0A9F3C6F002CEEDD /* Mem2Reg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Mem2Reg.cpp; sourceTree = ""; };
-		CF9720900A9F3CA2002CEEDD /* ValueTypes.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ValueTypes.cpp; path = ../lib/VMCore/ValueTypes.cpp; sourceTree = SOURCE_ROOT; };
-		CF9720910A9F3CC7002CEEDD /* FindBugs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FindBugs.cpp; sourceTree = ""; };
-		CF9720920A9F3CC7002CEEDD /* ToolRunner.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ToolRunner.cpp; sourceTree = ""; };
-		CF9720930A9F3CC7002CEEDD /* ToolRunner.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ToolRunner.h; sourceTree = ""; };
-		CF9720970A9F3D4D002CEEDD /* IntrinsicEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IntrinsicEmitter.cpp; sourceTree = ""; };
-		CF9720980A9F3D4D002CEEDD /* IntrinsicEmitter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IntrinsicEmitter.h; sourceTree = ""; };
-		CF9BCD0808C74DE0001E7011 /* SubtargetFeature.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SubtargetFeature.h; sourceTree = ""; };
-		CF9BCD1508C75070001E7011 /* SubtargetFeature.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SubtargetFeature.cpp; sourceTree = ""; };
-		CFA702BB0A6FA85F0006009A /* AlphaGenAsmWriter.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenAsmWriter.inc; sourceTree = ""; };
-		CFA702BC0A6FA85F0006009A /* AlphaGenCodeEmitter.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenCodeEmitter.inc; sourceTree = ""; };
-		CFA702BD0A6FA85F0006009A /* AlphaGenDAGISel.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenDAGISel.inc; sourceTree = ""; };
-		CFA702BE0A6FA85F0006009A /* AlphaGenInstrInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenInstrInfo.inc; sourceTree = ""; };
-		CFA702BF0A6FA85F0006009A /* AlphaGenInstrNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenInstrNames.inc; sourceTree = ""; };
-		CFA702C00A6FA85F0006009A /* AlphaGenRegisterInfo.h.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenRegisterInfo.h.inc; sourceTree = ""; };
-		CFA702C10A6FA85F0006009A /* AlphaGenRegisterInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenRegisterInfo.inc; sourceTree = ""; };
-		CFA702C20A6FA85F0006009A /* AlphaGenRegisterNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenRegisterNames.inc; sourceTree = ""; };
-		CFA702C30A6FA85F0006009A /* AlphaGenSubtarget.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = AlphaGenSubtarget.inc; sourceTree = ""; };
-		CFA702CB0A6FA8AD0006009A /* PPCGenAsmWriter.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenAsmWriter.inc; sourceTree = ""; };
-		CFA702CC0A6FA8AD0006009A /* PPCGenCodeEmitter.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenCodeEmitter.inc; sourceTree = ""; };
-		CFA702CD0A6FA8AD0006009A /* PPCGenDAGISel.inc */ = {isa = PBXFileReference; explicitFileType = sourcecode.pascal; fileEncoding = 4; path = PPCGenDAGISel.inc; sourceTree = ""; };
-		CFA702CE0A6FA8AD0006009A /* PPCGenInstrInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenInstrInfo.inc; sourceTree = ""; };
-		CFA702CF0A6FA8AD0006009A /* PPCGenInstrNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenInstrNames.inc; sourceTree = ""; };
-		CFA702D00A6FA8AD0006009A /* PPCGenRegisterInfo.h.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenRegisterInfo.h.inc; sourceTree = ""; };
-		CFA702D10A6FA8AD0006009A /* PPCGenRegisterInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenRegisterInfo.inc; sourceTree = ""; };
-		CFA702D20A6FA8AD0006009A /* PPCGenRegisterNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenRegisterNames.inc; sourceTree = ""; };
-		CFA702D30A6FA8AD0006009A /* PPCGenSubtarget.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = PPCGenSubtarget.inc; sourceTree = ""; };
-		CFA702D40A6FA8DD0006009A /* X86GenAsmWriter.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenAsmWriter.inc; sourceTree = ""; };
-		CFA702D50A6FA8DD0006009A /* X86GenAsmWriter1.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenAsmWriter1.inc; sourceTree = ""; };
-		CFA702D60A6FA8DD0006009A /* X86GenDAGISel.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenDAGISel.inc; sourceTree = ""; };
-		CFA702D70A6FA8DD0006009A /* X86GenInstrInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenInstrInfo.inc; sourceTree = ""; };
-		CFA702D80A6FA8DD0006009A /* X86GenInstrNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenInstrNames.inc; sourceTree = ""; };
-		CFA702D90A6FA8DD0006009A /* X86GenRegisterInfo.h.inc */ = {isa = PBXFileReference; fileEncoding = 4; languageSpecificationIdentifier = c.cpp; lastKnownFileType = sourcecode.pascal; path = X86GenRegisterInfo.h.inc; sourceTree = ""; };
-		CFA702DA0A6FA8DD0006009A /* X86GenRegisterInfo.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenRegisterInfo.inc; sourceTree = ""; };
-		CFA702DB0A6FA8DD0006009A /* X86GenRegisterNames.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenRegisterNames.inc; sourceTree = ""; };
-		CFA702DC0A6FA8DD0006009A /* X86GenSubtarget.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = X86GenSubtarget.inc; sourceTree = ""; };
-		CFABD0A20B09E342003EB061 /* PPCMachineFunctionInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCMachineFunctionInfo.h; sourceTree = ""; };
-		CFBD8B1A090E76540020B107 /* AlphaISelDAGToDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaISelDAGToDAG.cpp; sourceTree = ""; };
-		CFBD8B1B090E76540020B107 /* AlphaISelLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaISelLowering.cpp; sourceTree = ""; };
-		CFBD8B1C090E76540020B107 /* AlphaISelLowering.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AlphaISelLowering.h; sourceTree = ""; };
-		CFBD8B1D090E76540020B107 /* AlphaSubtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaSubtarget.cpp; sourceTree = ""; };
-		CFBD8B1E090E76540020B107 /* AlphaSubtarget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AlphaSubtarget.h; sourceTree = ""; };
-		CFC244570959DEF2009F8C47 /* DwarfWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DwarfWriter.cpp; sourceTree = ""; };
-		CFC244BB0959F24C009F8C47 /* X86ISelDAGToDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = X86ISelDAGToDAG.cpp; sourceTree = ""; };
-		CFC244BC0959F24C009F8C47 /* X86ISelLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = X86ISelLowering.cpp; sourceTree = ""; };
-		CFC244BD0959F24C009F8C47 /* X86ISelLowering.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = X86ISelLowering.h; sourceTree = ""; };
-		CFD7E4F30A798FC3000C7379 /* LinkAllCodegenComponents.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkAllCodegenComponents.h; sourceTree = ""; };
-		CFD99AA80AFE827B0068D19C /* LICENSE.TXT */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = LICENSE.TXT; path = ../LICENSE.TXT; sourceTree = SOURCE_ROOT; };
-		CFD99AAD0AFE827B0068D19C /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = README.txt; path = ../README.txt; sourceTree = SOURCE_ROOT; };
-		CFD99AB70AFE848A0068D19C /* Allocator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Allocator.cpp; sourceTree = ""; };
-		CFD99ABA0AFE84D70068D19C /* IncludeFile.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IncludeFile.cpp; sourceTree = ""; };
-		CFD99ABB0AFE84EF0068D19C /* Alarm.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = Alarm.inc; sourceTree = ""; };
-		CFD99ABE0AFE857A0068D19C /* README-X86-64.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "README-X86-64.txt"; sourceTree = ""; };
-		CFD99ADA0AFE87650068D19C /* lto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = lto.cpp; path = lto/lto.cpp; sourceTree = ""; };
-		CFD99ADB0AFE87870068D19C /* AnalysisWrappers.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AnalysisWrappers.cpp; path = opt/AnalysisWrappers.cpp; sourceTree = ""; };
-		CFD99ADC0AFE87870068D19C /* GraphPrinters.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = GraphPrinters.cpp; path = opt/GraphPrinters.cpp; sourceTree = ""; };
-		CFD99ADD0AFE87870068D19C /* opt.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = opt.cpp; path = opt/opt.cpp; sourceTree = ""; };
-		CFD99ADE0AFE87870068D19C /* PrintSCC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = PrintSCC.cpp; path = opt/PrintSCC.cpp; sourceTree = ""; };
-		CFE21C780A80CC0600D3E908 /* RegAllocRegistry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RegAllocRegistry.h; sourceTree = ""; };
-		CFE21C7B0A80CC1C00D3E908 /* SchedulerRegistry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SchedulerRegistry.h; sourceTree = ""; };
-		CFE420FB0A66F67300AB4BF6 /* MachineJumpTableInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachineJumpTableInfo.h; sourceTree = ""; };
-		CFE420FC0A66F67300AB4BF6 /* ValueTypes.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ValueTypes.td; sourceTree = ""; };
-		CFE420FD0A66F67300AB4BF6 /* Interpreter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Interpreter.h; sourceTree = ""; };
-		CFE420FE0A66F67300AB4BF6 /* JIT.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JIT.h; sourceTree = ""; };
-		CFE420FF0A66F67300AB4BF6 /* IntrinsicsPowerPC.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = IntrinsicsPowerPC.td; sourceTree = ""; };
-		CFE421000A66F67300AB4BF6 /* IntrinsicsX86.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = IntrinsicsX86.td; sourceTree = ""; };
-		CFE421010A66F67300AB4BF6 /* LinkAllVMCore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LinkAllVMCore.h; sourceTree = ""; };
-		CFE421060A66F86D00AB4BF6 /* ScheduleDAGRRList.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScheduleDAGRRList.cpp; sourceTree = ""; };
-		CFE421070A66F8DC00AB4BF6 /* GraphWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GraphWriter.cpp; sourceTree = ""; };
-		CFE421090A66F93300AB4BF6 /* Alarm.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Alarm.cpp; sourceTree = ""; };
-		CFE4210A0A66F93300AB4BF6 /* Alarm.inc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.pascal; path = Alarm.inc; sourceTree = ""; };
-		CFE4210B0A66F96400AB4BF6 /* AlphaSchedule.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = AlphaSchedule.td; sourceTree = ""; };
-		CFE421140A66FA2D00AB4BF6 /* PPC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPC.h; sourceTree = ""; };
-		CFE421150A66FA2D00AB4BF6 /* PPC.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPC.td; sourceTree = ""; };
-		CFE421160A66FA2D00AB4BF6 /* PPCAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCAsmPrinter.cpp; sourceTree = ""; };
-		CFE421170A66FA2D00AB4BF6 /* PPCBranchSelector.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCBranchSelector.cpp; sourceTree = ""; };
-		CFE421180A66FA2D00AB4BF6 /* PPCCodeEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCCodeEmitter.cpp; sourceTree = ""; };
-		CFE421190A66FA2D00AB4BF6 /* PPCFrameInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCFrameInfo.h; sourceTree = ""; };
-		CFE4211A0A66FA2D00AB4BF6 /* PPCHazardRecognizers.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCHazardRecognizers.cpp; sourceTree = ""; };
-		CFE4211B0A66FA2D00AB4BF6 /* PPCHazardRecognizers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCHazardRecognizers.h; sourceTree = ""; };
-		CFE4211C0A66FA2D00AB4BF6 /* PPCInstr64Bit.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCInstr64Bit.td; sourceTree = ""; };
-		CFE4211D0A66FA2D00AB4BF6 /* PPCInstrAltivec.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCInstrAltivec.td; sourceTree = ""; };
-		CFE4211E0A66FA2D00AB4BF6 /* PPCInstrBuilder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCInstrBuilder.h; sourceTree = ""; };
-		CFE4211F0A66FA2D00AB4BF6 /* PPCInstrFormats.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCInstrFormats.td; sourceTree = ""; };
-		CFE421200A66FA2D00AB4BF6 /* PPCInstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCInstrInfo.cpp; sourceTree = ""; };
-		CFE421210A66FA2D00AB4BF6 /* PPCInstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCInstrInfo.h; sourceTree = ""; };
-		CFE421220A66FA2D00AB4BF6 /* PPCInstrInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCInstrInfo.td; sourceTree = ""; };
-		CFE421230A66FA2D00AB4BF6 /* PPCISelDAGToDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCISelDAGToDAG.cpp; sourceTree = ""; };
-		CFE421240A66FA2D00AB4BF6 /* PPCISelLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCISelLowering.cpp; sourceTree = ""; };
-		CFE421250A66FA2D00AB4BF6 /* PPCISelLowering.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCISelLowering.h; sourceTree = ""; };
-		CFE421260A66FA2D00AB4BF6 /* PPCJITInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCJITInfo.cpp; sourceTree = ""; };
-		CFE421270A66FA2D00AB4BF6 /* PPCJITInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCJITInfo.h; sourceTree = ""; };
-		CFE421280A66FA2D00AB4BF6 /* PPCPerfectShuffle.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCPerfectShuffle.h; sourceTree = ""; };
-		CFE421290A66FA2D00AB4BF6 /* PPCRegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCRegisterInfo.cpp; sourceTree = ""; };
-		CFE4212A0A66FA2D00AB4BF6 /* PPCRegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCRegisterInfo.h; sourceTree = ""; };
-		CFE4212B0A66FA2D00AB4BF6 /* PPCRegisterInfo.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCRegisterInfo.td; sourceTree = ""; };
-		CFE4212C0A66FA2D00AB4BF6 /* PPCRelocations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCRelocations.h; sourceTree = ""; };
-		CFE4212D0A66FA2D00AB4BF6 /* PPCSchedule.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCSchedule.td; sourceTree = ""; };
-		CFE4212E0A66FA2D00AB4BF6 /* PPCScheduleG3.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCScheduleG3.td; sourceTree = ""; };
-		CFE4212F0A66FA2D00AB4BF6 /* PPCScheduleG4.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCScheduleG4.td; sourceTree = ""; };
-		CFE421300A66FA2D00AB4BF6 /* PPCScheduleG4Plus.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCScheduleG4Plus.td; sourceTree = ""; };
-		CFE421310A66FA2D00AB4BF6 /* PPCScheduleG5.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PPCScheduleG5.td; sourceTree = ""; };
-		CFE421320A66FA2E00AB4BF6 /* PPCSubtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCSubtarget.cpp; sourceTree = ""; };
-		CFE421330A66FA2E00AB4BF6 /* PPCSubtarget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCSubtarget.h; sourceTree = ""; };
-		CFE421340A66FA2E00AB4BF6 /* PPCTargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PPCTargetMachine.cpp; sourceTree = ""; };
-		CFE421350A66FA2E00AB4BF6 /* PPCTargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PPCTargetMachine.h; sourceTree = ""; };
-		CFE421360A66FA2E00AB4BF6 /* README_ALTIVEC.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README_ALTIVEC.txt; sourceTree = ""; };
-		CFE421370A66FA2E00AB4BF6 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		CFE421380A66FA8000AB4BF6 /* README-FPStack.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "README-FPStack.txt"; sourceTree = ""; };
-		CFE421390A66FA8000AB4BF6 /* README-SSE.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "README-SSE.txt"; sourceTree = ""; };
-		CFE4213A0A66FA8000AB4BF6 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		CFE4213B0A66FA8000AB4BF6 /* X86MachineFunctionInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = X86MachineFunctionInfo.h; sourceTree = ""; };
-		CFE4213D0A66FAE100AB4BF6 /* Hello.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Hello.cpp; sourceTree = ""; };
-		CFE4213F0A66FB5E00AB4BF6 /* IndMemRemoval.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IndMemRemoval.cpp; sourceTree = ""; };
-		CFF0DE6309BF6C360031957F /* X86InstrFPStack.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = X86InstrFPStack.td; sourceTree = ""; };
-		CFF0DE6409BF6C360031957F /* X86InstrMMX.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = X86InstrMMX.td; sourceTree = ""; };
-		CFF0DE6509BF6C360031957F /* X86InstrSSE.td */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = X86InstrSSE.td; sourceTree = ""; };
-		CFF8B434097C605F0047F72A /* UniqueVector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UniqueVector.h; sourceTree = ""; };
-		DE4DA0390911476D0012D44B /* LoopSimplify.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = LoopSimplify.cpp; path = ../lib/Transforms/Utils/LoopSimplify.cpp; sourceTree = SOURCE_ROOT; };
-		DE4DA03C091147920012D44B /* LiveInterval.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = LiveInterval.h; path = ../include/llvm/CodeGen/LiveInterval.h; sourceTree = SOURCE_ROOT; };
-		DE4DA03D091147920012D44B /* LiveIntervalAnalysis.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = LiveIntervalAnalysis.h; path = ../include/llvm/CodeGen/LiveIntervalAnalysis.h; sourceTree = SOURCE_ROOT; };
-		DE4DA065091148520012D44B /* SubtargetEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = SubtargetEmitter.cpp; path = ../utils/TableGen/SubtargetEmitter.cpp; sourceTree = SOURCE_ROOT; };
-		DE4DA066091148520012D44B /* SubtargetEmitter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = SubtargetEmitter.h; path = ../utils/TableGen/SubtargetEmitter.h; sourceTree = SOURCE_ROOT; };
-		DE66EC5B08ABE86900323D32 /* AsmWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = AsmWriter.cpp; path = ../lib/VMCore/AsmWriter.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC5C08ABE86A00323D32 /* BasicBlock.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = BasicBlock.cpp; path = ../lib/VMCore/BasicBlock.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6008ABE86A00323D32 /* Constants.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Constants.cpp; path = ../lib/VMCore/Constants.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6108ABE86A00323D32 /* Dominators.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Dominators.cpp; path = ../lib/VMCore/Dominators.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6208ABE86A00323D32 /* Function.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Function.cpp; path = ../lib/VMCore/Function.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6308ABE86A00323D32 /* Globals.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Globals.cpp; path = ../lib/VMCore/Globals.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6408ABE86A00323D32 /* Instruction.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Instruction.cpp; path = ../lib/VMCore/Instruction.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6508ABE86A00323D32 /* Instructions.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Instructions.cpp; path = ../lib/VMCore/Instructions.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6608ABE86A00323D32 /* LeakDetector.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = LeakDetector.cpp; path = ../lib/VMCore/LeakDetector.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6708ABE86A00323D32 /* Mangler.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Mangler.cpp; path = ../lib/VMCore/Mangler.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6808ABE86A00323D32 /* Module.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Module.cpp; path = ../lib/VMCore/Module.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6908ABE86A00323D32 /* ModuleProvider.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ModuleProvider.cpp; path = ../lib/VMCore/ModuleProvider.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6A08ABE86A00323D32 /* Pass.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Pass.cpp; path = ../lib/VMCore/Pass.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6D08ABE86A00323D32 /* SymbolTableListTraitsImpl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = SymbolTableListTraitsImpl.h; path = ../lib/VMCore/SymbolTableListTraitsImpl.h; sourceTree = SOURCE_ROOT; };
-		DE66EC6E08ABE86A00323D32 /* Type.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Type.cpp; path = ../lib/VMCore/Type.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC6F08ABE86A00323D32 /* Value.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Value.cpp; path = ../lib/VMCore/Value.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC7008ABE86A00323D32 /* Verifier.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Verifier.cpp; path = ../lib/VMCore/Verifier.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC8E08ABEAF000323D32 /* llvmAsmParser.y */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.yacc; name = llvmAsmParser.y; path = ../lib/AsmParser/llvmAsmParser.y; sourceTree = SOURCE_ROOT; };
-		DE66EC8F08ABEAF000323D32 /* Parser.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Parser.cpp; path = ../lib/AsmParser/Parser.cpp; sourceTree = SOURCE_ROOT; };
-		DE66EC9008ABEAF000323D32 /* ParserInternals.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ParserInternals.h; path = ../lib/AsmParser/ParserInternals.h; sourceTree = SOURCE_ROOT; };
-		DE66ECBE08ABEC0700323D32 /* AliasAnalysis.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AliasAnalysis.cpp; sourceTree = ""; };
-		DE66ECBF08ABEC0700323D32 /* AliasAnalysisCounter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AliasAnalysisCounter.cpp; sourceTree = ""; };
-		DE66ECC008ABEC0700323D32 /* AliasAnalysisEvaluator.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AliasAnalysisEvaluator.cpp; sourceTree = ""; };
-		DE66ECC108ABEC0700323D32 /* AliasSetTracker.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AliasSetTracker.cpp; sourceTree = ""; };
-		DE66ECC208ABEC0700323D32 /* BasicAliasAnalysis.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BasicAliasAnalysis.cpp; sourceTree = ""; };
-		DE66ECC308ABEC0700323D32 /* CFGPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CFGPrinter.cpp; sourceTree = ""; };
-		DE66ED1708ABEC0800323D32 /* InstCount.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = InstCount.cpp; sourceTree = ""; };
-		DE66ED1808ABEC0800323D32 /* Interval.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Interval.cpp; sourceTree = ""; };
-		DE66ED1908ABEC0800323D32 /* IntervalPartition.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IntervalPartition.cpp; sourceTree = ""; };
-		DE66ED1B08ABEC0800323D32 /* Andersens.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Andersens.cpp; sourceTree = ""; };
-		DE66ED1C08ABEC0800323D32 /* CallGraph.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CallGraph.cpp; sourceTree = ""; };
-		DE66ED1D08ABEC0800323D32 /* CallGraphSCCPass.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CallGraphSCCPass.cpp; sourceTree = ""; };
-		DE66ED2F08ABEC0800323D32 /* FindUsedTypes.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FindUsedTypes.cpp; sourceTree = ""; };
-		DE66ED3008ABEC0800323D32 /* GlobalsModRef.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = GlobalsModRef.cpp; sourceTree = ""; };
-		DE66ED3308ABEC0800323D32 /* LoadValueNumbering.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoadValueNumbering.cpp; sourceTree = ""; };
-		DE66ED3408ABEC0800323D32 /* LoopInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoopInfo.cpp; sourceTree = ""; };
-		DE66ED3608ABEC0800323D32 /* PostDominators.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PostDominators.cpp; sourceTree = ""; };
-		DE66ED3708ABEC0800323D32 /* ProfileInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProfileInfo.cpp; sourceTree = ""; };
-		DE66ED3808ABEC0800323D32 /* ProfileInfoLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProfileInfoLoader.cpp; sourceTree = ""; };
-		DE66ED3908ABEC0800323D32 /* ProfileInfoLoaderPass.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProfileInfoLoaderPass.cpp; sourceTree = ""; };
-		DE66ED3A08ABEC0800323D32 /* ScalarEvolution.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ScalarEvolution.cpp; sourceTree = ""; };
-		DE66ED3B08ABEC0800323D32 /* ScalarEvolutionExpander.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ScalarEvolutionExpander.cpp; sourceTree = ""; };
-		DE66ED3C08ABEC0800323D32 /* Trace.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Trace.cpp; sourceTree = ""; };
-		DE66ED3D08ABEC0800323D32 /* ValueNumbering.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ValueNumbering.cpp; sourceTree = ""; };
-		DE66ED3F08ABEC2A00323D32 /* AsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AsmPrinter.cpp; sourceTree = ""; };
-		DE66ED4008ABEC2A00323D32 /* BranchFolding.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BranchFolding.cpp; sourceTree = ""; };
-		DE66ED6F08ABEC2B00323D32 /* ELFWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ELFWriter.cpp; sourceTree = ""; };
-		DE66ED7008ABEC2B00323D32 /* IntrinsicLowering.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IntrinsicLowering.cpp; sourceTree = ""; };
-		DE66ED7108ABEC2B00323D32 /* LiveInterval.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LiveInterval.cpp; sourceTree = ""; };
-		DE66ED7308ABEC2B00323D32 /* LiveIntervalAnalysis.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LiveIntervalAnalysis.cpp; sourceTree = ""; };
-		DE66ED7508ABEC2B00323D32 /* LiveVariables.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LiveVariables.cpp; sourceTree = ""; };
-		DE66ED7608ABEC2B00323D32 /* MachineBasicBlock.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MachineBasicBlock.cpp; sourceTree = ""; };
-		DE66ED7808ABEC2B00323D32 /* MachineFunction.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MachineFunction.cpp; sourceTree = ""; };
-		DE66ED7908ABEC2B00323D32 /* MachineInstr.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MachineInstr.cpp; sourceTree = ""; };
-		DE66ED7B08ABEC2B00323D32 /* Passes.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Passes.cpp; sourceTree = ""; };
-		DE66ED7C08ABEC2B00323D32 /* PHIElimination.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PHIElimination.cpp; sourceTree = ""; };
-		DE66ED7D08ABEC2B00323D32 /* PhysRegTracker.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PhysRegTracker.h; sourceTree = ""; };
-		DE66ED7E08ABEC2B00323D32 /* PrologEpilogInserter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PrologEpilogInserter.cpp; sourceTree = ""; };
-		DE66ED8008ABEC2B00323D32 /* RegAllocLinearScan.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RegAllocLinearScan.cpp; sourceTree = ""; };
-		DE66ED8108ABEC2B00323D32 /* RegAllocLocal.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RegAllocLocal.cpp; sourceTree = ""; };
-		DE66ED8208ABEC2B00323D32 /* RegAllocSimple.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RegAllocSimple.cpp; sourceTree = ""; };
-		DE66ED9008ABEC2B00323D32 /* LegalizeDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LegalizeDAG.cpp; sourceTree = ""; };
-		DE66ED9208ABEC2B00323D32 /* SelectionDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SelectionDAG.cpp; sourceTree = ""; };
-		DE66ED9308ABEC2B00323D32 /* SelectionDAGISel.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SelectionDAGISel.cpp; sourceTree = ""; };
-		DE66ED9408ABEC2B00323D32 /* SelectionDAGPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SelectionDAGPrinter.cpp; sourceTree = ""; };
-		DE66ED9508ABEC2B00323D32 /* TwoAddressInstructionPass.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TwoAddressInstructionPass.cpp; sourceTree = ""; };
-		DE66ED9608ABEC2B00323D32 /* UnreachableBlockElim.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = UnreachableBlockElim.cpp; sourceTree = ""; };
-		DE66ED9808ABEC2B00323D32 /* VirtRegMap.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = VirtRegMap.cpp; sourceTree = ""; };
-		DE66ED9908ABEC2B00323D32 /* VirtRegMap.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = VirtRegMap.h; sourceTree = ""; };
-		DE66EDB108ABEC7300323D32 /* Debugger.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Debugger.cpp; sourceTree = ""; };
-		DE66EDB508ABEC7300323D32 /* ProgramInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProgramInfo.cpp; sourceTree = ""; };
-		DE66EDB608ABEC7300323D32 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		DE66EDB708ABEC7300323D32 /* RuntimeInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RuntimeInfo.cpp; sourceTree = ""; };
-		DE66EDB808ABEC7300323D32 /* SourceFile.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SourceFile.cpp; sourceTree = ""; };
-		DE66EDB908ABEC7300323D32 /* SourceLanguage-CFamily.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = "SourceLanguage-CFamily.cpp"; sourceTree = ""; };
-		DE66EDBA08ABEC7300323D32 /* SourceLanguage-CPlusPlus.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = "SourceLanguage-CPlusPlus.cpp"; sourceTree = ""; };
-		DE66EDBB08ABEC7300323D32 /* SourceLanguage-Unknown.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = "SourceLanguage-Unknown.cpp"; sourceTree = ""; };
-		DE66EDBC08ABEC7300323D32 /* SourceLanguage.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SourceLanguage.cpp; sourceTree = ""; };
-		DE66EDC408ABEC9000323D32 /* ExecutionEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ExecutionEngine.cpp; sourceTree = ""; };
-		DE66EDCE08ABEC9000323D32 /* Execution.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Execution.cpp; sourceTree = ""; };
-		DE66EDCF08ABEC9000323D32 /* ExternalFunctions.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ExternalFunctions.cpp; sourceTree = ""; };
-		DE66EDD008ABEC9000323D32 /* Interpreter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Interpreter.cpp; sourceTree = ""; };
-		DE66EDD108ABEC9000323D32 /* Interpreter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Interpreter.h; sourceTree = ""; };
-		DE66EDDE08ABEC9100323D32 /* Intercept.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Intercept.cpp; sourceTree = ""; };
-		DE66EDDF08ABEC9100323D32 /* JIT.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = JIT.cpp; sourceTree = ""; };
-		DE66EDE008ABEC9100323D32 /* JIT.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = JIT.h; sourceTree = ""; };
-		DE66EDE108ABEC9100323D32 /* JITEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = JITEmitter.cpp; sourceTree = ""; };
-		DE66EDE308ABEC9100323D32 /* TargetSelect.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetSelect.cpp; sourceTree = ""; };
-		DE66EDF608ABEDD300323D32 /* LinkArchives.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LinkArchives.cpp; sourceTree = ""; };
-		DE66EDF708ABEDD300323D32 /* Linker.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Linker.cpp; sourceTree = ""; };
-		DE66EDF808ABEDD300323D32 /* LinkItems.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LinkItems.cpp; sourceTree = ""; };
-		DE66EDF908ABEDD300323D32 /* LinkModules.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LinkModules.cpp; sourceTree = ""; };
-		DE66EDFC08ABEDE600323D32 /* Annotation.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Annotation.cpp; sourceTree = ""; };
-		DE66EE1D08ABEDE600323D32 /* CommandLine.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CommandLine.cpp; sourceTree = ""; };
-		DE66EE3D08ABEDE600323D32 /* Debug.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Debug.cpp; sourceTree = ""; };
-		DE66EE3E08ABEDE600323D32 /* FileUtilities.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FileUtilities.cpp; sourceTree = ""; };
-		DE66EE3F08ABEDE600323D32 /* IsInf.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IsInf.cpp; sourceTree = ""; };
-		DE66EE4008ABEDE600323D32 /* IsNAN.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IsNAN.cpp; sourceTree = ""; };
-		DE66EE4208ABEDE600323D32 /* PluginLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PluginLoader.cpp; sourceTree = ""; };
-		DE66EE4308ABEDE600323D32 /* SlowOperationInformer.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SlowOperationInformer.cpp; sourceTree = ""; };
-		DE66EE4408ABEDE600323D32 /* Statistic.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Statistic.cpp; sourceTree = ""; };
-		DE66EE4508ABEDE700323D32 /* StringExtras.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StringExtras.cpp; sourceTree = ""; };
-		DE66EE4608ABEDE700323D32 /* SystemUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SystemUtils.cpp; sourceTree = ""; };
-		DE66EE4708ABEDE700323D32 /* Timer.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Timer.cpp; sourceTree = ""; };
-		DE66EE6008ABEE3400323D32 /* DynamicLibrary.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DynamicLibrary.cpp; sourceTree = ""; };
-		DE66EE6108ABEE3400323D32 /* LICENSE.TXT */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = LICENSE.TXT; sourceTree = ""; };
-		DE66EE6508ABEE3400323D32 /* MappedFile.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MappedFile.cpp; sourceTree = ""; };
-		DE66EE6608ABEE3400323D32 /* Memory.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Memory.cpp; sourceTree = ""; };
-		DE66EE6708ABEE3400323D32 /* Mutex.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Mutex.cpp; sourceTree = ""; };
-		DE66EE6808ABEE3400323D32 /* Path.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Path.cpp; sourceTree = ""; };
-		DE66EE6908ABEE3400323D32 /* Process.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Process.cpp; sourceTree = ""; };
-		DE66EE6A08ABEE3400323D32 /* Program.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Program.cpp; sourceTree = ""; };
-		DE66EE6B08ABEE3400323D32 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		DE66EE7C08ABEE3400323D32 /* Signals.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Signals.cpp; sourceTree = ""; };
-		DE66EE7D08ABEE3400323D32 /* TimeValue.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TimeValue.cpp; sourceTree = ""; };
-		DE66EE7F08ABEE3500323D32 /* MappedFile.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = MappedFile.inc; sourceTree = ""; };
-		DE66EE8008ABEE3500323D32 /* Memory.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Memory.inc; sourceTree = ""; };
-		DE66EE8108ABEE3500323D32 /* Mutex.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Mutex.inc; sourceTree = ""; };
-		DE66EE8208ABEE3500323D32 /* Path.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Path.inc; sourceTree = ""; };
-		DE66EE8308ABEE3500323D32 /* Process.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Process.inc; sourceTree = ""; };
-		DE66EE8408ABEE3500323D32 /* Program.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Program.inc; sourceTree = ""; };
-		DE66EE8508ABEE3500323D32 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README.txt; sourceTree = ""; };
-		DE66EE8608ABEE3500323D32 /* Signals.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Signals.inc; sourceTree = ""; };
-		DE66EE8908ABEE3500323D32 /* TimeValue.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = TimeValue.inc; sourceTree = ""; };
-		DE66EE8A08ABEE3500323D32 /* Unix.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Unix.h; sourceTree = ""; };
-		DE66EE8C08ABEE3500323D32 /* DynamicLibrary.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = DynamicLibrary.inc; sourceTree = ""; };
-		DE66EE8D08ABEE3500323D32 /* MappedFile.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = MappedFile.inc; sourceTree = ""; };
-		DE66EE8E08ABEE3500323D32 /* Memory.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Memory.inc; sourceTree = ""; };
-		DE66EE8F08ABEE3500323D32 /* Mutex.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Mutex.inc; sourceTree = ""; };
-		DE66EE9008ABEE3500323D32 /* Path.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Path.inc; sourceTree = ""; };
-		DE66EE9108ABEE3500323D32 /* Process.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Process.inc; sourceTree = ""; };
-		DE66EE9208ABEE3500323D32 /* Program.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Program.inc; sourceTree = ""; };
-		DE66EE9308ABEE3500323D32 /* Signals.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Signals.inc; sourceTree = ""; };
-		DE66EE9408ABEE3500323D32 /* TimeValue.inc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = TimeValue.inc; sourceTree = ""; };
-		DE66EE9508ABEE3500323D32 /* Win32.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Win32.h; sourceTree = ""; };
-		DE66EE9808ABEE5E00323D32 /* Alpha.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Alpha.h; sourceTree = ""; };
-		DE66EE9908ABEE5E00323D32 /* Alpha.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Alpha.td; sourceTree = ""; };
-		DE66EE9A08ABEE5E00323D32 /* AlphaAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaAsmPrinter.cpp; sourceTree = ""; };
-		DE66EE9B08ABEE5E00323D32 /* AlphaCodeEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaCodeEmitter.cpp; sourceTree = ""; };
-		DE66EEA308ABEE5E00323D32 /* AlphaInstrFormats.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = AlphaInstrFormats.td; sourceTree = ""; };
-		DE66EEA408ABEE5E00323D32 /* AlphaInstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaInstrInfo.cpp; sourceTree = ""; };
-		DE66EEA508ABEE5E00323D32 /* AlphaInstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AlphaInstrInfo.h; sourceTree = ""; };
-		DE66EEA608ABEE5E00323D32 /* AlphaInstrInfo.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = AlphaInstrInfo.td; sourceTree = ""; };
-		DE66EEA908ABEE5E00323D32 /* AlphaJITInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaJITInfo.cpp; sourceTree = ""; };
-		DE66EEAA08ABEE5E00323D32 /* AlphaJITInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AlphaJITInfo.h; sourceTree = ""; };
-		DE66EEAB08ABEE5E00323D32 /* AlphaRegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaRegisterInfo.cpp; sourceTree = ""; };
-		DE66EEAC08ABEE5E00323D32 /* AlphaRegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AlphaRegisterInfo.h; sourceTree = ""; };
-		DE66EEAD08ABEE5E00323D32 /* AlphaRegisterInfo.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = AlphaRegisterInfo.td; sourceTree = ""; };
-		DE66EEAE08ABEE5E00323D32 /* AlphaRelocations.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AlphaRelocations.h; sourceTree = ""; };
-		DE66EEAF08ABEE5E00323D32 /* AlphaTargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AlphaTargetMachine.cpp; sourceTree = ""; };
-		DE66EEB008ABEE5E00323D32 /* AlphaTargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AlphaTargetMachine.h; sourceTree = ""; };
-		DE66EECA08ABEE5E00323D32 /* CTargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CTargetMachine.h; sourceTree = ""; };
-		DE66EF0E08ABEE5E00323D32 /* README */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README; sourceTree = ""; };
-		DE66EF1008ABEE5E00323D32 /* TargetRegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetRegisterInfo.cpp; sourceTree = ""; };
-		DE66F08A08ABEE6000323D32 /* Target.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Target.td; sourceTree = ""; };
-		DE66F08B08ABEE6000323D32 /* TargetData.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetData.cpp; sourceTree = ""; };
-		DE66F08C08ABEE6000323D32 /* TargetFrameInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetFrameInfo.cpp; sourceTree = ""; };
-		DE66F08D08ABEE6000323D32 /* TargetInstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetInstrInfo.cpp; sourceTree = ""; };
-		DE66F08F08ABEE6000323D32 /* TargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetMachine.cpp; sourceTree = ""; };
-		DE66F09008ABEE6000323D32 /* TargetMachineRegistry.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetMachineRegistry.cpp; sourceTree = ""; };
-		DE66F09208ABEE6000323D32 /* TargetSubtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TargetSubtarget.cpp; sourceTree = ""; };
-		DE66F0BC08ABEE6000323D32 /* X86.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86.h; sourceTree = ""; };
-		DE66F0BD08ABEE6000323D32 /* X86.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = X86.td; sourceTree = ""; };
-		DE66F0BE08ABEE6000323D32 /* X86AsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86AsmPrinter.cpp; sourceTree = ""; };
-		DE66F0BF08ABEE6000323D32 /* X86AsmPrinter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86AsmPrinter.h; sourceTree = ""; };
-		DE66F0C008ABEE6000323D32 /* X86ATTAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86ATTAsmPrinter.cpp; sourceTree = ""; };
-		DE66F0C108ABEE6000323D32 /* X86ATTAsmPrinter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86ATTAsmPrinter.h; sourceTree = ""; };
-		DE66F0C208ABEE6000323D32 /* X86CodeEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86CodeEmitter.cpp; sourceTree = ""; };
-		DE66F0C408ABEE6000323D32 /* X86FloatingPoint.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86FloatingPoint.cpp; sourceTree = ""; };
-		DE66F0CC08ABEE6000323D32 /* X86InstrBuilder.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86InstrBuilder.h; sourceTree = ""; };
-		DE66F0CD08ABEE6000323D32 /* X86InstrInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86InstrInfo.cpp; sourceTree = ""; };
-		DE66F0CE08ABEE6000323D32 /* X86InstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86InstrInfo.h; sourceTree = ""; };
-		DE66F0CF08ABEE6100323D32 /* X86InstrInfo.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = X86InstrInfo.td; sourceTree = ""; };
-		DE66F0D008ABEE6100323D32 /* X86IntelAsmPrinter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86IntelAsmPrinter.cpp; sourceTree = ""; };
-		DE66F0D108ABEE6100323D32 /* X86IntelAsmPrinter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86IntelAsmPrinter.h; sourceTree = ""; };
-		DE66F0D508ABEE6100323D32 /* X86JITInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86JITInfo.cpp; sourceTree = ""; };
-		DE66F0D608ABEE6100323D32 /* X86JITInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86JITInfo.h; sourceTree = ""; };
-		DE66F0D808ABEE6100323D32 /* X86RegisterInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86RegisterInfo.cpp; sourceTree = ""; };
-		DE66F0D908ABEE6100323D32 /* X86RegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86RegisterInfo.h; sourceTree = ""; };
-		DE66F0DA08ABEE6100323D32 /* X86RegisterInfo.td */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = X86RegisterInfo.td; sourceTree = ""; };
-		DE66F0DB08ABEE6100323D32 /* X86Relocations.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86Relocations.h; sourceTree = ""; };
-		DE66F0DC08ABEE6100323D32 /* X86Subtarget.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86Subtarget.cpp; sourceTree = ""; };
-		DE66F0DD08ABEE6100323D32 /* X86Subtarget.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86Subtarget.h; sourceTree = ""; };
-		DE66F0DE08ABEE6100323D32 /* X86TargetMachine.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = X86TargetMachine.cpp; sourceTree = ""; };
-		DE66F0DF08ABEE6100323D32 /* X86TargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = X86TargetMachine.h; sourceTree = ""; };
-		DE66F0EF08ABEFB300323D32 /* BlockProfiling.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BlockProfiling.cpp; sourceTree = ""; };
-		DE66F0FE08ABEFB300323D32 /* EdgeProfiling.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EdgeProfiling.cpp; sourceTree = ""; };
-		DE66F11B08ABEFB300323D32 /* ProfilingUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProfilingUtils.cpp; sourceTree = ""; };
-		DE66F11C08ABEFB300323D32 /* ProfilingUtils.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ProfilingUtils.h; sourceTree = ""; };
-		DE66F12008ABEFB300323D32 /* ArgumentPromotion.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ArgumentPromotion.cpp; sourceTree = ""; };
-		DE66F12108ABEFB300323D32 /* ConstantMerge.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ConstantMerge.cpp; sourceTree = ""; };
-		DE66F12208ABEFB300323D32 /* DeadArgumentElimination.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DeadArgumentElimination.cpp; sourceTree = ""; };
-		DE66F12308ABEFB300323D32 /* DeadTypeElimination.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DeadTypeElimination.cpp; sourceTree = ""; };
-		DE66F14C08ABEFB400323D32 /* GlobalDCE.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = GlobalDCE.cpp; sourceTree = ""; };
-		DE66F14D08ABEFB400323D32 /* GlobalOpt.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = GlobalOpt.cpp; sourceTree = ""; };
-		DE66F14E08ABEFB400323D32 /* Inliner.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Inliner.cpp; sourceTree = ""; };
-		DE66F15008ABEFB400323D32 /* InlineSimple.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = InlineSimple.cpp; sourceTree = ""; };
-		DE66F15108ABEFB400323D32 /* Internalize.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Internalize.cpp; sourceTree = ""; };
-		DE66F15208ABEFB400323D32 /* IPConstantPropagation.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IPConstantPropagation.cpp; sourceTree = ""; };
-		DE66F15308ABEFB400323D32 /* LoopExtractor.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoopExtractor.cpp; sourceTree = ""; };
-		DE66F15408ABEFB400323D32 /* LowerSetJmp.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LowerSetJmp.cpp; sourceTree = ""; };
-		DE66F15608ABEFB400323D32 /* PruneEH.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PruneEH.cpp; sourceTree = ""; };
-		DE66F15708ABEFB400323D32 /* RaiseAllocations.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RaiseAllocations.cpp; sourceTree = ""; };
-		DE66F15808ABEFB400323D32 /* SimplifyLibCalls.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SimplifyLibCalls.cpp; sourceTree = ""; };
-		DE66F15908ABEFB400323D32 /* StripSymbols.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StripSymbols.cpp; sourceTree = ""; };
-		DE66F15E08ABEFB400323D32 /* ADCE.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ADCE.cpp; sourceTree = ""; };
-		DE66F15F08ABEFB400323D32 /* BasicBlockPlacement.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BasicBlockPlacement.cpp; sourceTree = ""; };
-		DE66F16008ABEFB400323D32 /* CondPropagate.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CondPropagate.cpp; sourceTree = ""; };
-		DE66F16108ABEFB400323D32 /* ConstantProp.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ConstantProp.cpp; sourceTree = ""; };
-		DE66F16308ABEFB400323D32 /* DCE.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DCE.cpp; sourceTree = ""; };
-		DE66F16408ABEFB400323D32 /* DeadStoreElimination.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DeadStoreElimination.cpp; sourceTree = ""; };
-		DE66F1A308ABEFB400323D32 /* GCSE.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = GCSE.cpp; sourceTree = ""; };
-		DE66F1A408ABEFB400323D32 /* IndVarSimplify.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IndVarSimplify.cpp; sourceTree = ""; };
-		DE66F1A508ABEFB400323D32 /* InstructionCombining.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = InstructionCombining.cpp; sourceTree = ""; };
-		DE66F1A608ABEFB400323D32 /* LICM.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LICM.cpp; sourceTree = ""; };
-		DE66F1A808ABEFB400323D32 /* LoopStrengthReduce.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoopStrengthReduce.cpp; sourceTree = ""; };
-		DE66F1A908ABEFB400323D32 /* LoopUnroll.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoopUnroll.cpp; sourceTree = ""; };
-		DE66F1AA08ABEFB400323D32 /* LoopUnswitch.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoopUnswitch.cpp; sourceTree = ""; };
-		DE66F1B508ABEFB400323D32 /* Reassociate.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Reassociate.cpp; sourceTree = ""; };
-		DE66F1B608ABEFB400323D32 /* ScalarReplAggregates.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ScalarReplAggregates.cpp; sourceTree = ""; };
-		DE66F1B708ABEFB400323D32 /* SCCP.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SCCP.cpp; sourceTree = ""; };
-		DE66F1B808ABEFB400323D32 /* SimplifyCFG.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SimplifyCFG.cpp; sourceTree = ""; };
-		DE66F1B908ABEFB400323D32 /* TailDuplication.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TailDuplication.cpp; sourceTree = ""; };
-		DE66F1BA08ABEFB400323D32 /* TailRecursionElimination.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TailRecursionElimination.cpp; sourceTree = ""; };
-		DE66F1BE08ABEFB400323D32 /* BasicBlockUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BasicBlockUtils.cpp; sourceTree = ""; };
-		DE66F1BF08ABEFB400323D32 /* BreakCriticalEdges.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BreakCriticalEdges.cpp; sourceTree = ""; };
-		DE66F1C008ABEFB400323D32 /* CloneFunction.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CloneFunction.cpp; sourceTree = ""; };
-		DE66F1C108ABEFB400323D32 /* CloneModule.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CloneModule.cpp; sourceTree = ""; };
-		DE66F1C208ABEFB400323D32 /* CloneTrace.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CloneTrace.cpp; sourceTree = ""; };
-		DE66F1C308ABEFB400323D32 /* CodeExtractor.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CodeExtractor.cpp; sourceTree = ""; };
-		DE66F1E008ABEFB400323D32 /* DemoteRegToStack.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DemoteRegToStack.cpp; sourceTree = ""; };
-		DE66F1E108ABEFB400323D32 /* InlineFunction.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = InlineFunction.cpp; sourceTree = ""; };
-		DE66F1E208ABEFB400323D32 /* Local.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Local.cpp; sourceTree = ""; };
-		DE66F1E408ABEFB400323D32 /* PromoteMemoryToRegister.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PromoteMemoryToRegister.cpp; sourceTree = ""; };
-		DE66F1E508ABEFB400323D32 /* SimplifyCFG.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SimplifyCFG.cpp; sourceTree = ""; };
-		DE66F1E608ABEFB400323D32 /* UnifyFunctionExitNodes.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = UnifyFunctionExitNodes.cpp; sourceTree = ""; };
-		DE66F1E708ABEFB400323D32 /* ValueMapper.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ValueMapper.cpp; sourceTree = ""; };
-		DE66F1EA08ABF03100323D32 /* AbstractTypeUser.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AbstractTypeUser.h; sourceTree = ""; };
-		DE66F1EE08ABF03100323D32 /* DenseMap.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DenseMap.h; sourceTree = ""; };
-		DE66F1EF08ABF03100323D32 /* DepthFirstIterator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DepthFirstIterator.h; sourceTree = ""; };
-		DE66F1F008ABF03100323D32 /* EquivalenceClasses.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = EquivalenceClasses.h; sourceTree = ""; };
-		DE66F1F108ABF03100323D32 /* GraphTraits.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GraphTraits.h; sourceTree = ""; };
-		DE66F1F308ABF03100323D32 /* hash_map.in */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = hash_map.in; sourceTree = ""; };
-		DE66F1F508ABF03100323D32 /* hash_set.in */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = hash_set.in; sourceTree = ""; };
-		DE66F1F608ABF03100323D32 /* HashExtras.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = HashExtras.h; sourceTree = ""; };
-		DE66F1F708ABF03100323D32 /* ilist */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = ilist; sourceTree = ""; };
-		DE66F1F908ABF03100323D32 /* iterator.in */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = iterator.in; sourceTree = ""; };
-		DE66F1FA08ABF03100323D32 /* PostOrderIterator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PostOrderIterator.h; sourceTree = ""; };
-		DE66F1FB08ABF03100323D32 /* SCCIterator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SCCIterator.h; sourceTree = ""; };
-		DE66F1FC08ABF03100323D32 /* SetOperations.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SetOperations.h; sourceTree = ""; };
-		DE66F1FD08ABF03100323D32 /* SetVector.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SetVector.h; sourceTree = ""; };
-		DE66F1FE08ABF03100323D32 /* Statistic.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Statistic.h; sourceTree = ""; };
-		DE66F1FF08ABF03100323D32 /* STLExtras.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = STLExtras.h; sourceTree = ""; };
-		DE66F20008ABF03100323D32 /* StringExtras.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = StringExtras.h; sourceTree = ""; };
-		DE66F20108ABF03100323D32 /* Tree.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Tree.h; sourceTree = ""; };
-		DE66F20208ABF03100323D32 /* VectorExtras.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = VectorExtras.h; sourceTree = ""; };
-		DE66F20408ABF03100323D32 /* AliasAnalysis.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AliasAnalysis.h; sourceTree = ""; };
-		DE66F20508ABF03100323D32 /* AliasSetTracker.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AliasSetTracker.h; sourceTree = ""; };
-		DE66F20608ABF03100323D32 /* CallGraph.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CallGraph.h; sourceTree = ""; };
-		DE66F20708ABF03100323D32 /* CFGPrinter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CFGPrinter.h; sourceTree = ""; };
-		DE66F20808ABF03100323D32 /* ConstantsScanner.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ConstantsScanner.h; sourceTree = ""; };
-		DE66F20F08ABF03100323D32 /* Dominators.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Dominators.h; sourceTree = ""; };
-		DE66F21208ABF03100323D32 /* FindUsedTypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FindUsedTypes.h; sourceTree = ""; };
-		DE66F21308ABF03100323D32 /* Interval.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Interval.h; sourceTree = ""; };
-		DE66F21408ABF03100323D32 /* IntervalIterator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IntervalIterator.h; sourceTree = ""; };
-		DE66F21508ABF03100323D32 /* IntervalPartition.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IntervalPartition.h; sourceTree = ""; };
-		DE66F21608ABF03100323D32 /* LoadValueNumbering.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = LoadValueNumbering.h; sourceTree = ""; };
-		DE66F21708ABF03100323D32 /* LoopInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = LoopInfo.h; sourceTree = ""; };
-		DE66F21808ABF03100323D32 /* Passes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Passes.h; sourceTree = ""; };
-		DE66F21908ABF03100323D32 /* PostDominators.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PostDominators.h; sourceTree = ""; };
-		DE66F21A08ABF03100323D32 /* ProfileInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ProfileInfo.h; sourceTree = ""; };
-		DE66F21B08ABF03100323D32 /* ProfileInfoLoader.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ProfileInfoLoader.h; sourceTree = ""; };
-		DE66F21C08ABF03100323D32 /* ProfileInfoTypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ProfileInfoTypes.h; sourceTree = ""; };
-		DE66F21D08ABF03100323D32 /* ScalarEvolution.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ScalarEvolution.h; sourceTree = ""; };
-		DE66F21E08ABF03100323D32 /* ScalarEvolutionExpander.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ScalarEvolutionExpander.h; sourceTree = ""; };
-		DE66F21F08ABF03100323D32 /* ScalarEvolutionExpressions.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ScalarEvolutionExpressions.h; sourceTree = ""; };
-		DE66F22008ABF03100323D32 /* Trace.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Trace.h; sourceTree = ""; };
-		DE66F22108ABF03100323D32 /* ValueNumbering.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ValueNumbering.h; sourceTree = ""; };
-		DE66F22208ABF03100323D32 /* Verifier.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Verifier.h; sourceTree = ""; };
-		DE66F22308ABF03100323D32 /* Argument.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Argument.h; sourceTree = ""; };
-		DE66F22508ABF03100323D32 /* AsmAnnotationWriter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AsmAnnotationWriter.h; sourceTree = ""; };
-		DE66F22708ABF03100323D32 /* Parser.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Parser.h; sourceTree = ""; };
-		DE66F22808ABF03100323D32 /* PrintModulePass.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PrintModulePass.h; sourceTree = ""; };
-		DE66F22908ABF03100323D32 /* Writer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Writer.h; sourceTree = ""; };
-		DE66F22A08ABF03100323D32 /* BasicBlock.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BasicBlock.h; sourceTree = ""; };
-		DE66F23308ABF03100323D32 /* CallGraphSCCPass.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CallGraphSCCPass.h; sourceTree = ""; };
-		DE66F23408ABF03100323D32 /* CallingConv.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CallingConv.h; sourceTree = ""; };
-		DE66F23608ABF03100323D32 /* AsmPrinter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AsmPrinter.h; sourceTree = ""; };
-		DE66F23908ABF03100323D32 /* IntrinsicLowering.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IntrinsicLowering.h; sourceTree = ""; };
-		DE66F23A08ABF03100323D32 /* LiveVariables.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = LiveVariables.h; sourceTree = ""; };
-		DE66F23B08ABF03100323D32 /* MachineBasicBlock.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineBasicBlock.h; sourceTree = ""; };
-		DE66F23C08ABF03100323D32 /* MachineCodeEmitter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineCodeEmitter.h; sourceTree = ""; };
-		DE66F23D08ABF03100323D32 /* MachineConstantPool.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineConstantPool.h; sourceTree = ""; };
-		DE66F23E08ABF03100323D32 /* MachineFrameInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineFrameInfo.h; sourceTree = ""; };
-		DE66F23F08ABF03100323D32 /* MachineFunction.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineFunction.h; sourceTree = ""; };
-		DE66F24008ABF03100323D32 /* MachineFunctionPass.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineFunctionPass.h; sourceTree = ""; };
-		DE66F24108ABF03100323D32 /* MachineInstr.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineInstr.h; sourceTree = ""; };
-		DE66F24208ABF03100323D32 /* MachineInstrBuilder.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineInstrBuilder.h; sourceTree = ""; };
-		DE66F24308ABF03100323D32 /* MachineRelocation.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MachineRelocation.h; sourceTree = ""; };
-		DE66F24408ABF03100323D32 /* Passes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Passes.h; sourceTree = ""; };
-		DE66F24508ABF03100323D32 /* SchedGraphCommon.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SchedGraphCommon.h; sourceTree = ""; };
-		DE66F24608ABF03100323D32 /* SelectionDAG.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SelectionDAG.h; sourceTree = ""; };
-		DE66F24708ABF03100323D32 /* SelectionDAGISel.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SelectionDAGISel.h; sourceTree = ""; };
-		DE66F24808ABF03100323D32 /* SelectionDAGNodes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SelectionDAGNodes.h; sourceTree = ""; };
-		DE66F24B08ABF03100323D32 /* ValueTypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ValueTypes.h; sourceTree = ""; };
-		DE66F24E08ABF03100323D32 /* alloca.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = alloca.h; sourceTree = ""; };
-		DE66F25008ABF03100323D32 /* config.h.in */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = config.h.in; sourceTree = ""; };
-		DE66F25108ABF03100323D32 /* Constant.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Constant.h; sourceTree = ""; };
-		DE66F25208ABF03100323D32 /* Constants.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Constants.h; sourceTree = ""; };
-		DE66F25408ABF03100323D32 /* Debugger.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Debugger.h; sourceTree = ""; };
-		DE66F25508ABF03100323D32 /* InferiorProcess.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InferiorProcess.h; sourceTree = ""; };
-		DE66F25608ABF03100323D32 /* ProgramInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ProgramInfo.h; sourceTree = ""; };
-		DE66F25708ABF03100323D32 /* RuntimeInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = RuntimeInfo.h; sourceTree = ""; };
-		DE66F25808ABF03100323D32 /* SourceFile.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SourceFile.h; sourceTree = ""; };
-		DE66F25908ABF03100323D32 /* SourceLanguage.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SourceLanguage.h; sourceTree = ""; };
-		DE66F25A08ABF03100323D32 /* DerivedTypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DerivedTypes.h; sourceTree = ""; };
-		DE66F25C08ABF03100323D32 /* ExecutionEngine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ExecutionEngine.h; sourceTree = ""; };
-		DE66F25D08ABF03100323D32 /* GenericValue.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GenericValue.h; sourceTree = ""; };
-		DE66F25E08ABF03100323D32 /* Function.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Function.h; sourceTree = ""; };
-		DE66F25F08ABF03100323D32 /* GlobalValue.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GlobalValue.h; sourceTree = ""; };
-		DE66F26008ABF03100323D32 /* GlobalVariable.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GlobalVariable.h; sourceTree = ""; };
-		DE66F26108ABF03100323D32 /* InstrTypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InstrTypes.h; sourceTree = ""; };
-		DE66F26208ABF03100323D32 /* Instruction.def */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = Instruction.def; sourceTree = ""; };
-		DE66F26308ABF03100323D32 /* Instruction.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Instruction.h; sourceTree = ""; };
-		DE66F26408ABF03100323D32 /* Instructions.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Instructions.h; sourceTree = ""; };
-		DE66F26508ABF03100323D32 /* IntrinsicInst.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IntrinsicInst.h; sourceTree = ""; };
-		DE66F26608ABF03100323D32 /* Intrinsics.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Intrinsics.h; sourceTree = ""; };
-		DE66F26708ABF03100323D32 /* Linker.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Linker.h; sourceTree = ""; };
-		DE66F26808ABF03100323D32 /* Module.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Module.h; sourceTree = ""; };
-		DE66F26908ABF03200323D32 /* ModuleProvider.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ModuleProvider.h; sourceTree = ""; };
-		DE66F26A08ABF03200323D32 /* Pass.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Pass.h; sourceTree = ""; };
-		DE66F26B08ABF03200323D32 /* PassAnalysisSupport.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PassAnalysisSupport.h; sourceTree = ""; };
-		DE66F26C08ABF03200323D32 /* PassManager.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PassManager.h; sourceTree = ""; };
-		DE66F26D08ABF03200323D32 /* PassSupport.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PassSupport.h; sourceTree = ""; };
-		DE66F27008ABF03200323D32 /* AIXDataTypesFix.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AIXDataTypesFix.h; sourceTree = ""; };
-		DE66F27108ABF03200323D32 /* Annotation.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Annotation.h; sourceTree = ""; };
-		DE66F27208ABF03200323D32 /* CallSite.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CallSite.h; sourceTree = ""; };
-		DE66F27308ABF03200323D32 /* Casting.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Casting.h; sourceTree = ""; };
-		DE66F27408ABF03200323D32 /* CFG.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CFG.h; sourceTree = ""; };
-		DE66F27508ABF03200323D32 /* CommandLine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CommandLine.h; sourceTree = ""; };
-		DE66F27708ABF03200323D32 /* ConstantRange.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ConstantRange.h; sourceTree = ""; };
-		DE66F27908ABF03200323D32 /* DataTypes.h.in */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = DataTypes.h.in; sourceTree = ""; };
-		DE66F27A08ABF03200323D32 /* Debug.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Debug.h; sourceTree = ""; };
-		DE66F27B08ABF03200323D32 /* DOTGraphTraits.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DOTGraphTraits.h; sourceTree = ""; };
-		DE66F27C08ABF03200323D32 /* DynamicLinker.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DynamicLinker.h; sourceTree = ""; };
-		DE66F27D08ABF03200323D32 /* ELF.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ELF.h; sourceTree = ""; };
-		DE66F27E08ABF03200323D32 /* FileUtilities.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FileUtilities.h; sourceTree = ""; };
-		DE66F27F08ABF03200323D32 /* GetElementPtrTypeIterator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GetElementPtrTypeIterator.h; sourceTree = ""; };
-		DE66F28008ABF03200323D32 /* GraphWriter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = GraphWriter.h; sourceTree = ""; };
-		DE66F28108ABF03200323D32 /* InstIterator.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InstIterator.h; sourceTree = ""; };
-		DE66F28208ABF03200323D32 /* InstVisitor.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InstVisitor.h; sourceTree = ""; };
-		DE66F28308ABF03200323D32 /* LeakDetector.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = LeakDetector.h; sourceTree = ""; };
-		DE66F28408ABF03200323D32 /* Mangler.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Mangler.h; sourceTree = ""; };
-		DE66F28508ABF03200323D32 /* MathExtras.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MathExtras.h; sourceTree = ""; };
-		DE66F28608ABF03200323D32 /* MutexGuard.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MutexGuard.h; sourceTree = ""; };
-		DE66F28708ABF03200323D32 /* PassNameParser.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PassNameParser.h; sourceTree = ""; };
-		DE66F28808ABF03200323D32 /* PatternMatch.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PatternMatch.h; sourceTree = ""; };
-		DE66F28908ABF03200323D32 /* PluginLoader.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PluginLoader.h; sourceTree = ""; };
-		DE66F28A08ABF03200323D32 /* SlowOperationInformer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SlowOperationInformer.h; sourceTree = ""; };
-		DE66F28B08ABF03200323D32 /* StableBasicBlockNumbering.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = StableBasicBlockNumbering.h; sourceTree = ""; };
-		DE66F28C08ABF03200323D32 /* SystemUtils.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SystemUtils.h; sourceTree = ""; };
-		DE66F28E08ABF03200323D32 /* Timer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Timer.h; sourceTree = ""; };
-		DE66F29008ABF03200323D32 /* type_traits.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = type_traits.h; sourceTree = ""; };
-		DE66F29308ABF03200323D32 /* SymbolTableListTraits.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SymbolTableListTraits.h; sourceTree = ""; };
-		DE66F29508ABF03200323D32 /* DynamicLibrary.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DynamicLibrary.h; sourceTree = ""; };
-		DE66F29608ABF03200323D32 /* LICENSE.TXT */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = LICENSE.TXT; sourceTree = ""; };
-		DE66F29708ABF03200323D32 /* MappedFile.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MappedFile.h; sourceTree = ""; };
-		DE66F29808ABF03200323D32 /* Memory.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Memory.h; sourceTree = ""; };
-		DE66F29908ABF03200323D32 /* Mutex.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Mutex.h; sourceTree = ""; };
-		DE66F29A08ABF03200323D32 /* Path.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Path.h; sourceTree = ""; };
-		DE66F29B08ABF03200323D32 /* Process.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Process.h; sourceTree = ""; };
-		DE66F29C08ABF03200323D32 /* Program.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Program.h; sourceTree = ""; };
-		DE66F29D08ABF03200323D32 /* Signals.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Signals.h; sourceTree = ""; };
-		DE66F29E08ABF03200323D32 /* TimeValue.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TimeValue.h; sourceTree = ""; };
-		DE66F2A008ABF03200323D32 /* TargetRegisterInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetRegisterInfo.h; sourceTree = ""; };
-		DE66F2A108ABF03200323D32 /* TargetData.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetData.h; sourceTree = ""; };
-		DE66F2A208ABF03200323D32 /* TargetFrameInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetFrameInfo.h; sourceTree = ""; };
-		DE66F2A308ABF03200323D32 /* TargetInstrInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetInstrInfo.h; sourceTree = ""; };
-		DE66F2A408ABF03200323D32 /* TargetJITInfo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetJITInfo.h; sourceTree = ""; };
-		DE66F2A508ABF03200323D32 /* TargetLowering.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetLowering.h; sourceTree = ""; };
-		DE66F2A608ABF03200323D32 /* TargetMachine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetMachine.h; sourceTree = ""; };
-		DE66F2A708ABF03200323D32 /* TargetMachineRegistry.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetMachineRegistry.h; sourceTree = ""; };
-		DE66F2A808ABF03200323D32 /* TargetOptions.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetOptions.h; sourceTree = ""; };
-		DE66F2AA08ABF03200323D32 /* TargetSubtarget.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TargetSubtarget.h; sourceTree = ""; };
-		DE66F2AC08ABF03200323D32 /* Instrumentation.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Instrumentation.h; sourceTree = ""; };
-		DE66F2AD08ABF03200323D32 /* IPO.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IPO.h; sourceTree = ""; };
-		DE66F2AF08ABF03200323D32 /* Scalar.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Scalar.h; sourceTree = ""; };
-		DE66F2B108ABF03200323D32 /* BasicBlockUtils.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BasicBlockUtils.h; sourceTree = ""; };
-		DE66F2B208ABF03200323D32 /* Cloning.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Cloning.h; sourceTree = ""; };
-		DE66F2B308ABF03200323D32 /* FunctionUtils.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FunctionUtils.h; sourceTree = ""; };
-		DE66F2B408ABF03200323D32 /* Local.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Local.h; sourceTree = ""; };
-		DE66F2B508ABF03200323D32 /* PromoteMemToReg.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PromoteMemToReg.h; sourceTree = ""; };
-		DE66F2B608ABF03200323D32 /* UnifyFunctionExitNodes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = UnifyFunctionExitNodes.h; sourceTree = ""; };
-		DE66F2B708ABF03200323D32 /* Type.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Type.h; sourceTree = ""; };
-		DE66F2B808ABF03200323D32 /* Use.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Use.h; sourceTree = ""; };
-		DE66F2B908ABF03200323D32 /* User.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = User.h; sourceTree = ""; };
-		DE66F2BA08ABF03200323D32 /* Value.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Value.h; sourceTree = ""; };
-		DE66F2CC08ABF14400323D32 /* BugDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BugDriver.cpp; sourceTree = ""; };
-		DE66F2CD08ABF14400323D32 /* BugDriver.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = BugDriver.h; sourceTree = ""; };
-		DE66F2CE08ABF14400323D32 /* bugpoint.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = bugpoint.cpp; sourceTree = ""; };
-		DE66F2CF08ABF14400323D32 /* CrashDebugger.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CrashDebugger.cpp; sourceTree = ""; };
-		DE66F2E208ABF14400323D32 /* ExecutionDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ExecutionDriver.cpp; sourceTree = ""; };
-		DE66F2E308ABF14400323D32 /* ExtractFunction.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractFunction.cpp; sourceTree = ""; };
-		DE66F2E408ABF14400323D32 /* ListReducer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ListReducer.h; sourceTree = ""; };
-		DE66F2E608ABF14400323D32 /* Miscompilation.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Miscompilation.cpp; sourceTree = ""; };
-		DE66F2E708ABF14400323D32 /* OptimizerDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OptimizerDriver.cpp; sourceTree = ""; };
-		DE66F2E808ABF14400323D32 /* TestPasses.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TestPasses.cpp; sourceTree = ""; };
-		DE66F30008ABF14400323D32 /* llc.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = llc.cpp; path = llc/llc.cpp; sourceTree = ""; };
-		DE66F30708ABF14400323D32 /* lli.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = lli.cpp; path = lli/lli.cpp; sourceTree = ""; };
-		DE66F30E08ABF14400323D32 /* llvm-ar.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-ar.cpp"; path = "llvm-ar/llvm-ar.cpp"; sourceTree = ""; };
-		DE66F31508ABF14400323D32 /* llvm-as.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-as.cpp"; path = "llvm-as/llvm-as.cpp"; sourceTree = ""; };
-		DE66F31C08ABF14400323D32 /* llvm-bcanalyzer.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-bcanalyzer.cpp"; path = "llvm-bcanalyzer/llvm-bcanalyzer.cpp"; sourceTree = ""; };
-		DE66F31F08ABF14400323D32 /* CLICommand.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CLICommand.h; sourceTree = ""; };
-		DE66F32008ABF14400323D32 /* CLIDebugger.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CLIDebugger.cpp; sourceTree = ""; };
-		DE66F32108ABF14400323D32 /* CLIDebugger.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CLIDebugger.h; sourceTree = ""; };
-		DE66F32208ABF14400323D32 /* Commands.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Commands.cpp; sourceTree = ""; };
-		DE66F32B08ABF14400323D32 /* llvm-db.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = "llvm-db.cpp"; sourceTree = ""; };
-		DE66F33208ABF14400323D32 /* llvm-dis.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-dis.cpp"; path = "llvm-dis/llvm-dis.cpp"; sourceTree = ""; };
-		DE66F33908ABF14400323D32 /* llvm-extract.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-extract.cpp"; path = "llvm-extract/llvm-extract.cpp"; sourceTree = ""; };
-		DE66F34208ABF14400323D32 /* llvm-ld.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = "llvm-ld.cpp"; sourceTree = ""; };
-		DE66F34408ABF14400323D32 /* Optimize.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Optimize.cpp; sourceTree = ""; };
-		DE66F34A08ABF14400323D32 /* llvm-link.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-link.cpp"; path = "llvm-link/llvm-link.cpp"; sourceTree = ""; };
-		DE66F35108ABF14400323D32 /* llvm-nm.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-nm.cpp"; path = "llvm-nm/llvm-nm.cpp"; sourceTree = ""; };
-		DE66F35808ABF14500323D32 /* llvm-prof.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-prof.cpp"; path = "llvm-prof/llvm-prof.cpp"; sourceTree = ""; };
-		DE66F35F08ABF14500323D32 /* llvm-ranlib.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = "llvm-ranlib.cpp"; path = "llvm-ranlib/llvm-ranlib.cpp"; sourceTree = ""; };
-		DE66F36908ABF14500323D32 /* c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = c; sourceTree = ""; };
-		DE66F36A08ABF14500323D32 /* CompilerDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CompilerDriver.cpp; sourceTree = ""; };
-		DE66F36B08ABF14500323D32 /* CompilerDriver.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CompilerDriver.h; sourceTree = ""; };
-		DE66F36D08ABF14500323D32 /* ConfigLexer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = ConfigLexer.h; sourceTree = ""; };
-		DE66F36E08ABF14500323D32 /* ConfigLexer.l */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.lex; path = ConfigLexer.l; sourceTree = ""; };
-		DE66F36F08ABF14500323D32 /* Configuration.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Configuration.cpp; sourceTree = ""; };
-		DE66F37008ABF14500323D32 /* Configuration.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Configuration.h; sourceTree = ""; };
-		DE66F37108ABF14500323D32 /* cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = cpp; sourceTree = ""; };
-		DE66F37D08ABF14500323D32 /* ll */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = ll; sourceTree = ""; };
-		DE66F37E08ABF14500323D32 /* llvmc.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = llvmc.cpp; sourceTree = ""; };
-		DE66F38C08ABF35300323D32 /* CREDITS.TXT */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CREDITS.TXT; path = ../CREDITS.TXT; sourceTree = SOURCE_ROOT; };
-		DE66F38F08ABF35C00323D32 /* AliasAnalysis.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = AliasAnalysis.html; sourceTree = ""; };
-		DE66F39008ABF35C00323D32 /* Bugpoint.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = Bugpoint.html; sourceTree = ""; };
-		DE66F39208ABF35C00323D32 /* GCCFEBuildInstrs.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = GCCFEBuildInstrs.html; sourceTree = ""; };
-		DE66F39308ABF35C00323D32 /* CodeGenerator.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = CodeGenerator.html; sourceTree = ""; };
-		DE66F39408ABF35C00323D32 /* CodingStandards.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = CodingStandards.html; sourceTree = ""; };
-		DE66F39808ABF35C00323D32 /* bugpoint.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = bugpoint.pod; sourceTree = ""; };
-		DE66F39E08ABF35C00323D32 /* index.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = index.html; sourceTree = ""; };
-		DE66F39F08ABF35C00323D32 /* llc.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llc.pod; sourceTree = ""; };
-		DE66F3A008ABF35C00323D32 /* lli.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = lli.pod; sourceTree = ""; };
-		DE66F3A108ABF35C00323D32 /* llvm-ar.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-ar.pod"; sourceTree = ""; };
-		DE66F3A208ABF35C00323D32 /* llvm-as.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-as.pod"; sourceTree = ""; };
-		DE66F3A308ABF35C00323D32 /* llvm-bcanalyzer.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-bcanalyzer.pod"; sourceTree = ""; };
-		DE66F3A408ABF35C00323D32 /* llvm-db.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-db.pod"; sourceTree = ""; };
-		DE66F3A508ABF35C00323D32 /* llvm-dis.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-dis.pod"; sourceTree = ""; };
-		DE66F3A608ABF35C00323D32 /* llvm-extract.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-extract.pod"; sourceTree = ""; };
-		DE66F3A708ABF35C00323D32 /* llvm-ld.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-ld.pod"; sourceTree = ""; };
-		DE66F3A808ABF35C00323D32 /* llvm-link.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-link.pod"; sourceTree = ""; };
-		DE66F3A908ABF35C00323D32 /* llvm-nm.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-nm.pod"; sourceTree = ""; };
-		DE66F3AA08ABF35C00323D32 /* llvm-prof.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-prof.pod"; sourceTree = ""; };
-		DE66F3AB08ABF35C00323D32 /* llvm-ranlib.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = "llvm-ranlib.pod"; sourceTree = ""; };
-		DE66F3AC08ABF35C00323D32 /* llvmc.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvmc.pod; sourceTree = ""; };
-		DE66F3AD08ABF35C00323D32 /* llvmgcc.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvmgcc.pod; sourceTree = ""; };
-		DE66F3AE08ABF35C00323D32 /* llvmgxx.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvmgxx.pod; sourceTree = ""; };
-		DE66F3AF08ABF35C00323D32 /* Makefile */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = ""; };
-		DE66F3B408ABF35D00323D32 /* manpage.css */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = manpage.css; sourceTree = ""; };
-		DE66F3B508ABF35D00323D32 /* opt.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = opt.pod; sourceTree = ""; };
-		DE66F3B808ABF35D00323D32 /* stkrc.pod */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = stkrc.pod; sourceTree = ""; };
-		DE66F3B908ABF35D00323D32 /* CommandLine.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = CommandLine.html; sourceTree = ""; };
-		DE66F3BA08ABF35D00323D32 /* CompilerDriver.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = CompilerDriver.html; sourceTree = ""; };
-		DE66F3BB08ABF35D00323D32 /* CompilerWriterInfo.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = CompilerWriterInfo.html; sourceTree = ""; };
-		DE66F3BD08ABF35D00323D32 /* doxygen.cfg.in */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = doxygen.cfg.in; sourceTree = ""; };
-		DE66F3BE08ABF35D00323D32 /* doxygen.css */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = doxygen.css; sourceTree = ""; };
-		DE66F3BF08ABF35D00323D32 /* doxygen.footer */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = doxygen.footer; sourceTree = ""; };
-		DE66F3C008ABF35D00323D32 /* doxygen.header */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = doxygen.header; sourceTree = ""; };
-		DE66F3C108ABF35D00323D32 /* doxygen.intro */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = doxygen.intro; sourceTree = ""; };
-		DE66F3C208ABF35D00323D32 /* ExtendingLLVM.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = ExtendingLLVM.html; sourceTree = ""; };
-		DE66F3C308ABF35D00323D32 /* FAQ.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = FAQ.html; sourceTree = ""; };
-		DE66F3C408ABF35D00323D32 /* GarbageCollection.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = GarbageCollection.html; sourceTree = ""; };
-		DE66F3C508ABF35D00323D32 /* GettingStarted.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = GettingStarted.html; sourceTree = ""; };
-		DE66F3C608ABF35D00323D32 /* GettingStartedVS.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = GettingStartedVS.html; sourceTree = ""; };
-		DE66F3E408ABF35D00323D32 /* HowToSubmitABug.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = HowToSubmitABug.html; sourceTree = ""; };
-		DE66F3E608ABF35D00323D32 /* Debugging.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = Debugging.gif; sourceTree = ""; };
-		DE66F3E708ABF35D00323D32 /* libdeps.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = libdeps.gif; sourceTree = ""; };
-		DE66F3E808ABF35D00323D32 /* lines.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = lines.gif; sourceTree = ""; };
-		DE66F3E908ABF35D00323D32 /* objdeps.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = objdeps.gif; sourceTree = ""; };
-		DE66F3EA08ABF35D00323D32 /* venusflytrap.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = venusflytrap.jpg; sourceTree = ""; };
-		DE66F3EB08ABF35D00323D32 /* index.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = index.html; sourceTree = ""; };
-		DE66F3EC08ABF35D00323D32 /* LangRef.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = LangRef.html; sourceTree = ""; };
-		DE66F3ED08ABF35D00323D32 /* Lexicon.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = Lexicon.html; sourceTree = ""; };
-		DE66F3EE08ABF35D00323D32 /* llvm.css */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = llvm.css; sourceTree = ""; };
-		DE66F3F108ABF35D00323D32 /* MakefileGuide.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = MakefileGuide.html; sourceTree = ""; };
-		DE66F3F208ABF35D00323D32 /* ProgrammersManual.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = ProgrammersManual.html; sourceTree = ""; };
-		DE66F3F308ABF35D00323D32 /* Projects.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = Projects.html; sourceTree = ""; };
-		DE66F3F408ABF35D00323D32 /* ReleaseNotes.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = ReleaseNotes.html; sourceTree = ""; };
-		DE66F3F508ABF35D00323D32 /* SourceLevelDebugging.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = SourceLevelDebugging.html; sourceTree = ""; };
-		DE66F3F708ABF35D00323D32 /* SystemLibrary.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = SystemLibrary.html; sourceTree = ""; };
-		DE66F3F808ABF35D00323D32 /* TableGenFundamentals.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = TableGenFundamentals.html; sourceTree = ""; };
-		DE66F3F908ABF35D00323D32 /* TestingGuide.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = TestingGuide.html; sourceTree = ""; };
-		DE66F3FA08ABF35D00323D32 /* UsingLibraries.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = UsingLibraries.html; sourceTree = ""; };
-		DE66F3FB08ABF35D00323D32 /* WritingAnLLVMBackend.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = WritingAnLLVMBackend.html; sourceTree = ""; };
-		DE66F3FC08ABF35D00323D32 /* WritingAnLLVMPass.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = WritingAnLLVMPass.html; sourceTree = ""; };
-		DE66F40E08ABF37000323D32 /* fibonacci.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = fibonacci.cpp; path = Fibonacci/fibonacci.cpp; sourceTree = ""; };
-		DE66F41508ABF37000323D32 /* HowToUseJIT.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = HowToUseJIT.cpp; path = HowToUseJIT/HowToUseJIT.cpp; sourceTree = ""; };
-		DE66F41E08ABF37000323D32 /* ModuleMaker.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ModuleMaker.cpp; path = ModuleMaker/ModuleMaker.cpp; sourceTree = ""; };
-		DE66F42608ABF37000323D32 /* ParallelJIT.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ParallelJIT.cpp; path = ParallelJIT/ParallelJIT.cpp; sourceTree = ""; };
-		DE694D9F08B51E0C0039C106 /* ScheduleDAG.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ScheduleDAG.cpp; sourceTree = ""; };
-		DE81704008CFB44D0093BDEF /* fpcmp.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = fpcmp.cpp; path = fpcmp/fpcmp.cpp; sourceTree = ""; };
-		DE81704F08CFB44D0093BDEF /* NightlyTest.gnuplot */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = NightlyTest.gnuplot; sourceTree = ""; };
-		DE81705108CFB44D0093BDEF /* NightlyTestTemplate.html */ = {isa = PBXFileReference; explicitFileType = text.html.documentation; fileEncoding = 30; path = NightlyTestTemplate.html; sourceTree = ""; };
-		DE81705908CFB44D0093BDEF /* AsmWriterEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = AsmWriterEmitter.cpp; sourceTree = ""; };
-		DE81705A08CFB44D0093BDEF /* AsmWriterEmitter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = AsmWriterEmitter.h; sourceTree = ""; };
-		DE81705B08CFB44D0093BDEF /* CodeEmitterGen.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CodeEmitterGen.cpp; sourceTree = ""; };
-		DE81705C08CFB44D0093BDEF /* CodeEmitterGen.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CodeEmitterGen.h; sourceTree = ""; };
-		DE81705D08CFB44D0093BDEF /* CodeGenInstruction.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CodeGenInstruction.h; sourceTree = ""; };
-		DE81705E08CFB44D0093BDEF /* CodeGenRegisters.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CodeGenRegisters.h; sourceTree = ""; };
-		DE81705F08CFB44D0093BDEF /* CodeGenTarget.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CodeGenTarget.cpp; sourceTree = ""; };
-		DE81706008CFB44D0093BDEF /* CodeGenTarget.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CodeGenTarget.h; sourceTree = ""; };
-		DE81706708CFB44D0093BDEF /* DAGISelEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DAGISelEmitter.cpp; sourceTree = ""; };
-		DE81706808CFB44D0093BDEF /* DAGISelEmitter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DAGISelEmitter.h; sourceTree = ""; };
-		DE81708908CFB44D0093BDEF /* InstrInfoEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = InstrInfoEmitter.cpp; sourceTree = ""; };
-		DE81708A08CFB44D0093BDEF /* InstrInfoEmitter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = InstrInfoEmitter.h; sourceTree = ""; };
-		DE81708E08CFB44D0093BDEF /* Record.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Record.cpp; sourceTree = ""; };
-		DE81708F08CFB44D0093BDEF /* Record.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Record.h; sourceTree = ""; };
-		DE81709008CFB44D0093BDEF /* RegisterInfoEmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RegisterInfoEmitter.cpp; sourceTree = ""; };
-		DE81709108CFB44D0093BDEF /* RegisterInfoEmitter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = RegisterInfoEmitter.h; sourceTree = ""; };
-		DE8170AA08CFB44D0093BDEF /* TableGen.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TableGen.cpp; sourceTree = ""; };
-		DE8170AB08CFB44D0093BDEF /* TableGenBackend.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TableGenBackend.cpp; sourceTree = ""; };
-		DE8170AC08CFB44D0093BDEF /* TableGenBackend.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TableGenBackend.h; sourceTree = ""; };
-		DEFAB19D0959E9A100E0AB42 /* DwarfWriter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = DwarfWriter.h; path = ../include/llvm/CodeGen/DwarfWriter.h; sourceTree = SOURCE_ROOT; };
-		F22627320DAE34D10008F441 /* index.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = index.html; sourceTree = ""; };
-		F22627330DAE34D20008F441 /* JITTutorial1.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = JITTutorial1.html; sourceTree = ""; };
-		F22627340DAE34D20008F441 /* JITTutorial2-1.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "JITTutorial2-1.png"; sourceTree = ""; };
-		F22627350DAE34D20008F441 /* JITTutorial2.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = JITTutorial2.html; sourceTree = ""; };
-		F22627360DAE34D20008F441 /* LangImpl1.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl1.html; sourceTree = ""; };
-		F22627370DAE34D20008F441 /* LangImpl2.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl2.html; sourceTree = ""; };
-		F22627380DAE34D20008F441 /* LangImpl3.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl3.html; sourceTree = ""; };
-		F22627390DAE34D20008F441 /* LangImpl4.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl4.html; sourceTree = ""; };
-		F226273A0DAE34D20008F441 /* LangImpl5-cfg.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "LangImpl5-cfg.png"; sourceTree = ""; };
-		F226273B0DAE34D20008F441 /* LangImpl5.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl5.html; sourceTree = ""; };
-		F226273C0DAE34D20008F441 /* LangImpl6.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl6.html; sourceTree = ""; };
-		F226273D0DAE34D20008F441 /* LangImpl7.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl7.html; sourceTree = ""; };
-		F226273E0DAE34D20008F441 /* LangImpl8.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = LangImpl8.html; sourceTree = ""; };
-		F226273F0DAE34D20008F441 /* Makefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = ""; };
-		F22627400DAE34D20008F441 /* OCamlLangImpl1.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl1.html; sourceTree = ""; };
-		F22627410DAE34D20008F441 /* OCamlLangImpl2.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl2.html; sourceTree = ""; };
-		F22627420DAE34D20008F441 /* OCamlLangImpl3.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl3.html; sourceTree = ""; };
-		F22627430DAE34D20008F441 /* OCamlLangImpl4.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl4.html; sourceTree = ""; };
-		F22627440DAE34D20008F441 /* OCamlLangImpl5.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl5.html; sourceTree = ""; };
-		F22627450DAE34D20008F441 /* OCamlLangImpl6.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl6.html; sourceTree = ""; };
-		F22627460DAE34D20008F441 /* OCamlLangImpl7.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = OCamlLangImpl7.html; sourceTree = ""; };
-		F22761DF0DAD09CD003D8065 /* BrainF.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = BrainF.cpp; path = BrainF/BrainF.cpp; sourceTree = ""; };
-		F22761E00DAD09CD003D8065 /* BrainF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = BrainF.h; path = BrainF/BrainF.h; sourceTree = ""; };
-		F22761E10DAD09CD003D8065 /* BrainFDriver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = BrainFDriver.cpp; path = BrainF/BrainFDriver.cpp; sourceTree = ""; };
-		F27C8CE90DAD2EF900A33844 /* IRBuilder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IRBuilder.h; sourceTree = ""; };
-		F27C8CFF0DAD307700A33844 /* ShadowStackCollector.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShadowStackCollector.cpp; sourceTree = ""; };
-/* End PBXFileReference section */
-
-/* Begin PBXGroup section */
-		08FB7794FE84155DC02AAC07 /* LLVM */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F1E908ABF03100323D32 /* include/llvm */,
-				CF8F1B480B64F7AB00BB4199 /* include/llvm-c */,
-				DE66ECBD08ABEC0700323D32 /* lib/Analysis */,
-				9FE450DE0C77ABE400C4FEA4 /* lib/Archive */,
-				DE66EC8808ABEAC900323D32 /* lib/AsmParser */,
-				9F68EB030C77AD2C004AA152 /* lib/Bitcode */,
-				DE66ED3E08ABEC2A00323D32 /* lib/CodeGen */,
-				DE66ED9A08ABEC7200323D32 /* lib/Debugger */,
-				DE66EDBF08ABEC8F00323D32 /* lib/ExecutionEngine */,
-				DE66EDEB08ABEDD300323D32 /* lib/Linker */,
-				DE66EDFB08ABEDE600323D32 /* lib/Support */,
-				DE66EE4908ABEE3400323D32 /* lib/System */,
-				DE66EE9608ABEE5D00323D32 /* lib/Target */,
-				DE66F0E108ABEFB300323D32 /* lib/Transforms */,
-				DE66EC7508ABE8EF00323D32 /* lib/VMCore */,
-				DE66F2BD08ABF14400323D32 /* tools */,
-				DE816FAC08CFB44C0093BDEF /* utils */,
-				DE66F38D08ABF35C00323D32 /* docs */,
-				9FD3E56D0CA0116100E54D15 /* bindings */,
-				9F7C2B690CB9496B00498408 /* test */,
-				DE66F3FD08ABF37000323D32 /* examples */,
-				DE66F38C08ABF35300323D32 /* CREDITS.TXT */,
-				CFD99AA80AFE827B0068D19C /* LICENSE.TXT */,
-				CFD99AAD0AFE827B0068D19C /* README.txt */,
-				721CA1750D0B44D200D5004F /* Products */,
-			);
-			name = LLVM;
-			sourceTree = "";
-		};
-		721CA1750D0B44D200D5004F /* Products */ = {
-			isa = PBXGroup;
-			children = (
-			);
-			name = Products;
-			sourceTree = "";
-		};
-		9F4B0E5D0D0E02580061F270 /* bitreader */ = {
-			isa = PBXGroup;
-			children = (
-				9F4B0E5E0D0E02580061F270 /* bitreader_ocaml.c */,
-				9F4B0E5F0D0E02580061F270 /* llvm_bitreader.ml */,
-				9F4B0E600D0E02580061F270 /* llvm_bitreader.mli */,
-			);
-			path = bitreader;
-			sourceTree = "";
-		};
-		9F502ACD0D1D8CA3007939DF /* executionengine */ = {
-			isa = PBXGroup;
-			children = (
-				9F502ADB0D1D8CA3007939DF /* executionengine_ocaml.c */,
-				9F502ADC0D1D8CA3007939DF /* llvm_executionengine.ml */,
-				9F502ADD0D1D8CA3007939DF /* llvm_executionengine.mli */,
-			);
-			path = executionengine;
-			sourceTree = "";
-		};
-		9F68EB030C77AD2C004AA152 /* lib/Bitcode */ = {
-			isa = PBXGroup;
-			children = (
-				9F68EB050C77AD2C004AA152 /* Reader */,
-				9F68EB110C77AD2C004AA152 /* Writer */,
-			);
-			name = lib/Bitcode;
-			path = ../lib/Bitcode;
-			sourceTree = SOURCE_ROOT;
-		};
-		9F68EB050C77AD2C004AA152 /* Reader */ = {
-			isa = PBXGroup;
-			children = (
-				35A9CDF00CD0F6D5008ABC1D /* Deserialize.cpp */,
-				9F4B0E8D0D0E05ED0061F270 /* DeserializeAPFloat.cpp */,
-				354CF6D10CD299440059AF3E /* DeserializeAPInt.cpp */,
-				9F68EB060C77AD2C004AA152 /* BitcodeReader.cpp */,
-				9F68EB070C77AD2C004AA152 /* BitcodeReader.h */,
-				9F4B0E8C0D0E05ED0061F270 /* BitReader.cpp */,
-			);
-			path = Reader;
-			sourceTree = "";
-		};
-		9F68EB110C77AD2C004AA152 /* Writer */ = {
-			isa = PBXGroup;
-			children = (
-				354CF6D20CD2994D0059AF3E /* SerializeAPInt.cpp */,
-				9FD3E5920CA012B300E54D15 /* BitWriter.cpp */,
-				9F68EB120C77AD2C004AA152 /* BitcodeWriter.cpp */,
-				9F68EB130C77AD2C004AA152 /* BitcodeWriterPass.cpp */,
-				9F68EB250C77AD2C004AA152 /* ValueEnumerator.cpp */,
-				9F68EB260C77AD2C004AA152 /* ValueEnumerator.h */,
-				35A9CDF10CD0F6E1008ABC1D /* Serialize.cpp */,
-			);
-			path = Writer;
-			sourceTree = "";
-		};
-		9F7040170D8D72FF00FD06FF /* transforms */ = {
-			isa = PBXGroup;
-			children = (
-				9F7040190D8D730A00FD06FF /* scalar */,
-			);
-			name = transforms;
-			sourceTree = "";
-		};
-		9F7040190D8D730A00FD06FF /* scalar */ = {
-			isa = PBXGroup;
-			children = (
-				9F70401A0D8D732400FD06FF /* llvm_scalar_opts.ml */,
-				9F70401B0D8D732400FD06FF /* llvm_scalar_opts.mli */,
-				9F70401E0D8D735E00FD06FF /* scalar_opts_ocaml.c */,
-			);
-			name = scalar;
-			sourceTree = "";
-		};
-		9F77937F0C73C54C00551F9C /* Bitcode */ = {
-			isa = PBXGroup;
-			children = (
-				9F7793800C73C54C00551F9C /* Archive.h */,
-				9F7793810C73C54C00551F9C /* BitCodes.h */,
-				9F7793820C73C54C00551F9C /* BitstreamReader.h */,
-				9F7793830C73C54C00551F9C /* BitstreamWriter.h */,
-				9F7793840C73C54C00551F9C /* LLVMBitCodes.h */,
-				9F7793850C73C54C00551F9C /* ReaderWriter.h */,
-				35A9CDEE0CD0F6AF008ABC1D /* Serialization.h */,
-				35A9CDEF0CD0F6AF008ABC1D /* Serialize.h */,
-				35A9CDED0CD0F6AF008ABC1D /* Deserialize.h */,
-			);
-			path = Bitcode;
-			sourceTree = "";
-		};
-		9F7794120C73CB6100551F9C /* Mips */ = {
-			isa = PBXGroup;
-			children = (
-				9F7794140C73CB6100551F9C /* Mips.h */,
-				9F7794150C73CB6100551F9C /* Mips.td */,
-				9F7794160C73CB6100551F9C /* MipsAsmPrinter.cpp */,
-				9F7794170C73CB6100551F9C /* MipsCallingConv.td */,
-				9F7794180C73CB6100551F9C /* MipsInstrFormats.td */,
-				9F7794190C73CB6100551F9C /* MipsInstrInfo.cpp */,
-				9F77941A0C73CB6100551F9C /* MipsInstrInfo.h */,
-				9F77941B0C73CB6100551F9C /* MipsInstrInfo.td */,
-				9F77941C0C73CB6100551F9C /* MipsISelDAGToDAG.cpp */,
-				9F77941D0C73CB6100551F9C /* MipsISelLowering.cpp */,
-				9F77941E0C73CB6100551F9C /* MipsISelLowering.h */,
-				9F77941F0C73CB6100551F9C /* MipsMachineFunction.h */,
-				9F7794200C73CB6100551F9C /* MipsRegisterInfo.cpp */,
-				9F7794210C73CB6100551F9C /* MipsRegisterInfo.h */,
-				9F7794220C73CB6100551F9C /* MipsRegisterInfo.td */,
-				9F7794230C73CB6100551F9C /* MipsSubtarget.cpp */,
-				9F7794240C73CB6100551F9C /* MipsSubtarget.h */,
-				9F7794250C73CB6100551F9C /* MipsTargetAsmInfo.cpp */,
-				9F7794260C73CB6100551F9C /* MipsTargetAsmInfo.h */,
-				9F7794270C73CB6100551F9C /* MipsTargetMachine.cpp */,
-				9F7794280C73CB6100551F9C /* MipsTargetMachine.h */,
-			);
-			path = Mips;
-			sourceTree = "";
-		};
-		9F7794290C73CB7900551F9C /* MSIL */ = {
-			isa = PBXGroup;
-			children = (
-				9F77942F0C73CB7900551F9C /* MSILWriter.cpp */,
-				9F7794300C73CB7900551F9C /* MSILWriter.h */,
-			);
-			path = MSIL;
-			sourceTree = "";
-		};
-		9F7C240B0CB81ECD00498408 /* analysis */ = {
-			isa = PBXGroup;
-			children = (
-				9F7C240C0CB81ECD00498408 /* analysis_ocaml.c */,
-				9F7C240D0CB81ECD00498408 /* llvm_analysis.ml */,
-				9F7C240E0CB81ECD00498408 /* llvm_analysis.mli */,
-			);
-			path = analysis;
-			sourceTree = "";
-		};
-		9F7C2B690CB9496B00498408 /* test */ = {
-			isa = PBXGroup;
-			children = (
-				9F7C2C4B0CB9496C00498408 /* Bindings */,
-			);
-			name = test;
-			path = ../test;
-			sourceTree = SOURCE_ROOT;
-		};
-		9F7C2C4B0CB9496C00498408 /* Bindings */ = {
-			isa = PBXGroup;
-			children = (
-				9F7C2C4C0CB9496C00498408 /* Ocaml */,
-			);
-			path = Bindings;
-			sourceTree = "";
-		};
-		9F7C2C4C0CB9496C00498408 /* Ocaml */ = {
-			isa = PBXGroup;
-			children = (
-				9F7C2C4F0CB9496C00498408 /* analysis.ml */,
-				9F6B2CC00D0F6E56000F00FD /* bitreader.ml */,
-				9F7C2C520CB9496C00498408 /* bitwriter.ml */,
-				9F502AEC0D1D8CF8007939DF /* executionengine.ml */,
-				9FEDD6140D8D7C3B009F6DF1 /* scalar_opts.ml */,
-				9FEDD6BD0D8D8426009F6DF1 /* target.ml */,
-				9F7C2C5D0CB9496C00498408 /* vmcore.ml */,
-			);
-			path = Ocaml;
-			sourceTree = "";
-		};
-		9FA638E90C77B252007F12AE /* IPO */ = {
-			isa = PBXGroup;
-			children = (
-				9FA638EA0C77B252007F12AE /* InlinerPass.h */,
-			);
-			path = IPO;
-			sourceTree = "";
-		};
-		9FD3E56D0CA0116100E54D15 /* bindings */ = {
-			isa = PBXGroup;
-			children = (
-				9FD3E56F0CA0116100E54D15 /* ocaml */,
-			);
-			name = bindings;
-			path = ../bindings;
-			sourceTree = SOURCE_ROOT;
-		};
-		9FD3E56F0CA0116100E54D15 /* ocaml */ = {
-			isa = PBXGroup;
-			children = (
-				9F502ACD0D1D8CA3007939DF /* executionengine */,
-				9F7C240B0CB81ECD00498408 /* analysis */,
-				9F4B0E5D0D0E02580061F270 /* bitreader */,
-				9FD3E5700CA0116100E54D15 /* bitwriter */,
-				9FD3E57A0CA0116100E54D15 /* llvm */,
-				9FEDD6C00D8D844E009F6DF1 /* target */,
-				9F7040170D8D72FF00FD06FF /* transforms */,
-			);
-			path = ocaml;
-			sourceTree = "";
-		};
-		9FD3E5700CA0116100E54D15 /* bitwriter */ = {
-			isa = PBXGroup;
-			children = (
-				9FD3E5710CA0116100E54D15 /* bitwriter_ocaml.c */,
-				9FD3E5720CA0116100E54D15 /* llvm_bitwriter.ml */,
-				9FD3E5730CA0116100E54D15 /* llvm_bitwriter.mli */,
-			);
-			path = bitwriter;
-			sourceTree = "";
-		};
-		9FD3E57A0CA0116100E54D15 /* llvm */ = {
-			isa = PBXGroup;
-			children = (
-				9FD3E57B0CA0116100E54D15 /* llvm.ml */,
-				9FD3E57C0CA0116100E54D15 /* llvm.mli */,
-				9FD3E57D0CA0116100E54D15 /* llvm_ocaml.c */,
-			);
-			path = llvm;
-			sourceTree = "";
-		};
-		9FE450DE0C77ABE400C4FEA4 /* lib/Archive */ = {
-			isa = PBXGroup;
-			children = (
-				9FE450DF0C77ABE400C4FEA4 /* Archive.cpp */,
-				9FE450E00C77ABE400C4FEA4 /* ArchiveInternals.h */,
-				9FE450E10C77ABE400C4FEA4 /* ArchiveReader.cpp */,
-				9FE450E20C77ABE400C4FEA4 /* ArchiveWriter.cpp */,
-			);
-			name = lib/Archive;
-			path = ../lib/Archive;
-			sourceTree = SOURCE_ROOT;
-		};
-		9FEDD5F00D8D73AB009F6DF1 /* Transforms */ = {
-			isa = PBXGroup;
-			children = (
-				9FEDD5F10D8D73AB009F6DF1 /* Scalar.h */,
-			);
-			path = Transforms;
-			sourceTree = "";
-		};
-		9FEDD6C00D8D844E009F6DF1 /* target */ = {
-			isa = PBXGroup;
-			children = (
-				9FEDD6C10D8D844E009F6DF1 /* llvm_target.ml */,
-				9FEDD6C20D8D844E009F6DF1 /* llvm_target.mli */,
-				9FEDD6C40D8D844E009F6DF1 /* target_ocaml.c */,
-			);
-			path = target;
-			sourceTree = "";
-		};
-		CF8F1B480B64F7AB00BB4199 /* include/llvm-c */ = {
-			isa = PBXGroup;
-			children = (
-				9F7C23E50CB81C2100498408 /* Analysis.h */,
-				9F5B90E70D0DF19100CDFDEA /* BitReader.h */,
-				9FD3E58D0CA0125F00E54D15 /* BitWriter.h */,
-				9FD3E58E0CA0125F00E54D15 /* Core.h */,
-				9FEB8C550D1CD1E200EE46BC /* ExecutionEngine.h */,
-				CF8F1B490B64F7AB00BB4199 /* LinkTimeOptimizer.h */,
-				9FEDD6BB0D8D8408009F6DF1 /* lto.h */,
-				9FEDD6B80D8D83EC009F6DF1 /* Target.h */,
-				9FEDD5F00D8D73AB009F6DF1 /* Transforms */,
-			);
-			name = "include/llvm-c";
-			path = "../include/llvm-c";
-			sourceTree = SOURCE_ROOT;
-		};
-		CF8F1B5E0B64FADA00BB4199 /* llvm-upgrade */ = {
-			isa = PBXGroup;
-			children = (
-				CF8F1B680B64FADA00BB4199 /* llvm-upgrade.cpp */,
-				CF8F1B720B64FADA00BB4199 /* UpgradeInternals.h */,
-				CF8F1B750B64FADA00BB4199 /* UpgradeLexer.l */,
-				CF8F1B7C0B64FADA00BB4199 /* UpgradeParser.y */,
-			);
-			path = "llvm-upgrade";
-			sourceTree = "";
-		};
-		CF8F1B7E0B64FADA00BB4199 /* llvm2cpp */ = {
-			isa = PBXGroup;
-			children = (
-				CF8F1B7F0B64FADA00BB4199 /* CppWriter.cpp */,
-				CF8F1B800B64FADA00BB4199 /* CppWriter.h */,
-				CF8F1B870B64FADA00BB4199 /* llvm2cpp.cpp */,
-			);
-			path = llvm2cpp;
-			sourceTree = "";
-		};
-		CF8F1B960B64FB7F00BB4199 /* lto */ = {
-			isa = PBXGroup;
-			children = (
-				CF8F1B9D0B64FB7F00BB4199 /* lto-c.cpp */,
-				CF8F1B9E0B64FB7F00BB4199 /* lto.cpp */,
-			);
-			path = lto;
-			sourceTree = "";
-		};
-		CF8F1BAB0B64FB8000BB4199 /* opt */ = {
-			isa = PBXGroup;
-			children = (
-				CF8F1BAC0B64FB8000BB4199 /* AnalysisWrappers.cpp */,
-				CF8F1BB70B64FB8000BB4199 /* GraphPrinters.cpp */,
-				CF8F1BB90B64FB8000BB4199 /* opt.cpp */,
-				CF8F1BBA0B64FB8000BB4199 /* PrintSCC.cpp */,
-			);
-			path = opt;
-			sourceTree = "";
-		};
-		CF8F1BCF0B64FC8A00BB4199 /* ARM */ = {
-			isa = PBXGroup;
-			children = (
-				9FE4508B0C77A77000C4FEA4 /* ARMCodeEmitter.cpp */,
-				9FE4508C0C77A77000C4FEA4 /* ARMGenAsmWriter.inc */,
-				9FE4508D0C77A77000C4FEA4 /* ARMGenDAGISel.inc */,
-				9FE4508E0C77A77100C4FEA4 /* ARMGenInstrInfo.inc */,
-				9FE4508F0C77A77100C4FEA4 /* ARMGenInstrNames.inc */,
-				9FE450900C77A77100C4FEA4 /* ARMGenRegisterInfo.h.inc */,
-				9FE450910C77A77100C4FEA4 /* ARMGenRegisterInfo.inc */,
-				9FE450920C77A77100C4FEA4 /* ARMGenRegisterNames.inc */,
-				9FE450930C77A77100C4FEA4 /* ARMGenSubtarget.inc */,
-				9FE450940C77A77100C4FEA4 /* ARMJITInfo.cpp */,
-				9FE450950C77A77100C4FEA4 /* ARMJITInfo.h */,
-				9FE450960C77A77100C4FEA4 /* ARMRelocations.h */,
-				9FE450970C77A77100C4FEA4 /* README-Thumb.txt */,
-				9FE450980C77A77100C4FEA4 /* README.txt */,
-				CF8F1BD10B64FC8A00BB4199 /* ARM.h */,
-				CF8F1BD20B64FC8A00BB4199 /* ARM.td */,
-				CF8F1BD30B64FC8A00BB4199 /* ARMAddressingModes.h */,
-				CF8F1BD40B64FC8A00BB4199 /* ARMAsmPrinter.cpp */,
-				CF8F1BD50B64FC8A00BB4199 /* ARMConstantIslandPass.cpp */,
-				CF8F1BD60B64FC8A00BB4199 /* ARMConstantPoolValue.cpp */,
-				CF8F1BD70B64FC8A00BB4199 /* ARMConstantPoolValue.h */,
-				CF8F1BD80B64FC8A00BB4199 /* ARMFrameInfo.h */,
-				CF8F1BD90B64FC8A00BB4199 /* ARMInstrInfo.cpp */,
-				CF8F1BDA0B64FC8A00BB4199 /* ARMInstrInfo.h */,
-				CF8F1BDB0B64FC8A00BB4199 /* ARMInstrInfo.td */,
-				CF8F1BDC0B64FC8A00BB4199 /* ARMInstrThumb.td */,
-				CF8F1BDD0B64FC8A00BB4199 /* ARMInstrVFP.td */,
-				CF8F1BDE0B64FC8A00BB4199 /* ARMISelDAGToDAG.cpp */,
-				CF8F1BDF0B64FC8A00BB4199 /* ARMISelLowering.cpp */,
-				CF8F1BE00B64FC8A00BB4199 /* ARMISelLowering.h */,
-				CF8F1BE10B64FC8A00BB4199 /* ARMLoadStoreOptimizer.cpp */,
-				CF8F1BE20B64FC8A00BB4199 /* ARMMachineFunctionInfo.h */,
-				CF8F1BE30B64FC8A00BB4199 /* ARMRegisterInfo.cpp */,
-				CF8F1BE40B64FC8A00BB4199 /* ARMRegisterInfo.h */,
-				CF8F1BE50B64FC8A00BB4199 /* ARMRegisterInfo.td */,
-				CF8F1BE60B64FC8A00BB4199 /* ARMSubtarget.cpp */,
-				CF8F1BE70B64FC8A00BB4199 /* ARMSubtarget.h */,
-				CF8F1BE80B64FC8A00BB4199 /* ARMTargetAsmInfo.cpp */,
-				CF8F1BE90B64FC8A00BB4199 /* ARMTargetAsmInfo.h */,
-				CF8F1BEA0B64FC8A00BB4199 /* ARMTargetMachine.cpp */,
-				CF8F1BEB0B64FC8A00BB4199 /* ARMTargetMachine.h */,
-			);
-			path = ARM;
-			sourceTree = "";
-		};
-		CFD99ADF0AFE878F0068D19C /* opt */ = {
-			isa = PBXGroup;
-			children = (
-				CFD99ADB0AFE87870068D19C /* AnalysisWrappers.cpp */,
-				CFD99ADC0AFE87870068D19C /* GraphPrinters.cpp */,
-				CFD99ADD0AFE87870068D19C /* opt.cpp */,
-				CFD99ADE0AFE87870068D19C /* PrintSCC.cpp */,
-			);
-			name = opt;
-			sourceTree = "";
-		};
-		CFE4213C0A66FAE100AB4BF6 /* Hello */ = {
-			isa = PBXGroup;
-			children = (
-				CFE4213D0A66FAE100AB4BF6 /* Hello.cpp */,
-			);
-			path = Hello;
-			sourceTree = "";
-		};
-		DE66EC7508ABE8EF00323D32 /* lib/VMCore */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EC5B08ABE86900323D32 /* AsmWriter.cpp */,
-				9F77937B0C73C4F400551F9C /* AutoUpgrade.cpp */,
-				DE66EC5C08ABE86A00323D32 /* BasicBlock.cpp */,
-				9F77937C0C73C4F400551F9C /* ConstantFold.cpp */,
-				9F77937D0C73C4F400551F9C /* ConstantFold.h */,
-				DE66EC6008ABE86A00323D32 /* Constants.cpp */,
-				9FD3E5900CA0129D00E54D15 /* Core.cpp */,
-				DE66EC6108ABE86A00323D32 /* Dominators.cpp */,
-				DE66EC6208ABE86A00323D32 /* Function.cpp */,
-				DE66EC6308ABE86A00323D32 /* Globals.cpp */,
-				CF73C0BD098A551F00627152 /* InlineAsm.cpp */,
-				DE66EC6408ABE86A00323D32 /* Instruction.cpp */,
-				DE66EC6508ABE86A00323D32 /* Instructions.cpp */,
-				CF1ACC9709C9DE4400D3C5EB /* IntrinsicInst.cpp */,
-				DE66EC6608ABE86A00323D32 /* LeakDetector.cpp */,
-				DE66EC6708ABE86A00323D32 /* Mangler.cpp */,
-				DE66EC6808ABE86A00323D32 /* Module.cpp */,
-				DE66EC6908ABE86A00323D32 /* ModuleProvider.cpp */,
-				DE66EC6A08ABE86A00323D32 /* Pass.cpp */,
-				CF8F1B5C0B64FA7300BB4199 /* PassManager.cpp */,
-				DE66EC6D08ABE86A00323D32 /* SymbolTableListTraitsImpl.h */,
-				DE66EC6E08ABE86A00323D32 /* Type.cpp */,
-				CF73C0BE098A551F00627152 /* TypeSymbolTable.cpp */,
-				DE66EC6F08ABE86A00323D32 /* Value.cpp */,
-				CF73C0BF098A551F00627152 /* ValueSymbolTable.cpp */,
-				CF9720900A9F3CA2002CEEDD /* ValueTypes.cpp */,
-				DE66EC7008ABE86A00323D32 /* Verifier.cpp */,
-			);
-			name = lib/VMCore;
-			sourceTree = "";
-		};
-		DE66EC8808ABEAC900323D32 /* lib/AsmParser */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EC8E08ABEAF000323D32 /* llvmAsmParser.y */,
-				DE66EC8F08ABEAF000323D32 /* Parser.cpp */,
-				DE66EC9008ABEAF000323D32 /* ParserInternals.h */,
-			);
-			name = lib/AsmParser;
-			sourceTree = "";
-		};
-		DE66ECBD08ABEC0700323D32 /* lib/Analysis */ = {
-			isa = PBXGroup;
-			children = (
-				DE66ED1A08ABEC0800323D32 /* IPA */,
-				DE66ECBE08ABEC0700323D32 /* AliasAnalysis.cpp */,
-				DE66ECBF08ABEC0700323D32 /* AliasAnalysisCounter.cpp */,
-				DE66ECC008ABEC0700323D32 /* AliasAnalysisEvaluator.cpp */,
-				CF8F1B4D0B64F80700BB4199 /* AliasDebugger.cpp */,
-				DE66ECC108ABEC0700323D32 /* AliasSetTracker.cpp */,
-				9F7C23E60CB81C2B00498408 /* Analysis.cpp */,
-				DE66ECC208ABEC0700323D32 /* BasicAliasAnalysis.cpp */,
-				DE66ECC308ABEC0700323D32 /* CFGPrinter.cpp */,
-				CF73C0B0098A523C00627152 /* ConstantFolding.cpp */,
-				DE66ED1708ABEC0800323D32 /* InstCount.cpp */,
-				DE66ED1808ABEC0800323D32 /* Interval.cpp */,
-				DE66ED1908ABEC0800323D32 /* IntervalPartition.cpp */,
-				DE66ED3308ABEC0800323D32 /* LoadValueNumbering.cpp */,
-				DE66ED3408ABEC0800323D32 /* LoopInfo.cpp */,
-				9F68EB010C77AD02004AA152 /* LoopPass.cpp */,
-				9F68EB020C77AD02004AA152 /* MemoryDependenceAnalysis.cpp */,
-				DE66ED3608ABEC0800323D32 /* PostDominators.cpp */,
-				DE66ED3708ABEC0800323D32 /* ProfileInfo.cpp */,
-				DE66ED3808ABEC0800323D32 /* ProfileInfoLoader.cpp */,
-				DE66ED3908ABEC0800323D32 /* ProfileInfoLoaderPass.cpp */,
-				DE66ED3A08ABEC0800323D32 /* ScalarEvolution.cpp */,
-				DE66ED3B08ABEC0800323D32 /* ScalarEvolutionExpander.cpp */,
-				DE66ED3C08ABEC0800323D32 /* Trace.cpp */,
-				DE66ED3D08ABEC0800323D32 /* ValueNumbering.cpp */,
-			);
-			name = lib/Analysis;
-			path = ../lib/Analysis;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66ED1A08ABEC0800323D32 /* IPA */ = {
-			isa = PBXGroup;
-			children = (
-				DE66ED1B08ABEC0800323D32 /* Andersens.cpp */,
-				DE66ED1C08ABEC0800323D32 /* CallGraph.cpp */,
-				DE66ED1D08ABEC0800323D32 /* CallGraphSCCPass.cpp */,
-				DE66ED2F08ABEC0800323D32 /* FindUsedTypes.cpp */,
-				DE66ED3008ABEC0800323D32 /* GlobalsModRef.cpp */,
-			);
-			path = IPA;
-			sourceTree = "";
-		};
-		DE66ED3E08ABEC2A00323D32 /* lib/CodeGen */ = {
-			isa = PBXGroup;
-			children = (
-				F27C8CFF0DAD307700A33844 /* ShadowStackCollector.cpp */,
-				754221420D171DFC00DDB61B /* MachineLICM.cpp */,
-				9FE450AB0C77AB6100C4FEA4 /* README.txt */,
-				DE66ED8308ABEC2B00323D32 /* SelectionDAG */,
-				DE66ED3F08ABEC2A00323D32 /* AsmPrinter.cpp */,
-				DE66ED4008ABEC2A00323D32 /* BranchFolding.cpp */,
-				CFC244570959DEF2009F8C47 /* DwarfWriter.cpp */,
-				9F7793500C73BD1500551F9C /* ELFWriter.h */,
-				DE66ED6F08ABEC2B00323D32 /* ELFWriter.cpp */,
-				9F7793510C73BD1500551F9C /* IfConversion.cpp */,
-				DE66ED7008ABEC2B00323D32 /* IntrinsicLowering.cpp */,
-				DE66ED7108ABEC2B00323D32 /* LiveInterval.cpp */,
-				DE66ED7308ABEC2B00323D32 /* LiveIntervalAnalysis.cpp */,
-				DE66ED7508ABEC2B00323D32 /* LiveVariables.cpp */,
-				CF32AF5C0AEE6A4E00D24CD4 /* LLVMTargetMachine.cpp */,
-				9F7793520C73BD1500551F9C /* LowerSubregs.cpp */,
-				DE66ED7608ABEC2B00323D32 /* MachineBasicBlock.cpp */,
-				CF6529A6095B21A8007F884E /* MachineModuleInfo.cpp */,
-				DE66ED7808ABEC2B00323D32 /* MachineFunction.cpp */,
-				DE66ED7908ABEC2B00323D32 /* MachineInstr.cpp */,
-				CF4F27F60A7B6FA3004359F6 /* MachinePassRegistry.cpp */,
-				9F7793530C73BD1500551F9C /* MachOWriter.h */,
-				CF9720350A9F3ADC002CEEDD /* MachOWriter.cpp */,
-				DE66ED7B08ABEC2B00323D32 /* Passes.cpp */,
-				DE66ED7C08ABEC2B00323D32 /* PHIElimination.cpp */,
-				9F7793540C73BD1500551F9C /* PostRASchedulerList.cpp */,
-				DE66ED7D08ABEC2B00323D32 /* PhysRegTracker.h */,
-				DE66ED7E08ABEC2B00323D32 /* PrologEpilogInserter.cpp */,
-				9F7793550C73BD1500551F9C /* RegAllocBigBlock.cpp */,
-				DE66ED8008ABEC2B00323D32 /* RegAllocLinearScan.cpp */,
-				DE66ED8108ABEC2B00323D32 /* RegAllocLocal.cpp */,
-				9FE25D940CAB16FB005383FC /* RegisterCoalescer.cpp */,
-				9F7793560C73BD1500551F9C /* RegisterScavenging.cpp */,
-				DE66ED8208ABEC2B00323D32 /* RegAllocSimple.cpp */,
-				9F7793570C73BD1500551F9C /* SimpleRegisterCoalescing.cpp */,
-				DE66ED9508ABEC2B00323D32 /* TwoAddressInstructionPass.cpp */,
-				DE66ED9608ABEC2B00323D32 /* UnreachableBlockElim.cpp */,
-				DE66ED9808ABEC2B00323D32 /* VirtRegMap.cpp */,
-				DE66ED9908ABEC2B00323D32 /* VirtRegMap.h */,
-			);
-			name = lib/CodeGen;
-			path = ../lib/CodeGen;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66ED8308ABEC2B00323D32 /* SelectionDAG */ = {
-			isa = PBXGroup;
-			children = (
-				9FE450AC0C77AB6E00C4FEA4 /* CallingConvLower.cpp */,
-				CF6B5AFD095C82C300D1EA42 /* DAGCombiner.cpp */,
-				DE66ED9008ABEC2B00323D32 /* LegalizeDAG.cpp */,
-				CF7FFA1F0985081C008B0087 /* ScheduleDAGList.cpp */,
-				DE694D9F08B51E0C0039C106 /* ScheduleDAG.cpp */,
-				DE66ED9208ABEC2B00323D32 /* SelectionDAG.cpp */,
-				DE66ED9308ABEC2B00323D32 /* SelectionDAGISel.cpp */,
-				DE66ED9408ABEC2B00323D32 /* SelectionDAGPrinter.cpp */,
-				CFE421060A66F86D00AB4BF6 /* ScheduleDAGRRList.cpp */,
-				CF9720370A9F3B1C002CEEDD /* TargetLowering.cpp */,
-			);
-			path = SelectionDAG;
-			sourceTree = "";
-		};
-		DE66ED9A08ABEC7200323D32 /* lib/Debugger */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EDB108ABEC7300323D32 /* Debugger.cpp */,
-				DE66EDB508ABEC7300323D32 /* ProgramInfo.cpp */,
-				DE66EDB608ABEC7300323D32 /* README.txt */,
-				DE66EDB708ABEC7300323D32 /* RuntimeInfo.cpp */,
-				DE66EDB808ABEC7300323D32 /* SourceFile.cpp */,
-				DE66EDB908ABEC7300323D32 /* SourceLanguage-CFamily.cpp */,
-				DE66EDBA08ABEC7300323D32 /* SourceLanguage-CPlusPlus.cpp */,
-				DE66EDBB08ABEC7300323D32 /* SourceLanguage-Unknown.cpp */,
-				DE66EDBC08ABEC7300323D32 /* SourceLanguage.cpp */,
-			);
-			name = lib/Debugger;
-			path = ../lib/Debugger;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66EDBF08ABEC8F00323D32 /* lib/ExecutionEngine */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EDC508ABEC9000323D32 /* Interpreter */,
-				DE66EDD308ABEC9000323D32 /* JIT */,
-				DE66EDC408ABEC9000323D32 /* ExecutionEngine.cpp */,
-				9F502B090D1D8D8D007939DF /* ExecutionEngineBindings.cpp */,
-			);
-			name = lib/ExecutionEngine;
-			path = ../lib/ExecutionEngine;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66EDC508ABEC9000323D32 /* Interpreter */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EDCE08ABEC9000323D32 /* Execution.cpp */,
-				DE66EDCF08ABEC9000323D32 /* ExternalFunctions.cpp */,
-				DE66EDD008ABEC9000323D32 /* Interpreter.cpp */,
-				DE66EDD108ABEC9000323D32 /* Interpreter.h */,
-			);
-			path = Interpreter;
-			sourceTree = "";
-		};
-		DE66EDD308ABEC9000323D32 /* JIT */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EDDE08ABEC9100323D32 /* Intercept.cpp */,
-				DE66EDDF08ABEC9100323D32 /* JIT.cpp */,
-				DE66EDE008ABEC9100323D32 /* JIT.h */,
-				DE66EDE108ABEC9100323D32 /* JITEmitter.cpp */,
-				DE66EDE308ABEC9100323D32 /* TargetSelect.cpp */,
-			);
-			path = JIT;
-			sourceTree = "";
-		};
-		DE66EDEB08ABEDD300323D32 /* lib/Linker */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EDF608ABEDD300323D32 /* LinkArchives.cpp */,
-				DE66EDF708ABEDD300323D32 /* Linker.cpp */,
-				DE66EDF808ABEDD300323D32 /* LinkItems.cpp */,
-				DE66EDF908ABEDD300323D32 /* LinkModules.cpp */,
-			);
-			name = lib/Linker;
-			path = ../lib/Linker;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66EDFB08ABEDE600323D32 /* lib/Support */ = {
-			isa = PBXGroup;
-			children = (
-				9FE25D950CAB1724005383FC /* APFloat.cpp */,
-				9FE450A60C77AB3200C4FEA4 /* APInt.cpp */,
-				9FE450A70C77AB3200C4FEA4 /* ConstantRange.cpp */,
-				9FE450A80C77AB3200C4FEA4 /* MemoryBuffer.cpp */,
-				9FE450A90C77AB3200C4FEA4 /* SmallPtrSet.cpp */,
-				9FE450AA0C77AB3200C4FEA4 /* StringMap.cpp */,
-				CFD99AB70AFE848A0068D19C /* Allocator.cpp */,
-				DE66EDFC08ABEDE600323D32 /* Annotation.cpp */,
-				DE66EE1D08ABEDE600323D32 /* CommandLine.cpp */,
-				DE66EE3D08ABEDE600323D32 /* Debug.cpp */,
-				CF79495D09B326D4005ADFCA /* Dwarf.cpp */,
-				DE66EE3E08ABEDE600323D32 /* FileUtilities.cpp */,
-				CF42B6C40AF2512000D5D47C /* FoldingSet.cpp */,
-				CFE421070A66F8DC00AB4BF6 /* GraphWriter.cpp */,
-				DE66EE3F08ABEDE600323D32 /* IsInf.cpp */,
-				DE66EE4008ABEDE600323D32 /* IsNAN.cpp */,
-				CF8F1B500B64F86A00BB4199 /* ManagedStatic.cpp */,
-				DE66EE4208ABEDE600323D32 /* PluginLoader.cpp */,
-				DE66EE4308ABEDE600323D32 /* SlowOperationInformer.cpp */,
-				DE66EE4408ABEDE600323D32 /* Statistic.cpp */,
-				CF8F1B510B64F86A00BB4199 /* Streams.cpp */,
-				DE66EE4508ABEDE700323D32 /* StringExtras.cpp */,
-				9F5B90CB0D0CE87100CDFDEA /* StringPool.cpp */,
-				DE66EE4608ABEDE700323D32 /* SystemUtils.cpp */,
-				DE66EE4708ABEDE700323D32 /* Timer.cpp */,
-			);
-			name = lib/Support;
-			path = ../lib/Support;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66EE4908ABEE3400323D32 /* lib/System */ = {
-			isa = PBXGroup;
-			children = (
-				9FE450A50C77AAF000C4FEA4 /* Disassembler.cpp */,
-				DE66EE7E08ABEE3500323D32 /* Unix */,
-				DE66EE8B08ABEE3500323D32 /* Win32 */,
-				CFE421090A66F93300AB4BF6 /* Alarm.cpp */,
-				DE66EE6008ABEE3400323D32 /* DynamicLibrary.cpp */,
-				CF8F1B530B64F8C000BB4199 /* IncludeFile.cpp */,
-				DE66EE6108ABEE3400323D32 /* LICENSE.TXT */,
-				CFD99ABA0AFE84D70068D19C /* IncludeFile.cpp */,
-				DE66EE6508ABEE3400323D32 /* MappedFile.cpp */,
-				DE66EE6608ABEE3400323D32 /* Memory.cpp */,
-				DE66EE6708ABEE3400323D32 /* Mutex.cpp */,
-				DE66EE6808ABEE3400323D32 /* Path.cpp */,
-				DE66EE6908ABEE3400323D32 /* Process.cpp */,
-				DE66EE6A08ABEE3400323D32 /* Program.cpp */,
-				DE66EE6B08ABEE3400323D32 /* README.txt */,
-				DE66EE7C08ABEE3400323D32 /* Signals.cpp */,
-				DE66EE7D08ABEE3400323D32 /* TimeValue.cpp */,
-			);
-			name = lib/System;
-			path = ../lib/System;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66EE7E08ABEE3500323D32 /* Unix */ = {
-			isa = PBXGroup;
-			children = (
-				CFD99ABB0AFE84EF0068D19C /* Alarm.inc */,
-				DE66EE7F08ABEE3500323D32 /* MappedFile.inc */,
-				DE66EE8008ABEE3500323D32 /* Memory.inc */,
-				DE66EE8108ABEE3500323D32 /* Mutex.inc */,
-				DE66EE8208ABEE3500323D32 /* Path.inc */,
-				DE66EE8308ABEE3500323D32 /* Process.inc */,
-				DE66EE8408ABEE3500323D32 /* Program.inc */,
-				DE66EE8508ABEE3500323D32 /* README.txt */,
-				DE66EE8608ABEE3500323D32 /* Signals.inc */,
-				DE66EE8908ABEE3500323D32 /* TimeValue.inc */,
-				DE66EE8A08ABEE3500323D32 /* Unix.h */,
-			);
-			path = Unix;
-			sourceTree = "";
-		};
-		DE66EE8B08ABEE3500323D32 /* Win32 */ = {
-			isa = PBXGroup;
-			children = (
-				CFE4210A0A66F93300AB4BF6 /* Alarm.inc */,
-				DE66EE8C08ABEE3500323D32 /* DynamicLibrary.inc */,
-				DE66EE8D08ABEE3500323D32 /* MappedFile.inc */,
-				DE66EE8E08ABEE3500323D32 /* Memory.inc */,
-				DE66EE8F08ABEE3500323D32 /* Mutex.inc */,
-				DE66EE9008ABEE3500323D32 /* Path.inc */,
-				DE66EE9108ABEE3500323D32 /* Process.inc */,
-				DE66EE9208ABEE3500323D32 /* Program.inc */,
-				DE66EE9308ABEE3500323D32 /* Signals.inc */,
-				DE66EE9408ABEE3500323D32 /* TimeValue.inc */,
-				DE66EE9508ABEE3500323D32 /* Win32.h */,
-			);
-			path = Win32;
-			sourceTree = "";
-		};
-		DE66EE9608ABEE5D00323D32 /* lib/Target */ = {
-			isa = PBXGroup;
-			children = (
-				9F7794290C73CB7900551F9C /* MSIL */,
-				DE66EE9708ABEE5D00323D32 /* Alpha */,
-				CF8F1BCF0B64FC8A00BB4199 /* ARM */,
-				DE66EEC908ABEE5E00323D32 /* CBackend */,
-				9F7794120C73CB6100551F9C /* Mips */,
-				DE66EF1108ABEE5E00323D32 /* PowerPC */,
-				DE66EF7008ABEE5F00323D32 /* Sparc */,
-				DE66F09308ABEE6000323D32 /* X86 */,
-				DE66EF1008ABEE5E00323D32 /* TargetRegisterInfo.cpp */,
-				CF9BCD1508C75070001E7011 /* SubtargetFeature.cpp */,
-				9FEDD6B60D8D83D0009F6DF1 /* Target.cpp */,
-				DE66F08A08ABEE6000323D32 /* Target.td */,
-				CF47BD860AAF487E00A8B13E /* TargetAsmInfo.cpp */,
-				9FE25D960CAB1759005383FC /* TargetCallingConv.td */,
-				DE66F08B08ABEE6000323D32 /* TargetData.cpp */,
-				DE66F08C08ABEE6000323D32 /* TargetFrameInfo.cpp */,
-				DE66F08D08ABEE6000323D32 /* TargetInstrInfo.cpp */,
-				DE66F08F08ABEE6000323D32 /* TargetMachine.cpp */,
-				DE66F09008ABEE6000323D32 /* TargetMachineRegistry.cpp */,
-				84115FFE0B66D87400E1293E /* TargetMachOWriterInfo.cpp */,
-				CF490D14090541D30072DB1C /* TargetSchedule.td */,
-				CF490D15090541D30072DB1C /* TargetSelectionDAG.td */,
-				DE66F09208ABEE6000323D32 /* TargetSubtarget.cpp */,
-			);
-			name = lib/Target;
-			path = ../lib/Target;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66EE9708ABEE5D00323D32 /* Alpha */ = {
-			isa = PBXGroup;
-			children = (
-				DE66EE9808ABEE5E00323D32 /* Alpha.h */,
-				DE66EE9908ABEE5E00323D32 /* Alpha.td */,
-				DE66EE9A08ABEE5E00323D32 /* AlphaAsmPrinter.cpp */,
-				CF8F1B540B64F90F00BB4199 /* AlphaBranchSelector.cpp */,
-				DE66EE9B08ABEE5E00323D32 /* AlphaCodeEmitter.cpp */,
-				CFA702BB0A6FA85F0006009A /* AlphaGenAsmWriter.inc */,
-				CFA702BC0A6FA85F0006009A /* AlphaGenCodeEmitter.inc */,
-				CFA702BD0A6FA85F0006009A /* AlphaGenDAGISel.inc */,
-				CFA702BE0A6FA85F0006009A /* AlphaGenInstrInfo.inc */,
-				CFA702BF0A6FA85F0006009A /* AlphaGenInstrNames.inc */,
-				CFA702C00A6FA85F0006009A /* AlphaGenRegisterInfo.h.inc */,
-				CFA702C10A6FA85F0006009A /* AlphaGenRegisterInfo.inc */,
-				CFA702C20A6FA85F0006009A /* AlphaGenRegisterNames.inc */,
-				CFA702C30A6FA85F0006009A /* AlphaGenSubtarget.inc */,
-				DE66EEA308ABEE5E00323D32 /* AlphaInstrFormats.td */,
-				DE66EEA408ABEE5E00323D32 /* AlphaInstrInfo.cpp */,
-				DE66EEA508ABEE5E00323D32 /* AlphaInstrInfo.h */,
-				DE66EEA608ABEE5E00323D32 /* AlphaInstrInfo.td */,
-				CFBD8B1A090E76540020B107 /* AlphaISelDAGToDAG.cpp */,
-				CFBD8B1B090E76540020B107 /* AlphaISelLowering.cpp */,
-				CFBD8B1C090E76540020B107 /* AlphaISelLowering.h */,
-				DE66EEA908ABEE5E00323D32 /* AlphaJITInfo.cpp */,
-				DE66EEAA08ABEE5E00323D32 /* AlphaJITInfo.h */,
-				CF8F1B550B64F90F00BB4199 /* AlphaLLRP.cpp */,
-				DE66EEAB08ABEE5E00323D32 /* AlphaRegisterInfo.cpp */,
-				DE66EEAC08ABEE5E00323D32 /* AlphaRegisterInfo.h */,
-				DE66EEAD08ABEE5E00323D32 /* AlphaRegisterInfo.td */,
-				DE66EEAE08ABEE5E00323D32 /* AlphaRelocations.h */,
-				CFE4210B0A66F96400AB4BF6 /* AlphaSchedule.td */,
-				CFBD8B1D090E76540020B107 /* AlphaSubtarget.cpp */,
-				CFBD8B1E090E76540020B107 /* AlphaSubtarget.h */,
-				CF341DAE0AB07A8B0099B064 /* AlphaTargetAsmInfo.cpp */,
-				CF341DAD0AB07A8B0099B064 /* AlphaTargetAsmInfo.h */,
-				DE66EEAF08ABEE5E00323D32 /* AlphaTargetMachine.cpp */,
-				DE66EEB008ABEE5E00323D32 /* AlphaTargetMachine.h */,
-			);
-			path = Alpha;
-			sourceTree = "";
-		};
-		DE66EEC908ABEE5E00323D32 /* CBackend */ = {
-			isa = PBXGroup;
-			children = (
-				CF8F1B560B64F98900BB4199 /* CBackend.cpp */,
-				DE66EECA08ABEE5E00323D32 /* CTargetMachine.h */,
-			);
-			path = CBackend;
-			sourceTree = "";
-		};
-		DE66EF1108ABEE5E00323D32 /* PowerPC */ = {
-			isa = PBXGroup;
-			children = (
-				9FE4509A0C77A79C00C4FEA4 /* PPCCallingConv.td */,
-				9FE4509B0C77A79C00C4FEA4 /* PPCGenCallingConv.inc */,
-				841160000B66D8AC00E1293E /* PPCMachOWriterInfo.h */,
-				84115FFF0B66D89B00E1293E /* PPCMachOWriterInfo.cpp */,
-				CFA702CB0A6FA8AD0006009A /* PPCGenAsmWriter.inc */,
-				CFA702CC0A6FA8AD0006009A /* PPCGenCodeEmitter.inc */,
-				CFA702CD0A6FA8AD0006009A /* PPCGenDAGISel.inc */,
-				CFA702CE0A6FA8AD0006009A /* PPCGenInstrInfo.inc */,
-				CFA702CF0A6FA8AD0006009A /* PPCGenInstrNames.inc */,
-				CFA702D00A6FA8AD0006009A /* PPCGenRegisterInfo.h.inc */,
-				CFA702D10A6FA8AD0006009A /* PPCGenRegisterInfo.inc */,
-				CFA702D20A6FA8AD0006009A /* PPCGenRegisterNames.inc */,
-				CFA702D30A6FA8AD0006009A /* PPCGenSubtarget.inc */,
-				CFE421140A66FA2D00AB4BF6 /* PPC.h */,
-				CFE421150A66FA2D00AB4BF6 /* PPC.td */,
-				CFE421160A66FA2D00AB4BF6 /* PPCAsmPrinter.cpp */,
-				CFE421170A66FA2D00AB4BF6 /* PPCBranchSelector.cpp */,
-				CFE421180A66FA2D00AB4BF6 /* PPCCodeEmitter.cpp */,
-				CFE421190A66FA2D00AB4BF6 /* PPCFrameInfo.h */,
-				CFE4211A0A66FA2D00AB4BF6 /* PPCHazardRecognizers.cpp */,
-				CFE4211B0A66FA2D00AB4BF6 /* PPCHazardRecognizers.h */,
-				CFE4211C0A66FA2D00AB4BF6 /* PPCInstr64Bit.td */,
-				CFE4211D0A66FA2D00AB4BF6 /* PPCInstrAltivec.td */,
-				CFE4211E0A66FA2D00AB4BF6 /* PPCInstrBuilder.h */,
-				CFE4211F0A66FA2D00AB4BF6 /* PPCInstrFormats.td */,
-				CFE421200A66FA2D00AB4BF6 /* PPCInstrInfo.cpp */,
-				CFE421210A66FA2D00AB4BF6 /* PPCInstrInfo.h */,
-				CFE421220A66FA2D00AB4BF6 /* PPCInstrInfo.td */,
-				CFE421230A66FA2D00AB4BF6 /* PPCISelDAGToDAG.cpp */,
-				CFE421240A66FA2D00AB4BF6 /* PPCISelLowering.cpp */,
-				CFE421250A66FA2D00AB4BF6 /* PPCISelLowering.h */,
-				CFE421260A66FA2D00AB4BF6 /* PPCJITInfo.cpp */,
-				CFE421270A66FA2D00AB4BF6 /* PPCJITInfo.h */,
-				CFABD0A20B09E342003EB061 /* PPCMachineFunctionInfo.h */,
-				CFE421280A66FA2D00AB4BF6 /* PPCPerfectShuffle.h */,
-				CF8F1B570B64F9AC00BB4199 /* PPCPredicates.cpp */,
-				CF8F1B580B64F9AC00BB4199 /* PPCPredicates.h */,
-				CFE421290A66FA2D00AB4BF6 /* PPCRegisterInfo.cpp */,
-				CFE4212A0A66FA2D00AB4BF6 /* PPCRegisterInfo.h */,
-				CFE4212B0A66FA2D00AB4BF6 /* PPCRegisterInfo.td */,
-				CFE4212C0A66FA2D00AB4BF6 /* PPCRelocations.h */,
-				CFE4212D0A66FA2D00AB4BF6 /* PPCSchedule.td */,
-				CFE4212E0A66FA2D00AB4BF6 /* PPCScheduleG3.td */,
-				CFE4212F0A66FA2D00AB4BF6 /* PPCScheduleG4.td */,
-				CFE421300A66FA2D00AB4BF6 /* PPCScheduleG4Plus.td */,
-				CFE421310A66FA2D00AB4BF6 /* PPCScheduleG5.td */,
-				CFE421320A66FA2E00AB4BF6 /* PPCSubtarget.cpp */,
-				CFE421330A66FA2E00AB4BF6 /* PPCSubtarget.h */,
-				CF341E020AB080220099B064 /* PPCTargetAsmInfo.cpp */,
-				CF341E010AB080220099B064 /* PPCTargetAsmInfo.h */,
-				CFE421340A66FA2E00AB4BF6 /* PPCTargetMachine.cpp */,
-				CFE421350A66FA2E00AB4BF6 /* PPCTargetMachine.h */,
-				CFE421360A66FA2E00AB4BF6 /* README_ALTIVEC.txt */,
-				CFE421370A66FA2E00AB4BF6 /* README.txt */,
-			);
-			path = PowerPC;
-			sourceTree = "";
-		};
-		DE66EF7008ABEE5F00323D32 /* Sparc */ = {
-			isa = PBXGroup;
-			children = (
-				CF65280109D1BA3800C4B521 /* SparcGenAsmWriter.inc */,
-				CF65280209D1BA3800C4B521 /* SparcGenDAGISel.inc */,
-				CF65280309D1BA3800C4B521 /* SparcGenInstrInfo.inc */,
-				CF65280409D1BA3800C4B521 /* SparcGenInstrNames.inc */,
-				CF65280509D1BA3800C4B521 /* SparcGenRegisterInfo.h.inc */,
-				CF65280609D1BA3800C4B521 /* SparcGenRegisterInfo.inc */,
-				CF65280709D1BA3800C4B521 /* SparcGenRegisterNames.inc */,
-				CF65280809D1BA3800C4B521 /* SparcGenSubtarget.inc */,
-				CF6527FA09D1BA3800C4B521 /* DelaySlotFiller.cpp */,
-				CF6527FB09D1BA3800C4B521 /* FPMover.cpp */,
-				CF6527FC09D1BA3800C4B521 /* Makefile */,
-				CF6527FD09D1BA3800C4B521 /* README.txt */,
-				CF6527FE09D1BA3800C4B521 /* Sparc.h */,
-				CF6527FF09D1BA3800C4B521 /* Sparc.td */,
-				CF65280009D1BA3800C4B521 /* SparcAsmPrinter.cpp */,
-				CF65280909D1BA3800C4B521 /* SparcInstrFormats.td */,
-				CF65280A09D1BA3800C4B521 /* SparcInstrInfo.cpp */,
-				CF65280B09D1BA3800C4B521 /* SparcInstrInfo.h */,
-				CF65280C09D1BA3800C4B521 /* SparcInstrInfo.td */,
-				CF65280D09D1BA3800C4B521 /* SparcISelDAGToDAG.cpp */,
-				CF65280E09D1BA3800C4B521 /* SparcRegisterInfo.cpp */,
-				CF65280F09D1BA3800C4B521 /* SparcRegisterInfo.h */,
-				CF65281009D1BA3800C4B521 /* SparcRegisterInfo.td */,
-				CF65281109D1BA3800C4B521 /* SparcSubtarget.cpp */,
-				CF65281209D1BA3800C4B521 /* SparcSubtarget.h */,
-				CF341E230AB0814B0099B064 /* SparcTargetAsmInfo.cpp */,
-				CF341E220AB0814B0099B064 /* SparcTargetAsmInfo.h */,
-				CF65281309D1BA3800C4B521 /* SparcTargetMachine.cpp */,
-				CF65281409D1BA3800C4B521 /* SparcTargetMachine.h */,
-			);
-			path = Sparc;
-			sourceTree = "";
-		};
-		DE66F09308ABEE6000323D32 /* X86 */ = {
-			isa = PBXGroup;
-			children = (
-				9FE4509C0C77A7BC00C4FEA4 /* README-MMX.txt */,
-				9FE4509D0C77A7BC00C4FEA4 /* X86CallingConv.td */,
-				9FE4509F0C77A7BC00C4FEA4 /* X86ELFWriterInfo.cpp */,
-				9FE450A00C77A7BC00C4FEA4 /* X86ELFWriterInfo.h */,
-				9FE450A10C77A7BC00C4FEA4 /* X86GenCallingConv.inc */,
-				9FE450A20C77A7BC00C4FEA4 /* X86InstrFormats.td */,
-				CFA702D40A6FA8DD0006009A /* X86GenAsmWriter.inc */,
-				CFA702D50A6FA8DD0006009A /* X86GenAsmWriter1.inc */,
-				CFA702D60A6FA8DD0006009A /* X86GenDAGISel.inc */,
-				CFA702D70A6FA8DD0006009A /* X86GenInstrInfo.inc */,
-				CFA702D80A6FA8DD0006009A /* X86GenInstrNames.inc */,
-				CFA702D90A6FA8DD0006009A /* X86GenRegisterInfo.h.inc */,
-				CFA702DA0A6FA8DD0006009A /* X86GenRegisterInfo.inc */,
-				CFA702DB0A6FA8DD0006009A /* X86GenRegisterNames.inc */,
-				CFA702DC0A6FA8DD0006009A /* X86GenSubtarget.inc */,
-				CFE421380A66FA8000AB4BF6 /* README-FPStack.txt */,
-				CFE421390A66FA8000AB4BF6 /* README-SSE.txt */,
-				CFD99ABE0AFE857A0068D19C /* README-X86-64.txt */,
-				CFE4213A0A66FA8000AB4BF6 /* README.txt */,
-				CFF0DE6309BF6C360031957F /* X86InstrFPStack.td */,
-				CFF0DE6409BF6C360031957F /* X86InstrMMX.td */,
-				CFF0DE6509BF6C360031957F /* X86InstrSSE.td */,
-				DE66F0BC08ABEE6000323D32 /* X86.h */,
-				DE66F0BD08ABEE6000323D32 /* X86.td */,
-				DE66F0BE08ABEE6000323D32 /* X86AsmPrinter.cpp */,
-				DE66F0BF08ABEE6000323D32 /* X86AsmPrinter.h */,
-				DE66F0C008ABEE6000323D32 /* X86ATTAsmPrinter.cpp */,
-				DE66F0C108ABEE6000323D32 /* X86ATTAsmPrinter.h */,
-				DE66F0C208ABEE6000323D32 /* X86CodeEmitter.cpp */,
-				CF8F1B590B64F9E100BB4199 /* X86COFF.h */,
-				DE66F0C408ABEE6000323D32 /* X86FloatingPoint.cpp */,
-				DE66F0CC08ABEE6000323D32 /* X86InstrBuilder.h */,
-				DE66F0CD08ABEE6000323D32 /* X86InstrInfo.cpp */,
-				DE66F0CE08ABEE6000323D32 /* X86InstrInfo.h */,
-				DE66F0CF08ABEE6100323D32 /* X86InstrInfo.td */,
-				DE66F0D008ABEE6100323D32 /* X86IntelAsmPrinter.cpp */,
-				DE66F0D108ABEE6100323D32 /* X86IntelAsmPrinter.h */,
-				DE66F0D508ABEE6100323D32 /* X86JITInfo.cpp */,
-				DE66F0D608ABEE6100323D32 /* X86JITInfo.h */,
-				CFE4213B0A66FA8000AB4BF6 /* X86MachineFunctionInfo.h */,
-				DE66F0D808ABEE6100323D32 /* X86RegisterInfo.cpp */,
-				DE66F0D908ABEE6100323D32 /* X86RegisterInfo.h */,
-				DE66F0DA08ABEE6100323D32 /* X86RegisterInfo.td */,
-				DE66F0DB08ABEE6100323D32 /* X86Relocations.h */,
-				CFC244BB0959F24C009F8C47 /* X86ISelDAGToDAG.cpp */,
-				CFC244BC0959F24C009F8C47 /* X86ISelLowering.cpp */,
-				CFC244BD0959F24C009F8C47 /* X86ISelLowering.h */,
-				DE66F0DC08ABEE6100323D32 /* X86Subtarget.cpp */,
-				DE66F0DD08ABEE6100323D32 /* X86Subtarget.h */,
-				CF341E330AB082D60099B064 /* X86TargetAsmInfo.cpp */,
-				CF341E320AB082D60099B064 /* X86TargetAsmInfo.h */,
-				DE66F0DE08ABEE6100323D32 /* X86TargetMachine.cpp */,
-				DE66F0DF08ABEE6100323D32 /* X86TargetMachine.h */,
-			);
-			path = X86;
-			sourceTree = "";
-		};
-		DE66F0E108ABEFB300323D32 /* lib/Transforms */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F0EE08ABEFB300323D32 /* Instrumentation */,
-				CFE4213C0A66FAE100AB4BF6 /* Hello */,
-				DE66F11F08ABEFB300323D32 /* IPO */,
-				DE66F15C08ABEFB400323D32 /* Scalar */,
-				DE66F1BD08ABEFB400323D32 /* Utils */,
-			);
-			name = lib/Transforms;
-			path = ../lib/Transforms;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66F0EE08ABEFB300323D32 /* Instrumentation */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F0EF08ABEFB300323D32 /* BlockProfiling.cpp */,
-				DE66F0FE08ABEFB300323D32 /* EdgeProfiling.cpp */,
-				DE66F11B08ABEFB300323D32 /* ProfilingUtils.cpp */,
-				DE66F11C08ABEFB300323D32 /* ProfilingUtils.h */,
-				CF73C0B7098A546000627152 /* RSProfiling.cpp */,
-				CF73C0B8098A546000627152 /* RSProfiling.h */,
-			);
-			path = Instrumentation;
-			sourceTree = "";
-		};
-		DE66F11F08ABEFB300323D32 /* IPO */ = {
-			isa = PBXGroup;
-			children = (
-				9F7793770C73C48A00551F9C /* StripDeadPrototypes.cpp */,
-				DE66F12008ABEFB300323D32 /* ArgumentPromotion.cpp */,
-				DE66F12108ABEFB300323D32 /* ConstantMerge.cpp */,
-				DE66F12208ABEFB300323D32 /* DeadArgumentElimination.cpp */,
-				DE66F12308ABEFB300323D32 /* DeadTypeElimination.cpp */,
-				DE66F14C08ABEFB400323D32 /* GlobalDCE.cpp */,
-				DE66F14D08ABEFB400323D32 /* GlobalOpt.cpp */,
-				CFE4213F0A66FB5E00AB4BF6 /* IndMemRemoval.cpp */,
-				DE66F14E08ABEFB400323D32 /* Inliner.cpp */,
-				DE66F15008ABEFB400323D32 /* InlineSimple.cpp */,
-				DE66F15108ABEFB400323D32 /* Internalize.cpp */,
-				DE66F15208ABEFB400323D32 /* IPConstantPropagation.cpp */,
-				DE66F15308ABEFB400323D32 /* LoopExtractor.cpp */,
-				DE66F15408ABEFB400323D32 /* LowerSetJmp.cpp */,
-				DE66F15608ABEFB400323D32 /* PruneEH.cpp */,
-				DE66F15708ABEFB400323D32 /* RaiseAllocations.cpp */,
-				DE66F15808ABEFB400323D32 /* SimplifyLibCalls.cpp */,
-				DE66F15908ABEFB400323D32 /* StripSymbols.cpp */,
-			);
-			path = IPO;
-			sourceTree = "";
-		};
-		DE66F15C08ABEFB400323D32 /* Scalar */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F15E08ABEFB400323D32 /* ADCE.cpp */,
-				DE66F15F08ABEFB400323D32 /* BasicBlockPlacement.cpp */,
-				9F7793460C73BC2000551F9C /* CodeGenPrepare.cpp */,
-				DE66F16008ABEFB400323D32 /* CondPropagate.cpp */,
-				DE66F16108ABEFB400323D32 /* ConstantProp.cpp */,
-				DE66F16308ABEFB400323D32 /* DCE.cpp */,
-				DE66F16408ABEFB400323D32 /* DeadStoreElimination.cpp */,
-				DE66F1A308ABEFB400323D32 /* GCSE.cpp */,
-				9F7793470C73BC2000551F9C /* GVN.cpp */,
-				9F7793480C73BC2000551F9C /* GVNPRE.cpp */,
-				DE66F1A408ABEFB400323D32 /* IndVarSimplify.cpp */,
-				DE66F1A508ABEFB400323D32 /* InstructionCombining.cpp */,
-				DE66F1A608ABEFB400323D32 /* LICM.cpp */,
-				9F77934A0C73BC2000551F9C /* LoopRotation.cpp */,
-				9F7793490C73BC2000551F9C /* LoopIndexSplit.cpp */,
-				DE66F1A808ABEFB400323D32 /* LoopStrengthReduce.cpp */,
-				DE66F1A908ABEFB400323D32 /* LoopUnroll.cpp */,
-				DE66F1AA08ABEFB400323D32 /* LoopUnswitch.cpp */,
-				CF8F1B5B0B64FA2F00BB4199 /* PredicateSimplifier.cpp */,
-				DE66F1B508ABEFB400323D32 /* Reassociate.cpp */,
-				CF73C0B9098A546000627152 /* Reg2Mem.cpp */,
-				9FEDD5F70D8D797D009F6DF1 /* Scalar.cpp */,
-				DE66F1B608ABEFB400323D32 /* ScalarReplAggregates.cpp */,
-				DE66F1B708ABEFB400323D32 /* SCCP.cpp */,
-				DE66F1B808ABEFB400323D32 /* SimplifyCFG.cpp */,
-				DE66F1B908ABEFB400323D32 /* TailDuplication.cpp */,
-				DE66F1BA08ABEFB400323D32 /* TailRecursionElimination.cpp */,
-			);
-			path = Scalar;
-			sourceTree = "";
-		};
-		DE66F1BD08ABEFB400323D32 /* Utils */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F1BE08ABEFB400323D32 /* BasicBlockUtils.cpp */,
-				9F7793780C73C49A00551F9C /* BasicInliner.cpp */,
-				DE66F1BF08ABEFB400323D32 /* BreakCriticalEdges.cpp */,
-				DE66F1C008ABEFB400323D32 /* CloneFunction.cpp */,
-				9F7793790C73C49A00551F9C /* CloneLoop.cpp */,
-				DE66F1C108ABEFB400323D32 /* CloneModule.cpp */,
-				DE66F1C208ABEFB400323D32 /* CloneTrace.cpp */,
-				DE66F1C308ABEFB400323D32 /* CodeExtractor.cpp */,
-				DE66F1E008ABEFB400323D32 /* DemoteRegToStack.cpp */,
-				9F77937A0C73C49A00551F9C /* InlineCost.cpp */,
-				DE66F1E108ABEFB400323D32 /* InlineFunction.cpp */,
-				CF97208A0A9F3C6F002CEEDD /* LCSSA.cpp */,
-				DE66F1E208ABEFB400323D32 /* Local.cpp */,
-				DE4DA0390911476D0012D44B /* LoopSimplify.cpp */,
-				CF97208B0A9F3C6F002CEEDD /* LowerAllocations.cpp */,
-				CF97208C0A9F3C6F002CEEDD /* LowerInvoke.cpp */,
-				CF97208E0A9F3C6F002CEEDD /* LowerSwitch.cpp */,
-				CF97208F0A9F3C6F002CEEDD /* Mem2Reg.cpp */,
-				DE66F1E408ABEFB400323D32 /* PromoteMemoryToRegister.cpp */,
-				DE66F1E508ABEFB400323D32 /* SimplifyCFG.cpp */,
-				DE66F1E608ABEFB400323D32 /* UnifyFunctionExitNodes.cpp */,
-				DE66F1E708ABEFB400323D32 /* ValueMapper.cpp */,
-			);
-			path = Utils;
-			sourceTree = "";
-		};
-		DE66F1E908ABF03100323D32 /* include/llvm */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F1EB08ABF03100323D32 /* ADT */,
-				DE66F20308ABF03100323D32 /* Analysis */,
-				DE66F22408ABF03100323D32 /* Assembly */,
-				9F77937F0C73C54C00551F9C /* Bitcode */,
-				DE66F23508ABF03100323D32 /* CodeGen */,
-				DE66F24C08ABF03100323D32 /* Config */,
-				DE66F25308ABF03100323D32 /* Debugger */,
-				DE66F25B08ABF03100323D32 /* ExecutionEngine */,
-				DE66F26E08ABF03200323D32 /* Support */,
-				DE66F29408ABF03200323D32 /* System */,
-				DE66F29F08ABF03200323D32 /* Target */,
-				DE66F2AB08ABF03200323D32 /* Transforms */,
-				DE66F1EA08ABF03100323D32 /* AbstractTypeUser.h */,
-				DE66F22308ABF03100323D32 /* Argument.h */,
-				9FA638D90C77B184007F12AE /* AutoUpgrade.h */,
-				DE66F22A08ABF03100323D32 /* BasicBlock.h */,
-				DE66F23308ABF03100323D32 /* CallGraphSCCPass.h */,
-				DE66F23408ABF03100323D32 /* CallingConv.h */,
-				DE66F25108ABF03100323D32 /* Constant.h */,
-				DE66F25208ABF03100323D32 /* Constants.h */,
-				DE66F25A08ABF03100323D32 /* DerivedTypes.h */,
-				DE66F25E08ABF03100323D32 /* Function.h */,
-				9FA638DA0C77B184007F12AE /* GlobalAlias.h */,
-				DE66F25F08ABF03100323D32 /* GlobalValue.h */,
-				DE66F26008ABF03100323D32 /* GlobalVariable.h */,
-				CF73C0A2098A4FDF00627152 /* InlineAsm.h */,
-				DE66F26108ABF03100323D32 /* InstrTypes.h */,
-				DE66F26208ABF03100323D32 /* Instruction.def */,
-				DE66F26308ABF03100323D32 /* Instruction.h */,
-				DE66F26408ABF03100323D32 /* Instructions.h */,
-				DE66F26508ABF03100323D32 /* IntrinsicInst.h */,
-				DE66F26608ABF03100323D32 /* Intrinsics.h */,
-				CF65223409CA39B800C4B521 /* Intrinsics.gen */,
-				CFE420FF0A66F67300AB4BF6 /* IntrinsicsPowerPC.td */,
-				CFE421000A66F67300AB4BF6 /* IntrinsicsX86.td */,
-				CF8D62FA09C2226F006017BA /* Intrinsics.td */,
-				CF9720260A9F39B9002CEEDD /* LinkAllPasses.h */,
-				CFE421010A66F67300AB4BF6 /* LinkAllVMCore.h */,
-				CF9720270A9F39B9002CEEDD /* LinkTimeOptimizer.h */,
-				DE66F26708ABF03100323D32 /* Linker.h */,
-				DE66F26808ABF03100323D32 /* Module.h */,
-				DE66F26908ABF03200323D32 /* ModuleProvider.h */,
-				9F77937E0C73C53000551F9C /* ParameterAttributes.h */,
-				DE66F26A08ABF03200323D32 /* Pass.h */,
-				DE66F26B08ABF03200323D32 /* PassAnalysisSupport.h */,
-				DE66F26C08ABF03200323D32 /* PassManager.h */,
-				CF8F1B420B64F70B00BB4199 /* PassManagers.h */,
-				DE66F26D08ABF03200323D32 /* PassSupport.h */,
-				DE66F29308ABF03200323D32 /* SymbolTableListTraits.h */,
-				DE66F2B708ABF03200323D32 /* Type.h */,
-				CF73C0A3098A4FDF00627152 /* TypeSymbolTable.h */,
-				DE66F2B808ABF03200323D32 /* Use.h */,
-				DE66F2B908ABF03200323D32 /* User.h */,
-				DE66F2BA08ABF03200323D32 /* Value.h */,
-				CF73C0A4098A4FDF00627152 /* ValueSymbolTable.h */,
-			);
-			name = include/llvm;
-			path = ../include/llvm;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66F1EB08ABF03100323D32 /* ADT */ = {
-			isa = PBXGroup;
-			children = (
-				35E98A830CBC2ED300C5CDC1 /* DenseSet.h */,
-				35E98A840CBC2ED300C5CDC1 /* ImmutableMap.h */,
-				35E98A850CBC2ED300C5CDC1 /* ImmutableSet.h */,
-				9FA638DD0C77B1AB007F12AE /* BitVector.h */,
-				DE66F1EE08ABF03100323D32 /* DenseMap.h */,
-				DE66F1EF08ABF03100323D32 /* DepthFirstIterator.h */,
-				DE66F1F008ABF03100323D32 /* EquivalenceClasses.h */,
-				CF42B6BF0AF24F5300D5D47C /* FoldingSet.h */,
-				CF42B6BF0AF24F5300D5D47C /* FoldingSet.h */,
-				DE66F1F108ABF03100323D32 /* GraphTraits.h */,
-				DE66F1F308ABF03100323D32 /* hash_map.in */,
-				DE66F1F508ABF03100323D32 /* hash_set.in */,
-				DE66F1F608ABF03100323D32 /* HashExtras.h */,
-				DE66F1F708ABF03100323D32 /* ilist */,
-				9FA638E00C77B1AB007F12AE /* IndexedMap.h */,
-				9FE25D900CAB166D005383FC /* APFloat.h */,
-				9FA638DB0C77B1AB007F12AE /* APInt.h */,
-				9FA638DC0C77B1AB007F12AE /* APSInt.h */,
-				DE66F1F908ABF03100323D32 /* iterator.in */,
-				DE66F1FA08ABF03100323D32 /* PostOrderIterator.h */,
-				DE66F1FB08ABF03100323D32 /* SCCIterator.h */,
-				DE66F1FC08ABF03100323D32 /* SetOperations.h */,
-				DE66F1FD08ABF03100323D32 /* SetVector.h */,
-				9FA638E20C77B1AB007F12AE /* SmallPtrSet.h */,
-				9FA638E30C77B1AB007F12AE /* SmallSet.h */,
-				CF33BE160AF62B4200E93805 /* SmallString.h */,
-				CF71B60F0AC45EDA0007F57C /* SmallVector.h */,
-				9FE25D910CAB166D005383FC /* SparseBitVector.h */,
-				9FA638E40C77B1AB007F12AE /* StringMap.h */,
-				DE66F1FE08ABF03100323D32 /* Statistic.h */,
-				DE66F1FF08ABF03100323D32 /* STLExtras.h */,
-				DE66F20008ABF03100323D32 /* StringExtras.h */,
-				DE66F20108ABF03100323D32 /* Tree.h */,
-				CFF8B434097C605F0047F72A /* UniqueVector.h */,
-				DE66F20208ABF03100323D32 /* VectorExtras.h */,
-			);
-			path = ADT;
-			sourceTree = "";
-		};
-		DE66F20308ABF03100323D32 /* Analysis */ = {
-			isa = PBXGroup;
-			children = (
-				9FA638E50C77B203007F12AE /* LoopPass.h */,
-				9FA638E60C77B203007F12AE /* MemoryDependenceAnalysis.h */,
-				DE66F20408ABF03100323D32 /* AliasAnalysis.h */,
-				DE66F20508ABF03100323D32 /* AliasSetTracker.h */,
-				DE66F20608ABF03100323D32 /* CallGraph.h */,
-				DE66F20708ABF03100323D32 /* CFGPrinter.h */,
-				CF73C0A5098A507300627152 /* ConstantFolding.h */,
-				DE66F20808ABF03100323D32 /* ConstantsScanner.h */,
-				DE66F20F08ABF03100323D32 /* Dominators.h */,
-				DE66F21208ABF03100323D32 /* FindUsedTypes.h */,
-				DE66F21308ABF03100323D32 /* Interval.h */,
-				DE66F21408ABF03100323D32 /* IntervalIterator.h */,
-				DE66F21508ABF03100323D32 /* IntervalPartition.h */,
-				DE66F21608ABF03100323D32 /* LoadValueNumbering.h */,
-				DE66F21708ABF03100323D32 /* LoopInfo.h */,
-				DE66F21808ABF03100323D32 /* Passes.h */,
-				DE66F21908ABF03100323D32 /* PostDominators.h */,
-				DE66F21A08ABF03100323D32 /* ProfileInfo.h */,
-				DE66F21B08ABF03100323D32 /* ProfileInfoLoader.h */,
-				DE66F21C08ABF03100323D32 /* ProfileInfoTypes.h */,
-				DE66F21D08ABF03100323D32 /* ScalarEvolution.h */,
-				DE66F21E08ABF03100323D32 /* ScalarEvolutionExpander.h */,
-				DE66F21F08ABF03100323D32 /* ScalarEvolutionExpressions.h */,
-				DE66F22008ABF03100323D32 /* Trace.h */,
-				DE66F22108ABF03100323D32 /* ValueNumbering.h */,
-				DE66F22208ABF03100323D32 /* Verifier.h */,
-			);
-			path = Analysis;
-			sourceTree = "";
-		};
-		DE66F22408ABF03100323D32 /* Assembly */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F22508ABF03100323D32 /* AsmAnnotationWriter.h */,
-				DE66F22708ABF03100323D32 /* Parser.h */,
-				DE66F22808ABF03100323D32 /* PrintModulePass.h */,
-				DE66F22908ABF03100323D32 /* Writer.h */,
-			);
-			path = Assembly;
-			sourceTree = "";
-		};
-		DE66F23508ABF03100323D32 /* CodeGen */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F23608ABF03100323D32 /* AsmPrinter.h */,
-				9F7793860C73C57100551F9C /* CallingConvLower.h */,
-				DEFAB19D0959E9A100E0AB42 /* DwarfWriter.h */,
-				9F7793870C73C57100551F9C /* ELFRelocation.h */,
-				9F7793880C73C57100551F9C /* FileWriters.h */,
-				DE66F23908ABF03100323D32 /* IntrinsicLowering.h */,
-				CFD7E4F30A798FC3000C7379 /* LinkAllCodegenComponents.h */,
-				DE4DA03C091147920012D44B /* LiveInterval.h */,
-				DE4DA03D091147920012D44B /* LiveIntervalAnalysis.h */,
-				DE66F23A08ABF03100323D32 /* LiveVariables.h */,
-				DE66F23B08ABF03100323D32 /* MachineBasicBlock.h */,
-				DE66F23C08ABF03100323D32 /* MachineCodeEmitter.h */,
-				DE66F23D08ABF03100323D32 /* MachineConstantPool.h */,
-				CF6F487109505E1500BC9E82 /* MachineModuleInfo.h */,
-				DE66F23E08ABF03100323D32 /* MachineFrameInfo.h */,
-				DE66F23F08ABF03100323D32 /* MachineFunction.h */,
-				DE66F24008ABF03100323D32 /* MachineFunctionPass.h */,
-				DE66F24108ABF03100323D32 /* MachineInstr.h */,
-				DE66F24208ABF03100323D32 /* MachineInstrBuilder.h */,
-				CFE420FB0A66F67300AB4BF6 /* MachineJumpTableInfo.h */,
-				CF6527D909D1A53400C4B521 /* MachineLocation.h */,
-				CF4F27E60A7B6E23004359F6 /* MachinePassRegistry.h */,
-				DE66F24308ABF03100323D32 /* MachineRelocation.h */,
-				9F7793890C73C57100551F9C /* MachORelocation.h */,
-				DE66F24408ABF03100323D32 /* Passes.h */,
-				CFE21C780A80CC0600D3E908 /* RegAllocRegistry.h */,
-				9FE25D920CAB169F005383FC /* RegisterCoalescer.h */,
-				9F77938A0C73C57100551F9C /* RegisterScavenging.h */,
-				CF8F1B410B64F6D100BB4199 /* RuntimeLibcalls.h */,
-				DE66F24508ABF03100323D32 /* SchedGraphCommon.h */,
-				CF7FFA2109850864008B0087 /* ScheduleDAG.h */,
-				CFE21C7B0A80CC1C00D3E908 /* SchedulerRegistry.h */,
-				DE66F24608ABF03100323D32 /* SelectionDAG.h */,
-				DE66F24708ABF03100323D32 /* SelectionDAGISel.h */,
-				DE66F24808ABF03100323D32 /* SelectionDAGNodes.h */,
-				DE66F24B08ABF03100323D32 /* ValueTypes.h */,
-				CFE420FC0A66F67300AB4BF6 /* ValueTypes.td */,
-			);
-			path = CodeGen;
-			sourceTree = "";
-		};
-		DE66F24C08ABF03100323D32 /* Config */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F24E08ABF03100323D32 /* alloca.h */,
-				CF73C0A9098A50FD00627152 /* config.h */,
-				DE66F25008ABF03100323D32 /* config.h.in */,
-			);
-			path = Config;
-			sourceTree = "";
-		};
-		DE66F25308ABF03100323D32 /* Debugger */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F25408ABF03100323D32 /* Debugger.h */,
-				DE66F25508ABF03100323D32 /* InferiorProcess.h */,
-				DE66F25608ABF03100323D32 /* ProgramInfo.h */,
-				DE66F25708ABF03100323D32 /* RuntimeInfo.h */,
-				DE66F25808ABF03100323D32 /* SourceFile.h */,
-				DE66F25908ABF03100323D32 /* SourceLanguage.h */,
-			);
-			path = Debugger;
-			sourceTree = "";
-		};
-		DE66F25B08ABF03100323D32 /* ExecutionEngine */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F25C08ABF03100323D32 /* ExecutionEngine.h */,
-				DE66F25D08ABF03100323D32 /* GenericValue.h */,
-				CFE420FD0A66F67300AB4BF6 /* Interpreter.h */,
-				CFE420FE0A66F67300AB4BF6 /* JIT.h */,
-			);
-			path = ExecutionEngine;
-			sourceTree = "";
-		};
-		DE66F26E08ABF03200323D32 /* Support */ = {
-			isa = PBXGroup;
-			children = (
-				F27C8CE90DAD2EF900A33844 /* IRBuilder.h */,
-				DE66F27008ABF03200323D32 /* AIXDataTypesFix.h */,
-				9F5B90CE0D0CE89300CDFDEA /* AlignOf.h */,
-				CF8F1B430B64F74400BB4199 /* Allocator.h */,
-				DE66F27108ABF03200323D32 /* Annotation.h */,
-				DE66F27208ABF03200323D32 /* CallSite.h */,
-				DE66F27308ABF03200323D32 /* Casting.h */,
-				DE66F27408ABF03200323D32 /* CFG.h */,
-				DE66F27508ABF03200323D32 /* CommandLine.h */,
-				CF8F1B440B64F74400BB4199 /* Compiler.h */,
-				DE66F27708ABF03200323D32 /* ConstantRange.h */,
-				CF73C0AD098A519400627152 /* DataTypes.h */,
-				DE66F27908ABF03200323D32 /* DataTypes.h.in */,
-				DE66F27A08ABF03200323D32 /* Debug.h */,
-				DE66F27B08ABF03200323D32 /* DOTGraphTraits.h */,
-				DE66F27C08ABF03200323D32 /* DynamicLinker.h */,
-				DE66F27D08ABF03200323D32 /* ELF.h */,
-				CF8E00490989162500DA2399 /* Dwarf.h */,
-				DE66F27E08ABF03200323D32 /* FileUtilities.h */,
-				DE66F27F08ABF03200323D32 /* GetElementPtrTypeIterator.h */,
-				DE66F28008ABF03200323D32 /* GraphWriter.h */,
-				DE66F28108ABF03200323D32 /* InstIterator.h */,
-				DE66F28208ABF03200323D32 /* InstVisitor.h */,
-				DE66F28308ABF03200323D32 /* LeakDetector.h */,
-				CF8F1B460B64F74400BB4199 /* ManagedStatic.h */,
-				DE66F28408ABF03200323D32 /* Mangler.h */,
-				DE66F28508ABF03200323D32 /* MathExtras.h */,
-				9F7794880C73D51000551F9C /* MemoryBuffer.h */,
-				DE66F28608ABF03200323D32 /* MutexGuard.h */,
-				CF8F1B470B64F74400BB4199 /* OutputBuffer.h */,
-				DE66F28708ABF03200323D32 /* PassNameParser.h */,
-				DE66F28808ABF03200323D32 /* PatternMatch.h */,
-				DE66F28908ABF03200323D32 /* PluginLoader.h */,
-				9F5B90CF0D0CE89300CDFDEA /* Registry.h */,
-				DE66F28A08ABF03200323D32 /* SlowOperationInformer.h */,
-				DE66F28B08ABF03200323D32 /* StableBasicBlockNumbering.h */,
-				9F7794890C73D51000551F9C /* Streams.h */,
-				9F5B90D00D0CE89300CDFDEA /* StringPool.h */,
-				DE66F28C08ABF03200323D32 /* SystemUtils.h */,
-				DE66F28E08ABF03200323D32 /* Timer.h */,
-				DE66F29008ABF03200323D32 /* type_traits.h */,
-			);
-			path = Support;
-			sourceTree = "";
-		};
-		DE66F29408ABF03200323D32 /* System */ = {
-			isa = PBXGroup;
-			children = (
-				CF73C0AE098A51AD00627152 /* Alarm.h */,
-				9FA638E70C77B222007F12AE /* Disassembler.h */,
-				DE66F29508ABF03200323D32 /* DynamicLibrary.h */,
-				CF9720340A9F3A41002CEEDD /* IncludeFile.h */,
-				DE66F29608ABF03200323D32 /* LICENSE.TXT */,
-				DE66F29708ABF03200323D32 /* MappedFile.h */,
-				DE66F29808ABF03200323D32 /* Memory.h */,
-				DE66F29908ABF03200323D32 /* Mutex.h */,
-				DE66F29A08ABF03200323D32 /* Path.h */,
-				DE66F29B08ABF03200323D32 /* Process.h */,
-				DE66F29C08ABF03200323D32 /* Program.h */,
-				DE66F29D08ABF03200323D32 /* Signals.h */,
-				DE66F29E08ABF03200323D32 /* TimeValue.h */,
-			);
-			path = System;
-			sourceTree = "";
-		};
-		DE66F29F08ABF03200323D32 /* Target */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F2A008ABF03200323D32 /* TargetRegisterInfo.h */,
-				CF9BCD0808C74DE0001E7011 /* SubtargetFeature.h */,
-				CF47BD380AAF40BC00A8B13E /* TargetAsmInfo.h */,
-				DE66F2A108ABF03200323D32 /* TargetData.h */,
-				9FA638E80C77B231007F12AE /* TargetELFWriterInfo.h */,
-				DE66F2A208ABF03200323D32 /* TargetFrameInfo.h */,
-				DE66F2A308ABF03200323D32 /* TargetInstrInfo.h */,
-				CF26835B09178F5500C5F253 /* TargetInstrItineraries.h */,
-				DE66F2A408ABF03200323D32 /* TargetJITInfo.h */,
-				DE66F2A508ABF03200323D32 /* TargetLowering.h */,
-				DE66F2A608ABF03200323D32 /* TargetMachine.h */,
-				DE66F2A708ABF03200323D32 /* TargetMachineRegistry.h */,
-				8443EF210B66B62D00959964 /* TargetMachOWriterInfo.h */,
-				DE66F2A808ABF03200323D32 /* TargetOptions.h */,
-				DE66F2AA08ABF03200323D32 /* TargetSubtarget.h */,
-			);
-			path = Target;
-			sourceTree = "";
-		};
-		DE66F2AB08ABF03200323D32 /* Transforms */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F2AC08ABF03200323D32 /* Instrumentation.h */,
-				9FA638E90C77B252007F12AE /* IPO */,
-				DE66F2AD08ABF03200323D32 /* IPO.h */,
-				CF73C0AF098A51DD00627152 /* RSProfiling.h */,
-				DE66F2AF08ABF03200323D32 /* Scalar.h */,
-				DE66F2B008ABF03200323D32 /* Utils */,
-			);
-			path = Transforms;
-			sourceTree = "";
-		};
-		DE66F2B008ABF03200323D32 /* Utils */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F2B108ABF03200323D32 /* BasicBlockUtils.h */,
-				9FA638EB0C77B26B007F12AE /* BasicInliner.h */,
-				DE66F2B208ABF03200323D32 /* Cloning.h */,
-				DE66F2B308ABF03200323D32 /* FunctionUtils.h */,
-				9FA638EC0C77B26B007F12AE /* InlineCost.h */,
-				DE66F2B408ABF03200323D32 /* Local.h */,
-				DE66F2B508ABF03200323D32 /* PromoteMemToReg.h */,
-				DE66F2B608ABF03200323D32 /* UnifyFunctionExitNodes.h */,
-			);
-			path = Utils;
-			sourceTree = "";
-		};
-		DE66F2BD08ABF14400323D32 /* tools */ = {
-			isa = PBXGroup;
-			children = (
-				CFD99ADF0AFE878F0068D19C /* opt */,
-				DE66F2CB08ABF14400323D32 /* bugpoint */,
-				DE66F2F008ABF14400323D32 /* gccld */,
-				DE66F31E08ABF14400323D32 /* llvm-db */,
-				DE66F33B08ABF14400323D32 /* llvm-ld */,
-				DE66F36808ABF14500323D32 /* llvmc */,
-				CF8F1B5E0B64FADA00BB4199 /* llvm-upgrade */,
-				CF8F1B7E0B64FADA00BB4199 /* llvm2cpp */,
-				CFD99ADA0AFE87650068D19C /* lto.cpp */,
-				DE66F30008ABF14400323D32 /* llc.cpp */,
-				DE66F30708ABF14400323D32 /* lli.cpp */,
-				DE66F30E08ABF14400323D32 /* llvm-ar.cpp */,
-				DE66F31508ABF14400323D32 /* llvm-as.cpp */,
-				DE66F31C08ABF14400323D32 /* llvm-bcanalyzer.cpp */,
-				DE66F33208ABF14400323D32 /* llvm-dis.cpp */,
-				DE66F33908ABF14400323D32 /* llvm-extract.cpp */,
-				DE66F34A08ABF14400323D32 /* llvm-link.cpp */,
-				DE66F35108ABF14400323D32 /* llvm-nm.cpp */,
-				DE66F35808ABF14500323D32 /* llvm-prof.cpp */,
-				DE66F35F08ABF14500323D32 /* llvm-ranlib.cpp */,
-				CF8F1B960B64FB7F00BB4199 /* lto */,
-				CF8F1BAB0B64FB8000BB4199 /* opt */,
-			);
-			name = tools;
-			path = ../tools;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66F2CB08ABF14400323D32 /* bugpoint */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F2CC08ABF14400323D32 /* BugDriver.cpp */,
-				DE66F2CD08ABF14400323D32 /* BugDriver.h */,
-				DE66F2CE08ABF14400323D32 /* bugpoint.cpp */,
-				DE66F2CF08ABF14400323D32 /* CrashDebugger.cpp */,
-				DE66F2E208ABF14400323D32 /* ExecutionDriver.cpp */,
-				DE66F2E308ABF14400323D32 /* ExtractFunction.cpp */,
-				CF9720910A9F3CC7002CEEDD /* FindBugs.cpp */,
-				DE66F2E408ABF14400323D32 /* ListReducer.h */,
-				DE66F2E608ABF14400323D32 /* Miscompilation.cpp */,
-				DE66F2E708ABF14400323D32 /* OptimizerDriver.cpp */,
-				DE66F2E808ABF14400323D32 /* TestPasses.cpp */,
-				CF9720920A9F3CC7002CEEDD /* ToolRunner.cpp */,
-				CF9720930A9F3CC7002CEEDD /* ToolRunner.h */,
-			);
-			path = bugpoint;
-			sourceTree = "";
-		};
-		DE66F2F008ABF14400323D32 /* gccld */ = {
-			isa = PBXGroup;
-			children = (
-			);
-			path = gccld;
-			sourceTree = "";
-		};
-		DE66F31E08ABF14400323D32 /* llvm-db */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F31F08ABF14400323D32 /* CLICommand.h */,
-				DE66F32008ABF14400323D32 /* CLIDebugger.cpp */,
-				DE66F32108ABF14400323D32 /* CLIDebugger.h */,
-				DE66F32208ABF14400323D32 /* Commands.cpp */,
-				DE66F32B08ABF14400323D32 /* llvm-db.cpp */,
-			);
-			path = "llvm-db";
-			sourceTree = "";
-		};
-		DE66F33B08ABF14400323D32 /* llvm-ld */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F34208ABF14400323D32 /* llvm-ld.cpp */,
-				DE66F34408ABF14400323D32 /* Optimize.cpp */,
-			);
-			path = "llvm-ld";
-			sourceTree = "";
-		};
-		DE66F36808ABF14500323D32 /* llvmc */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F36908ABF14500323D32 /* c */,
-				DE66F36A08ABF14500323D32 /* CompilerDriver.cpp */,
-				DE66F36B08ABF14500323D32 /* CompilerDriver.h */,
-				CF8F1B950B64FB5000BB4199 /* ConfigLexer.cpp */,
-				DE66F36D08ABF14500323D32 /* ConfigLexer.h */,
-				DE66F36E08ABF14500323D32 /* ConfigLexer.l */,
-				DE66F36F08ABF14500323D32 /* Configuration.cpp */,
-				DE66F37008ABF14500323D32 /* Configuration.h */,
-				DE66F37108ABF14500323D32 /* cpp */,
-				DE66F37D08ABF14500323D32 /* ll */,
-				DE66F37E08ABF14500323D32 /* llvmc.cpp */,
-			);
-			path = llvmc;
-			sourceTree = "";
-		};
-		DE66F38D08ABF35C00323D32 /* docs */ = {
-			isa = PBXGroup;
-			children = (
-				F22627310DAE34D10008F441 /* tutorial */,
-				DE66F38F08ABF35C00323D32 /* AliasAnalysis.html */,
-				DE66F39008ABF35C00323D32 /* Bugpoint.html */,
-				DE66F39208ABF35C00323D32 /* GCCFEBuildInstrs.html */,
-				DE66F39308ABF35C00323D32 /* CodeGenerator.html */,
-				DE66F39408ABF35C00323D32 /* CodingStandards.html */,
-				DE66F39508ABF35C00323D32 /* CommandGuide */,
-				DE66F3B908ABF35D00323D32 /* CommandLine.html */,
-				DE66F3BA08ABF35D00323D32 /* CompilerDriver.html */,
-				DE66F3BB08ABF35D00323D32 /* CompilerWriterInfo.html */,
-				DE66F3BD08ABF35D00323D32 /* doxygen.cfg.in */,
-				DE66F3BE08ABF35D00323D32 /* doxygen.css */,
-				DE66F3BF08ABF35D00323D32 /* doxygen.footer */,
-				DE66F3C008ABF35D00323D32 /* doxygen.header */,
-				DE66F3C108ABF35D00323D32 /* doxygen.intro */,
-				DE66F3C208ABF35D00323D32 /* ExtendingLLVM.html */,
-				DE66F3C308ABF35D00323D32 /* FAQ.html */,
-				DE66F3C408ABF35D00323D32 /* GarbageCollection.html */,
-				DE66F3C508ABF35D00323D32 /* GettingStarted.html */,
-				DE66F3C608ABF35D00323D32 /* GettingStartedVS.html */,
-				DE66F3E408ABF35D00323D32 /* HowToSubmitABug.html */,
-				DE66F3E508ABF35D00323D32 /* img */,
-				DE66F3EB08ABF35D00323D32 /* index.html */,
-				DE66F3EC08ABF35D00323D32 /* LangRef.html */,
-				DE66F3ED08ABF35D00323D32 /* Lexicon.html */,
-				DE66F3EE08ABF35D00323D32 /* llvm.css */,
-				DE66F3F108ABF35D00323D32 /* MakefileGuide.html */,
-				DE66F3F208ABF35D00323D32 /* ProgrammersManual.html */,
-				DE66F3F308ABF35D00323D32 /* Projects.html */,
-				DE66F3F408ABF35D00323D32 /* ReleaseNotes.html */,
-				DE66F3F508ABF35D00323D32 /* SourceLevelDebugging.html */,
-				DE66F3F708ABF35D00323D32 /* SystemLibrary.html */,
-				DE66F3F808ABF35D00323D32 /* TableGenFundamentals.html */,
-				DE66F3F908ABF35D00323D32 /* TestingGuide.html */,
-				DE66F3FA08ABF35D00323D32 /* UsingLibraries.html */,
-				DE66F3FB08ABF35D00323D32 /* WritingAnLLVMBackend.html */,
-				DE66F3FC08ABF35D00323D32 /* WritingAnLLVMPass.html */,
-			);
-			name = docs;
-			path = ../docs;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE66F39508ABF35C00323D32 /* CommandGuide */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F39808ABF35C00323D32 /* bugpoint.pod */,
-				DE66F39E08ABF35C00323D32 /* index.html */,
-				DE66F39F08ABF35C00323D32 /* llc.pod */,
-				DE66F3A008ABF35C00323D32 /* lli.pod */,
-				DE66F3A108ABF35C00323D32 /* llvm-ar.pod */,
-				DE66F3A208ABF35C00323D32 /* llvm-as.pod */,
-				DE66F3A308ABF35C00323D32 /* llvm-bcanalyzer.pod */,
-				DE66F3A408ABF35C00323D32 /* llvm-db.pod */,
-				DE66F3A508ABF35C00323D32 /* llvm-dis.pod */,
-				DE66F3A608ABF35C00323D32 /* llvm-extract.pod */,
-				DE66F3A708ABF35C00323D32 /* llvm-ld.pod */,
-				DE66F3A808ABF35C00323D32 /* llvm-link.pod */,
-				DE66F3A908ABF35C00323D32 /* llvm-nm.pod */,
-				DE66F3AA08ABF35C00323D32 /* llvm-prof.pod */,
-				DE66F3AB08ABF35C00323D32 /* llvm-ranlib.pod */,
-				DE66F3AC08ABF35C00323D32 /* llvmc.pod */,
-				DE66F3AD08ABF35C00323D32 /* llvmgcc.pod */,
-				DE66F3AE08ABF35C00323D32 /* llvmgxx.pod */,
-				DE66F3AF08ABF35C00323D32 /* Makefile */,
-				DE66F3B408ABF35D00323D32 /* manpage.css */,
-				DE66F3B508ABF35D00323D32 /* opt.pod */,
-				DE66F3B808ABF35D00323D32 /* stkrc.pod */,
-			);
-			path = CommandGuide;
-			sourceTree = "";
-		};
-		DE66F3E508ABF35D00323D32 /* img */ = {
-			isa = PBXGroup;
-			children = (
-				DE66F3E608ABF35D00323D32 /* Debugging.gif */,
-				DE66F3E708ABF35D00323D32 /* libdeps.gif */,
-				DE66F3E808ABF35D00323D32 /* lines.gif */,
-				DE66F3E908ABF35D00323D32 /* objdeps.gif */,
-				DE66F3EA08ABF35D00323D32 /* venusflytrap.jpg */,
-			);
-			path = img;
-			sourceTree = "";
-		};
-		DE66F3FD08ABF37000323D32 /* examples */ = {
-			isa = PBXGroup;
-			children = (
-				F22761DF0DAD09CD003D8065 /* BrainF.cpp */,
-				F22761E00DAD09CD003D8065 /* BrainF.h */,
-				F22761E10DAD09CD003D8065 /* BrainFDriver.cpp */,
-				DE66F40E08ABF37000323D32 /* fibonacci.cpp */,
-				DE66F41508ABF37000323D32 /* HowToUseJIT.cpp */,
-				DE66F41E08ABF37000323D32 /* ModuleMaker.cpp */,
-				DE66F42608ABF37000323D32 /* ParallelJIT.cpp */,
-			);
-			name = examples;
-			path = ../examples;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE816FAC08CFB44C0093BDEF /* utils */ = {
-			isa = PBXGroup;
-			children = (
-				DE81705708CFB44D0093BDEF /* TableGen */,
-				DE81704008CFB44D0093BDEF /* fpcmp.cpp */,
-				DE81704F08CFB44D0093BDEF /* NightlyTest.gnuplot */,
-				DE81705108CFB44D0093BDEF /* NightlyTestTemplate.html */,
-			);
-			name = utils;
-			path = ../utils;
-			sourceTree = SOURCE_ROOT;
-		};
-		DE81705708CFB44D0093BDEF /* TableGen */ = {
-			isa = PBXGroup;
-			children = (
-				DE81705908CFB44D0093BDEF /* AsmWriterEmitter.cpp */,
-				DE81705A08CFB44D0093BDEF /* AsmWriterEmitter.h */,
-				DE81705B08CFB44D0093BDEF /* CodeEmitterGen.cpp */,
-				DE81705C08CFB44D0093BDEF /* CodeEmitterGen.h */,
-				DE81705D08CFB44D0093BDEF /* CodeGenInstruction.h */,
-				CF8F1BC90B64FBD500BB4199 /* CodeGenIntrinsics.h */,
-				DE81705E08CFB44D0093BDEF /* CodeGenRegisters.h */,
-				DE81705F08CFB44D0093BDEF /* CodeGenTarget.cpp */,
-				DE81706008CFB44D0093BDEF /* CodeGenTarget.h */,
-				DE81706708CFB44D0093BDEF /* DAGISelEmitter.cpp */,
-				DE81706808CFB44D0093BDEF /* DAGISelEmitter.h */,
-				CF9720970A9F3D4D002CEEDD /* IntrinsicEmitter.cpp */,
-				CF9720980A9F3D4D002CEEDD /* IntrinsicEmitter.h */,
-				DE81708908CFB44D0093BDEF /* InstrInfoEmitter.cpp */,
-				DE81708A08CFB44D0093BDEF /* InstrInfoEmitter.h */,
-				DE81708E08CFB44D0093BDEF /* Record.cpp */,
-				DE81708F08CFB44D0093BDEF /* Record.h */,
-				DE81709008CFB44D0093BDEF /* RegisterInfoEmitter.cpp */,
-				DE81709108CFB44D0093BDEF /* RegisterInfoEmitter.h */,
-				DE4DA065091148520012D44B /* SubtargetEmitter.cpp */,
-				DE4DA066091148520012D44B /* SubtargetEmitter.h */,
-				DE8170AA08CFB44D0093BDEF /* TableGen.cpp */,
-				DE8170AB08CFB44D0093BDEF /* TableGenBackend.cpp */,
-				DE8170AC08CFB44D0093BDEF /* TableGenBackend.h */,
-				CF490E300907BBF80072DB1C /* SubtargetEmitter.cpp */,
-				CF490E2F0907BBF80072DB1C /* SubtargetEmitter.h */,
-			);
-			path = TableGen;
-			sourceTree = "";
-		};
-		F22627310DAE34D10008F441 /* tutorial */ = {
-			isa = PBXGroup;
-			children = (
-				F22627320DAE34D10008F441 /* index.html */,
-				F22627330DAE34D20008F441 /* JITTutorial1.html */,
-				F22627340DAE34D20008F441 /* JITTutorial2-1.png */,
-				F22627350DAE34D20008F441 /* JITTutorial2.html */,
-				F22627360DAE34D20008F441 /* LangImpl1.html */,
-				F22627370DAE34D20008F441 /* LangImpl2.html */,
-				F22627380DAE34D20008F441 /* LangImpl3.html */,
-				F22627390DAE34D20008F441 /* LangImpl4.html */,
-				F226273A0DAE34D20008F441 /* LangImpl5-cfg.png */,
-				F226273B0DAE34D20008F441 /* LangImpl5.html */,
-				F226273C0DAE34D20008F441 /* LangImpl6.html */,
-				F226273D0DAE34D20008F441 /* LangImpl7.html */,
-				F226273E0DAE34D20008F441 /* LangImpl8.html */,
-				F226273F0DAE34D20008F441 /* Makefile */,
-				F22627400DAE34D20008F441 /* OCamlLangImpl1.html */,
-				F22627410DAE34D20008F441 /* OCamlLangImpl2.html */,
-				F22627420DAE34D20008F441 /* OCamlLangImpl3.html */,
-				F22627430DAE34D20008F441 /* OCamlLangImpl4.html */,
-				F22627440DAE34D20008F441 /* OCamlLangImpl5.html */,
-				F22627450DAE34D20008F441 /* OCamlLangImpl6.html */,
-				F22627460DAE34D20008F441 /* OCamlLangImpl7.html */,
-			);
-			path = tutorial;
-			sourceTree = "";
-		};
-/* End PBXGroup section */
-
-/* Begin PBXLegacyTarget section */
-		CF0329B608D1BE110030FD33 /* LLVM lib */ = {
-			isa = PBXLegacyTarget;
-			buildArgumentsString = "$(ACTION) -j 2";
-			buildConfigurationList = CF0329B708D1BE530030FD33 /* Build configuration list for PBXLegacyTarget "LLVM lib" */;
-			buildPhases = (
-			);
-			buildToolPath = /usr/bin/make;
-			buildWorkingDirectory = "$(SRCROOT)/../lib";
-			dependencies = (
-			);
-			name = "LLVM lib";
-			passBuildSettingsInEnvironment = 0;
-			productName = "LLVM lib";
-		};
-		CF0329BB08D1BE5D0030FD33 /* LLVM llc */ = {
-			isa = PBXLegacyTarget;
-			buildArgumentsString = "$(ACTION) -j 2";
-			buildConfigurationList = CF0329C308D1BEC40030FD33 /* Build configuration list for PBXLegacyTarget "LLVM llc" */;
-			buildPhases = (
-			);
-			buildToolPath = /usr/bin/make;
-			buildWorkingDirectory = "$(SRCROOT)/../tools/llc";
-			dependencies = (
-			);
-			name = "LLVM llc";
-			passBuildSettingsInEnvironment = 0;
-			productName = "LLVM llc";
-		};
-		CF490E830907CDAB0072DB1C /* LLVM TableGen */ = {
-			isa = PBXLegacyTarget;
-			buildArgumentsString = "$(ACTION) -j 2";
-			buildConfigurationList = CF490E840907CDAB0072DB1C /* Build configuration list for PBXLegacyTarget "LLVM TableGen" */;
-			buildPhases = (
-			);
-			buildToolPath = /usr/bin/make;
-			buildWorkingDirectory = "${SRCROOT}/../utils/TableGen";
-			dependencies = (
-			);
-			name = "LLVM TableGen";
-			passBuildSettingsInEnvironment = 0;
-			productName = "LLVM llc";
-		};
-		CFDF86BD0ADE819D00D40A3D /* LLVM lib release */ = {
-			isa = PBXLegacyTarget;
-			buildArgumentsString = "$(ACTION) -j 2 ENABLE_OPTIMIZED=1 DISABLE_ASSERTIONS=1";
-			buildConfigurationList = CFDF86BE0ADE819D00D40A3D /* Build configuration list for PBXLegacyTarget "LLVM lib release" */;
-			buildPhases = (
-			);
-			buildToolPath = /usr/bin/make;
-			buildWorkingDirectory = "$(SRCROOT)/../lib";
-			dependencies = (
-			);
-			name = "LLVM lib release";
-			passBuildSettingsInEnvironment = 0;
-			productName = "LLVM lib";
-		};
-		CFDF86C60ADE81D000D40A3D /* LLVM llc release */ = {
-			isa = PBXLegacyTarget;
-			buildArgumentsString = "$(ACTION) -j 2 ENABLE_OPTIMIZED=1 DISABLE_ASSERTIONS=1";
-			buildConfigurationList = CFDF86C70ADE81D000D40A3D /* Build configuration list for PBXLegacyTarget "LLVM llc release" */;
-			buildPhases = (
-			);
-			buildToolPath = /usr/bin/make;
-			buildWorkingDirectory = "$(SRCROOT)/../tools/llc";
-			dependencies = (
-			);
-			name = "LLVM llc release";
-			passBuildSettingsInEnvironment = 0;
-			productName = "LLVM llc";
-		};
-		D28A88AD04BDD90700651E21 /* LLVM */ = {
-			isa = PBXLegacyTarget;
-			buildArgumentsString = "$(ACTION) -j 2";
-			buildConfigurationList = DE66EC4C08ABE78900323D32 /* Build configuration list for PBXLegacyTarget "LLVM" */;
-			buildPhases = (
-			);
-			buildToolPath = /usr/bin/make;
-			buildWorkingDirectory = "$(SRCROOT)/../";
-			dependencies = (
-			);
-			name = LLVM;
-			passBuildSettingsInEnvironment = 0;
-			productName = LLVM;
-		};
-/* End PBXLegacyTarget section */
-
-/* Begin PBXProject section */
-		08FB7793FE84155DC02AAC07 /* Project object */ = {
-			isa = PBXProject;
-			buildConfigurationList = DE66EC5008ABE78900323D32 /* Build configuration list for PBXProject "LLVM" */;
-			compatibilityVersion = "Xcode 2.4";
-			hasScannedForEncodings = 1;
-			mainGroup = 08FB7794FE84155DC02AAC07 /* LLVM */;
-			productRefGroup = 721CA1750D0B44D200D5004F /* Products */;
-			projectDirPath = "";
-			projectRoot = "";
-			targets = (
-				D28A88AD04BDD90700651E21 /* LLVM */,
-				CF0329B608D1BE110030FD33 /* LLVM lib */,
-				CF0329BB08D1BE5D0030FD33 /* LLVM llc */,
-				CF0329BC08D1BE8E0030FD33 /* LLVM full llc */,
-				CF490E830907CDAB0072DB1C /* LLVM TableGen */,
-				CFDF86BD0ADE819D00D40A3D /* LLVM lib release */,
-				CFDF86C60ADE81D000D40A3D /* LLVM llc release */,
-				CFDF86D00ADE820000D40A3D /* LLVM full llc release */,
-			);
-		};
-/* End PBXProject section */
-
-/* Begin PBXTargetDependency section */
-		CF0329BE08D1BE970030FD33 /* PBXTargetDependency */ = {
-			isa = PBXTargetDependency;
-			target = CF0329B608D1BE110030FD33 /* LLVM lib */;
-			targetProxy = CF0329BD08D1BE970030FD33 /* PBXContainerItemProxy */;
-		};
-		CF0329C008D1BE9B0030FD33 /* PBXTargetDependency */ = {
-			isa = PBXTargetDependency;
-			target = CF0329BB08D1BE5D0030FD33 /* LLVM llc */;
-			targetProxy = CF0329BF08D1BE9B0030FD33 /* PBXContainerItemProxy */;
-		};
-		CFDF86DA0ADE822100D40A3D /* PBXTargetDependency */ = {
-			isa = PBXTargetDependency;
-			target = CFDF86BD0ADE819D00D40A3D /* LLVM lib release */;
-			targetProxy = CFDF86D90ADE822100D40A3D /* PBXContainerItemProxy */;
-		};
-		CFDF86DC0ADE822100D40A3D /* PBXTargetDependency */ = {
-			isa = PBXTargetDependency;
-			target = CFDF86C60ADE81D000D40A3D /* LLVM llc release */;
-			targetProxy = CFDF86DB0ADE822100D40A3D /* PBXContainerItemProxy */;
-		};
-/* End PBXTargetDependency section */
-
-/* Begin XCBuildConfiguration section */
-		CF0329B808D1BE530030FD33 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM lib";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CF0329B908D1BE530030FD33 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM lib";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		CF0329C408D1BEC40030FD33 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CF0329C508D1BEC40030FD33 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		CF0329C808D1BEC40030FD33 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM full llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CF0329C908D1BEC40030FD33 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM full llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		CF490E850907CDAB0072DB1C /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM TableGen";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CF490E860907CDAB0072DB1C /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		CFDF86BF0ADE819D00D40A3D /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM lib";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CFDF86C00ADE819D00D40A3D /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM lib";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		CFDF86C80ADE81D000D40A3D /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CFDF86C90ADE81D000D40A3D /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		CFDF86D60ADE820000D40A3D /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM full llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Debug;
-		};
-		CFDF86D70ADE820000D40A3D /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				OTHER_REZFLAGS = "";
-				PRODUCT_NAME = "LLVM full llc";
-				SECTORDER_FLAGS = "";
-				WARNING_CFLAGS = (
-					"-Wmost",
-					"-Wno-four-char-constants",
-					"-Wno-unknown-pragmas",
-				);
-			};
-			name = Release;
-		};
-		DE66EC4D08ABE78900323D32 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				DEBUGGING_SYMBOLS = YES;
-				GCC_DYNAMIC_NO_PIC = NO;
-				GCC_ENABLE_FIX_AND_CONTINUE = YES;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
-				GCC_OPTIMIZATION_LEVEL = 0;
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				PRODUCT_NAME = LLVM;
-				ZERO_LINK = YES;
-			};
-			name = Debug;
-		};
-		DE66EC4E08ABE78900323D32 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				ENABLE_OPTIMIZED = 1;
-				GCC_ENABLE_FIX_AND_CONTINUE = NO;
-				OTHER_CFLAGS = "";
-				OTHER_LDFLAGS = "";
-				PRODUCT_NAME = LLVM;
-				ZERO_LINK = NO;
-			};
-			name = Release;
-		};
-		DE66EC5108ABE78900323D32 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				DEBUG_INFORMATION_FORMAT = dwarf;
-				GCC_OPTIMIZATION_LEVEL = 0;
-				USER_HEADER_SEARCH_PATHS = "../include/**";
-			};
-			name = Debug;
-		};
-		DE66EC5208ABE78900323D32 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				DEBUG_INFORMATION_FORMAT = dwarf;
-				USER_HEADER_SEARCH_PATHS = "../include/**";
-			};
-			name = Release;
-		};
-/* End XCBuildConfiguration section */
-
-/* Begin XCConfigurationList section */
-		CF0329B708D1BE530030FD33 /* Build configuration list for PBXLegacyTarget "LLVM lib" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CF0329B808D1BE530030FD33 /* Debug */,
-				CF0329B908D1BE530030FD33 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		CF0329C308D1BEC40030FD33 /* Build configuration list for PBXLegacyTarget "LLVM llc" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CF0329C408D1BEC40030FD33 /* Debug */,
-				CF0329C508D1BEC40030FD33 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		CF0329C708D1BEC40030FD33 /* Build configuration list for PBXAggregateTarget "LLVM full llc" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CF0329C808D1BEC40030FD33 /* Debug */,
-				CF0329C908D1BEC40030FD33 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		CF490E840907CDAB0072DB1C /* Build configuration list for PBXLegacyTarget "LLVM TableGen" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CF490E850907CDAB0072DB1C /* Debug */,
-				CF490E860907CDAB0072DB1C /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		CFDF86BE0ADE819D00D40A3D /* Build configuration list for PBXLegacyTarget "LLVM lib release" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CFDF86BF0ADE819D00D40A3D /* Debug */,
-				CFDF86C00ADE819D00D40A3D /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		CFDF86C70ADE81D000D40A3D /* Build configuration list for PBXLegacyTarget "LLVM llc release" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CFDF86C80ADE81D000D40A3D /* Debug */,
-				CFDF86C90ADE81D000D40A3D /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		CFDF86D50ADE820000D40A3D /* Build configuration list for PBXAggregateTarget "LLVM full llc release" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				CFDF86D60ADE820000D40A3D /* Debug */,
-				CFDF86D70ADE820000D40A3D /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		DE66EC4C08ABE78900323D32 /* Build configuration list for PBXLegacyTarget "LLVM" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				DE66EC4D08ABE78900323D32 /* Debug */,
-				DE66EC4E08ABE78900323D32 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-		DE66EC5008ABE78900323D32 /* Build configuration list for PBXProject "LLVM" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				DE66EC5108ABE78900323D32 /* Debug */,
-				DE66EC5208ABE78900323D32 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Debug;
-		};
-/* End XCConfigurationList section */
-	};
-	rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
-}
diff --git a/Xcode/README.txt b/Xcode/README.txt
deleted file mode 100644
index 614cd674726..00000000000
--- a/Xcode/README.txt
+++ /dev/null
@@ -1 +0,0 @@
-Xcode project files for LLVM, for Xcode 2.1
diff --git a/autoconf/m4/bison.m4 b/autoconf/m4/bison.m4
deleted file mode 100644
index 48b83cc4a61..00000000000
--- a/autoconf/m4/bison.m4
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Check for Bison. 
-#
-# This macro verifies that Bison is installed.  If successful, then
-# 1) YACC is set to bison -y (to emulate YACC calls)
-# 2) BISON is set to bison
-#
-AC_DEFUN([AC_PROG_BISON],
-[AC_CACHE_CHECK([],[llvm_cv_has_bison],[AC_PROG_YACC()])
-if test "$YACC" != "bison -y"; then
-  AC_SUBST(BISON,[])
-  AC_MSG_WARN([bison not found, can't rebuild grammars])
-else
-  AC_SUBST(BISON,[bison])
-fi])
diff --git a/autoconf/m4/cxx_bidi_iterator.m4 b/autoconf/m4/cxx_bidi_iterator.m4
deleted file mode 100644
index d7de85630b5..00000000000
--- a/autoconf/m4/cxx_bidi_iterator.m4
+++ /dev/null
@@ -1,22 +0,0 @@
-#
-# Check for bidirectional iterator extension.  This is modified from
-# http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_have_ext_hash_set.html
-#
-AC_DEFUN([AC_CXX_HAVE_BI_ITERATOR],
-[AC_CACHE_CHECK(whether the compiler has the bidirectional iterator,
-ac_cv_cxx_have_bi_iterator,
-[AC_REQUIRE([AC_CXX_NAMESPACES])
-  AC_LANG_PUSH([C++])
-  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include 
-#ifdef HAVE_NAMESPACES
-using namespace std;
-#endif]], [[bidirectional_iterator t; return 0;]])],[ac_cv_cxx_have_bi_iterator=yes],[ac_cv_cxx_have_bi_iterator=no])
-  AC_LANG_POP([C++])
-])
-if test "$ac_cv_cxx_have_bi_iterator" = yes
-then
-  AC_DEFINE(HAVE_BI_ITERATOR,1,[Have bi-directional iterator])
-else
-  AC_DEFINE(HAVE_BI_ITERATOR,0,[Does not have bi-directional iterator])
-fi
-])
diff --git a/autoconf/m4/cxx_fwd_iterator.m4 b/autoconf/m4/cxx_fwd_iterator.m4
deleted file mode 100644
index eb7660c7c25..00000000000
--- a/autoconf/m4/cxx_fwd_iterator.m4
+++ /dev/null
@@ -1,22 +0,0 @@
-# Check for forward iterator extension.  This is modified from
-# http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_have_ext_hash_set.html
-AC_DEFUN([AC_CXX_HAVE_FWD_ITERATOR],
-[AC_CACHE_CHECK(whether the compiler has forward iterators,
-ac_cv_cxx_have_fwd_iterator,
-[AC_REQUIRE([AC_CXX_NAMESPACES])
-  AC_LANG_PUSH([C++])
-  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include 
-#ifdef HAVE_NAMESPACES
-using namespace std;
-#endif]], [[forward_iterator t; return 0;]])],[ac_cv_cxx_have_fwd_iterator=yes],[ac_cv_cxx_have_fwd_iterator=no])
-  AC_LANG_POP([C++])
-])
-if test "$ac_cv_cxx_have_fwd_iterator" = yes
-then
-   AC_DEFINE(HAVE_FWD_ITERATOR,1,[Have forward iterator])
-else
-   AC_DEFINE(HAVE_FWD_ITERATOR,0,[Does not have forward iterator])
-fi
-])
-
-
diff --git a/autoconf/m4/cxx_namespaces.m4 b/autoconf/m4/cxx_namespaces.m4
deleted file mode 100644
index d8d650e4d44..00000000000
--- a/autoconf/m4/cxx_namespaces.m4
+++ /dev/null
@@ -1,19 +0,0 @@
-# Check for C++ namespace support.  This is from
-# http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_namespaces.html
-#
-AC_DEFUN([AC_CXX_NAMESPACES],
-[AC_CACHE_CHECK(whether the compiler implements namespaces,
-ac_cv_cxx_namespaces,
-[AC_LANG_PUSH([C++])
- AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
-   [[namespace Outer { namespace Inner { int i = 0; }}]],
-   [[using namespace Outer::Inner; return i;]])], 
-   ac_cv_cxx_namespaces=yes, 
-   ac_cv_cxx_namespaces=no)
- AC_LANG_POP([C++])
-])
-if test "$ac_cv_cxx_namespaces" = yes; then
-  AC_DEFINE(HAVE_NAMESPACES,,[define if the compiler implements namespaces])
-fi
-])
-
diff --git a/autoconf/m4/cxx_std_iterator.m4 b/autoconf/m4/cxx_std_iterator.m4
deleted file mode 100644
index 38a611764c7..00000000000
--- a/autoconf/m4/cxx_std_iterator.m4
+++ /dev/null
@@ -1,26 +0,0 @@
-# Check for standard iterator extension.  This is modified from
-# http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_have_ext_hash_set.html
-AC_DEFUN([AC_CXX_HAVE_STD_ITERATOR],
-[AC_CACHE_CHECK(whether the compiler has the standard iterator,
-ac_cv_cxx_have_std_iterator,
-[AC_REQUIRE([AC_CXX_NAMESPACES])
-  AC_LANG_PUSH([C++])
-  AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
-    [[#include 
-#ifdef HAVE_NAMESPACES
-using namespace std;
-#endif]],
-  [[iterator t; return 0;]])],
-  ac_cv_cxx_have_std_iterator=yes, 
-  ac_cv_cxx_have_std_iterator=no)
-  AC_LANG_POP([C++])
-])
-if test "$ac_cv_cxx_have_std_iterator" = yes
-then
-   AC_DEFINE(HAVE_STD_ITERATOR,1,[Have std namespace iterator])
-else
-   AC_DEFINE(HAVE_STD_ITERATOR,0,[Does not have std namespace iterator])
-fi
-])
-
-
diff --git a/autoconf/m4/flex.m4 b/autoconf/m4/flex.m4
deleted file mode 100644
index 5cb3dc4f8fd..00000000000
--- a/autoconf/m4/flex.m4
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Check for FLEX.  
-#
-# This macro verifies that flex is installed.  If successful, then
-# 1) $LEX is set to "flex" (to emulate lex calls)
-# 2) BISON is set to bison
-AC_DEFUN([AC_PROG_FLEX],
-[AC_CACHE_CHECK(,
-ac_cv_has_flex,
-[AC_PROG_LEX()
-])
-if test "$LEX" != "flex"; then
-  AC_MSG_ERROR([flex not found but required])
-else
-  AC_SUBST(FLEX,[flex],[location of flex])
-fi
-])
diff --git a/docs/AdvancedGetElementPtr.html b/docs/AdvancedGetElementPtr.html
deleted file mode 100644
index 1d372786927..00000000000
--- a/docs/AdvancedGetElementPtr.html
+++ /dev/null
@@ -1,362 +0,0 @@
-
-
-
-  
-  The Revenge Of The Often Misunderstood GEP Instruction
-  
-  
-
-
-
-
- The Revenge Of The Often Misunderstood GEP Instruction -
- - - - -
-

GEP was mysterious and wily at first, but it turned out that the basic - workings were fairly comprehensible. However the dragon was merely subdued; - now it's back, and it has more fundamental complexity to confront. This - document seeks to uncover misunderstandings of the GEP operator that tend - to persist past initial confusion about the funky "extra 0" thing. Here we - show that the GEP instruction is really not quite as simple as it seems, - even after the initial confusion is overcome.

-
- - - -
-

It's very similar; there are only subtle differences.

- -

With ptrtoint, you have to pick an integer type. One approach is to pick i64; - this is safe on everything LLVM supports (LLVM internally assumes pointers - are never wider than 64 bits in many places), and the optimizer will actually - narrow the i64 arithmetic down to the actual pointer size on targets which - don't support 64-bit arithmetic in most cases. However, there are some cases - where it doesn't do this. With GEP you can avoid this problem. - -

Also, GEP carries additional pointer aliasing rules. It's invalid to take a - GEP from one object, address into a different separately allocated - object, and dereference it. IR producers (front-ends) must follow this rule, - and consumers (optimizers, specifically alias analysis) benefit from being - able to rely on it.

- -

And, GEP is more concise in common cases.

- -

However, for the underlying integer computation implied, there - is no difference.

- -
- - - -
-

You don't. The integer computation implied by a GEP is target-independent. - Typically what you'll need to do is make your backend pattern-match - expressions trees involving ADD, MUL, etc., which are what GEP is lowered - into. This has the advantage of letting your code work correctly in more - cases.

- -

GEP does use target-dependent parameters for the size and layout of data - types, which targets can customize.

- -

If you require support for addressing units which are not 8 bits, you'll - need to fix a lot of code in the backend, with GEP lowering being only a - small piece of the overall picture.

- -
- - - -
-

The specific type i32 is probably just a historical artifact, however it's - wide enough for all practical purposes, so there's been no need to change it. - It doesn't necessarily imply i32 address arithmetic; it's just an identifier - which identifies a field in a struct. Requiring that all struct indices be - the same reduces the range of possibilities for cases where two GEPs are - effectively the same but have distinct operand types.

- -
- - - -
-

GEPs don't natively support VLAs. LLVM's type system is entirely static, - and GEP address computations are guided by an LLVM type.

- -

VLA indices can be implemented as linearized indices. For example, an - expression like X[a][b][c], must be effectively lowered into a form - like X[a*m+b*n+c], so that it appears to the GEP as a single-dimensional - array reference.

- -

This means if you want to write an analysis which understands array - indices and you want to support VLAs, your code will have to be - prepared to reverse-engineer the linearization. One way to solve this - problem is to use the ScalarEvolution library, which always presents - VLA and non-VLA indexing in the same manner.

- -
- - - -
-

There are two senses in which an array index can be out of bounds.

- -

First, there's the array type which comes from the (static) type of - the first operand to the GEP. Indices greater than the number of elements - in the corresponding static array type are valid. There is no problem with - out of bounds indices in this sense. Indexing into an array only depends - on the size of the array element, not the number of elements.

- -

A common example of how this is used is arrays where the size is not known. - It's common to use array types with zero length to represent these. The - fact that the static type says there are zero elements is irrelevant; it's - perfectly valid to compute arbitrary element indices, as the computation - only depends on the size of the array element, not the number of - elements. Note that zero-sized arrays are not a special case here.

- -

This sense is unconnected with inbounds keyword. The - inbounds keyword is designed to describe low-level pointer - arithmetic overflow conditions, rather than high-level array - indexing rules. - -

Analysis passes which wish to understand array indexing should not - assume that the static array type bounds are respected.

- -

The second sense of being out of bounds is computing an address that's - beyond the actual underlying allocated object.

- -

With the inbounds keyword, the result value of the GEP is - undefined if the address is outside the actual underlying allocated - object and not the address one-past-the-end.

- -

Without the inbounds keyword, there are no restrictions - on computing out-of-bounds addresses. Obviously, performing a load or - a store requires an address of allocated and sufficiently aligned - memory. But the GEP itself is only concerned with computing addresses.

- -
- - - -
-

Yes. This is basically a special case of array indices being out - of bounds.

- -
- - - -
-

Yes. If both addresses are within the same allocated object, or - one-past-the-end, you'll get the comparison result you expect. If either - is outside of it, integer arithmetic wrapping may occur, so the - comparison may not be meaningful.

- -
- - - -
-

Yes. There are no restrictions on bitcasting a pointer value to an arbitrary - pointer type. The types in a GEP serve only to define the parameters for the - underlying integer computation. They need not correspond with the actual - type of the underlying object.

- -

Furthermore, loads and stores don't have to use the same types as the type - of the underlying object. Types in this context serve only to specify - memory size and alignment. Beyond that there are merely a hint to the - optimizer indicating how the value will likely be used.

- -
- - - -
-

You can compute an address that way, but if you use GEP to do the add, - you can't use that pointer to actually access the object, unless the - object is managed outside of LLVM.

- -

The underlying integer computation is sufficiently defined; null has a - defined value -- zero -- and you can add whatever value you want to it.

- -

However, it's invalid to access (load from or store to) an LLVM-aware - object with such a pointer. This includes GlobalVariables, Allocas, and - objects pointed to by noalias pointers.

- -

If you really need this functionality, you can do the arithmetic with - explicit integer instructions, and use inttoptr to convert the result to - an address. Most of GEP's special aliasing rules do not apply to pointers - computed from ptrtoint, arithmetic, and inttoptr sequences.

- -
- - - -
-

As with arithmetic on null, You can use GEP to compute an address that - way, but you can't use that pointer to actually access the object if you - do, unless the object is managed outside of LLVM.

- -

Also as above, ptrtoint and inttoptr provide an alternative way to do this - which do not have this restriction.

- -
- - - -
-

You can't do type-based alias analysis using LLVM's built-in type system, - because LLVM has no restrictions on mixing types in addressing, loads or - stores.

- -

It would be possible to add special annotations to the IR, probably using - metadata, to describe a different type system (such as the C type system), - and do type-based aliasing on top of that. This is a much bigger - undertaking though.

- -
- - - - -
-

Some LLVM optimizers operate on GEPs by internally lowering them into - more primitive integer expressions, which allows them to be combined - with other integer expressions and/or split into multiple separate - integer expressions. If they've made non-trivial changes, translating - back into LLVM IR can involve reverse-engineering the structure of - the addressing in order to fit it into the static type of the original - first operand. It isn't always possibly to fully reconstruct this - structure; sometimes the underlying addressing doesn't correspond with - the static type at all. In such cases the optimizer instead will emit - a GEP with the base pointer casted to a simple address-unit pointer, - using the name "uglygep". This isn't pretty, but it's just as - valid, and it's sufficient to preserve the pointer aliasing guarantees - that GEP provides.

- -
- - - - -
-

Sort of. This hasn't always been forcefully disallowed, though it's - not recommended. It leads to awkward special cases in the optimizers. - In the future, it may be outright disallowed.

- -

Instead, you should cast your pointer types and use arrays instead of - vectors for addressing. Arrays have the same in-memory representation - as vectors, so the addressing is interchangeable.

- -
- - - - -
-

Unknown.

- -
- - - - -
-

If the GEP has the inbounds keyword, the result value is - undefined.

- -

Otherwise, the result value is the result from evaluating the implied - two's complement integer computation. However, since there's no - guarantee of where an object will be allocated in the address space, - such values have limited meaning.

- -
- - - - -
-

None, except that the address space qualifier on the first operand pointer - type always matches the address space qualifier on the result type.

- -
- - - - -
-

The design of GEP has the following goals, in rough unofficial - order of priority:

-
    -
  • Support C, C-like languages, and languages which can be - conceptually lowered into C (this covers a lot).
  • -
  • Support optimizations such as those that are common in - C compilers.
  • -
  • Provide a consistent method for computing addresses so that - address computations don't need to be a part of load and - store instructions in the IR.
  • -
  • Support non-C-like languages, to the extent that it doesn't - interfere with other goals.
  • -
  • Minimize target-specific information in the IR.
  • -
-
- - - -
-
- Valid CSS - Valid HTML 4.01 - The LLVM Compiler Infrastructure
- Last modified: $Date: 2010-02-18 19:40:29 +0100 (Thu, 18 Feb 2010) $ -
- - - diff --git a/docs/CommandGuide/llvm-db.pod b/docs/CommandGuide/llvm-db.pod deleted file mode 100644 index 132417685c2..00000000000 --- a/docs/CommandGuide/llvm-db.pod +++ /dev/null @@ -1,16 +0,0 @@ -=pod - -=head1 NAME - -llvm-db - LLVM debugger (alpha) - -=head1 SYNOPSIS - -Details coming soon. Please see -L in the meantime. - -=head1 AUTHORS - -Maintained by the LLVM Team (L). - -=cut diff --git a/docs/ReleaseNotes-2.6.html b/docs/ReleaseNotes-2.6.html deleted file mode 100644 index 64084cd4f55..00000000000 --- a/docs/ReleaseNotes-2.6.html +++ /dev/null @@ -1,784 +0,0 @@ - - - - - - LLVM 2.6 Release Notes - - - -
LLVM 2.6 Release Notes
- -
    -
  1. Introduction
  2. -
  3. Sub-project Status Update
  4. -
  5. External Projects Using LLVM 2.6
  6. -
  7. What's New in LLVM 2.6?
  8. -
  9. Installation Instructions
  10. -
  11. Portability and Supported Platforms
  12. -
  13. Known Problems
  14. -
  15. Additional Information
  16. -
- -
-

Written by the LLVM Team

-
- - - - - -
- -

This document contains the release notes for the LLVM Compiler -Infrastructure, release 2.6. Here we describe the status of LLVM, including -major improvements from the previous release and significant known problems. -All LLVM releases may be downloaded from the LLVM releases web site.

- -

For more information about LLVM, including information about the latest -release, please check out the main LLVM -web site. If you have questions or comments, the LLVM Developer's Mailing -List is a good place to send them.

- -

Note that if you are reading this file from a Subversion checkout or the -main LLVM web page, this document applies to the next release, not the -current one. To see the release notes for a specific release, please see the -releases page.

- -
- - - - - - - - - -
-

-The LLVM 2.6 distribution currently consists of code from the core LLVM -repository —which roughly includes the LLVM optimizers, code generators -and supporting tools — and the llvm-gcc repository. In addition to this -code, the LLVM Project includes other sub-projects that are in development. The -two which are the most actively developed are the Clang -Project and the VMKit Project. -

- -
- - - - - -
- -

The Clang project is an effort to build -a set of new 'LLVM native' front-end technologies for the LLVM optimizer and -code generator. While Clang is not included in the LLVM 2.6 release, it is -continuing to make major strides forward in all areas. Its C and Objective-C -parsing and code generation support is now very solid. For example, it is -capable of successfully building many real-world applications for X86-32 -and X86-64, -including the FreeBSD -kernel and gcc 4.2. C++ is also -making incredible progress, -and work on templates has recently started. If you are -interested in fast compiles and good diagnostics, we encourage you to try it out -by building from mainline -and reporting any issues you hit to the Clang front-end mailing -list.

- -

In the LLVM 2.6 time-frame, the Clang team has made many improvements:

- -
    -
  • Something wonderful!
  • -
  • Many many bugs are fixed and many features have been added.
  • -
-
- - - - -
- -

Previously announced in the 2.4 LLVM release, the Clang project also -includes an early stage static source code analysis tool for automatically finding bugs -in C and Objective-C programs. The tool performs a growing set of checks to find -bugs that occur on a specific path within a program.

- -

In the LLVM 2.6 time-frame there have been many significant improvements to -XYZ.

- -

The set of checks performed by the static analyzer continues to expand, and -future plans for the tool include full source-level inter-procedural analysis -and deeper checks such as buffer overrun detection. There are many opportunities -to extend and enhance the static analyzer, and anyone interested in working on -this project is encouraged to get involved!

- -
- - - - -
-

-The VMKit project is an implementation of -a JVM and a CLI Virtual Machines (Microsoft .NET is an -implementation of the CLI) using the Just-In-Time compiler of LLVM.

- -

Following LLVM 2.6, VMKit has its XYZ release that you can find on its -webpage. The release includes -bug fixes, cleanup and new features. The major changes are:

- -
    - -
  • Something wonderful!
  • - -
-
- - - - - - -
-Pure -
- -
-

-Pure -is an algebraic/functional programming language based on term rewriting. -Programs are collections of equations which are used to evaluate expressions in -a symbolic fashion. Pure offers dynamic typing, eager and lazy evaluation, -lexical closures, a hygienic macro system (also based on term rewriting), -built-in list and matrix support (including list and matrix comprehensions) and -an easy-to-use C interface. The interpreter uses LLVM as a backend to - JIT-compile Pure programs to fast native code.

- -

In addition to the usual algebraic data structures, Pure also has -MATLAB-style matrices in order to support numeric computations and signal -processing in an efficient way. Pure is mainly aimed at mathematical -applications right now, but it has been designed as a general purpose language. -The dynamic interpreter environment and the C interface make it possible to use -it as a kind of functional scripting language for many application areas. -

-
- - - - - -
-

-LDC is an implementation of -the D Programming Language using the LLVM optimizer and code generator. -The LDC project works great with the LLVM 2.6 release. General improvements in -this -cycle have included new inline asm constraint handling, better debug info -support, general bugfixes, and better x86-64 support. This has allowed -some major improvements in LDC, getting us much closer to being as -fully featured as the original DMD compiler from DigitalMars. -

-
- - - - -
-

Roadsend PHP (rphp) is an open -source implementation of the PHP programming -language that uses LLVM for its optimizer, JIT, and static compiler. This is a -reimplementation of an earlier project that is now based on LLVM.

-
- - - - -
-

Unladen Swallow is a -branch of Python intended to be fully -compatible and significantly faster. It uses LLVM's optimization passes and JIT -compiler.

-
- - - - -
-

Rubinius is a new virtual -machine for Ruby. It leverages LLVM to dynamically compile Ruby code down to -machine code using LLVM's JIT.

-
- - - - - - -
- -

This release includes a huge number of bug fixes, performance tweaks, and -minor improvements. Some of the major improvements and new features are listed -in this section. -

-
- - - - -
- -

LLVM 2.6 includes several major new capabilities:

- -
    -
  • Something wonderful!
  • -
- -
- - - - - -
- -

LLVM fully supports the llvm-gcc 4.2 front-end, which marries the GCC -front-ends and driver with the LLVM optimizer and code generator. It currently -includes support for the C, C++, Objective-C, Ada, and Fortran front-ends.

- -
    -
  • Something wonderful!
  • -
- -
- - - - - -
-

LLVM IR has several new features that are used by our existing front-ends and -can be useful if you are writing a front-end for LLVM:

- -
    -
  • Something wonderful!
  • -
- -
- - - - -
- -

In addition to a large array of bug fixes and minor performance tweaks, this -release includes a few major enhancements and additions to the optimizers:

- -
    - -
  • Something wonderful!
  • - -
- -
- - - - -
- -

We have put a significant amount of work into the code generator -infrastructure, which allows us to implement more aggressive algorithms and make -it run faster:

- -
    - -
  • Something wonderful!
  • -
-
- - - - -
-

New features of the X86 target include: -

- -
    - -
  • Something wonderful!
  • -
- -
- - - - -
-

New features of the PIC16 target include: -

- -
    -
  • Something wonderful!
  • -
- -

Things not yet supported:

- -
    -
  • Floating point.
  • -
  • Passing/returning aggregate types to and from functions.
  • -
  • Variable arguments.
  • -
  • Indirect function calls.
  • -
  • Interrupts/programs.
  • -
  • Debug info.
  • -
- -
- - - - - -
-

New features include:

- -
    -
  • Something wonderful!
  • -
- -
- - - - - -
- -

If you're already an LLVM user or developer with out-of-tree changes based -on LLVM 2.5, this section lists some "gotchas" that you may run into upgrading -from the previous release.

- -
    - -
  • Something horrible!
  • - -
- - -

In addition, many APIs have changed in this release. Some of the major LLVM -API changes are:

- -
    -
  • LLVM's global uniquing tables for Types and Constants have - been privatized into members of an LLVMContext. A number of APIs - now take an LLVMContext as a parameter. To smooth the transition - for clients that will only ever use a single context, the new - getGlobalContext() API can be used to access a default global - context which can be passed in any and all cases where a context is - required. -
  • The getABITypeSize methods are now called getAllocSize.
  • -
- -
- - - - - - - -
- -

LLVM is known to work on the following platforms:

- -
    -
  • Intel and AMD machines (IA32, X86-64, AMD64, EMT-64) running Red Hat -Linux, Fedora Core and FreeBSD (and probably other unix-like systems).
  • -
  • PowerPC and X86-based Mac OS X systems, running 10.3 and above in 32-bit -and 64-bit modes.
  • -
  • Intel and AMD machines running on Win32 using MinGW libraries (native).
  • -
  • Intel and AMD machines running on Win32 with the Cygwin libraries (limited - support is available for native builds with Visual C++).
  • -
  • Sun UltraSPARC workstations running Solaris 10.
  • -
  • Alpha-based machines running Debian GNU/Linux.
  • -
  • Itanium-based (IA64) machines running Linux and HP-UX.
  • -
- -

The core LLVM infrastructure uses GNU autoconf to adapt itself -to the machine and operating system on which it is built. However, minor -porting may be required to get LLVM to work on new platforms. We welcome your -portability patches and reports of successful builds or error messages.

- -
- - - - - -
- -

This section contains significant known problems with the LLVM system, -listed by component. If you run into a problem, please check the LLVM bug database and submit a bug if -there isn't already one.

- -
- - - - -
- -

The following components of this LLVM release are either untested, known to -be broken or unreliable, or are in early development. These components should -not be relied on, and bugs should not be filed against them, but they may be -useful to some people. In particular, if you would like to work on one of these -components, please contact us on the LLVMdev list.

- -
    -
  • The MSIL, IA64, Alpha, SPU, MIPS, and PIC16 backends are experimental.
  • -
  • The llc "-filetype=asm" (the default) is the only - supported value for this option.
  • -
- -
- - - - -
- -
    -
  • The X86 backend does not yet support - all inline assembly that uses the X86 - floating point stack. It supports the 'f' and 't' constraints, but not - 'u'.
  • -
  • The X86 backend generates inefficient floating point code when configured - to generate code for systems that don't have SSE2.
  • -
  • Win64 code generation wasn't widely tested. Everything should work, but we - expect small issues to happen. Also, llvm-gcc cannot build the mingw64 - runtime currently due - to several - bugs and due to lack of support for - the - 'u' inline assembly constraint and for X87 floating point inline assembly.
  • -
  • The X86-64 backend does not yet support the LLVM IR instruction - va_arg. Currently, the llvm-gcc and front-ends support variadic - argument constructs on X86-64 by lowering them manually.
  • -
- -
- - - - -
- -
    -
  • The Linux PPC32/ABI support needs testing for the interpreter and static -compilation, and lacks support for debug information.
  • -
- -
- - - - -
- -
    -
  • Thumb mode works only on ARMv6 or higher processors. On sub-ARMv6 -processors, thumb programs can crash or produce wrong -results (PR1388).
  • -
  • Compilation for ARM Linux OABI (old ABI) is supported but not fully tested. -
  • -
  • There is a bug in QEMU-ARM (<= 0.9.0) which causes it to incorrectly - execute -programs compiled with LLVM. Please use more recent versions of QEMU.
  • -
- -
- - - - -
- -
    -
  • The SPARC backend only supports the 32-bit SPARC ABI (-m32); it does not - support the 64-bit SPARC ABI (-m64).
  • -
- -
- - - - -
- -
    -
  • The O32 ABI is not fully supported.
  • -
  • 64-bit MIPS targets are not supported yet.
  • -
- -
- - - - -
- -
    - -
  • On 21164s, some rare FP arithmetic sequences which may trap do not have the -appropriate nops inserted to ensure restartability.
  • - -
-
- - - - -
- -
    -
  • The Itanium backend is highly experimental and has a number of known - issues. We are looking for a maintainer for the Itanium backend. If you - are interested, please contact the LLVMdev mailing list.
  • -
- -
- - - - -
- - - -
- - - - - -
- -

llvm-gcc does not currently support Link-Time -Optimization on most platforms "out-of-the-box". Please inquire on the -LLVMdev mailing list if you are interested.

- -

The only major language feature of GCC not supported by llvm-gcc is - the __builtin_apply family of builtins. However, some extensions - are only supported on some targets. For example, trampolines are only - supported on some targets (these are used when you take the address of a - nested function).

- -

If you run into GCC extensions which are not supported, please let us know. -

- -
- - - - -
- -

The C++ front-end is considered to be fully -tested and works for a number of non-trivial programs, including LLVM -itself, Qt, Mozilla, etc.

- -
    -
  • Exception handling works well on the X86 and PowerPC targets. Currently - only Linux and Darwin targets are supported (both 32 and 64 bit).
  • -
- -
- - - - -
-
    -
  • Fortran support generally works, but there are still several unresolved bugs - in Bugzilla. Please see the tools/gfortran component for details.
  • -
-
- - - - -
-The llvm-gcc 4.2 Ada compiler works fairly well; however, this is not a mature -technology, and problems should be expected. -
    -
  • The Ada front-end currently only builds on X86-32. This is mainly due -to lack of trampoline support (pointers to nested functions) on other platforms. -However, it also fails to build on X86-64 -which does support trampolines.
  • -
  • The Ada front-end fails to bootstrap. -This is due to lack of LLVM support for setjmp/longjmp style -exception handling, which is used internally by the compiler. -Workaround: configure with --disable-bootstrap.
  • -
  • The c380004, c393010 -and cxg2021 ACATS tests fail -(c380004 also fails with gcc-4.2 mainline). -If the compiler is built with checks disabled then c393010 -causes the compiler to go into an infinite loop, using up all system memory.
  • -
  • Some GCC specific Ada tests continue to crash the compiler.
  • -
  • The -E binder option (exception backtraces) -does not work and will result in programs -crashing if an exception is raised. Workaround: do not use -E.
  • -
  • Only discrete types are allowed to start -or finish at a non-byte offset in a record. Workaround: do not pack records -or use representation clauses that result in a field of a non-discrete type -starting or finishing in the middle of a byte.
  • -
  • The lli interpreter considers -'main' as generated by the Ada binder to be invalid. -Workaround: hand edit the file to use pointers for argv and -envp rather than integers.
  • -
  • The -fstack-check option is -ignored.
  • -
-
- - - - - -
- -

A wide variety of additional information is available on the LLVM web page, in particular in the documentation section. The web page also -contains versions of the API documentation which is up-to-date with the -Subversion version of the source code. -You can access versions of these documents specific to this release by going -into the "llvm/doc/" directory in the LLVM tree.

- -

If you have any questions or comments about LLVM, please feel free to contact -us via the mailing -lists.

- -
- - - -
-
- Valid CSS - Valid HTML 4.01 - - LLVM Compiler Infrastructure
- Last modified: $Date: 2009-07-02 18:48:38 +0200 (Thu, 02 Jul 2009) $ -
- - - diff --git a/docs/tutorial/JITTutorial1.html b/docs/tutorial/JITTutorial1.html deleted file mode 100644 index 3b7b8dea1ac..00000000000 --- a/docs/tutorial/JITTutorial1.html +++ /dev/null @@ -1,207 +0,0 @@ - - - - - LLVM Tutorial 1: A First Function - - - - - - - - -
LLVM Tutorial 1: A First Function
- -
-

Written by Owen Anderson

-
- - - - - -
- -

For starters, let's consider a relatively straightforward function that takes three integer parameters and returns an arithmetic combination of them. This is nice and simple, especially since it involves no control flow:

- -
-
-int mul_add(int x, int y, int z) {
-  return x * y + z;
-}
-
-
- -

As a preview, the LLVM IR we’re going to end up generating for this function will look like:

- -
-
-define i32 @mul_add(i32 %x, i32 %y, i32 %z) {
-entry:
-  %tmp = mul i32 %x, %y
-  %tmp2 = add i32 %tmp, %z
-  ret i32 %tmp2
-}
-
-
- -

If you're unsure what the above code says, skim through the LLVM Language Reference Manual and convince yourself that the above LLVM IR is actually equivalent to the original function. Once you’re satisfied with that, let's move on to actually generating it programmatically!

- -

Of course, before we can start, we need to #include the appropriate LLVM header files:

- -
-
-#include "llvm/Module.h"
-#include "llvm/Function.h"
-#include "llvm/PassManager.h"
-#include "llvm/CallingConv.h"
-#include "llvm/Analysis/Verifier.h"
-#include "llvm/Assembly/PrintModulePass.h"
-#include "llvm/Support/IRBuilder.h"
-#include "llvm/Support/raw_ostream.h"
-
-
- -

Now, let's get started on our real program. Here's what our basic main() will look like:

- -
-
-using namespace llvm;
-
-Module* makeLLVMModule();
-
-int main(int argc, char**argv) {
-  Module* Mod = makeLLVMModule();
-
-  verifyModule(*Mod, PrintMessageAction);
-
-  PassManager PM;
-  PM.add(createPrintModulePass(&outs()));
-  PM.run(*Mod);
-
-  delete Mod;
-  return 0;
-}
-
-
- -

The first segment is pretty simple: it creates an LLVM “module.†In LLVM, a module represents a single unit of code that is to be processed together. A module contains things like global variables, function declarations, and implementations. Here we’ve declared a makeLLVMModule() function to do the real work of creating the module. Don’t worry, we’ll be looking at that one next!

- -

The second segment runs the LLVM module verifier on our newly created module. While this probably isn’t really necessary for a simple module like this one, it's always a good idea, especially if you’re generating LLVM IR based on some input. The verifier will print an error message if your LLVM module is malformed in any way.

- -

Finally, we instantiate an LLVM PassManager and run -the PrintModulePass on our module. LLVM uses an explicit pass -infrastructure to manage optimizations and various other things. -A PassManager, as should be obvious from its name, manages passes: -it is responsible for scheduling them, invoking them, and ensuring the proper -disposal after we’re done with them. For this example, we’re just using a -trivial pass that prints out our module in textual form.

- -

Now onto the interesting part: creating and populating a module. Here's the -first chunk of our makeLLVMModule():

- -
-
-Module* makeLLVMModule() {
-  // Module Construction
-  Module* mod = new Module("test", getGlobalContext());
-
-
- -

Exciting, isn’t it!? All we’re doing here is instantiating a module and giving it a name. The name isn’t particularly important unless you’re going to be dealing with multiple modules at once.

- -
-
-  Constant* c = mod->getOrInsertFunction("mul_add",
-  /*ret type*/                           IntegerType::get(32),
-  /*args*/                               IntegerType::get(32),
-                                         IntegerType::get(32),
-                                         IntegerType::get(32),
-  /*varargs terminated with null*/       NULL);
-  
-  Function* mul_add = cast<Function>(c);
-  mul_add->setCallingConv(CallingConv::C);
-
-
- -

We construct our Function by calling getOrInsertFunction() on our module, passing in the name, return type, and argument types of the function. In the case of our mul_add function, that means one 32-bit integer for the return value and three 32-bit integers for the arguments.

- -

You'll notice that getOrInsertFunction() doesn't actually return a Function*. This is because getOrInsertFunction() will return a cast of the existing function if the function already existed with a different prototype. Since we know that there's not already a mul_add function, we can safely just cast c to a Function*. - -

In addition, we set the calling convention for our new function to be the C -calling convention. This isn’t strictly necessary, but it ensures that our new -function will interoperate properly with C code, which is a good thing.

- -
-
-  Function::arg_iterator args = mul_add->arg_begin();
-  Value* x = args++;
-  x->setName("x");
-  Value* y = args++;
-  y->setName("y");
-  Value* z = args++;
-  z->setName("z");
-
-
- -

While we’re setting up our function, let's also give names to the parameters. This also isn’t strictly necessary (LLVM will generate names for them if you don’t specify them), but it’ll make looking at our output somewhat more pleasant. To name the parameters, we iterate over the arguments of our function and call setName() on them. We’ll also keep the pointer to x, y, and z around, since we’ll need them when we get around to creating instructions.

- -

Great! We have a function now. But what good is a function if it has no body? Before we start working on a body for our new function, we need to recall some details of the LLVM IR. The IR, being an abstract assembly language, represents control flow using jumps (we call them branches), both conditional and unconditional. The straight-line sequences of code between branches are called basic blocks, or just blocks. To create a body for our function, we fill it with blocks:

- -
-
-  BasicBlock* block = BasicBlock::Create(getGlobalContext(), "entry", mul_add);
-  IRBuilder<> builder(block);
-
-
- -

We create a new basic block, as you might expect, by calling its constructor. All we need to tell it is its name and the function to which it belongs. In addition, we’re creating an IRBuilder object, which is a convenience interface for creating instructions and appending them to the end of a block. Instructions can be created through their constructors as well, but some of their interfaces are quite complicated. Unless you need a lot of control, using IRBuilder will make your life simpler.

- -
-
-  Value* tmp = builder.CreateBinOp(Instruction::Mul,
-                                   x, y, "tmp");
-  Value* tmp2 = builder.CreateBinOp(Instruction::Add,
-                                    tmp, z, "tmp2");
-
-  builder.CreateRet(tmp2);
-  
-  return mod;
-}
-
-
- -

The final step in creating our function is to create the instructions that make it up. Our mul_add function is composed of just three instructions: a multiply, an add, and a return. IRBuilder gives us a simple interface for constructing these instructions and appending them to the “entry†block. Each of the calls to IRBuilder returns a Value* that represents the value yielded by the instruction. You’ll also notice that, above, x, y, and z are also Value*'s, so it's clear that instructions operate on Value*'s.

- -

And that's it! Now you can compile and run your code, and get a wonderful textual print out of the LLVM IR we saw at the beginning. To compile, use the following command line as a guide:

- -
-
-# c++ -g tut1.cpp `llvm-config --cxxflags --ldflags --libs core` -o tut1
-# ./tut1
-
-
- -

The llvm-config utility is used to obtain the necessary GCC-compatible compiler flags for linking with LLVM. For this example, we only need the 'core' library. We'll use others once we start adding optimizers and the JIT engine.

- -Next: A More Complicated Function -
- - -
-
- Valid CSS! - Valid HTML 4.01! - - Owen Anderson
- The LLVM Compiler Infrastructure
- Last modified: $Date: 2009-07-21 11:05:13 -0700 (Tue, 21 Jul 2009) $ -
- - - diff --git a/docs/tutorial/JITTutorial2-1.png b/docs/tutorial/JITTutorial2-1.png deleted file mode 100644 index eb21695f684aa96dbd8b77cca08726e90d19965d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 59107 zcmbTeWl)_>&^AZ}3oaoz!QI{6-Q9z`y95m$+}$05+ab8SySux?-sJh-s<(Fc&+e&8 zr7{e2dV0Ehdak}YA#yUJa9=RLfPsO*iHiv-fPsDD0t5Td4Fv&=JQvZ{0DpZp;g{wI z16%kcFe{r4{2SU}9!BhjdVuAUPj^fh7kaJ(q5TVH(JkWf>z`lct3-K$trX8;! zXld=F)4q;bnh+Q!D~V;pt?p*JqfEh)SfOZ+SO;0;I;FxFw2(Lz*_D213&Dvgpc&B7 zg?SuY#b2U8|5kx%O1)YIbGwIVev)9BSPf&IeKHPPrx*C;P!1A&Bs_g0dG(6(%@|$p zo|lf!a}^|FJi2zqK8A7W$v$?49r67m()&jq`7ulgl27RU!=#&Zj`(kI(x6lD-;j71 zG{V1m#MC5Q|3>0!YeV4mie0xNSkE`ZXh}F=2?$b18&=&das_}BX<1`P$5;Qb?^A?5mS zgv^Y71OI&_C$A^q|J$St;*Q|g*9{>^{&#U}x9K+2KXMGV`_-*^Fi+_J+a5K$lq(t^ z86qDUssP#TaR0UM801<~AcV$H^-0mE-66*a>UsTPQI19~m`&z6)gvZP3Y> z`SGQQsy|4kGFYb2UnVxJa1pW_1OK|7HS5|Hm#O*1^whHF!V>Np;u9uyMzfnzY3)vRup5p6st}-n5mMkYi6UJ{tc{3=I(_!;QiA6^U#8BSqx#&s9#?ljig)^mwT9X6kJYhwwz-r|k@RhaWB4$gh+C> z`8C&p{O%ppfZgs2L+L!+hJtIi^MpkxrtKggg|AiAVd`!YSH_r+7&O^wT}>i?AE2qVd@22L{|o3 z;O=s7T0gaQF=7v;{IlW^{Z2;N`c-#Sl7omN)bJo|Y+CA`i&jgm>N}cwaDI7sc5U;LFE57pJFNd`b@UXH~ZznEaDW8JBKGlbV z+NK`-IjgREv9&H-c)>Dz|5@rlIP{q30NnJ_m5+vl$Y z{jM;zi;nVc78A&S14u)zr@gRx{p+H~lq){zY5dd55XRFv5z?Cx`c&uEv~?F~K?>HdM+SjVDoS+u>_2N)9m2I{belT#>P{*r2o{&W@j z+IeoP#mXibMhp+Eukj`6oQO{^3nw4Eseg1-#90O(`(-243al+sVjmVF%@RY*G@KAZ zUN;6Zebsk(SSk<8v7gfH?>X0L^;HO0S(^bh=u)VU>(mGd#%b$xxK1rKIXJQ?&7`UZ z*9{W~_8{3nJx{Q3K+tP1DFzBI3seh+nT`u_!NIW4Oh(2VrB*!U`k|IrIaKSQ8C5qh zz8tFX>(33qNcMkc==eRfGklZ822>RXn{-Z9#b?9q{NvnVCkLIg5UE3ttgJ zl~X2nt!M{yy7-MGGpFGjuTL-NI#rx__)Mrj4BkFjD^1U2m&_B$mV4>Z;@ZKEF6lTW zl69GxX#bJwn}!0PVJ#jnDf~XI8zr^n-55rpS6S-ULnd9`lB*)D5u-_i4#5zj0z!V_u9+#RNei4HHiymnH5)7e%tkI_Tv_aZiF-A{3=t)F+!dsM|2GiuHUarI7aCJ-=nie zNo|3u(dqzWxVUjEez6Us{Tgki&8)&M5?gM?b4La17S#PltIL1(n{FE+^JkWvNswOg z0jB!jGvu<%x*y1korwxjN;)DPt6xEU&jK|gREdd6+)y&@blE%}(SOqNC7>!#C~Ba3 zsI4zne#^zujxs7kp=c%B)u?S|?GV$nuZ8?Fo!G?50B1Tb>mxsin28kBoC)@WN7%&K zB8@JF+fZNn@K?*rr90`WGc|$D=1Ff-O~J)oJ*8okc+n&lW;nCOa~8pQ&vulkHIUtppK+8I z>^0XUSf$gK2W4-Ot`AJ>2@xBRqXmDjPkj9Bbw`8O16r`V8KcBh3y_?baG)w*Zt=9m z9*SJ4Z+XH#nfR9UoeG6hGDf2PXKzw~y=Ad3X7l9w* zwo&goIAX#ZZJ6d>S0Hi1Vw&0yUTFA`9#TsFE}z(VeZ2aYH53Nx6!LE_Lxi^1kJ{G8jCu81*ODgRDtb0@Y0{J|+rcGCb26EkNZew}jc+!k`Ew89iojo#TI z%CdFCxR&wPaB~#)1EcC0C~2qq{=I#(jh*AutaZBu@X`ggKUyH^qEd2{;pm&t0FZn% zWFSwWc0X&$m9&wcN6f7;w{xmq^)}4I14=tp!lu0RPUn+ZDe@dM`4fF2JE23XwuA$3 zO}YASm8;Us`~nS}N+y_xf}$;?!WkxJXqF+OsWR!!RW833G%xrFzw#0hvYHgaqp!?O zq-+uma#ZOEl7ZuUH!!F5CH>Ck(>eN>4epPP#)U5kWyAivVE1mw=o z=SBP?Yr0^4X6o6(>(0_F_e{AAWY7eqJiCI+Iz-3Z-~0QO4q_G`Yvg^YtEN&=uV5&R zU*G3pR+iXlY&6UBn=??Pm=V6s=w~uXc2j!G(o>CpUP#g<6=K;l3nAkED$i`?qnfTq zuld=5Z9|?iAH|8-UOAiy7NvbS8brD^8jHCkrtqC4KmqwjZSkH!vT^KIHARTxII&vZ z31-;Ns~kghjzvu2S7`1HvsIQI^qxFvZj?he<}b|LgrxPv%Xd9mNLOqt(h|C{q4hi+ zgd~}`vWb|ojXqPq<@7PvTzYv==M65R;%o?I^y=+u4GDcz-u6cKdqp+S~8RKC)#O6EBju=S<}?W|;N%fs5Ug%e@0ohO=Ud#Ybna9{nbp1UaKZL;^sHZf`?{4YEM6Zag4a zw(TmvKcHY7CL#PoI~Nvqy-^5nRup8!hdTH>Nl5hA3~>wn75(ilZeI#_a5u4VM6f(*gYMPF zf)Cdx$rYa4C*WPGQIK%Z*d7x5$C%QZx0d;`spgVw^lvDrjf3ll9H-^nDksBsh22hV z{gb|_XC2pUEjmoZW07iX{(SAc`xBw*qZOky*G^~U>bb$);rxtPIg58C|pEr#Yr zzwC+W=pxJY?dvsu3JUCUyrjHJCHFZ61S8CPDo|z?yiR(g|MMXk-`<~LX@_u~5 z*~d-_&e+E%Guhk>rawIocz-2r*|gWOGU?GdMPM_ox_w){7cJ~>R9FqRo4cKGq4mUR zG(6EsqFg-h2Sta1n2^^T$CNxCKG5q^_P(^#oIg)p#)o)-UIY7e#dKaL7#p4Mn)lOl z9=m_`7ed;DxDT_7YnZRte5s$J_&{@xk3L=Qm0$bY@#ZdX;ekZ{PY)*-^fp@^3QaED zSn4FAsVXj>8R%fK-&8A7k=?i4%2P2dDWBz)r!&+{s)g-v3JeoB_Eo^9;~OivM|_ah zY-Do;a;ME}jY^r(()j_jHMUlY)7N1%7@muXs9qhgv#s*G%Fe;!3Ld9tE34TV`<~T6 z#>Tzv@_X?C>n02x(<+>&xl`Y!z9?$DqHz&Y7XNn3-)G}$pw}LB>1+kN6={R`=4zy1 zYSIf;+BkzS4bwKbzA8f-%;nd1Wdmn!-##3dT%oolq-!6xmURJqdi4nc;={DS$8>{1 zVjY5(H;?IV9aPNv4&~)=UA#pe26Zk~pIA3!g!?i5BPEv}h*85n=x>(PV}yc(&)Wt} zTg{Y;gjX&Z9~V#Yn!wzT+5`RT&>SC1FE~qaJ;tUDmKyAlJPmZGcQ6Hf`e?_WUi;3Q zjvDj^xxCTr`V|_6q#3bf*}eyTNOfQtIRf4|WM)LoC=&`uXENm-8O{A!;Fl&Yv6Bl+ z8icOTI@!Xw6C;?+G3t#dT%Rq3)8+K(ztq=f_k)2?K2@+HBp|X|=ei!0M zP7N%;C5N!t#*cq+8vI1lCgX$=t88lD1m5l=rrk@%bThJM$j?nZDCSVGxf^|-3n@US z{<)MRCV65uCnLky$k(r5@AD*+lkZ2f@BZht=ULz)saa|1=X!{U!#&dWqAoVNu^g`c z%)Mgv8{cPMiV@zZ{wxF#IDKxUXp-_5h;_TI*z4$ zEA6**^exCe4qX%u9`P7uaN6+a1QB|~Z`}Bl+a!f%UV@1AY>lJKas zzdYFlyym8sh9J3Y5^fY?E`>`yOq3yBmNsN@k=#4wiDgFfmGi1SI?O)2s3fxa!sxum zmbfDV_im1kC1&$qXPfc^GSWYqn+Azxk1Q~`ncTf2nxEw)rypn|G3{(l?ZR1!P$k!5 z{~Qpx)h@q-h!WPA2R^aOU<5P&2MEB|DYU3+$LrVf4@Vyf6UZJ9NPqR}@`pNv6_ZTY zwDHn4A%^Yks#0pSy&aE7$G!d-#FUpGzG4Ff;)6O5qsLI7x4spCxnGZcyf9V#jhU$D zSv1PLu9pi=^QLb31!16LNwA^0ppvFUUc?;?RV*KWi^S(PiajRjC8!Wi^Bd@_90NJQL zwu`IZp~!R0uz5bHETE^+WPs_Uj9OmjdnAz2=Uxf~1odAH}K8y1D|a(ZKWm6o~L z#8)$=cxQ#)fDvsbmYB(_bhH1{O(HS`KwQc7J8NKXX7Pgcm*jT@xA@VS*o)56gR|4W zweYbq(86MOA z_J7A)K35@(F%hd`ogsew&}8)clKgWXQLBTDL4bh5AQF#rzMC#~W-^DhuEHDE$;V@h z1>`Y1KKJj`W0WI&_Al=muU4a0OQ`+jT{~)D;b>7eksiByCnWZSxzNSHb8scj)fblE zf&oA^)bN&*BJTi?5CEr-3BbS_=+Sv|vwHf!?Bi+m>q82lU%zkHa)C9oLJ~=B*b1gc@|#=s_$U$tNYkMDU=nDz|LbOvtgGj%tO~CA;nal4pg2 zb~M`4u>@EA!ngat%BdUj<(-&n&p0vgPY{ZSwX{EW89wQZCmZ22~QxzqMa6%zhwlj z1?!5RYGLeNAcUN*23dv!++>Y)=b5p3Va5pP(ir!^ z5LU9^Y;r$z{b2uR#({Z@iz8t6l52me#g&DDe+cZSP^_X6<21N!8lheMkm+mjfP;qRo~OT;#!zos_H4^NZ`| zZ9G5wPpyWc9XYQB*=!F|%C=Z;DrPXQ+-VJ&+krX4@)_F}B$i&E@nW%4WZaTGO z6W7dQ8}w-$ddVsHq1=N5@O^BDr}48(hp4Za)OTJwwD4UEtIOY^pVoYeKdq(11gH&- zJ65yXVOLULH(Tb@j7UE8Sk>?(Btw63GKNY>sfZT$PSlIv3>G&{9sMAB;i5d!Xt}AJ zG4*e|v#l~6pL53}UF~2Gi_lo7j?Gn(UR6;%}Y@_vYJ64UX;5)_R&k`_5c|1iRHW*yKZCEoD3_W!w_| zhvE^CjbFP9#7Bv#C^@}NBca70c6Jsjg)-BT{7$+6EIp$E4!*1})J%vy*DL5_v=_MXijPqYgaS&O<~7IQcdtno z%jbt*Iy~Rg6UQ54QdI)FM%~4TAxm+B>r04Pxqi8XX9^YEuXxQm^9{q8+m6i+NXUGd z3f{0=^WV4qczH)jckxrmD?iRKLyXLxI=IRpA&SxcY*X0Da1i0aMR~9v@x065AN|(^ ztLdLJ|7#CD*Uqzfp&cL!4dI|)$?r>Rh;#7$)V;E&afAjr z^#1~KsudD!`f#xNOpq0({*CnINWbhl0J+SN0iZ&cN5~l{FQ?IMlBjX5*-OA znn>E;uADM@eu`u@79(P9(jV5SEmZPkz@+2jurB`&ER#Cu$h+Bk6qMG=*l<{ilCT5G za5<;Tkm6dqa!iMcIIzz|D~LPw4r$eZrJ**ipM_8Hz9PiS3@VC4&*g%6EyF z*B|GLRfL~=KyC`pSJiPUtc9HZwkuTdm1~B3fCsOac4_8v=0w!Ngfh~^BF>?3Dr*`k zn1^bLinV(Cyvv6?IyDX>Z{Bf%%;h>tBd5Jip~*V`iU4FE#T)n&W43V3QuWdG>q!#} zLwW8ay2^?Jqri&nIv=&%-M&>UY~e}QgZ+Vv--m<4yYCHE$S=_rmTJkguNA*Ry6$$~ zGW_fukTZN435aLI)DFvh`5(FL9z)2!;>jWjDxcINoz2_zl@#}E6&|e=4qK&!}2lAe4 z7oS9|DEF;VLd(&dn&wBO37#0GbH!8F$dhK+;?T%+vU_1W)Haa0?5C)6$GP&P&de>) zj&Dgi7IIlSpxwa}+tflD8pUlrmi_kPjq%rhgma*U$xTfY%~Qon)v!SGcM#57%|>4l zoX)8z6UM2J02o}#a_(4?uBS?B+}F~~LMmA| z@&-A}xLs8!FP-*v>(Wpv#i^Zi+qDZSJQs&Rz0l?Yy)U|kD%m!n_pP{za+V4e^d5txtQEAUYMG;&~XJ4 zTs4CE(j!}#sv@h8990wtFI**iREKaID}Ib{MBqh08+4goYDd1aJZG7D?II<`-@cA> zs8B&^*H(ZVMYnwcr9=L#7xkM~7lDPJ2Cld%vo=lsg{u3Nr;$SHvM&1>O(}ArXf(4q zt)Q30N=RrRqJ5)~JOetaxDn7tzdEzR#9@s2=T|YKvPSiikDmiUxD6TuI2M<;H;fXl z-7iev$m4T7Q>BYx2acL{ULi@U4XAH+s!HOC96$<9b#>%3s6LG`3P{Rk2+g0vv^ppf zo+!v5mvfW?B7_BGT~ivQi-%JOr(a3=ZyLKpRmb|H8|H`UABo)FK{&nYa3Uf59h0CJ zd;^s~C2>}>ML#1?H0jbW9a+iaPu_vNEi@E<*+f0XvFw3amJLu}s^-JzmT3$AGPS`O z1A6k4D=AV?k%ZT@@V-+*Pf?tPh;*uHW(-RmRak0g$n$Tx0umL*BOhj-gQWMZ^b-rOgTN}7c{rB zpKu0mx_t^Jz^usG29685is9-{|5I(bTM+~0S(`Vn$Rl{t#m<-!A7+#3NYD%llS_z6 zDjc;`KJ8z#$`0d;sX7FX4I7?->_>w%0Uq3z69sHm%PzBTdKPwD%P4!_Rp#ZMw&p}c zFZCT=52tUE#SmEOr+iS=FKe0mVP&Td;~*F*yK)Btmk!bOhcVeN-(f$uJksJ29XbZ) zuTK(Vo5u?dQ0{3}6rZ>@s(qeDu*V>)b|P!eVd3fmWh8)n}F7lQ= zKD`(6v86%&-LEW5H7s|>2nOLl^T4^0p31K_x1pbU>m0aDxuSbG zulRDauJ~$}jdfYFbeRtJhD%uASl8aL%R3wye^#jYx&~=y8V31BxfhqD$sKh4){NKd zU$`T`xZKH}*0#=HeT1!Z@u9LFL}uL)fK@T@%aV5MaSJN6opKas(a%N4d2q_!W&yiR z)N{kag~Eom6{3<$ywLls`^>46o2V;)Nekg}wk`;kT{mH=jHGQ@ zjP#cx5W;n>J1?IZTkY2W5@uK(%*pIh|=fC-J!gFp{qc^%E6mIvr z0&hj!R-Y!<1ag`uOcnFG>3tix2lsg4B`zYhPRI|Aw()DUDGND?yue1`Z(PQ?-bxX# zYd2S=J>)5MT%>78Sv(!EWY|b_O@^{b<)^A)AV(X=T@QVqOH8lUeR)9d3DQ7_i!0hs zx1!4)VUH%YYCihYwe-NfOde|4mc1k0U(><=10e>&kmaeg)5<7Fk2We)>|?lCWorH* zJUxEC(6-NCm_6=YAZ)2NyD2QF+r6JRzo@CWAPfXhOd%((%%=PJvFGkY^cva*v5t^A z)%)EaR)#~3akB3Frh*o{##a9uRka^ThPmjOF&}_?LmO)Z`HmE8lsz`4)o0zVwe(pM z`9{vFRx>C*T!*c}N2HW8|Ill5rCVeqt z#$&a?)E17?Bw&j8(!*xZ^Wz^V7})=tAtFiwWu)2f+Wlfai@o~a^_2=l%kTaF=sKtm(ZqkSfquxYk z3Llrd_QJ?G)?0K^s;3U1y8D@zFs7*?#vg zx9L7yW*{O5#hu|2FQ@IuI$w=KY88FSKVi+SF_dw$-@;YT8NnwiEQGugVp{xbC=1+N)TY?KT=TU0=&Qyc)gc)8#_E)yKp?bv@KrI#Y72O( zndROQlAw9vc60|=fh0~jIm7(VX=n``p}+s3iFAI?&C$W$B9YR#A4;U?B%ZL%RX8L> z&wRvivc8vGIsO>`Sm)qzO{THCNx}{RAf10;%LEeLPdoPpG$x1|+r0IQMAduMrip|Q zu8kT9ChW=WOH zbB;uaf?)ApyP(a4t_&pK!V2XWa}o$-lWnGXiAFjM7qE-aE~1FUWa>0UIOl)@>)&etJDoZ=e$@8o!T4YHfcrHg8kb4PWf z$2T)h5#0&**xdgHo`1(su&ghk$Yx{E$dK=+r9eK`UPWJnylJs6{uRDGt6&+|J~sK+ zMKNKD$#(qX`>nioK82d-gZRQNApE*N(Vgd08^7@*|3TZ&X_~9rPjQx@yTst$<2X0? zC0?}kP~I5A9UF}9_ahr*|eo3x{aMW)S*A@{ta&2toWOzKyYP%o0Z+FiKy|9v& zC}|b+^kL#rOe0+8DM|}i+?MD4ETI9>9dmvHHCE3}Wu~}3;a2iPUmL>9lOKD2bTGMd z8mDskX{l;Y6nQnUrN&8AE75$lQcNr~?^k9mC>ypnU|0Zcsq=6<&C=6rh$w53M#^fh z@z~>r3*Ywt9+sXEk3@HIh-Kh%mRFD0ok3;`N=#FDm3m3fJRd{7e8_9ipw(0nH%ap=A0e<(JVL*yr(Os)zc^ODK$lJ0nG zN9+N!F=Kk9CHQfcnXl$k2oZA1h(dLBP5SfoIK(6n=wN;@-PwWB)*fCzTPNOPI{{Qm~k-G`xcoj$=-8w#|hw~9AOm|ZB%)A z!|P2u(7$8wRSHOxSk;X*QbWTBn!|^au+GH4CMgwvWbB|(EGQug@my)-WrQrX9BFhe zAjJ5!gjZ)#uI6m$!j^uCIyQ1RV@GkbkTCY6;1?}3wR1;7UZf7`YP($XQI!7Pr_%A` zRhF8sg^Jebcs^9c7^PdcUL#3W>vU#+2>a-T%k0xIN=dbi-MjNxOIqtTwmbF$I;so@ z>mpc4X|UHg29OOllUW|s3KZcl-D9b~joAaB+jeI_Fj{ujqWt2|TU9ThsJ>i6|6%Ox zd;pVlbPW{$?Kx&su-$`ukqbfJ145E!L!nYcHc|4~S%v|T4{==AyQi}U$TpbZ%7n)^ zk@tHqa8hjt^F6tmM|>TGouBir6VzEJ#20K~A}xPu2Gr^)R6q4c1H@*e;`u5&$sB(G z<4vI_;i_%Sv+N$weX?V)H&;y zdI@Ia_jMTraM$Bjw!ganN8#?~wRc|^MCTVGAQ1&1hTRJ6iF`uc{(o3w<}D+=IU%ci$bJ8B5 zfO1WRDyOHL`RYsNW%uZ>d=e1F_s4K=pDvZHS+-`68Yt#K=0me5Y7^d=v~8J1_kd<& zKB3@hVAo=hdDEHXb$-Ka3cJ$pr+w8;cIa94xR}{Am0Q(%1~WXHx^}WD~FBQHdNJw(4|H`@X8!Cg;9M;43lvjqmb+y}uWQ9MT0w>lF=2Qc#e; z08G zIrq>vo38Z`skfObq-?f^3Gm>uP9#iJ@A~QH;i~P=TThrYhRP3#^f$#d1E~6bU^=^i z^j83T;h$^#|8F|zvrx;>F}gc9GA^?5|0X}g{j3g(wzb=`t{Ag#RX*?D_ue+!l) z3;0T@Lc|f5clmf!Ny_mV@LW+${?$8Ll&$c;TVjLZMh`g^CQFbHDb9yh2 zHzDxBrt%JK*kaPsJ$pQNO+vvjafe4oC^$gx#>giUt~fbT*^F+N_9yM@o0|X$2B1J{=;JOy=&h>waEzhvDd zh`{~Xxq}E$0wyGN7C0%hVaw$pr9MmQ#eQxS2?ur#abZmjibyUJ@8d*NmC0C!Q1E+o zu?R2|@H>CJXD~(5VwE4SO-&HUfy`xe1weiPVdM8noQ7?1O-2V9%m{CrR`a4R@3%v ze@-8T;JyOy<$lF|x*X#<#O7(5Ul5NQ%&78VxlQLxD`@N@3(0U5%9-DCPZB>Ir^ zu7v`^iM$K9`S<6i`tW^7+D5j?ce@aHyAP%ccSffv zRV&^PPF(h}%kNs-V?R3>83%|;6FERI+Z|b`F}b*1vdOKgqMOJ@q=s>C(*X@Bs;iUx z+yPtt)uk}S6-`r0ty!-JxT)*q04bpPi9Z*Gyf4s4v*lgdE-T=vBMJZXf*k1r?1k%Y z*}?T;C-LIM#)tELNlL&$i=W#{i;Dh^kIMmP30#(JtAK8zV`Kf};!vNrNqNN`$%KX? z$M#~+E|(p~xY^t;fBZL*44ByXv_tCy9o*H?!YKqDladl@*cZ7mA&S>?ehxVO`*Q!y zTATv~sp`0ax4+(0qTqa)__K54zSF`Li~!(E2s}yu$r$9~N>-ucal-t39?ZMFf|K)^ z5gqn^wgE(p07uIWmINrU325H3QwH38h_)U3UvL71TV-v3kbdsbeGYtX0~}AIBI#Ui zSCF< z>NEhUc6N6DohunWu#lGLc?YDu?$4Gpkme~TpHP^;W8&WaMDC?_#@(t1?SGcSM#6>q z4e;f7JbN`YwfCh=!_V(xT-*SW**B}EnM@{$YmJ7`EZ0CdvOEv(3d}*z%P!9EfXRzS z<-M(rBIW=(XL7*1IJuZi#<=gWb-W*p;Dx1YfAusE5i$#xmz4?8p-U;Ly@&SqvmBKo zc@M}6?10zwPm-aAcfIE}?Rgv9z*QB4go2wAdwc7AJYW6k?IH6mBrPrN zJ>JBgyK<>DSmP)tC~WI*cX{8G>TWP*K1h8e1ek9ryg*6c;WGWq6EgGV*d+NFk=kIR zz+%#6=Iky?!kNeh$dCL8-Y5EaauAJZ*x1l!xb0%N1+W0M&D)cu;NIR|=)E@}JZt?m zefLQ;;A$-6z8)6@2pn*)w>EDqfbC5X3whX=awh#5(^m?&-9UsynIFK1ht zYmaC=m(fu~fL2nv4`)g*Vl$sVCu%#Z4?n!O(UBzs;Zhw45f9(oe$;cGwKBf1$Yihl(j)Fo0a7#8Jz-D~{`R`K1QIepNj(JqCz(Fb^XQup^i9_jiTCYcY{Qlf8An2^_4V<{ z_3@z4?x?(h1c+w=noagbKnk7XM)2Z6`Vt*w%D#nzo03rJxkKr?m+ta@Apki*C~0U=L=D&fy8{2uaBG)f z?BU6Yu(mdixw-kaiPL{Qjl}Qc98QO*vlZH5FHd*>u0gu0a0Xa9oh`||+^|49&#kaoMn7|SkeUTW0_!vCTbVAEd# zSDpeQbolhN66(KL{^gz2GS2!m6AU@Nv=a9Ea|7e}4_@0#%^K-@uTl(M6JMAwLfqdg0%{hR7@EzW);V5vu>Br&cV4S$9#0 zPwIz4oRQaNXLallq9+Kfmb^HYi8po8;~Q=0n{LRtNNus17|dA*D;2IJUz*Y1!|)0E z06)C$)hzdCcR@@8JRLC}Z?gmyPU8;;u7c#7ZmBQtxiiwp=QCiFKuAh>z5;HN-zazo zr=z_QSa$LiL{p|bX|%MyB2tc%Q&almN53`ILSDs|s`QOOGPHMIlVMj5Uj`@Gi;OWr zI!sE51hks|FFXGgnVHdH$F~!5c_~UUPObSWL`cV`j+p2yIoP&LKLI2+Q>J;hPJD0k zZWe!$SFKfgDiYjJMgO}v|H(db&hT;rR$#x3RzA{aj)t8kf&>9a-VpP;L4`mwT(feD zpY*>n`MF(SvpgA2rS~<*yKh{DK#wup_3^&iP4B(?qbuOQwmb2vk>-aYJY33pe;#_4NX#YaYdL|3XZCi;MM6@DJR#1Z*-VeT3!yC^mHCAvUKzV8YUy z7ut=!_^R=26A@V)9)IQi>NpX$G7@<1dy-1aNSHD>e9Jg9{L1llC(^qY@{oQHYldv5kRcadi)kX(Z?Vg+|^sd4P}ZnHgDC>ci9IRT>PkJoKyUI^^$>@e69 zo7d(?VViH#jTT-0|7Bk~qz7lD;4#jS1Un5~yYIDhgo zj~JtIb)@ia^yc{RFtK_vdr#E9&5Rk*c)1!_{TRYA*}%Z;#1-T{l!VF36p3w$D;xQ3 zPkJCD*Gz&iQ{L8ia*Q&cLBX8qfm@gth>2i0R)JNuSAb<3cH@>bVvH`mAP2!ZXV9gB zBDKWotNs3-G|dKj&UZ;9TxBx2LRwo}!6S{UFE<2Q;sRU!?_P5EOn0IoKe{gEdcJOD zxlBLDF;PQf{|^`7+Ud7uT)EcI1K3mSeFy$U6qWKM^NFSjh=~hVq)EogzfEzP8VF2f zl;Pn1{15oKhC6$ETX?ST_nW;sQD+;KsDNGUTB4qRu)aNJszvuM(FIH67R(>7{MQntuvGo#I5Y zKbzVDMw5rq(!5{w7E%Dj;>7qO-W=h3i*^bP3D;0k-`3CXP`L#wo>wE6rdFub;Ho|{ zO_g^4l~_~{1ow-UqpaSJ1Ayny4tb=*Tjaj=+k1^=t(sov$qc<A;>lcIqiWUNQP)P0I}_ zn>ty!j{7uGDG2c&ysALG;FR0e-t`uS;JycUCg5Cqds$4D>aDPV zXLuhkXJD1xnU_Q$F8py@r*CVg!1m65)ycVVEteZ-#iAFi5sBF?G&Yr$GUc`ZeZ~o0 z9*FmCZ{C{y=ebjxuZEe*G!EXI#~|Xm&%Tf9FaygbkCRwEr2TBpHaX-X&Q1T4vr@*a z>%8CA%n9Q!E~v`Z2a)IF9b1ZmKBK`|+iN-U5}>^hbQOTyB`cfTSj!KR+`^DUt_V8= zRaPXBSNy??KN)mpn6*lXt!Zf8jLx&}SzD62yjFZ-#pgU@laP!e)NF??98qpuBO+1Z zAw8Y1M`7oz_=}Q`o%r5EjrNOgXclsri~AuU_Gx=>*{F-8+jG``Ds$L~I?gJG_N?6)Y_xy`Ai{!Lp zt{y!lZ+SgMcD{xC&h}X~%9K@RwCrMlrp}#Y z)j8B&9_q=GB7JyU^4W#1wGThrdf0t8Cnfs9JFyudcKjH+7aov$)12jP6^R%t;<_Dt zpv-jQ;q|UP3P^rYfW#O>LsPTb?P|AJRRa0_f1v>KaMlX(HOG6;!IhA>>1n$W(DsA> zr*p9eHcV|8LqhxinZhu?+(G`%yYWv18@puasOcDd=$sW(r*^C*&v@-5OP z-Sq=KKBg1Vq=U!*McG>hRzg z?9&o45W+0)bAGqZcGwe!z$1;lgpw>VHP&SmOPW?J3?D-`!Fuvkpr zXVld|h&-(cNh%sbzUFl(eS(cUEz4+6)hJU z$tMNgQZF6MFzY%@j0ky7?`|)qj*yy~T6Xta=h@`eiR~^IQnX_(&tQfn>4QRG=*-* z?YwLi4vt>80GALJi!LT59UTVR&2F8mofglH>Sx_ZSu$(ECFy|a5@`omijOc}0s>h7 zkiLRd^S9!|H~|=^D_x1@#3o62Z+J2HVp(JPh^+j6J{b>0SiyAS^Vh*&42ns4mqr+= za@#w!%rI2eDfY*iE}~c$LE}QQg=h^%Mf;&ktrC?(^RZ&4a60llQ%;5-kF?hD9|DY1 z)aaQR!%$LVK5AsNiK>msll#v*$Eo>mU^EcLc}caik1G;O+6MHEYj)586DU1Jh5l0yka&jQUs(Jj{^VynC+SUKcY2V@n8SI2k>sJH~R1>>Bo*$O5cys+XG&zPF zS~*WjN-&vKvz^$oeJ!NlW{tg?{|$+(iMOa4mo0hl#%Ra>0x;T()&q1OZumM$I&O*C z*Rv2dl0dmMGte!^i2n25kCF7bo{Fs$9vQvgnfYf8TuA!Raa0^0%7Gvs1>SmOtGU`_{R&kcS~u zLkq{oju&ofxazFw{j7O2**ir_uW|doe>6ch4Bx2 zSn#4UZ2SpY!E^8PL`rq8VeWSy;&Nzq5^Tn!d|2yW^pm~5=8v;Yz=6E-@Rmon$0je` z$8-2|z7z9kg($^@iGw;4q2P0B>Ilf)HqK9ZVfydw?^8v+BK|Vk2j%{+jCLEz<|&n; zY943%j|akH5vm_>_LaVkePb!oUNLc1CvK+Pt04U%HoWAf=)DHeNm@PKKtJ-W{+r!C z4Y1oivlS|h9_K_!NHSu^YS@XiF?*!~7BX2qmK|>|**zWuCzq$odz8$l>tUu#fBk>b z+Xn~!(c359=AZYApW@%Tu_mP$R5=XT>)t@HIy=bRIUCZv=aOD>29 z9(g=avO0;RG704&Aw$4hQqlN54atx$jn=SbdDE$#;z}whM@{h*l8O>>>(H$$cYh{Q zh>u@rrhjXFb%@b2HFt&;G`FCr=qLY}5}Pk~Q_kCY>!2uCaW{a7=UO$H=+!C#l2{fJV;HFNusdG6$y}QuN z*TpfWK2ybZF>E&97a-DYVg%~5Fv2x2`|FnohZ{ILu)Dqd1OE1?%`wTPQp?2Hrz$`8 zNI^bJlY2YFWol=A4aaJ!>LPbdWxao5LHab^vXl(j(k5nmBc%0y)%KFJDz(_XXMFU+ z!y?V1Zxn48IQue0h~nKld6DAcn@5cc1cZ(L38v_NK#U@yUAB4W^PbjPf_NRKc~-pO zlMYqQb_qIX#UC?zd1{B3%s<7|BGgS7MfxVRXeHaxg`p0LkWD4xMOYYY;fhDnfoZWJ*+uE`Pxo_5un+8W1tuWukj9GH{gS zQHFGd=_;Frykd0gybL?A#LkJ@SzRm?*eGZph8rPzxyq3u*YZ+T90Hj8oO60lUP-NL z$_Gd&!gIzQddZ&ElEcC;zRVq^(_TZv0<`w80IeP7UL>z0LdACY*-TP@gY=rT24^;x zLT9m~%qmy0wLDag5j!l|cox&bdJVmZA=*jv{(3R*cwwjG6;Q>weXY6WwY9=mS-q9< z3V=hH;KwMSu(9eFGiR$)y|lEVtZP6?VYhQuSoD@(){x^`UXbl@4m~ErJsLL-t4ZPY zZB5~yg6arCd9JlTrr#3tH%pc}GbV4Sl*%kC6jtBE!Ku=i3=TJ?HOdoN8uKtYnbjdf zCPMZZyEVWzJIUa1F+SmNI7#CWe8%_92XVA>S7_@KWy?2*1g*jV{^3n9NJzsNeUFIrqG|_-zk{-E^--iXZ#s89aP<9^Oi#wb zhvl$fPvRXAgv3@FQHKT14rtv(RbQBlOjS%RV?HEr47@9%)A54OCMy>=N>!EgWZ@eO z6oXb-3;J}54Whr9N$+lQkmqQzER+u{=6Q|elWDv)l>r}0ugqz0L0>{g6K+=!)Of6@ zOp14 z)EW<@v$;XOF!7Y=%@D$Zi>u(B%i8{?=~r~Tmg+OdbSAy0C&8$n9mzB9vxFb|U53%} z$QM5Cm_%&Qewxx>{si~oH5;MAsSSLqtgo-&TcA{nt@e_7xkkcOt+~^KV!*99X6ckp z+2L~|-Qs{W%et9+Q_lk?vB@VNUk--LcTSTZxF4Ib<2SS_J7&We2c^PJCZK|rD?O*} z6zkwO7W%StcSC-LA#mLiuY7%OyIayO3UFrs>9B8xBFeAu`#Y#%fKD+jF8pv~tWx+@ z_)l)4Z6IMQhi~{aJT6a;hj1H)k_b;SVtRk)G~d_zB3isEi-{&WYil$CWC#JWZ>wjL z=p8yIpb+$N1CybP*+VzQqPyKjg^&%FJZ`@iTkRJ^n%GMN)32v1pXVT-qns5rq_Y-` zIvu#BTt2!4q<2NOg(n<0Y|fF{d^Psd_5BQC!FtlOZqRRg_e*-~wu3qqe@|+nOzg<& zDve%+;#B5p@q7A5QUXKFatw<_)r>pD4;xFRK8=`Oq%{+|em^BP4uZti&PH%UtueN9 znhXq%mf>s|2vqCfn)|G|TPUX{cTw);>8jELpG`ps1Z&DaBp5<5LIri&d7icoG1q*s zQyR)5#y*Zx-Uj*b$laKZWEV{vJZ|=HIZuhH7gvt* z!7x>GRsmWD{B`y3UT(LHNS$si5kc$Kb8+tjx%!bh#qKT)TOC?y18PecJ47aKxP6!^ z`n3-GZsGggQ>r5R$pbOs1HE8!2JLv2J>eYPd8nzWqdl*tZsfOQZcs%-I?Cu@YO7sM z&=7gt7+2JgB5rg~i{)FlQ?|H2p&l>%c*#Y`CTsUpnIe|W`tGv6$xTRgqEA0l)as_r z8s4DW`RA^3vzv9@|DeH(n%WK;bSbV^QS~RUJF20lb>w862INCcFg_q`$!Qjpbx9T4 z2t}10b9mO2;?ND;qTk=X+HH+a${u#JyJ|;zXCN6f<{xp36IzFR6r%Om+F+Jyd3^%i zr_8lQx5!~C*G*G5; zmW?T>zd!YNpKUA^nhw=xv5%AmOfYPm_DZHC&7vtp;|x6R+!Sru?E!WEq})oCFSd@P zElg%w-JF;UBdY<(wM5CkbR}F#>hF$^WJ$7<5{Gy7(n!RWloZLB8<@nj%>~2hO64l_ z0~2^3Xu1m3PP*vB*e4_URc6JX)r2lLQisfm7r zrk*LpyC$<%pp;-p1_NY1@*=u}GpB^h$(^`5a@WuXIqE1|Yy}9!Wt$Kf38zTOO!P{-Yoa&OL8GUSl}Qg_qNlj zJPNEjk@OH}aoit7R?JIwF5z#1d-WT*EW^iR8}JErym-g-sEVY2K7$+;pAEm`<~vjf zt;;V3)Oy+4l^RMQ*C0aD5kZGeu?CQOt|LaR48niz&y0C)7StYWty=EXl%{lOdWbVs zh(1^0Bnio858xD=M3kX&v>>CiOK&BdD04I>oorpP-zrHoReR5BTJu@rmMG;nz14%7 zDq^IfOzY7#9pmNc{v9LY3qfW#Qj<@a&%6?b$0y= zM>`8FgZt|Me3E5VEW%z>e@t$a0@|HIf(y%o*Kd&o4PDB~k!EWQ1lv_cLQw zyM=x#z5=_JNo^Pl2xJ+21shY{(ZXE3VxCQMN*-&dek%^aR+$GSNvCH8&j4IoZZ;u`yt8KfbeV zf=de6KKs05FN$b`x=V~Kx=MWAs5Nq&)HIJ`F5^yMu4dc4`oM3XE#@?P1W}_un{N48 z_+-7i`iLM@6`|(7qy+D8P8YI^Ut+jOrrT5?2vThEG~{hBpnZQ52L%yfl zTe{j|GpKf8>Z@YR=~=Sp+j^XE9jW@ulc;F+vUNV9eB z)jh(FMsXPp+`vy?aTqZnwuN<PdCH^7pcn6&uofg$9`MCTsGx3Jh|4zPt`m4x^#Z+B0L!6W2mSCYQe(^ z)T`QOaCSNQ;7#TG-Sa8#*fdiK4nt-}E&HnD1x8ES29t-p5c4N?vYxQnhmEEcPWb*>{<-i>Uu1Y1fm5OIK@TG^o=$*lg!k4q_OX8}Jo>=IQ+P$WG zTiUn;RKG*3rP$Ub33-mSOG_6o$$+w;LR zv2H6gIKMAk7M;1xSCCldw`JqC?7$=UfcfL4E1n_!DJ(_?m0pa;q`=CpPLOwe`82g* zz$U{te@{9>GwW7?-j1w1Rc5RztZE? z{zjAtdhc0xegO3f&-SFF61}w#I-DF|4?eP&`b&QVIh&4|euO6dV(s z5QXb`FJ_g=I6?05g`f71GZh+nq>{`+(^1_?z}1m{R|Arfm31xu8fyLavD=2PAWVmPIBWe= zyixLjgSs1~A@5wIFI7n|8{5wYt_l}pqx8Xg$~5S1a6zmTyWHg7<(nr1Qmp79Q&&UF zi?nXF{KNEgPJwcyyvTW(^&n{d=AYey$kV#D1?Zq*7yh^!yjzy#X@{vl@7kL^(Us{K zKsI142ZYChmmy4r;y9lnnZwg->K5eWeNp!vt{hd^&69jA-xbi*$f~-+lI}P8Vlyu- zhvFC0Zf$K5Q8FN@k;hd^f2#LD<{2%h%qfN7kXJk5ejT2%`QOS&)9 z_SRzxsR(k|!-m;SH>Xqq{!AEXlvq$T@U8tlr(t3=qzTTbjX*bT+Qq%UZ$Hp z8wUE$8r@x1YxLai$HuuBvLo0K=67w~BH4KK$}d|~AIi!RGkkehbo{&R1a43K9%I08 zImVtrHM|1v5jJ*(auP+N<~aO1y>o7JchdA$?4g&$7eS5TSsx5a-`y!0Hiu_ra`1cp z5mD*X>3P9Tc9SQ^4eumk%x{D~uu5#23CC9W6lty8JPK(2;!1LH3kw>Jt^~f*q~iy% z{(CQ0KlY&V)p&{`vX~t^<^~4jgahN}XKB_2Ir0m?@+dcX_JnRty3-1_z}trTLp7-a zh16+9VykIZ@ikO~l6j^XN0~?U{J@ki2V`!UMi?rJ<}PiX2sDUP!y z#ct!Z-b{mzLn?o&80lC_nd3gBvQo78c$Nw?;XQ_WUTYg1lb zV@Yfl$$dc-_$*@M3ay_EF?)Z3X_U19)Bp1Le1X=K>C<)p{$K^{W1*j&%qeW8^D!(f zL$e+1RQSfW$>Fc=)D#3He{hwjU7O>9_WXBP?vRfu?=~-y#7zjtMODDXBQ>&GoS)D} zbw87(anDm&m&C>!o=CZ_5w#i^RBcYSA-2+gE!*8(N)@&LE&_Mn+P07PQ1Cf|6zk6G z!fKWAM?}Pr6!6b^5B}Wc=?TJ5b<(je{zh5!#u<{(>kU_p*L5g#yNlz__k19`X54??Y}g#Ubcdfifu9$=5vNOM zI@l&8l$J`AtZ$n!Hzug#5h{V~Fx3&0W~r$!ID45b$(n}oZ&xBoq$t6yqEkx~Z?=}C z_S;IJ+!xfA={)D!D%T8)gABMcjV8rc4!e8QzWE|o1lefO@buy0wbhwiE&uJNiI;va zJrTB^weFvWOknTs==jlK(1Xg?QL+o4VNM7?C$G1{Lr1{MNX+%fN6Za8P{PKI?Q1Nb-HjQ)!brAKT_5$jnSKX9UYqGEG%UWhX_4DkL z%u{6C&>g!EQt^RxPq`B>3*iEiV&eI)rSn5($RG{5*6YT*Rqxi1)N!x~d|psq(N6_K z577C6qqpg-9|^%myx@O*w6^giV(f^x~xf zWmh-uhkb&k)2zU$^PzAAr9?0Aq1vygPgg_ml<*SxCp&0dKjTz_xlUeabI+2xO~&=jTPgIDjTv8tm?S@;W>QlD@N z2Ma*CWyPb8Azi}Fg{&0+X%1BVNU7l`abjE=A~B}(2`No{FHH*F+(XVvCiR`wXdM;9 z`n9#N%ppt_gN;rxJ_1%mHQm0c$IEx)N$dL1-h(AMK&C(ELwT-zX^N_Eb$g5>P&#pe zZc;2>XiDhTDlozyJQRC4VzW6pSi9X#IcQ;Yri^=)Kegr<-C3V#RifSYl^wJ!@x+*eW6E8--qT5;u=*81L-Ev*`W(rtSJ2iuX_GBDe-;oH6r@ouv9FLF(j+-X- z(iPmgXe2JKbXxj}!@;^H{?^QaFWA$SPKaspHqt{^mzt^DODf9o!@fexRdTBQHlsWm zSS;EkdXMviLRlvdj!@2obP#OOKyX^vbs8Za?wm>q)qC{66an7OI z#sqIdE$GQj&s8!xbf5BwKeF%0T#zeKE62o-+pJTp8rfv7Nl@>urMa|qjj~1|-|Rz1 zJ8RFy%0)qV5lfXJSRkakF`M z1+7H;JFg)@L`-p?AR^-!au28xD9Ar{oQWQ&8cQ~@T%GO) zrg(1Ol4!P?5X0%{Mz8=Vk!m)2Eu*C_H8n|^gtz7{nR+xXcDQ|MQ%g#c`PY665)oDT z`tlGNW>SpkZZw|0B`fB@;iUzJW^g?}ig}rD93Rrec5)=SU%bun>-ihImGwRk;KSIZ z#wfu-Ezzg`pw9ElQdkPk(kNHb8TbX_T6)hl9X2M00C)TTcba{WlEUZ*L9=x0CP8%8 zf%n_ZER36DTnOSVs1DRC>s3dEp92t@3Oa=MkuRHgid?wSoH&m~IQU{nOrIK`6c45s ziCqG5TJT4+o~j=2srzso{NHxo?q#N$~8NgQNS zJ7DP_RLT*?#EX0RJ7f$!Z&pKV6@(=5MQtbirL}Uz1Cfx z4}0}U%id~&gqX@18nT7_J~$-g_jOWCAiE!~K=5H$kVVWv-5T7y zBxc&s4C=U}WnlcGT(0)L$4_{QLqrzA>bRrJm~~xwe}1QQI>5g^9dn*P4}5>L-Q~IcGsfkzd41?OVfKZpiI{S7Kl-!Z!+E^1E~f@L z%p8-i*x;aYy zLOLOC^1UF$Pw0+r#L4IiiGHDYM>I(XuYuiGSAC8Mjgrq;?5XWRoHIAk^=*bDYReLJ z*4cyFkv7Xe8gs5Pw<1#eJIkgDx}fKizz1NUT@c+3_{Q*6xxhQCtBzwK{d^_^=bKm8 z&xfndKV|Ao(|-bGYBpGZ*rf>0gKAq(qUbb?v1<78O$L-<+NGa8*b+h^>JAFjwc??p za9&*|;`=hJT}6PaEYd-U)qVSNl4+P`Zu_-BvL&sPY-R0g0B%ibt$`zTZutqioXe2` zK%!RaOx4n@J<0pBee~Akt^=o5f*I2X)o&(QwL#A>6#;{parEYsYE1K@eI{L-KhHy75s7izu` zR@j?>x~>Lp$ZUG$$B#BbxP%J&bnP})s;pESHex>EbF}l0Z-&3z?RN=?5!UL7Tjcgd znLqn;M$A#R`+aXT!F*ZQz6yWmQ>*#%Jhyz3czn=Ga&E|(KSIf$7DHKasE_~6Vo8N{ zIk$rMA(`;kZzoR2mWm}+l@!K{zd9;2=k7}P%^gx zga@fMr+Ao(-xv^==f3;>9AjW5Ua4+hE*eJC(_v;Je2L|K<@huB9j^L<)N94W@deN*vqO}dqW)teNiBX zIblQXH*1bLU+=Rfz2Y|PQMp{A=c3b--dmiRAk1fdoqY&)YfNK%+Pt7Hl|mZJ7j7Uz zuRkru1)m0z>!GU-b}a7RwH`yTSyP8vdF{6wuT99iCAW3N1_~ik+?}&N_vH}BKJcSR zrGhb6QWkqX?RzT8t9p)Fwc=?dTa2N7630Eb6+_4NkIMH&b*EnB^4d>dD9XlPaWh&# zCo6c9d?D?HM?p&jo%vdM%x(2C_KB~0I-S0@t z6SigZ_C;;IU|Vy+jtX$mjwMtwt`L!%WUqUBb~=(jc{Db_&6T(3qEs_Y-$ZL#P>=N2 zH&|jUrwb9S|bo{btQCV>VrujRZN*>cZA7H+ zRsi4dLQe9BG3we@%)zt65SjoplK)a+QBVj%IxL;1c@O&)zdoWFMKy6%Surk<~5R;YTe!7qkBjo8u3-Gu`s9jnCvMiN~@Ot{@8O z780~p8u*a~tPt7!Nu|mP+!0H%xCckI?Cel8wYtt<#c_p>A}y3+tNRs%8U~6)sAcI& zpHN;{0tc=GF{oz5%-)li$yGqm+YQcRYF~X`Vb$7P(xp<5rGknHaMDok3bVJzE(tH9 zm&R?vEXL6wQ)Agk7o98jx)}hz5D=4uZINBBmSbYv!j<;`z02GAyjeRFG+u^237wOJ zBm&k3fwwc@Ek-eFQhh82R&6dtH2|V^iY}_}cN)1fH7J*Md#@~2Cp<=DWfh60Ry&Ox z@r%{%w=3$58C9?VaF`)C)DaAuamJ~Qy4)*C>dX}Sjcbzg8|I|*+{us)w~Mo)n=y_& z(TK|Qy?|_NJ$4$Y980=ru=D_NS}$nWkuweY)Dj>rQ@~)dxb+mgs|gVFHqVt7C)xeV z$R8~y(fi>6kJZ?`)FjZI^bligh^XWn9yLquT~m}j^=|pP2<-!>W|Y#99CKS-5vFf< zx2InzBL!HxW`RAGa(i2bQmxt=*`ctx~y z`1T81=H)4|vV((%f_l}D{U%5a;8IuMxw7h1#fbx@%*9^w03TJdo=5vP+TKqx!~A1m z5SSA0Tg6bnJJ+J*zB}TomZx0D$<8RJ%p7H`zsG4hsZ!eK+?mWbU8F#1%)}7o^3a&h zu7AH+igt;cE4RKhBu1=zS)z~#T-vxaLeoRZ3oa$Ff|LlT<_xSSO>&@ekY=&8F|LaC z;3bI!fhay+I6P_iPoT9Fi*acW{+tIZ)<+!AocbQAO(SgY%F?VF1j;6#v6~7^zmN%s zTtD+a6Ej}i)B~uxS^q?t?<`U2K6LaXK?_FMAb9mZC=gMcuFS4ge?>IIYYx7Q*5!#i41~^Y} zvdz<^lTNwA!ef?}z4RN$g7Xk?z zTY%gz1FZ={Gf-V`xc>Yw^0b;0$Zj5X+t9#f)9CS-9mgrlb9H=G_9xS!7#?REJ|?2g zuWWKITxJ9!))GTZz3m~g<(Y%6=}$9FRN@v#c9g5Ta&QiCvay-JLg#G6=&0je-bFGn zbUS^3W0m=$s_SfRsa2HM9LDfX@j!t(1)XL}@$k)3mM6K@I~Zli8A&7ubQd(J;ZqiZ z+N=3uk@HxVjh_18_Hg-gh1CuQ6`%Foa%*@g^fIqeEWI{3Ra5g6xPC6J){3btONdiD z#fZ{-uRs_pYQAn2h}mC|SWZrDAVEaY1KqqBguiB2ET!FaNwFn8WiQTZl}kf5uZQxygPO{iNRTh+#7UrjH7C7Mw_+ ze5HA=KOC6kH1|}lvw=o|OMkM=4{OQ$^U)0cW;stiU6;xE-9XcNep8Iu+?oD@8)>ta zjDZ14UHgxk+$EqI%SseMk70>O3f-`f-8f`*dZgRQQ_!8BPD>a>tHvg^Pc zmN=cMhcDOpUOvsA3*~z!MwL$v6LCBg3-Y|8kv@G!kW;AAcn)RSV=T<}mvuc$RwE-v z#v(7+%{GjgpR6Pt?cPSHPFD+_mw518BtSig9ViF+?wmaiz;lDpSO^Oc&@J{>uHxWcw3g@rJ>%Eh$Z`k^tbRLh- zDG8_e_}_!Z)dn^lF#3>oFCxN8e#Qm)D(+16Ap6fVq%B~^j-}yZkEa@o1O~6srsFy_m^aPP7 zueO~Rm4E??E+zm3}OdKrw>A$(QkYwPPnI~-3@dRF*5Vc%@}pAo8p z-zwDqHMsC_G~raA!8F=sq|fWE&v-5Lzj9j-iS8gLcLuD9<<4 zC-)Sfj!qQ_z0i4y-`z%wU%4~WF$mD2`U%WvFGgj#oeT#d_dEsR5de0e zOLr-&T(0n2H5F+n!@b7gDpfAIn*6n5C1?@^V^j%#>BvyeJ#fm+#ofuDpGOYun;1)un-@+Ld_Nx4@!{b3)!*Q-ruX!TZ+i3Y z{_@+&c%|3o2SWq!`q;RQw9<<2%~}vq()K_$d`Y@WShL|gTJ1V*fIeii?5R%QJ==jw zijD*v!0GQ)SM7gi;8q%G<))zDwOwo?OJ>2A&kLEJDl^HloXa&X^SiY*wTm3E=t%alaVD)aa3(+aW zNx)L(zxyv6lkLuTyVf*d&VK;=Qz7qTWYvWhjakb)ZI1#WkPH2vM*Z4B)lzKvdbjIZ&`$q)#D&Q8BG0&mujg zs*Ju;JS=D&(NOubuj&toAlq!A04I+O1=P~U7IwHelSd|M44|a$nDsWoh)4DOk$*rH z;JU~X;MX`a+Qx;WwRpe-oB6K(zp?OtchtWD3avl+6%pxQC<-8lVZ6aq{)LZf?b{mt z^X;DOfVp+zcoyn7>S+?>o@oCQ9-x(eIdFbZjb8D7JT|qm8m+~WhzGP=-uYaz`S=|j zSw20lz48DuA53(p0?0K&M99C^UXItgPH#7H*X}+59Q$O+Fd^g~RKZ>>Ivr``o)r}M z4^>`|&hYT?nJq22fNH=%ttc>8CQ?$;g<3PTH?sM>wg-aw7akjOX#EoaP7D0&Cr|`l z=Nsi5kX5jEhSm@Hb?W3je(CX=6+|%f21B4_{OhV?g%uS+lcqgQ4!g4I>d9tyz)}j{ z@r<87=jT&o!2z@0fqk2NBAT|_HahpiUQS_IS#JbB7ZV+#05bNswMR`TTdiMCK-%ij zPRswZ955BgV|y?)&7P2MQT~jWr_JX#I!N_Yk(6`OTfd z-(U$sOZO)(9btfsK*&2tC`7!0w`q+yB&VbZ6ZzGcjBfyfIQIFyK<0}QkibU+yq%Ma zOSpf#;`O0o5ZDMv$Q#SCu&|Ju4XzJn7n+?c{>@PUsJ;4%;&N}GMh^6G(Rd~ffq1{> z7{mCAhVwnGBQ?IhJoXBr5j2H^oXLQOP;a3cg|X`M>hZdEtFc)=iZ*LL?&=L}Uo>()%Hm%DE4)6fUzY&am zKEgbnSyTkGJC-JBW@h%+2q?e)bv83UZ=#L|BpLR%Cug*}Q&1%cFDoxcDG7LzQBzf7{U~7-7w?bF-2)L|< ze|shR+pAHkG$pImlE2g8+$3VhpH z@`b1@k9?lzeL}=~fmpKo=R21zYtPdDZM!H$K6l-Op{CYA)EE7AC{gV8&$@1I9DzYW z=YSZ}w^RT@y8}^f(Kxo=9CS!j9tL=ce85}J@;iXu4w~S?($bPCx+Bo)W4S})$vS87 zAqkLs75~~R)^$Aq^XzI`=C7bgz2#!`TNtYP+Wzi#LY^1aq!8%Q49LB1G(af!XWyf%ucbn+vZ?BI*+2^>5Y z0K)C6+b;f_NYGsmC2!Q!7LH-%^w6r5{o`=i`L?lW%Cj$dg z0=-tY?JO{a|KF#Iczrp2?MrCCB4@`#Y<)N=d5cCyhV|xc;eX%n^8`Y(egtTQaZ4l6n$o}N6Pfa!NMEHF{U!wRAZ<~KSw9fN^%3FAzoi1CqATYFDp#p+nyw^oC zMzTzRw=Zt0bUdKjJ2=?AKHtKbPzo6tk!u6K4=*kPY#suDwQ1isD%9xr!k)9?oLu<_ zHUN%KE0Vo-B-EXj85MVBs;t7>75FH-q_dt-C!CA7_v}Fwh9S zW`W)BJ||5kD%bbGA^WXq+;+wMf3N_;($$oS+}ziIa+*INi1i1EYtpwJLl|=2OtZlb zzuyUe-Yq1vfg7Ug4ggz1R0WG+lkkghYwPNIa~00Od{v(& zaDhkd>4BnIXtX1x*J_5SS(F?DTuB19{Ic<6lk?|c7xKr}Z$ub;Kw9e|py~3y?x(Zvn)J6bQ`Kic5^UUm znbOJC`E)gnRSyWi;NIRahIaNtH_wZh3^ENNAU-8=lmF*Q>MdIW4S^p9-CGj>clfIM z|9@DE@7+GT12HlkjMjcM>p#8jI=nVfhX;BlK{qxGd%^<5CMG66_sJ_idcz~Z>(R20 z(wYb%dw1w86#X!i0dgu>Sl2rCzM05&1XH1X{AT)&jPv5F4o_-hk2R4?0a{}gNWfUZ;~0N{2a0s(Tj z&Gv*6&oxjkTMnTy^Py+03df1FoIzB=u(!AOPaBH1jCD#R7z1{ySJjV*GMxuZPi~8J z8;{|OYSZj~nBCo*arc%?OWon3h%81>dU4+UVaLZ7B6j=QEQ?Nsg%g7zHxw&xIJjgD zxi{SA$HXK$obG);4Lj{+XhMU^8Phx#npJPMCh#o!e+W4i`-sGdYY7o*R`VvqoFy7b zTZs!M6*g)zT&4PhRhTpupclzXD!lZg>@N%6r#ohZYs+Vlr4Ms)EaEI29P>84E-Q#E z2dGxpn@ZgRnM?3UE#H_;=zr~2@~_T@7PQZ^6;z`FOBusVsS4k25xS@&m<*OD?D=;MC*FujJiCEs-s?nU)SOc+;gUJJ=O=cL>X`zjp> zw)>tVc5ZJ5K)UPCHKp4S+SRaucZ}6;!5Qf0+C2tg6E@W9iDlX=on>kk_@c7%UOE1& zB`uks&Y(dtL>?N1U#EZd_J2TH+2GI4+-};Dol9xZNzF%b>fA;%!+g9ycycm!ZUO)M z(M_|MRaLd+AYsV0C1cI!8)c4seL+`m%a1^?Qj8)-Vq)S_XAKPs>gf?* z*jHC>?wJV%UPTNp*Vu0{c1+z=4}G`_r#_hD@~_`fk4-47Z0HP4pF`7MYi;E&bY{_I z7pI9ts12#=_SBG$hjlwdlvZ2%V@ng-K!CZn9GUPH$n!})#~>LEX6oTacq`MA-^6_s zyDQfXu9D)LkA;eHdokso*k?jfm8g!XK75_u2X-@nRxCE37#9~nJByflj4h^BX^BAJ zlu|`O&*78Dtq3+uVg_zPLw*ma^EjTyRsc|5eZ~#^=3sF#hFvk|!phGwdw-_q*3X=+ z`FfrP@D?$QiiTvD=L#I3{ICwp1dl`P2VaisW^NGHPNhq*9JpX& zbfh&5Q#2|d7GZz_fTsFT)fcdKyJ@{t+UY^nXk`Ew{!*1t`uJzXD%F4!fa3{7NN|#NkbIB1edHXiZ?UTTo(p7y%zgvsr${>@a`&1A{ z4Gg;HH~UAs)Th;N1A`14I01*w>+?!<7YlkB;Mdcxc@^|84hy4SHd^ZQ!KD+>d`_M* zx$6&!l1nuMwHB@)l-zbDRL+0)ey2X))Vd=ZF4V4pO5piDBwOPGd>4BdC3UG57R1XA z5!4T5(tv^^c7M92_@m|%6yAV{fWS@T%zqaRZIe&ie9(M+jvsV~=7D5YwQz=*D!eM? zvZ>`KJQ8qzo$`z84`@g_6iR7zb-K%&<+ri#bU(7~GFh8-@1PcrrNth~ZsWtDc4{dX zLqv;44f+X`#)P~MaeW$XN$0nVGdiAnD$Ew0v&@bh^{0*cfo;3)*=8MhbX@nQ4^W3o zdV7xR7e;{s4qr;0JkBlWO{bV|yiP4#v)jNB#qx(o5O~>tz37=*;8-gD)bNbJKke}k z9ERbGyu1V3U|6IA4#41M4z7LfFKjn#0`fy5rYaX>?)3G1xnU(1Qfw$`fYIjW=Wk1kA8d2-U-xKNQQVeoBQUx44jrDgbDn?tVULXN$iHk4z|!w+`8=IF?#ec zNG=r-f}%2?Oze0>xTT1v!K-m8U?Hfm0?sGAvs%I_YxU_RZWzPL#5Ekx%kTcq+<&7xUd1_M;WpILNWHpK zFpgogyQ4oF8n@x`QYTC`M8_`|WvTWud|7_y(G42~9?D18vEOk0L@~Jd)W~#}es#Nc zW=!aVr1%Zo$3_thH+N8EyS$4h+x2Kc>9Xx?nd0;va_u$*7%w3`o_6G|w;q}qm-8x)Q!Gxy>$cy;{P5{7(&%d0k=NBm zO?!rq_St>5_xPr}20>qNt2htH2ORsQf+8P3NADyMN($WmafY6kwD(uW7)pI`(!A)Bg%Q3BfCzg3~aiJe=Lpz8JF9~UsF|uh%VN|>m2zJ zOF49EP-kqk^XL)2#E`>6b>8J)y^gpmehZ3x0vtKr^Cp-#qQ2WzAISAQx$4hP7xJS( z#~l{g{E?meX#*nxj`Ojmx4MnOD6}Rz5&tP@saC|k%y;vLmJR#)D9$fSYf=X?T&Bc` z)P;38JRZHuf-l@MY5j8DP#msSP}8Ql@N$o1$d6k_Gd}1g5^@SX!QeBD-s|0F-fMr( z8hOZR5q1`M5eu)Qb&i^XkAIoSATMA%yQDSzc$G=_cyBA(%owVca@sSuJq+aaRhJ-S zeMRQ((;7ZWkZ!Pqf$Je&2cJy6*E*`DCQKu3Z-?%2*p&C^ZQ8}5l0yzaIafMIUvX{z zW0n0f|5&6mJ62CB2p(R#bw_eba~^97O^uK8S%2BS5OZnibiggH?CES?qmGn z2lUJtnUK;Irtv(^wK@M&ksQWrnKp>?xH5>zil8{*Lnb zsaO);60%1o1Sjw!l17$g<9k(i|6(`uCS-;KPdQECA$uWmq{z0rc5NPG07)v#Db#rK z1v_5FN!30w52ezi8uLtc6~#|#sH$z_5x9Vp+|*`ownD~VY(`15&sMXYE=@LKxTl4dR^HuGt-jh59>VSo zn*Yb4ndjxZrp+${V{B_OOZj++1hQfq(5dYPt2tw3h2o7aoO!60eofAn-@Cv4LPQmG=*h5-+nFNmgKUu|kn4)oEU`{o|z?>HrjRMr?qu%ES z7|pmkiozar`AfkgNT|cHJ}!*6QcKX0^YsRme~j}TcOk(I0fe(32ai3ylauk&=@uHG z@2!n7%0zZs>E9}>V|%kQr?dw8?>00Fe@9=cO0lX)vckm;TC~J~0d>K+%Rih-;Y-XA z$ly_ykAMWf-s0>zOwOwnDE)=!kMue?d15~rrw^2TgCOv>p+{ESTsXa48a`Q{3Q#U~ z3~7~9zC9b5G1g*h*Wt}G)ymBuRf+J;%jW`Sz#8+@^xXKbv~%*vTC68^&H-n=>*SeX zwXAx&7gfwaKB6cU`=IbORCN=pT#~f4UwhePt|ldFl8wY$bN?Q@=#oHN@|4^WJO5?Z zqK&`-ml%bdJhLV_iRbH6s7*YoADsEZR4bD1)O0(pZ`A%78m9hP!3F0l7hx5nZ{eu* z@P(z?cM>3fBn+{XQI2dUj^m^2mpeXw5P0J~m&kXFy!;2rqC>-FiYC%Dp~4vyb?Vn= z4B3PkQ|-9BV-Uw)xH>lwDhfzN=#P#*EytXg6(Xp5d#U>wl!;Z{sh5z{iU^3qyyp=& z&kl{Hli1qR%0ENDUS9|=V8lo)cK;;!o#ywc!8(Y|qOKC56aEdA&lyaGE=|Gz_W)yp z-_ga?i1zn>+~lotBWnY3`KvnsR6-`C%bPlCXylG2}QPpj^l|i0?DoWS7gsn9jr|GhRzDH4UYWPZrXhHkt;}C993IfU=}~~R+kbA~ApXA?{eN!d|8G7d!F}uUQ@g~&By<#hFH~>RL?RO#)5nY5 z*8Z;{C_6hxtii|X{`Wo1#Wrb#x?6?iN%6rIZHbaq;l2TA|!=KoRjXg3N z@kW%j@$f8hGGXQ9h5Oc_jFFFIQJHtC#d>>SQ{|r-Q&21Nk#eftF7`hjTz(Rr)bK>- z9#Nv8>45D_%ZWeYR*Y0;FYmz`zZuAjx~tF8iVtk-*;DIi`=VarP9^1uH8ir-^=-T<~UF@IueMjOuA^VJZFLpwRJr$;e~-qlf} zMe)#O7}{;x2526~jvpe`sp7Dhg6jB;B2Ehv81Eo!EF_0M+zBXk-_EkB}+ zuH4cnBfxJdiOvSY;;p!``9NV2{i@mrARnVTX!V(%f-^h5=JuB-2koX=jOs*%jnO_P z@ro&MGwA`en~+LN@rB$H*E>29y+KLq>Skn+aNeDwA~u`Her@l-Ko zU{38vpWnbPC(G&N25J!P+kw(;WTjm_lH|z?Pi`=z3PTqO%d;KFjnc7?8bm&rR78*F zSLX+Qx4hY6DykMfcKGj~1gSpoc6le}tpKgX0KI76jOIon7QanfeZZN?N#P_RAFyVZ zJ|%H`=)j)m6v^jcUM=g~7>404A#-wjiioY5VuRoN3ipsSaiEWvX-fy4PQ=&GA+t7Q zm%HuKtWI$33UH!pFXlhKaZ$q+TfNumL zFS-Qn+DSvaT`55;`l)r2i2B9-gK= z_j)n{2xmXfGq1FOX?mF+MhmfW?vhk_M&rFG0uA4UC%9 z#}A2A%*eKoxequv{hleZdd*xRs))~|>83r|NYFbd$dOsuZRjeiA;vrGLBSEw{yq;o z1JR*%55j?RO!y~UZ2Qs-FJ=E&E>v_~=imT!)$HI3Q5vA;7p7KM!y2Eo<-qY(wY5Ne zAQ{9;_bqk)VP`15BrxeZ>4KymJs2BW1R5^L6?uDp(ArIZV|j>fiG8P*>n;D&!WH-# zlE~kN=U>m=OC4ZZIlE1ntMhiHe;sZ*Yct*Vw-iF07{U@W_grgXOnRa8y>Bu*>xrMS zkKSgfX7v zlusX!PZJ$P6*zYFWByn2`u{C9k8#%jZz~v?%xyhNM`^#5ci1{|ls7)2YPlZje1aX< zdw0*;OVt%5V$c3->S_ero-M`|`jwP@xInzmzP+K0E2_D4I}u5%pb=0}L3XH7;_zrd zd8_72Th5N1aj217qKN|EMj>XEH)HORQdxQIvZTnKeKFKVKmbQ8JD_V5e@4&Hu&=F% z++cZucmn-tR)+mOtCefv)s4v~Q>|)bx#TKnE33Y^US17SVT{P$!ylX|B}=@h6jMzd z9Eg`Id=H$CG$0t@e`0-`c;7dsh@wlm?&4bOB3gPO@lYxWGRQ&x)4T1YVf>rL8~NLy zgmJm`|6vA<<^o`t@Km|Hto`_5BXTvrv+enOrC`s`E*9ov#bzxZ*5bIPO24(*(bPWs z*d#*iE4`aBmX@_^mhML-8v7W@-FI7}w0C$b;c~T2*}pH=P~0qgN_|uDHwuQ}Tnhs3 zEK$!J_KqBS;QT9FS6X1@$W|O7BW|E*chTcpgov*%Njz_Xk%ZQeiIP0lx!OJ(G*P*8 zOsRwY$B%A17J#(#Q_}=w=98+$98rPCq<=D9sx8dA6Nj&>!<#4;{X?egEzxP8P@Cs>E98e~k^uygh+Ncd!T zvjj{gPt-+3M6RRi+6(gex3=znmAg69XKsvzdoW11OD`SE1p$xZwv1jrw)F1g?bQvr z*}fH5RGQAo8ynP-V{3lVTYJH-A1Qse^O5&#!UbvRqO!uQCzpNtlwiRrTTA@dSC(9d zvwxyG^06$3w1jOnJx7{lS3$G2#$)({&VcFeRAQ z`B%Z}7>MLZP&zlg*$Re{2DF_p^V~`cvO3pm5D=05!~?RahzS;(b7CkQ9bVETWE2J2WjI4i(w#N?rcGh@{iR7l9+8Uvf*i17;)<-XEoZ|hR-d8 z^2?)4=IWt;*~jYuS5Z;tUGwn8m3|Ai*|;QRkJG+^ zAt17>ggGJc&S#wR#m`}DVSmChPZL{uiP2gTglz?SK7E|-6z3C1j$l)0u|UHKcNdJy zDvRafsopyRw2T{t(QCP&X=!$095I;16-rk(skLKn{X_vWzPj`V9$`I)6$WlI=I?%y zs5#Pv0U9Uzd>2+QGN7>_GsF5+{X6*`8D+57$^e|rbB2l(En^F@*=byrg( z$R1FliBIqcU}WR6JW{6L_v#Vk*L~vde*q2C%TRU>tGPeFP7cq&19MdjTcA7ME*tfa z+o7IQPt7V<==mbn=zgrLv5YZ~7*#?bAImIWUlYTQIT4)8(-RZ5FxT!k75ag!h?IYR z^!1~S+OKK^c6aIL5nY8ZM|jYdgnO{y@Duf)W^$++0E=+vsI~r75Qn~+iJ58>p93%6zh;#_esV_Cr^)pXY z&`L zD!&w&`!V_&BA>2`(T?I0^tS<(zTN{M$((%t>a-0efX(;7b*OB{TOe85@kd$jCkHrwwff%c3K?>QBopMV zdAIek6`^nxV87dj#kWVebrH|o8`J~-W5DMaKba{n9ACIFMY>zzcDWuvsBRb%X@Z6* zF`yK2TI2{FY|TOc%4+qj#9`fZM!^DmR>k2P6tRWqrx3j3!_#nzQ}siKU%g_+lD!${ zs!0HF2UKAZ7yNFuVvq`n%hu+{>ls||#XM1!I@gy~5BmR+5?7gyod(mB!x4QZ#;QKb z!wnjjq}V2m4HTT;a%4XUYP2nfYQc~4eCwo1ZcfA1jEg--MBXyfp*&^9d^x=wxLoqf zjuNj@W>Cpbyf-|hyO?TSev5c_j^KMSF z;q+KM1t(8 z(XP5n-rn!lVOz>e$M0XCXq)4^$HUjE2|vWL(XwX?lbMJi~0 z2wq2z+wT@RN}*G6r!)MY79b8ZrY(_lq&Uqza$+6#jCtI5G18vZ$H1J$Q?bel@4KsS zLBG)zwd8_N3$N8Q&9$)WlGuwSv&J1lz zLpghowsYjJY9-Xv(Jko9f78&RE4ymaRSf?Lgx)s5X6lz-4szzn&5wVa+)i7pdF;bJ zfMRov&Ih|EAW|bxu8r0+rfwFp>Rk4>KmmhwRg870dT~z_G!Fifs=TNG-&=6=YGn-`R$R8U>?oV z5Gg9G%d2;}KG_|!YV?G+Ee3s*L?~8j_V|-CA)gf6KDaeWeCqRPF(4&2{qd7yvBQRu z2^m_R5bwmURXd-;%(=?KXG*~P+^tx@GY3yQa%HCb4{X@aWYl0u8CQ)$028Y7T2usd z4kV4rJfB9ICJVK$G#8LE1N9it8Q0)p`5P-8+4{r$eCVg@`ECnt+Gx}y(c`M;k+#ad z7t+LZ25z-{_K~I*?uOYIJY!;)+FxR!>-I#T3ksClXJVR7ntMS*@BoWM!Aq4V^(QI5 z@idLb?2=15k2Uf5IH@ZL;aOB5bc`9TuVYC`YXYRn zk%Z?O5A;dK!WlyTV!?d_SpsrE`YsLv$qT24+Eh@ka<%^`giy(#jl|nk^PMzF&#n71 zo)rkEaQ1mNmtgp+0ewV^)~DwJ3j~hjD2<7}=P9I4?{@|<5rwc0X)w73B$dIo*^fab zg)$b_lYmPbV7_dFZn@19nYl#fW9LwrY!p1|NWVR|5MG*K9hp;OkA%(}SZqE;GRrl|>94 zWYYMOu5Ea!!r&~`!u%mo1(pc4X)?f`^S0~eP}OeYO7n{pavcw@^a24+4)^NJ_L|r;U@gP!672IhN;qU4o z5?djTTSS-J1|1yMQb<{}*Vfn+tA<+UicYcG3BNJjeQQ~UVf3&reoG6*iMi8USAMa& z|8;eU>^)_(`t(l*i6KPLff3+@Dlbib$Md*b^NpKm?C)#5Xrp}c)V$C9t;Z>!wnbXO z%~+BBI4ume^4=s-d;8|VK)0f01Hn!Ef3}3EnTwHs4FIL)J>q0J&&ZC_&2z%+ILIDA z^6At*)Kgv~d>HK@?v9qMBFxyFm`24w$y}LTSHAz%zVX@1M-?iGib52vN zuD(j&=J1%z=5BZU;l+jM`=)+47PJQP!oWmMdnp3BU@dh_T*2^|^w!IiK;3QTfLFgQ z7-%}RF(1|4-CdGf{?1Tf({xbxI}|)v#cd&HAKHBr$a9q?ABiAtT%cGdnu9b zB+JVmK-*~BU6`3kgOHhu-7lxf-Qw{yxv=1W*FYF96Q8(vx=Vq4*O=|U;Hat!OP}lC z#IyFZSlL(~dFMdZph`Nt5SEwsdTMGtsN0|1esB5Xj^@W&v;%uP`pT0?zE#(^L@rY! z`^QBBF1{DttkjYomX4tleaVe4WTP@ky@%C=b*@fVHK#(ds@y@5+BCMlf$HHIJRuEt z$T|saJlxB6mp8_*&q^`9eF)^$s$R&C_7A5RMamhenFCAyXKhkZ`s$f|*zUFkxaE&+ z^hrMo1|}q}-*$!b(G`+1yX1VEX)G>UaW|xo_(6=2s2+cE##*+gK3Ws&`ak_cW5rm= z4v$xIfm+QmlQSYuPsNx|Ek&P~LY)f$O*~#(hXRP#FE>^#D4nzJyR{2+hS8&=2L`Ou z!q-idDHiOKR4CRwwtig0{S32Hk-#11@{n?Oi!(8*a}|w)g96lTK4Vxt1aNRKNOLuC zDR1ffqOzmwmK0O>bomBD3$plrwYiH^LzDVrLH{ytoHH^IIB2&MBhi<%L3#nQwlC)P zC{&|4Rdva3s1h4nOa2aU-?c2yFk__2yd37XUReWOfEh}QJsJ2ALYjm2(g%WhWBM`1KcXtw>m>B<8LN|wwW%L$f14F#v`Z|DTm0AiY_jJ~}8aeSy$;KrJJCCc^i>*10 zMus2osl9)#U3!07=Bz^Q)w?4xTxLDhT(mUx9#N7c#j1>!2;&ZYr7f-@|i zgc;o< z$OC*rDvnli$8=SqpT_w}xIZON;ddR)q7dtzAd|1I16~`fto1NVDarvA!1>wzid-Rg zc{_VE_zoYccO_s^P^LgwcwL25tC!>QaR!ysc6@RqDfP*?*oBOiX7wlDL9?F}Ldvw1 zTRzV~z%(agr8KIF{$pB`s<~(Xw2?p|)$ekeoaTnufDO7#(_8ctq7m+I$i;0I?v zxvN|w;B_f(jkPvWEfW|~x2Z>M#P91Lr1H=}*2RXG6k$^snDKHMpWAlghmDdZC!@uO z9F~ra%fFOcc5kX{TI-=YFlXvT8i;~4yliZgZgvYhq~>z9uvm$?7b@vWvOD9)^OokC z#$tIYME`xe*@GIT!2Vdoq5E55P2wt*xlQq4j1T(Y#E*&}OqiP8ly~=H>;Q>J^Fn;X zS|k2iv~6Hg{Y0!1bO^vLbW+;wzRoCC$XuqfL4am|gu^oohw!VUeAP&=IR_! zk!>IujL~gC9q9xY%HX(M)`pavGfkzgpPx`v8iIr$WPDej^dulX=<5QBG2OG(f(4mIh(fO$fU4)&16cMcN&T9ru6!C^LaMDmpaEU& zi^^Ok#U8C0J7XaQ^o~OdZ}pySt4Nr;Z4Per+^8qhZpo5Le>d_T(8x;ZWu(`FC%4}b zJYB2R+8+Pw^ae4bN%nkJ-AZO3A)x8c>(CoW^SEP8*=i>Xu{EEWZeqAA?-2 z06PD6!7$P@mN@B4^cp`i0HV9IAR6(q34Xx_Vd=4 z;1%9rPZ~KgM+t#7ri~1ImR>O2A)1@`e&Zs5*49 zlRNepngEg^S{kyvWKndN-ZyNRx~`AY;GRs)y}5?o6H}SeWNMH62v*Bo_T>9xmpU$Y z)k0J=lm-6wksLyNM>Ti#BwU(rcJT%K4(eaGa2JXuvYSnkhR0O(s=v^)x2CzW`)1Ug znJ?nbiwp7klUIaa#^bx#)+(AS)Z}bAI2Y%-u(x&39J6(u5Ve=JnCUwx`hfNJCw}W3 zxN@2i(1Rg+!ssIt<%|W$MOU3$v#fh2jjkjio!yVFWO~Dd+R>v8G#F*4z*`+dC&An) zWQtwN;a54^%vE2##X=T4C_S{ZzdV*Rno9+=ER~sUtRbsi#b;P~RmhaE@;5PF3LC?k zX|4%)+MiuA(~v@2{Q?uE>3+N?@fDi6k)mIs3U<$~;*;M8euPiN{kL4n=&IjLnsZ*N z18xS04r}7EYZvXEJ=D7nXgvR!Ww_-YZ+&l^3fqcOaPRCna|WT2mRl9 z+%YjR>Y8i(D>;eNDJslk0_6NvAGe48D6zAKYqM(G)UFZ&O$YnKaCuUhED}`;zZIe6 z%JD)o9amGBf0ZO0TUC+Pd~A70;Uey=*n31Fi$i7ZUu>Xo>{Es|sG*e56r-@kuRqBq za`3d6`~xEI1?ejuB%Q>&XOM=0YxW+TPOrXh<0xM7Xwv$N0NDVAW}Bh8LS(LS`9w0q zNuLY$F4Z`OUf%uz^o=@Z%b=pp&?NY%sl$HN?$QkW<*sYSt#Q}pxQBK-8a8$cS7k&s ztUwRDRAnMl`|#op_2JEG;d3pt+miz5Vs?ZcIJ;!OB$1AF*7ZekT4QB%D~u6aKRc_W zj`f#pJLhx0pT3Xr_??32`Mh8E%m`aFW&p;V2vv&%@C1)}ww}t53A)AymiqkQdR0Rd z<*L`hnc>xBN=;|L`x8!Z*Wg)PU{W30_szmKVh+Z1@K%%CvYiD3(^3O zyME4~E{u;U>yUD>Nbv5)iR#t?GKuIU)kOuo`>nC>;^A2_sHm`AMMgD3x`9ds!EPtc zKW2Z;ZBDYM#HmIaSH8xfYAhP{=fNvw=x}1>H@6>CbSo6p?OBdjjx*q2*r}KA<;t9E zoYW{>uNnY})t*hJk>YQ4?|yq>IfrEz*NM@W&9)L3@!Y&@VUFg`GBHWOcJ=ifYknog zKW341Ud~s{4WC1Wb@#E+pv1RaGE0|}PuLc+R2b>J;t)A=RulvcmO&&}mAO}KiO6G8dojU^C@`YUG2J#<4Z z#)xNiMm=%YG0O*gVX1a!E)seZHuJO(6i|eu#2l5o>8@%lw*7*~JSULV@3ycmevhdf z`O9z^`MmI)FowDYT6=}!4?7`&{v@y z)2?jZIHQEP6&?WHimOSU$h_|lEK*UtqbI$AB&`7ms)}~P^jmup_#W6;C6D|=zRzrT z=)G@dy<|rh``k|w_Z`KxG+}8DTh@@A&@+zJRvcOGvFSnfXk8;Z$A`g~otH{n{52I* zdcz$Vt&xKmTRSZu2h-d7r3E|lH1_vF{=jtuJ^Dx;3<9``pDpF~uylEfV!j9e#G>UO z^ds}Ik!3D*45h{IDbPMpaaF(XLTfeIeSTE>^pYLzcHa3Wb+F2rw$2|?v=o8=gPFap zFzeNzN&Lz1DNmiwzlUX}oH-k50l=#kPp)+Q@WX ziqP#?i={0=`NvMA#&0a2@OQN(m2ItGlzRbDiD~!o_<4jyz-lNcDAw`Z6)Pq(? zX$l5w2*Oicw_}9zWnN~Nh&dpYf^Rj*tX)XJ#`ZpxSS8QfU6)<#wn3r9F4E4B4jk!l zp@6rTGRkeTiv(aD2yx+_!6OEVV7T4IQ-3?~9TU+nHVBZP`8-iru_?KN-v@Uw4V!~% z^?Lme31^$&HxJis(ETf%jmMX%Oeup5K!k!L{pR%)-;eK&gcFrSzFgauN z&q2wFpB`V&K6p7dzK~!qN32SfWi5mg+FXgjY)WqQ(nMJs?s3v)`EYCGw>8FDHOnZ* zgM;#sWvm7=eY^b>MKLjDMPCcrWz;&@s@htLf>w8r-k1NN9_=Is>-664IKibMa_D}ET!`yCN5Eexre7t*NVcdNm6*>wLojGrV`pP}yYbo*X0CB2uL zv0H`~i5IMI9@y<35jJ`<#-IayiRL#LU>X6?OGQ?WAySdWOQirSgm7X~o3Bf2AEkw_ z)v}viYA>(VIM_APt=3HaZ@W0d!+&($%UlRuY&eka!Wo|U^@Ud*e&{q&kBJZkfOP-d zhB7Yt4^~lP>|zoOI()-dEuVPI+*z4I*^)_*$=}PVy0p$7NqR2q1akFdKF@j{XAa>^ zt~apNv2xsHWR$hcE;>>R8~VIFurq4we>gB9V`NPg(!XQ!5H=h<6^_;J%D`QjT1h)w z)bO~7p0;>0drXZi24^0O4EotUh3^wm%r4b8p}m6-f|`Rk{Frwf8O|SQR<}Q{qWvi?_hmD>YfHKYO`hOb!9Mr4lzVA9J~-|ZIWNTgR0_seMl8;km%gF zCO06F5BIWd*?!}c(n%J~&XpWN87P#u{joa4O+D?d>Z{0y-6YJ`sYxa6b*UmfPy>8; zNr2V254JaXpEs~0Ockm1T$f4X>sl#?lD$|8NYshT5axMnM!|4CqVE7(ueKk|*I3pl z9$Z!BI5NJWr^smR%uSYWy6s0=fXS)^ zSd5IVj(ywwIBCTwIS@JId=^;QsRQOyG!4c+&TeREPb!j-F?3G`as}eYhvS+ugd)hE zci%-^XvlHa!D}yt&P|B~jiC^1VQn0SZ>`gwy|f_z;4ls3caabm%B@Ks7{k4ee!HPI zUsD>HXv0Q{Zd(_GR7F$sU&zfY1*cdhocr=Z`}!rSlHa_ya|bi_;pZ4~b|Ss?tFQTMMExDM~#|NUWl# zor;&2CsMxdg4qxug|ulcWiHF@Vb||DzwyQnB-?WPfeYXFO1FiA$P&BWg8QGCfd`il zq23R{hMsxsaDmOAdD`~q)V4paJKVxfHy1qfWrw$zG87ukXCYqK<<->Zb_af>{{R)9 z5`w^dje~xW;j4(4+U)kNU@!-c?EQOdSijaL%AC-{vh+KufH9RYDK{Q3@yLBnpR=fa{P@etT)@V_;3t_) z$S%!|gLG`a^H5QkV;7_&SV^`bdPd~rzg=7WNzwpGYVEEH(|a#1j-chz@U&dV?K zoDj@-*Z0paenP!>mD`{;J~CfF%g%RVFTHzY7G9evBW{iQHo)qvhJ3Mdp5wcdJT^ukkY;LReBuY85?Yc4}UiOwpyC zOg`zlZ<^Wv68~i`hWm>%gS$aIB?Rl9DAO`_Q2DwEf)gvbm+9g*gTcD~k3-)EMBSoB zcY89*r8~5hkU*ppc4mGW08fpYtD>N`?W2)$D+UrSmM@*DRyqk^nP^DdoodZ_dh?7Y zC|-V~t_-fK0PFsd&_*xOM#NCT3`}V5ROy*bPXNfk>FNJzIz<&(i!)anWY*v+qme2* zaF$g6Wa>a;N4_TVWr~i4RWn)oYFA%DOSS}uBNSma4KHedv?LU1GR%?TDJDb zfYUK)twohV)Rq>vX)Udy#Hm@?-=xeRB?qA#+!vulq6mhwN|S7s%B$x+CD6FFObtNA zyZy(PHEt3+oCNe$N=yS@VM5_G5zQpiVZQG6+368WZk&scTTac%^xxvK5KTwY#nr6Y z`Vr(Ptt~WTmx1g7or&a>Inodu{sY?vWr$pm@vcjg8k zoJmbOc5#u(mXPwqYkw{%4H~vphizei+>7x_EdW25l>{pD_46_*K!-5!3ZyW%#GH|&~JWaJy=t8_As#Zsf@&4 zeUL$@t1CicXn^1Z_71h2h0u~Y*= zu>dTuprfiML|9m36GvIXmD#_0P*ZXiUn{awb|<2}bg9zg09}|)#Z_uMSXOvA)qA8Y zeM;Z8Cw5;|YBjInna_=!&1tc1WNpPFq~@Jq^JQKaIUydXwa{6XfUBXmEv*EdX@PVd zmMEX(Dp#$PolPl~6TIUh7ROS8$UFu^89H-$K<80aziU?kfe{Fqv9Xl=C3odRgUxcx z%4wzs$iB|dB|6Gl)U~5H2pGJ}!-G}SYE-gx;b$h+9fCBQ3TrrTns=EUFH_e%>S?D~ z3okWU6x1^#Uf1I`BFzBEy*id1);T$#*8j8s(sFm5(;oRT=*z#OR&Gvtn9m!CYJI3e>aARVpdIszpjc^Xely*)8kdS&@y9~-2-8LtoH|&UA$6Rrt_)4)qc)agXtdObp2KBt(S&8U) z{B8TGiqG1Imb>MVuZozZK=oMpsr#g$)lqO3zIQrH4 zmHkhNQJKwBrZ-prPI+^$J8+koC&OumZ(h@n;JhlWxEiXqNztyrs?nBE(a?1ZGv?q3 zHLMka>KS;7k;Kx(qq|)x*Zh9J??t={on=NH|I zhP(uKFd)@aoP5{$yqvG?7DL+F?e(*uGHwI908J-$<@NO=W?eiFLTCj8?pQdPd4)!( zOWk4{_<)DBp`MhSKyiOtYdzHG>RO0~Sw1rVp}NXIQG1&Ub4g}YT@q&Exbctiv`Fbs zZFfo~o>BMgpm7TfY65O*wGg^6asNgYOo=>qZ*o%JxR6108Y0_Y8b=+C9dskLb&K>0 zY<-{;o|og)fd0r7AdimBe0HQ#NC*^Ye*Yd<;T~vZbI~*axk;;7A<16sFY|$p-NTPg zZORh?WxJ8RA?NG)p7f{-{&gJg5sWVL$@k`)d&+O6)sF7GKfi^iQ@4DPvO-ChrgKWV zdnc6?4xG*goDQx0aL8|>}<_^PoGcK;s zZ#(_$UlST+faG0kxWbI?igorVGxLnLnl85=Xq86Qo(Ch6*+*bc#>>7HH(YPPu~|KV z_6=DtK{F?wdrv^OIQO0R?(1UTS?Yq1*Jn|gh^}q;Ek%U&(tJjovB7A#Z`FHu$S;3z zc%x`057pnxf_QXHxtMVNI6rGoH&A}XL_t0^8!#Ma3Gz4>EF=%Nas%tC{(YltHC$N%T0t>VH722yqHr8x zyh``$D+SJ!Gn(bN-XB*jED)ZKx7mGCPeL=*K>>rl1$v+MmsuDJSyK&^Gx=FGBCV;i;RjXBX%Sl!;qP6n zF)R_87T(V4mDg^pL-yGwEER7!!uGl}^0KEZjk5Rm?BciBat)|AsU!;lVSl(V`brEL z%rHLI53-Zz0oFlc{x+rQaDslj_9soK;prw1nJU~L{%2PDG79}25@Ylq=Te#Gd`Gw9 zkiq^kVhwb9rh_^N!q4kmh$1yxVJ=x!^be057lcBhM$~+b4on!B6XzcDf1kemSP%gh zm41citO#yeH!G&1((~!4Zz;#1Q98hM$dmf)r-p60zM1Ud1E*=T;U~+_U;H`!zhrfG zWhDx)_SrWs7gR9D!njQ2ww^BzS4+#}+}xjrHwZmmURYJ~|KaW@iWc_ltY2uB-P0i4 zeff~V=+J+-`;3Vh3}eQqS|I~I7)CYs%WFpl4k&E8;*97q zK-S*%#Kb2vSRG(vhl{Ii|!?%yoBQ{B!|m^Ia%8bZ2}=i z+Vz63lUXDYM5Oz?R->yu4D->Nx4n-faLm_>#d~kM*A%$ zDWQDYw`wAv>p$Cc3j<>&UcH9#oo(`-9hY84=!JbKZ2ZW@+~DzvE$5k)DN~Bg)^Vuc z{eVGN7gb#?cHO}37n>=5ue~^9%CZ3-6IL}Xb{783xn%P72%%Hv;h&IH_Fs%PUQR_o_Z4!woR?PM7pX(RlsVXlD)q6Yk4JZq( z8Cp;haeTP@E{~SH>FU!_H0T57&td3@KgqD%=>OyR`=FWrrzqOom})U1{PY_(M&~sH zFRp)VPU1Yx7;)*GD&z(4$l7+>18`lA;%KlJ{`vcW31gd-My8DRS3Jnb4O?3?SoT-D zI_B#(gBdegN>I$I<2jw>xVUF$W(R}ox%7G}G45C>);%$dS2N$vk1d2&^!8HFl21=r z!=p0#<$Q6@`Eg@Kv{h&l?HTMW|Khx(=7+Q*W;Xq)QH@U%) zr(0pAC(HNQwf?GMux>YP)J9a#4VZ)Bcoecj5pgbUfG^c1{{+20yfj!y=cQKuUzMF@SXAHM_YDN3OF%jVq+4PTq>+^FmWH8ANg5Od-n)b+0GEj@x{}XR-1JX6iMyVpRVvs_63!Q zsy*ExJDHfiKP_(ZVI&XgMHX2Gk2MRR*{{^c26hqrk3TC4N;I9+u;<}l%<*juCf`j> zDg0p8x{uEWVS1#xt@g!Y)7PKs(btaVtPke-r#o8X(t=wVlUPmf<7N(FFNG6c>cH6+h8WVj(gZ09{unb+b5>1$ z8Zk`0XZ{V@%;?FRIyQ7i+F_c8MpXSN0wJ6lf0i|@lU36^#;?JHGN>5jRsHK9Of1E1(&gq_Dz^K?W_x#iXTKWRv$q%Qn$ zK)`!yyrFQyMdNT2>j)Yx>f)SwGM0>u*($X03LsSdAgG-k=OiF+B} z^PogGd-e<8YQ2b=OloqV4%5@RC2f$% z_kfG$=^h^8D6AtbeO=SLL~F<&H=?|c(Ct74SF!Jw7l$N*4E=~$Lu6brf<>5jZ}4`5 z$!Ylx!~uc;+Zj~&rL;cIaRK4us=9Ct^BDQR;jjLy>xw9-o5e$J_7@2R2A-su{D zRrgr)POh~v`Q{pTwYY_Vgwg1gO3Z4wT3TMugaG)RQM#;xA~|QEn4mkXSWs@uYSjU8&wNvLY9=WKXj%%`|ph2bC7Id`su9Sf^oLoqoU1Sjj$9?~6rU#|EFdG#?JPkQwobL(y;ro? zlZjekR!6DJK#P83%8#lzCnc%|uWc&%ea&1P!h)MfloDE8`VZ z{1T9^dOI?FO^13LitF$9GoiSFBBQv}!BhMAixq}$p=^BtFzsxf*3dMUpAxBLZxlfX zTgvP>&=_9g&Sjz%_!SZvI(lTEmW@kZM(k179$t3p+Ns8`nvI(rwkO}CJ!~1gKHC_C zs8mD9*HKVJqF-UmBC{pM{DraM>=0i2fvFU}iQdz*ZSEB32&SK$+~5PB1+=wFzC<5G zSKR0(lDNq!*lx`Hk7sKqzee5u2N4SkJjp7Nu-_=<#*EtKmhAAltb`crS3L1nho(~# z=92!)$MS#bPv4hFLAjF?fvhA2!=gAMvn9silymiT~ z?Nnt&jPl9NJB-ojT~VG4N&Z~CL7ykHZS#>2>PG?7FN5B#FG#j|qf}8n`Z2}l?^KYu zXTdSn^GEI?;gcSXF1NImNl=pY6%SD$wT&56fX@8*WX@*iBrPj7fYBTWKaGuOHoSjryS^; z5h7;+>@8*AR~o56*?cA`KPT9#L9;hUYv~t3iIW4rV`BQAfi&e&R4qNiL@Hp0r!^F@ zLaf6dN^m_H_ONIAV`y&f4{vos+%{dM2%Wa~SN0r;LUW%Ii2&-%GW(RFVcUyU`GA1# zH|_pyCcz=npiml91`6elLUC}2%*@Og+i7m$>@XA%o{vN9IYQbx8?*_$*p?YEsgHgn z?O*6}UQBG_0u@!5~sF zv^#ugvK#ePsybPIM!N6x2O*f0xk~r;3bTrAg@^O~<@fe&!Ll4ri z83WF=$5ve##X96^EX<(|V|y4{Xy8lT*eMJuuPy2&X@1{yu}|B!ti zq;OhlV41~H2WeZCrm@FKFn9!$vMh2fW+8t2>FE8F3j#x-*G3HiNq9bQ=#VDDSHCBYf{hVBV(bSUkfemHs8D^x3#i6pZ8 zA~b4;Ih!3qeVJ0~9AFuZ56+^~G0F-Roi&We|1_}yfr1pyThUcufGk05Yq!4s&V66*`-uAqXFpU5{~m)s zN8-?Gwl&xudt)}yB5ySgs!vOBCT0=b%C(#&nZP$jUegSe4{Q*@6XX+MJkZQ{OLG@e zZ{Ak1^#CB%92{+}SP#WI_7$p66$yAiykdQHVz$Mq`hAp{fmdj6!)?jT$NMg+IbG^_ zQ!wMc(c5i-;oHpSPOWc(->3CpTFe7n;qm1jw`cK>AXKlx4E#={K&J*CI;pmtRLWq;yd9$DyLtb0umuL)ZJP*rCiegyGx|f7zYqX1|l2^ zUSr}js7Th8!%5b==G0QJYMl&cfPc8}Y1En*xz2~(iTH&zp5?tP<;hwJy}{EM;H^B# z{o`<(Bi{Ue;44ul0IUrbQQ@mJCYWm<4KB(CFzHMN)RD5#tuzW!SrRdJk$;pAfS+T1 z@&7YuMAI5Zd1-RPzfs_I-VOS})g7{=LUq$Ql2EeNThw+oQGHOvchdiCD0s2@NWX{Pu`dRL%;XvJR~ZDT`H4% z99B92Ng1|J;a(kF;Yvr9F*IR}&2n0!v!*d@r6o!iO>1Lc_0}95QuN&ojM;sS_JoWC zqIm49hSLw_Ztjr!?`813#%y}h(b6acDdRLt&Xlz6y17wHz9Q=*`n_^>y#fWsEBf12 zC;<`CVG*O-#p&0`>z_c=$&s$H8=P7uh$7N$cVlZyPB{oiGT_4PQeHgpx5)3qeMDwn zweoF4P2!J54&-1|DCnE(R>xv3I)jEIDl0+CoL>C6(+A(S5;nkNA^wUa5=IyFWIo1n zt@xSQMZ6JvjDWeA{E#Jfg7p@L*|jMIU;6T5m8bTU*u(K4+MII8VQUd_Ehqdi0Cu-zX=IErvFrU(REQe$1e zQD^4w1NP2HH<;~JH)mpw>p_gIN{O%vTj4>dP(oS0c!Xf+0_`BC0a6gma7yDU}Il;F|2bw zoQFhdh|wB|umNulmLYdV-YwwWY-m5m$TzOXd0(X6&+k_Y@Nw`*f6oib@17Xv+u4QU zOjai-J?FSOwhimOetU}&|M%{~{UY`%dXWE8X`BOk1$D&V#7VaW#n*v9VYHB}W9)%I z{TEZxGCd}Ph;7fq9cW9@lQI|5*OL*%sE&Pmkrl6K+LzIMKHtg-6cSCb|Ioh%;Vg`H z8ddB?RDxu}q3(AZ35^M8r`)g$L1-e|U2eld0vf@lalY_- zESW>gMPc-POQ*iphfQs->5c>}f|YD{9H)Nw3yNbymnZ zw>#iZj3He@j&JNM(~YoCe$K^W@(K_c6Z<>w$Ed}Hh=v%y8|Jz_6BF~pdxf!h))KoO z?*hA7FV_Cf#lqWTtz*b^q4q@9bH8yZ_Z5!TI|bJrUPX5DzbcM-H2s2U+BRn5lcK4w zwqnWZR*t3&>MR$M_}NwhI*YIUn8ZRXOlW-&x+@p6)Y#3d4M5<3!b$(AG5CyWrr1~Z zaOOitWSO8Shkp(Jw6VGw03L{R3;1)aXeQM}MZYXr__R#WFi>~}R5SFl;~dOu%sTCo z>G{GeXnZUZ5K^coBwAXYb2i5ZR)RYp>M1|Hb|I(oJlr7R zFNz_}ZDy(LA{+Wp(L%`4=P=~*V$eM&9hINYSO0ytXBz#G!d|I%GoKYHVXKTC@B1#V zB^o_iN4@O15GGj|_bIgHfOcsalZNyqE@0^E-q7AO^Gq_FT^NHH??ycbCVH&rMLs51Rz7h)$8Bv|eBY1F?H3Qf>g+S(ctUy8lkqli&u_n(Q zwX!i}%D_t_rHfqB&sszH7vHJ9Axu5=v1LY*?`;l0Ijz+Wo*pQ52dx^9yQGcvA_z+! z{*CYy%a4>9V_aCTXT3d4>aNK~Xw5lmHs6 zY95D*G3KcrcY$+Tt`i8!s-_uA^bHO@>M9JCV5nnlPyO^r4L^|bw|Le>V!Vh*Rc0_( zCmm&4sgxUh{q(DK+Qs}<(u89O@QmJ23f=4?Tb-akem%Ep8jVZQ_sA3@l~3P+&@GGhxmas_6Jt+x)NRqNe;j zbaPp{tM!uaDb3O(}ZzgFeKIZ`K8##BTdaE|?Is9!DBFEBuIq?xzvP z65_)|_w852I5A__5N>}Cx1FX3?3~D)7frBGX6m5gJ@LZ6w(ucjVJcmx3@H_gz}5rm z`0S;pubf%gv1BNJx}}Q%P00~!nyqR(85vS;;dQHj><+h~z{s@)KaD?^5;fH_we`KN zD8NQ}EPG>BDBS&qx__on zy(-qaI!-Gn8`2$}NSN&=o^E;Jer^!F^GyJH<793wsVI zL8Ow7PubT88)SE_zIU3NWA;T0UaHc(;$aJ^R1j6_O%AL3T;(O42FZ5w`(E&?nhG$V z3bFn^H9`UKEDoyX0y7t`EGSudo$V0nOmXRkBbY}H#SFgrQu}bje??IeJ>5ps&w3U> znJg1R`bv=Br`Qq%0(U`Cte5m{$1Ot1E=`u#>W5Me&F3u}CRP`};439YAO?i^O&zbQz{{9HR?bL?)HAHG(X#b zvNIun1Bw5ba)SAmI;DNxG-Mv^;1`qD^i-Ns18?iO-3Zl}3#nz|WdA@VAQ*TZ+CLA1bLt`O?gj0Ku1t@_!j^Y1Yii zky*!5)o9H?0lqV`x5Cg*XQxXhd+GW}Pp}A~VIQ~epO~x!TB8O6(x>iV`<&`kZA}${ z)0$=q~kZQxA9oM^>V1yY%AwsB*XiG2Aq&nv@8!Dk|nZZg&?0j-#NVd54_ca2ktqU}?jB z{{&qS)%pNHYzF88X=%T;$;Nz~nVuvj==qP?me@c;(dGOcHF**TOLSvUGjz1+!##Av zz{oHQ+X%U^YkTQ1Ep1ScOT=b^a_wbDnCxS;SYsV)Od{k!?sn&ic>cpiD$_0}x_SK> z0nwcIWvLHAAm3mL3IQ2@aK=m&*djm5l_+|I@;x_4-##y2%jV9G-rhGXnfpyVUv;p0 zx6VknJ*1PX7WPU910?=q-ec8@d!v{2;kBHK_Lg@?C*U;^~wB469fT@Zu zeN#_zfzc_<#93w8=NZ5;x!4 t|AUA0&mr6YY@atn6Jhj!cfy9QiQD$4oj)~4E#3k?&lNQls^qL9{vYOSzXSjP diff --git a/docs/tutorial/JITTutorial2.html b/docs/tutorial/JITTutorial2.html deleted file mode 100644 index 504d96597b0..00000000000 --- a/docs/tutorial/JITTutorial2.html +++ /dev/null @@ -1,200 +0,0 @@ - - - - - LLVM Tutorial 2: A More Complicated Function - - - - - - - - -
LLVM Tutorial 2: A More Complicated Function
- -
- - - - - -
- -

Now that we understand the basics of creating functions in LLVM, let's move on to a more complicated example: something with control flow. As an example, let's consider Euclid's Greatest Common Denominator (GCD) algorithm:

- -
-
-unsigned gcd(unsigned x, unsigned y) {
-  if(x == y) {
-    return x;
-  } else if(x < y) {
-    return gcd(x, y - x);
-  } else {
-    return gcd(x - y, y);
-  }
-}
-
-
- -

With this example, we'll learn how to create functions with multiple blocks and control flow, and how to make function calls within your LLVM code. For starters, consider the diagram below.

- -
GCD CFG
- -

This is a graphical representation of a program in LLVM IR. It places each basic block on a node of a graph and uses directed edges to indicate flow control. These blocks will be serialized when written to a text or bitcode file, but it is often useful conceptually to think of them as a graph. Again, if you are unsure about the code in the diagram, you should skim through the LLVM Language Reference Manual and convince yourself that it is, in fact, the GCD algorithm.

- -

The first part of our code is practically the same as from the first tutorial. The same basic setup is required: creating a module, verifying it, and running the PrintModulePass on it. Even the first segment of makeLLVMModule() looks essentially the same, except that gcd takes one fewer parameter than mul_add.

- -
-
-#include "llvm/Module.h"
-#include "llvm/Function.h"
-#include "llvm/PassManager.h"
-#include "llvm/Analysis/Verifier.h"
-#include "llvm/Assembly/PrintModulePass.h"
-#include "llvm/Support/IRBuilder.h"
-#include "llvm/Support/raw_ostream.h"
-
-using namespace llvm;
-
-Module* makeLLVMModule();
-
-int main(int argc, char**argv) {
-  Module* Mod = makeLLVMModule();
-  
-  verifyModule(*Mod, PrintMessageAction);
-  
-  PassManager PM;
-  PM.add(createPrintModulePass(&outs()));
-  PM.run(*Mod);
-
-  delete Mod;  
-  return 0;
-}
-
-Module* makeLLVMModule() {
-  Module* mod = new Module("tut2");
-  
-  Constant* c = mod->getOrInsertFunction("gcd",
-                                         IntegerType::get(32),
-                                         IntegerType::get(32),
-                                         IntegerType::get(32),
-                                         NULL);
-  Function* gcd = cast<Function>(c);
-  
-  Function::arg_iterator args = gcd->arg_begin();
-  Value* x = args++;
-  x->setName("x");
-  Value* y = args++;
-  y->setName("y");
-
-
- -

Here, however, is where our code begins to diverge from the first tutorial. Because gcd has control flow, it is composed of multiple blocks interconnected by branching (br) instructions. For those familiar with assembly language, a block is similar to a labeled set of instructions. For those not familiar with assembly language, a block is basically a set of instructions that can be branched to and is executed linearly until the block is terminated by one of a small number of control flow instructions, such as br or ret.

- -

Blocks correspond to the nodes in the diagram we looked at in the beginning of this tutorial. From the diagram, we can see that this function contains five blocks, so we'll go ahead and create them. Note that we're making use of LLVM's automatic name uniquing in this code sample, since we're giving two blocks the same name.

- -
-
-  BasicBlock* entry = BasicBlock::Create(getGlobalContext(), ("entry", gcd);
-  BasicBlock* ret = BasicBlock::Create(getGlobalContext(), ("return", gcd);
-  BasicBlock* cond_false = BasicBlock::Create(getGlobalContext(), ("cond_false", gcd);
-  BasicBlock* cond_true = BasicBlock::Create(getGlobalContext(), ("cond_true", gcd);
-  BasicBlock* cond_false_2 = BasicBlock::Create(getGlobalContext(), ("cond_false", gcd);
-
-
- -

Now we're ready to begin generating code! We'll start with the entry block. This block corresponds to the top-level if-statement in the original C code, so we need to compare x and y. To achieve this, we perform an explicit comparison using ICmpEQ. ICmpEQ stands for an integer comparison for equality and returns a 1-bit integer result. This 1-bit result is then used as the input to a conditional branch, with ret as the true and cond_false as the false case.

- -
-
-  IRBuilder<> builder(entry);
-  Value* xEqualsY = builder.CreateICmpEQ(x, y, "tmp");
-  builder.CreateCondBr(xEqualsY, ret, cond_false);
-
-
- -

Our next block, ret, is pretty simple: it just returns the value of x. Recall that this block is only reached if x == y, so this is the correct behavior. Notice that instead of creating a new IRBuilder for each block, we can use SetInsertPoint to retarget our existing one. This saves on construction and memory allocation costs.

- -
-
-  builder.SetInsertPoint(ret);
-  builder.CreateRet(x);
-
-
- -

cond_false is a more interesting block: we now know that x -!= y, so we must branch again to determine which of x -and y is larger. This is achieved using the ICmpULT -instruction, which stands for integer comparison for unsigned -less-than. In LLVM, integer types do not carry sign; a 32-bit integer -pseudo-register can be interpreted as signed or unsigned without casting. -Whether a signed or unsigned interpretation is desired is specified in the -instruction. This is why several instructions in the LLVM IR, such as integer -less-than, include a specifier for signed or unsigned.

- -

Also note that we're again making use of LLVM's automatic name uniquing, this time at a register level. We've deliberately chosen to name every instruction "tmp" to illustrate that LLVM will give them all unique names without getting confused.

- -
-
-  builder.SetInsertPoint(cond_false);
-  Value* xLessThanY = builder.CreateICmpULT(x, y, "tmp");
-  builder.CreateCondBr(xLessThanY, cond_true, cond_false_2);
-
-
- -

Our last two blocks are quite similar; they're both recursive calls to gcd with different parameters. To create a call instruction, we have to create a vector (or any other container with InputInterators) to hold the arguments. We then pass in the beginning and ending iterators for this vector.

- -
-
-  builder.SetInsertPoint(cond_true);
-  Value* yMinusX = builder.CreateSub(y, x, "tmp");
-  std::vector<Value*> args1;
-  args1.push_back(x);
-  args1.push_back(yMinusX);
-  Value* recur_1 = builder.CreateCall(gcd, args1.begin(), args1.end(), "tmp");
-  builder.CreateRet(recur_1);
-  
-  builder.SetInsertPoint(cond_false_2);
-  Value* xMinusY = builder.CreateSub(x, y, "tmp");
-  std::vector<Value*> args2;
-  args2.push_back(xMinusY);
-  args2.push_back(y);
-  Value* recur_2 = builder.CreateCall(gcd, args2.begin(), args2.end(), "tmp");
-  builder.CreateRet(recur_2);
-  
-  return mod;
-}
-
-
- -

And that's it! You can compile and execute your code in the same way as before, by doing:

- -
-
-# c++ -g tut2.cpp `llvm-config --cxxflags --ldflags --libs core` -o tut2
-# ./tut2
-
-
- -
- - -
-
- Valid CSS! - Valid HTML 4.01! - - Owen Anderson
- The LLVM Compiler Infrastructure
- Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $ -
- - - diff --git a/include/llvm/ADT/iterator.cmake b/include/llvm/ADT/iterator.cmake deleted file mode 100644 index 55df8ce2643..00000000000 --- a/include/llvm/ADT/iterator.cmake +++ /dev/null @@ -1,79 +0,0 @@ -//===-- llvm/ADT/iterator - Portable wrapper around --*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file was developed by the LLVM research group and is distributed under -// the University of Illinois Open Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file provides a wrapper around the mysterious header file. -// In GCC 2.95.3, the file defines a bidirectional_iterator class (and other -// friends), instead of the standard iterator class. In GCC 3.1, the -// bidirectional_iterator class got moved out and the new, standards compliant, -// iterator<> class was added. Because there is nothing that we can do to get -// correct behavior on both compilers, we have this header with #ifdef's. Gross -// huh? -// -// By #includ'ing this file, you get the contents of plus the -// following classes in the global namespace: -// -// 1. bidirectional_iterator -// 2. forward_iterator -// -// The #if directives' expressions are filled in by Autoconf. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_ADT_ITERATOR -#define LLVM_ADT_ITERATOR - -#include - -#undef HAVE_BI_ITERATOR -#undef HAVE_STD_ITERATOR -#undef HAVE_FWD_ITERATOR - -// defined by Kevin -#define HAVE_STD_ITERATOR 1 - -#ifdef _MSC_VER -# define HAVE_BI_ITERATOR 0 -# define HAVE_STD_ITERATOR 1 -# define HAVE_FWD_ITERATOR 0 -#endif - -#if !HAVE_BI_ITERATOR -# if HAVE_STD_ITERATOR -/// If the bidirectional iterator is not defined, we attempt to define it in -/// terms of the C++ standard iterator. Otherwise, we import it with a "using" -/// statement. -/// -template -struct bidirectional_iterator - : public std::iterator { -}; -# else -# error "Need to have standard iterator to define bidirectional iterator!" -# endif -#else -using std::bidirectional_iterator; -#endif - -#if !HAVE_FWD_ITERATOR -# if HAVE_STD_ITERATOR -/// If the forward iterator is not defined, attempt to define it in terms of -/// the C++ standard iterator. Otherwise, we import it with a "using" statement. -/// -template -struct forward_iterator - : public std::iterator { -}; -# else -# error "Need to have standard iterator to define forward iterator!" -# endif -#else -using std::forward_iterator; -#endif - -#endif diff --git a/include/llvm/ADT/iterator.h.in b/include/llvm/ADT/iterator.h.in deleted file mode 100644 index dce74625118..00000000000 --- a/include/llvm/ADT/iterator.h.in +++ /dev/null @@ -1,76 +0,0 @@ -//==-- llvm/ADT/iterator.h - Portable wrapper around --*- C++ -*-==// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file provides a wrapper around the mysterious header file. -// In GCC 2.95.3, the file defines a bidirectional_iterator class (and other -// friends), instead of the standard iterator class. In GCC 3.1, the -// bidirectional_iterator class got moved out and the new, standards compliant, -// iterator<> class was added. Because there is nothing that we can do to get -// correct behavior on both compilers, we have this header with #ifdef's. Gross -// huh? -// -// By #includ'ing this file, you get the contents of plus the -// following classes in the global namespace: -// -// 1. bidirectional_iterator -// 2. forward_iterator -// -// The #if directives' expressions are filled in by Autoconf. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_ADT_ITERATOR_H -#define LLVM_ADT_ITERATOR_H - -#include - -#undef HAVE_BI_ITERATOR -#undef HAVE_STD_ITERATOR -#undef HAVE_FWD_ITERATOR - -#ifdef _MSC_VER -# define HAVE_BI_ITERATOR 0 -# define HAVE_STD_ITERATOR 1 -# define HAVE_FWD_ITERATOR 0 -#endif - -#if !HAVE_BI_ITERATOR -# if HAVE_STD_ITERATOR -/// If the bidirectional iterator is not defined, we attempt to define it in -/// terms of the C++ standard iterator. Otherwise, we import it with a "using" -/// statement. -/// -template -struct bidirectional_iterator - : public std::iterator { -}; -# else -# error "Need to have standard iterator to define bidirectional iterator!" -# endif -#else -using std::bidirectional_iterator; -#endif - -#if !HAVE_FWD_ITERATOR -# if HAVE_STD_ITERATOR -/// If the forward iterator is not defined, attempt to define it in terms of -/// the C++ standard iterator. Otherwise, we import it with a "using" statement. -/// -template -struct forward_iterator - : public std::iterator { -}; -# else -# error "Need to have standard iterator to define forward iterator!" -# endif -#else -using std::forward_iterator; -#endif - -#endif // LLVM_ADT_ITERATOR_H diff --git a/include/llvm/Support/DataTypes.h.cmake b/include/llvm/Support/DataTypes.h.cmake deleted file mode 100644 index ad210ed3b54..00000000000 --- a/include/llvm/Support/DataTypes.h.cmake +++ /dev/null @@ -1,152 +0,0 @@ -/*===-- include/Support/DataTypes.h - Define fixed size types -----*- C -*-===*\ -|* *| -|* The LLVM Compiler Infrastructure *| -|* *| -|* This file is distributed under the University of Illinois Open Source *| -|* License. See LICENSE.TXT for details. *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file contains definitions to figure out the size of _HOST_ data types.*| -|* This file is important because different host OS's define different macros,*| -|* which makes portability tough. This file exports the following *| -|* definitions: *| -|* *| -|* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| -|* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| -|* *| -|* No library is required when using these functinons. *| -|* *| -|*===----------------------------------------------------------------------===*/ - -/* Please leave this file C-compatible. */ - -#ifndef SUPPORT_DATATYPES_H -#define SUPPORT_DATATYPES_H - -#cmakedefine HAVE_SYS_TYPES_H ${HAVE_SYS_TYPES_H} -#cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H} -#cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H} -#cmakedefine HAVE_UINT64_T ${HAVE_UINT64_T} -#cmakedefine HAVE_U_INT64_T ${HAVE_U_INT64_T} - -#ifdef __cplusplus -#include -#else -#include -#endif - -#ifndef _MSC_VER - -/* Note that this header's correct operation depends on __STDC_LIMIT_MACROS - being defined. We would define it here, but in order to prevent Bad Things - happening when system headers or C++ STL headers include stdint.h before we - define it here, we define it on the g++ command line (in Makefile.rules). */ -#if !defined(__STDC_LIMIT_MACROS) -# error "Must #define __STDC_LIMIT_MACROS before #including Support/DataTypes.h" -#endif - -#if !defined(__STDC_CONSTANT_MACROS) -# error "Must #define __STDC_CONSTANT_MACROS before " \ - "#including Support/DataTypes.h" -#endif - -/* Note that includes , if this is a C99 system. */ -#ifdef HAVE_SYS_TYPES_H -#include -#endif - -#ifdef HAVE_INTTYPES_H -#include -#endif - -#ifdef HAVE_STDINT_H -#include -#endif - -#ifdef _AIX -#include "llvm/Support/AIXDataTypesFix.h" -#endif - -/* Handle incorrect definition of uint64_t as u_int64_t */ -#ifndef HAVE_UINT64_T -#ifdef HAVE_U_INT64_T -typedef u_int64_t uint64_t; -#else -# error "Don't have a definition for uint64_t on this platform" -#endif -#endif - -#ifdef _OpenBSD_ -#define INT8_MAX 127 -#define INT8_MIN -128 -#define UINT8_MAX 255 -#define INT16_MAX 32767 -#define INT16_MIN -32768 -#define UINT16_MAX 65535 -#define INT32_MAX 2147483647 -#define INT32_MIN -2147483648 -#define UINT32_MAX 4294967295U -#endif - -#else /* _MSC_VER */ -/* Visual C++ doesn't provide standard integer headers, but it does provide - built-in data types. */ -#include -#include -#include -#ifdef __cplusplus -#include -#else -#include -#endif -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -typedef signed int int32_t; -typedef unsigned int uint32_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef signed int ssize_t; -#define INT8_MAX 127 -#define INT8_MIN -128 -#define UINT8_MAX 255 -#define INT16_MAX 32767 -#define INT16_MIN -32768 -#define UINT16_MAX 65535 -#define INT32_MAX 2147483647 -#define INT32_MIN -2147483648 -#define UINT32_MAX 4294967295U -#define INT8_C(C) C -#define UINT8_C(C) C -#define INT16_C(C) C -#define UINT16_C(C) C -#define INT32_C(C) C -#define UINT32_C(C) C ## U -#define INT64_C(C) ((int64_t) C ## LL) -#define UINT64_C(C) ((uint64_t) C ## ULL) -#endif /* _MSC_VER */ - -/* Set defaults for constants which we cannot find. */ -#if !defined(INT64_MAX) -# define INT64_MAX 9223372036854775807LL -#endif -#if !defined(INT64_MIN) -# define INT64_MIN ((-INT64_MAX)-1) -#endif -#if !defined(UINT64_MAX) -# define UINT64_MAX 0xffffffffffffffffULL -#endif - -#if __GNUC__ > 3 -#define END_WITH_NULL __attribute__((sentinel)) -#else -#define END_WITH_NULL -#endif - -#ifndef HUGE_VALF -#define HUGE_VALF (float)HUGE_VAL -#endif - -#endif /* SUPPORT_DATATYPES_H */ diff --git a/include/llvm/Support/DataTypes.h.in b/include/llvm/Support/DataTypes.h.in deleted file mode 100644 index 405f4764c8f..00000000000 --- a/include/llvm/Support/DataTypes.h.in +++ /dev/null @@ -1,147 +0,0 @@ -/*===-- include/Support/DataTypes.h - Define fixed size types -----*- C -*-===*\ -|* *| -|* The LLVM Compiler Infrastructure *| -|* *| -|* This file is distributed under the University of Illinois Open Source *| -|* License. See LICENSE.TXT for details. *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* This file contains definitions to figure out the size of _HOST_ data types.*| -|* This file is important because different host OS's define different macros,*| -|* which makes portability tough. This file exports the following *| -|* definitions: *| -|* *| -|* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| -|* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| -|* *| -|* No library is required when using these functinons. *| -|* *| -|*===----------------------------------------------------------------------===*/ - -/* Please leave this file C-compatible. */ - -#ifndef SUPPORT_DATATYPES_H -#define SUPPORT_DATATYPES_H - -#undef HAVE_SYS_TYPES_H -#undef HAVE_INTTYPES_H -#undef HAVE_STDINT_H -#undef HAVE_UINT64_T -#undef HAVE_U_INT64_T - -#ifdef __cplusplus -#include -#else -#include -#endif - -#ifndef _MSC_VER - -/* Note that this header's correct operation depends on __STDC_LIMIT_MACROS - being defined. We would define it here, but in order to prevent Bad Things - happening when system headers or C++ STL headers include stdint.h before we - define it here, we define it on the g++ command line (in Makefile.rules). */ -#if !defined(__STDC_LIMIT_MACROS) -# error "Must #define __STDC_LIMIT_MACROS before #including Support/DataTypes.h" -#endif - -#if !defined(__STDC_CONSTANT_MACROS) -# error "Must #define __STDC_CONSTANT_MACROS before " \ - "#including Support/DataTypes.h" -#endif - -/* Note that includes , if this is a C99 system. */ -#ifdef HAVE_SYS_TYPES_H -#include -#endif - -#ifdef HAVE_INTTYPES_H -#include -#endif - -#ifdef HAVE_STDINT_H -#include -#endif - -#ifdef _AIX -#include "llvm/Support/AIXDataTypesFix.h" -#endif - -/* Handle incorrect definition of uint64_t as u_int64_t */ -#ifndef HAVE_UINT64_T -#ifdef HAVE_U_INT64_T -typedef u_int64_t uint64_t; -#else -# error "Don't have a definition for uint64_t on this platform" -#endif -#endif - -#ifdef _OpenBSD_ -#define INT8_MAX 127 -#define INT8_MIN -128 -#define UINT8_MAX 255 -#define INT16_MAX 32767 -#define INT16_MIN -32768 -#define UINT16_MAX 65535 -#define INT32_MAX 2147483647 -#define INT32_MIN -2147483648 -#define UINT32_MAX 4294967295U -#endif - -#else /* _MSC_VER */ -/* Visual C++ doesn't provide standard integer headers, but it does provide - built-in data types. */ -#include -#include -#include -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -typedef signed int int32_t; -typedef unsigned int uint32_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef signed int ssize_t; -#define INT8_MAX 127 -#define INT8_MIN -128 -#define UINT8_MAX 255 -#define INT16_MAX 32767 -#define INT16_MIN -32768 -#define UINT16_MAX 65535 -#define INT32_MAX 2147483647 -#define INT32_MIN -2147483648 -#define UINT32_MAX 4294967295U -#define INT8_C(C) C -#define UINT8_C(C) C -#define INT16_C(C) C -#define UINT16_C(C) C -#define INT32_C(C) C -#define UINT32_C(C) C ## U -#define INT64_C(C) ((int64_t) C ## LL) -#define UINT64_C(C) ((uint64_t) C ## ULL) -#endif /* _MSC_VER */ - -/* Set defaults for constants which we cannot find. */ -#if !defined(INT64_MAX) -# define INT64_MAX 9223372036854775807LL -#endif -#if !defined(INT64_MIN) -# define INT64_MIN ((-INT64_MAX)-1) -#endif -#if !defined(UINT64_MAX) -# define UINT64_MAX 0xffffffffffffffffULL -#endif - -#if __GNUC__ > 3 -#define END_WITH_NULL __attribute__((sentinel)) -#else -#define END_WITH_NULL -#endif - -#ifndef HUGE_VALF -#define HUGE_VALF (float)HUGE_VAL -#endif - -#endif /* SUPPORT_DATATYPES_H */ diff --git a/mklib b/mklib deleted file mode 100755 index f0d27e18b7f..00000000000 --- a/mklib +++ /dev/null @@ -1,7517 +0,0 @@ -#! /bin/sh - -# mklibT - Provide generalized library-building support services. -# Generated automatically by (GNU ) -# NOTE: Changes made to this file will be lost: look at ltmain.sh. -# -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001 -# Free Software Foundation, Inc. -# -# This file is part of GNU Libtool: -# Originally by Gordon Matzigkeit , 1996 -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - -# A sed program that does not truncate output. -SED="/usr/bin/sed" - -# Sed that helps us avoid accidentally triggering echo(1) options like -n. -Xsed="/usr/bin/sed -e 1s/^X//" - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -# The names of the tagged configurations supported by this script. -available_tags=" CXX" - -# ### BEGIN LIBTOOL CONFIG - -# Libtool was configured on host pes.vlakno.cz: - -# Shell to use when invoking shell scripts. -SHELL="/bin/sh" - -# Whether or not to build shared libraries. -build_libtool_libs=yes - -# Whether or not to build static libraries. -build_old_libs=yes - -# Whether or not to add -lc for building shared libraries. -build_libtool_need_lc=no - -# Whether or not to disallow shared libs when runtime libs are static -allow_libtool_libs_with_static_runtimes=no - -# Whether or not to optimize for fast installation. -fast_install=needless - -# The host system. -host_alias= -host=x86_64-unknown-freebsd7.2 -host_os=freebsd7.2 - -# The build system. -build_alias= -build=x86_64-unknown-freebsd7.2 -build_os=freebsd7.2 - -# An echo program that does not interpret backslashes. -echo="echo" - -# The archiver. -AR="ar" -AR_FLAGS="cru" - -# A C compiler. -LTCC="gcc" - -# LTCC compiler flags. -LTCFLAGS="-g -O2" - -# A language-specific compiler. -CC="gcc" - -# Is the compiler the GNU C compiler? -with_gcc=yes - -# An ERE matcher. -EGREP="/usr/bin/grep -E" - -# The linker used to build libraries. -LD="/usr/bin/ld" - -# Whether we need hard or soft links. -LN_S="ln -s" - -# A BSD-compatible nm program. -NM="/usr/bin/nm -B" - -# A symbol stripping program -STRIP="strip" - -# Used to examine libraries when file_magic_cmd begins "file" -MAGIC_CMD=file - -# Used on cygwin: DLL creation program. -DLLTOOL="dlltool" - -# Used on cygwin: object dumper. -OBJDUMP="objdump" - -# Used on cygwin: assembler. -AS="as" - -# The name of the directory that contains temporary libtool files. -objdir=.libs - -# How to create reloadable object files. -reload_flag=" -r" -reload_cmds="\$LD\$reload_flag -o \$output\$reload_objs" - -# How to pass a linker flag through the compiler. -wl="-Wl," - -# Object file suffix (normally "o"). -objext="o" - -# Old archive suffix (normally "a"). -libext="a" - -# Shared library suffix (normally ".so"). -shrext_cmds='.so' - -# Executable file suffix (normally ""). -exeext="" - -# Additional compiler flags for building library objects. -pic_flag=" -fPIC -DPIC" -pic_mode=default - -# What is the maximum length of a command? -max_cmd_len=196608 - -# Does compiler simultaneously support -c and -o options? -compiler_c_o="yes" - -# Must we lock files when doing compilation? -need_locks="no" - -# Do we need the lib prefix for modules? -need_lib_prefix=no - -# Do we need a version for libraries? -need_version=no - -# Whether dlopen is supported. -dlopen_support=yes - -# Whether dlopen of programs is supported. -dlopen_self=yes - -# Whether dlopen of statically linked programs is supported. -dlopen_self_static=no - -# Compiler flag to prevent dynamic linking. -link_static_flag="-static" - -# Compiler flag to turn off builtin functions. -no_builtin_flag=" -fno-builtin" - -# Compiler flag to allow reflexive dlopens. -export_dynamic_flag_spec="\${wl}--export-dynamic" - -# Compiler flag to generate shared objects directly from archives. -whole_archive_flag_spec="\${wl}--whole-archive\$convenience \${wl}--no-whole-archive" - -# Compiler flag to generate thread-safe objects. -thread_safe_flag_spec="" - -# Library versioning type. -version_type=freebsd-elf - -# Format of library name prefix. -libname_spec="lib\$name" - -# List of archive names. First name is the real one, the rest are links. -# The last name is the one that the linker finds with -lNAME. -library_names_spec="\${libname}\${release}\${shared_ext}\$versuffix \${libname}\${release}\${shared_ext} \$libname\${shared_ext}" - -# The coded name of the library, if different from the real name. -soname_spec="" - -# Commands used to build and install an old-style archive. -RANLIB="ranlib" -old_archive_cmds="\$AR \$AR_FLAGS \$oldlib\$oldobjs\$old_deplibs~\$RANLIB \$oldlib" -old_postinstall_cmds="chmod 644 \$oldlib~\$RANLIB \$oldlib" -old_postuninstall_cmds="" - -# Create an old-style archive from a shared archive. -old_archive_from_new_cmds="" - -# Create a temporary old-style archive to link instead of a shared archive. -old_archive_from_expsyms_cmds="" - -# Commands used to build and install a shared archive. -archive_cmds="\$CC -shared \$libobjs \$deplibs \$compiler_flags \${wl}-soname \$wl\$soname -o \$lib" -archive_expsym_cmds="\$CC -shared \$libobjs \$deplibs \$compiler_flags \${wl}-soname \$wl\$soname \${wl}-retain-symbols-file \$wl\$export_symbols -o \$lib" -postinstall_cmds="" -postuninstall_cmds="" - -# Commands used to build a loadable module (assumed same as above if empty) -module_cmds="" -module_expsym_cmds="" - -# Commands to strip libraries. -old_striplib="strip --strip-debug" -striplib="strip --strip-unneeded" - -# Dependencies to place before the objects being linked to create a -# shared library. -predep_objects="" - -# Dependencies to place after the objects being linked to create a -# shared library. -postdep_objects="" - -# Dependencies to place before the objects being linked to create a -# shared library. -predeps="" - -# Dependencies to place after the objects being linked to create a -# shared library. -postdeps="" - -# The library search path used internally by the compiler when linking -# a shared library. -compiler_lib_search_path="" - -# Method to check whether dependent libraries are shared objects. -deplibs_check_method="pass_all" - -# Command to use when deplibs_check_method == file_magic. -file_magic_cmd="\$MAGIC_CMD" - -# Flag that allows shared libraries with undefined symbols to be built. -allow_undefined_flag="" - -# Flag that forces no undefined symbols. -no_undefined_flag="" - -# Commands used to finish a libtool library installation in a directory. -finish_cmds="" - -# Same as above, but a single script fragment to be evaled but not shown. -finish_eval="" - -# Take the output of nm and produce a listing of raw symbols and C names. -global_symbol_pipe="sed -n -e 's/^.*[ ]\\([ABCDGIRSTW][ABCDGIRSTW]*\\)[ ][ ]*\\([_A-Za-z][_A-Za-z0-9]*\\)\$/\\1 \\2 \\2/p'" - -# Transform the output of nm in a proper C declaration -global_symbol_to_cdecl="sed -n -e 's/^. .* \\(.*\\)\$/extern int \\1;/p'" - -# Transform the output of nm in a C name address pair -global_symbol_to_c_name_address="sed -n -e 's/^: \\([^ ]*\\) \$/ {\\\"\\1\\\", (lt_ptr) 0},/p' -e 's/^[BCDEGRST] \\([^ ]*\\) \\([^ ]*\\)\$/ {\"\\2\", (lt_ptr) \\&\\2},/p'" - -# This is the shared library runtime path variable. -runpath_var=LD_RUN_PATH - -# This is the shared library path variable. -shlibpath_var=LD_LIBRARY_PATH - -# Is shlibpath searched before the hard-coded library search path? -shlibpath_overrides_runpath=yes - -# How to hardcode a shared library path into an executable. -hardcode_action=immediate - -# Whether we should hardcode library paths into libraries. -hardcode_into_libs=yes - -# Flag to hardcode $libdir into a binary during linking. -# This must work even if $libdir does not exist. -hardcode_libdir_flag_spec="\${wl}--rpath \${wl}\$libdir" - -# If ld is used when linking, flag to hardcode $libdir into -# a binary during linking. This must work even if $libdir does -# not exist. -hardcode_libdir_flag_spec_ld="" - -# Whether we need a single -rpath flag with a separated argument. -hardcode_libdir_separator="" - -# Set to yes if using DIR/libNAME during linking hardcodes DIR into the -# resulting binary. -hardcode_direct=no - -# Set to yes if using the -LDIR flag during linking hardcodes DIR into the -# resulting binary. -hardcode_minus_L=no - -# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into -# the resulting binary. -hardcode_shlibpath_var=unsupported - -# Set to yes if building a shared library automatically hardcodes DIR into the library -# and all subsequent libraries and executables linked against it. -hardcode_automatic=no - -# Variables whose values should be saved in libtool wrapper scripts and -# restored at relink time. -variables_saved_for_relink="PATH LD_LIBRARY_PATH LD_RUN_PATH GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" - -# Whether libtool must link a program against all its dependency libraries. -link_all_deplibs=unknown - -# Compile-time system search path for libraries -sys_lib_search_path_spec=" /usr/lib/ /usr/lib/" - -# Run-time system search path for libraries -sys_lib_dlsearch_path_spec="/lib /usr/lib" - -# Fix the shell variable $srcfile for the compiler. -fix_srcfile_path="" - -# Set to yes if exported symbols are required. -always_export_symbols=no - -# The commands to list exported symbols. -export_symbols_cmds="\$NM \$libobjs \$convenience | \$global_symbol_pipe | \$SED 's/.* //' | sort | uniq > \$export_symbols" - -# The commands to extract the exported symbol list from a shared archive. -extract_expsyms_cmds="" - -# Symbols that should not be listed in the preloaded symbols. -exclude_expsyms="_GLOBAL_OFFSET_TABLE_" - -# Symbols that must always be exported. -include_expsyms="" - -# ### END LIBTOOL CONFIG - -# ltmain.sh - Provide generalized library-building support services. -# NOTE: Changing this file will not affect anything until you rerun configure. -# -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005 -# Free Software Foundation, Inc. -# Originally by Gordon Matzigkeit , 1996 -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - -basename="s,^.*/,,g" - -# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh -# is ksh but when the shell is invoked as "sh" and the current value of -# the _XPG environment variable is not equal to 1 (one), the special -# positional parameter $0, within a function call, is the name of the -# function. -progpath="$0" - -# The name of this program: -progname=`echo "$progpath" | $SED $basename` -modename="$progname" - -# Global variables: -EXIT_SUCCESS=0 -EXIT_FAILURE=1 - -PROGRAM=ltmain.sh -PACKAGE=libtool -VERSION=1.5.22 -TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)" - -# See if we are running on zsh, and set the options which allow our -# commands through without removal of \ escapes. -if test -n "${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST -fi - -# Check that we have a working $echo. -if test "X$1" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift -elif test "X$1" = X--fallback-echo; then - # Avoid inline document here, it may be left over - : -elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then - # Yippee, $echo works! - : -else - # Restart under the correct shell, and then maybe $echo will work. - exec $SHELL "$progpath" --no-reexec ${1+"$@"} -fi - -if test "X$1" = X--fallback-echo; then - # used as fallback echo - shift - cat <&2 - $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 - exit $EXIT_FAILURE -fi - -# Global variables. -mode=$default_mode -nonopt= -prev= -prevopt= -run= -show="$echo" -show_help= -execute_dlfiles= -duplicate_deps=no -preserve_args= -lo2o="s/\\.lo\$/.${objext}/" -o2lo="s/\\.${objext}\$/.lo/" - -##################################### -# Shell function definitions: -# This seems to be the best place for them - -# func_mktempdir [string] -# Make a temporary directory that won't clash with other running -# libtool processes, and avoids race conditions if possible. If -# given, STRING is the basename for that directory. -func_mktempdir () -{ - my_template="${TMPDIR-/tmp}/${1-$progname}" - - if test "$run" = ":"; then - # Return a directory name, but don't create it in dry-run mode - my_tmpdir="${my_template}-$$" - else - - # If mktemp works, use that first and foremost - my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` - - if test ! -d "$my_tmpdir"; then - # Failing that, at least try and use $RANDOM to avoid a race - my_tmpdir="${my_template}-${RANDOM-0}$$" - - save_mktempdir_umask=`umask` - umask 0077 - $mkdir "$my_tmpdir" - umask $save_mktempdir_umask - fi - - # If we're not in dry-run mode, bomb out on failure - test -d "$my_tmpdir" || { - $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2 - exit $EXIT_FAILURE - } - fi - - $echo "X$my_tmpdir" | $Xsed -} - - -# func_win32_libid arg -# return the library type of file 'arg' -# -# Need a lot of goo to handle *both* DLLs and import libs -# Has to be a shell function in order to 'eat' the argument -# that is supplied when $file_magic_command is called. -func_win32_libid () -{ - win32_libid_type="unknown" - win32_fileres=`file -L $1 2>/dev/null` - case $win32_fileres in - *ar\ archive\ import\ library*) # definitely import - win32_libid_type="x86 archive import" - ;; - *ar\ archive*) # could be an import, or static - if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \ - $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then - win32_nmres=`eval $NM -f posix -A $1 | \ - $SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'` - case $win32_nmres in - import*) win32_libid_type="x86 archive import";; - *) win32_libid_type="x86 archive static";; - esac - fi - ;; - *DLL*) - win32_libid_type="x86 DLL" - ;; - *executable*) # but shell scripts are "executable" too... - case $win32_fileres in - *MS\ Windows\ PE\ Intel*) - win32_libid_type="x86 DLL" - ;; - esac - ;; - esac - $echo $win32_libid_type -} - - -# func_infer_tag arg -# Infer tagged configuration to use if any are available and -# if one wasn't chosen via the "--tag" command line option. -# Only attempt this if the compiler in the base compile -# command doesn't match the default compiler. -# arg is usually of the form 'gcc ...' -func_infer_tag () -{ - if test -n "$available_tags" && test -z "$tagname"; then - CC_quoted= - for arg in $CC; do - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - CC_quoted="$CC_quoted $arg" - done - case $@ in - # Blanks in the command may have been stripped by the calling shell, - # but not from the CC environment variable when configure was run. - " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;; - # Blanks at the start of $base_compile will cause this to fail - # if we don't check for them as well. - *) - for z in $available_tags; do - if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then - # Evaluate the configuration. - eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" - CC_quoted= - for arg in $CC; do - # Double-quote args containing other shell metacharacters. - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - CC_quoted="$CC_quoted $arg" - done - case "$@ " in - " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) - # The compiler in the base compile command matches - # the one in the tagged configuration. - # Assume this is the tagged configuration we want. - tagname=$z - break - ;; - esac - fi - done - # If $tagname still isn't set, then no tagged configuration - # was found and let the user know that the "--tag" command - # line option must be used. - if test -z "$tagname"; then - $echo "$modename: unable to infer tagged configuration" - $echo "$modename: specify a tag with \`--tag'" 1>&2 - exit $EXIT_FAILURE -# else -# $echo "$modename: using $tagname tagged configuration" - fi - ;; - esac - fi -} - - -# func_extract_an_archive dir oldlib -func_extract_an_archive () -{ - f_ex_an_ar_dir="$1"; shift - f_ex_an_ar_oldlib="$1" - - $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)" - $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $? - if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then - : - else - $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2 - exit $EXIT_FAILURE - fi -} - -# func_extract_archives gentop oldlib ... -func_extract_archives () -{ - my_gentop="$1"; shift - my_oldlibs=${1+"$@"} - my_oldobjs="" - my_xlib="" - my_xabs="" - my_xdir="" - my_status="" - - $show "${rm}r $my_gentop" - $run ${rm}r "$my_gentop" - $show "$mkdir $my_gentop" - $run $mkdir "$my_gentop" - my_status=$? - if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then - exit $my_status - fi - - for my_xlib in $my_oldlibs; do - # Extract the objects. - case $my_xlib in - [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; - *) my_xabs=`pwd`"/$my_xlib" ;; - esac - my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'` - my_xdir="$my_gentop/$my_xlib" - - $show "${rm}r $my_xdir" - $run ${rm}r "$my_xdir" - $show "$mkdir $my_xdir" - $run $mkdir "$my_xdir" - exit_status=$? - if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then - exit $exit_status - fi - case $host in - *-darwin*) - $show "Extracting $my_xabs" - # Do not bother doing anything if just a dry run - if test -z "$run"; then - darwin_orig_dir=`pwd` - cd $my_xdir || exit $? - darwin_archive=$my_xabs - darwin_curdir=`pwd` - darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'` - darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null` - if test -n "$darwin_arches"; then - darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'` - darwin_arch= - $show "$darwin_base_archive has multiple architectures $darwin_arches" - for darwin_arch in $darwin_arches ; do - mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}" - lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" - cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" - func_extract_an_archive "`pwd`" "${darwin_base_archive}" - cd "$darwin_curdir" - $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" - done # $darwin_arches - ## Okay now we have a bunch of thin objects, gotta fatten them up :) - darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP` - darwin_file= - darwin_files= - for darwin_file in $darwin_filelist; do - darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` - lipo -create -output "$darwin_file" $darwin_files - done # $darwin_filelist - ${rm}r unfat-$$ - cd "$darwin_orig_dir" - else - cd "$darwin_orig_dir" - func_extract_an_archive "$my_xdir" "$my_xabs" - fi # $darwin_arches - fi # $run - ;; - *) - func_extract_an_archive "$my_xdir" "$my_xabs" - ;; - esac - my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` - done - func_extract_archives_result="$my_oldobjs" -} -# End of Shell function definitions -##################################### - -# Darwin sucks -eval std_shrext=\"$shrext_cmds\" - -disable_libs=no - -# Parse our command line options once, thoroughly. -while test "$#" -gt 0 -do - arg="$1" - shift - - case $arg in - -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;; - *) optarg= ;; - esac - - # If the previous option needs an argument, assign it. - if test -n "$prev"; then - case $prev in - execute_dlfiles) - execute_dlfiles="$execute_dlfiles $arg" - ;; - tag) - tagname="$arg" - preserve_args="${preserve_args}=$arg" - - # Check whether tagname contains only valid characters - case $tagname in - *[!-_A-Za-z0-9,/]*) - $echo "$progname: invalid tag name: $tagname" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - case $tagname in - CC) - # Don't test for the "default" C tag, as we know, it's there, but - # not specially marked. - ;; - *) - if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then - taglist="$taglist $tagname" - # Evaluate the configuration. - eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`" - else - $echo "$progname: ignoring unknown tag $tagname" 1>&2 - fi - ;; - esac - ;; - *) - eval "$prev=\$arg" - ;; - esac - - prev= - prevopt= - continue - fi - - # Have we seen a non-optional argument yet? - case $arg in - --help) - show_help=yes - ;; - - --version) - $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP" - $echo - $echo "Copyright (C) 2005 Free Software Foundation, Inc." - $echo "This is free software; see the source for copying conditions. There is NO" - $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." - exit $? - ;; - - --config) - ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath - # Now print the configurations for the tags. - for tagname in $taglist; do - ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath" - done - exit $? - ;; - - --debug) - $echo "$progname: enabling shell trace mode" - set -x - preserve_args="$preserve_args $arg" - ;; - - --dry-run | -n) - run=: - ;; - - --features) - $echo "host: $host" - if test "$build_libtool_libs" = yes; then - $echo "enable shared libraries" - else - $echo "disable shared libraries" - fi - if test "$build_old_libs" = yes; then - $echo "enable static libraries" - else - $echo "disable static libraries" - fi - exit $? - ;; - - --finish) mode="finish" ;; - - --mode) prevopt="--mode" prev=mode ;; - --mode=*) mode="$optarg" ;; - - --preserve-dup-deps) duplicate_deps="yes" ;; - - --quiet | --silent) - show=: - preserve_args="$preserve_args $arg" - ;; - - --tag) - prevopt="--tag" - prev=tag - preserve_args="$preserve_args --tag" - ;; - --tag=*) - set tag "$optarg" ${1+"$@"} - shift - prev=tag - preserve_args="$preserve_args --tag" - ;; - - -dlopen) - prevopt="-dlopen" - prev=execute_dlfiles - ;; - - -*) - $echo "$modename: unrecognized option \`$arg'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; - - *) - nonopt="$arg" - break - ;; - esac -done - -if test -n "$prevopt"; then - $echo "$modename: option \`$prevopt' requires an argument" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE -fi - -case $disable_libs in -no) - ;; -shared) - build_libtool_libs=no - build_old_libs=yes - ;; -static) - build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` - ;; -esac - -# If this variable is set in any of the actions, the command in it -# will be execed at the end. This prevents here-documents from being -# left over by shells. -exec_cmd= - -if test -z "$show_help"; then - - # Infer the operation mode. - if test -z "$mode"; then - $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2 - $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2 - case $nonopt in - *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*) - mode=link - for arg - do - case $arg in - -c) - mode=compile - break - ;; - esac - done - ;; - *db | *dbx | *strace | *truss) - mode=execute - ;; - *install*|cp|mv) - mode=install - ;; - *rm) - mode=uninstall - ;; - *) - # If we have no mode, but dlfiles were specified, then do execute mode. - test -n "$execute_dlfiles" && mode=execute - - # Just use the default operation mode. - if test -z "$mode"; then - if test -n "$nonopt"; then - $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2 - else - $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2 - fi - fi - ;; - esac - fi - - # Only execute mode is allowed to have -dlopen flags. - if test -n "$execute_dlfiles" && test "$mode" != execute; then - $echo "$modename: unrecognized option \`-dlopen'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Change the help message to a mode-specific one. - generic_help="$help" - help="Try \`$modename --help --mode=$mode' for more information." - - # These modes are in order of execution frequency so that they run quickly. - case $mode in - # libtool compile mode - compile) - modename="$modename: compile" - # Get the compilation command and the source file. - base_compile= - srcfile="$nonopt" # always keep a non-empty value in "srcfile" - suppress_opt=yes - suppress_output= - arg_mode=normal - libobj= - later= - - for arg - do - case $arg_mode in - arg ) - # do not "continue". Instead, add this to base_compile - lastarg="$arg" - arg_mode=normal - ;; - - target ) - libobj="$arg" - arg_mode=normal - continue - ;; - - normal ) - # Accept any command-line options. - case $arg in - -o) - if test -n "$libobj" ; then - $echo "$modename: you cannot specify \`-o' more than once" 1>&2 - exit $EXIT_FAILURE - fi - arg_mode=target - continue - ;; - - -static | -prefer-pic | -prefer-non-pic) - later="$later $arg" - continue - ;; - - -no-suppress) - suppress_opt=no - continue - ;; - - -Xcompiler) - arg_mode=arg # the next one goes into the "base_compile" arg list - continue # The current "srcfile" will either be retained or - ;; # replaced later. I would guess that would be a bug. - - -Wc,*) - args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"` - lastarg= - save_ifs="$IFS"; IFS=',' - for arg in $args; do - IFS="$save_ifs" - - # Double-quote args containing other shell metacharacters. - # Many Bourne shells cannot handle close brackets correctly - # in scan sets, so we specify it separately. - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - lastarg="$lastarg $arg" - done - IFS="$save_ifs" - lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"` - - # Add the arguments to base_compile. - base_compile="$base_compile $lastarg" - continue - ;; - - * ) - # Accept the current argument as the source file. - # The previous "srcfile" becomes the current argument. - # - lastarg="$srcfile" - srcfile="$arg" - ;; - esac # case $arg - ;; - esac # case $arg_mode - - # Aesthetically quote the previous argument. - lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"` - - case $lastarg in - # Double-quote args containing other shell metacharacters. - # Many Bourne shells cannot handle close brackets correctly - # in scan sets, and some SunOS ksh mistreat backslash-escaping - # in scan sets (worked around with variable expansion), - # and furthermore cannot handle '|' '&' '(' ')' in scan sets - # at all, so we specify them separately. - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - lastarg="\"$lastarg\"" - ;; - esac - - base_compile="$base_compile $lastarg" - done # for arg - - case $arg_mode in - arg) - $echo "$modename: you must specify an argument for -Xcompile" - exit $EXIT_FAILURE - ;; - target) - $echo "$modename: you must specify a target with \`-o'" 1>&2 - exit $EXIT_FAILURE - ;; - *) - # Get the name of the library object. - [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'` - ;; - esac - - # Recognize several different file suffixes. - # If the user specifies -o file.o, it is replaced with file.lo - xform='[cCFSifmso]' - case $libobj in - *.ada) xform=ada ;; - *.adb) xform=adb ;; - *.ads) xform=ads ;; - *.asm) xform=asm ;; - *.c++) xform=c++ ;; - *.cc) xform=cc ;; - *.ii) xform=ii ;; - *.class) xform=class ;; - *.cpp) xform=cpp ;; - *.cxx) xform=cxx ;; - *.f90) xform=f90 ;; - *.for) xform=for ;; - *.java) xform=java ;; - esac - - libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` - - case $libobj in - *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;; - *) - $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - func_infer_tag $base_compile - - for arg in $later; do - case $arg in - -static) - build_old_libs=yes - continue - ;; - - -prefer-pic) - pic_mode=yes - continue - ;; - - -prefer-non-pic) - pic_mode=no - continue - ;; - esac - done - - qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"` - case $qlibobj in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - qlibobj="\"$qlibobj\"" ;; - esac - test "X$libobj" != "X$qlibobj" \ - && $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \ - && $echo "$modename: libobj name \`$libobj' may not contain shell special characters." - objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'` - xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$obj"; then - xdir= - else - xdir=$xdir/ - fi - lobj=${xdir}$objdir/$objname - - if test -z "$base_compile"; then - $echo "$modename: you must specify a compilation command" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Delete any leftover library objects. - if test "$build_old_libs" = yes; then - removelist="$obj $lobj $libobj ${libobj}T" - else - removelist="$lobj $libobj ${libobj}T" - fi - - $run $rm $removelist - trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 - - # On Cygwin there's no "real" PIC flag so we must build both object types - case $host_os in - cygwin* | mingw* | pw32* | os2*) - pic_mode=default - ;; - esac - if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then - # non-PIC code in shared libraries is not supported - pic_mode=default - fi - - # Calculate the filename of the output object if compiler does - # not support -o with -c - if test "$compiler_c_o" = no; then - output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} - lockfile="$output_obj.lock" - removelist="$removelist $output_obj $lockfile" - trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 - else - output_obj= - need_locks=no - lockfile= - fi - - # Lock this critical section if it is needed - # We use this script file to make the link, it avoids creating a new file - if test "$need_locks" = yes; then - until $run ln "$progpath" "$lockfile" 2>/dev/null; do - $show "Waiting for $lockfile to be removed" - sleep 2 - done - elif test "$need_locks" = warn; then - if test -f "$lockfile"; then - $echo "\ -*** ERROR, $lockfile exists and contains: -`cat $lockfile 2>/dev/null` - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $run $rm $removelist - exit $EXIT_FAILURE - fi - $echo "$srcfile" > "$lockfile" - fi - - if test -n "$fix_srcfile_path"; then - eval srcfile=\"$fix_srcfile_path\" - fi - qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"` - case $qsrcfile in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - qsrcfile="\"$qsrcfile\"" ;; - esac - - $run $rm "$libobj" "${libobj}T" - - # Create a libtool object file (analogous to a ".la" file), - # but don't create it if we're doing a dry run. - test -z "$run" && cat > ${libobj}T </dev/null`" != "X$srcfile"; then - $echo "\ -*** ERROR, $lockfile contains: -`cat $lockfile 2>/dev/null` - -but it should contain: -$srcfile - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $run $rm $removelist - exit $EXIT_FAILURE - fi - - # Just move the object if needed, then go on to compile the next one - if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then - $show "$mv $output_obj $lobj" - if $run $mv $output_obj $lobj; then : - else - error=$? - $run $rm $removelist - exit $error - fi - fi - - # Append the name of the PIC object to the libtool object file. - test -z "$run" && cat >> ${libobj}T <> ${libobj}T </dev/null`" != "X$srcfile"; then - $echo "\ -*** ERROR, $lockfile contains: -`cat $lockfile 2>/dev/null` - -but it should contain: -$srcfile - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $run $rm $removelist - exit $EXIT_FAILURE - fi - - # Just move the object if needed - if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then - $show "$mv $output_obj $obj" - if $run $mv $output_obj $obj; then : - else - error=$? - $run $rm $removelist - exit $error - fi - fi - - # Append the name of the non-PIC object the libtool object file. - # Only append if the libtool object file exists. - test -z "$run" && cat >> ${libobj}T <> ${libobj}T <&2 - fi - if test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=yes - else - if test -z "$pic_flag" && test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=built - fi - build_libtool_libs=no - build_old_libs=yes - break - ;; - esac - done - - # See if our shared archives depend on static archives. - test -n "$old_archive_from_new_cmds" && build_old_libs=yes - - # Go through the arguments, transforming them on the way. - while test "$#" -gt 0; do - arg="$1" - shift - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test - ;; - *) qarg=$arg ;; - esac - libtool_args="$libtool_args $qarg" - - # If the previous option needs an argument, assign it. - if test -n "$prev"; then - case $prev in - output) - compile_command="$compile_command @OUTPUT@" - finalize_command="$finalize_command @OUTPUT@" - ;; - esac - - case $prev in - dlfiles|dlprefiles) - if test "$preload" = no; then - # Add the symbol object into the linking commands. - compile_command="$compile_command @SYMFILE@" - finalize_command="$finalize_command @SYMFILE@" - preload=yes - fi - case $arg in - *.la | *.lo) ;; # We handle these cases below. - force) - if test "$dlself" = no; then - dlself=needless - export_dynamic=yes - fi - prev= - continue - ;; - self) - if test "$prev" = dlprefiles; then - dlself=yes - elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then - dlself=yes - else - dlself=needless - export_dynamic=yes - fi - prev= - continue - ;; - *) - if test "$prev" = dlfiles; then - dlfiles="$dlfiles $arg" - else - dlprefiles="$dlprefiles $arg" - fi - prev= - continue - ;; - esac - ;; - expsyms) - export_symbols="$arg" - if test ! -f "$arg"; then - $echo "$modename: symbol file \`$arg' does not exist" - exit $EXIT_FAILURE - fi - prev= - continue - ;; - expsyms_regex) - export_symbols_regex="$arg" - prev= - continue - ;; - inst_prefix) - inst_prefix_dir="$arg" - prev= - continue - ;; - precious_regex) - precious_files_regex="$arg" - prev= - continue - ;; - release) - release="-$arg" - prev= - continue - ;; - objectlist) - if test -f "$arg"; then - save_arg=$arg - moreargs= - for fil in `cat $save_arg` - do -# moreargs="$moreargs $fil" - arg=$fil - # A libtool-controlled object. - - # Check to see that this really is a libtool object. - if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - pic_object= - non_pic_object= - - # Read the .lo file - # If there is no directory component, then add one. - case $arg in - */* | *\\*) . $arg ;; - *) . ./$arg ;; - esac - - if test -z "$pic_object" || \ - test -z "$non_pic_object" || - test "$pic_object" = none && \ - test "$non_pic_object" = none; then - $echo "$modename: cannot find name of object for \`$arg'" 1>&2 - exit $EXIT_FAILURE - fi - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - if test "$pic_object" != none; then - # Prepend the subdirectory the object is found in. - pic_object="$xdir$pic_object" - - if test "$prev" = dlfiles; then - if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then - dlfiles="$dlfiles $pic_object" - prev= - continue - else - # If libtool objects are unsupported, then we need to preload. - prev=dlprefiles - fi - fi - - # CHECK ME: I think I busted this. -Ossama - if test "$prev" = dlprefiles; then - # Preload the old-style object. - dlprefiles="$dlprefiles $pic_object" - prev= - fi - - # A PIC object. - libobjs="$libobjs $pic_object" - arg="$pic_object" - fi - - # Non-PIC object. - if test "$non_pic_object" != none; then - # Prepend the subdirectory the object is found in. - non_pic_object="$xdir$non_pic_object" - - # A standard non-PIC object - non_pic_objects="$non_pic_objects $non_pic_object" - if test -z "$pic_object" || test "$pic_object" = none ; then - arg="$non_pic_object" - fi - else - # If the PIC object exists, use it instead. - # $xdir was prepended to $pic_object above. - non_pic_object="$pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - else - # Only an error if not doing a dry-run. - if test -z "$run"; then - $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 - exit $EXIT_FAILURE - else - # Dry-run case. - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` - non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` - libobjs="$libobjs $pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - fi - done - else - $echo "$modename: link input file \`$save_arg' does not exist" - exit $EXIT_FAILURE - fi - arg=$save_arg - prev= - continue - ;; - rpath | xrpath) - # We need an absolute path. - case $arg in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - $echo "$modename: only absolute run-paths are allowed" 1>&2 - exit $EXIT_FAILURE - ;; - esac - if test "$prev" = rpath; then - case "$rpath " in - *" $arg "*) ;; - *) rpath="$rpath $arg" ;; - esac - else - case "$xrpath " in - *" $arg "*) ;; - *) xrpath="$xrpath $arg" ;; - esac - fi - prev= - continue - ;; - xcompiler) - compiler_flags="$compiler_flags $qarg" - prev= - compile_command="$compile_command $qarg" - finalize_command="$finalize_command $qarg" - continue - ;; - xlinker) - linker_flags="$linker_flags $qarg" - compiler_flags="$compiler_flags $wl$qarg" - prev= - compile_command="$compile_command $wl$qarg" - finalize_command="$finalize_command $wl$qarg" - continue - ;; - xcclinker) - linker_flags="$linker_flags $qarg" - compiler_flags="$compiler_flags $qarg" - prev= - compile_command="$compile_command $qarg" - finalize_command="$finalize_command $qarg" - continue - ;; - shrext) - shrext_cmds="$arg" - prev= - continue - ;; - darwin_framework|darwin_framework_skip) - test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg" - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - prev= - continue - ;; - *) - eval "$prev=\"\$arg\"" - prev= - continue - ;; - esac - fi # test -n "$prev" - - prevarg="$arg" - - case $arg in - -all-static) - if test -n "$link_static_flag"; then - compile_command="$compile_command $link_static_flag" - finalize_command="$finalize_command $link_static_flag" - fi - continue - ;; - - -allow-undefined) - # FIXME: remove this flag sometime in the future. - $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2 - continue - ;; - - -avoid-version) - avoid_version=yes - continue - ;; - - -dlopen) - prev=dlfiles - continue - ;; - - -dlpreopen) - prev=dlprefiles - continue - ;; - - -export-dynamic) - export_dynamic=yes - continue - ;; - - -export-symbols | -export-symbols-regex) - if test -n "$export_symbols" || test -n "$export_symbols_regex"; then - $echo "$modename: more than one -exported-symbols argument is not allowed" - exit $EXIT_FAILURE - fi - if test "X$arg" = "X-export-symbols"; then - prev=expsyms - else - prev=expsyms_regex - fi - continue - ;; - - -framework|-arch|-isysroot) - case " $CC " in - *" ${arg} ${1} "* | *" ${arg} ${1} "*) - prev=darwin_framework_skip ;; - *) compiler_flags="$compiler_flags $arg" - prev=darwin_framework ;; - esac - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - continue - ;; - - -inst-prefix-dir) - prev=inst_prefix - continue - ;; - - # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* - # so, if we see these flags be careful not to treat them like -L - -L[A-Z][A-Z]*:*) - case $with_gcc/$host in - no/*-*-irix* | /*-*-irix*) - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - ;; - esac - continue - ;; - - -L*) - dir=`$echo "X$arg" | $Xsed -e 's/^-L//'` - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - absdir=`cd "$dir" && pwd` - if test -z "$absdir"; then - $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2 - absdir="$dir" - notinst_path="$notinst_path $dir" - fi - dir="$absdir" - ;; - esac - case "$deplibs " in - *" -L$dir "*) ;; - *) - deplibs="$deplibs -L$dir" - lib_search_path="$lib_search_path $dir" - ;; - esac - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'` - case :$dllsearchpath: in - *":$dir:"*) ;; - *) dllsearchpath="$dllsearchpath:$dir";; - esac - case :$dllsearchpath: in - *":$testbindir:"*) ;; - *) dllsearchpath="$dllsearchpath:$testbindir";; - esac - ;; - esac - continue - ;; - - -l*) - if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*) - # These systems don't actually have a C or math library (as such) - continue - ;; - *-*-os2*) - # These systems don't actually have a C library (as such) - test "X$arg" = "X-lc" && continue - ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc due to us having libc/libc_r. - test "X$arg" = "X-lc" && continue - ;; - *-*-rhapsody* | *-*-darwin1.[012]) - # Rhapsody C and math libraries are in the System framework - deplibs="$deplibs -framework System" - continue - ;; - *-*-sco3.2v5* | *-*-sco5v6*) - # Causes problems with __ctype - test "X$arg" = "X-lc" && continue - ;; - *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) - # Compiler inserts libc in the correct place for threads to work - test "X$arg" = "X-lc" && continue - ;; - esac - elif test "X$arg" = "X-lc_r"; then - case $host in - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc_r directly, use -pthread flag. - continue - ;; - esac - fi - deplibs="$deplibs $arg" - continue - ;; - - # Tru64 UNIX uses -model [arg] to determine the layout of C++ - # classes, name mangling, and exception handling. - -model) - compile_command="$compile_command $arg" - compiler_flags="$compiler_flags $arg" - finalize_command="$finalize_command $arg" - prev=xcompiler - continue - ;; - - -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) - compiler_flags="$compiler_flags $arg" - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - continue - ;; - - -module) - module=yes - continue - ;; - - # -64, -mips[0-9] enable 64-bit mode on the SGI compiler - # -r[0-9][0-9]* specifies the processor on the SGI compiler - # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler - # +DA*, +DD* enable 64-bit mode on the HP compiler - # -q* pass through compiler args for the IBM compiler - # -m* pass through architecture-specific compiler args for GCC - # -m*, -t[45]*, -txscale* pass through architecture-specific - # compiler args for GCC - # -pg pass through profiling flag for GCC - # @file GCC response files - -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \ - -t[45]*|-txscale*|@*) - - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - compiler_flags="$compiler_flags $arg" - continue - ;; - - -shrext) - prev=shrext - continue - ;; - - -no-fast-install) - fast_install=no - continue - ;; - - -no-install) - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - # The PATH hackery in wrapper scripts is required on Windows - # in order for the loader to find any dlls it needs. - $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2 - $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2 - fast_install=no - ;; - *) no_install=yes ;; - esac - continue - ;; - - -no-undefined) - allow_undefined=no - continue - ;; - - -objectlist) - prev=objectlist - continue - ;; - - -o) prev=output ;; - - -precious-files-regex) - prev=precious_regex - continue - ;; - - -release) - prev=release - continue - ;; - - -rpath) - prev=rpath - continue - ;; - - -R) - prev=xrpath - continue - ;; - - -R*) - dir=`$echo "X$arg" | $Xsed -e 's/^-R//'` - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - $echo "$modename: only absolute run-paths are allowed" 1>&2 - exit $EXIT_FAILURE - ;; - esac - case "$xrpath " in - *" $dir "*) ;; - *) xrpath="$xrpath $dir" ;; - esac - continue - ;; - - -static) - # The effects of -static are defined in a previous loop. - # We used to do the same as -all-static on platforms that - # didn't have a PIC flag, but the assumption that the effects - # would be equivalent was wrong. It would break on at least - # Digital Unix and AIX. - continue - ;; - - -thread-safe) - thread_safe=yes - continue - ;; - - -version-info) - prev=vinfo - continue - ;; - -version-number) - prev=vinfo - vinfo_number=yes - continue - ;; - - -Wc,*) - args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'` - arg= - save_ifs="$IFS"; IFS=',' - for flag in $args; do - IFS="$save_ifs" - case $flag in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - flag="\"$flag\"" - ;; - esac - arg="$arg $wl$flag" - compiler_flags="$compiler_flags $flag" - done - IFS="$save_ifs" - arg=`$echo "X$arg" | $Xsed -e "s/^ //"` - ;; - - -Wl,*) - args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'` - arg= - save_ifs="$IFS"; IFS=',' - for flag in $args; do - IFS="$save_ifs" - case $flag in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - flag="\"$flag\"" - ;; - esac - arg="$arg $wl$flag" - compiler_flags="$compiler_flags $wl$flag" - linker_flags="$linker_flags $flag" - done - IFS="$save_ifs" - arg=`$echo "X$arg" | $Xsed -e "s/^ //"` - ;; - - -Xcompiler) - prev=xcompiler - continue - ;; - - -Xlinker) - prev=xlinker - continue - ;; - - -XCClinker) - prev=xcclinker - continue - ;; - - # Some other compiler flag. - -* | +*) - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - ;; - - *.$objext) - # A standard object. - objs="$objs $arg" - ;; - - *.lo) - # A libtool-controlled object. - - # Check to see that this really is a libtool object. - if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - pic_object= - non_pic_object= - - # Read the .lo file - # If there is no directory component, then add one. - case $arg in - */* | *\\*) . $arg ;; - *) . ./$arg ;; - esac - - if test -z "$pic_object" || \ - test -z "$non_pic_object" || - test "$pic_object" = none && \ - test "$non_pic_object" = none; then - $echo "$modename: cannot find name of object for \`$arg'" 1>&2 - exit $EXIT_FAILURE - fi - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - if test "$pic_object" != none; then - # Prepend the subdirectory the object is found in. - pic_object="$xdir$pic_object" - - if test "$prev" = dlfiles; then - if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then - dlfiles="$dlfiles $pic_object" - prev= - continue - else - # If libtool objects are unsupported, then we need to preload. - prev=dlprefiles - fi - fi - - # CHECK ME: I think I busted this. -Ossama - if test "$prev" = dlprefiles; then - # Preload the old-style object. - dlprefiles="$dlprefiles $pic_object" - prev= - fi - - # A PIC object. - libobjs="$libobjs $pic_object" - arg="$pic_object" - fi - - # Non-PIC object. - if test "$non_pic_object" != none; then - # Prepend the subdirectory the object is found in. - non_pic_object="$xdir$non_pic_object" - - # A standard non-PIC object - non_pic_objects="$non_pic_objects $non_pic_object" - if test -z "$pic_object" || test "$pic_object" = none ; then - arg="$non_pic_object" - fi - else - # If the PIC object exists, use it instead. - # $xdir was prepended to $pic_object above. - non_pic_object="$pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - else - # Only an error if not doing a dry-run. - if test -z "$run"; then - $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 - exit $EXIT_FAILURE - else - # Dry-run case. - - # Extract subdirectory from the argument. - xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` - if test "X$xdir" = "X$arg"; then - xdir= - else - xdir="$xdir/" - fi - - pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` - non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` - libobjs="$libobjs $pic_object" - non_pic_objects="$non_pic_objects $non_pic_object" - fi - fi - ;; - - *.$libext) - # An archive. - deplibs="$deplibs $arg" - old_deplibs="$old_deplibs $arg" - continue - ;; - - *.la) - # A libtool-controlled library. - - if test "$prev" = dlfiles; then - # This library was specified with -dlopen. - dlfiles="$dlfiles $arg" - prev= - elif test "$prev" = dlprefiles; then - # The library was specified with -dlpreopen. - dlprefiles="$dlprefiles $arg" - prev= - else - deplibs="$deplibs $arg" - fi - continue - ;; - - # Some other compiler argument. - *) - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - ;; - esac # arg - - # Now actually substitute the argument into the commands. - if test -n "$arg"; then - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - fi - done # argument parsing loop - - if test -n "$prev"; then - $echo "$modename: the \`$prevarg' option requires an argument" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then - eval arg=\"$export_dynamic_flag_spec\" - compile_command="$compile_command $arg" - finalize_command="$finalize_command $arg" - fi - - oldlibs= - # calculate the name of the file, without its directory - outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'` - libobjs_save="$libobjs" - - if test -n "$shlibpath_var"; then - # get the directories listed in $shlibpath_var - eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` - else - shlib_search_path= - fi - eval sys_lib_search_path=\"$sys_lib_search_path_spec\" - eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" - - output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'` - if test "X$output_objdir" = "X$output"; then - output_objdir="$objdir" - else - output_objdir="$output_objdir/$objdir" - fi - # Create the object directory. - if test ! -d "$output_objdir"; then - $show "$mkdir $output_objdir" - $run $mkdir $output_objdir - exit_status=$? - if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then - exit $exit_status - fi - fi - - # Determine the type of output - case $output in - "") - $echo "$modename: you must specify an output file" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; - *.$libext) linkmode=oldlib ;; - *.lo | *.$objext) linkmode=obj ;; - *.la) linkmode=lib ;; - *) linkmode=prog ;; # Anything else should be a program. - esac - - case $host in - *cygwin* | *mingw* | *pw32*) - # don't eliminate duplications in $postdeps and $predeps - duplicate_compiler_generated_deps=yes - ;; - *) - duplicate_compiler_generated_deps=$duplicate_deps - ;; - esac - specialdeplibs= - - libs= - # Find all interdependent deplibs by searching for libraries - # that are linked more than once (e.g. -la -lb -la) - for deplib in $deplibs; do - if test "X$duplicate_deps" = "Xyes" ; then - case "$libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - libs="$libs $deplib" - done - - if test "$linkmode" = lib; then - libs="$predeps $libs $compiler_lib_search_path $postdeps" - - # Compute libraries that are listed more than once in $predeps - # $postdeps and mark them as special (i.e., whose duplicates are - # not to be eliminated). - pre_post_deps= - if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then - for pre_post_dep in $predeps $postdeps; do - case "$pre_post_deps " in - *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; - esac - pre_post_deps="$pre_post_deps $pre_post_dep" - done - fi - pre_post_deps= - fi - - deplibs= - newdependency_libs= - newlib_search_path= - need_relink=no # whether we're linking any uninstalled libtool libraries - notinst_deplibs= # not-installed libtool libraries - case $linkmode in - lib) - passes="conv link" - for file in $dlfiles $dlprefiles; do - case $file in - *.la) ;; - *) - $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2 - exit $EXIT_FAILURE - ;; - esac - done - ;; - prog) - compile_deplibs= - finalize_deplibs= - alldeplibs=no - newdlfiles= - newdlprefiles= - passes="conv scan dlopen dlpreopen link" - ;; - *) passes="conv" - ;; - esac - for pass in $passes; do - if test "$linkmode,$pass" = "lib,link" || - test "$linkmode,$pass" = "prog,scan"; then - libs="$deplibs" - deplibs= - fi - if test "$linkmode" = prog; then - case $pass in - dlopen) libs="$dlfiles" ;; - dlpreopen) libs="$dlprefiles" ;; - link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; - esac - fi - if test "$pass" = dlopen; then - # Collect dlpreopened libraries - save_deplibs="$deplibs" - deplibs= - fi - for deplib in $libs; do - lib= - found=no - case $deplib in - -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - compiler_flags="$compiler_flags $deplib" - fi - continue - ;; - -l*) - if test "$linkmode" != lib && test "$linkmode" != prog; then - $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2 - continue - fi - name=`$echo "X$deplib" | $Xsed -e 's/^-l//'` - for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do - for search_ext in .la $std_shrext .so .a; do - # Search the libtool library - lib="$searchdir/lib${name}${search_ext}" - if test -f "$lib"; then - if test "$search_ext" = ".la"; then - found=yes - else - found=no - fi - break 2 - fi - done - done - if test "$found" != yes; then - # deplib doesn't seem to be a libtool library - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" - fi - continue - else # deplib is a libtool library - # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, - # We need to do some special things here, and not later. - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - case " $predeps $postdeps " in - *" $deplib "*) - if (${SED} -e '2q' $lib | - grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - library_names= - old_library= - case $lib in - */* | *\\*) . $lib ;; - *) . ./$lib ;; - esac - for l in $old_library $library_names; do - ll="$l" - done - if test "X$ll" = "X$old_library" ; then # only static version available - found=no - ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` - test "X$ladir" = "X$lib" && ladir="." - lib=$ladir/$old_library - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" - fi - continue - fi - fi - ;; - *) ;; - esac - fi - fi - ;; # -l - -L*) - case $linkmode in - lib) - deplibs="$deplib $deplibs" - test "$pass" = conv && continue - newdependency_libs="$deplib $newdependency_libs" - newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` - ;; - prog) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - continue - fi - if test "$pass" = scan; then - deplibs="$deplib $deplibs" - else - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - fi - newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` - ;; - *) - $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2 - ;; - esac # linkmode - continue - ;; # -L - -R*) - if test "$pass" = link; then - dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'` - # Make sure the xrpath contains only unique directories. - case "$xrpath " in - *" $dir "*) ;; - *) xrpath="$xrpath $dir" ;; - esac - fi - deplibs="$deplib $deplibs" - continue - ;; - *.la) lib="$deplib" ;; - *.$libext) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - continue - fi - case $linkmode in - lib) - valid_a_lib=no - case $deplibs_check_method in - match_pattern*) - set dummy $deplibs_check_method - match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"` - if eval $echo \"$deplib\" 2>/dev/null \ - | $SED 10q \ - | $EGREP "$match_pattern_regex" > /dev/null; then - valid_a_lib=yes - fi - ;; - pass_all) - valid_a_lib=yes - ;; - esac - if test "$valid_a_lib" != yes; then - $echo - $echo "*** Warning: Trying to link with static lib archive $deplib." - $echo "*** I have the capability to make that library automatically link in when" - $echo "*** you link to this library. But I can only do this if you have a" - $echo "*** shared version of the library, which you do not appear to have" - $echo "*** because the file extensions .$libext of this argument makes me believe" - $echo "*** that it is just a static archive that I should not used here." - else - $echo - $echo "*** Warning: Linking the shared library $output against the" - $echo "*** static library $deplib is not portable!" - deplibs="$deplib $deplibs" - fi - continue - ;; - prog) - if test "$pass" != link; then - deplibs="$deplib $deplibs" - else - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - fi - continue - ;; - esac # linkmode - ;; # *.$libext - *.lo | *.$objext) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - elif test "$linkmode" = prog; then - if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then - # If there is no dlopen support or we're linking statically, - # we need to preload. - newdlprefiles="$newdlprefiles $deplib" - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - newdlfiles="$newdlfiles $deplib" - fi - fi - continue - ;; - %DEPLIBS%) - alldeplibs=yes - continue - ;; - esac # case $deplib - if test "$found" = yes || test -f "$lib"; then : - else - $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2 - exit $EXIT_FAILURE - fi - - # Check to see that this really is a libtool archive. - if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : - else - $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 - exit $EXIT_FAILURE - fi - - ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` - test "X$ladir" = "X$lib" && ladir="." - - dlname= - dlopen= - dlpreopen= - libdir= - library_names= - old_library= - # If the library was installed with an old release of libtool, - # it will not redefine variables installed, or shouldnotlink - installed=yes - shouldnotlink=no - avoidtemprpath= - - - # Read the .la file - case $lib in - */* | *\\*) . $lib ;; - *) . ./$lib ;; - esac - - if test "$linkmode,$pass" = "lib,link" || - test "$linkmode,$pass" = "prog,scan" || - { test "$linkmode" != prog && test "$linkmode" != lib; }; then - test -n "$dlopen" && dlfiles="$dlfiles $dlopen" - test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" - fi - - if test "$pass" = conv; then - # Only check for convenience libraries - deplibs="$lib $deplibs" - if test -z "$libdir"; then - if test -z "$old_library"; then - $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - # It is a libtool convenience library, so add in its objects. - convenience="$convenience $ladir/$objdir/$old_library" - old_convenience="$old_convenience $ladir/$objdir/$old_library" - tmp_libs= - for deplib in $dependency_libs; do - deplibs="$deplib $deplibs" - if test "X$duplicate_deps" = "Xyes" ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done - elif test "$linkmode" != prog && test "$linkmode" != lib; then - $echo "$modename: \`$lib' is not a convenience library" 1>&2 - exit $EXIT_FAILURE - fi - continue - fi # $pass = conv - - - # Get the name of the library we link against. - linklib= - for l in $old_library $library_names; do - linklib="$l" - done - if test -z "$linklib"; then - $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - - # This library was specified with -dlopen. - if test "$pass" = dlopen; then - if test -z "$libdir"; then - $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - if test -z "$dlname" || - test "$dlopen_support" != yes || - test "$build_libtool_libs" = no; then - # If there is no dlname, no dlopen support or we're linking - # statically, we need to preload. We also need to preload any - # dependent libraries so libltdl's deplib preloader doesn't - # bomb out in the load deplibs phase. - dlprefiles="$dlprefiles $lib $dependency_libs" - else - newdlfiles="$newdlfiles $lib" - fi - continue - fi # $pass = dlopen - - # We need an absolute path. - case $ladir in - [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; - *) - abs_ladir=`cd "$ladir" && pwd` - if test -z "$abs_ladir"; then - $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2 - $echo "$modename: passing it literally to the linker, although it might fail" 1>&2 - abs_ladir="$ladir" - fi - ;; - esac - laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` - - # Find the relevant object directory and library name. - if test "X$installed" = Xyes; then - if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then - $echo "$modename: warning: library \`$lib' was moved." 1>&2 - dir="$ladir" - absdir="$abs_ladir" - libdir="$abs_ladir" - else - dir="$libdir" - absdir="$libdir" - fi - test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes - else - if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then - dir="$ladir" - absdir="$abs_ladir" - # Remove this search path later - notinst_path="$notinst_path $abs_ladir" - else - dir="$ladir/$objdir" - absdir="$abs_ladir/$objdir" - # Remove this search path later - notinst_path="$notinst_path $abs_ladir" - fi - fi # $installed = yes - name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` - - # This library was specified with -dlpreopen. - if test "$pass" = dlpreopen; then - if test -z "$libdir"; then - $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2 - exit $EXIT_FAILURE - fi - # Prefer using a static library (so that no silly _DYNAMIC symbols - # are required to link). - if test -n "$old_library"; then - newdlprefiles="$newdlprefiles $dir/$old_library" - # Otherwise, use the dlname, so that lt_dlopen finds it. - elif test -n "$dlname"; then - newdlprefiles="$newdlprefiles $dir/$dlname" - else - newdlprefiles="$newdlprefiles $dir/$linklib" - fi - fi # $pass = dlpreopen - - if test -z "$libdir"; then - # Link the convenience library - if test "$linkmode" = lib; then - deplibs="$dir/$old_library $deplibs" - elif test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$dir/$old_library $compile_deplibs" - finalize_deplibs="$dir/$old_library $finalize_deplibs" - else - deplibs="$lib $deplibs" # used for prog,scan pass - fi - continue - fi - - - if test "$linkmode" = prog && test "$pass" != link; then - newlib_search_path="$newlib_search_path $ladir" - deplibs="$lib $deplibs" - - linkalldeplibs=no - if test "$link_all_deplibs" != no || test -z "$library_names" || - test "$build_libtool_libs" = no; then - linkalldeplibs=yes - fi - - tmp_libs= - for deplib in $dependency_libs; do - case $deplib in - -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test - esac - # Need to link against all dependency_libs? - if test "$linkalldeplibs" = yes; then - deplibs="$deplib $deplibs" - else - # Need to hardcode shared library paths - # or/and link against static libraries - newdependency_libs="$deplib $newdependency_libs" - fi - if test "X$duplicate_deps" = "Xyes" ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done # for deplib - continue - fi # $linkmode = prog... - - if test "$linkmode,$pass" = "prog,link"; then - if test -n "$library_names" && - { test "$prefer_static_libs" = no || test -z "$old_library"; }; then - # We need to hardcode the library path - if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then - # Make sure the rpath contains only unique directories. - case "$temp_rpath " in - *" $dir "*) ;; - *" $absdir "*) ;; - *) temp_rpath="$temp_rpath $absdir" ;; - esac - fi - - # Hardcode the library path. - # Skip directories that are in the system default run-time - # search path. - case " $sys_lib_dlsearch_path " in - *" $absdir "*) ;; - *) - case "$compile_rpath " in - *" $absdir "*) ;; - *) compile_rpath="$compile_rpath $absdir" - esac - ;; - esac - case " $sys_lib_dlsearch_path " in - *" $libdir "*) ;; - *) - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" - esac - ;; - esac - fi # $linkmode,$pass = prog,link... - - if test "$alldeplibs" = yes && - { test "$deplibs_check_method" = pass_all || - { test "$build_libtool_libs" = yes && - test -n "$library_names"; }; }; then - # We only need to search for static libraries - continue - fi - fi - - link_static=no # Whether the deplib will be linked statically - use_static_libs=$prefer_static_libs - if test "$use_static_libs" = built && test "$installed" = yes ; then - use_static_libs=no - fi - if test -n "$library_names" && - { test "$use_static_libs" = no || test -z "$old_library"; }; then - if test "$installed" = no; then - notinst_deplibs="$notinst_deplibs $lib" - need_relink=yes - fi - # This is a shared library - - # Warn about portability, can't link against -module's on - # some systems (darwin) - if test "$shouldnotlink" = yes && test "$pass" = link ; then - $echo - if test "$linkmode" = prog; then - $echo "*** Warning: Linking the executable $output against the loadable module" - else - $echo "*** Warning: Linking the shared library $output against the loadable module" - fi - $echo "*** $linklib is not portable!" - fi - if test "$linkmode" = lib && - test "$hardcode_into_libs" = yes; then - # Hardcode the library path. - # Skip directories that are in the system default run-time - # search path. - case " $sys_lib_dlsearch_path " in - *" $absdir "*) ;; - *) - case "$compile_rpath " in - *" $absdir "*) ;; - *) compile_rpath="$compile_rpath $absdir" - esac - ;; - esac - case " $sys_lib_dlsearch_path " in - *" $libdir "*) ;; - *) - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" - esac - ;; - esac - fi - - if test -n "$old_archive_from_expsyms_cmds"; then - # figure out the soname - set dummy $library_names - realname="$2" - shift; shift - libname=`eval \\$echo \"$libname_spec\"` - # use dlname if we got it. it's perfectly good, no? - if test -n "$dlname"; then - soname="$dlname" - elif test -n "$soname_spec"; then - # bleh windows - case $host in - *cygwin* | mingw*) - major=`expr $current - $age` - versuffix="-$major" - ;; - esac - eval soname=\"$soname_spec\" - else - soname="$realname" - fi - - # Make a new name for the extract_expsyms_cmds to use - soroot="$soname" - soname=`$echo $soroot | ${SED} -e 's/^.*\///'` - newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a" - - # If the library has no export list, then create one now - if test -f "$output_objdir/$soname-def"; then : - else - $show "extracting exported symbol list from \`$soname'" - save_ifs="$IFS"; IFS='~' - cmds=$extract_expsyms_cmds - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - fi - - # Create $newlib - if test -f "$output_objdir/$newlib"; then :; else - $show "generating import library for \`$soname'" - save_ifs="$IFS"; IFS='~' - cmds=$old_archive_from_expsyms_cmds - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - fi - # make sure the library variables are pointing to the new library - dir=$output_objdir - linklib=$newlib - fi # test -n "$old_archive_from_expsyms_cmds" - - if test "$linkmode" = prog || test "$mode" != relink; then - add_shlibpath= - add_dir= - add= - lib_linked=yes - case $hardcode_action in - immediate | unsupported) - if test "$hardcode_direct" = no; then - add="$dir/$linklib" - case $host in - *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; - *-*-sysv4*uw2*) add_dir="-L$dir" ;; - *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ - *-*-unixware7*) add_dir="-L$dir" ;; - *-*-darwin* ) - # if the lib is a module then we can not link against - # it, someone is ignoring the new warnings I added - if /usr/bin/file -L $add 2> /dev/null | - $EGREP ": [^:]* bundle" >/dev/null ; then - $echo "** Warning, lib $linklib is a module, not a shared library" - if test -z "$old_library" ; then - $echo - $echo "** And there doesn't seem to be a static archive available" - $echo "** The link will probably fail, sorry" - else - add="$dir/$old_library" - fi - fi - esac - elif test "$hardcode_minus_L" = no; then - case $host in - *-*-sunos*) add_shlibpath="$dir" ;; - esac - add_dir="-L$dir" - add="-l$name" - elif test "$hardcode_shlibpath_var" = no; then - add_shlibpath="$dir" - add="-l$name" - else - lib_linked=no - fi - ;; - relink) - if test "$hardcode_direct" = yes; then - add="$dir/$linklib" - elif test "$hardcode_minus_L" = yes; then - add_dir="-L$dir" - # Try looking first in the location we're being installed to. - if test -n "$inst_prefix_dir"; then - case $libdir in - [\\/]*) - add_dir="$add_dir -L$inst_prefix_dir$libdir" - ;; - esac - fi - add="-l$name" - elif test "$hardcode_shlibpath_var" = yes; then - add_shlibpath="$dir" - add="-l$name" - else - lib_linked=no - fi - ;; - *) lib_linked=no ;; - esac - - if test "$lib_linked" != yes; then - $echo "$modename: configuration error: unsupported hardcode properties" - exit $EXIT_FAILURE - fi - - if test -n "$add_shlibpath"; then - case :$compile_shlibpath: in - *":$add_shlibpath:"*) ;; - *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; - esac - fi - if test "$linkmode" = prog; then - test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" - test -n "$add" && compile_deplibs="$add $compile_deplibs" - else - test -n "$add_dir" && deplibs="$add_dir $deplibs" - test -n "$add" && deplibs="$add $deplibs" - if test "$hardcode_direct" != yes && \ - test "$hardcode_minus_L" != yes && \ - test "$hardcode_shlibpath_var" = yes; then - case :$finalize_shlibpath: in - *":$libdir:"*) ;; - *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; - esac - fi - fi - fi - - if test "$linkmode" = prog || test "$mode" = relink; then - add_shlibpath= - add_dir= - add= - # Finalize command for both is simple: just hardcode it. - if test "$hardcode_direct" = yes; then - add="$libdir/$linklib" - elif test "$hardcode_minus_L" = yes; then - add_dir="-L$libdir" - add="-l$name" - elif test "$hardcode_shlibpath_var" = yes; then - case :$finalize_shlibpath: in - *":$libdir:"*) ;; - *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; - esac - add="-l$name" - elif test "$hardcode_automatic" = yes; then - if test -n "$inst_prefix_dir" && - test -f "$inst_prefix_dir$libdir/$linklib" ; then - add="$inst_prefix_dir$libdir/$linklib" - else - add="$libdir/$linklib" - fi - else - # We cannot seem to hardcode it, guess we'll fake it. - add_dir="-L$libdir" - # Try looking first in the location we're being installed to. - if test -n "$inst_prefix_dir"; then - case $libdir in - [\\/]*) - add_dir="$add_dir -L$inst_prefix_dir$libdir" - ;; - esac - fi - add="-l$name" - fi - - if test "$linkmode" = prog; then - test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" - test -n "$add" && finalize_deplibs="$add $finalize_deplibs" - else - test -n "$add_dir" && deplibs="$add_dir $deplibs" - test -n "$add" && deplibs="$add $deplibs" - fi - fi - elif test "$linkmode" = prog; then - # Here we assume that one of hardcode_direct or hardcode_minus_L - # is not unsupported. This is valid on all known static and - # shared platforms. - if test "$hardcode_direct" != unsupported; then - test -n "$old_library" && linklib="$old_library" - compile_deplibs="$dir/$linklib $compile_deplibs" - finalize_deplibs="$dir/$linklib $finalize_deplibs" - else - compile_deplibs="-l$name -L$dir $compile_deplibs" - finalize_deplibs="-l$name -L$dir $finalize_deplibs" - fi - elif test "$build_libtool_libs" = yes; then - # Not a shared library - if test "$deplibs_check_method" != pass_all; then - # We're trying link a shared library against a static one - # but the system doesn't support it. - - # Just print a warning and add the library to dependency_libs so - # that the program can be linked against the static library. - $echo - $echo "*** Warning: This system can not link to static lib archive $lib." - $echo "*** I have the capability to make that library automatically link in when" - $echo "*** you link to this library. But I can only do this if you have a" - $echo "*** shared version of the library, which you do not appear to have." - if test "$module" = yes; then - $echo "*** But as you try to build a module library, libtool will still create " - $echo "*** a static module, that should work as long as the dlopening application" - $echo "*** is linked with the -dlopen flag to resolve symbols at runtime." - if test -z "$global_symbol_pipe"; then - $echo - $echo "*** However, this would only work if libtool was able to extract symbol" - $echo "*** lists from a program, using \`nm' or equivalent, but libtool could" - $echo "*** not find such a program. So, this module is probably useless." - $echo "*** \`nm' from GNU binutils and a full rebuild may help." - fi - if test "$build_old_libs" = no; then - build_libtool_libs=module - build_old_libs=yes - else - build_libtool_libs=no - fi - fi - else - deplibs="$dir/$old_library $deplibs" - link_static=yes - fi - fi # link shared/static library? - - if test "$linkmode" = lib; then - if test -n "$dependency_libs" && - { test "$hardcode_into_libs" != yes || - test "$build_old_libs" = yes || - test "$link_static" = yes; }; then - # Extract -R from dependency_libs - temp_deplibs= - for libdir in $dependency_libs; do - case $libdir in - -R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'` - case " $xrpath " in - *" $temp_xrpath "*) ;; - *) xrpath="$xrpath $temp_xrpath";; - esac;; - *) temp_deplibs="$temp_deplibs $libdir";; - esac - done - dependency_libs="$temp_deplibs" - fi - - newlib_search_path="$newlib_search_path $absdir" - # Link against this library - test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" - # ... and its dependency_libs - tmp_libs= - for deplib in $dependency_libs; do - newdependency_libs="$deplib $newdependency_libs" - if test "X$duplicate_deps" = "Xyes" ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done - - if test "$link_all_deplibs" != no; then - # Add the search paths of all dependency libraries - for deplib in $dependency_libs; do - case $deplib in - -L*) path="$deplib" ;; - *.la) - dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'` - test "X$dir" = "X$deplib" && dir="." - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; - *) - absdir=`cd "$dir" && pwd` - if test -z "$absdir"; then - $echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2 - absdir="$dir" - fi - ;; - esac - if grep "^installed=no" $deplib > /dev/null; then - path="$absdir/$objdir" - else - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` - if test -z "$libdir"; then - $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2 - exit $EXIT_FAILURE - fi - if test "$absdir" != "$libdir"; then - $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2 - fi - path="$absdir" - fi - depdepl= - case $host in - *-*-darwin*) - # we do not want to link against static libs, - # but need to link against shared - eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` - if test -n "$deplibrary_names" ; then - for tmp in $deplibrary_names ; do - depdepl=$tmp - done - if test -f "$path/$depdepl" ; then - depdepl="$path/$depdepl" - fi - # do not add paths which are already there - case " $newlib_search_path " in - *" $path "*) ;; - *) newlib_search_path="$newlib_search_path $path";; - esac - fi - path="" - ;; - *) - path="-L$path" - ;; - esac - ;; - -l*) - case $host in - *-*-darwin*) - # Again, we only want to link against shared libraries - eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"` - for tmp in $newlib_search_path ; do - if test -f "$tmp/lib$tmp_libs.dylib" ; then - eval depdepl="$tmp/lib$tmp_libs.dylib" - break - fi - done - path="" - ;; - *) continue ;; - esac - ;; - *) continue ;; - esac - case " $deplibs " in - *" $path "*) ;; - *) deplibs="$path $deplibs" ;; - esac - case " $deplibs " in - *" $depdepl "*) ;; - *) deplibs="$depdepl $deplibs" ;; - esac - done - fi # link_all_deplibs != no - fi # linkmode = lib - done # for deplib in $libs - dependency_libs="$newdependency_libs" - if test "$pass" = dlpreopen; then - # Link the dlpreopened libraries before other libraries - for deplib in $save_deplibs; do - deplibs="$deplib $deplibs" - done - fi - if test "$pass" != dlopen; then - if test "$pass" != conv; then - # Make sure lib_search_path contains only unique directories. - lib_search_path= - for dir in $newlib_search_path; do - case "$lib_search_path " in - *" $dir "*) ;; - *) lib_search_path="$lib_search_path $dir" ;; - esac - done - newlib_search_path= - fi - - if test "$linkmode,$pass" != "prog,link"; then - vars="deplibs" - else - vars="compile_deplibs finalize_deplibs" - fi - for var in $vars dependency_libs; do - # Add libraries to $var in reverse order - eval tmp_libs=\"\$$var\" - new_libs= - for deplib in $tmp_libs; do - # FIXME: Pedantically, this is the right thing to do, so - # that some nasty dependency loop isn't accidentally - # broken: - #new_libs="$deplib $new_libs" - # Pragmatically, this seems to cause very few problems in - # practice: - case $deplib in - -L*) new_libs="$deplib $new_libs" ;; - -R*) ;; - *) - # And here is the reason: when a library appears more - # than once as an explicit dependence of a library, or - # is implicitly linked in more than once by the - # compiler, it is considered special, and multiple - # occurrences thereof are not removed. Compare this - # with having the same library being listed as a - # dependency of multiple other libraries: in this case, - # we know (pedantically, we assume) the library does not - # need to be listed more than once, so we keep only the - # last copy. This is not always right, but it is rare - # enough that we require users that really mean to play - # such unportable linking tricks to link the library - # using -Wl,-lname, so that libtool does not consider it - # for duplicate removal. - case " $specialdeplibs " in - *" $deplib "*) new_libs="$deplib $new_libs" ;; - *) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$deplib $new_libs" ;; - esac - ;; - esac - ;; - esac - done - tmp_libs= - for deplib in $new_libs; do - case $deplib in - -L*) - case " $tmp_libs " in - *" $deplib "*) ;; - *) tmp_libs="$tmp_libs $deplib" ;; - esac - ;; - *) tmp_libs="$tmp_libs $deplib" ;; - esac - done - eval $var=\"$tmp_libs\" - done # for var - fi - # Last step: remove runtime libs from dependency_libs - # (they stay in deplibs) - tmp_libs= - for i in $dependency_libs ; do - case " $predeps $postdeps $compiler_lib_search_path " in - *" $i "*) - i="" - ;; - esac - if test -n "$i" ; then - tmp_libs="$tmp_libs $i" - fi - done - dependency_libs=$tmp_libs - done # for pass - if test "$linkmode" = prog; then - dlfiles="$newdlfiles" - dlprefiles="$newdlprefiles" - fi - - case $linkmode in - oldlib) - if test -n "$deplibs"; then - $echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2 - fi - - if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then - $echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2 - fi - - if test -n "$rpath"; then - $echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2 - fi - - if test -n "$xrpath"; then - $echo "$modename: warning: \`-R' is ignored for archives" 1>&2 - fi - - if test -n "$vinfo"; then - $echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2 - fi - - if test -n "$release"; then - $echo "$modename: warning: \`-release' is ignored for archives" 1>&2 - fi - - if test -n "$export_symbols" || test -n "$export_symbols_regex"; then - $echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2 - fi - - # Now set the variables for building old libraries. - build_libtool_libs=no - oldlibs="$output" - objs="$objs$old_deplibs" - ;; - - lib) - # Make sure we only generate libraries of the form `libNAME.la'. - case $outputname in - lib*) - name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` - eval shared_ext=\"$shrext_cmds\" - eval libname=\"$libname_spec\" - ;; - *) - if test "$module" = no; then - $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - if test "$need_lib_prefix" != no; then - # Add the "lib" prefix for modules if required - name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'` - eval shared_ext=\"$shrext_cmds\" - eval libname=\"$libname_spec\" - else - libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'` - fi - ;; - esac - - if test -n "$objs"; then - if test "$deplibs_check_method" != pass_all; then - $echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1 - exit $EXIT_FAILURE - else - $echo - $echo "*** Warning: Linking the shared library $output against the non-libtool" - $echo "*** objects $objs is not portable!" - libobjs="$libobjs $objs" - fi - fi - - if test "$dlself" != no; then - $echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2 - fi - - set dummy $rpath - if test "$#" -gt 2; then - $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2 - fi - install_libdir="$2" - - oldlibs= - if test -z "$rpath"; then - if test "$build_libtool_libs" = yes; then - # Building a libtool convenience library. - # Some compilers have problems with a `.al' extension so - # convenience libraries should have the same extension an - # archive normally would. - oldlibs="$output_objdir/$libname.$libext $oldlibs" - build_libtool_libs=convenience - build_old_libs=yes - fi - - if test -n "$vinfo"; then - $echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2 - fi - - if test -n "$release"; then - $echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2 - fi - else - - # Parse the version information argument. - save_ifs="$IFS"; IFS=':' - set dummy $vinfo 0 0 0 - IFS="$save_ifs" - - if test -n "$8"; then - $echo "$modename: too many parameters to \`-version-info'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # convert absolute version numbers to libtool ages - # this retains compatibility with .la files and attempts - # to make the code below a bit more comprehensible - - case $vinfo_number in - yes) - number_major="$2" - number_minor="$3" - number_revision="$4" - # - # There are really only two kinds -- those that - # use the current revision as the major version - # and those that subtract age and use age as - # a minor version. But, then there is irix - # which has an extra 1 added just for fun - # - case $version_type in - darwin|linux|osf|windows) - current=`expr $number_major + $number_minor` - age="$number_minor" - revision="$number_revision" - ;; - freebsd-aout|freebsd-elf|sunos) - current="$number_major" - revision="$number_minor" - age="0" - ;; - irix|nonstopux) - current=`expr $number_major + $number_minor - 1` - age="$number_minor" - revision="$number_minor" - ;; - esac - ;; - no) - current="$2" - revision="$3" - age="$4" - ;; - esac - - # Check that each of the things are valid numbers. - case $current in - 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; - *) - $echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>&2 - $echo "$modename: \`$vinfo' is not valid version information" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - case $revision in - 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; - *) - $echo "$modename: REVISION \`$revision' must be a nonnegative integer" 1>&2 - $echo "$modename: \`$vinfo' is not valid version information" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - case $age in - 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; - *) - $echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2 - $echo "$modename: \`$vinfo' is not valid version information" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - if test "$age" -gt "$current"; then - $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2 - $echo "$modename: \`$vinfo' is not valid version information" 1>&2 - exit $EXIT_FAILURE - fi - - # Calculate the version variables. - major= - versuffix= - verstring= - case $version_type in - none) ;; - - darwin) - # Like Linux, but with the current version available in - # verstring for coding it into the library header - major=.`expr $current - $age` - versuffix="$major.$age.$revision" - # Darwin ld doesn't like 0 for these options... - minor_current=`expr $current + 1` - verstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" - ;; - - freebsd-aout) - major=".$current" - versuffix=".$current.$revision"; - ;; - - freebsd-elf) - major=".$current" - versuffix=".$current"; - ;; - - irix | nonstopux) - major=`expr $current - $age + 1` - - case $version_type in - nonstopux) verstring_prefix=nonstopux ;; - *) verstring_prefix=sgi ;; - esac - verstring="$verstring_prefix$major.$revision" - - # Add in all the interfaces that we are compatible with. - loop=$revision - while test "$loop" -ne 0; do - iface=`expr $revision - $loop` - loop=`expr $loop - 1` - verstring="$verstring_prefix$major.$iface:$verstring" - done - - # Before this point, $major must not contain `.'. - major=.$major - versuffix="$major.$revision" - ;; - - linux) - major=.`expr $current - $age` - versuffix="$major.$age.$revision" - ;; - - osf) - major=.`expr $current - $age` - versuffix=".$current.$age.$revision" - verstring="$current.$age.$revision" - - # Add in all the interfaces that we are compatible with. - loop=$age - while test "$loop" -ne 0; do - iface=`expr $current - $loop` - loop=`expr $loop - 1` - verstring="$verstring:${iface}.0" - done - - # Make executables depend on our current version. - verstring="$verstring:${current}.0" - ;; - - sunos) - major=".$current" - versuffix=".$current.$revision" - ;; - - windows) - # Use '-' rather than '.', since we only want one - # extension on DOS 8.3 filesystems. - major=`expr $current - $age` - versuffix="-$major" - ;; - - *) - $echo "$modename: unknown library version type \`$version_type'" 1>&2 - $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 - exit $EXIT_FAILURE - ;; - esac - - # Clear the version info if we defaulted, and they specified a release. - if test -z "$vinfo" && test -n "$release"; then - major= - case $version_type in - darwin) - # we can't check for "0.0" in archive_cmds due to quoting - # problems, so we reset it completely - verstring= - ;; - *) - verstring="0.0" - ;; - esac - if test "$need_version" = no; then - versuffix= - else - versuffix=".0.0" - fi - fi - - # Remove version info from name if versioning should be avoided - if test "$avoid_version" = yes && test "$need_version" = no; then - major= - versuffix= - verstring="" - fi - - # Check to see if the archive will have undefined symbols. - if test "$allow_undefined" = yes; then - if test "$allow_undefined_flag" = unsupported; then - $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2 - build_libtool_libs=no - build_old_libs=yes - fi - else - # Don't allow undefined symbols. - allow_undefined_flag="$no_undefined_flag" - fi - fi - - if test "$mode" != relink; then - # Remove our outputs, but don't remove object files since they - # may have been created when compiling PIC objects. - removelist= - tempremovelist=`$echo "$output_objdir/*"` - for p in $tempremovelist; do - case $p in - *.$objext) - ;; - $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) - if test "X$precious_files_regex" != "X"; then - if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 - then - continue - fi - fi - removelist="$removelist $p" - ;; - *) ;; - esac - done - if test -n "$removelist"; then - $show "${rm}r $removelist" - $run ${rm}r $removelist - fi - fi - - # Now set the variables for building old libraries. - if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then - oldlibs="$oldlibs $output_objdir/$libname.$libext" - - # Transform .lo files to .o files. - oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` - fi - - # Eliminate all temporary directories. - for path in $notinst_path; do - lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"` - deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"` - dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"` - done - - if test -n "$xrpath"; then - # If the user specified any rpath flags, then add them. - temp_xrpath= - for libdir in $xrpath; do - temp_xrpath="$temp_xrpath -R$libdir" - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" ;; - esac - done - if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then - dependency_libs="$temp_xrpath $dependency_libs" - fi - fi - - # Make sure dlfiles contains only unique files that won't be dlpreopened - old_dlfiles="$dlfiles" - dlfiles= - for lib in $old_dlfiles; do - case " $dlprefiles $dlfiles " in - *" $lib "*) ;; - *) dlfiles="$dlfiles $lib" ;; - esac - done - - # Make sure dlprefiles contains only unique files - old_dlprefiles="$dlprefiles" - dlprefiles= - for lib in $old_dlprefiles; do - case "$dlprefiles " in - *" $lib "*) ;; - *) dlprefiles="$dlprefiles $lib" ;; - esac - done - - if test "$build_libtool_libs" = yes; then - if test -n "$rpath"; then - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*) - # these systems don't actually have a c library (as such)! - ;; - *-*-rhapsody* | *-*-darwin1.[012]) - # Rhapsody C library is in the System framework - deplibs="$deplibs -framework System" - ;; - *-*-netbsd*) - # Don't link with libc until the a.out ld.so is fixed. - ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc due to us having libc/libc_r. - ;; - *-*-sco3.2v5* | *-*-sco5v6*) - # Causes problems with __ctype - ;; - *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) - # Compiler inserts libc in the correct place for threads to work - ;; - *) - # Add libc to deplibs on all other systems if necessary. - if test "$build_libtool_need_lc" = "yes"; then - deplibs="$deplibs -lc" - fi - ;; - esac - fi - - # Transform deplibs into only deplibs that can be linked in shared. - name_save=$name - libname_save=$libname - release_save=$release - versuffix_save=$versuffix - major_save=$major - # I'm not sure if I'm treating the release correctly. I think - # release should show up in the -l (ie -lgmp5) so we don't want to - # add it in twice. Is that correct? - release="" - versuffix="" - major="" - newdeplibs= - droppeddeps=no - case $deplibs_check_method in - pass_all) - # Don't check for shared/static. Everything works. - # This might be a little naive. We might want to check - # whether the library exists or not. But this is on - # osf3 & osf4 and I'm not really sure... Just - # implementing what was already the behavior. - newdeplibs=$deplibs - ;; - test_compile) - # This code stresses the "libraries are programs" paradigm to its - # limits. Maybe even breaks it. We compile a program, linking it - # against the deplibs as a proxy for the library. Then we can check - # whether they linked in statically or dynamically with ldd. - $rm conftest.c - cat > conftest.c </dev/null` - for potent_lib in $potential_libs; do - # Follow soft links. - if ls -lLd "$potent_lib" 2>/dev/null \ - | grep " -> " >/dev/null; then - continue - fi - # The statement above tries to avoid entering an - # endless loop below, in case of cyclic links. - # We might still enter an endless loop, since a link - # loop can be closed while we follow links, - # but so what? - potlib="$potent_lib" - while test -h "$potlib" 2>/dev/null; do - potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` - case $potliblink in - [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; - *) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; - esac - done - if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \ - | ${SED} 10q \ - | $EGREP "$file_magic_regex" > /dev/null; then - newdeplibs="$newdeplibs $a_deplib" - a_deplib="" - break 2 - fi - done - done - fi - if test -n "$a_deplib" ; then - droppeddeps=yes - $echo - $echo "*** Warning: linker path does not have real file for library $a_deplib." - $echo "*** I have the capability to make that library automatically link in when" - $echo "*** you link to this library. But I can only do this if you have a" - $echo "*** shared version of the library, which you do not appear to have" - $echo "*** because I did check the linker path looking for a file starting" - if test -z "$potlib" ; then - $echo "*** with $libname but no candidates were found. (...for file magic test)" - else - $echo "*** with $libname and none of the candidates passed a file format test" - $echo "*** using a file magic. Last file checked: $potlib" - fi - fi - else - # Add a -L argument. - newdeplibs="$newdeplibs $a_deplib" - fi - done # Gone through all deplibs. - ;; - match_pattern*) - set dummy $deplibs_check_method - match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"` - for a_deplib in $deplibs; do - name=`expr $a_deplib : '-l\(.*\)'` - # If $name is empty we are operating on a -L argument. - if test -n "$name" && test "$name" != "0"; then - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - case " $predeps $postdeps " in - *" $a_deplib "*) - newdeplibs="$newdeplibs $a_deplib" - a_deplib="" - ;; - esac - fi - if test -n "$a_deplib" ; then - libname=`eval \\$echo \"$libname_spec\"` - for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do - potential_libs=`ls $i/$libname[.-]* 2>/dev/null` - for potent_lib in $potential_libs; do - potlib="$potent_lib" # see symlink-check above in file_magic test - if eval $echo \"$potent_lib\" 2>/dev/null \ - | ${SED} 10q \ - | $EGREP "$match_pattern_regex" > /dev/null; then - newdeplibs="$newdeplibs $a_deplib" - a_deplib="" - break 2 - fi - done - done - fi - if test -n "$a_deplib" ; then - droppeddeps=yes - $echo - $echo "*** Warning: linker path does not have real file for library $a_deplib." - $echo "*** I have the capability to make that library automatically link in when" - $echo "*** you link to this library. But I can only do this if you have a" - $echo "*** shared version of the library, which you do not appear to have" - $echo "*** because I did check the linker path looking for a file starting" - if test -z "$potlib" ; then - $echo "*** with $libname but no candidates were found. (...for regex pattern test)" - else - $echo "*** with $libname and none of the candidates passed a file format test" - $echo "*** using a regex pattern. Last file checked: $potlib" - fi - fi - else - # Add a -L argument. - newdeplibs="$newdeplibs $a_deplib" - fi - done # Gone through all deplibs. - ;; - none | unknown | *) - newdeplibs="" - tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \ - -e 's/ -[LR][^ ]*//g'` - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - for i in $predeps $postdeps ; do - # can't use Xsed below, because $i might contain '/' - tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"` - done - fi - if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \ - | grep . >/dev/null; then - $echo - if test "X$deplibs_check_method" = "Xnone"; then - $echo "*** Warning: inter-library dependencies are not supported in this platform." - else - $echo "*** Warning: inter-library dependencies are not known to be supported." - fi - $echo "*** All declared inter-library dependencies are being dropped." - droppeddeps=yes - fi - ;; - esac - versuffix=$versuffix_save - major=$major_save - release=$release_save - libname=$libname_save - name=$name_save - - case $host in - *-*-rhapsody* | *-*-darwin1.[012]) - # On Rhapsody replace the C library is the System framework - newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'` - ;; - esac - - if test "$droppeddeps" = yes; then - if test "$module" = yes; then - $echo - $echo "*** Warning: libtool could not satisfy all declared inter-library" - $echo "*** dependencies of module $libname. Therefore, libtool will create" - $echo "*** a static module, that should work as long as the dlopening" - $echo "*** application is linked with the -dlopen flag." - if test -z "$global_symbol_pipe"; then - $echo - $echo "*** However, this would only work if libtool was able to extract symbol" - $echo "*** lists from a program, using \`nm' or equivalent, but libtool could" - $echo "*** not find such a program. So, this module is probably useless." - $echo "*** \`nm' from GNU binutils and a full rebuild may help." - fi - if test "$build_old_libs" = no; then - oldlibs="$output_objdir/$libname.$libext" - build_libtool_libs=module - build_old_libs=yes - else - build_libtool_libs=no - fi - else - $echo "*** The inter-library dependencies that have been dropped here will be" - $echo "*** automatically added whenever a program is linked with this library" - $echo "*** or is declared to -dlopen it." - - if test "$allow_undefined" = no; then - $echo - $echo "*** Since this library must not contain undefined symbols," - $echo "*** because either the platform does not support them or" - $echo "*** it was explicitly requested with -no-undefined," - $echo "*** libtool will only create a static version of it." - if test "$build_old_libs" = no; then - oldlibs="$output_objdir/$libname.$libext" - build_libtool_libs=module - build_old_libs=yes - else - build_libtool_libs=no - fi - fi - fi - fi - # Done checking deplibs! - deplibs=$newdeplibs - fi - - - # move library search paths that coincide with paths to not yet - # installed libraries to the beginning of the library search list - new_libs= - for path in $notinst_path; do - case " $new_libs " in - *" -L$path/$objdir "*) ;; - *) - case " $deplibs " in - *" -L$path/$objdir "*) - new_libs="$new_libs -L$path/$objdir" ;; - esac - ;; - esac - done - for deplib in $deplibs; do - case $deplib in - -L*) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$new_libs $deplib" ;; - esac - ;; - *) new_libs="$new_libs $deplib" ;; - esac - done - deplibs="$new_libs" - - - # All the library-specific variables (install_libdir is set above). - library_names= - old_library= - dlname= - - # Test again, we may have decided not to build it any more - if test "$build_libtool_libs" = yes; then - if test "$hardcode_into_libs" = yes; then - # Hardcode the library paths - hardcode_libdirs= - dep_rpath= - rpath="$finalize_rpath" - test "$mode" != relink && rpath="$compile_rpath$rpath" - for libdir in $rpath; do - if test -n "$hardcode_libdir_flag_spec"; then - if test -n "$hardcode_libdir_separator"; then - if test -z "$hardcode_libdirs"; then - hardcode_libdirs="$libdir" - else - # Just accumulate the unique libdirs. - case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in - *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) - ;; - *) - hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" - ;; - esac - fi - else - eval flag=\"$hardcode_libdir_flag_spec\" - dep_rpath="$dep_rpath $flag" - fi - elif test -n "$runpath_var"; then - case "$perm_rpath " in - *" $libdir "*) ;; - *) perm_rpath="$perm_rpath $libdir" ;; - esac - fi - done - # Substitute the hardcoded libdirs into the rpath. - if test -n "$hardcode_libdir_separator" && - test -n "$hardcode_libdirs"; then - libdir="$hardcode_libdirs" - if test -n "$hardcode_libdir_flag_spec_ld"; then - eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" - else - eval dep_rpath=\"$hardcode_libdir_flag_spec\" - fi - fi - if test -n "$runpath_var" && test -n "$perm_rpath"; then - # We should set the runpath_var. - rpath= - for dir in $perm_rpath; do - rpath="$rpath$dir:" - done - eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" - fi - test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" - fi - - shlibpath="$finalize_shlibpath" - test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" - if test -n "$shlibpath"; then - eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" - fi - - # Get the real and link names of the library. - eval shared_ext=\"$shrext_cmds\" - eval library_names=\"$library_names_spec\" - set dummy $library_names - realname="$2" - shift; shift - - if test -n "$soname_spec"; then - eval soname=\"$soname_spec\" - else - soname="$realname" - fi - if test -z "$dlname"; then - dlname=$soname - fi - - lib="$output_objdir/$realname" - linknames= - for link - do - linknames="$linknames $link" - done - - # Use standard objects if they are pic - test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - - # Prepare the list of exported symbols - if test -z "$export_symbols"; then - if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then - $show "generating symbol list for \`$libname.la'" - export_symbols="$output_objdir/$libname.exp" - $run $rm $export_symbols - cmds=$export_symbols_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - if len=`expr "X$cmd" : ".*"` && - test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then - $show "$cmd" - $run eval "$cmd" || exit $? - skipped_export=false - else - # The command line is too long to execute in one step. - $show "using reloadable object file for export list..." - skipped_export=: - # Break out early, otherwise skipped_export may be - # set to false by a later but shorter cmd. - break - fi - done - IFS="$save_ifs" - if test -n "$export_symbols_regex"; then - $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"" - $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' - $show "$mv \"${export_symbols}T\" \"$export_symbols\"" - $run eval '$mv "${export_symbols}T" "$export_symbols"' - fi - fi - fi - - if test -n "$export_symbols" && test -n "$include_expsyms"; then - $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"' - fi - - tmp_deplibs= - for test_deplib in $deplibs; do - case " $convenience " in - *" $test_deplib "*) ;; - *) - tmp_deplibs="$tmp_deplibs $test_deplib" - ;; - esac - done - deplibs="$tmp_deplibs" - - if test -n "$convenience"; then - if test -n "$whole_archive_flag_spec"; then - save_libobjs=$libobjs - eval libobjs=\"\$libobjs $whole_archive_flag_spec\" - else - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - func_extract_archives $gentop $convenience - libobjs="$libobjs $func_extract_archives_result" - fi - fi - - if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then - eval flag=\"$thread_safe_flag_spec\" - linker_flags="$linker_flags $flag" - fi - - # Make a backup of the uninstalled library when relinking - if test "$mode" = relink; then - $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $? - fi - - # Do each of the archive commands. - if test "$module" = yes && test -n "$module_cmds" ; then - if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then - eval test_cmds=\"$module_expsym_cmds\" - cmds=$module_expsym_cmds - else - eval test_cmds=\"$module_cmds\" - cmds=$module_cmds - fi - else - if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then - eval test_cmds=\"$archive_expsym_cmds\" - cmds=$archive_expsym_cmds - else - eval test_cmds=\"$archive_cmds\" - cmds=$archive_cmds - fi - fi - - if test "X$skipped_export" != "X:" && - len=`expr "X$test_cmds" : ".*" 2>/dev/null` && - test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then - : - else - # The command line is too long to link in one step, link piecewise. - $echo "creating reloadable object files..." - - # Save the value of $output and $libobjs because we want to - # use them later. If we have whole_archive_flag_spec, we - # want to use save_libobjs as it was before - # whole_archive_flag_spec was expanded, because we can't - # assume the linker understands whole_archive_flag_spec. - # This may have to be revisited, in case too many - # convenience libraries get linked in and end up exceeding - # the spec. - if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then - save_libobjs=$libobjs - fi - save_output=$output - output_la=`$echo "X$output" | $Xsed -e "$basename"` - - # Clear the reloadable object creation command queue and - # initialize k to one. - test_cmds= - concat_cmds= - objlist= - delfiles= - last_robj= - k=1 - output=$output_objdir/$output_la-${k}.$objext - # Loop over the list of objects to be linked. - for obj in $save_libobjs - do - eval test_cmds=\"$reload_cmds $objlist $last_robj\" - if test "X$objlist" = X || - { len=`expr "X$test_cmds" : ".*" 2>/dev/null` && - test "$len" -le "$max_cmd_len"; }; then - objlist="$objlist $obj" - else - # The command $test_cmds is almost too long, add a - # command to the queue. - if test "$k" -eq 1 ; then - # The first file doesn't have a previous command to add. - eval concat_cmds=\"$reload_cmds $objlist $last_robj\" - else - # All subsequent reloadable object files will link in - # the last one created. - eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\" - fi - last_robj=$output_objdir/$output_la-${k}.$objext - k=`expr $k + 1` - output=$output_objdir/$output_la-${k}.$objext - objlist=$obj - len=1 - fi - done - # Handle the remaining objects by creating one last - # reloadable object file. All subsequent reloadable object - # files will link in the last one created. - test -z "$concat_cmds" || concat_cmds=$concat_cmds~ - eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" - - if ${skipped_export-false}; then - $show "generating symbol list for \`$libname.la'" - export_symbols="$output_objdir/$libname.exp" - $run $rm $export_symbols - libobjs=$output - # Append the command to create the export file. - eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\" - fi - - # Set up a command to remove the reloadable object files - # after they are used. - i=0 - while test "$i" -lt "$k" - do - i=`expr $i + 1` - delfiles="$delfiles $output_objdir/$output_la-${i}.$objext" - done - - $echo "creating a temporary reloadable object file: $output" - - # Loop through the commands generated above and execute them. - save_ifs="$IFS"; IFS='~' - for cmd in $concat_cmds; do - IFS="$save_ifs" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - - libobjs=$output - # Restore the value of output. - output=$save_output - - if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then - eval libobjs=\"\$libobjs $whole_archive_flag_spec\" - fi - # Expand the library linking commands again to reset the - # value of $libobjs for piecewise linking. - - # Do each of the archive commands. - if test "$module" = yes && test -n "$module_cmds" ; then - if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then - cmds=$module_expsym_cmds - else - cmds=$module_cmds - fi - else - if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then - cmds=$archive_expsym_cmds - else - cmds=$archive_cmds - fi - fi - - # Append the command to remove the reloadable object files - # to the just-reset $cmds. - eval cmds=\"\$cmds~\$rm $delfiles\" - fi - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || { - lt_exit=$? - - # Restore the uninstalled library and exit - if test "$mode" = relink; then - $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)' - fi - - exit $lt_exit - } - done - IFS="$save_ifs" - - # Restore the uninstalled library and exit - if test "$mode" = relink; then - $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $? - - if test -n "$convenience"; then - if test -z "$whole_archive_flag_spec"; then - $show "${rm}r $gentop" - $run ${rm}r "$gentop" - fi - fi - - exit $EXIT_SUCCESS - fi - - # Create links to the real library. - for linkname in $linknames; do - if test "$realname" != "$linkname"; then - $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)" - $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $? - fi - done - - # If -module or -export-dynamic was specified, set the dlname. - if test "$module" = yes || test "$export_dynamic" = yes; then - # On all known operating systems, these are identical. - dlname="$soname" - fi - fi - ;; - - obj) - if test -n "$deplibs"; then - $echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2 - fi - - if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then - $echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2 - fi - - if test -n "$rpath"; then - $echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2 - fi - - if test -n "$xrpath"; then - $echo "$modename: warning: \`-R' is ignored for objects" 1>&2 - fi - - if test -n "$vinfo"; then - $echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2 - fi - - if test -n "$release"; then - $echo "$modename: warning: \`-release' is ignored for objects" 1>&2 - fi - - case $output in - *.lo) - if test -n "$objs$old_deplibs"; then - $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2 - exit $EXIT_FAILURE - fi - libobj="$output" - obj=`$echo "X$output" | $Xsed -e "$lo2o"` - ;; - *) - libobj= - obj="$output" - ;; - esac - - # Delete the old objects. - $run $rm $obj $libobj - - # Objects from convenience libraries. This assumes - # single-version convenience libraries. Whenever we create - # different ones for PIC/non-PIC, this we'll have to duplicate - # the extraction. - reload_conv_objs= - gentop= - # reload_cmds runs $LD directly, so let us get rid of - # -Wl from whole_archive_flag_spec - wl= - - if test -n "$convenience"; then - if test -n "$whole_archive_flag_spec"; then - eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\" - else - gentop="$output_objdir/${obj}x" - generated="$generated $gentop" - - func_extract_archives $gentop $convenience - reload_conv_objs="$reload_objs $func_extract_archives_result" - fi - fi - - # Create the old-style object. - reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test - - output="$obj" - cmds=$reload_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - - # Exit if we aren't doing a library object file. - if test -z "$libobj"; then - if test -n "$gentop"; then - $show "${rm}r $gentop" - $run ${rm}r $gentop - fi - - exit $EXIT_SUCCESS - fi - - if test "$build_libtool_libs" != yes; then - if test -n "$gentop"; then - $show "${rm}r $gentop" - $run ${rm}r $gentop - fi - - # Create an invalid libtool object if no PIC, so that we don't - # accidentally link it into a program. - # $show "echo timestamp > $libobj" - # $run eval "echo timestamp > $libobj" || exit $? - exit $EXIT_SUCCESS - fi - - if test -n "$pic_flag" || test "$pic_mode" != default; then - # Only do commands if we really have different PIC objects. - reload_objs="$libobjs $reload_conv_objs" - output="$libobj" - cmds=$reload_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - fi - - if test -n "$gentop"; then - $show "${rm}r $gentop" - $run ${rm}r $gentop - fi - - exit $EXIT_SUCCESS - ;; - - prog) - case $host in - *cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;; - esac - if test -n "$vinfo"; then - $echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2 - fi - - if test -n "$release"; then - $echo "$modename: warning: \`-release' is ignored for programs" 1>&2 - fi - - if test "$preload" = yes; then - if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown && - test "$dlopen_self_static" = unknown; then - $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support." - fi - fi - - case $host in - *-*-rhapsody* | *-*-darwin1.[012]) - # On Rhapsody replace the C library is the System framework - compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'` - finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'` - ;; - esac - - case $host in - *darwin*) - # Don't allow lazy linking, it breaks C++ global constructors - if test "$tagname" = CXX ; then - compile_command="$compile_command ${wl}-bind_at_load" - finalize_command="$finalize_command ${wl}-bind_at_load" - fi - ;; - esac - - - # move library search paths that coincide with paths to not yet - # installed libraries to the beginning of the library search list - new_libs= - for path in $notinst_path; do - case " $new_libs " in - *" -L$path/$objdir "*) ;; - *) - case " $compile_deplibs " in - *" -L$path/$objdir "*) - new_libs="$new_libs -L$path/$objdir" ;; - esac - ;; - esac - done - for deplib in $compile_deplibs; do - case $deplib in - -L*) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$new_libs $deplib" ;; - esac - ;; - *) new_libs="$new_libs $deplib" ;; - esac - done - compile_deplibs="$new_libs" - - - compile_command="$compile_command $compile_deplibs" - finalize_command="$finalize_command $finalize_deplibs" - - if test -n "$rpath$xrpath"; then - # If the user specified any rpath flags, then add them. - for libdir in $rpath $xrpath; do - # This is the magic to use -rpath. - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" ;; - esac - done - fi - - # Now hardcode the library paths - rpath= - hardcode_libdirs= - for libdir in $compile_rpath $finalize_rpath; do - if test -n "$hardcode_libdir_flag_spec"; then - if test -n "$hardcode_libdir_separator"; then - if test -z "$hardcode_libdirs"; then - hardcode_libdirs="$libdir" - else - # Just accumulate the unique libdirs. - case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in - *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) - ;; - *) - hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" - ;; - esac - fi - else - eval flag=\"$hardcode_libdir_flag_spec\" - rpath="$rpath $flag" - fi - elif test -n "$runpath_var"; then - case "$perm_rpath " in - *" $libdir "*) ;; - *) perm_rpath="$perm_rpath $libdir" ;; - esac - fi - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - testbindir=`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'` - case :$dllsearchpath: in - *":$libdir:"*) ;; - *) dllsearchpath="$dllsearchpath:$libdir";; - esac - case :$dllsearchpath: in - *":$testbindir:"*) ;; - *) dllsearchpath="$dllsearchpath:$testbindir";; - esac - ;; - esac - done - # Substitute the hardcoded libdirs into the rpath. - if test -n "$hardcode_libdir_separator" && - test -n "$hardcode_libdirs"; then - libdir="$hardcode_libdirs" - eval rpath=\" $hardcode_libdir_flag_spec\" - fi - compile_rpath="$rpath" - - rpath= - hardcode_libdirs= - for libdir in $finalize_rpath; do - if test -n "$hardcode_libdir_flag_spec"; then - if test -n "$hardcode_libdir_separator"; then - if test -z "$hardcode_libdirs"; then - hardcode_libdirs="$libdir" - else - # Just accumulate the unique libdirs. - case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in - *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) - ;; - *) - hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" - ;; - esac - fi - else - eval flag=\"$hardcode_libdir_flag_spec\" - rpath="$rpath $flag" - fi - elif test -n "$runpath_var"; then - case "$finalize_perm_rpath " in - *" $libdir "*) ;; - *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; - esac - fi - done - # Substitute the hardcoded libdirs into the rpath. - if test -n "$hardcode_libdir_separator" && - test -n "$hardcode_libdirs"; then - libdir="$hardcode_libdirs" - eval rpath=\" $hardcode_libdir_flag_spec\" - fi - finalize_rpath="$rpath" - - if test -n "$libobjs" && test "$build_old_libs" = yes; then - # Transform all the library objects into standard objects. - compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - fi - - dlsyms= - if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then - if test -n "$NM" && test -n "$global_symbol_pipe"; then - dlsyms="${outputname}S.c" - else - $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2 - fi - fi - - if test -n "$dlsyms"; then - case $dlsyms in - "") ;; - *.c) - # Discover the nlist of each of the dlfiles. - nlist="$output_objdir/${outputname}.nm" - - $show "$rm $nlist ${nlist}S ${nlist}T" - $run $rm "$nlist" "${nlist}S" "${nlist}T" - - # Parse the name list into a source file. - $show "creating $output_objdir/$dlsyms" - - test -z "$run" && $echo > "$output_objdir/$dlsyms" "\ -/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */ -/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */ - -#ifdef __cplusplus -extern \"C\" { -#endif - -/* Prevent the only kind of declaration conflicts we can make. */ -#define lt_preloaded_symbols some_other_symbol - -/* External symbol declarations for the compiler. */\ -" - - if test "$dlself" = yes; then - $show "generating symbol list for \`$output'" - - test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist" - - # Add our own program objects to the symbol list. - progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - for arg in $progfiles; do - $show "extracting global C symbols from \`$arg'" - $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'" - done - - if test -n "$exclude_expsyms"; then - $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' - $run eval '$mv "$nlist"T "$nlist"' - fi - - if test -n "$export_symbols_regex"; then - $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' - $run eval '$mv "$nlist"T "$nlist"' - fi - - # Prepare the list of exported symbols - if test -z "$export_symbols"; then - export_symbols="$output_objdir/$outputname.exp" - $run $rm $export_symbols - $run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' - case $host in - *cygwin* | *mingw* ) - $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' - $run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' - ;; - esac - else - $run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' - $run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' - $run eval 'mv "$nlist"T "$nlist"' - case $host in - *cygwin* | *mingw* ) - $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' - $run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' - ;; - esac - fi - fi - - for arg in $dlprefiles; do - $show "extracting global C symbols from \`$arg'" - name=`$echo "$arg" | ${SED} -e 's%^.*/%%'` - $run eval '$echo ": $name " >> "$nlist"' - $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'" - done - - if test -z "$run"; then - # Make sure we have at least an empty file. - test -f "$nlist" || : > "$nlist" - - if test -n "$exclude_expsyms"; then - $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T - $mv "$nlist"T "$nlist" - fi - - # Try sorting and uniquifying the output. - if grep -v "^: " < "$nlist" | - if sort -k 3
/dev/null 2>&1; then - sort -k 3 - else - sort +2 - fi | - uniq > "$nlist"S; then - : - else - grep -v "^: " < "$nlist" > "$nlist"S - fi - - if test -f "$nlist"S; then - eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"' - else - $echo '/* NONE */' >> "$output_objdir/$dlsyms" - fi - - $echo >> "$output_objdir/$dlsyms" "\ - -#undef lt_preloaded_symbols - -#if defined (__STDC__) && __STDC__ -# define lt_ptr void * -#else -# define lt_ptr char * -# define const -#endif - -/* The mapping between symbol names and symbols. */ -" - - case $host in - *cygwin* | *mingw* ) - $echo >> "$output_objdir/$dlsyms" "\ -/* DATA imports from DLLs on WIN32 can't be const, because - runtime relocations are performed -- see ld's documentation - on pseudo-relocs */ -struct { -" - ;; - * ) - $echo >> "$output_objdir/$dlsyms" "\ -const struct { -" - ;; - esac - - - $echo >> "$output_objdir/$dlsyms" "\ - const char *name; - lt_ptr address; -} -lt_preloaded_symbols[] = -{\ -" - - eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms" - - $echo >> "$output_objdir/$dlsyms" "\ - {0, (lt_ptr) 0} -}; - -/* This works around a problem in FreeBSD linker */ -#ifdef FREEBSD_WORKAROUND -static const void *lt_preloaded_setup() { - return lt_preloaded_symbols; -} -#endif - -#ifdef __cplusplus -} -#endif\ -" - fi - - pic_flag_for_symtable= - case $host in - # compiling the symbol table file with pic_flag works around - # a FreeBSD bug that causes programs to crash when -lm is - # linked before any other PIC object. But we must not use - # pic_flag when linking with -static. The problem exists in - # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. - *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) - case "$compile_command " in - *" -static "*) ;; - *) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";; - esac;; - *-*-hpux*) - case "$compile_command " in - *" -static "*) ;; - *) pic_flag_for_symtable=" $pic_flag";; - esac - esac - - # Now compile the dynamic symbol file. - $show "(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")" - $run eval '(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $? - - # Clean up the generated files. - $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T" - $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T" - - # Transform the symbol file into the correct name. - case $host in - *cygwin* | *mingw* ) - if test -f "$output_objdir/${outputname}.def" ; then - compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"` - else - compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` - fi - ;; - * ) - compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` - ;; - esac - ;; - *) - $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2 - exit $EXIT_FAILURE - ;; - esac - else - # We keep going just in case the user didn't refer to - # lt_preloaded_symbols. The linker will fail if global_symbol_pipe - # really was required. - - # Nullify the symbol file. - compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` - fi - - if test "$need_relink" = no || test "$build_libtool_libs" != yes; then - # Replace the output file specification. - compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` - link_command="$compile_command$compile_rpath" - - # We have no uninstalled library dependencies, so finalize right now. - $show "$link_command" - $run eval "$link_command" - exit_status=$? - - # Delete the generated files. - if test -n "$dlsyms"; then - $show "$rm $output_objdir/${outputname}S.${objext}" - $run $rm "$output_objdir/${outputname}S.${objext}" - fi - - exit $exit_status - fi - - if test -n "$shlibpath_var"; then - # We should set the shlibpath_var - rpath= - for dir in $temp_rpath; do - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) - # Absolute path. - rpath="$rpath$dir:" - ;; - *) - # Relative path: add a thisdir entry. - rpath="$rpath\$thisdir/$dir:" - ;; - esac - done - temp_rpath="$rpath" - fi - - if test -n "$compile_shlibpath$finalize_shlibpath"; then - compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" - fi - if test -n "$finalize_shlibpath"; then - finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" - fi - - compile_var= - finalize_var= - if test -n "$runpath_var"; then - if test -n "$perm_rpath"; then - # We should set the runpath_var. - rpath= - for dir in $perm_rpath; do - rpath="$rpath$dir:" - done - compile_var="$runpath_var=\"$rpath\$$runpath_var\" " - fi - if test -n "$finalize_perm_rpath"; then - # We should set the runpath_var. - rpath= - for dir in $finalize_perm_rpath; do - rpath="$rpath$dir:" - done - finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " - fi - fi - - if test "$no_install" = yes; then - # We don't need to create a wrapper script. - link_command="$compile_var$compile_command$compile_rpath" - # Replace the output file specification. - link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` - # Delete the old output file. - $run $rm $output - # Link the executable and exit - $show "$link_command" - $run eval "$link_command" || exit $? - exit $EXIT_SUCCESS - fi - - if test "$hardcode_action" = relink; then - # Fast installation is not supported - link_command="$compile_var$compile_command$compile_rpath" - relink_command="$finalize_var$finalize_command$finalize_rpath" - - $echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2 - $echo "$modename: \`$output' will be relinked during installation" 1>&2 - else - if test "$fast_install" != no; then - link_command="$finalize_var$compile_command$finalize_rpath" - if test "$fast_install" = yes; then - relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` - else - # fast_install is set to needless - relink_command= - fi - else - link_command="$compile_var$compile_command$compile_rpath" - relink_command="$finalize_var$finalize_command$finalize_rpath" - fi - fi - - # Replace the output file specification. - link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` - - # Delete the old output files. - $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname - - $show "$link_command" - $run eval "$link_command" || exit $? - - # Now create the wrapper script. - $show "creating $output" - - # Quote the relink command for shipping. - if test -n "$relink_command"; then - # Preserve any variables that may affect compiler behavior - for var in $variables_saved_for_relink; do - if eval test -z \"\${$var+set}\"; then - relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command" - elif eval var_value=\$$var; test -z "$var_value"; then - relink_command="$var=; export $var; $relink_command" - else - var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"` - relink_command="$var=\"$var_value\"; export $var; $relink_command" - fi - done - relink_command="(cd `pwd`; $relink_command)" - relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` - fi - - # Quote $echo for shipping. - if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then - case $progpath in - [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; - *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; - esac - qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"` - else - qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"` - fi - - # Only actually do things if our run command is non-null. - if test -z "$run"; then - # win32 will think the script is a binary if it has - # a .exe suffix, so we strip it off here. - case $output in - *.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;; - esac - # test for cygwin because mv fails w/o .exe extensions - case $host in - *cygwin*) - exeext=.exe - outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;; - *) exeext= ;; - esac - case $host in - *cygwin* | *mingw* ) - output_name=`basename $output` - output_path=`dirname $output` - cwrappersource="$output_path/$objdir/lt-$output_name.c" - cwrapper="$output_path/$output_name.exe" - $rm $cwrappersource $cwrapper - trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 - - cat > $cwrappersource <> $cwrappersource<<"EOF" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(PATH_MAX) -# define LT_PATHMAX PATH_MAX -#elif defined(MAXPATHLEN) -# define LT_PATHMAX MAXPATHLEN -#else -# define LT_PATHMAX 1024 -#endif - -#ifndef DIR_SEPARATOR -# define DIR_SEPARATOR '/' -# define PATH_SEPARATOR ':' -#endif - -#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ - defined (__OS2__) -# define HAVE_DOS_BASED_FILE_SYSTEM -# ifndef DIR_SEPARATOR_2 -# define DIR_SEPARATOR_2 '\\' -# endif -# ifndef PATH_SEPARATOR_2 -# define PATH_SEPARATOR_2 ';' -# endif -#endif - -#ifndef DIR_SEPARATOR_2 -# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) -#else /* DIR_SEPARATOR_2 */ -# define IS_DIR_SEPARATOR(ch) \ - (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) -#endif /* DIR_SEPARATOR_2 */ - -#ifndef PATH_SEPARATOR_2 -# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) -#else /* PATH_SEPARATOR_2 */ -# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) -#endif /* PATH_SEPARATOR_2 */ - -#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) -#define XFREE(stale) do { \ - if (stale) { free ((void *) stale); stale = 0; } \ -} while (0) - -/* -DDEBUG is fairly common in CFLAGS. */ -#undef DEBUG -#if defined DEBUGWRAPPER -# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__) -#else -# define DEBUG(format, ...) -#endif - -const char *program_name = NULL; - -void * xmalloc (size_t num); -char * xstrdup (const char *string); -const char * base_name (const char *name); -char * find_executable(const char *wrapper); -int check_executable(const char *path); -char * strendzap(char *str, const char *pat); -void lt_fatal (const char *message, ...); - -int -main (int argc, char *argv[]) -{ - char **newargz; - int i; - - program_name = (char *) xstrdup (base_name (argv[0])); - DEBUG("(main) argv[0] : %s\n",argv[0]); - DEBUG("(main) program_name : %s\n",program_name); - newargz = XMALLOC(char *, argc+2); -EOF - - cat >> $cwrappersource <> $cwrappersource <<"EOF" - newargz[1] = find_executable(argv[0]); - if (newargz[1] == NULL) - lt_fatal("Couldn't find %s", argv[0]); - DEBUG("(main) found exe at : %s\n",newargz[1]); - /* we know the script has the same name, without the .exe */ - /* so make sure newargz[1] doesn't end in .exe */ - strendzap(newargz[1],".exe"); - for (i = 1; i < argc; i++) - newargz[i+1] = xstrdup(argv[i]); - newargz[argc+1] = NULL; - - for (i=0; i> $cwrappersource <> $cwrappersource <> $cwrappersource <<"EOF" - return 127; -} - -void * -xmalloc (size_t num) -{ - void * p = (void *) malloc (num); - if (!p) - lt_fatal ("Memory exhausted"); - - return p; -} - -char * -xstrdup (const char *string) -{ - return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL -; -} - -const char * -base_name (const char *name) -{ - const char *base; - -#if defined (HAVE_DOS_BASED_FILE_SYSTEM) - /* Skip over the disk name in MSDOS pathnames. */ - if (isalpha ((unsigned char)name[0]) && name[1] == ':') - name += 2; -#endif - - for (base = name; *name; name++) - if (IS_DIR_SEPARATOR (*name)) - base = name + 1; - return base; -} - -int -check_executable(const char * path) -{ - struct stat st; - - DEBUG("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!"); - if ((!path) || (!*path)) - return 0; - - if ((stat (path, &st) >= 0) && - ( - /* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */ -#if defined (S_IXOTH) - ((st.st_mode & S_IXOTH) == S_IXOTH) || -#endif -#if defined (S_IXGRP) - ((st.st_mode & S_IXGRP) == S_IXGRP) || -#endif - ((st.st_mode & S_IXUSR) == S_IXUSR)) - ) - return 1; - else - return 0; -} - -/* Searches for the full path of the wrapper. Returns - newly allocated full path name if found, NULL otherwise */ -char * -find_executable (const char* wrapper) -{ - int has_slash = 0; - const char* p; - const char* p_next; - /* static buffer for getcwd */ - char tmp[LT_PATHMAX + 1]; - int tmp_len; - char* concat_name; - - DEBUG("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!"); - - if ((wrapper == NULL) || (*wrapper == '\0')) - return NULL; - - /* Absolute path? */ -#if defined (HAVE_DOS_BASED_FILE_SYSTEM) - if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] == ':') - { - concat_name = xstrdup (wrapper); - if (check_executable(concat_name)) - return concat_name; - XFREE(concat_name); - } - else - { -#endif - if (IS_DIR_SEPARATOR (wrapper[0])) - { - concat_name = xstrdup (wrapper); - if (check_executable(concat_name)) - return concat_name; - XFREE(concat_name); - } -#if defined (HAVE_DOS_BASED_FILE_SYSTEM) - } -#endif - - for (p = wrapper; *p; p++) - if (*p == '/') - { - has_slash = 1; - break; - } - if (!has_slash) - { - /* no slashes; search PATH */ - const char* path = getenv ("PATH"); - if (path != NULL) - { - for (p = path; *p; p = p_next) - { - const char* q; - size_t p_len; - for (q = p; *q; q++) - if (IS_PATH_SEPARATOR(*q)) - break; - p_len = q - p; - p_next = (*q == '\0' ? q : q + 1); - if (p_len == 0) - { - /* empty path: current directory */ - if (getcwd (tmp, LT_PATHMAX) == NULL) - lt_fatal ("getcwd failed"); - tmp_len = strlen(tmp); - concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1); - memcpy (concat_name, tmp, tmp_len); - concat_name[tmp_len] = '/'; - strcpy (concat_name + tmp_len + 1, wrapper); - } - else - { - concat_name = XMALLOC(char, p_len + 1 + strlen(wrapper) + 1); - memcpy (concat_name, p, p_len); - concat_name[p_len] = '/'; - strcpy (concat_name + p_len + 1, wrapper); - } - if (check_executable(concat_name)) - return concat_name; - XFREE(concat_name); - } - } - /* not found in PATH; assume curdir */ - } - /* Relative path | not found in path: prepend cwd */ - if (getcwd (tmp, LT_PATHMAX) == NULL) - lt_fatal ("getcwd failed"); - tmp_len = strlen(tmp); - concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1); - memcpy (concat_name, tmp, tmp_len); - concat_name[tmp_len] = '/'; - strcpy (concat_name + tmp_len + 1, wrapper); - - if (check_executable(concat_name)) - return concat_name; - XFREE(concat_name); - return NULL; -} - -char * -strendzap(char *str, const char *pat) -{ - size_t len, patlen; - - assert(str != NULL); - assert(pat != NULL); - - len = strlen(str); - patlen = strlen(pat); - - if (patlen <= len) - { - str += len - patlen; - if (strcmp(str, pat) == 0) - *str = '\0'; - } - return str; -} - -static void -lt_error_core (int exit_status, const char * mode, - const char * message, va_list ap) -{ - fprintf (stderr, "%s: %s: ", program_name, mode); - vfprintf (stderr, message, ap); - fprintf (stderr, ".\n"); - - if (exit_status >= 0) - exit (exit_status); -} - -void -lt_fatal (const char *message, ...) -{ - va_list ap; - va_start (ap, message); - lt_error_core (EXIT_FAILURE, "FATAL", message, ap); - va_end (ap); -} -EOF - # we should really use a build-platform specific compiler - # here, but OTOH, the wrappers (shell script and this C one) - # are only useful if you want to execute the "real" binary. - # Since the "real" binary is built for $host, then this - # wrapper might as well be built for $host, too. - $run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource - ;; - esac - $rm $output - trap "$rm $output; exit $EXIT_FAILURE" 1 2 15 - - $echo > $output "\ -#! $SHELL - -# $output - temporary wrapper script for $objdir/$outputname -# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP -# -# The $output program cannot be directly executed until all the libtool -# libraries that it depends on are installed. -# -# This wrapper script should never be moved out of the build directory. -# If it is, it will not operate correctly. - -# Sed substitution that helps us do robust quoting. It backslashifies -# metacharacters that are still active within double-quoted strings. -Xsed='${SED} -e 1s/^X//' -sed_quote_subst='$sed_quote_subst' - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -relink_command=\"$relink_command\" - -# This environment variable determines our operation mode. -if test \"\$libtool_install_magic\" = \"$magic\"; then - # install mode needs the following variable: - notinst_deplibs='$notinst_deplibs' -else - # When we are sourced in execute mode, \$file and \$echo are already set. - if test \"\$libtool_execute_magic\" != \"$magic\"; then - echo=\"$qecho\" - file=\"\$0\" - # Make sure echo works. - if test \"X\$1\" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift - elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then - # Yippee, \$echo works! - : - else - # Restart under the correct shell, and then maybe \$echo will work. - exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} - fi - fi\ -" - $echo >> $output "\ - - # Find the directory that this script lives in. - thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` - test \"x\$thisdir\" = \"x\$file\" && thisdir=. - - # Follow symbolic links until we get to the real thisdir. - file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` - while test -n \"\$file\"; do - destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` - - # If there was a directory component, then change thisdir. - if test \"x\$destdir\" != \"x\$file\"; then - case \"\$destdir\" in - [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; - *) thisdir=\"\$thisdir/\$destdir\" ;; - esac - fi - - file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\` - file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` - done - - # Try to get the absolute directory name. - absdir=\`cd \"\$thisdir\" && pwd\` - test -n \"\$absdir\" && thisdir=\"\$absdir\" -" - - if test "$fast_install" = yes; then - $echo >> $output "\ - program=lt-'$outputname'$exeext - progdir=\"\$thisdir/$objdir\" - - if test ! -f \"\$progdir/\$program\" || \\ - { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ - test \"X\$file\" != \"X\$progdir/\$program\"; }; then - - file=\"\$\$-\$program\" - - if test ! -d \"\$progdir\"; then - $mkdir \"\$progdir\" - else - $rm \"\$progdir/\$file\" - fi" - - $echo >> $output "\ - - # relink executable if necessary - if test -n \"\$relink_command\"; then - if relink_command_output=\`eval \$relink_command 2>&1\`; then : - else - $echo \"\$relink_command_output\" >&2 - $rm \"\$progdir/\$file\" - exit $EXIT_FAILURE - fi - fi - - $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || - { $rm \"\$progdir/\$program\"; - $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; } - $rm \"\$progdir/\$file\" - fi" - else - $echo >> $output "\ - program='$outputname' - progdir=\"\$thisdir/$objdir\" -" - fi - - $echo >> $output "\ - - if test -f \"\$progdir/\$program\"; then" - - # Export our shlibpath_var if we have one. - if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then - $echo >> $output "\ - # Add our own library path to $shlibpath_var - $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" - - # Some systems cannot cope with colon-terminated $shlibpath_var - # The second colon is a workaround for a bug in BeOS R4 sed - $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` - - export $shlibpath_var -" - fi - - # fixup the dll searchpath if we need to. - if test -n "$dllsearchpath"; then - $echo >> $output "\ - # Add the dll search path components to the executable PATH - PATH=$dllsearchpath:\$PATH -" - fi - - $echo >> $output "\ - if test \"\$libtool_execute_magic\" != \"$magic\"; then - # Run the actual program with our arguments. -" - case $host in - # Backslashes separate directories on plain windows - *-*-mingw | *-*-os2*) - $echo >> $output "\ - exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} -" - ;; - - *) - $echo >> $output "\ - exec \"\$progdir/\$program\" \${1+\"\$@\"} -" - ;; - esac - $echo >> $output "\ - \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\" - exit $EXIT_FAILURE - fi - else - # The program doesn't exist. - \$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 - \$echo \"This script is just a wrapper for \$program.\" 1>&2 - $echo \"See the $PACKAGE documentation for more information.\" 1>&2 - exit $EXIT_FAILURE - fi -fi\ -" - chmod +x $output - fi - exit $EXIT_SUCCESS - ;; - esac - - # See if we need to build an old-fashioned archive. - for oldlib in $oldlibs; do - - if test "$build_libtool_libs" = convenience; then - oldobjs="$libobjs_save" - addlibs="$convenience" - build_libtool_libs=no - else - if test "$build_libtool_libs" = module; then - oldobjs="$libobjs_save" - build_libtool_libs=no - else - oldobjs="$old_deplibs $non_pic_objects" - fi - addlibs="$old_convenience" - fi - - if test -n "$addlibs"; then - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - func_extract_archives $gentop $addlibs - oldobjs="$oldobjs $func_extract_archives_result" - fi - - # Do each command in the archive commands. - if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then - cmds=$old_archive_from_new_cmds - else - # POSIX demands no paths to be encoded in archives. We have - # to avoid creating archives with duplicate basenames if we - # might have to extract them afterwards, e.g., when creating a - # static archive out of a convenience library, or when linking - # the entirety of a libtool archive into another (currently - # not supported by libtool). - if (for obj in $oldobjs - do - $echo "X$obj" | $Xsed -e 's%^.*/%%' - done | sort | sort -uc >/dev/null 2>&1); then - : - else - $echo "copying selected object files to avoid basename conflicts..." - - if test -z "$gentop"; then - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - $show "${rm}r $gentop" - $run ${rm}r "$gentop" - $show "$mkdir $gentop" - $run $mkdir "$gentop" - exit_status=$? - if test "$exit_status" -ne 0 && test ! -d "$gentop"; then - exit $exit_status - fi - fi - - save_oldobjs=$oldobjs - oldobjs= - counter=1 - for obj in $save_oldobjs - do - objbase=`$echo "X$obj" | $Xsed -e 's%^.*/%%'` - case " $oldobjs " in - " ") oldobjs=$obj ;; - *[\ /]"$objbase "*) - while :; do - # Make sure we don't pick an alternate name that also - # overlaps. - newobj=lt$counter-$objbase - counter=`expr $counter + 1` - case " $oldobjs " in - *[\ /]"$newobj "*) ;; - *) if test ! -f "$gentop/$newobj"; then break; fi ;; - esac - done - $show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" - $run ln "$obj" "$gentop/$newobj" || - $run cp "$obj" "$gentop/$newobj" - oldobjs="$oldobjs $gentop/$newobj" - ;; - *) oldobjs="$oldobjs $obj" ;; - esac - done - fi - - eval cmds=\"$old_archive_cmds\" - - if len=`expr "X$cmds" : ".*"` && - test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then - cmds=$old_archive_cmds - else - # the command line is too long to link in one step, link in parts - $echo "using piecewise archive linking..." - save_RANLIB=$RANLIB - RANLIB=: - objlist= - concat_cmds= - save_oldobjs=$oldobjs - - # Is there a better way of finding the last object in the list? - for obj in $save_oldobjs - do - last_oldobj=$obj - done - for obj in $save_oldobjs - do - oldobjs="$objlist $obj" - objlist="$objlist $obj" - eval test_cmds=\"$old_archive_cmds\" - if len=`expr "X$test_cmds" : ".*" 2>/dev/null` && - test "$len" -le "$max_cmd_len"; then - : - else - # the above command should be used before it gets too long - oldobjs=$objlist - if test "$obj" = "$last_oldobj" ; then - RANLIB=$save_RANLIB - fi - test -z "$concat_cmds" || concat_cmds=$concat_cmds~ - eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" - objlist= - fi - done - RANLIB=$save_RANLIB - oldobjs=$objlist - if test "X$oldobjs" = "X" ; then - eval cmds=\"\$concat_cmds\" - else - eval cmds=\"\$concat_cmds~\$old_archive_cmds\" - fi - fi - fi - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - eval cmd=\"$cmd\" - IFS="$save_ifs" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - done - - if test -n "$generated"; then - $show "${rm}r$generated" - $run ${rm}r$generated - fi - - # Now create the libtool archive. - case $output in - *.la) - old_library= - test "$build_old_libs" = yes && old_library="$libname.$libext" - $show "creating $output" - - # Preserve any variables that may affect compiler behavior - for var in $variables_saved_for_relink; do - if eval test -z \"\${$var+set}\"; then - relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command" - elif eval var_value=\$$var; test -z "$var_value"; then - relink_command="$var=; export $var; $relink_command" - else - var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"` - relink_command="$var=\"$var_value\"; export $var; $relink_command" - fi - done - # Quote the link command for shipping. - relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" - relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` - if test "$hardcode_automatic" = yes ; then - relink_command= - fi - - - # Only create the output if not a dry run. - if test -z "$run"; then - for installed in no yes; do - if test "$installed" = yes; then - if test -z "$install_libdir"; then - break - fi - output="$output_objdir/$outputname"i - # Replace all uninstalled libtool libraries with the installed ones - newdependency_libs= - for deplib in $dependency_libs; do - case $deplib in - *.la) - name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'` - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` - if test -z "$libdir"; then - $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2 - exit $EXIT_FAILURE - fi - newdependency_libs="$newdependency_libs $libdir/$name" - ;; - *) newdependency_libs="$newdependency_libs $deplib" ;; - esac - done - dependency_libs="$newdependency_libs" - newdlfiles= - for lib in $dlfiles; do - name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` - if test -z "$libdir"; then - $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 - exit $EXIT_FAILURE - fi - newdlfiles="$newdlfiles $libdir/$name" - done - dlfiles="$newdlfiles" - newdlprefiles= - for lib in $dlprefiles; do - name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` - if test -z "$libdir"; then - $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 - exit $EXIT_FAILURE - fi - newdlprefiles="$newdlprefiles $libdir/$name" - done - dlprefiles="$newdlprefiles" - else - newdlfiles= - for lib in $dlfiles; do - case $lib in - [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; - *) abs=`pwd`"/$lib" ;; - esac - newdlfiles="$newdlfiles $abs" - done - dlfiles="$newdlfiles" - newdlprefiles= - for lib in $dlprefiles; do - case $lib in - [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; - *) abs=`pwd`"/$lib" ;; - esac - newdlprefiles="$newdlprefiles $abs" - done - dlprefiles="$newdlprefiles" - fi - $rm $output - # place dlname in correct position for cygwin - tdlname=$dlname - case $host,$output,$installed,$module,$dlname in - *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; - esac - $echo > $output "\ -# $outputname - a libtool library file -# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP -# -# Please DO NOT delete this file! -# It is necessary for linking the library. - -# The name that we can dlopen(3). -dlname='$tdlname' - -# Names of this library. -library_names='$library_names' - -# The name of the static archive. -old_library='$old_library' - -# Libraries that this one depends upon. -dependency_libs='$dependency_libs' - -# Version information for $libname. -current=$current -age=$age -revision=$revision - -# Is this an already installed library? -installed=$installed - -# Should we warn about portability when linking against -modules? -shouldnotlink=$module - -# Files to dlopen/dlpreopen -dlopen='$dlfiles' -dlpreopen='$dlprefiles' - -# Directory that this library needs to be installed in: -libdir='$install_libdir'" - if test "$installed" = no && test "$need_relink" = yes; then - $echo >> $output "\ -relink_command=\"$relink_command\"" - fi - done - fi - - # Do a symbolic link so that the libtool archive can be found in - # LD_LIBRARY_PATH before the program is installed. - $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)" - $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $? - ;; - esac - exit $EXIT_SUCCESS - ;; - - # libtool install mode - install) - modename="$modename: install" - - # There may be an optional sh(1) argument at the beginning of - # install_prog (especially on Windows NT). - if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || - # Allow the use of GNU shtool's install command. - $echo "X$nonopt" | grep shtool > /dev/null; then - # Aesthetically quote it. - arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - install_prog="$arg " - arg="$1" - shift - else - install_prog= - arg=$nonopt - fi - - # The real first argument should be the name of the installation program. - # Aesthetically quote it. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - install_prog="$install_prog$arg" - - # We need to accept at least all the BSD install flags. - dest= - files= - opts= - prev= - install_type= - isdir=no - stripme= - for arg - do - if test -n "$dest"; then - files="$files $dest" - dest=$arg - continue - fi - - case $arg in - -d) isdir=yes ;; - -f) - case " $install_prog " in - *[\\\ /]cp\ *) ;; - *) prev=$arg ;; - esac - ;; - -g | -m | -o) prev=$arg ;; - -s) - stripme=" -s" - continue - ;; - -*) - ;; - *) - # If the previous option needed an argument, then skip it. - if test -n "$prev"; then - prev= - else - dest=$arg - continue - fi - ;; - esac - - # Aesthetically quote the argument. - arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` - case $arg in - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - arg="\"$arg\"" - ;; - esac - install_prog="$install_prog $arg" - done - - if test -z "$install_prog"; then - $echo "$modename: you must specify an install program" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - if test -n "$prev"; then - $echo "$modename: the \`$prev' option requires an argument" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - if test -z "$files"; then - if test -z "$dest"; then - $echo "$modename: no file or destination specified" 1>&2 - else - $echo "$modename: you must specify a destination" 1>&2 - fi - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Strip any trailing slash from the destination. - dest=`$echo "X$dest" | $Xsed -e 's%/$%%'` - - # Check to see that the destination is a directory. - test -d "$dest" && isdir=yes - if test "$isdir" = yes; then - destdir="$dest" - destname= - else - destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'` - test "X$destdir" = "X$dest" && destdir=. - destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'` - - # Not a directory, so check to see that there is only one file specified. - set dummy $files - if test "$#" -gt 2; then - $echo "$modename: \`$dest' is not a directory" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - fi - case $destdir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - for file in $files; do - case $file in - *.lo) ;; - *) - $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; - esac - done - ;; - esac - - # This variable tells wrapper scripts just to set variables rather - # than running their programs. - libtool_install_magic="$magic" - - staticlibs= - future_libdirs= - current_libdirs= - for file in $files; do - - # Do each installation. - case $file in - *.$libext) - # Do the static libraries later. - staticlibs="$staticlibs $file" - ;; - - *.la) - # Check to see that this really is a libtool archive. - if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : - else - $echo "$modename: \`$file' is not a valid libtool archive" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - library_names= - old_library= - relink_command= - # If there is no directory component, then add one. - case $file in - */* | *\\*) . $file ;; - *) . ./$file ;; - esac - - # Add the libdir to current_libdirs if it is the destination. - if test "X$destdir" = "X$libdir"; then - case "$current_libdirs " in - *" $libdir "*) ;; - *) current_libdirs="$current_libdirs $libdir" ;; - esac - else - # Note the libdir as a future libdir. - case "$future_libdirs " in - *" $libdir "*) ;; - *) future_libdirs="$future_libdirs $libdir" ;; - esac - fi - - dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/ - test "X$dir" = "X$file/" && dir= - dir="$dir$objdir" - - if test -n "$relink_command"; then - # Determine the prefix the user has applied to our future dir. - inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"` - - # Don't allow the user to place us outside of our expected - # location b/c this prevents finding dependent libraries that - # are installed to the same prefix. - # At present, this check doesn't affect windows .dll's that - # are installed into $libdir/../bin (currently, that works fine) - # but it's something to keep an eye on. - if test "$inst_prefix_dir" = "$destdir"; then - $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2 - exit $EXIT_FAILURE - fi - - if test -n "$inst_prefix_dir"; then - # Stick the inst_prefix_dir data into the link command. - relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` - else - relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%%"` - fi - - $echo "$modename: warning: relinking \`$file'" 1>&2 - $show "$relink_command" - if $run eval "$relink_command"; then : - else - $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2 - exit $EXIT_FAILURE - fi - fi - - # See the names of the shared library. - set dummy $library_names - if test -n "$2"; then - realname="$2" - shift - shift - - srcname="$realname" - test -n "$relink_command" && srcname="$realname"T - - # Install the shared library and build the symlinks. - $show "$install_prog $dir/$srcname $destdir/$realname" - $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $? - if test -n "$stripme" && test -n "$striplib"; then - $show "$striplib $destdir/$realname" - $run eval "$striplib $destdir/$realname" || exit $? - fi - - if test "$#" -gt 0; then - # Delete the old symlinks, and create new ones. - # Try `ln -sf' first, because the `ln' binary might depend on - # the symlink we replace! Solaris /bin/ln does not understand -f, - # so we also need to try rm && ln -s. - for linkname - do - if test "$linkname" != "$realname"; then - $show "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })" - $run eval "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })" - fi - done - fi - - # Do each command in the postinstall commands. - lib="$destdir/$realname" - cmds=$postinstall_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || { - lt_exit=$? - - # Restore the uninstalled library and exit - if test "$mode" = relink; then - $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)' - fi - - exit $lt_exit - } - done - IFS="$save_ifs" - fi - - # Install the pseudo-library for information purposes. - name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` - instname="$dir/$name"i - $show "$install_prog $instname $destdir/$name" - $run eval "$install_prog $instname $destdir/$name" || exit $? - - # Maybe install the static library, too. - test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" - ;; - - *.lo) - # Install (i.e. copy) a libtool object. - - # Figure out destination file name, if it wasn't already specified. - if test -n "$destname"; then - destfile="$destdir/$destname" - else - destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'` - destfile="$destdir/$destfile" - fi - - # Deduce the name of the destination old-style object file. - case $destfile in - *.lo) - staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"` - ;; - *.$objext) - staticdest="$destfile" - destfile= - ;; - *) - $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - # Install the libtool object if requested. - if test -n "$destfile"; then - $show "$install_prog $file $destfile" - $run eval "$install_prog $file $destfile" || exit $? - fi - - # Install the old object if enabled. - if test "$build_old_libs" = yes; then - # Deduce the name of the old-style object file. - staticobj=`$echo "X$file" | $Xsed -e "$lo2o"` - - $show "$install_prog $staticobj $staticdest" - $run eval "$install_prog \$staticobj \$staticdest" || exit $? - fi - exit $EXIT_SUCCESS - ;; - - *) - # Figure out destination file name, if it wasn't already specified. - if test -n "$destname"; then - destfile="$destdir/$destname" - else - destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'` - destfile="$destdir/$destfile" - fi - - # If the file is missing, and there is a .exe on the end, strip it - # because it is most likely a libtool script we actually want to - # install - stripped_ext="" - case $file in - *.exe) - if test ! -f "$file"; then - file=`$echo $file|${SED} 's,.exe$,,'` - stripped_ext=".exe" - fi - ;; - esac - - # Do a test to see if this is really a libtool program. - case $host in - *cygwin*|*mingw*) - wrapper=`$echo $file | ${SED} -e 's,.exe$,,'` - ;; - *) - wrapper=$file - ;; - esac - if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then - notinst_deplibs= - relink_command= - - # Note that it is not necessary on cygwin/mingw to append a dot to - # foo even if both foo and FILE.exe exist: automatic-append-.exe - # behavior happens only for exec(3), not for open(2)! Also, sourcing - # `FILE.' does not work on cygwin managed mounts. - # - # If there is no directory component, then add one. - case $wrapper in - */* | *\\*) . ${wrapper} ;; - *) . ./${wrapper} ;; - esac - - # Check the variables that should have been set. - if test -z "$notinst_deplibs"; then - $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2 - exit $EXIT_FAILURE - fi - - finalize=yes - for lib in $notinst_deplibs; do - # Check to see that each library is installed. - libdir= - if test -f "$lib"; then - # If there is no directory component, then add one. - case $lib in - */* | *\\*) . $lib ;; - *) . ./$lib ;; - esac - fi - libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test - if test -n "$libdir" && test ! -f "$libfile"; then - $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2 - finalize=no - fi - done - - relink_command= - # Note that it is not necessary on cygwin/mingw to append a dot to - # foo even if both foo and FILE.exe exist: automatic-append-.exe - # behavior happens only for exec(3), not for open(2)! Also, sourcing - # `FILE.' does not work on cygwin managed mounts. - # - # If there is no directory component, then add one. - case $wrapper in - */* | *\\*) . ${wrapper} ;; - *) . ./${wrapper} ;; - esac - - outputname= - if test "$fast_install" = no && test -n "$relink_command"; then - if test "$finalize" = yes && test -z "$run"; then - tmpdir=`func_mktempdir` - file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'` - outputname="$tmpdir/$file" - # Replace the output file specification. - relink_command=`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` - - $show "$relink_command" - if $run eval "$relink_command"; then : - else - $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2 - ${rm}r "$tmpdir" - continue - fi - file="$outputname" - else - $echo "$modename: warning: cannot relink \`$file'" 1>&2 - fi - else - # Install the binary that we compiled earlier. - file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` - fi - fi - - # remove .exe since cygwin /usr/bin/install will append another - # one anyway - case $install_prog,$host in - */usr/bin/install*,*cygwin*) - case $file:$destfile in - *.exe:*.exe) - # this is ok - ;; - *.exe:*) - destfile=$destfile.exe - ;; - *:*.exe) - destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'` - ;; - esac - ;; - esac - $show "$install_prog$stripme $file $destfile" - $run eval "$install_prog\$stripme \$file \$destfile" || exit $? - test -n "$outputname" && ${rm}r "$tmpdir" - ;; - esac - done - - for file in $staticlibs; do - name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` - - # Set up the ranlib parameters. - oldlib="$destdir/$name" - - $show "$install_prog $file $oldlib" - $run eval "$install_prog \$file \$oldlib" || exit $? - - if test -n "$stripme" && test -n "$old_striplib"; then - $show "$old_striplib $oldlib" - $run eval "$old_striplib $oldlib" || exit $? - fi - - # Do each command in the postinstall commands. - cmds=$old_postinstall_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || exit $? - done - IFS="$save_ifs" - done - - if test -n "$future_libdirs"; then - $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2 - fi - - if test -n "$current_libdirs"; then - # Maybe just do a dry run. - test -n "$run" && current_libdirs=" -n$current_libdirs" - exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' - else - exit $EXIT_SUCCESS - fi - ;; - - # libtool finish mode - finish) - modename="$modename: finish" - libdirs="$nonopt" - admincmds= - - if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then - for dir - do - libdirs="$libdirs $dir" - done - - for libdir in $libdirs; do - if test -n "$finish_cmds"; then - # Do each command in the finish commands. - cmds=$finish_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" || admincmds="$admincmds - $cmd" - done - IFS="$save_ifs" - fi - if test -n "$finish_eval"; then - # Do the single finish_eval. - eval cmds=\"$finish_eval\" - $run eval "$cmds" || admincmds="$admincmds - $cmds" - fi - done - fi - - # Exit here if they wanted silent mode. - test "$show" = : && exit $EXIT_SUCCESS - - $echo "X----------------------------------------------------------------------" | $Xsed - $echo "Libraries have been installed in:" - for libdir in $libdirs; do - $echo " $libdir" - done - $echo - $echo "If you ever happen to want to link against installed libraries" - $echo "in a given directory, LIBDIR, you must either use libtool, and" - $echo "specify the full pathname of the library, or use the \`-LLIBDIR'" - $echo "flag during linking and do at least one of the following:" - if test -n "$shlibpath_var"; then - $echo " - add LIBDIR to the \`$shlibpath_var' environment variable" - $echo " during execution" - fi - if test -n "$runpath_var"; then - $echo " - add LIBDIR to the \`$runpath_var' environment variable" - $echo " during linking" - fi - if test -n "$hardcode_libdir_flag_spec"; then - libdir=LIBDIR - eval flag=\"$hardcode_libdir_flag_spec\" - - $echo " - use the \`$flag' linker flag" - fi - if test -n "$admincmds"; then - $echo " - have your system administrator run these commands:$admincmds" - fi - if test -f /etc/ld.so.conf; then - $echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" - fi - $echo - $echo "See any operating system documentation about shared libraries for" - $echo "more information, such as the ld(1) and ld.so(8) manual pages." - $echo "X----------------------------------------------------------------------" | $Xsed - exit $EXIT_SUCCESS - ;; - - # libtool execute mode - execute) - modename="$modename: execute" - - # The first argument is the command name. - cmd="$nonopt" - if test -z "$cmd"; then - $echo "$modename: you must specify a COMMAND" 1>&2 - $echo "$help" - exit $EXIT_FAILURE - fi - - # Handle -dlopen flags immediately. - for file in $execute_dlfiles; do - if test ! -f "$file"; then - $echo "$modename: \`$file' is not a file" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - dir= - case $file in - *.la) - # Check to see that this really is a libtool archive. - if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : - else - $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Read the libtool library. - dlname= - library_names= - - # If there is no directory component, then add one. - case $file in - */* | *\\*) . $file ;; - *) . ./$file ;; - esac - - # Skip this library if it cannot be dlopened. - if test -z "$dlname"; then - # Warn if it was a shared library. - test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'" - continue - fi - - dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` - test "X$dir" = "X$file" && dir=. - - if test -f "$dir/$objdir/$dlname"; then - dir="$dir/$objdir" - else - $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2 - exit $EXIT_FAILURE - fi - ;; - - *.lo) - # Just add the directory containing the .lo file. - dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` - test "X$dir" = "X$file" && dir=. - ;; - - *) - $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2 - continue - ;; - esac - - # Get the absolute pathname. - absdir=`cd "$dir" && pwd` - test -n "$absdir" && dir="$absdir" - - # Now add the directory to shlibpath_var. - if eval "test -z \"\$$shlibpath_var\""; then - eval "$shlibpath_var=\"\$dir\"" - else - eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" - fi - done - - # This variable tells wrapper scripts just to set shlibpath_var - # rather than running their programs. - libtool_execute_magic="$magic" - - # Check if any of the arguments is a wrapper script. - args= - for file - do - case $file in - -*) ;; - *) - # Do a test to see if this is really a libtool program. - if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - # If there is no directory component, then add one. - case $file in - */* | *\\*) . $file ;; - *) . ./$file ;; - esac - - # Transform arg to wrapped name. - file="$progdir/$program" - fi - ;; - esac - # Quote arguments (to preserve shell metacharacters). - file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"` - args="$args \"$file\"" - done - - if test -z "$run"; then - if test -n "$shlibpath_var"; then - # Export the shlibpath_var. - eval "export $shlibpath_var" - fi - - # Restore saved environment variables - if test "${save_LC_ALL+set}" = set; then - LC_ALL="$save_LC_ALL"; export LC_ALL - fi - if test "${save_LANG+set}" = set; then - LANG="$save_LANG"; export LANG - fi - - # Now prepare to actually exec the command. - exec_cmd="\$cmd$args" - else - # Display what would be done. - if test -n "$shlibpath_var"; then - eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\"" - $echo "export $shlibpath_var" - fi - $echo "$cmd$args" - exit $EXIT_SUCCESS - fi - ;; - - # libtool clean and uninstall mode - clean | uninstall) - modename="$modename: $mode" - rm="$nonopt" - files= - rmforce= - exit_status=0 - - # This variable tells wrapper scripts just to set variables rather - # than running their programs. - libtool_install_magic="$magic" - - for arg - do - case $arg in - -f) rm="$rm $arg"; rmforce=yes ;; - -*) rm="$rm $arg" ;; - *) files="$files $arg" ;; - esac - done - - if test -z "$rm"; then - $echo "$modename: you must specify an RM program" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - fi - - rmdirs= - - origobjdir="$objdir" - for file in $files; do - dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` - if test "X$dir" = "X$file"; then - dir=. - objdir="$origobjdir" - else - objdir="$dir/$origobjdir" - fi - name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` - test "$mode" = uninstall && objdir="$dir" - - # Remember objdir for removal later, being careful to avoid duplicates - if test "$mode" = clean; then - case " $rmdirs " in - *" $objdir "*) ;; - *) rmdirs="$rmdirs $objdir" ;; - esac - fi - - # Don't error if the file doesn't exist and rm -f was used. - if (test -L "$file") >/dev/null 2>&1 \ - || (test -h "$file") >/dev/null 2>&1 \ - || test -f "$file"; then - : - elif test -d "$file"; then - exit_status=1 - continue - elif test "$rmforce" = yes; then - continue - fi - - rmfiles="$file" - - case $name in - *.la) - # Possibly a libtool archive, so verify it. - if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - . $dir/$name - - # Delete the libtool libraries and symlinks. - for n in $library_names; do - rmfiles="$rmfiles $objdir/$n" - done - test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" - - case "$mode" in - clean) - case " $library_names " in - # " " in the beginning catches empty $dlname - *" $dlname "*) ;; - *) rmfiles="$rmfiles $objdir/$dlname" ;; - esac - test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" - ;; - uninstall) - if test -n "$library_names"; then - # Do each command in the postuninstall commands. - cmds=$postuninstall_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" - if test "$?" -ne 0 && test "$rmforce" != yes; then - exit_status=1 - fi - done - IFS="$save_ifs" - fi - - if test -n "$old_library"; then - # Do each command in the old_postuninstall commands. - cmds=$old_postuninstall_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $show "$cmd" - $run eval "$cmd" - if test "$?" -ne 0 && test "$rmforce" != yes; then - exit_status=1 - fi - done - IFS="$save_ifs" - fi - # FIXME: should reinstall the best remaining shared library. - ;; - esac - fi - ;; - - *.lo) - # Possibly a libtool object, so verify it. - if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - - # Read the .lo file - . $dir/$name - - # Add PIC object to the list of files to remove. - if test -n "$pic_object" \ - && test "$pic_object" != none; then - rmfiles="$rmfiles $dir/$pic_object" - fi - - # Add non-PIC object to the list of files to remove. - if test -n "$non_pic_object" \ - && test "$non_pic_object" != none; then - rmfiles="$rmfiles $dir/$non_pic_object" - fi - fi - ;; - - *) - if test "$mode" = clean ; then - noexename=$name - case $file in - *.exe) - file=`$echo $file|${SED} 's,.exe$,,'` - noexename=`$echo $name|${SED} 's,.exe$,,'` - # $file with .exe has already been added to rmfiles, - # add $file without .exe - rmfiles="$rmfiles $file" - ;; - esac - # Do a test to see if this is a libtool program. - if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then - relink_command= - . $dir/$noexename - - # note $name still contains .exe if it was in $file originally - # as does the version of $file that was added into $rmfiles - rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" - if test "$fast_install" = yes && test -n "$relink_command"; then - rmfiles="$rmfiles $objdir/lt-$name" - fi - if test "X$noexename" != "X$name" ; then - rmfiles="$rmfiles $objdir/lt-${noexename}.c" - fi - fi - fi - ;; - esac - $show "$rm $rmfiles" - $run $rm $rmfiles || exit_status=1 - done - objdir="$origobjdir" - - # Try to remove the ${objdir}s in the directories where we deleted files - for dir in $rmdirs; do - if test -d "$dir"; then - $show "rmdir $dir" - $run rmdir $dir >/dev/null 2>&1 - fi - done - - exit $exit_status - ;; - - "") - $echo "$modename: you must specify a MODE" 1>&2 - $echo "$generic_help" 1>&2 - exit $EXIT_FAILURE - ;; - esac - - if test -z "$exec_cmd"; then - $echo "$modename: invalid operation mode \`$mode'" 1>&2 - $echo "$generic_help" 1>&2 - exit $EXIT_FAILURE - fi -fi # test -z "$show_help" - -if test -n "$exec_cmd"; then - eval exec $exec_cmd - exit $EXIT_FAILURE -fi - -# We need to display help for each of the modes. -case $mode in -"") $echo \ -"Usage: $modename [OPTION]... [MODE-ARG]... - -Provide generalized library-building support services. - - --config show all configuration variables - --debug enable verbose shell tracing --n, --dry-run display commands without modifying any files - --features display basic configuration information and exit - --finish same as \`--mode=finish' - --help display this help message and exit - --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS] - --quiet same as \`--silent' - --silent don't print informational messages - --tag=TAG use configuration variables from tag TAG - --version print version information - -MODE must be one of the following: - - clean remove files from the build directory - compile compile a source file into a libtool object - execute automatically set library path, then run a program - finish complete the installation of libtool libraries - install install libraries or executables - link create a library or an executable - uninstall remove libraries from an installed directory - -MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for -a more detailed description of MODE. - -Report bugs to ." - exit $EXIT_SUCCESS - ;; - -clean) - $echo \ -"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE... - -Remove files from the build directory. - -RM is the name of the program to use to delete files associated with each FILE -(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed -to RM. - -If FILE is a libtool library, object or program, all the files associated -with it are deleted. Otherwise, only FILE itself is deleted using RM." - ;; - -compile) - $echo \ -"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE - -Compile a source file into a libtool library object. - -This mode accepts the following additional options: - - -o OUTPUT-FILE set the output file name to OUTPUT-FILE - -prefer-pic try to building PIC objects only - -prefer-non-pic try to building non-PIC objects only - -static always build a \`.o' file suitable for static linking - -COMPILE-COMMAND is a command to be used in creating a \`standard' object file -from the given SOURCEFILE. - -The output file name is determined by removing the directory component from -SOURCEFILE, then substituting the C source code suffix \`.c' with the -library object suffix, \`.lo'." - ;; - -execute) - $echo \ -"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]... - -Automatically set library path, then run a program. - -This mode accepts the following additional options: - - -dlopen FILE add the directory containing FILE to the library path - -This mode sets the library path environment variable according to \`-dlopen' -flags. - -If any of the ARGS are libtool executable wrappers, then they are translated -into their corresponding uninstalled binary, and any of their required library -directories are added to the library path. - -Then, COMMAND is executed, with ARGS as arguments." - ;; - -finish) - $echo \ -"Usage: $modename [OPTION]... --mode=finish [LIBDIR]... - -Complete the installation of libtool libraries. - -Each LIBDIR is a directory that contains libtool libraries. - -The commands that this mode executes may require superuser privileges. Use -the \`--dry-run' option if you just want to see what would be executed." - ;; - -install) - $echo \ -"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND... - -Install executables or libraries. - -INSTALL-COMMAND is the installation command. The first component should be -either the \`install' or \`cp' program. - -The rest of the components are interpreted as arguments to that command (only -BSD-compatible install options are recognized)." - ;; - -link) - $echo \ -"Usage: $modename [OPTION]... --mode=link LINK-COMMAND... - -Link object files or libraries together to form another library, or to -create an executable program. - -LINK-COMMAND is a command using the C compiler that you would use to create -a program from several object files. - -The following components of LINK-COMMAND are treated specially: - - -all-static do not do any dynamic linking at all - -avoid-version do not add a version suffix if possible - -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime - -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols - -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) - -export-symbols SYMFILE - try to export only the symbols listed in SYMFILE - -export-symbols-regex REGEX - try to export only the symbols matching REGEX - -LLIBDIR search LIBDIR for required installed libraries - -lNAME OUTPUT-FILE requires the installed library libNAME - -module build a library that can dlopened - -no-fast-install disable the fast-install mode - -no-install link a not-installable executable - -no-undefined declare that a library does not refer to external symbols - -o OUTPUT-FILE create OUTPUT-FILE from the specified objects - -objectlist FILE Use a list of object files found in FILE to specify objects - -precious-files-regex REGEX - don't remove output files matching REGEX - -release RELEASE specify package release information - -rpath LIBDIR the created library will eventually be installed in LIBDIR - -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries - -static do not do any dynamic linking of libtool libraries - -version-info CURRENT[:REVISION[:AGE]] - specify library version info [each variable defaults to 0] - -All other options (arguments beginning with \`-') are ignored. - -Every other argument is treated as a filename. Files ending in \`.la' are -treated as uninstalled libtool libraries, other files are standard or library -object files. - -If the OUTPUT-FILE ends in \`.la', then a libtool library is created, -only library objects (\`.lo' files) may be specified, and \`-rpath' is -required, except when creating a convenience library. - -If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created -using \`ar' and \`ranlib', or on Windows using \`lib'. - -If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file -is created, otherwise an executable program is created." - ;; - -uninstall) - $echo \ -"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... - -Remove libraries from an installation directory. - -RM is the name of the program to use to delete files associated with each FILE -(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed -to RM. - -If FILE is a libtool library, all the files associated with it are deleted. -Otherwise, only FILE itself is deleted using RM." - ;; - -*) - $echo "$modename: invalid operation mode \`$mode'" 1>&2 - $echo "$help" 1>&2 - exit $EXIT_FAILURE - ;; -esac - -$echo -$echo "Try \`$modename --help' for more information about other modes." - -exit $? - -# The TAGs below are defined such that we never get into a situation -# in which we disable both kinds of libraries. Given conflicting -# choices, we go for a static library, that is the most portable, -# since we can't tell whether shared libraries were disabled because -# the user asked for that or because the platform doesn't support -# them. This is particularly important on AIX, because we don't -# support having both static and shared libraries enabled at the same -# time on that platform, so we default to a shared-only configuration. -# If a disable-shared tag is given, we'll fallback to a static-only -# configuration. But we'll never go from static-only to shared-only. - -# ### BEGIN LIBTOOL TAG CONFIG: disable-shared -disable_libs=shared -# ### END LIBTOOL TAG CONFIG: disable-shared - -# ### BEGIN LIBTOOL TAG CONFIG: disable-static -disable_libs=static -# ### END LIBTOOL TAG CONFIG: disable-static - -# Local Variables: -# mode:shell-script -# sh-indentation:2 -# End: -# ### BEGIN LIBTOOL TAG CONFIG: CXX - -# Libtool was configured on host pes.vlakno.cz: - -# Shell to use when invoking shell scripts. -SHELL="/bin/sh" - -# Whether or not to build shared libraries. -build_libtool_libs=yes - -# Whether or not to build static libraries. -build_old_libs=yes - -# Whether or not to add -lc for building shared libraries. -build_libtool_need_lc=no - -# Whether or not to disallow shared libs when runtime libs are static -allow_libtool_libs_with_static_runtimes=no - -# Whether or not to optimize for fast installation. -fast_install=needless - -# The host system. -host_alias= -host=x86_64-unknown-freebsd7.2 -host_os=freebsd7.2 - -# The build system. -build_alias= -build=x86_64-unknown-freebsd7.2 -build_os=freebsd7.2 - -# An echo program that does not interpret backslashes. -echo="echo" - -# The archiver. -AR="ar" -AR_FLAGS="cru" - -# A C compiler. -LTCC="gcc" - -# LTCC compiler flags. -LTCFLAGS="-g -O2" - -# A language-specific compiler. -CC="g++" - -# Is the compiler the GNU C compiler? -with_gcc=yes - -# An ERE matcher. -EGREP="/usr/bin/grep -E" - -# The linker used to build libraries. -LD="/usr/bin/ld" - -# Whether we need hard or soft links. -LN_S="ln -s" - -# A BSD-compatible nm program. -NM="/usr/bin/nm -B" - -# A symbol stripping program -STRIP="strip" - -# Used to examine libraries when file_magic_cmd begins "file" -MAGIC_CMD=file - -# Used on cygwin: DLL creation program. -DLLTOOL="dlltool" - -# Used on cygwin: object dumper. -OBJDUMP="objdump" - -# Used on cygwin: assembler. -AS="as" - -# The name of the directory that contains temporary libtool files. -objdir=.libs - -# How to create reloadable object files. -reload_flag=" -r" -reload_cmds="\$LD\$reload_flag -o \$output\$reload_objs" - -# How to pass a linker flag through the compiler. -wl="-Wl," - -# Object file suffix (normally "o"). -objext="o" - -# Old archive suffix (normally "a"). -libext="a" - -# Shared library suffix (normally ".so"). -shrext_cmds='.so' - -# Executable file suffix (normally ""). -exeext="" - -# Additional compiler flags for building library objects. -pic_flag=" -fPIC -DPIC" -pic_mode=default - -# What is the maximum length of a command? -max_cmd_len=196608 - -# Does compiler simultaneously support -c and -o options? -compiler_c_o="yes" - -# Must we lock files when doing compilation? -need_locks="no" - -# Do we need the lib prefix for modules? -need_lib_prefix=no - -# Do we need a version for libraries? -need_version=no - -# Whether dlopen is supported. -dlopen_support=yes - -# Whether dlopen of programs is supported. -dlopen_self=yes - -# Whether dlopen of statically linked programs is supported. -dlopen_self_static=no - -# Compiler flag to prevent dynamic linking. -link_static_flag="-static" - -# Compiler flag to turn off builtin functions. -no_builtin_flag=" -fno-builtin" - -# Compiler flag to allow reflexive dlopens. -export_dynamic_flag_spec="\${wl}--export-dynamic" - -# Compiler flag to generate shared objects directly from archives. -whole_archive_flag_spec="\${wl}--whole-archive\$convenience \${wl}--no-whole-archive" - -# Compiler flag to generate thread-safe objects. -thread_safe_flag_spec="" - -# Library versioning type. -version_type=freebsd-elf - -# Format of library name prefix. -libname_spec="lib\$name" - -# List of archive names. First name is the real one, the rest are links. -# The last name is the one that the linker finds with -lNAME. -library_names_spec="\${libname}\${release}\${shared_ext}\$versuffix \${libname}\${release}\${shared_ext} \$libname\${shared_ext}" - -# The coded name of the library, if different from the real name. -soname_spec="" - -# Commands used to build and install an old-style archive. -RANLIB="ranlib" -old_archive_cmds="\$AR \$AR_FLAGS \$oldlib\$oldobjs\$old_deplibs~\$RANLIB \$oldlib" -old_postinstall_cmds="chmod 644 \$oldlib~\$RANLIB \$oldlib" -old_postuninstall_cmds="" - -# Create an old-style archive from a shared archive. -old_archive_from_new_cmds="" - -# Create a temporary old-style archive to link instead of a shared archive. -old_archive_from_expsyms_cmds="" - -# Commands used to build and install a shared archive. -archive_cmds="\$CC -shared -nostdlib \$predep_objects \$libobjs \$deplibs \$postdep_objects \$compiler_flags \${wl}-soname \$wl\$soname -o \$lib" -archive_expsym_cmds="\$CC -shared -nostdlib \$predep_objects \$libobjs \$deplibs \$postdep_objects \$compiler_flags \${wl}-soname \$wl\$soname \${wl}-retain-symbols-file \$wl\$export_symbols -o \$lib" -postinstall_cmds="" -postuninstall_cmds="" - -# Commands used to build a loadable module (assumed same as above if empty) -module_cmds="" -module_expsym_cmds="" - -# Commands to strip libraries. -old_striplib="strip --strip-debug" -striplib="strip --strip-unneeded" - -# Dependencies to place before the objects being linked to create a -# shared library. -predep_objects="/usr/lib/crti.o /usr/lib/crtbeginS.o" - -# Dependencies to place after the objects being linked to create a -# shared library. -postdep_objects="/usr/lib/crtendS.o /usr/lib/crtn.o" - -# Dependencies to place before the objects being linked to create a -# shared library. -predeps="" - -# Dependencies to place after the objects being linked to create a -# shared library. -postdeps="-lstdc++ -lm -lgcc_s -lc -lgcc_s" - -# The library search path used internally by the compiler when linking -# a shared library. -compiler_lib_search_path="-L/usr/lib -L/usr/lib" - -# Method to check whether dependent libraries are shared objects. -deplibs_check_method="pass_all" - -# Command to use when deplibs_check_method == file_magic. -file_magic_cmd="\$MAGIC_CMD" - -# Flag that allows shared libraries with undefined symbols to be built. -allow_undefined_flag="" - -# Flag that forces no undefined symbols. -no_undefined_flag="" - -# Commands used to finish a libtool library installation in a directory. -finish_cmds="" - -# Same as above, but a single script fragment to be evaled but not shown. -finish_eval="" - -# Take the output of nm and produce a listing of raw symbols and C names. -global_symbol_pipe="sed -n -e 's/^.*[ ]\\([ABCDGIRSTW][ABCDGIRSTW]*\\)[ ][ ]*\\([_A-Za-z][_A-Za-z0-9]*\\)\$/\\1 \\2 \\2/p'" - -# Transform the output of nm in a proper C declaration -global_symbol_to_cdecl="sed -n -e 's/^. .* \\(.*\\)\$/extern int \\1;/p'" - -# Transform the output of nm in a C name address pair -global_symbol_to_c_name_address="sed -n -e 's/^: \\([^ ]*\\) \$/ {\\\"\\1\\\", (lt_ptr) 0},/p' -e 's/^[BCDEGRST] \\([^ ]*\\) \\([^ ]*\\)\$/ {\"\\2\", (lt_ptr) \\&\\2},/p'" - -# This is the shared library runtime path variable. -runpath_var=LD_RUN_PATH - -# This is the shared library path variable. -shlibpath_var=LD_LIBRARY_PATH - -# Is shlibpath searched before the hard-coded library search path? -shlibpath_overrides_runpath=yes - -# How to hardcode a shared library path into an executable. -hardcode_action=immediate - -# Whether we should hardcode library paths into libraries. -hardcode_into_libs=yes - -# Flag to hardcode $libdir into a binary during linking. -# This must work even if $libdir does not exist. -hardcode_libdir_flag_spec="\${wl}--rpath \${wl}\$libdir" - -# If ld is used when linking, flag to hardcode $libdir into -# a binary during linking. This must work even if $libdir does -# not exist. -hardcode_libdir_flag_spec_ld="" - -# Whether we need a single -rpath flag with a separated argument. -hardcode_libdir_separator="" - -# Set to yes if using DIR/libNAME during linking hardcodes DIR into the -# resulting binary. -hardcode_direct=no - -# Set to yes if using the -LDIR flag during linking hardcodes DIR into the -# resulting binary. -hardcode_minus_L=no - -# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into -# the resulting binary. -hardcode_shlibpath_var=unsupported - -# Set to yes if building a shared library automatically hardcodes DIR into the library -# and all subsequent libraries and executables linked against it. -hardcode_automatic=no - -# Variables whose values should be saved in libtool wrapper scripts and -# restored at relink time. -variables_saved_for_relink="PATH LD_LIBRARY_PATH LD_RUN_PATH GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" - -# Whether libtool must link a program against all its dependency libraries. -link_all_deplibs=unknown - -# Compile-time system search path for libraries -sys_lib_search_path_spec=" /usr/lib/ /usr/lib/" - -# Run-time system search path for libraries -sys_lib_dlsearch_path_spec="/lib /usr/lib" - -# Fix the shell variable $srcfile for the compiler. -fix_srcfile_path="" - -# Set to yes if exported symbols are required. -always_export_symbols=no - -# The commands to list exported symbols. -export_symbols_cmds="\$NM \$libobjs \$convenience | \$global_symbol_pipe | \$SED 's/.* //' | sort | uniq > \$export_symbols" - -# The commands to extract the exported symbol list from a shared archive. -extract_expsyms_cmds="" - -# Symbols that should not be listed in the preloaded symbols. -exclude_expsyms="" - -# Symbols that must always be exported. -include_expsyms="" - -# ### END LIBTOOL TAG CONFIG: CXX - diff --git a/runtime/libprofile/BlockProfiling.c b/runtime/libprofile/BlockProfiling.c deleted file mode 100644 index db80bffe56d..00000000000 --- a/runtime/libprofile/BlockProfiling.c +++ /dev/null @@ -1,45 +0,0 @@ -/*===-- BlockProfiling.c - Support library for block profiling ------------===*\ -|* -|* The LLVM Compiler Infrastructure -|* -|* This file is distributed under the University of Illinois Open Source -|* License. See LICENSE.TXT for details. -|* -|*===----------------------------------------------------------------------===*| -|* -|* This file implements the call back routines for the block profiling -|* instrumentation pass. This should be used with the -insert-block-profiling -|* LLVM pass. -|* -\*===----------------------------------------------------------------------===*/ - -#include "Profiling.h" -#include - -static unsigned *ArrayStart; -static unsigned NumElements; - -/* BlockProfAtExitHandler - When the program exits, just write out the profiling - * data. - */ -static void BlockProfAtExitHandler() { - /* Note that if this were doing something more intelligent with the - * instrumentation, we could do some computation here to expand what we - * collected into simple block profiles. (Or we could do it in llvm-prof.) - * Regardless, we directly count each block, so no expansion is necessary. - */ - write_profiling_data(BlockInfo, ArrayStart, NumElements); -} - - -/* llvm_start_block_profiling - This is the main entry point of the block - * profiling library. It is responsible for setting up the atexit handler. - */ -int llvm_start_block_profiling(int argc, const char **argv, - unsigned *arrayStart, unsigned numElements) { - int Ret = save_arguments(argc, argv); - ArrayStart = arrayStart; - NumElements = numElements; - atexit(BlockProfAtExitHandler); - return Ret; -} diff --git a/runtime/libprofile/FunctionProfiling.c b/runtime/libprofile/FunctionProfiling.c deleted file mode 100644 index 24aa2061307..00000000000 --- a/runtime/libprofile/FunctionProfiling.c +++ /dev/null @@ -1,42 +0,0 @@ -/*===-- FunctionProfiling.c - Support library for function profiling ------===*\ -|* -|* The LLVM Compiler Infrastructure -|* -|* This file is distributed under the University of Illinois Open Source -|* License. See LICENSE.TXT for details. -|* -|*===----------------------------------------------------------------------===*| -|* -|* This file implements the call back routines for the function profiling -|* instrumentation pass. This should be used with the -|* -insert-function-profiling LLVM pass. -|* -\*===----------------------------------------------------------------------===*/ - -#include "Profiling.h" -#include - -static unsigned *ArrayStart; -static unsigned NumElements; - -/* FuncProfAtExitHandler - When the program exits, just write out the profiling - * data. - */ -static void FuncProfAtExitHandler() { - /* Just write out the data we collected. - */ - write_profiling_data(FunctionInfo, ArrayStart, NumElements); -} - - -/* llvm_start_func_profiling - This is the main entry point of the function - * profiling library. It is responsible for setting up the atexit handler. - */ -int llvm_start_func_profiling(int argc, const char **argv, - unsigned *arrayStart, unsigned numElements) { - int Ret = save_arguments(argc, argv); - ArrayStart = arrayStart; - NumElements = numElements; - atexit(FuncProfAtExitHandler); - return Ret; -} diff --git a/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp b/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp deleted file mode 100644 index a86be6cb5dd..00000000000 --- a/utils/valgrind/x86_64-pc-linux-gnu_gcc-4.3.3.supp +++ /dev/null @@ -1,23 +0,0 @@ -{ - libstdcxx_overlapped_memcpy_in_stable_sort_1 - Memcheck:Overlap - fun:memcpy - ... - fun:_ZSt11stable_sortIN9__gnu_cxx17__normal_iteratorIPSt4pairIPKN4llvm5ValueEjESt6vectorIS7_SaIS7_EEEEN12_GLOBAL__N_116CstSortPredicateEEvT_SF_T0_ -} - -{ - libstdcxx_overlapped_memcpy_in_stable_sort_2 - Memcheck:Overlap - fun:memcpy - ... - fun:_ZSt11stable_sortIN9__gnu_cxx17__normal_iteratorIPSt4pairIPKN4llvm5ValueEjESt6vectorIS7_SaIS7_EEEEN12_GLOBAL__N_116CstSortPredicateEEvT_SF_T0_ -} - -{ - libstdcxx_overlapped_memcpy_in_stable_sort_3 - Memcheck:Overlap - fun:memcpy - ... - fun:_ZSt11stable_sortIN9__gnu_cxx17__normal_iteratorIPSt4pairIPKN4llvm4TypeEjESt6vectorIS7_SaIS7_EEEEPFbRKS7_SE_EEvT_SH_T0_ -} diff --git a/win32/Analysis/Analysis.vcproj b/win32/Analysis/Analysis.vcproj deleted file mode 100644 index e116aa384d9..00000000000 --- a/win32/Analysis/Analysis.vcproj +++ /dev/null @@ -1,573 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Archive/Archive.vcproj b/win32/Archive/Archive.vcproj deleted file mode 100644 index efd2f378769..00000000000 --- a/win32/Archive/Archive.vcproj +++ /dev/null @@ -1,337 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/AsmParser/AsmParser.vcproj b/win32/AsmParser/AsmParser.vcproj deleted file mode 100644 index 96ca6d172b6..00000000000 --- a/win32/AsmParser/AsmParser.vcproj +++ /dev/null @@ -1,346 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Bitcode/Bitcode.vcproj b/win32/Bitcode/Bitcode.vcproj deleted file mode 100644 index 06bc4f0149c..00000000000 --- a/win32/Bitcode/Bitcode.vcproj +++ /dev/null @@ -1,422 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/CBackend/CBackend.vcproj b/win32/CBackend/CBackend.vcproj deleted file mode 100644 index 14047590edf..00000000000 --- a/win32/CBackend/CBackend.vcproj +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/CodeGen/CodeGen.vcproj b/win32/CodeGen/CodeGen.vcproj deleted file mode 100644 index d7c913857da..00000000000 --- a/win32/CodeGen/CodeGen.vcproj +++ /dev/null @@ -1,849 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Configure/Configure.vcproj b/win32/Configure/Configure.vcproj deleted file mode 100644 index 6e504b03b04..00000000000 --- a/win32/Configure/Configure.vcproj +++ /dev/null @@ -1,319 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/ExecutionEngine/ExecutionEngine.vcproj b/win32/ExecutionEngine/ExecutionEngine.vcproj deleted file mode 100644 index b86db6f994b..00000000000 --- a/win32/ExecutionEngine/ExecutionEngine.vcproj +++ /dev/null @@ -1,429 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Fibonacci/Fibonacci.vcproj b/win32/Fibonacci/Fibonacci.vcproj deleted file mode 100644 index a2575639873..00000000000 --- a/win32/Fibonacci/Fibonacci.vcproj +++ /dev/null @@ -1,386 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Linker/Linker.vcproj b/win32/Linker/Linker.vcproj deleted file mode 100644 index e88566ae671..00000000000 --- a/win32/Linker/Linker.vcproj +++ /dev/null @@ -1,337 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Support/Support.vcproj b/win32/Support/Support.vcproj deleted file mode 100644 index 027668d686c..00000000000 --- a/win32/Support/Support.vcproj +++ /dev/null @@ -1,743 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/System/System.vcproj b/win32/System/System.vcproj deleted file mode 100644 index f72a754a3cd..00000000000 --- a/win32/System/System.vcproj +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/TableGen/TableGen.vcproj b/win32/TableGen/TableGen.vcproj deleted file mode 100644 index 4dd189910f4..00000000000 --- a/win32/TableGen/TableGen.vcproj +++ /dev/null @@ -1,538 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Target/Target.vcproj b/win32/Target/Target.vcproj deleted file mode 100644 index 05eea5b2f9b..00000000000 --- a/win32/Target/Target.vcproj +++ /dev/null @@ -1,433 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/Transforms/Transforms.vcproj b/win32/Transforms/Transforms.vcproj deleted file mode 100644 index 2554a4ea3b6..00000000000 --- a/win32/Transforms/Transforms.vcproj +++ /dev/null @@ -1,759 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/VMCore/VMCore.vcproj b/win32/VMCore/VMCore.vcproj deleted file mode 100644 index 4accd55b02e..00000000000 --- a/win32/VMCore/VMCore.vcproj +++ /dev/null @@ -1,650 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/bugpoint/bugpoint.vcproj b/win32/bugpoint/bugpoint.vcproj deleted file mode 100644 index 1c8a7d7e17b..00000000000 --- a/win32/bugpoint/bugpoint.vcproj +++ /dev/null @@ -1,429 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clang.sln b/win32/clang.sln deleted file mode 100644 index 1c6967f36c4..00000000000 --- a/win32/clang.sln +++ /dev/null @@ -1,591 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "support", "Support\Support.vcproj", "{28AA9146-3482-4F41-9CC6-407B1D258508}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TableGen", "TableGen\TableGen.vcproj", "{339C2249-26B6-4172-B484-85653029AF57}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Fibonacci", "Fibonacci\Fibonacci.vcproj", "{48FB551D-E37E-42EC-BC97-FF7219774867}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {76295AE8-A083-460E-9F80-6F2B8923264A} = {76295AE8-A083-460E-9F80-6F2B8923264A} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {144EEBF6-8C9B-4473-B715-2C821666AF6C} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExecutionEngine", "ExecutionEngine\ExecutionEngine.vcproj", "{76295AE8-A083-460E-9F80-6F2B8923264A}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VMCore", "VMCore\VMCore.vcproj", "{45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Target", "Target\Target.vcproj", "{059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CodeGen", "CodeGen\CodeGen.vcproj", "{08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "System", "System\System.vcproj", "{0F8407F3-FA23-4CF1-83A9-DCBE0B361489}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Analysis", "Analysis\Analysis.vcproj", "{0622E827-8464-489D-8B1C-B0B496F35C08}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "x86", "x86\x86.vcproj", "{144EEBF6-8C9B-4473-B715-2C821666AF6C}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Transforms", "Transforms\Transforms.vcproj", "{C59374C1-9FC0-4147-B836-327DFDC52D99}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Configure", "Configure\Configure.vcproj", "{19514E48-456C-4B9D-8637-F2285476461E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lli", "lli\lli.vcproj", "{FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {76295AE8-A083-460E-9F80-6F2B8923264A} = {76295AE8-A083-460E-9F80-6F2B8923264A} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {144EEBF6-8C9B-4473-B715-2C821666AF6C} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llc", "llc\llc.vcproj", "{ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {057777CD-DED5-46DF-BF9A-6B76DE212549} = {057777CD-DED5-46DF-BF9A-6B76DE212549} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {144EEBF6-8C9B-4473-B715-2C821666AF6C} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-dis", "llvm-dis\llvm-dis.vcproj", "{B13476BC-30AB-4EA0-BC1E-212C0A459405}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-as", "llvm-as\llvm-as.vcproj", "{4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {3DC216F5-1DDD-478A-84F8-C124E5C31982} = {3DC216F5-1DDD-478A-84F8-C124E5C31982} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AsmParser", "AsmParser\AsmParser.vcproj", "{3DC216F5-1DDD-478A-84F8-C124E5C31982}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-ar", "llvm-ar\llvm-ar.vcproj", "{0FF2B75C-49C1-4B49-A44A-531C93000296}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-ranlib", "llvm-ranlib\llvm-ranlib.vcproj", "{BB16C7EE-B4ED-4714-B5ED-B775C62A6612}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-link", "llvm-link\llvm-link.vcproj", "{5E249789-49E1-4600-B12B-8AD2BB6439B2}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {342CF48F-760A-4040-A9A1-7D75AA2471CE} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Linker", "Linker\Linker.vcproj", "{342CF48F-760A-4040-A9A1-7D75AA2471CE}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CBackend", "CBackend\CBackend.vcproj", "{057777CD-DED5-46DF-BF9A-6B76DE212549}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opt", "opt\opt.vcproj", "{006D8B41-C3C7-4448-85E1-AF8907E591E5}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-bcanalyzer", "llvm-bcanalyzer\llvm-bcanalyzer.vcproj", "{E0B1E329-BE3E-456D-B372-5F397BE42C84}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-ld", "llvm-ld\llvm-ld.vcproj", "{64D8AA46-88DB-41F4-B837-053AE02406B8}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {342CF48F-760A-4040-A9A1-7D75AA2471CE} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-nm", "llvm-nm\llvm-nm.vcproj", "{5FF862CE-80A0-4B48-A80B-68AE325A0432}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-prof", "llvm-prof\llvm-prof.vcproj", "{ACBE81D9-64B1-4133-823A-807A4E60B454}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bugpoint", "bugpoint\bugpoint.vcproj", "{57249192-8E29-4D85-8B7A-FEFF1760B1DA}" - ProjectSection(ProjectDependencies) = postProject - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {342CF48F-760A-4040-A9A1-7D75AA2471CE} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {3DC216F5-1DDD-478A-84F8-C124E5C31982} = {3DC216F5-1DDD-478A-84F8-C124E5C31982} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Bitcode", "Bitcode\Bitcode.vcproj", "{F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}" - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Archive", "Archive\Archive.vcproj", "{F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}" - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "LLVM", "LLVM", "{455BCF47-13B6-451E-8321-8ED9C4866BAA}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Clang", "Clang", "{DAC2AB11-F09C-454B-86FD-9BDBBA25827F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangLex", "..\tools\clang\win32\clangLex\clangLex.vcproj", "{030F6909-B2FA-4E53-BEA7-9A559CFC2F73}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangParse", "..\tools\clang\win32\clangParse\clangParse.vcproj", "{05DF3074-11AF-491A-B078-83BD2EDC31F6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangAST", "..\tools\clang\win32\clangAST\clangAST.vcproj", "{5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangSema", "..\tools\clang\win32\clangSema\clangSema.vcproj", "{4727E8B7-AA99-41C9-AB09-A8A862595DB7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangCodeGen", "..\tools\clang\win32\clangCodeGen\clangCodeGen.vcproj", "{4CEC5897-D957-47E7-A6AE-2021D4F44A8F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangDriver", "..\tools\clang\win32\clangDriver\clangDriver.vcproj", "{7E7DA455-C276-4B93-8D02-8F7E2F629BAF}" - ProjectSection(ProjectDependencies) = postProject - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73} = {030F6909-B2FA-4E53-BEA7-9A559CFC2F73} - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0} = {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {05DF3074-11AF-491A-B078-83BD2EDC31F6} = {05DF3074-11AF-491A-B078-83BD2EDC31F6} - {298B4876-6EF1-4E80-85D7-72F80693BBEB} = {298B4876-6EF1-4E80-85D7-72F80693BBEB} - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F} = {4CEC5897-D957-47E7-A6AE-2021D4F44A8F} - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D} = {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D} - {4727E8B7-AA99-41C9-AB09-A8A862595DB7} = {4727E8B7-AA99-41C9-AB09-A8A862595DB7} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD} = {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD} - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4} = {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangBasic", "..\tools\clang\win32\clangBasic\clangBasic.vcproj", "{298B4876-6EF1-4E80-85D7-72F80693BBEB}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangAnalysis", "..\tools\clang\win32\clangAnalysis\clangAnalysis.vcproj", "{6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangRewrite", "..\tools\clang\win32\clangRewrite\clangRewrite.vcproj", "{F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clangLibDriver", "..\tools\clang\win32\clangLibDriver\clangLibDriver.vcproj", "{AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Configure|Win32 = Configure|Win32 - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {28AA9146-3482-4F41-9CC6-407B1D258508}.Configure|Win32.ActiveCfg = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Configure|Win32.Build.0 = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Debug|Win32.ActiveCfg = Debug|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Debug|Win32.Build.0 = Debug|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Release|Win32.ActiveCfg = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Release|Win32.Build.0 = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Configure|Win32.ActiveCfg = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Configure|Win32.Build.0 = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Debug|Win32.ActiveCfg = Debug|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Debug|Win32.Build.0 = Debug|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Release|Win32.ActiveCfg = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Release|Win32.Build.0 = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Configure|Win32.ActiveCfg = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Configure|Win32.Build.0 = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Debug|Win32.ActiveCfg = Debug|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Debug|Win32.Build.0 = Debug|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Release|Win32.ActiveCfg = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Release|Win32.Build.0 = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Configure|Win32.ActiveCfg = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Configure|Win32.Build.0 = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Debug|Win32.ActiveCfg = Debug|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Debug|Win32.Build.0 = Debug|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Release|Win32.ActiveCfg = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Release|Win32.Build.0 = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Configure|Win32.ActiveCfg = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Configure|Win32.Build.0 = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Debug|Win32.ActiveCfg = Debug|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Debug|Win32.Build.0 = Debug|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Release|Win32.ActiveCfg = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Release|Win32.Build.0 = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Configure|Win32.ActiveCfg = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Configure|Win32.Build.0 = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Debug|Win32.ActiveCfg = Debug|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Debug|Win32.Build.0 = Debug|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Release|Win32.ActiveCfg = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Release|Win32.Build.0 = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Configure|Win32.ActiveCfg = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Configure|Win32.Build.0 = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Debug|Win32.ActiveCfg = Debug|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Debug|Win32.Build.0 = Debug|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Release|Win32.ActiveCfg = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Release|Win32.Build.0 = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Configure|Win32.ActiveCfg = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Configure|Win32.Build.0 = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Debug|Win32.ActiveCfg = Debug|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Debug|Win32.Build.0 = Debug|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Release|Win32.ActiveCfg = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Release|Win32.Build.0 = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Configure|Win32.ActiveCfg = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Configure|Win32.Build.0 = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Debug|Win32.ActiveCfg = Debug|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Debug|Win32.Build.0 = Debug|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Release|Win32.ActiveCfg = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Release|Win32.Build.0 = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Configure|Win32.ActiveCfg = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Configure|Win32.Build.0 = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Debug|Win32.ActiveCfg = Debug|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Debug|Win32.Build.0 = Debug|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Release|Win32.ActiveCfg = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Release|Win32.Build.0 = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Configure|Win32.ActiveCfg = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Configure|Win32.Build.0 = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Debug|Win32.ActiveCfg = Debug|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Debug|Win32.Build.0 = Debug|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Release|Win32.ActiveCfg = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Release|Win32.Build.0 = Release|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Configure|Win32.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Configure|Win32.Build.0 = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Debug|Win32.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Debug|Win32.Build.0 = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Release|Win32.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Release|Win32.Build.0 = Configure|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Configure|Win32.ActiveCfg = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Configure|Win32.Build.0 = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Debug|Win32.ActiveCfg = Debug|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Debug|Win32.Build.0 = Debug|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Release|Win32.ActiveCfg = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Release|Win32.Build.0 = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Configure|Win32.ActiveCfg = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Configure|Win32.Build.0 = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Debug|Win32.ActiveCfg = Debug|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Debug|Win32.Build.0 = Debug|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Release|Win32.ActiveCfg = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Release|Win32.Build.0 = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Configure|Win32.ActiveCfg = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Configure|Win32.Build.0 = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Debug|Win32.ActiveCfg = Debug|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Debug|Win32.Build.0 = Debug|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Release|Win32.ActiveCfg = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Release|Win32.Build.0 = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Configure|Win32.ActiveCfg = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Configure|Win32.Build.0 = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Debug|Win32.ActiveCfg = Debug|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Debug|Win32.Build.0 = Debug|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Release|Win32.ActiveCfg = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Release|Win32.Build.0 = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Configure|Win32.ActiveCfg = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Configure|Win32.Build.0 = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Debug|Win32.ActiveCfg = Debug|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Debug|Win32.Build.0 = Debug|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Release|Win32.ActiveCfg = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Release|Win32.Build.0 = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Configure|Win32.ActiveCfg = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Configure|Win32.Build.0 = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Debug|Win32.ActiveCfg = Debug|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Debug|Win32.Build.0 = Debug|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Release|Win32.ActiveCfg = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Release|Win32.Build.0 = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Configure|Win32.ActiveCfg = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Configure|Win32.Build.0 = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Debug|Win32.ActiveCfg = Debug|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Debug|Win32.Build.0 = Debug|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Release|Win32.ActiveCfg = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Release|Win32.Build.0 = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Configure|Win32.ActiveCfg = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Configure|Win32.Build.0 = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Debug|Win32.ActiveCfg = Debug|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Debug|Win32.Build.0 = Debug|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Release|Win32.ActiveCfg = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Release|Win32.Build.0 = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Configure|Win32.ActiveCfg = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Configure|Win32.Build.0 = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Debug|Win32.ActiveCfg = Debug|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Debug|Win32.Build.0 = Debug|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Release|Win32.ActiveCfg = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Release|Win32.Build.0 = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Configure|Win32.ActiveCfg = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Configure|Win32.Build.0 = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Debug|Win32.ActiveCfg = Debug|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Debug|Win32.Build.0 = Debug|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Release|Win32.ActiveCfg = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Release|Win32.Build.0 = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Configure|Win32.ActiveCfg = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Configure|Win32.Build.0 = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Debug|Win32.ActiveCfg = Debug|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Debug|Win32.Build.0 = Debug|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Release|Win32.ActiveCfg = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Release|Win32.Build.0 = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Configure|Win32.ActiveCfg = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Configure|Win32.Build.0 = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Debug|Win32.ActiveCfg = Debug|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Debug|Win32.Build.0 = Debug|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Release|Win32.ActiveCfg = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Release|Win32.Build.0 = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Configure|Win32.ActiveCfg = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Configure|Win32.Build.0 = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Debug|Win32.ActiveCfg = Debug|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Debug|Win32.Build.0 = Debug|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Release|Win32.ActiveCfg = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Release|Win32.Build.0 = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Configure|Win32.ActiveCfg = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Configure|Win32.Build.0 = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Debug|Win32.ActiveCfg = Debug|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Debug|Win32.Build.0 = Debug|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Release|Win32.ActiveCfg = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Release|Win32.Build.0 = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Configure|Win32.ActiveCfg = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Configure|Win32.Build.0 = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Debug|Win32.ActiveCfg = Debug|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Debug|Win32.Build.0 = Debug|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Release|Win32.ActiveCfg = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Release|Win32.Build.0 = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Configure|Win32.ActiveCfg = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Configure|Win32.Build.0 = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Debug|Win32.ActiveCfg = Debug|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Debug|Win32.Build.0 = Debug|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Release|Win32.ActiveCfg = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Release|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Configure|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Configure|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Debug|Win32.ActiveCfg = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Debug|Win32.Build.0 = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Release|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Release|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Configure|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Configure|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Debug|Win32.ActiveCfg = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Debug|Win32.Build.0 = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Release|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Release|Win32.Build.0 = Release|Win32 - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73}.Configure|Win32.ActiveCfg = Release|Win32 - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73}.Configure|Win32.Build.0 = Release|Win32 - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73}.Debug|Win32.ActiveCfg = Debug|Win32 - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73}.Debug|Win32.Build.0 = Debug|Win32 - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73}.Release|Win32.ActiveCfg = Release|Win32 - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73}.Release|Win32.Build.0 = Release|Win32 - {05DF3074-11AF-491A-B078-83BD2EDC31F6}.Configure|Win32.ActiveCfg = Release|Win32 - {05DF3074-11AF-491A-B078-83BD2EDC31F6}.Configure|Win32.Build.0 = Release|Win32 - {05DF3074-11AF-491A-B078-83BD2EDC31F6}.Debug|Win32.ActiveCfg = Debug|Win32 - {05DF3074-11AF-491A-B078-83BD2EDC31F6}.Debug|Win32.Build.0 = Debug|Win32 - {05DF3074-11AF-491A-B078-83BD2EDC31F6}.Release|Win32.ActiveCfg = Release|Win32 - {05DF3074-11AF-491A-B078-83BD2EDC31F6}.Release|Win32.Build.0 = Release|Win32 - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}.Configure|Win32.ActiveCfg = Release|Win32 - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}.Configure|Win32.Build.0 = Release|Win32 - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}.Debug|Win32.ActiveCfg = Debug|Win32 - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}.Debug|Win32.Build.0 = Debug|Win32 - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}.Release|Win32.ActiveCfg = Release|Win32 - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD}.Release|Win32.Build.0 = Release|Win32 - {4727E8B7-AA99-41C9-AB09-A8A862595DB7}.Configure|Win32.ActiveCfg = Release|Win32 - {4727E8B7-AA99-41C9-AB09-A8A862595DB7}.Configure|Win32.Build.0 = Release|Win32 - {4727E8B7-AA99-41C9-AB09-A8A862595DB7}.Debug|Win32.ActiveCfg = Debug|Win32 - {4727E8B7-AA99-41C9-AB09-A8A862595DB7}.Debug|Win32.Build.0 = Debug|Win32 - {4727E8B7-AA99-41C9-AB09-A8A862595DB7}.Release|Win32.ActiveCfg = Release|Win32 - {4727E8B7-AA99-41C9-AB09-A8A862595DB7}.Release|Win32.Build.0 = Release|Win32 - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F}.Configure|Win32.ActiveCfg = Release|Win32 - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F}.Configure|Win32.Build.0 = Release|Win32 - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F}.Debug|Win32.ActiveCfg = Debug|Win32 - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F}.Debug|Win32.Build.0 = Debug|Win32 - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F}.Release|Win32.ActiveCfg = Release|Win32 - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F}.Release|Win32.Build.0 = Release|Win32 - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF}.Configure|Win32.ActiveCfg = Release|Win32 - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF}.Configure|Win32.Build.0 = Release|Win32 - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF}.Debug|Win32.ActiveCfg = Debug|Win32 - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF}.Debug|Win32.Build.0 = Debug|Win32 - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF}.Release|Win32.ActiveCfg = Release|Win32 - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF}.Release|Win32.Build.0 = Release|Win32 - {298B4876-6EF1-4E80-85D7-72F80693BBEB}.Configure|Win32.ActiveCfg = Release|Win32 - {298B4876-6EF1-4E80-85D7-72F80693BBEB}.Configure|Win32.Build.0 = Release|Win32 - {298B4876-6EF1-4E80-85D7-72F80693BBEB}.Debug|Win32.ActiveCfg = Debug|Win32 - {298B4876-6EF1-4E80-85D7-72F80693BBEB}.Debug|Win32.Build.0 = Debug|Win32 - {298B4876-6EF1-4E80-85D7-72F80693BBEB}.Release|Win32.ActiveCfg = Release|Win32 - {298B4876-6EF1-4E80-85D7-72F80693BBEB}.Release|Win32.Build.0 = Release|Win32 - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}.Configure|Win32.ActiveCfg = Release|Win32 - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}.Configure|Win32.Build.0 = Release|Win32 - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}.Debug|Win32.ActiveCfg = Debug|Win32 - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}.Debug|Win32.Build.0 = Debug|Win32 - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}.Release|Win32.ActiveCfg = Release|Win32 - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0}.Release|Win32.Build.0 = Release|Win32 - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}.Configure|Win32.ActiveCfg = Release|Win32 - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}.Configure|Win32.Build.0 = Release|Win32 - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}.Debug|Win32.ActiveCfg = Debug|Win32 - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}.Debug|Win32.Build.0 = Debug|Win32 - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}.Release|Win32.ActiveCfg = Release|Win32 - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D}.Release|Win32.Build.0 = Release|Win32 - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}.Configure|Win32.ActiveCfg = Release|Win32 - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}.Configure|Win32.Build.0 = Release|Win32 - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}.Debug|Win32.ActiveCfg = Debug|Win32 - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}.Debug|Win32.Build.0 = Debug|Win32 - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}.Release|Win32.ActiveCfg = Release|Win32 - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {339C2249-26B6-4172-B484-85653029AF57} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {48FB551D-E37E-42EC-BC97-FF7219774867} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {76295AE8-A083-460E-9F80-6F2B8923264A} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {19514E48-456C-4B9D-8637-F2285476461E} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {B13476BC-30AB-4EA0-BC1E-212C0A459405} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {3DC216F5-1DDD-478A-84F8-C124E5C31982} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {0FF2B75C-49C1-4B49-A44A-531C93000296} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {5E249789-49E1-4600-B12B-8AD2BB6439B2} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {057777CD-DED5-46DF-BF9A-6B76DE212549} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {006D8B41-C3C7-4448-85E1-AF8907E591E5} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {E0B1E329-BE3E-456D-B372-5F397BE42C84} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {64D8AA46-88DB-41F4-B837-053AE02406B8} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {5FF862CE-80A0-4B48-A80B-68AE325A0432} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {ACBE81D9-64B1-4133-823A-807A4E60B454} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {57249192-8E29-4D85-8B7A-FEFF1760B1DA} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {455BCF47-13B6-451E-8321-8ED9C4866BAA} - {030F6909-B2FA-4E53-BEA7-9A559CFC2F73} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {05DF3074-11AF-491A-B078-83BD2EDC31F6} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {5125C3DB-FBD6-4BF8-8D8B-CE51D6E93BCD} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {4727E8B7-AA99-41C9-AB09-A8A862595DB7} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {4CEC5897-D957-47E7-A6AE-2021D4F44A8F} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {7E7DA455-C276-4B93-8D02-8F7E2F629BAF} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {298B4876-6EF1-4E80-85D7-72F80693BBEB} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {6C98551A-4C36-4E74-8419-4D3EEEC9D8E0} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {F9FBDDA2-9EE1-473C-A456-BE20B7B2439D} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - {AECB78DF-C319-4D49-B2FD-F98F62EBBDF4} = {DAC2AB11-F09C-454B-86FD-9BDBBA25827F} - EndGlobalSection - GlobalSection(DPCodeReviewSolutionGUID) = preSolution - DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} - EndGlobalSection -EndGlobal diff --git a/win32/common.vsprops b/win32/common.vsprops deleted file mode 100644 index 80eb0425dbc..00000000000 --- a/win32/common.vsprops +++ /dev/null @@ -1,11 +0,0 @@ - - - - diff --git a/win32/config.h b/win32/config.h deleted file mode 100644 index 62d4c05d62a..00000000000 --- a/win32/config.h +++ /dev/null @@ -1,30 +0,0 @@ -/* This file is appended to config.h.in to form the Windows version of - * config.h */ - -#define PACKAGE_NAME "LLVM (win32 vc8.0)" -#define PACKAGE_VERSION 2.4 -#define PACKAGE_STRING "llvm 2.6svn" -#define LLVM_HOSTTRIPLE "i686-pc-win32" -#define HAVE_WINDOWS_H 1 -#define HAVE_LIMITS_H 1 -#define HAVE_SYS_STAT_H 1 -#define HAVE_STDLIB_H 1 -#define HAVE_STDIO_H 1 -#define HAVE_STRING_H 1 -#define HAVE_CEILF 1 -#define HAVE_FLOORF 1 -#define SHLIBEXT ".lib" -#define error_t int -#define HAVE_ERRNO_H 1 -#define LTDL_DLOPEN_DEPLIBS 1 -#define LTDL_OBJDIR "_libs" -#define LTDL_SHLIBPATH_VAR "PATH" -#define LTDL_SHLIB_EXT ".dll" -#define LTDL_SYSSEARCHPATH "" -#define LLVM_ON_WIN32 1 - -#define strtoll _strtoi64 -#define strtoull _strtoui64 -#define stricmp _stricmp -#define strdup _strdup - diff --git a/win32/dobison.cmd b/win32/dobison.cmd deleted file mode 100755 index 03d56ab4058..00000000000 --- a/win32/dobison.cmd +++ /dev/null @@ -1,29 +0,0 @@ -@echo off -rem dobison.cmd prefix mode target source -rem prefix - passed to bison as -p -rem mode - either debug or release -rem target - generated parser file name without extension -rem source - input to bison -rem headercopydir - directory to receive a copy of the header - -if "%2"=="debug" (set flags=-tvdo) else (set flags=-vdo) - -rem Test for presence of bison. -bison --help >NUL -if errorlevel 1 goto nobison - -rem Run bison. -echo bison -p%1 %flags%%3.cpp %4 -echo move %3.hpp %3.h -bison -p%1 %flags%%3.cpp %4 && move %3.hpp %3.h -echo copy %3.h %5 -copy %3.h %5 -exit - -:nobison -echo Bison not found. Using pre-generated files. -copy %~pn4.cpp.cvs .\%3.cpp -copy %~pn4.cpp.cvs %5\%3.cpp -copy %~pn4.h.cvs .\%3.h -copy %~pn4.h.cvs %5\%3.h -exit diff --git a/win32/doflex.cmd b/win32/doflex.cmd deleted file mode 100755 index 8f32fbdaa4a..00000000000 --- a/win32/doflex.cmd +++ /dev/null @@ -1,20 +0,0 @@ -@echo off -rem doflex.cmd prefix mode target source -rem mode - either debug or release -rem target - generated parser file name without extension -rem source - input to bison - -if "%1"=="debug" (set flags=-t) else (set flags=-t) - -rem Test for presence of flex. -flex --help >NUL -if errorlevel 1 goto noflex - -rem Run flex. -flex %flags% >%2.cpp %3 -exit - -:noflex -echo Flex not found. Using pre-generated files. -copy %~pn3.cpp.cvs %2.cpp -exit diff --git a/win32/llc/llc.vcproj b/win32/llc/llc.vcproj deleted file mode 100644 index 2ce6f460428..00000000000 --- a/win32/llc/llc.vcproj +++ /dev/null @@ -1,385 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/lli/lli.vcproj b/win32/lli/lli.vcproj deleted file mode 100644 index 0bcee7ed117..00000000000 --- a/win32/lli/lli.vcproj +++ /dev/null @@ -1,385 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-ar/llvm-ar.vcproj b/win32/llvm-ar/llvm-ar.vcproj deleted file mode 100644 index 1235ef13a44..00000000000 --- a/win32/llvm-ar/llvm-ar.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-as/llvm-as.vcproj b/win32/llvm-as/llvm-as.vcproj deleted file mode 100644 index e65070664e4..00000000000 --- a/win32/llvm-as/llvm-as.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-bcanalyzer/llvm-bcanalyzer.vcproj b/win32/llvm-bcanalyzer/llvm-bcanalyzer.vcproj deleted file mode 100644 index 18254c78788..00000000000 --- a/win32/llvm-bcanalyzer/llvm-bcanalyzer.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-dis/llvm-dis.vcproj b/win32/llvm-dis/llvm-dis.vcproj deleted file mode 100644 index be2261bf2bc..00000000000 --- a/win32/llvm-dis/llvm-dis.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-ld/llvm-ld.vcproj b/win32/llvm-ld/llvm-ld.vcproj deleted file mode 100644 index a2b4a541c55..00000000000 --- a/win32/llvm-ld/llvm-ld.vcproj +++ /dev/null @@ -1,385 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-link/llvm-link.vcproj b/win32/llvm-link/llvm-link.vcproj deleted file mode 100644 index 2624698eb70..00000000000 --- a/win32/llvm-link/llvm-link.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-nm/llvm-nm.vcproj b/win32/llvm-nm/llvm-nm.vcproj deleted file mode 100644 index 3c402a084aa..00000000000 --- a/win32/llvm-nm/llvm-nm.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-prof/llvm-prof.vcproj b/win32/llvm-prof/llvm-prof.vcproj deleted file mode 100644 index 77608abc9c9..00000000000 --- a/win32/llvm-prof/llvm-prof.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm-ranlib/llvm-ranlib.vcproj b/win32/llvm-ranlib/llvm-ranlib.vcproj deleted file mode 100644 index 2398ececc72..00000000000 --- a/win32/llvm-ranlib/llvm-ranlib.vcproj +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/llvm.sln b/win32/llvm.sln deleted file mode 100644 index 8aab563f6c6..00000000000 --- a/win32/llvm.sln +++ /dev/null @@ -1,719 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "support", "Support\Support.vcproj", "{28AA9146-3482-4F41-9CC6-407B1D258508}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TableGen", "TableGen\TableGen.vcproj", "{339C2249-26B6-4172-B484-85653029AF57}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Fibonacci", "Fibonacci\Fibonacci.vcproj", "{48FB551D-E37E-42EC-BC97-FF7219774867}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {144EEBF6-8C9B-4473-B715-2C821666AF6C} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {76295AE8-A083-460E-9F80-6F2B8923264A} = {76295AE8-A083-460E-9F80-6F2B8923264A} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExecutionEngine", "ExecutionEngine\ExecutionEngine.vcproj", "{76295AE8-A083-460E-9F80-6F2B8923264A}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VMCore", "VMCore\VMCore.vcproj", "{45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Target", "Target\Target.vcproj", "{059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CodeGen", "CodeGen\CodeGen.vcproj", "{08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "System", "System\System.vcproj", "{0F8407F3-FA23-4CF1-83A9-DCBE0B361489}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Analysis", "Analysis\Analysis.vcproj", "{0622E827-8464-489D-8B1C-B0B496F35C08}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "x86", "x86\x86.vcproj", "{144EEBF6-8C9B-4473-B715-2C821666AF6C}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Transforms", "Transforms\Transforms.vcproj", "{C59374C1-9FC0-4147-B836-327DFDC52D99}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {339C2249-26B6-4172-B484-85653029AF57} = {339C2249-26B6-4172-B484-85653029AF57} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Configure", "Configure\Configure.vcproj", "{19514E48-456C-4B9D-8637-F2285476461E}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lli", "lli\lli.vcproj", "{FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {144EEBF6-8C9B-4473-B715-2C821666AF6C} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {76295AE8-A083-460E-9F80-6F2B8923264A} = {76295AE8-A083-460E-9F80-6F2B8923264A} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llc", "llc\llc.vcproj", "{ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {144EEBF6-8C9B-4473-B715-2C821666AF6C} = {144EEBF6-8C9B-4473-B715-2C821666AF6C} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {057777CD-DED5-46DF-BF9A-6B76DE212549} = {057777CD-DED5-46DF-BF9A-6B76DE212549} - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} = {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-dis", "llvm-dis\llvm-dis.vcproj", "{B13476BC-30AB-4EA0-BC1E-212C0A459405}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-as", "llvm-as\llvm-as.vcproj", "{4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {3DC216F5-1DDD-478A-84F8-C124E5C31982} = {3DC216F5-1DDD-478A-84F8-C124E5C31982} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AsmParser", "AsmParser\AsmParser.vcproj", "{3DC216F5-1DDD-478A-84F8-C124E5C31982}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-ar", "llvm-ar\llvm-ar.vcproj", "{0FF2B75C-49C1-4B49-A44A-531C93000296}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-ranlib", "llvm-ranlib\llvm-ranlib.vcproj", "{BB16C7EE-B4ED-4714-B5ED-B775C62A6612}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-link", "llvm-link\llvm-link.vcproj", "{5E249789-49E1-4600-B12B-8AD2BB6439B2}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {342CF48F-760A-4040-A9A1-7D75AA2471CE} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Linker", "Linker\Linker.vcproj", "{342CF48F-760A-4040-A9A1-7D75AA2471CE}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CBackend", "CBackend\CBackend.vcproj", "{057777CD-DED5-46DF-BF9A-6B76DE212549}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opt", "opt\opt.vcproj", "{006D8B41-C3C7-4448-85E1-AF8907E591E5}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-bcanalyzer", "llvm-bcanalyzer\llvm-bcanalyzer.vcproj", "{E0B1E329-BE3E-456D-B372-5F397BE42C84}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-ld", "llvm-ld\llvm-ld.vcproj", "{64D8AA46-88DB-41F4-B837-053AE02406B8}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {342CF48F-760A-4040-A9A1-7D75AA2471CE} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-nm", "llvm-nm\llvm-nm.vcproj", "{5FF862CE-80A0-4B48-A80B-68AE325A0432}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "llvm-prof", "llvm-prof\llvm-prof.vcproj", "{ACBE81D9-64B1-4133-823A-807A4E60B454}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bugpoint", "bugpoint\bugpoint.vcproj", "{57249192-8E29-4D85-8B7A-FEFF1760B1DA}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {3DC216F5-1DDD-478A-84F8-C124E5C31982} = {3DC216F5-1DDD-478A-84F8-C124E5C31982} - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} = {0F8407F3-FA23-4CF1-83A9-DCBE0B361489} - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {C59374C1-9FC0-4147-B836-327DFDC52D99} = {C59374C1-9FC0-4147-B836-327DFDC52D99} - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} = {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4} - {342CF48F-760A-4040-A9A1-7D75AA2471CE} = {342CF48F-760A-4040-A9A1-7D75AA2471CE} - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} = {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - {0622E827-8464-489D-8B1C-B0B496F35C08} = {0622E827-8464-489D-8B1C-B0B496F35C08} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Bitcode", "Bitcode\Bitcode.vcproj", "{F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {28AA9146-3482-4F41-9CC6-407B1D258508} = {28AA9146-3482-4F41-9CC6-407B1D258508} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Archive", "Archive\Archive.vcproj", "{F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}" - ProjectSection(WebsiteProperties) = preProject - Debug.AspNetCompiler.Debug = "True" - Release.AspNetCompiler.Debug = "False" - EndProjectSection - ProjectSection(ProjectDependencies) = postProject - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} = {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB} - {19514E48-456C-4B9D-8637-F2285476461E} = {19514E48-456C-4B9D-8637-F2285476461E} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Configure|Win32 = Configure|Win32 - Configure|x64 = Configure|x64 - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {28AA9146-3482-4F41-9CC6-407B1D258508}.Configure|Win32.ActiveCfg = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Configure|Win32.Build.0 = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Configure|x64.ActiveCfg = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Debug|Win32.ActiveCfg = Debug|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Debug|Win32.Build.0 = Debug|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Debug|x64.ActiveCfg = Debug|x64 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Debug|x64.Build.0 = Debug|x64 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Release|Win32.ActiveCfg = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Release|Win32.Build.0 = Release|Win32 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Release|x64.ActiveCfg = Release|x64 - {28AA9146-3482-4F41-9CC6-407B1D258508}.Release|x64.Build.0 = Release|x64 - {339C2249-26B6-4172-B484-85653029AF57}.Configure|Win32.ActiveCfg = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Configure|Win32.Build.0 = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Configure|x64.ActiveCfg = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Debug|Win32.ActiveCfg = Debug|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Debug|Win32.Build.0 = Debug|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Debug|x64.ActiveCfg = Debug|x64 - {339C2249-26B6-4172-B484-85653029AF57}.Debug|x64.Build.0 = Debug|x64 - {339C2249-26B6-4172-B484-85653029AF57}.Release|Win32.ActiveCfg = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Release|Win32.Build.0 = Release|Win32 - {339C2249-26B6-4172-B484-85653029AF57}.Release|x64.ActiveCfg = Release|x64 - {339C2249-26B6-4172-B484-85653029AF57}.Release|x64.Build.0 = Release|x64 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Configure|Win32.ActiveCfg = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Configure|Win32.Build.0 = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Configure|x64.ActiveCfg = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Debug|Win32.ActiveCfg = Debug|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Debug|Win32.Build.0 = Debug|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Debug|x64.ActiveCfg = Debug|x64 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Debug|x64.Build.0 = Debug|x64 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Release|Win32.ActiveCfg = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Release|Win32.Build.0 = Release|Win32 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Release|x64.ActiveCfg = Release|x64 - {48FB551D-E37E-42EC-BC97-FF7219774867}.Release|x64.Build.0 = Release|x64 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Configure|Win32.ActiveCfg = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Configure|Win32.Build.0 = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Configure|x64.ActiveCfg = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Debug|Win32.ActiveCfg = Debug|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Debug|Win32.Build.0 = Debug|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Debug|x64.ActiveCfg = Debug|x64 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Debug|x64.Build.0 = Debug|x64 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Release|Win32.ActiveCfg = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Release|Win32.Build.0 = Release|Win32 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Release|x64.ActiveCfg = Release|x64 - {76295AE8-A083-460E-9F80-6F2B8923264A}.Release|x64.Build.0 = Release|x64 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Configure|Win32.ActiveCfg = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Configure|Win32.Build.0 = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Configure|x64.ActiveCfg = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Debug|Win32.ActiveCfg = Debug|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Debug|Win32.Build.0 = Debug|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Debug|x64.ActiveCfg = Debug|x64 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Debug|x64.Build.0 = Debug|x64 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Release|Win32.ActiveCfg = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Release|Win32.Build.0 = Release|Win32 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Release|x64.ActiveCfg = Release|x64 - {45CD78D7-C5D9-47FE-AD12-F3251EEDAFFB}.Release|x64.Build.0 = Release|x64 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Configure|Win32.ActiveCfg = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Configure|Win32.Build.0 = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Configure|x64.ActiveCfg = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Debug|Win32.ActiveCfg = Debug|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Debug|Win32.Build.0 = Debug|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Debug|x64.ActiveCfg = Debug|x64 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Debug|x64.Build.0 = Debug|x64 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Release|Win32.ActiveCfg = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Release|Win32.Build.0 = Release|Win32 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Release|x64.ActiveCfg = Release|x64 - {059FBAB8-C76D-48A0-AA75-3C57BD3EAFE4}.Release|x64.Build.0 = Release|x64 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Configure|Win32.ActiveCfg = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Configure|Win32.Build.0 = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Configure|x64.ActiveCfg = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Debug|Win32.ActiveCfg = Debug|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Debug|Win32.Build.0 = Debug|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Debug|x64.ActiveCfg = Debug|x64 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Debug|x64.Build.0 = Debug|x64 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Release|Win32.ActiveCfg = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Release|Win32.Build.0 = Release|Win32 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Release|x64.ActiveCfg = Release|x64 - {08CEB1BB-C2A4-4587-B9A9-AEDB8FB44897}.Release|x64.Build.0 = Release|x64 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Configure|Win32.ActiveCfg = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Configure|Win32.Build.0 = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Configure|x64.ActiveCfg = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Debug|Win32.ActiveCfg = Debug|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Debug|Win32.Build.0 = Debug|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Debug|x64.ActiveCfg = Debug|x64 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Debug|x64.Build.0 = Debug|x64 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Release|Win32.ActiveCfg = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Release|Win32.Build.0 = Release|Win32 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Release|x64.ActiveCfg = Release|x64 - {0F8407F3-FA23-4CF1-83A9-DCBE0B361489}.Release|x64.Build.0 = Release|x64 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Configure|Win32.ActiveCfg = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Configure|Win32.Build.0 = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Configure|x64.ActiveCfg = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Debug|Win32.ActiveCfg = Debug|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Debug|Win32.Build.0 = Debug|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Debug|x64.ActiveCfg = Debug|x64 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Debug|x64.Build.0 = Debug|x64 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Release|Win32.ActiveCfg = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Release|Win32.Build.0 = Release|Win32 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Release|x64.ActiveCfg = Release|x64 - {0622E827-8464-489D-8B1C-B0B496F35C08}.Release|x64.Build.0 = Release|x64 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Configure|Win32.ActiveCfg = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Configure|Win32.Build.0 = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Configure|x64.ActiveCfg = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Debug|Win32.ActiveCfg = Debug|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Debug|Win32.Build.0 = Debug|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Debug|x64.ActiveCfg = Debug|x64 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Debug|x64.Build.0 = Debug|x64 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Release|Win32.ActiveCfg = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Release|Win32.Build.0 = Release|Win32 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Release|x64.ActiveCfg = Release|x64 - {144EEBF6-8C9B-4473-B715-2C821666AF6C}.Release|x64.Build.0 = Release|x64 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Configure|Win32.ActiveCfg = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Configure|Win32.Build.0 = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Configure|x64.ActiveCfg = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Debug|Win32.ActiveCfg = Debug|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Debug|Win32.Build.0 = Debug|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Debug|x64.ActiveCfg = Debug|x64 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Debug|x64.Build.0 = Debug|x64 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Release|Win32.ActiveCfg = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Release|Win32.Build.0 = Release|Win32 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Release|x64.ActiveCfg = Release|x64 - {C59374C1-9FC0-4147-B836-327DFDC52D99}.Release|x64.Build.0 = Release|x64 - {19514E48-456C-4B9D-8637-F2285476461E}.Configure|Win32.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Configure|Win32.Build.0 = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Configure|x64.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Debug|Win32.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Debug|Win32.Build.0 = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Debug|x64.ActiveCfg = Configure|x64 - {19514E48-456C-4B9D-8637-F2285476461E}.Debug|x64.Build.0 = Configure|x64 - {19514E48-456C-4B9D-8637-F2285476461E}.Release|Win32.ActiveCfg = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Release|Win32.Build.0 = Configure|Win32 - {19514E48-456C-4B9D-8637-F2285476461E}.Release|x64.ActiveCfg = Configure|x64 - {19514E48-456C-4B9D-8637-F2285476461E}.Release|x64.Build.0 = Configure|x64 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Configure|Win32.ActiveCfg = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Configure|Win32.Build.0 = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Configure|x64.ActiveCfg = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Debug|Win32.ActiveCfg = Debug|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Debug|Win32.Build.0 = Debug|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Debug|x64.ActiveCfg = Debug|x64 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Debug|x64.Build.0 = Debug|x64 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Release|Win32.ActiveCfg = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Release|Win32.Build.0 = Release|Win32 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Release|x64.ActiveCfg = Release|x64 - {FB6FFD68-C1E4-4DCF-AB02-36D205D5263E}.Release|x64.Build.0 = Release|x64 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Configure|Win32.ActiveCfg = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Configure|Win32.Build.0 = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Configure|x64.ActiveCfg = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Debug|Win32.ActiveCfg = Debug|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Debug|Win32.Build.0 = Debug|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Debug|x64.ActiveCfg = Debug|x64 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Debug|x64.Build.0 = Debug|x64 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Release|Win32.ActiveCfg = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Release|Win32.Build.0 = Release|Win32 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Release|x64.ActiveCfg = Release|x64 - {ADE86BDC-B04C-43DF-B9BB-90492C7B14AC}.Release|x64.Build.0 = Release|x64 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Configure|Win32.ActiveCfg = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Configure|Win32.Build.0 = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Configure|x64.ActiveCfg = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Debug|Win32.ActiveCfg = Debug|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Debug|Win32.Build.0 = Debug|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Debug|x64.ActiveCfg = Debug|x64 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Debug|x64.Build.0 = Debug|x64 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Release|Win32.ActiveCfg = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Release|Win32.Build.0 = Release|Win32 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Release|x64.ActiveCfg = Release|x64 - {B13476BC-30AB-4EA0-BC1E-212C0A459405}.Release|x64.Build.0 = Release|x64 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Configure|Win32.ActiveCfg = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Configure|Win32.Build.0 = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Configure|x64.ActiveCfg = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Debug|Win32.ActiveCfg = Debug|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Debug|Win32.Build.0 = Debug|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Debug|x64.ActiveCfg = Debug|x64 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Debug|x64.Build.0 = Debug|x64 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Release|Win32.ActiveCfg = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Release|Win32.Build.0 = Release|Win32 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Release|x64.ActiveCfg = Release|x64 - {4FBC40A5-E626-4A6C-A9D3-FAE5C28D30CC}.Release|x64.Build.0 = Release|x64 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Configure|Win32.ActiveCfg = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Configure|Win32.Build.0 = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Configure|x64.ActiveCfg = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Debug|Win32.ActiveCfg = Debug|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Debug|Win32.Build.0 = Debug|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Debug|x64.ActiveCfg = Debug|x64 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Debug|x64.Build.0 = Debug|x64 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Release|Win32.ActiveCfg = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Release|Win32.Build.0 = Release|Win32 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Release|x64.ActiveCfg = Release|x64 - {3DC216F5-1DDD-478A-84F8-C124E5C31982}.Release|x64.Build.0 = Release|x64 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Configure|Win32.ActiveCfg = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Configure|Win32.Build.0 = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Configure|x64.ActiveCfg = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Debug|Win32.ActiveCfg = Debug|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Debug|Win32.Build.0 = Debug|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Debug|x64.ActiveCfg = Debug|x64 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Debug|x64.Build.0 = Debug|x64 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Release|Win32.ActiveCfg = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Release|Win32.Build.0 = Release|Win32 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Release|x64.ActiveCfg = Release|x64 - {0FF2B75C-49C1-4B49-A44A-531C93000296}.Release|x64.Build.0 = Release|x64 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Configure|Win32.ActiveCfg = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Configure|Win32.Build.0 = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Configure|x64.ActiveCfg = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Debug|Win32.ActiveCfg = Debug|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Debug|Win32.Build.0 = Debug|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Debug|x64.ActiveCfg = Debug|x64 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Debug|x64.Build.0 = Debug|x64 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Release|Win32.ActiveCfg = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Release|Win32.Build.0 = Release|Win32 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Release|x64.ActiveCfg = Release|x64 - {BB16C7EE-B4ED-4714-B5ED-B775C62A6612}.Release|x64.Build.0 = Release|x64 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Configure|Win32.ActiveCfg = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Configure|Win32.Build.0 = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Configure|x64.ActiveCfg = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Debug|Win32.ActiveCfg = Debug|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Debug|Win32.Build.0 = Debug|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Debug|x64.ActiveCfg = Debug|x64 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Debug|x64.Build.0 = Debug|x64 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Release|Win32.ActiveCfg = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Release|Win32.Build.0 = Release|Win32 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Release|x64.ActiveCfg = Release|x64 - {5E249789-49E1-4600-B12B-8AD2BB6439B2}.Release|x64.Build.0 = Release|x64 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Configure|Win32.ActiveCfg = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Configure|Win32.Build.0 = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Configure|x64.ActiveCfg = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Debug|Win32.ActiveCfg = Debug|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Debug|Win32.Build.0 = Debug|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Debug|x64.ActiveCfg = Debug|x64 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Debug|x64.Build.0 = Debug|x64 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Release|Win32.ActiveCfg = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Release|Win32.Build.0 = Release|Win32 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Release|x64.ActiveCfg = Release|x64 - {342CF48F-760A-4040-A9A1-7D75AA2471CE}.Release|x64.Build.0 = Release|x64 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Configure|Win32.ActiveCfg = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Configure|Win32.Build.0 = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Configure|x64.ActiveCfg = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Debug|Win32.ActiveCfg = Debug|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Debug|Win32.Build.0 = Debug|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Debug|x64.ActiveCfg = Debug|x64 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Debug|x64.Build.0 = Debug|x64 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Release|Win32.ActiveCfg = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Release|Win32.Build.0 = Release|Win32 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Release|x64.ActiveCfg = Release|x64 - {057777CD-DED5-46DF-BF9A-6B76DE212549}.Release|x64.Build.0 = Release|x64 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Configure|Win32.ActiveCfg = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Configure|Win32.Build.0 = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Configure|x64.ActiveCfg = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Debug|Win32.ActiveCfg = Debug|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Debug|Win32.Build.0 = Debug|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Debug|x64.ActiveCfg = Debug|x64 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Debug|x64.Build.0 = Debug|x64 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Release|Win32.ActiveCfg = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Release|Win32.Build.0 = Release|Win32 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Release|x64.ActiveCfg = Release|x64 - {006D8B41-C3C7-4448-85E1-AF8907E591E5}.Release|x64.Build.0 = Release|x64 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Configure|Win32.ActiveCfg = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Configure|Win32.Build.0 = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Configure|x64.ActiveCfg = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Debug|Win32.ActiveCfg = Debug|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Debug|Win32.Build.0 = Debug|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Debug|x64.ActiveCfg = Debug|x64 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Debug|x64.Build.0 = Debug|x64 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Release|Win32.ActiveCfg = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Release|Win32.Build.0 = Release|Win32 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Release|x64.ActiveCfg = Release|x64 - {E0B1E329-BE3E-456D-B372-5F397BE42C84}.Release|x64.Build.0 = Release|x64 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Configure|Win32.ActiveCfg = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Configure|Win32.Build.0 = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Configure|x64.ActiveCfg = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Debug|Win32.ActiveCfg = Debug|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Debug|Win32.Build.0 = Debug|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Debug|x64.ActiveCfg = Debug|x64 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Debug|x64.Build.0 = Debug|x64 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Release|Win32.ActiveCfg = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Release|Win32.Build.0 = Release|Win32 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Release|x64.ActiveCfg = Release|x64 - {64D8AA46-88DB-41F4-B837-053AE02406B8}.Release|x64.Build.0 = Release|x64 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Configure|Win32.ActiveCfg = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Configure|Win32.Build.0 = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Configure|x64.ActiveCfg = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Debug|Win32.ActiveCfg = Debug|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Debug|Win32.Build.0 = Debug|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Debug|x64.ActiveCfg = Debug|x64 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Debug|x64.Build.0 = Debug|x64 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Release|Win32.ActiveCfg = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Release|Win32.Build.0 = Release|Win32 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Release|x64.ActiveCfg = Release|x64 - {5FF862CE-80A0-4B48-A80B-68AE325A0432}.Release|x64.Build.0 = Release|x64 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Configure|Win32.ActiveCfg = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Configure|Win32.Build.0 = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Configure|x64.ActiveCfg = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Debug|Win32.ActiveCfg = Debug|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Debug|Win32.Build.0 = Debug|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Debug|x64.ActiveCfg = Debug|x64 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Debug|x64.Build.0 = Debug|x64 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Release|Win32.ActiveCfg = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Release|Win32.Build.0 = Release|Win32 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Release|x64.ActiveCfg = Release|x64 - {ACBE81D9-64B1-4133-823A-807A4E60B454}.Release|x64.Build.0 = Release|x64 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Configure|Win32.ActiveCfg = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Configure|Win32.Build.0 = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Configure|x64.ActiveCfg = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Debug|Win32.ActiveCfg = Debug|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Debug|Win32.Build.0 = Debug|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Debug|x64.ActiveCfg = Debug|x64 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Debug|x64.Build.0 = Debug|x64 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Release|Win32.ActiveCfg = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Release|Win32.Build.0 = Release|Win32 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Release|x64.ActiveCfg = Release|x64 - {57249192-8E29-4D85-8B7A-FEFF1760B1DA}.Release|x64.Build.0 = Release|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Configure|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Configure|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Configure|x64.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Debug|Win32.ActiveCfg = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Debug|Win32.Build.0 = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Debug|x64.ActiveCfg = Debug|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Debug|x64.Build.0 = Debug|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Release|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Release|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Release|x64.ActiveCfg = Release|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D62}.Release|x64.Build.0 = Release|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Configure|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Configure|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Configure|x64.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Debug|Win32.ActiveCfg = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Debug|Win32.Build.0 = Debug|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Debug|x64.ActiveCfg = Debug|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Debug|x64.Build.0 = Debug|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Release|Win32.ActiveCfg = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Release|Win32.Build.0 = Release|Win32 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Release|x64.ActiveCfg = Release|x64 - {F1EFF064-8869-4DFF-8E1A-CD8F4A5F8D61}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(DPCodeReviewSolutionGUID) = preSolution - DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} - EndGlobalSection -EndGlobal diff --git a/win32/opt/opt.vcproj b/win32/opt/opt.vcproj deleted file mode 100644 index 8ef1629eb7f..00000000000 --- a/win32/opt/opt.vcproj +++ /dev/null @@ -1,393 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/unistd.h b/win32/unistd.h deleted file mode 100644 index 412afcc0a66..00000000000 --- a/win32/unistd.h +++ /dev/null @@ -1 +0,0 @@ -// This file has to be here because it's #included from the auto generated FileLexer.cpp diff --git a/win32/x86/x86.vcproj b/win32/x86/x86.vcproj deleted file mode 100644 index b5d10e8291f..00000000000 --- a/win32/x86/x86.vcproj +++ /dev/null @@ -1,620 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 659f684ea05427406d94d6f530a77916495a800f Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Thu, 16 Sep 2010 17:24:25 +0000 Subject: [PATCH 0813/1624] Add support for dumping kernel to gconcat. Dumping goes to the component, where dump partition begins. --- sys/geom/concat/g_concat.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/sys/geom/concat/g_concat.c b/sys/geom/concat/g_concat.c index 1f523755c7d..545cb8f4ce7 100644 --- a/sys/geom/concat/g_concat.c +++ b/sys/geom/concat/g_concat.c @@ -211,6 +211,39 @@ g_concat_access(struct g_provider *pp, int dr, int dw, int de) return (error); } +static void +g_concat_kernel_dump(struct bio *bp) +{ + struct g_concat_softc *sc; + struct g_concat_disk *disk; + struct bio *cbp; + struct g_kerneldump *gkd; + u_int i; + + sc = bp->bio_to->geom->softc; + gkd = (struct g_kerneldump *)bp->bio_data; + for (i = 0; i < sc->sc_ndisks; i++) { + if (sc->sc_disks[i].d_start <= gkd->offset && + sc->sc_disks[i].d_end > gkd->offset) + break; + } + if (i == sc->sc_ndisks) + g_io_deliver(bp, EOPNOTSUPP); + disk = &sc->sc_disks[i]; + gkd->offset -= disk->d_start; + if (gkd->length > disk->d_end - disk->d_start - gkd->offset) + gkd->length = disk->d_end - disk->d_start - gkd->offset; + cbp = g_clone_bio(bp); + if (cbp == NULL) { + g_io_deliver(bp, ENOMEM); + return; + } + cbp->bio_done = g_std_done; + g_io_request(cbp, disk->d_consumer); + G_CONCAT_DEBUG(1, "Kernel dump will go to %s.", + disk->d_consumer->provider->name); +} + static void g_concat_flush(struct g_concat_softc *sc, struct bio *bp) { @@ -280,7 +313,12 @@ g_concat_start(struct bio *bp) g_concat_flush(sc, bp); return; case BIO_GETATTR: + if (strcmp("GEOM::kerneldump", bp->bio_attribute) == 0) { + g_concat_kernel_dump(bp); + return; + } /* To which provider it should be delivered? */ + /* FALLTHROUGH */ default: g_io_deliver(bp, EOPNOTSUPP); return; From 767c3593eb92a3bfa74ad311b0ab16d3ceb8b84c Mon Sep 17 00:00:00 2001 From: Pyun YongHyeon Date: Thu, 16 Sep 2010 17:32:37 +0000 Subject: [PATCH 0814/1624] Fix incorrect RX BD producer updates. The producer index was already updated after allocating mbuf so driver had to use the last index instead of using next producer index. This should fix driver hang which may happen under high network load. Reported by: Igor Sysoev rambler-co dot ru>, Vlad Galu dudu dot ro> Tested by: Igor Sysoev rambler-co dot ru>, Vlad Galu dudu dot ro> MFC after: 10 days --- sys/dev/bge/if_bge.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sys/dev/bge/if_bge.c b/sys/dev/bge/if_bge.c index aff148ff0e3..0d1b871c261 100644 --- a/sys/dev/bge/if_bge.c +++ b/sys/dev/bge/if_bge.c @@ -3386,9 +3386,11 @@ bge_rxeof(struct bge_softc *sc, uint16_t rx_prod, int holdlck) sc->bge_rx_saved_considx = rx_cons; bge_writembx(sc, BGE_MBX_RX_CONS0_LO, sc->bge_rx_saved_considx); if (stdcnt) - bge_writembx(sc, BGE_MBX_RX_STD_PROD_LO, sc->bge_std); + bge_writembx(sc, BGE_MBX_RX_STD_PROD_LO, (sc->bge_std + + BGE_STD_RX_RING_CNT - 1) % BGE_STD_RX_RING_CNT); if (jumbocnt) - bge_writembx(sc, BGE_MBX_RX_JUMBO_PROD_LO, sc->bge_jumbo); + bge_writembx(sc, BGE_MBX_RX_JUMBO_PROD_LO, (sc->bge_jumbo + + BGE_JUMBO_RX_RING_CNT - 1) % BGE_JUMBO_RX_RING_CNT); #ifdef notyet /* * This register wraps very quickly under heavy packet drops. From dfe2c294f34e8a72230f2da4f3acb9fa993a74a0 Mon Sep 17 00:00:00 2001 From: Attilio Rao Date: Thu, 16 Sep 2010 17:49:10 +0000 Subject: [PATCH 0815/1624] Implement device unbusying via a cdevpriv destructor. Suggested by: jhb Tested by: Mark Johnston Reviewed by: emaste, jhb MFC after: 10 days X-MFC: r212661 --- sys/dev/aac/aac.c | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/sys/dev/aac/aac.c b/sys/dev/aac/aac.c index 4ff1640ab84..3071ddfc225 100644 --- a/sys/dev/aac/aac.c +++ b/sys/dev/aac/aac.c @@ -189,9 +189,9 @@ static char *aac_describe_code(struct aac_code_lookup *table, /* Management Interface */ static d_open_t aac_open; -static d_close_t aac_close; static d_ioctl_t aac_ioctl; static d_poll_t aac_poll; +static void aac_cdevpriv_dtor(void *arg); static int aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib); static int aac_ioctl_send_raw_srb(struct aac_softc *sc, caddr_t arg); static void aac_handle_aif(struct aac_softc *sc, @@ -212,9 +212,8 @@ static struct aac_mntinforesp * static struct cdevsw aac_cdevsw = { .d_version = D_VERSION, - .d_flags = D_NEEDGIANT | D_TRACKCLOSE, + .d_flags = D_NEEDGIANT, .d_open = aac_open, - .d_close = aac_close, .d_ioctl = aac_ioctl, .d_poll = aac_poll, .d_name = "aac", @@ -2802,18 +2801,7 @@ aac_open(struct cdev *dev, int flags, int fmt, struct thread *td) sc = dev->si_drv1; fwprintf(sc, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, ""); device_busy(sc->aac_dev); - - return 0; -} - -static int -aac_close(struct cdev *dev, int flags, int fmt, struct thread *td) -{ - struct aac_softc *sc; - - sc = dev->si_drv1; - fwprintf(sc, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, ""); - device_unbusy(sc->aac_dev); + devfs_set_cdevpriv(sc, aac_cdevpriv_dtor); return 0; } @@ -3200,6 +3188,21 @@ out: return(error); } +/* + * cdevpriv interface private destructor. + */ +static void +aac_cdevpriv_dtor(void *arg) +{ + struct aac_softc *sc; + + sc = arg; + fwprintf(sc, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, ""); + mtx_lock(&Giant); + device_unbusy(sc->aac_dev); + mtx_unlock(&Giant); +} + /* * Handle an AIF sent to us by the controller; queue it for later reference. * If the queue fills up, then drop the older entries. From d0d7bcdf92d0eece07efe24d418433980b517898 Mon Sep 17 00:00:00 2001 From: Jung-uk Kim Date: Thu, 16 Sep 2010 18:37:33 +0000 Subject: [PATCH 0816/1624] Fix a typo in a comment. Submitted by: afiveg --- sys/net/bpf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/net/bpf.c b/sys/net/bpf.c index ab2ba1f2528..e5165731dae 100644 --- a/sys/net/bpf.c +++ b/sys/net/bpf.c @@ -1392,7 +1392,7 @@ bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, break; /* - * Set packet timestamp format and resolution. + * Get packet timestamp format and resolution. */ case BIOCGTSTAMP: *(u_int *)addr = d->bd_tstamp; From f0613ab15b5d3060331332a023e1fc862817fd7a Mon Sep 17 00:00:00 2001 From: "Jayachandran C." Date: Thu, 16 Sep 2010 19:13:55 +0000 Subject: [PATCH 0817/1624] Network driver updates. - Move RMI MIPS extension to atomic increment word (LDADDWU) to common header file sys/mips/rmi/rmi_mips_exts.h - Fix xlr_ldaddwu() for 64 bit, it is a 32 bit operation, use unsigned int* instead of unsigned long* argument - Provide dummy xlr_enable_kx/xlr_restore_kx for n32 and n64. - Provide xlr_paddr_ld() instead of xlr_paddr_lw(), so that the descriptor formats are same for 32 and 64 bit - update nlge and rge for the changes These changes are also needed by the security driver which will be added later. --- sys/mips/rmi/dev/nlge/if_nlge.c | 85 ++++++++++---------------- sys/mips/rmi/dev/xlr/rge.c | 66 ++++---------------- sys/mips/rmi/rmi_mips_exts.h | 104 ++++++++++++++++++++++++-------- 3 files changed, 124 insertions(+), 131 deletions(-) diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c index a80b2674539..1a217c0445b 100644 --- a/sys/mips/rmi/dev/nlge/if_nlge.c +++ b/sys/mips/rmi/dev/nlge/if_nlge.c @@ -300,31 +300,13 @@ DRIVER_MODULE(miibus, nlge, miibus_driver, miibus_devclass, 0, 0); static uma_zone_t nl_tx_desc_zone; -/* Function to atomically increment an integer with the given value. */ -static __inline__ unsigned int -ldadd_wu(unsigned int value, unsigned long *addr) +static __inline void +atomic_incr_long(unsigned long *addr) { - __asm__ __volatile__( ".set push\n" - ".set noreorder\n" - "move $8, %2\n" - "move $9, %3\n" - /* "ldaddwu $8, $9\n" */ - ".word 0x71280011\n" - "move %0, $8\n" - ".set pop\n" - : "=&r"(value), "+m"(*addr) - : "0"(value), "r" ((unsigned long)addr) - : "$8", "$9"); - return value; -} + /* XXX: fix for 64 bit */ + unsigned int *iaddr = (unsigned int *)addr; -static __inline__ uint32_t -xlr_enable_kx(void) -{ - uint32_t sr = mips_rd_status(); - - mips_wr_status((sr & ~MIPS_SR_INT_IE) | MIPS_SR_KX); - return sr; + xlr_ldaddwu(1, iaddr); } static int @@ -683,7 +665,7 @@ nlge_msgring_handler(int bucket, int size, int code, int stid, if (ifp->if_drv_flags & IFF_DRV_OACTIVE){ ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; } - ldadd_wu(1, (tx_error) ? &ifp->if_oerrors: &ifp->if_opackets); + atomic_incr_long((tx_error) ? &ifp->if_oerrors: &ifp->if_opackets); } else if (ctrl == CTRL_SNGL || ctrl == CTRL_START) { /* Rx Packet */ @@ -766,7 +748,7 @@ fail: //ifp->if_drv_flags |= IFF_DRV_OACTIVE; //IF_PREPEND(&ifp->if_snd, m); m_freem(m); - ldadd_wu(1, &ifp->if_iqdrops); + atomic_incr_long(&ifp->if_iqdrops); } return; } @@ -774,14 +756,15 @@ fail: static void nlge_rx(struct nlge_softc *sc, vm_paddr_t paddr, int len) { - struct ifnet *ifp; - struct mbuf *m; - uint32_t tm, mag, sr; + struct ifnet *ifp; + struct mbuf *m; + uint64_t tm, mag; + uint32_t sr; sr = xlr_enable_kx(); - tm = xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE); - mag = xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE + sizeof(uint32_t)); - mips_wr_status(sr); + tm = xlr_paddr_ld(paddr - XLR_CACHELINE_SIZE); + mag = xlr_paddr_ld(paddr - XLR_CACHELINE_SIZE + sizeof(uint64_t)); + xlr_restore_kx(sr); m = (struct mbuf *)(intptr_t)tm; if (mag != 0xf00bad) { @@ -797,7 +780,7 @@ nlge_rx(struct nlge_softc *sc, vm_paddr_t paddr, int len) m->m_pkthdr.len = m->m_len = len; m->m_pkthdr.rcvif = ifp; - ldadd_wu(1, &ifp->if_ipackets); + atomic_incr_long(&ifp->if_ipackets); (*ifp->if_input)(ifp, m); } @@ -1895,15 +1878,11 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg, return 2; } /* - * As we currently use xlr_paddr_lw on a 32-bit - * OS, both the pointers are laid out in one - * 64-bit location - this makes it easy to - * retrieve the pointers when processing the - * tx free-back descriptor. + * Save the virtual address in the descriptor, + * it makes freeing easy. */ p2p->frag[XLR_MAX_TX_FRAGS] = - (((uint64_t) (vm_offset_t) p2p) << 32) | - ((vm_offset_t) mbuf_chain); + (uint64_t)(vm_offset_t)p2p; cur_p2d = &p2p->frag[0]; is_p2p = 1; } else if (msg_sz == (FMN_SZ - 2 + XLR_MAX_TX_FRAGS)) { @@ -1932,7 +1911,7 @@ prepare_fmn_message(struct nlge_softc *sc, struct msgrng_msg *fmn_msg, cur_p2d[-1] |= (1ULL << 63); /* set eop in most-recent p2d */ *cur_p2d = (1ULL << 63) | ((uint64_t)fb_stn_id << 54) | - (vm_offset_t) mbuf_chain; + (vm_offset_t) mbuf_chain; /* XXX: fix 64 bit */ *tx_desc = p2p; if (is_p2p) { @@ -1973,39 +1952,41 @@ release_tx_desc(vm_paddr_t paddr) { struct nlge_tx_desc *tx_desc; uint32_t sr; - uint32_t val1, val2; + uint64_t vaddr; paddr += (XLR_MAX_TX_FRAGS * sizeof(uint64_t)); sr = xlr_enable_kx(); - val1 = xlr_paddr_lw(paddr); - paddr += sizeof(void *); - val2 = xlr_paddr_lw(paddr); - mips_wr_status(sr); + vaddr = xlr_paddr_ld(paddr); + xlr_restore_kx(sr); - tx_desc = (struct nlge_tx_desc*)(intptr_t) val1; + tx_desc = (struct nlge_tx_desc*)(intptr_t)vaddr; uma_zfree(nl_tx_desc_zone, tx_desc); } static void * get_buf(void) { - struct mbuf *m_new; - vm_paddr_t temp1, temp2; - unsigned int *md; + struct mbuf *m_new; + uint64_t *md; +#ifdef INVARIANTS + vm_paddr_t temp1, temp2; +#endif if ((m_new = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR)) == NULL) - return NULL; + return (NULL); m_new->m_len = m_new->m_pkthdr.len = MCLBYTES; m_adj(m_new, XLR_CACHELINE_SIZE - ((unsigned int)m_new->m_data & 0x1f)); - md = (unsigned int *)m_new->m_data; - md[0] = (unsigned int)m_new; /* Back Ptr */ + md = (uint64_t *)m_new->m_data; + md[0] = (intptr_t)m_new; /* Back Ptr */ md[1] = 0xf00bad; m_adj(m_new, XLR_CACHELINE_SIZE); +#ifdef INVARIANTS temp1 = vtophys((vm_offset_t) m_new->m_data); temp2 = vtophys((vm_offset_t) m_new->m_data + 1536); if ((temp1 + 1536) != temp2) panic("ALLOCED BUFFER IS NOT CONTIGUOUS\n"); +#endif return ((void *)m_new->m_data); } diff --git a/sys/mips/rmi/dev/xlr/rge.c b/sys/mips/rmi/dev/xlr/rge.c index c7a02c261d1..09045f4bdcf 100644 --- a/sys/mips/rmi/dev/xlr/rge.c +++ b/sys/mips/rmi/dev/xlr/rge.c @@ -184,35 +184,8 @@ int xlr_rge_tx_ok_done[MAXCPU]; int xlr_rge_rx_done[MAXCPU]; int xlr_rge_repl_done[MAXCPU]; -static __inline__ unsigned int -ldadd_wu(unsigned int value, unsigned long *addr) -{ - __asm__ __volatile__(".set push\n" - ".set noreorder\n" - "move $8, %2\n" - "move $9, %3\n" - /* "ldaddwu $8, $9\n" */ - ".word 0x71280011\n" - "move %0, $8\n" - ".set pop\n" - : "=&r"(value), "+m"(*addr) - : "0"(value), "r"((unsigned long)addr) - : "$8", "$9"); - - return value; -} - -static __inline__ uint32_t -xlr_enable_kx(void) -{ - uint32_t sr = mips_rd_status(); - - mips_wr_status((sr & ~MIPS_SR_INT_IE) | MIPS_SR_KX); - return sr; -} - /* #define mac_stats_add(x, val) ({(x) += (val);}) */ -#define mac_stats_add(x, val) ldadd_wu(val, &x) +#define mac_stats_add(x, val) xlr_ldaddwu(val, &x) #define XLR_MAX_CORE 8 #define RGE_LOCK_INIT(_sc, _name) \ @@ -611,25 +584,16 @@ static void free_buf(vm_paddr_t paddr) { struct mbuf *m; - uint32_t mag; -#ifdef __mips_n64 - uint64_t *vaddr; - - vaddr = (uint64_t *)MIPS_PHYS_TO_XKPHYS_CACHED(paddr); - m = (struct mbuf *)vaddr[0]; - mag = (uint32_t)vaddr[1]; -#else + uint64_t mag; uint32_t sr; sr = xlr_enable_kx(); - m = (struct mbuf *)(intptr_t)xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE + sizeof(uint32_t)); - mag = xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE + 3 * sizeof(uint32_t)); - mips_wr_status(sr); -#endif - + m = (struct mbuf *)(intptr_t)xlr_paddr_ld(paddr - XLR_CACHELINE_SIZE); + mag = xlr_paddr_ld(paddr - XLR_CACHELINE_SIZE + sizeof(uint64_t)); + xlr_restore_kx(sr); if (mag != 0xf00bad) { - printf("Something is wrong kseg:%lx found mag:%x not 0xf00bad\n", - (u_long)paddr, mag); + printf("Something is wrong kseg:%lx found mag:%lx not 0xf00bad\n", + (u_long)paddr, (u_long)mag); return; } if (m != NULL) @@ -2022,15 +1986,8 @@ static void rge_rx(struct rge_softc *sc, vm_paddr_t paddr, int len) { struct mbuf *m; - uint32_t mag; struct ifnet *ifp = sc->rge_ifp; -#ifdef __mips_n64 - uint64_t *vaddr; - - vaddr =(uint64_t *)MIPS_PHYS_TO_XKPHYS_CACHED(paddr - XLR_CACHELINE_SIZE); - m = (struct mbuf *)vaddr[0]; - mag = (uint32_t)vaddr[1]; -#else + uint64_t mag; uint32_t sr; /* * On 32 bit machines we use XKPHYS to get the values stores with @@ -2038,10 +1995,9 @@ rge_rx(struct rge_softc *sc, vm_paddr_t paddr, int len) * KX is enabled to prevent this setting leaking to other code. */ sr = xlr_enable_kx(); - m = (struct mbuf *)(intptr_t)xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE + sizeof(uint32_t)); - mag = xlr_paddr_lw(paddr - XLR_CACHELINE_SIZE + 3 * sizeof(uint32_t)); - mips_wr_status(sr); -#endif + m = (struct mbuf *)(intptr_t)xlr_paddr_ld(paddr - XLR_CACHELINE_SIZE); + mag = xlr_paddr_ld(paddr - XLR_CACHELINE_SIZE + sizeof(uint64_t)); + xlr_restore_kx(sr); if (mag != 0xf00bad) { /* somebody else packet Error - FIXME in intialization */ printf("cpu %d: *ERROR* Not my packet paddr %p\n", diff --git a/sys/mips/rmi/rmi_mips_exts.h b/sys/mips/rmi/rmi_mips_exts.h index 6f86ed257bf..a21f5e020f2 100644 --- a/sys/mips/rmi/rmi_mips_exts.h +++ b/sys/mips/rmi/rmi_mips_exts.h @@ -348,7 +348,7 @@ write_c0_eimr64(uint64_t val) write_c0_register64(9, 7, val); } -static __inline__ int +static __inline int xlr_test_and_set(int *lock) { int oldval = 0; @@ -367,10 +367,10 @@ xlr_test_and_set(int *lock) : "$8", "$9" ); - return (oldval == 0 ? 1 /* success */ : 0 /* failure */ ); + return (oldval == 0 ? 1 /* success */ : 0 /* failure */); } -static __inline__ uint32_t +static __inline uint32_t xlr_mfcr(uint32_t reg) { uint32_t val; @@ -385,7 +385,7 @@ xlr_mfcr(uint32_t reg) return val; } -static __inline__ void +static __inline void xlr_mtcr(uint32_t reg, uint32_t val) { __asm__ __volatile__( @@ -396,26 +396,47 @@ xlr_mtcr(uint32_t reg, uint32_t val) : "$8", "$9"); } +/* + * Atomic increment a unsigned int + */ +static __inline unsigned int +xlr_ldaddwu(unsigned int value, unsigned int *addr) +{ + __asm__ __volatile__( + ".set push\n" + ".set noreorder\n" + "move $8, %2\n" + "move $9, %3\n" + ".word 0x71280011\n" /* ldaddwu $8, $9 */ + "move %0, $8\n" + ".set pop\n" + : "=&r"(value), "+m"(*addr) + : "0"(value), "r" ((unsigned long)addr) + : "$8", "$9"); + + return (value); +} + #if defined(__mips_n64) -static __inline__ uint32_t -xlr_paddr_lw(uint64_t paddr) +static __inline uint64_t +xlr_paddr_ld(uint64_t paddr) { paddr |= 0x9800000000000000ULL; - return (*(uint32_t *)(uintptr_t)paddr); + return (*(uint64_t *)(uintptr_t)paddr); } #elif defined(__mips_n32) -static __inline__ uint32_t -xlr_paddr_lw(uint64_t paddr) +static __inline uint64_t +xlr_paddr_ld(uint64_t paddr) { - uint32_t val; + uint64_t val; paddr |= 0x9800000000000000ULL; __asm__ __volatile__( ".set push \n\t" ".set mips64 \n\t" - "lw %0, 0(%1) \n\t" + "ld %0, 0(%1) \n\t" ".set pop \n" : "=r"(val) : "r"(paddr)); @@ -423,27 +444,62 @@ xlr_paddr_lw(uint64_t paddr) return (val); } #else -static __inline__ uint32_t -xlr_paddr_lw(uint64_t paddr) +static __inline uint32_t +xlr_paddr_ld(uint64_t paddr) { - uint32_t high, low, tmp; + uint32_t addrh, addrl; + uint32_t valh, vall; - high = 0x98000000 | (paddr >> 32); - low = paddr & 0xffffffff; + addrh = 0x98000000 | (paddr >> 32); + addrl = paddr & 0xffffffff; __asm__ __volatile__( ".set push \n\t" ".set mips64 \n\t" - "dsll32 %1, %1, 0 \n\t" - "dsll32 %2, %2, 0 \n\t" /* get rid of the */ - "dsrl32 %2, %2, 0 \n\t" /* sign extend */ - "or %1, %1, %2 \n\t" - "lw %0, 0(%1) \n\t" + "dsll32 %2, %2, 0 \n\t" + "dsll32 %3, %3, 0 \n\t" /* get rid of the */ + "dsrl32 %3, %3, 0 \n\t" /* sign extend */ + "or %2, %2, %3 \n\t" + "lw %0, 0(%2) \n\t" + "lw %1, 4(%2) \n\t" ".set pop \n" - : "=r"(tmp) - : "r"(high), "r"(low)); + : "=&r"(valh), "=r"(vall) + : "r"(addrh), "r"(addrl)); - return tmp; + return (((uint64_t)valh << 32) | vall); +} +#endif + +/* + * XXX: Not really needed in n32 or n64, retain for now + */ +#if defined(__mips_n64) || defined(__mips_n32) +static __inline uint32_t +xlr_enable_kx(void) +{ + + return (0); +} + +static __inline void +xlr_restore_kx(uint32_t sr) +{ +} +#else +static __inline uint32_t +xlr_enable_kx(void) +{ + uint32_t sr = mips_rd_status(); + + mips_wr_status((sr & ~MIPS_SR_INT_IE) | MIPS_SR_KX); + return (sr); +} + +static __inline void +xlr_restore_kx(uint32_t sr) +{ + + mips_wr_status(sr); } #endif From f7181386986eb773fabf8d0e7f993281f0693915 Mon Sep 17 00:00:00 2001 From: "Jayachandran C." Date: Thu, 16 Sep 2010 19:25:24 +0000 Subject: [PATCH 0818/1624] Update rge.h for r212758 - stats incremented using xlr_ldaddwu should be unsigned int. --- sys/mips/rmi/dev/xlr/rge.h | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/sys/mips/rmi/dev/xlr/rge.h b/sys/mips/rmi/dev/xlr/rge.h index 98b5847c6d8..fa98a0d6076 100644 --- a/sys/mips/rmi/dev/xlr/rge.h +++ b/sys/mips/rmi/dev/xlr/rge.h @@ -26,6 +26,7 @@ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * + * $FreeBSD$ * RMI_BSD */ #ifndef _RMI_RGE_H_ #define _RMI_RGE_H_ @@ -972,12 +973,12 @@ enum { }; struct rge_softc_stats { - unsigned long rx_frames; - unsigned long tx_frames; - unsigned long rx_packets; - unsigned long rx_bytes; - unsigned long tx_packets; - unsigned long tx_bytes; + unsigned int rx_frames; + unsigned int tx_frames; + unsigned int rx_packets; + unsigned int rx_bytes; + unsigned int tx_packets; + unsigned int tx_bytes; }; struct driver_data { From 65742a25f73183e6d4476539ba18aff6480e73d4 Mon Sep 17 00:00:00 2001 From: Jung-uk Kim Date: Thu, 16 Sep 2010 19:43:32 +0000 Subject: [PATCH 0819/1624] Update acfreebsd.h for ACPI_THREAD_ID change. Note this patch was committed on upstream GIT: http://git.moblin.org/cgit.cgi/acpica/commit/?id=184ee2428cf02b0035d5de8a82c06fdfbc2ae14c --- include/platform/acfreebsd.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/include/platform/acfreebsd.h b/include/platform/acfreebsd.h index 6c087da084f..59694e3d573 100644 --- a/include/platform/acfreebsd.h +++ b/include/platform/acfreebsd.h @@ -165,6 +165,8 @@ #include #endif +#define ACPI_CAST_PTHREAD_T(pthread) ((ACPI_THREAD_ID) ACPI_TO_INTEGER (pthread)) + #define ACPI_USE_STANDARD_HEADERS #define ACPI_FLUSH_CPU_CACHE() From 01b36cb0890e53cab307672c59676e3f6ff01050 Mon Sep 17 00:00:00 2001 From: Jung-uk Kim Date: Thu, 16 Sep 2010 20:11:40 +0000 Subject: [PATCH 0820/1624] Remove an unnecessary hack from ACPICA 20100915 (r212761). --- sys/dev/acpi_support/acpi_wmi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/dev/acpi_support/acpi_wmi.c b/sys/dev/acpi_support/acpi_wmi.c index cf70ab09172..5b95cc926cb 100644 --- a/sys/dev/acpi_support/acpi_wmi.c +++ b/sys/dev/acpi_support/acpi_wmi.c @@ -202,7 +202,7 @@ static devclass_t acpi_wmi_devclass; DRIVER_MODULE(acpi_wmi, acpi, acpi_wmi_driver, acpi_wmi_devclass, 0, 0); MODULE_VERSION(acpi_wmi, 1); MODULE_DEPEND(acpi_wmi, acpi, 1, 1, 1); -static char *wmi_ids[] = {"PNP0C14", "PNP0c14", NULL}; +static char *wmi_ids[] = {"PNP0C14", NULL}; /* * Probe for the PNP0C14 ACPI node From bb15db8f16483d44560a313248bdcd095da28f71 Mon Sep 17 00:00:00 2001 From: "Jayachandran C." Date: Thu, 16 Sep 2010 20:23:22 +0000 Subject: [PATCH 0821/1624] RMI security accelerator driver update. - Compile fixes for 9.0, the previous version of this driver was for FreeBSD 6. - Add virtual address field in OperationDescriptor_t, we cannot use MIPS_PHYS_TO_KSEG0 on physical address. - Fixes for new message ring API - Remove unused sys/mips/rmi/dev/sec/stats.h - Whitespace fixes --- sys/mips/rmi/dev/sec/desc.h | 3 +- sys/mips/rmi/dev/sec/rmilib.c | 200 ++++----------- sys/mips/rmi/dev/sec/rmilib.h | 9 +- sys/mips/rmi/dev/sec/rmisec.c | 146 +++++------ sys/mips/rmi/dev/sec/stats.h | 469 ---------------------------------- sys/mips/rmi/iodi.c | 1 + 6 files changed, 117 insertions(+), 711 deletions(-) delete mode 100644 sys/mips/rmi/dev/sec/stats.h diff --git a/sys/mips/rmi/dev/sec/desc.h b/sys/mips/rmi/dev/sec/desc.h index 5757e13a765..1238d001060 100644 --- a/sys/mips/rmi/dev/sec/desc.h +++ b/sys/mips/rmi/dev/sec/desc.h @@ -26,6 +26,7 @@ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * + * $FreeBSD$ * RMI_BSD */ #ifndef _DESC_H_ #define _DESC_H_ @@ -2320,7 +2321,7 @@ typedef struct OperationDescriptor_s { uint32_t flags; uint32_t cpu; uint32_t seq_num; - uint64_t reserved; + uint64_t vaddr; } OperationDescriptor_t, *OperationDescriptor_pt; diff --git a/sys/mips/rmi/dev/sec/rmilib.c b/sys/mips/rmi/dev/sec/rmilib.c index 6068e5d2852..014bfc87280 100644 --- a/sys/mips/rmi/dev/sec/rmilib.c +++ b/sys/mips/rmi/dev/sec/rmilib.c @@ -41,7 +41,6 @@ __FBSDID("$FreeBSD$"); #include #include #include -#include #include #include @@ -49,20 +48,19 @@ __FBSDID("$FreeBSD$"); #include - -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include -// static int msgrng_stnid_pk0 = MSGRNG_STNID_PK0; +/* static int msgrng_stnid_pk0 = MSGRNG_STNID_PK0; */ -/*#define RMI_SEC_DEBUG */ +/* #define RMI_SEC_DEBUG */ #define SMP_CACHE_BYTES XLR_CACHELINE_SIZE #define NUM_CHUNKS(size, bits) ( ((size)>>(bits)) + (((size)&((1<<(bits))-1))?1:0) ) @@ -72,86 +70,44 @@ symkey_desc_pt g_desc; struct xlr_sec_command *g_cmd; #ifdef XLR_SEC_CMD_DEBUG -static void - decode_symkey_desc(symkey_desc_pt desc, uint32_t cfg_vector); - +static void decode_symkey_desc(symkey_desc_pt desc, uint32_t cfg_vector); #endif -void print_buf(char *desc, void *data, int len); +static int xlr_sec_cipher_hash_command(xlr_sec_io_pt op, symkey_desc_pt desc, + uint8_t); +static xlr_sec_error_t xlr_sec_setup_descriptor(xlr_sec_io_pt op, + unsigned int flags, symkey_desc_pt desc, uint32_t * cfg_vector); -static int - xlr_sec_cipher_hash_command(xlr_sec_io_pt op, symkey_desc_pt desc, uint8_t); - -static xlr_sec_error_t -xlr_sec_setup_descriptor(xlr_sec_io_pt op, - unsigned int flags, - symkey_desc_pt desc, - uint32_t * cfg_vector); - -static -xlr_sec_error_t -xlr_sec_setup_packet(xlr_sec_io_pt op, - symkey_desc_pt desc, - unsigned int flags, - uint64_t * data, - PacketDescriptor_pt pkt_desc, - ControlDescriptor_pt ctl_desc, - uint32_t vector, - PacketDescriptor_pt next_pkt_desc, +static xlr_sec_error_t xlr_sec_setup_packet(xlr_sec_io_pt op, + symkey_desc_pt desc, unsigned int flags, uint64_t * data, + PacketDescriptor_pt pkt_desc, ControlDescriptor_pt ctl_desc, + uint32_t vector, PacketDescriptor_pt next_pkt_desc, uint8_t multi_frag_flag); - -static int - xlr_sec_submit_message(symkey_desc_pt desc, uint32_t cfg_vector); - -static -xlr_sec_error_t -xlr_sec_setup_cipher(xlr_sec_io_pt op, - ControlDescriptor_pt ctl_desc, - uint32_t * vector); - -static -xlr_sec_error_t -xlr_sec_setup_digest(xlr_sec_io_pt op, - ControlDescriptor_pt ctl_desc, - uint32_t * vector); - -static -xlr_sec_error_t -xlr_sec_setup_cksum(xlr_sec_io_pt op, +static int xlr_sec_submit_message(symkey_desc_pt desc, uint32_t cfg_vector); +static xlr_sec_error_t xlr_sec_setup_cipher(xlr_sec_io_pt op, + ControlDescriptor_pt ctl_desc, uint32_t * vector); +static xlr_sec_error_t xlr_sec_setup_digest(xlr_sec_io_pt op, + ControlDescriptor_pt ctl_desc, uint32_t * vector); +static xlr_sec_error_t xlr_sec_setup_cksum(xlr_sec_io_pt op, ControlDescriptor_pt ctl_desc); +static xlr_sec_error_t xlr_sec_control_setup(xlr_sec_io_pt op, + unsigned int flags, uint64_t * control, ControlDescriptor_pt ctl_desc, + xlr_sec_drv_user_t * user, uint32_t vector); +static void xlr_sec_free_desc(symkey_desc_pt desc); -static -xlr_sec_error_t -xlr_sec_control_setup(xlr_sec_io_pt op, - unsigned int flags, - uint64_t * control, - ControlDescriptor_pt ctl_desc, - xlr_sec_drv_user_t * user, - uint32_t vector); - - -xlr_sec_error_t -xlr_sec_submit_op(symkey_desc_pt desc); - -static void xlr_sec_free_desc(symkey_desc_pt desc); - -void -xlr_sec_msgring_handler(int bucket, int size, int code, int stid, +void print_buf(char *desc, void *data, int len); +xlr_sec_error_t xlr_sec_submit_op(symkey_desc_pt desc); +void xlr_sec_msgring_handler(int bucket, int size, int code, int stid, struct msgrng_msg *msg, void *data); - void xlr_sec_init(struct xlr_sec_softc *sc) { unsigned int i; xlr_reg_t *mmio; - mmio = sc->mmio = xlr_io_mmio(XLR_IO_SECURITY_OFFSET); - xlr_write_reg(mmio, SEC_DMA_CREDIT, SEC_DMA_CREDIT_CONFIG); - - xlr_write_reg(mmio, SEC_CONFIG2, SEC_CFG2_ROUND_ROBIN_ON); for (i = 0; i < 8; i++) @@ -168,7 +124,6 @@ xlr_sec_init(struct xlr_sec_softc *sc) xls_cc_table_sec.counters[i >> 3][i & 0x07] : cc_table_sec.counters[i >> 3][i & 0x07]); - /* * Register a bucket handler with the phoenix messaging subsystem * For now, register handler for bucket 0->5 in msg stn 0 @@ -179,30 +134,23 @@ xlr_sec_init(struct xlr_sec_softc *sc) return; } - - int xlr_sec_setup(struct xlr_sec_session *ses, struct xlr_sec_command *cmd, - symkey_desc_pt desc -) + symkey_desc_pt desc) { xlr_sec_io_pt op; int size, ret_val; int iv_len; - desc->ses = ses; op = &cmd->op; if (op == NULL) return (-ENOMEM); - - desc->ctl_desc.instruction = 0; memset(&desc->ctl_desc.cipherHashInfo, 0, sizeof(CipherHashInfo_t)); desc->control = 0; - desc->pkt_desc[0].srcLengthIVOffUseIVNext = 0; desc->pkt_desc[0].dstDataSettings = 0; desc->pkt_desc[0].authDstNonceLow = 0; @@ -211,12 +159,10 @@ xlr_sec_setup(struct xlr_sec_session *ses, desc->pkt_desc[1].dstDataSettings = 0; desc->pkt_desc[1].authDstNonceLow = 0; desc->pkt_desc[1].ckSumDstNonceHiCFBMaskLLWMask = 0; - desc->data = 0; desc->ctl_result = 0; desc->data_result = 0; - if (op->flags & XLR_SEC_FLAGS_HIGH_PRIORITY) if (!xlr_is_xls()) desc->op_ctl.stn_id++; @@ -225,7 +171,6 @@ xlr_sec_setup(struct xlr_sec_session *ses, desc->user.user_dest = (uint8_t *) (unsigned long)op->dest_buf; desc->user.user_auth = (uint8_t *) (unsigned long)op->auth_dest; - if ((op->cipher_type == XLR_SEC_CIPHER_TYPE_ARC4) && (!op->rc4_state && (op->rc4_loadstate || op->rc4_savestate))) { printf(" ** Load/Save State and no State **"); @@ -234,7 +179,6 @@ xlr_sec_setup(struct xlr_sec_session *ses, } desc->user.user_state = (uint8_t *) (unsigned long)op->rc4_state; - switch (op->cipher_type) { case XLR_SEC_CIPHER_TYPE_NONE: iv_len = 0; @@ -260,10 +204,6 @@ xlr_sec_setup(struct xlr_sec_session *ses, xlr_sec_free_desc(desc); return (-EINVAL); } - - - - size = op->source_buf_size + iv_len; /* @@ -276,7 +216,8 @@ xlr_sec_setup(struct xlr_sec_session *ses, if (op->cipher_type == XLR_SEC_CIPHER_TYPE_NONE) { if (op->source_buf_size != 0) { - memcpy(desc->user.aligned_src, (uint8_t *) (unsigned long)op->source_buf, + memcpy(desc->user.aligned_src, + (uint8_t *)(uintptr_t)op->source_buf, op->source_buf_size); } } else { @@ -306,12 +247,9 @@ xlr_sec_setup(struct xlr_sec_session *ses, } } - - /* Set source to new kernel space */ op->source_buf = (uint64_t) (unsigned long)desc->user.aligned_src; - /* * Build new dest buffer, for Cipher output only */ @@ -324,7 +262,6 @@ xlr_sec_setup(struct xlr_sec_session *ses, } else { /* DEBUG -dpk */ XLR_SEC_CMD_DIAG("dest_buf_size = %d \n", op->dest_buf_size); - size = op->dest_buf_size + iv_len; /* @@ -335,11 +272,9 @@ xlr_sec_setup(struct xlr_sec_session *ses, op->cipher_mode == XLR_SEC_CIPHER_MODE_CTR) size += XLR_SEC_AES_BLOCK_SIZE - 1; op->dest_buf = (uint64_t) (unsigned long)desc->user.aligned_dest; - } ret_val = xlr_sec_cipher_hash_command(op, desc, ses->multi_frag_flag); - return (ret_val); } @@ -396,7 +331,6 @@ xlr_sec_cipher_hash_command(xlr_sec_io_pt op, symkey_desc_pt desc, return err; } - static xlr_sec_error_t xlr_sec_setup_descriptor(xlr_sec_io_pt op, unsigned int flags, @@ -407,7 +341,6 @@ xlr_sec_setup_descriptor(xlr_sec_io_pt op, XLR_SEC_CMD_DIAG("xlr_sec_setup_descriptor: ENTER\n"); - if ((err = xlr_sec_setup_cipher(op, &desc->ctl_desc, cfg_vector)) != XLR_SEC_ERR_NONE) { XLR_SEC_CMD_DIAG("xlr_sec_setup_descriptor: xlr_sec_setup_cipher done err %d\n", (int)err); @@ -483,7 +416,7 @@ xlr_sec_setup_packet(xlr_sec_io_pt op, len = op->source_buf_size + byte_offset - global_offset; if (multi_frag_flag) { - next_seg_addr = (uint64_t) vtophys((void *)(unsigned long)(desc->next_src_buf)); + next_seg_addr = (uint64_t)vtophys((void *)(uintptr_t)desc->next_src_buf); next_seg_addr = (next_seg_addr & ~(SMP_CACHE_BYTES - 1)); next_len = desc->next_src_len; } @@ -505,14 +438,12 @@ xlr_sec_setup_packet(xlr_sec_io_pt op, */ cipher_offset_dwords = (op->iv_offset + byte_offset) >> 3; - if (op->cipher_mode == XLR_SEC_CIPHER_MODE_F8 || op->cipher_mode == XLR_SEC_CIPHER_MODE_CTR) { if (multi_frag_flag) { int nlhmac = ((op->source_buf_size + global_offset + 7 - op->cipher_offset) >> 3) & 1; pkt_desc->srcLengthIVOffUseIVNext = - FIELD_VALUE(PKT_DSC_HASHBYTES, len & 7) | FIELD_VALUE(PKT_DSC_IVOFF, cipher_offset_dwords) | FIELD_VALUE(PKT_DSC_PKTLEN, nlhmac + ((len + 7) >> 3)) | @@ -539,7 +470,6 @@ xlr_sec_setup_packet(xlr_sec_io_pt op, } else { if (multi_frag_flag) { pkt_desc->srcLengthIVOffUseIVNext = - FIELD_VALUE(PKT_DSC_HASHBYTES, len & 7) | FIELD_VALUE(PKT_DSC_IVOFF, cipher_offset_dwords) | FIELD_VALUE(PKT_DSC_PKTLEN, (len + 7) >> 3) | @@ -890,7 +820,6 @@ xlr_sec_setup_packet(xlr_sec_io_pt op, CLEAR_SET_FIELD(next_pkt_desc->ckSumDstNonceHiCFBMaskLLWMask, PKT_DSC_CKSUM_DST_ADDR, (uint64_t) vtophys((void *)(unsigned long)desc->next_cksum_dest)); - } } /* @@ -902,17 +831,13 @@ xlr_sec_setup_packet(xlr_sec_io_pt op, XLR_SEC_CMD_DIAG(" xlr_sec_setup_packet(): pkt_desc=%p phys_pkt_desc=%llx \n", pkt_desc, (unsigned long long)vtophys(pkt_desc)); - - CLEAR_SET_FIELD(*data, MSG_CMD_DATA_ADDR, ((uint64_t) vtophys(pkt_desc))); CLEAR_SET_FIELD(*data, MSG_CMD_DATA_CTL, SEC_EOP); CLEAR_SET_FIELD(*data, MSG_CMD_DATA_LEN, MSG_CMD_DATA_LEN_LOAD); - XLR_SEC_CMD_DIAG("xlr_sec_setup_packet: DONE\n"); #ifdef RMI_SEC_DEBUG - { printf("data desc\n"); printf("srcLengthIVOffUseIVNext = 0x%llx\n", pkt_desc->srcLengthIVOffUseIVNext); @@ -1036,9 +961,7 @@ xlr_sec_submit_message(symkey_desc_pt desc, uint32_t cfg_vector) int ret_val = 0; XLR_SEC_CMD_DIAG("xlr_sec_submit_message: ENTER\n"); - err = XLR_SEC_ERR_NONE; - XLR_SEC_CMD_DIAG_SYM_DESC(desc, cfg_vector); do { @@ -1206,7 +1129,6 @@ xlr_sec_setup_cipher(xlr_sec_io_pt op, return XLR_SEC_ERR_NONE; } - static xlr_sec_error_t xlr_sec_setup_digest(xlr_sec_io_pt op, @@ -1304,7 +1226,6 @@ xlr_sec_setup_digest(xlr_sec_io_pt op, *vector |= digest_vector; XLR_SEC_CMD_DIAG("xlr_sec_setup_digest: EXIT vector = %04x\n", *vector); - return XLR_SEC_ERR_NONE; } @@ -1350,7 +1271,6 @@ xlr_sec_control_setup(xlr_sec_io_pt op, XLR_SEC_CMD_DIAG(" ENTER vector = %04x\n", vector); #endif - switch (vector) { case XLR_SEC_VECTOR_MAC: XLR_SEC_CMD_DIAG(" XLR_SEC_VECTOR_MAC \n"); @@ -1970,7 +1890,6 @@ xlr_sec_control_setup(xlr_sec_io_pt op, return XLR_SEC_ERR_NONE; } - xlr_sec_error_t xlr_sec_submit_op(symkey_desc_pt desc) { @@ -2013,31 +1932,18 @@ xlr_sec_submit_op(symkey_desc_pt desc) XLR_SEC_CMD_DIAG("[%s]: IN_IRQ=%d msg0=0x%llx msg1=0x%llx \n", __FUNCTION__, desc->op_ctl.flags, send_msg.msg0, send_msg.msg1); - - retries = 100; - while (retries--) { - msgrng_flags_save(msgrng_flags); - - code = message_send_retry(SEC_MSGRING_WORDSIZE, - MSGRNG_CODE_SEC, - desc->op_ctl.stn_id, - &send_msg); - - - msgrng_flags_restore(msgrng_flags); - + msgrng_flags = msgrng_access_enable(); + code = message_send(SEC_MSGRING_WORDSIZE, MSGRNG_CODE_SEC, + desc->op_ctl.stn_id, &send_msg); + msgrng_restore(msgrng_flags); if (code == 0) break; } - - return (XLR_SEC_ERR_NONE); } - - symkey_desc_pt xlr_sec_allocate_desc(void *session_ptr) { @@ -2090,7 +1996,6 @@ xlr_sec_allocate_desc(void *session_ptr) new->user.kern_auth = new->user.user_auth = NULL; new->user.aligned_auth = new->user.user_auth = NULL; - /* find cacheline alignment */ aligned = new; addr = (uint64_t) vtophys(new); @@ -2101,6 +2006,7 @@ xlr_sec_allocate_desc(void *session_ptr) /* setup common control info */ aligned->op_ctl.phys_self = addr; aligned->op_ctl.stn_id = MSGRNG_STNID_SEC0; + aligned->op_ctl.vaddr = (uintptr_t)aligned; return (aligned); } @@ -2114,8 +2020,6 @@ xlr_sec_free_desc(symkey_desc_pt desc) return; } contigfree(desc, sizeof(symkey_desc_t), M_DEVBUF); - - return; } @@ -2816,7 +2720,7 @@ decode_symkey_desc(symkey_desc_pt desc, uint32_t cfg_vector) break; } DPRINT("PACKET DESCRIPTOR: \n"); - word = desc->pkt_desc.srcLengthIVOffUseIVNext; + word = 0; //desc->pkt_desc.srcLengthIVOffUseIVNext; DPRINT("\tSrcLengthIVOffsetIVNext: %llx\n", word); DPRINT("\t\tLoad HMAC = %lld \n", GET_FIELD(word, PKT_DSC_LOADHMACKEY)); @@ -2841,7 +2745,7 @@ decode_symkey_desc(symkey_desc_pt desc, uint32_t cfg_vector) DPRINT("\t\tGlobal Src Offset = %lld \n", GET_FIELD(word, PKT_DSC_SEGOFFSET)); - word = desc->pkt_desc.dstDataSettings; + word = 0; //desc->pkt_desc.dstDataSettings; DPRINT("\tdstDataSettings: %llx \n", word); DPRINT("\t\tArc4 Byte Count = %lld \n", GET_FIELD(word, PKT_DSC_ARC4BYTECOUNT)); @@ -2859,7 +2763,7 @@ decode_symkey_desc(symkey_desc_pt desc, uint32_t cfg_vector) PKT_DSC_CPHR_DST_DWOFFSET)); DPRINT("\t\tCipher Dest Offset= %lld \n", GET_FIELD(word, PKT_DSC_CPHR_DST_OFFSET)); - word = desc->pkt_desc.authDstNonceLow; + word = 0; //desc->pkt_desc.authDstNonceLow; DPRINT("\tauthDstNonceLow: %llx \n", word); DPRINT("\t\tNonce Low 24 = %lld \n", GET_FIELD(word, PKT_DSC_NONCE_LOW)); @@ -2867,7 +2771,7 @@ decode_symkey_desc(symkey_desc_pt desc, uint32_t cfg_vector) PKT_DSC_AUTH_DST_ADDR)); DPRINT("\t\tCipher Offset High= %lld \n", GET_FIELD(word, PKT_DSC_CIPH_OFF_HI)); - word = desc->pkt_desc.ckSumDstNonceHiCFBMaskLLWMask; + word = 0; //desc->pkt_desc.ckSumDstNonceHiCFBMaskLLWMask; DPRINT("\tckSumDstNonceHiCFBMaskLLWMask: %llx \n", word); DPRINT("\t\tHash Byte off = %lld \n", GET_FIELD(word, PKT_DSC_HASH_BYTE_OFF)); DPRINT("\t\tPacket Len bytes = %lld \n", GET_FIELD(word, PKT_DSC_PKTLEN_BYTES)); @@ -2897,7 +2801,7 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, symkey_desc_pt desc = NULL; struct xlr_sec_session *ses = NULL; struct xlr_sec_command *cmd = NULL; - + uint32_t flags; if (code != MSGRNG_CODE_SEC) { panic("xlr_sec_msgring_handler: bad code = %d," @@ -2916,7 +2820,6 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, sec_eng = GET_FIELD(msg->msg0, MSG_CTL_OP_TYPE); sec_pipe = GET_FIELD(msg->msg1, MSG_CTL_OP_TYPE); - error = msg->msg0 >> 40 & 0x1ff; if (error) printf("ctrl error = 0x%llx\n", error); @@ -2938,12 +2841,11 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, * they are used for the engine and pipe Id. */ addr = GET_FIELD(msg->msg1, MSG_RSLT_DATA_DSC_ADDR); - addr = addr & ~((1 << 5) - 1); if (!addr) { panic("[%s:STNID_SEC]: NULL symkey addr!\n", __FUNCTION__); - } + /* * The adddress points to the data descriptor. The operation * descriptor is defined with the 32-byte cacheline size in @@ -2951,7 +2853,10 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, * reference the symkey descriptor. (ref: xlr_sec_desc.h) */ addr = addr - sizeof(OperationDescriptor_t); - desc = (symkey_desc_pt) MIPS_PHYS_TO_KSEG0(addr); + flags = xlr_enable_kx(); + desc = (symkey_desc_pt)(uintptr_t)xlr_paddr_ld(addr + + offsetof(OperationDescriptor_t, vaddr)); + xlr_restore_kx(flags); if (!desc) { printf("\nerror : not getting desc back correctly \n"); @@ -3099,10 +3004,8 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, } #endif - /* Copy cipher-data to User-space */ if (op->cipher_type != XLR_SEC_CIPHER_TYPE_NONE) { - size = op->dest_buf_size; /* DEBUG -dpk */ @@ -3119,14 +3022,12 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, crypto_copyback(cmd->crp->crp_flags, cmd->crp->crp_buf, 0, cmd->op.dest_buf_size, (caddr_t)(long)desc->user.aligned_dest + op->cipher_offset); crypto_done(cmd->crp); - } - } + /* Copy digest to User-space */ if (op->digest_type != XLR_SEC_DIGEST_TYPE_NONE) { - int offset = 0; switch (op->digest_type) { @@ -3163,7 +3064,6 @@ xlr_sec_msgring_handler(int bucket, int size, int code, int stid, } if (op->cipher_type == XLR_SEC_CIPHER_TYPE_ARC4 && op->rc4_savestate) { - size = XLR_SEC_MAX_RC4_STATE_SIZE; XLR_SEC_CMD_DIAG("state: to_addr=%p from_addr=%p size=%d \n", diff --git a/sys/mips/rmi/dev/sec/rmilib.h b/sys/mips/rmi/dev/sec/rmilib.h index 1f65c885c10..00106f9b944 100644 --- a/sys/mips/rmi/dev/sec/rmilib.h +++ b/sys/mips/rmi/dev/sec/rmilib.h @@ -25,7 +25,8 @@ * 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. - * + * + * $FreeBSD$ * RMI_BSD */ @@ -33,12 +34,10 @@ #define _RMILIB_H_ #include -__FBSDID("$FreeBSD$"); - #include -#include +#include -/*#define XLR_SEC_CMD_DEBUG*/ +/* #define XLR_SEC_CMD_DEBUG */ #ifdef XLR_SEC_CMD_DEBUG #define DPRINT printf diff --git a/sys/mips/rmi/dev/sec/rmisec.c b/sys/mips/rmi/dev/sec/rmisec.c index acced4ac130..5e00307c8e6 100644 --- a/sys/mips/rmi/dev/sec/rmisec.c +++ b/sys/mips/rmi/dev/sec/rmisec.c @@ -43,29 +43,27 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include +#include +#include +#include +#include +#include + +#include "cryptodev_if.h" #include #include -#include -#include -#include -#include - -#include -#include - #include -/*#define RMI_SEC_DEBUG */ - +/* #define RMI_SEC_DEBUG */ void xlr_sec_print_data(struct cryptop *crp); -static int xlr_sec_newsession(void *arg, uint32_t * sidp, struct cryptoini *cri); -static int xlr_sec_freesession(void *arg, uint64_t tid); -static int xlr_sec_process(void *arg, struct cryptop *crp, int hint); - +static int xlr_sec_newsession(device_t dev, uint32_t * sidp, struct cryptoini *cri); +static int xlr_sec_freesession(device_t dev, uint64_t tid); +static int xlr_sec_process(device_t dev, struct cryptop *crp, int hint); static int xlr_sec_probe(device_t); static int xlr_sec_attach(device_t); @@ -82,6 +80,11 @@ static device_method_t xlr_sec_methods[] = { DEVMETHOD(bus_print_child, bus_generic_print_child), DEVMETHOD(bus_driver_added, bus_generic_driver_added), + /* crypto device methods */ + DEVMETHOD(cryptodev_newsession, xlr_sec_newsession), + DEVMETHOD(cryptodev_freesession,xlr_sec_freesession), + DEVMETHOD(cryptodev_process, xlr_sec_process), + {0, 0} }; @@ -95,81 +98,63 @@ static devclass_t xlr_sec_devclass; DRIVER_MODULE(rmisec, iodi, xlr_sec_driver, xlr_sec_devclass, 0, 0); MODULE_DEPEND(rmisec, crypto, 1, 1, 1); - - static int xlr_sec_probe(device_t dev) { + + device_set_desc(dev, "XLR Security Accelerator"); return (BUS_PROBE_DEFAULT); - } - /* * Attach an interface that successfully probed. */ static int xlr_sec_attach(device_t dev) { - struct xlr_sec_softc *sc = device_get_softc(dev); - bzero(sc, sizeof(*sc)); sc->sc_dev = dev; - - - mtx_init(&sc->sc_mtx, device_get_nameunit(dev), "rmi crypto driver", MTX_DEF); - - sc->sc_cid = crypto_get_driverid(0); + mtx_init(&sc->sc_mtx, device_get_nameunit(dev), "rmi crypto driver", + MTX_DEF); + sc->sc_cid = crypto_get_driverid(dev, CRYPTOCAP_F_HARDWARE); if (sc->sc_cid < 0) { printf("xlr_sec - error : could not get the driver id\n"); goto error_exit; } - if (crypto_register(sc->sc_cid, CRYPTO_DES_CBC, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_DES_CBC, 0, 0) != 0) printf("register failed for CRYPTO_DES_CBC\n"); - if (crypto_register(sc->sc_cid, CRYPTO_3DES_CBC, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_3DES_CBC, 0, 0) != 0) printf("register failed for CRYPTO_3DES_CBC\n"); - if (crypto_register(sc->sc_cid, CRYPTO_AES_CBC, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, - xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_AES_CBC, 0, 0) != 0) printf("register failed for CRYPTO_AES_CBC\n"); - if (crypto_register(sc->sc_cid, CRYPTO_ARC4, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_ARC4, 0, 0) != 0) printf("register failed for CRYPTO_ARC4\n"); - - if (crypto_register(sc->sc_cid, CRYPTO_MD5, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_MD5, 0, 0) != 0) printf("register failed for CRYPTO_MD5\n"); - if (crypto_register(sc->sc_cid, CRYPTO_SHA1, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_SHA1, 0, 0) != 0) printf("register failed for CRYPTO_SHA1\n"); - if (crypto_register(sc->sc_cid, CRYPTO_MD5_HMAC, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_MD5_HMAC, 0, 0) != 0) printf("register failed for CRYPTO_MD5_HMAC\n"); - if (crypto_register(sc->sc_cid, CRYPTO_SHA1_HMAC, 0, 0, - xlr_sec_newsession, xlr_sec_freesession, xlr_sec_process, sc) != 0) + if (crypto_register(sc->sc_cid, CRYPTO_SHA1_HMAC, 0, 0) != 0) printf("register failed for CRYPTO_SHA1_HMAC\n"); - xlr_sec_init(sc); + device_printf(dev, "Initialization complete!\n"); return (0); - error_exit: return (ENXIO); } - /* * Detach an interface that successfully probed. */ @@ -194,39 +179,28 @@ xlr_sec_detach(device_t dev) return (0); } - - - /* * Allocate a new 'session' and return an encoded session id. 'sidp' * contains our registration id, and should contain an encoded session * id on successful allocation. */ static int -xlr_sec_newsession(void *arg, u_int32_t * sidp, struct cryptoini *cri) +xlr_sec_newsession(device_t dev, u_int32_t *sidp, struct cryptoini *cri) { struct cryptoini *c; - struct xlr_sec_softc *sc = arg; + struct xlr_sec_softc *sc = device_get_softc(dev); int mac = 0, cry = 0, sesn; struct xlr_sec_session *ses = NULL; - if (sidp == NULL || cri == NULL || sc == NULL) return (EINVAL); - if (sc->sc_sessions == NULL) { ses = sc->sc_sessions = (struct xlr_sec_session *)malloc( sizeof(struct xlr_sec_session), M_DEVBUF, M_NOWAIT); if (ses == NULL) return (ENOMEM); - - ses->desc_ptr = (void *)xlr_sec_allocate_desc((void *)ses); - if (ses->desc_ptr == NULL) - return (ENOMEM); - sesn = 0; - ses->sessionid = sesn; sc->sc_nsessions = 1; } else { for (sesn = 0; sesn < sc->sc_nsessions; sesn++) { @@ -242,23 +216,22 @@ xlr_sec_newsession(void *arg, u_int32_t * sidp, struct cryptoini *cri) sizeof(struct xlr_sec_session), M_DEVBUF, M_NOWAIT); if (ses == NULL) return (ENOMEM); - bcopy(sc->sc_sessions, ses, sesn * sizeof(struct xlr_sec_session)); - bzero(sc->sc_sessions, sesn * sizeof(struct xlr_sec_session)); + bcopy(sc->sc_sessions, ses, sesn * sizeof(*ses)); + bzero(sc->sc_sessions, sesn * sizeof(*ses)); free(sc->sc_sessions, M_DEVBUF); sc->sc_sessions = ses; ses = &sc->sc_sessions[sesn]; - ses->sessionid = sesn; - ses->desc_ptr = (void *)xlr_sec_allocate_desc((void *)ses); - if (ses->desc_ptr == NULL) - return (ENOMEM); sc->sc_nsessions++; } } + bzero(ses, sizeof(*ses)); + ses->sessionid = sesn; + ses->desc_ptr = xlr_sec_allocate_desc(ses); + if (ses->desc_ptr == NULL) + return (ENOMEM); ses->hs_used = 1; - for (c = cri; c != NULL; c = c->cri_next) { - switch (c->cri_alg) { case CRYPTO_MD5: case CRYPTO_SHA1: @@ -313,9 +286,9 @@ xlr_sec_newsession(void *arg, u_int32_t * sidp, struct cryptoini *cri) * XXX to blow away any keys already stored there. */ static int -xlr_sec_freesession(void *arg, u_int64_t tid) +xlr_sec_freesession(device_t dev, u_int64_t tid) { - struct xlr_sec_softc *sc = arg; + struct xlr_sec_softc *sc = device_get_softc(dev); int session; u_int32_t sid = CRYPTO_SESID2LID(tid); @@ -327,7 +300,6 @@ xlr_sec_freesession(void *arg, u_int64_t tid) return (EINVAL); sc->sc_sessions[session].hs_used = 0; - return (0); } @@ -375,11 +347,10 @@ xlr_sec_print_data(struct cryptop *crp) #endif - static int -xlr_sec_process(void *arg, struct cryptop *crp, int hint) +xlr_sec_process(device_t dev, struct cryptop *crp, int hint) { - struct xlr_sec_softc *sc = arg; + struct xlr_sec_softc *sc = device_get_softc(dev); struct xlr_sec_command *cmd = NULL; int session, err; struct cryptodesc *crd1, *crd2, *maccrd, *enccrd; @@ -466,7 +437,6 @@ xlr_sec_process(void *arg, struct cryptop *crp, int hint) cmd->op.num_packets = 1; cmd->op.num_fragments = 1; - if (cmd->op.source_buf_size > SEC_MAX_FRAG_LEN) { ses->multi_frag_flag = 1; } else { @@ -499,7 +469,6 @@ xlr_sec_process(void *arg, struct cryptop *crp, int hint) cmd->op.pkt_iv = XLR_SEC_PKT_IV_OLD; cmd->op.pkt_lastword = XLR_SEC_LASTWORD_128; - default: printf("currently not handled\n"); } @@ -524,8 +493,10 @@ xlr_sec_process(void *arg, struct cryptop *crp, int hint) memcpy(&cmd->op.crypt_key[0], enccrd->crd_key, XLR_SEC_DES_KEY_LENGTH); } else { cmd->op.cipher_type = XLR_SEC_CIPHER_TYPE_3DES; - //if (enccrd->crd_flags & CRD_F_KEY_EXPLICIT) { - memcpy(&cmd->op.crypt_key[0], enccrd->crd_key, XLR_SEC_3DES_KEY_LENGTH); + //if (enccrd->crd_flags & CRD_F_KEY_EXPLICIT) + { + memcpy(&cmd->op.crypt_key[0], enccrd->crd_key, + XLR_SEC_3DES_KEY_LENGTH); } } @@ -550,16 +521,19 @@ xlr_sec_process(void *arg, struct cryptop *crp, int hint) cmd->op.pkt_lastword = XLR_SEC_LASTWORD_128; //if ((!(enccrd->crd_flags & CRD_F_IV_PRESENT)) && - if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT)) { - memcpy(&cmd->op.initial_vector[0], enccrd->crd_iv, XLR_SEC_DES_IV_LENGTH); - } + if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT)) { + memcpy(&cmd->op.initial_vector[0], enccrd->crd_iv, + XLR_SEC_DES_IV_LENGTH); + } break; case CRYPTO_AES_CBC: if (enccrd->crd_alg == CRYPTO_AES_CBC) { cmd->op.cipher_type = XLR_SEC_CIPHER_TYPE_AES128; - //if (enccrd->crd_flags & CRD_F_KEY_EXPLICIT) { - memcpy(&cmd->op.crypt_key[0], enccrd->crd_key, XLR_SEC_AES128_KEY_LENGTH); + //if (enccrd->crd_flags & CRD_F_KEY_EXPLICIT) + { + memcpy(&cmd->op.crypt_key[0], enccrd->crd_key, + XLR_SEC_AES128_KEY_LENGTH); } } cmd->op.cipher_mode = XLR_SEC_CIPHER_MODE_CBC; @@ -583,11 +557,11 @@ xlr_sec_process(void *arg, struct cryptop *crp, int hint) cmd->op.pkt_lastword = XLR_SEC_LASTWORD_128; //if (!(enccrd->crd_flags & CRD_F_IV_PRESENT)) { - if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT)) { - memcpy(&cmd->op.initial_vector[0], enccrd->crd_iv, XLR_SEC_AES_BLOCK_SIZE); - } - // + if ((enccrd->crd_flags & CRD_F_IV_EXPLICIT)) { + memcpy(&cmd->op.initial_vector[0], enccrd->crd_iv, + XLR_SEC_AES_BLOCK_SIZE); } + //} break; } } diff --git a/sys/mips/rmi/dev/sec/stats.h b/sys/mips/rmi/dev/sec/stats.h deleted file mode 100644 index 276f7e9b999..00000000000 --- a/sys/mips/rmi/dev/sec/stats.h +++ /dev/null @@ -1,469 +0,0 @@ -/*- - * Copyright (c) 2003-2009 RMI Corporation - * 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. Neither the name of RMI Corporation, 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 AUTHOR 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 AUTHOR 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. - * - * RMI_BSD */ - -#ifndef _STATS_H_ -#define _STATS_H_ - -typedef struct hmac_stats -{ - unsigned long md5_count; - unsigned long long md5_bytes; - unsigned long sha1_count; - unsigned long long sha1_bytes; - unsigned long sha256_count; - unsigned long long sha256_bytes; - unsigned long sha384_count; - unsigned long long sha384_bytes; - unsigned long sha512_count; - unsigned long long sha512_bytes; - unsigned long gcm_count; - unsigned long long gcm_bytes; - unsigned long kasumi_f9_count; - unsigned long long kasumi_f9_bytes; - unsigned long reverts; - unsigned long long reverts_bytes; -} hmac_stats_t, *hmac_stats_pt; - -typedef struct cipher_stats -{ - unsigned long des_encrypts; - unsigned long long des_encrypt_bytes; - unsigned long des_decrypts; - unsigned long long des_decrypt_bytes; - unsigned long des3_encrypts; - unsigned long long des3_encrypt_bytes; - unsigned long des3_decrypts; - unsigned long long des3_decrypt_bytes; - unsigned long aes_encrypts; - unsigned long long aes_encrypt_bytes; - unsigned long aes_decrypts; - unsigned long long aes_decrypt_bytes; - unsigned long arc4_encrypts; - unsigned long long arc4_encrypt_bytes; - unsigned long arc4_decrypts; - unsigned long long arc4_decrypt_bytes; - unsigned long kasumi_f8_encrypts; - unsigned long long kasumi_f8_encrypt_bytes; - unsigned long kasumi_f8_decrypts; - unsigned long long kasumi_f8_decrypt_bytes; - unsigned long reverts; - unsigned long long reverts_bytes; -} cipher_stats_t, *cipher_stats_pt; - - -typedef struct modexp_stats -{ - unsigned long modexp_512s; - unsigned long modexp_1024s; -} modexp_stats_t, *modexp_stats_pt; - -typedef struct ecc_stats -{ - unsigned long ecc_mul; - unsigned long ecc_add; - unsigned long ecc_dbl; - unsigned long ecc_vfy; - unsigned long ecc_bin_mul; - unsigned long ecc_field_bin_inv; - unsigned long ecc_field_bin_mul; - unsigned long ecc_field_bin_add; - unsigned long ecc_field_add; - unsigned long ecc_field_sub; - unsigned long ecc_field_mul; - unsigned long ecc_field_inv; - unsigned long ecc_field_div; - unsigned long ecc_field_red; -} ecc_stats_t, *ecc_stats_pt; - - -typedef struct opt_stats -{ - unsigned long combined; - unsigned long unaligned_auth_dest; - unsigned long sym_failed; - unsigned long modexp_failed; - unsigned long ecc_failed; -} opt_stats_t, *opt_stats_pt; - -typedef struct rmisec_stats -{ - uint32_t sent; - uint32_t received; - uint32_t stats_mask; - uint32_t control_mask; - rwlock_t rmisec_control_lock; - rwlock_t rmisec_stats_lock; - char clear_start[0]; - uint64_t wait_time; - uint32_t max_wait_time; - uint32_t maxsnd_wait_time; - uint32_t wait_count; - hmac_stats_t hmac; - cipher_stats_t cipher; - modexp_stats_t modexp; - ecc_stats_t ecc; - opt_stats_t opt; -} rmisec_stats_t, *rmisec_stats_pt; - - -/* stats routines */ - -static void inline phxdrv_record_sent(rmisec_stats_pt stats) -{ - write_lock(&stats->rmisec_stats_lock); - stats->sent++; - write_unlock(&stats->rmisec_stats_lock); -} - -static void inline phxdrv_record_received(rmisec_stats_pt stats) -{ - write_lock(&stats->rmisec_stats_lock); - stats->received++; - write_unlock(&stats->rmisec_stats_lock); -} - - -static void inline phxdrv_record_des(rmisec_stats_pt stats, int enc, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_DES) { - write_lock(&stats->rmisec_stats_lock); - if (enc) { - stats->cipher.des_encrypts++; - stats->cipher.des_encrypt_bytes += nbytes; - } - else { - stats->cipher.des_decrypts++; - stats->cipher.des_decrypt_bytes += nbytes; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_3des(rmisec_stats_pt stats, int enc, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_3DES) { - write_lock(&stats->rmisec_stats_lock); - if (enc) { - stats->cipher.des3_encrypts++; - stats->cipher.des3_encrypt_bytes += nbytes; - } - else { - stats->cipher.des3_decrypts++; - stats->cipher.des3_decrypt_bytes += nbytes; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_aes(rmisec_stats_pt stats, int enc, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_AES) { - write_lock(&stats->rmisec_stats_lock); - if (enc) { - stats->cipher.aes_encrypts++; - stats->cipher.aes_encrypt_bytes += nbytes; - } - else { - stats->cipher.aes_decrypts++; - stats->cipher.aes_decrypt_bytes += nbytes; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_arc4(rmisec_stats_pt stats, int enc, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_ARC4) { - write_lock(&stats->rmisec_stats_lock); - if (enc) { - stats->cipher.arc4_encrypts++; - stats->cipher.arc4_encrypt_bytes += nbytes; - } - else { - stats->cipher.arc4_decrypts++; - stats->cipher.arc4_decrypt_bytes += nbytes; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_kasumi_f8(rmisec_stats_pt stats, int enc, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_KASUMI_F8) { - write_lock(&stats->rmisec_stats_lock); - if (enc) { - stats->cipher.kasumi_f8_encrypts++; - stats->cipher.kasumi_f8_encrypt_bytes += nbytes; - } - else { - stats->cipher.kasumi_f8_decrypts++; - stats->cipher.kasumi_f8_decrypt_bytes += nbytes; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_modexp(rmisec_stats_pt stats, - int blksize) -{ - if (stats->stats_mask & PHXDRV_PROFILE_MODEXP) { - write_lock(&stats->rmisec_stats_lock); - if (blksize == 512) { - stats->modexp.modexp_512s++; - } - if (blksize == 1024) { - stats->modexp.modexp_1024s++; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_ecc(rmisec_stats_pt stats, PHX_ECC_OP op) -{ - if (stats->stats_mask & PHXDRV_PROFILE_ECC) { - write_lock(&stats->rmisec_stats_lock); - switch (op) { - case PHX_ECC_NOP: - break; - case PHX_ECC_MUL: - stats->ecc.ecc_mul++; - break; - case PHX_ECC_BIN_MUL: - stats->ecc.ecc_bin_mul++; - break; - case PHX_ECC_ADD: - stats->ecc.ecc_add++; - break; - case PHX_ECC_DBL: - stats->ecc.ecc_dbl++; - break; - case PHX_ECC_VFY: - stats->ecc.ecc_vfy++; - break; - case PHX_ECC_FIELD_BIN_INV: - stats->ecc.ecc_field_bin_inv++; - break; - case PHX_ECC_FIELD_BIN_MUL: - stats->ecc.ecc_field_bin_mul++; - break; - case PHX_ECC_FIELD_BIN_ADD: - stats->ecc.ecc_field_bin_add++; - break; - case PHX_ECC_FIELD_ADD: - stats->ecc.ecc_field_add++; - break; - case PHX_ECC_FIELD_SUB: - stats->ecc.ecc_field_sub++; - break; - case PHX_ECC_FIELD_MUL: - stats->ecc.ecc_field_mul++; - break; - case PHX_ECC_FIELD_INV: - stats->ecc.ecc_field_inv++; - break; - case PHX_ECC_FIELD_DIV: - stats->ecc.ecc_field_div++; - break; - case PHX_ECC_FIELD_RED: - stats->ecc.ecc_field_red++; - break; - case PHX_ECC_FIELD: - case PHX_ECC_BIN: - break; - } - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_cipher_revert(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_CPHR_REVERTS) { - write_lock(&stats->rmisec_stats_lock); - stats->cipher.reverts++; - stats->cipher.reverts_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_hmac_revert(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_HMAC_REVERTS) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.reverts++; - stats->hmac.reverts_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_md5(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_MD5) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.md5_count++; - stats->hmac.md5_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_sha1(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_SHA1) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.sha1_count++; - stats->hmac.sha1_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_sha256(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_SHA256) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.sha256_count++; - stats->hmac.sha256_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_sha384(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_SHA384) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.sha384_count++; - stats->hmac.sha384_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_sha512(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_SHA512) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.sha512_count++; - stats->hmac.sha512_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_gcm(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_GCM) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.gcm_count++; - stats->hmac.gcm_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_kasumi_f9(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_KASUMI_F9) { - write_lock(&stats->rmisec_stats_lock); - stats->hmac.kasumi_f9_count++; - stats->hmac.kasumi_f9_bytes += nbytes; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_unaligned_auth_dest(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_UNALIGNED_AUTH_DEST) { - write_lock(&stats->rmisec_stats_lock); - stats->opt.unaligned_auth_dest++; - write_unlock(&stats->rmisec_stats_lock); - } -} - - -static void inline phxdrv_record_combined(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_COMBINED) { - write_lock(&stats->rmisec_stats_lock); - stats->opt.combined++; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_sym_failed(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_COMBINED) { - write_lock(&stats->rmisec_stats_lock); - stats->opt.sym_failed++; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_modexp_failed(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_COMBINED) { - write_lock(&stats->rmisec_stats_lock); - stats->opt.modexp_failed++; - write_unlock(&stats->rmisec_stats_lock); - } -} - -static void inline phxdrv_record_ecc_failed(rmisec_stats_pt stats, - int nbytes) -{ - if (stats->stats_mask & PHXDRV_PROFILE_COMBINED) { - write_lock(&stats->rmisec_stats_lock); - stats->opt.ecc_failed++; - write_unlock(&stats->rmisec_stats_lock); - } -} - -#endif diff --git a/sys/mips/rmi/iodi.c b/sys/mips/rmi/iodi.c index 31cc6e7be3b..60b7915d1bc 100644 --- a/sys/mips/rmi/iodi.c +++ b/sys/mips/rmi/iodi.c @@ -213,6 +213,7 @@ iodi_attach(device_t dev) device_add_child(dev, "uart", 0); device_add_child(dev, "xlr_i2c", 0); device_add_child(dev, "pcib", 0); + device_add_child(dev, "rmisec", -1); if (xlr_board_info.usb) device_add_child(dev, "ehci", 0); From 9ed03f0231513446c0987e780331f8070c3ecdc3 Mon Sep 17 00:00:00 2001 From: Xin LI Date: Thu, 16 Sep 2010 21:06:23 +0000 Subject: [PATCH 0822/1624] status bits should be &'ed against status to be really functional. Reported by: Jike Song Reviewed by: yongari MFC after: 1 week --- sys/dev/alc/if_alc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sys/dev/alc/if_alc.c b/sys/dev/alc/if_alc.c index 8830b0557e4..53bcb097d67 100644 --- a/sys/dev/alc/if_alc.c +++ b/sys/dev/alc/if_alc.c @@ -2948,8 +2948,8 @@ alc_rxeof(struct alc_softc *sc, struct rx_rdesc *rrd) * errored frames. */ status |= RRD_TCP_UDPCSUM_NOK | RRD_IPCSUM_NOK; - if ((RRD_ERR_CRC | RRD_ERR_ALIGN | RRD_ERR_TRUNC | - RRD_ERR_RUNT) != 0) + if ((status & (RRD_ERR_CRC | RRD_ERR_ALIGN | + RRD_ERR_TRUNC | RRD_ERR_RUNT)) != 0) return; } From 1c18314d17c6ce5596c814db1ca20c9b55f0df62 Mon Sep 17 00:00:00 2001 From: Andre Oppermann Date: Thu, 16 Sep 2010 21:06:45 +0000 Subject: [PATCH 0823/1624] Remove the TCP inflight bandwidth limiter as announced in r211315 to give way for the pluggable congestion control framework. It is the task of the congestion control algorithm to set the congestion window and amount of inflight data without external interference. In 'struct tcpcb' the variables previously used by the inflight limiter are renamed to spares to keep the ABI intact and to have some more space for future extensions. In 'struct tcp_info' the variable 'tcpi_snd_bwnd' is not removed to preserve the ABI. It is always set to 0. In siftr.c in 'struct pkt_node' the variable 'snd_bwnd' is not removed to preserve the ABI. It is always set to 0. These unused variable in the various structures may be reused in the future or garbage collected before the next release or at some other point when an ABI change happens anyway for other reasons. No MFC is planned. The inflight bandwidth limiter stays disabled by default in the other branches but remains available. --- sys/netinet/siftr.c | 4 +- sys/netinet/tcp.h | 2 +- sys/netinet/tcp_input.c | 4 - sys/netinet/tcp_output.c | 1 - sys/netinet/tcp_subr.c | 206 --------------------------------------- sys/netinet/tcp_timer.h | 3 - sys/netinet/tcp_usrreq.c | 22 ++--- sys/netinet/tcp_var.h | 9 +- 8 files changed, 16 insertions(+), 235 deletions(-) diff --git a/sys/netinet/siftr.c b/sys/netinet/siftr.c index 34f363636cc..6097ad48a75 100644 --- a/sys/netinet/siftr.c +++ b/sys/netinet/siftr.c @@ -193,7 +193,7 @@ struct pkt_node { u_long snd_wnd; /* Receive Window (bytes). */ u_long rcv_wnd; - /* Bandwidth Controlled Window (bytes). */ + /* Unused (was: Bandwidth Controlled Window (bytes)). */ u_long snd_bwnd; /* Slow Start Threshold (bytes). */ u_long snd_ssthresh; @@ -775,7 +775,7 @@ siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp, pn->snd_cwnd = tp->snd_cwnd; pn->snd_wnd = tp->snd_wnd; pn->rcv_wnd = tp->rcv_wnd; - pn->snd_bwnd = tp->snd_bwnd; + pn->snd_bwnd = 0; /* Unused, kept for compat. */ pn->snd_ssthresh = tp->snd_ssthresh; pn->snd_scale = tp->snd_scale; pn->rcv_scale = tp->rcv_scale; diff --git a/sys/netinet/tcp.h b/sys/netinet/tcp.h index 27d45aac2f5..62a89f7adda 100644 --- a/sys/netinet/tcp.h +++ b/sys/netinet/tcp.h @@ -221,7 +221,7 @@ struct tcp_info { /* FreeBSD extensions to tcp_info. */ u_int32_t tcpi_snd_wnd; /* Advertised send window. */ - u_int32_t tcpi_snd_bwnd; /* Bandwidth send window. */ + u_int32_t tcpi_snd_bwnd; /* No longer used. */ u_int32_t tcpi_snd_nxt; /* Next egress seqno */ u_int32_t tcpi_rcv_nxt; /* Next ingress seqno */ u_int32_t tcpi_toe_tid; /* HWTID for TOE endpoints */ diff --git a/sys/netinet/tcp_input.c b/sys/netinet/tcp_input.c index e4bddb90525..22a2ea4a89c 100644 --- a/sys/netinet/tcp_input.c +++ b/sys/netinet/tcp_input.c @@ -1321,7 +1321,6 @@ tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so, tcp_xmit_timer(tp, ticks - tp->t_rtttime); } - tcp_xmit_bandwidth_limit(tp, th->th_ack); acked = th->th_ack - tp->snd_una; TCPSTAT_INC(tcps_rcvackpack); TCPSTAT_ADD(tcps_rcvackbyte, acked); @@ -2278,7 +2277,6 @@ process_ACK: tp->t_rttlow = ticks - tp->t_rtttime; tcp_xmit_timer(tp, ticks - tp->t_rtttime); } - tcp_xmit_bandwidth_limit(tp, th->th_ack); /* * If all outstanding data is acked, stop retransmit @@ -3328,8 +3326,6 @@ tcp_mss(struct tcpcb *tp, int offer) tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh); TCPSTAT_INC(tcps_usedssthresh); } - if (metrics.rmx_bandwidth) - tp->snd_bandwidth = metrics.rmx_bandwidth; /* * Set the slow-start flight size depending on whether this diff --git a/sys/netinet/tcp_output.c b/sys/netinet/tcp_output.c index 50d0ee6a4cd..94b48fc474a 100644 --- a/sys/netinet/tcp_output.c +++ b/sys/netinet/tcp_output.c @@ -225,7 +225,6 @@ again: tso = 0; off = tp->snd_nxt - tp->snd_una; sendwin = min(tp->snd_wnd, tp->snd_cwnd); - sendwin = min(sendwin, tp->snd_bwnd); flags = tcp_outflags[tp->t_state]; /* diff --git a/sys/netinet/tcp_subr.c b/sys/netinet/tcp_subr.c index b537fb94958..d19a91a1698 100644 --- a/sys/netinet/tcp_subr.c +++ b/sys/netinet/tcp_subr.c @@ -160,14 +160,6 @@ SYSCTL_VNET_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, "Default TCP Maximum Segment Size for IPv6"); #endif -static int -vnet_sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS) -{ - - VNET_SYSCTL_ARG(req, arg1); - return (sysctl_msec_to_ticks(oidp, arg1, arg2, req)); -} - /* * Minimum MSS we accept and use. This prevents DoS attacks where * we are forced to a ridiculous low MSS like 20 and send hundreds @@ -213,50 +205,6 @@ SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW, &VNET_NAME(tcp_isn_reseed_interval), 0, "Seconds between reseeding of ISN secret"); -/* - * TCP bandwidth limiting sysctls. Note that the default lower bound of - * 1024 exists only for debugging. A good production default would be - * something like 6100. - */ -SYSCTL_NODE(_net_inet_tcp, OID_AUTO, inflight, CTLFLAG_RW, 0, - "TCP inflight data limiting"); - -static VNET_DEFINE(int, tcp_inflight_enable) = 0; -#define V_tcp_inflight_enable VNET(tcp_inflight_enable) -SYSCTL_VNET_INT(_net_inet_tcp_inflight, OID_AUTO, enable, CTLFLAG_RW, - &VNET_NAME(tcp_inflight_enable), 0, - "Enable automatic TCP inflight data limiting"); - -static int tcp_inflight_debug = 0; -SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, debug, CTLFLAG_RW, - &tcp_inflight_debug, 0, - "Debug TCP inflight calculations"); - -static VNET_DEFINE(int, tcp_inflight_rttthresh); -#define V_tcp_inflight_rttthresh VNET(tcp_inflight_rttthresh) -SYSCTL_VNET_PROC(_net_inet_tcp_inflight, OID_AUTO, rttthresh, - CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(tcp_inflight_rttthresh), 0, - vnet_sysctl_msec_to_ticks, "I", - "RTT threshold below which inflight will deactivate itself"); - -static VNET_DEFINE(int, tcp_inflight_min) = 6144; -#define V_tcp_inflight_min VNET(tcp_inflight_min) -SYSCTL_VNET_INT(_net_inet_tcp_inflight, OID_AUTO, min, CTLFLAG_RW, - &VNET_NAME(tcp_inflight_min), 0, - "Lower-bound for TCP inflight window"); - -static VNET_DEFINE(int, tcp_inflight_max) = TCP_MAXWIN << TCP_MAX_WINSHIFT; -#define V_tcp_inflight_max VNET(tcp_inflight_max) -SYSCTL_VNET_INT(_net_inet_tcp_inflight, OID_AUTO, max, CTLFLAG_RW, - &VNET_NAME(tcp_inflight_max), 0, - "Upper-bound for TCP inflight window"); - -static VNET_DEFINE(int, tcp_inflight_stab) = 20; -#define V_tcp_inflight_stab VNET(tcp_inflight_stab) -SYSCTL_VNET_INT(_net_inet_tcp_inflight, OID_AUTO, stab, CTLFLAG_RW, - &VNET_NAME(tcp_inflight_stab), 0, - "Inflight Algorithm Stabilization 20 = 2 packets"); - #ifdef TCP_SORECEIVE_STREAM static int tcp_soreceive_stream = 0; SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN, @@ -338,8 +286,6 @@ tcp_init(void) in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize, "tcp_inpcb", tcp_inpcb_init, NULL, UMA_ZONE_NOFREE); - V_tcp_inflight_rttthresh = TCPTV_INFLIGHT_RTTTHRESH; - /* * These have to be type stable for the benefit of the timers. */ @@ -728,10 +674,8 @@ tcp_newtcpcb(struct inpcb *inp) tp->t_rttmin = tcp_rexmit_min; tp->t_rxtcur = TCPTV_RTOBASE; tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; - tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; tp->t_rcvtime = ticks; - tp->t_bw_rtttime = ticks; /* * IPv4 TTL initialization is necessary for an IPv6 socket as well, * because the socket may be bound to an IPv6 wildcard address, @@ -849,8 +793,6 @@ tcp_discardcb(struct tcpcb *tp) metrics.rmx_rtt = tp->t_srtt; metrics.rmx_rttvar = tp->t_rttvar; - /* XXX: This wraps if the pipe is more than 4 Gbit per second */ - metrics.rmx_bandwidth = tp->snd_bandwidth; metrics.rmx_cwnd = tp->snd_cwnd; metrics.rmx_sendpipe = 0; metrics.rmx_recvpipe = 0; @@ -1773,154 +1715,6 @@ ipsec_hdrsiz_tcp(struct tcpcb *tp) } #endif /* IPSEC */ -/* - * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING - * - * This code attempts to calculate the bandwidth-delay product as a - * means of determining the optimal window size to maximize bandwidth, - * minimize RTT, and avoid the over-allocation of buffers on interfaces and - * routers. This code also does a fairly good job keeping RTTs in check - * across slow links like modems. We implement an algorithm which is very - * similar (but not meant to be) TCP/Vegas. The code operates on the - * transmitter side of a TCP connection and so only effects the transmit - * side of the connection. - * - * BACKGROUND: TCP makes no provision for the management of buffer space - * at the end points or at the intermediate routers and switches. A TCP - * stream, whether using NewReno or not, will eventually buffer as - * many packets as it is able and the only reason this typically works is - * due to the fairly small default buffers made available for a connection - * (typicaly 16K or 32K). As machines use larger windows and/or window - * scaling it is now fairly easy for even a single TCP connection to blow-out - * all available buffer space not only on the local interface, but on - * intermediate routers and switches as well. NewReno makes a misguided - * attempt to 'solve' this problem by waiting for an actual failure to occur, - * then backing off, then steadily increasing the window again until another - * failure occurs, ad-infinitum. This results in terrible oscillation that - * is only made worse as network loads increase and the idea of intentionally - * blowing out network buffers is, frankly, a terrible way to manage network - * resources. - * - * It is far better to limit the transmit window prior to the failure - * condition being achieved. There are two general ways to do this: First - * you can 'scan' through different transmit window sizes and locate the - * point where the RTT stops increasing, indicating that you have filled the - * pipe, then scan backwards until you note that RTT stops decreasing, then - * repeat ad-infinitum. This method works in principle but has severe - * implementation issues due to RTT variances, timer granularity, and - * instability in the algorithm which can lead to many false positives and - * create oscillations as well as interact badly with other TCP streams - * implementing the same algorithm. - * - * The second method is to limit the window to the bandwidth delay product - * of the link. This is the method we implement. RTT variances and our - * own manipulation of the congestion window, bwnd, can potentially - * destabilize the algorithm. For this reason we have to stabilize the - * elements used to calculate the window. We do this by using the minimum - * observed RTT, the long term average of the observed bandwidth, and - * by adding two segments worth of slop. It isn't perfect but it is able - * to react to changing conditions and gives us a very stable basis on - * which to extend the algorithm. - */ -void -tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq) -{ - u_long bw; - u_long bwnd; - int save_ticks; - - INP_WLOCK_ASSERT(tp->t_inpcb); - - /* - * If inflight_enable is disabled in the middle of a tcp connection, - * make sure snd_bwnd is effectively disabled. - */ - if (V_tcp_inflight_enable == 0 || - tp->t_rttlow < V_tcp_inflight_rttthresh) { - tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; - tp->snd_bandwidth = 0; - return; - } - - /* - * Figure out the bandwidth. Due to the tick granularity this - * is a very rough number and it MUST be averaged over a fairly - * long period of time. XXX we need to take into account a link - * that is not using all available bandwidth, but for now our - * slop will ramp us up if this case occurs and the bandwidth later - * increases. - * - * Note: if ticks rollover 'bw' may wind up negative. We must - * effectively reset t_bw_rtttime for this case. - */ - save_ticks = ticks; - if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1) - return; - - bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz / - (save_ticks - tp->t_bw_rtttime); - tp->t_bw_rtttime = save_ticks; - tp->t_bw_rtseq = ack_seq; - if (tp->t_bw_rtttime == 0 || (int)bw < 0) - return; - bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4; - - tp->snd_bandwidth = bw; - - /* - * Calculate the semi-static bandwidth delay product, plus two maximal - * segments. The additional slop puts us squarely in the sweet - * spot and also handles the bandwidth run-up case and stabilization. - * Without the slop we could be locking ourselves into a lower - * bandwidth. - * - * Situations Handled: - * (1) Prevents over-queueing of packets on LANs, especially on - * high speed LANs, allowing larger TCP buffers to be - * specified, and also does a good job preventing - * over-queueing of packets over choke points like modems - * (at least for the transmit side). - * - * (2) Is able to handle changing network loads (bandwidth - * drops so bwnd drops, bandwidth increases so bwnd - * increases). - * - * (3) Theoretically should stabilize in the face of multiple - * connections implementing the same algorithm (this may need - * a little work). - * - * (4) Stability value (defaults to 20 = 2 maximal packets) can - * be adjusted with a sysctl but typically only needs to be - * on very slow connections. A value no smaller then 5 - * should be used, but only reduce this default if you have - * no other choice. - */ -#define USERTT ((tp->t_srtt + tp->t_rttbest) / 2) - bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + V_tcp_inflight_stab * tp->t_maxseg / 10; -#undef USERTT - - if (tcp_inflight_debug > 0) { - static int ltime; - if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) { - ltime = ticks; - printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n", - tp, - bw, - tp->t_rttbest, - tp->t_srtt, - bwnd - ); - } - } - if ((long)bwnd < V_tcp_inflight_min) - bwnd = V_tcp_inflight_min; - if (bwnd > V_tcp_inflight_max) - bwnd = V_tcp_inflight_max; - if ((long)bwnd < tp->t_maxseg * 2) - bwnd = tp->t_maxseg * 2; - tp->snd_bwnd = bwnd; -} - #ifdef TCP_SIGNATURE /* * Callback function invoked by m_apply() to digest TCP segment data diff --git a/sys/netinet/tcp_timer.h b/sys/netinet/tcp_timer.h index 1ab0b7b2938..4bfcdf65c15 100644 --- a/sys/netinet/tcp_timer.h +++ b/sys/netinet/tcp_timer.h @@ -86,9 +86,6 @@ #define TCPTV_KEEPINTVL ( 75*hz) /* default probe interval */ #define TCPTV_KEEPCNT 8 /* max probes before drop */ -#define TCPTV_INFLIGHT_RTTTHRESH (10*hz/1000) /* below which inflight - disengages, in msec */ - #define TCPTV_FINWAIT2_TIMEOUT (60*hz) /* FIN_WAIT_2 timeout if no receiver */ /* diff --git a/sys/netinet/tcp_usrreq.c b/sys/netinet/tcp_usrreq.c index 2e61c3125c4..f35890bee19 100644 --- a/sys/netinet/tcp_usrreq.c +++ b/sys/netinet/tcp_usrreq.c @@ -1105,7 +1105,6 @@ tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td) tp->t_state = TCPS_SYN_SENT; tcp_timer_activate(tp, TT_KEEP, tcp_keepinit); tp->iss = tcp_new_isn(tp); - tp->t_bw_rtseq = tp->iss; tcp_sendseqinit(tp); return 0; @@ -1168,7 +1167,6 @@ tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td) tp->t_state = TCPS_SYN_SENT; tcp_timer_activate(tp, TT_KEEP, tcp_keepinit); tp->iss = tcp_new_isn(tp); - tp->t_bw_rtseq = tp->iss; tcp_sendseqinit(tp); return 0; @@ -1214,7 +1212,7 @@ tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti) ti->tcpi_rcv_space = tp->rcv_wnd; ti->tcpi_rcv_nxt = tp->rcv_nxt; ti->tcpi_snd_wnd = tp->snd_wnd; - ti->tcpi_snd_bwnd = tp->snd_bwnd; + ti->tcpi_snd_bwnd = 0; /* Unused, kept for compat. */ ti->tcpi_snd_nxt = tp->snd_nxt; ti->tcpi_snd_mss = tp->t_maxseg; ti->tcpi_rcv_mss = tp->t_maxseg; @@ -1795,26 +1793,24 @@ db_print_tcpcb(struct tcpcb *tp, const char *name, int indent) tp->rcv_adv, tp->rcv_wnd, tp->rcv_up); db_print_indent(indent); - db_printf("snd_wnd: %lu snd_cwnd: %lu snd_bwnd: %lu\n", - tp->snd_wnd, tp->snd_cwnd, tp->snd_bwnd); + db_printf("snd_wnd: %lu snd_cwnd: %lu\n", + tp->snd_wnd, tp->snd_cwnd); db_print_indent(indent); - db_printf("snd_ssthresh: %lu snd_bandwidth: %lu snd_recover: " - "0x%08x\n", tp->snd_ssthresh, tp->snd_bandwidth, - tp->snd_recover); + db_printf("snd_ssthresh: %lu snd_recover: " + "0x%08x\n", tp->snd_ssthresh, tp->snd_recover); db_print_indent(indent); db_printf("t_maxopd: %u t_rcvtime: %u t_startime: %u\n", tp->t_maxopd, tp->t_rcvtime, tp->t_starttime); db_print_indent(indent); - db_printf("t_rttime: %u t_rtsq: 0x%08x t_bw_rtttime: %u\n", - tp->t_rtttime, tp->t_rtseq, tp->t_bw_rtttime); + db_printf("t_rttime: %u t_rtsq: 0x%08x\n", + tp->t_rtttime, tp->t_rtseq); db_print_indent(indent); - db_printf("t_bw_rtseq: 0x%08x t_rxtcur: %d t_maxseg: %u " - "t_srtt: %d\n", tp->t_bw_rtseq, tp->t_rxtcur, tp->t_maxseg, - tp->t_srtt); + db_printf("t_rxtcur: %d t_maxseg: %u t_srtt: %d\n", + tp->t_rxtcur, tp->t_maxseg, tp->t_srtt); db_print_indent(indent); db_printf("t_rttvar: %d t_rxtshift: %d t_rttmin: %u " diff --git a/sys/netinet/tcp_var.h b/sys/netinet/tcp_var.h index b753e105ee5..2b7abcaf095 100644 --- a/sys/netinet/tcp_var.h +++ b/sys/netinet/tcp_var.h @@ -135,12 +135,12 @@ struct tcpcb { u_long snd_wnd; /* send window */ u_long snd_cwnd; /* congestion-controlled window */ - u_long snd_bwnd; /* bandwidth-controlled window */ + u_long snd_spare1; /* unused */ u_long snd_ssthresh; /* snd_cwnd size threshold for * for slow start exponential to * linear switch */ - u_long snd_bandwidth; /* calculated bandwidth or 0 */ + u_long snd_spare2; /* unused */ tcp_seq snd_recover; /* for use in NewReno Fast Recovery */ u_int t_maxopd; /* mss plus options */ @@ -150,8 +150,8 @@ struct tcpcb { u_int t_rtttime; /* RTT measurement start time */ tcp_seq t_rtseq; /* sequence number being timed */ - u_int t_bw_rtttime; /* used for bandwidth calculation */ - tcp_seq t_bw_rtseq; /* used for bandwidth calculation */ + u_int t_bw_spare1; /* unused */ + tcp_seq t_bw_spare2; /* unused */ int t_rxtcur; /* current retransmit value (ticks) */ u_int t_maxseg; /* maximum segment size */ @@ -654,7 +654,6 @@ void tcpip_fillheaders(struct inpcb *, void *, void *); void tcp_timer_activate(struct tcpcb *, int, u_int); int tcp_timer_active(struct tcpcb *, int); void tcp_trace(short, short, struct tcpcb *, void *, struct tcphdr *, int); -void tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq); /* * All tcp_hc_* functions are IPv4 and IPv6 (via in_conninfo) */ From a0482fa4e7fa27b01184f938097f0666b78016dd Mon Sep 17 00:00:00 2001 From: Dimitry Andric Date: Thu, 16 Sep 2010 21:14:28 +0000 Subject: [PATCH 0824/1624] Make vendor/clang/dist exactly the same as upstream's r108428. Some files and directories were already added/removed in the upstream repository, but were not added/removed here, when the previous snapshot was imported. Note: I did not import the file test/Lexer/conflict-marker.c, because it contains merge conflict markers on purpose, which upsets our pre-commit hooks. Approved by: rpaulo (mentor) --- VER | 1 - docs/BlockImplementation.txt | 647 ----- include/clang/AST/DeclNodes.def | 165 -- include/clang/AST/StmtNodes.def | 165 -- lib/Headers/arm_neon.h | 537 ---- lib/Headers/arm_neon.td | 341 --- tools/CIndex/CIndex.cpp | 2589 -------------------- tools/CIndex/CIndex.darwin.exports | 81 - tools/CIndex/CIndex.exports | 81 - tools/CIndex/CIndexCodeCompletion.cpp | 512 ---- tools/CIndex/CIndexDiagnostic.cpp | 285 --- tools/CIndex/CIndexDiagnostic.h | 53 - tools/CIndex/CIndexInclusionStack.cpp | 67 - tools/CIndex/CIndexUSRs.cpp | 469 ---- tools/CIndex/CIndexer.cpp | 154 -- tools/CIndex/CIndexer.h | 78 - tools/CIndex/CMakeLists.txt | 56 - tools/CIndex/CXCursor.cpp | 369 --- tools/CIndex/CXCursor.h | 112 - tools/CIndex/CXSourceLocation.h | 75 - tools/CIndex/Makefile | 55 - tools/index-test/CMakeLists.txt | 23 - tools/index-test/Makefile | 25 - tools/index-test/index-test.cpp | 334 --- utils/pch-test.pl | 61 - win32/clangAST/clangAST.vcproj | 347 --- win32/clangAnalysis/clangAnalysis.vcproj | 351 --- win32/clangBasic/clangBasic.vcproj | 236 -- win32/clangCodeGen/clangCodeGen.vcproj | 271 -- win32/clangDriver/clangDriver.vcproj | 270 -- win32/clangLex/clangLex.vcproj | 283 --- win32/clangLibDriver/clangLibDriver.vcproj | 205 -- win32/clangParse/clangParse.vcproj | 248 -- win32/clangRewrite/clangRewrite.vcproj | 191 -- win32/clangSema/clangSema.vcproj | 263 -- www/analyzer/menu.js | 17 - 36 files changed, 10017 deletions(-) delete mode 100644 VER delete mode 100644 docs/BlockImplementation.txt delete mode 100644 include/clang/AST/DeclNodes.def delete mode 100644 include/clang/AST/StmtNodes.def delete mode 100644 lib/Headers/arm_neon.h delete mode 100644 lib/Headers/arm_neon.td delete mode 100644 tools/CIndex/CIndex.cpp delete mode 100644 tools/CIndex/CIndex.darwin.exports delete mode 100644 tools/CIndex/CIndex.exports delete mode 100644 tools/CIndex/CIndexCodeCompletion.cpp delete mode 100644 tools/CIndex/CIndexDiagnostic.cpp delete mode 100644 tools/CIndex/CIndexDiagnostic.h delete mode 100644 tools/CIndex/CIndexInclusionStack.cpp delete mode 100644 tools/CIndex/CIndexUSRs.cpp delete mode 100644 tools/CIndex/CIndexer.cpp delete mode 100644 tools/CIndex/CIndexer.h delete mode 100644 tools/CIndex/CMakeLists.txt delete mode 100644 tools/CIndex/CXCursor.cpp delete mode 100644 tools/CIndex/CXCursor.h delete mode 100644 tools/CIndex/CXSourceLocation.h delete mode 100644 tools/CIndex/Makefile delete mode 100644 tools/index-test/CMakeLists.txt delete mode 100644 tools/index-test/Makefile delete mode 100644 tools/index-test/index-test.cpp delete mode 100755 utils/pch-test.pl delete mode 100644 win32/clangAST/clangAST.vcproj delete mode 100644 win32/clangAnalysis/clangAnalysis.vcproj delete mode 100644 win32/clangBasic/clangBasic.vcproj delete mode 100644 win32/clangCodeGen/clangCodeGen.vcproj delete mode 100644 win32/clangDriver/clangDriver.vcproj delete mode 100644 win32/clangLex/clangLex.vcproj delete mode 100644 win32/clangLibDriver/clangLibDriver.vcproj delete mode 100644 win32/clangParse/clangParse.vcproj delete mode 100644 win32/clangRewrite/clangRewrite.vcproj delete mode 100644 win32/clangSema/clangSema.vcproj delete mode 100644 www/analyzer/menu.js diff --git a/VER b/VER deleted file mode 100644 index cd5ac039d67..00000000000 --- a/VER +++ /dev/null @@ -1 +0,0 @@ -2.0 diff --git a/docs/BlockImplementation.txt b/docs/BlockImplementation.txt deleted file mode 100644 index c420455979c..00000000000 --- a/docs/BlockImplementation.txt +++ /dev/null @@ -1,647 +0,0 @@ -Block Implementation Specification - -Copyright 2008-2009 Apple, Inc. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -0. History - -2008/7/14 - created -2008/8/21 - revised, C++ -2008/9/24 - add NULL isa field to __block storage -2008/10/1 - revise block layout to use a static descriptor structure -2008/10/6 - revise block layout to use an unsigned long int flags -2008/10/28 - specify use of _Block_object_assign/dispose for all "Object" types in helper functions -2008/10/30 - revise new layout to have invoke function in same place -2008/10/30 - add __weak support - -This document describes the Apple ABI implementation specification of Blocks. - -1. High Level - -A Block consists of a structure of the following form: - -struct Block_literal_1 { - void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock - int flags; - int reserved; - void (*invoke)(void *, ...); - struct Block_descriptor_1 { - unsigned long int reserved; // NULL - unsigned long int size; // sizeof(struct Block_literal_1) - // optional helper functions - void (*copy_helper)(void *dst, void *src); - void (*dispose_helper)(void *src); - } *descriptor; - // imported variables -}; - -The following flags bits are used by the compiler: - -enum { - BLOCK_HAS_COPY_DISPOSE = (1 << 25), - BLOCK_HAS_CTOR = (1 << 26), // helpers have C++ code - BLOCK_IS_GLOBAL = (1 << 28), - BLOCK_HAS_DESCRIPTOR = (1 << 29), // interim until complete world build is accomplished -}; - -Block literals may occur within functions where the structure is created in stack local memory. They may also appear as initialization expressions for Block variables of global or static local variables. - -When a Block literal expression is evaluated the stack based structure is initialized as follows: - -1) static descriptor structure is declared and initialized as follows: -1a) the invoke function pointer is set to a function that takes the Block structure as its first argument and the rest of the arguments (if any) to the Block and executes the Block compound statement. -1b) the size field is set to the size of the following Block literal structure. -1c) the copy_helper and dispose_helper function pointers are set to respective helper functions if they are required by the Block literal -2) a stack (or global) Block literal data structure is created and initialized as follows: -2a) the isa field is set to the address of the external _NSConcreteStackBlock, which is a block of uninitialized memory supplied in libSystem, or _NSConcreteGlobalBlock if this is a static or file level block literal. -2) The flags field is set to zero unless there are variables imported into the block that need helper functions for program level Block_copy() and Block_release() operations, in which case the (1<<25) flags bit is set. - -As an example, the Block literal expression - ^ { printf("hello world\n"); } -would cause to be created on a 32-bit system: - -struct __block_literal_1 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_1 *); - struct __block_descriptor_1 *descriptor; -}; - -void __block_invoke_1(struct __block_literal_1 *_block) { - printf("hello world\n"); -} - -static struct __block_descriptor_1 { - unsigned long int reserved; - unsigned long int Block_size; -} __block_descriptor_1 = { 0, sizeof(struct __block_literal_1), __block_invoke_1 }; - -and where the block literal appeared - - struct __block_literal_1 _block_literal = { - &_NSConcreteStackBlock, - (1<<29), , - __block_invoke_1, - &__block_descriptor_1 - }; - -Blocks import other Block references, const copies of other variables, and variables marked __block. In Objective-C variables may additionally be objects. - -When a Block literal expression used as the initial value of a global or static local variable it is initialized as follows: - struct __block_literal_1 __block_literal_1 = { - &_NSConcreteGlobalBlock, - (1<<28)|(1<<29), , - __block_invoke_1, - &__block_descriptor_1 - }; -that is, a different address is provided as the first value and a particular (1<<28) bit is set in the flags field, and otherwise it is the same as for stack based Block literals. This is an optimization that can be used for any Block literal that imports no const or __block storage variables. - - -2. Imported Variables - -Variables of "auto" storage class are imported as const copies. Variables of "__block" storage class are imported as a pointer to an enclosing data structure. Global variables are simply referenced and not considered as imported. - -2.1 Imported const copy variables - -Automatic storage variables not marked with __block are imported as const copies. - -The simplest example is that of importing a variable of type int. - - int x = 10; - void (^vv)(void) = ^{ printf("x is %d\n", x); } - x = 11; - vv(); - -would be compiled - -struct __block_literal_2 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_2 *); - struct __block_descriptor_2 *descriptor; - const int x; -}; - -void __block_invoke_2(struct __block_literal_2 *_block) { - printf("x is %d\n", _block->x); -} - -static struct __block_descriptor_2 { - unsigned long int reserved; - unsigned long int Block_size; -} __block_descriptor_2 = { 0, sizeof(struct __block_literal_2) }; - -and - - struct __block_literal_2 __block_literal_2 = { - &_NSConcreteStackBlock, - (1<<29), , - __block_invoke_2, - &__block_descriptor_2, - x - }; - -In summary, scalars, structures, unions, and function pointers are generally imported as const copies with no need for helper functions. - -2.2 Imported const copy of Block reference - -The first case where copy and dispose helper functions are required is for the case of when a block itself is imported. In this case both a copy_helper function and a dispose_helper function are needed. The copy_helper function is passed both the existing stack based pointer and the pointer to the new heap version and should call back into the runtime to actually do the copy operation on the imported fields within the block. The runtime functions are all described in Section 5.0 Runtime Helper Functions. - -An example: - - void (^existingBlock)(void) = ...; - void (^vv)(void) = ^{ existingBlock(); } - vv(); - -struct __block_literal_3 { - ...; // existing block -}; - -struct __block_literal_4 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_4 *); - struct __block_literal_3 *const existingBlock; -}; - -void __block_invoke_4(struct __block_literal_2 *_block) { - __block->existingBlock->invoke(__block->existingBlock); -} - -void __block_copy_4(struct __block_literal_4 *dst, struct __block_literal_4 *src) { - //_Block_copy_assign(&dst->existingBlock, src->existingBlock, 0); - _Block_object_assign(&dst->existingBlock, src->existingBlock, BLOCK_FIELD_IS_BLOCK); -} - -void __block_dispose_4(struct __block_literal_4 *src) { - // was _Block_destroy - _Block_object_dispose(src->existingBlock, BLOCK_FIELD_IS_BLOCK); -} - -static struct __block_descriptor_4 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_4 *dst, struct __block_literal_4 *src); - void (*dispose_helper)(struct __block_literal_4 *); -} __block_descriptor_4 = { - 0, - sizeof(struct __block_literal_4), - __block_copy_4, - __block_dispose_4, -}; - -and where it is used - - struct __block_literal_4 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<29), - __block_invoke_4, - & __block_descriptor_4 - existingBlock, - }; - -2.2.1 Importing __attribute__((NSObject)) variables. - -GCC introduces __attribute__((NSObject)) on structure pointers to mean "this is an object". This is useful because many low level data structures are declared as opaque structure pointers, e.g. CFStringRef, CFArrayRef, etc. When used from C, however, these are still really objects and are the second case where that requires copy and dispose helper functions to be generated. The copy helper functions generated by the compiler should use the _Block_object_assign runtime helper function and in the dispose helper the _Block_object_dispose runtime helper function should be called. - -For example, block xyzzy in the following - - struct Opaque *__attribute__((NSObject)) objectPointer = ...; - ... - void (^xyzzy)(void) = ^{ CFPrint(objectPointer); }; - -would have helper functions - -void __block_copy_xyzzy(struct __block_literal_5 *dst, struct __block_literal_5 *src) { - _Block_object_assign(&dst->objectPointer, src-> objectPointer, BLOCK_FIELD_IS_OBJECT); -} - -void __block_dispose_xyzzy(struct __block_literal_5 *src) { - _Block_object_dispose(src->objectPointer, BLOCK_FIELD_IS_OBJECT); -} - -generated. - - -2.3 Imported __block marked variables. - -2.3.1 Layout of __block marked variables - -The compiler must embed variables that are marked __block in a specialized structure of the form: - -struct _block_byref_xxxx { - void *isa; - struct Block_byref *forwarding; - int flags; //refcount; - int size; - typeof(marked_variable) marked_variable; -}; - -Variables of certain types require helper functions for when Block_copy() and Block_release() are performed upon a referencing Block. At the "C" level only variables that are of type Block or ones that have __attribute__((NSObject)) marked require helper functions. In Objective-C objects require helper functions and in C++ stack based objects require helper functions. Variables that require helper functions use the form: - -struct _block_byref_xxxx { - void *isa; - struct _block_byref_xxxx *forwarding; - int flags; //refcount; - int size; - // helper functions called via Block_copy() and Block_release() - void (*byref_keep)(void *dst, void *src); - void (*byref_dispose)(void *); - typeof(marked_variable) marked_variable; -}; - -The structure is initialized such that - a) the forwarding pointer is set to the beginning of its enclosing structure, - b) the size field is initialized to the total size of the enclosing structure, - c) the flags field is set to either 0 if no helper functions are needed or (1<<25) if they are, - d) the helper functions are initialized (if present) - e) the variable itself is set to its initial value. - f) the isa field is set to NULL - -2.3.2 Access to __block variables from within its lexical scope. - -In order to "move" the variable to the heap upon a copy_helper operation the compiler must rewrite access to such a variable to be indirect through the structures forwarding pointer. For example: - - int __block i = 10; - i = 11; - -would be rewritten to be: - - struct _block_byref_i { - void *isa; - struct _block_byref_i *forwarding; - int flags; //refcount; - int size; - int captured_i; - } i = { NULL, &i, 0, sizeof(struct _block_byref_i), 11 }; - - i.forwarding->captured_i = 11; - -In the case of a Block reference variable being marked __block the helper code generated must use the _Block_object_assign and _Block_object_dispose routines supplied by the runtime to make the copies. For example: - - __block void (voidBlock)(void) = blockA; - voidBlock = blockB; - -would translate into - -struct _block_byref_voidBlock { - void *isa; - struct _block_byref_voidBlock *forwarding; - int flags; //refcount; - int size; - void (*byref_keep)(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src); - void (*byref_dispose)(struct _block_byref_voidBlock *); - void (^captured_voidBlock)(void); -}; - -void _block_byref_keep_helper(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) { - //_Block_copy_assign(&dst->captured_voidBlock, src->captured_voidBlock, 0); - _Block_object_assign(&dst->captured_voidBlock, src->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER); -} - -void _block_byref_dispose_helper(struct _block_byref_voidBlock *param) { - //_Block_destroy(param->captured_voidBlock, 0); - _Block_object_dispose(param->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER)} - -and - struct _block_byref_voidBlock voidBlock = {( .forwarding=&voidBlock, .flags=(1<<25), .size=sizeof(struct _block_byref_voidBlock *), - .byref_keep=_block_byref_keep_helper, .byref_dispose=_block_byref_dispose_helper, - .captured_voidBlock=blockA }; - - voidBlock.forwarding->captured_voidBlock = blockB; - - -2.3.3 Importing __block variables into Blocks - -A Block that uses a __block variable in its compound statement body must import the variable and emit copy_helper and dispose_helper helper functions that, in turn, call back into the runtime to actually copy or release the byref data block using the functions _Block_object_assign and _Block_object_dispose. - -For example: - - int __block i = 2; - functioncall(^{ i = 10; }); - -would translate to - -struct _block_byref_i { - void *isa; // set to NULL - struct _block_byref_voidBlock *forwarding; - int flags; //refcount; - int size; - void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src); - void (*byref_dispose)(struct _block_byref_i *); - int captured_i; -}; - - -struct __block_literal_5 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_5 *); - struct __block_descriptor_5 *descriptor; - struct _block_byref_i *i_holder; -}; - -void __block_invoke_5(struct __block_literal_5 *_block) { - _block->forwarding->captured_i = 10; -} - -void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) { - //_Block_byref_assign_copy(&dst->captured_i, src->captured_i); - _Block_object_assign(&dst->captured_i, src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER); -} - -void __block_dispose_5(struct __block_literal_5 *src) { - //_Block_byref_release(src->captured_i); - _Block_object_dispose(src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER); -} - -static struct __block_descriptor_5 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src); - void (*dispose_helper)(struct __block_literal_5 *); -} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5) __block_copy_5, __block_dispose_5 }; - -and - - struct _block_byref_i i = {( .forwarding=&i, .flags=0, .size=sizeof(struct _block_byref_i) )}; - struct __block_literal_5 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<29), , - __block_invoke_5, - &__block_descriptor_5, - 2, - }; - -2.3.4 Importing __attribute__((NSObject)) __block variables - -A __block variable that is also marked __attribute__((NSObject)) should have byref_keep and byref_dispose helper functions that use _Block_object_assign and _Block_object_dispose. - -2.3.5 __block escapes - -Because Blocks referencing __block variables may have Block_copy() performed upon them the underlying storage for the variables may move to the heap. In Objective-C Garbage Collection Only compilation environments the heap used is the garbage collected one and no further action is required. Otherwise the compiler must issue a call to potentially release any heap storage for __block variables at all escapes or terminations of their scope. - - -2.3.6 Nesting - -Blocks may contain Block literal expressions. Any variables used within inner blocks are imported into all enclosing Block scopes even if the variables are not used. This includes const imports as well as __block variables. - -3. Objective C Extensions to Blocks - -3.1 Importing Objects - -Objects should be treated as __attribute__((NSObject)) variables; all copy_helper, dispose_helper, byref_keep, and byref_dispose helper functions should use _Block_object_assign and _Block_object_dispose. There should be no code generated that uses -retain or -release methods. - - -3.2 Blocks as Objects - -The compiler will treat Blocks as objects when synthesizing property setters and getters, will characterize them as objects when generating garbage collection strong and weak layout information in the same manner as objects, and will issue strong and weak write-barrier assignments in the same manner as objects. - -3.3 __weak __block Support - -Objective-C (and Objective-C++) support the __weak attribute on __block variables. Under normal circumstances the compiler uses the Objective-C runtime helper support functions objc_assign_weak and objc_read_weak. Both should continue to be used for all reads and writes of __weak __block variables: - objc_read_weak(&block->byref_i->forwarding->i) - -The __weak variable is stored in a _block_byref_xxxx structure and the Block has copy and dispose helpers for this structure that call: - _Block_object_assign(&dest->_block_byref_i, src-> _block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF); -and - _Block_object_dispose(src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF); - - -In turn, the block_byref copy support helpers distinguish between whether the __block variable is a Block or not and should either call: - _Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_OBJECT | BLOCK_BYREF_CALLER); -for something declared as an object or - _Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER); -for something declared as a Block. - -A full example follows: - - - __block __weak id obj = ; - functioncall(^{ [obj somemessage]; }); - -would translate to - -struct _block_byref_obj { - void *isa; // uninitialized - struct _block_byref_obj *forwarding; - int flags; //refcount; - int size; - void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src); - void (*byref_dispose)(struct _block_byref_i *); - int captured_obj; -}; - -void _block_byref_obj_keep(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) { - //_Block_copy_assign(&dst->captured_obj, src->captured_obj, 0); - _Block_object_assign(&dst->captured_obj, src->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER); -} - -void _block_byref_obj_dispose(struct _block_byref_voidBlock *param) { - //_Block_destroy(param->captured_obj, 0); - _Block_object_dispose(param->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER); -}; - -for the block byref part and - -struct __block_literal_5 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_5 *); - struct __block_descriptor_5 *descriptor; - struct _block_byref_obj *byref_obj; -}; - -void __block_invoke_5(struct __block_literal_5 *_block) { - [objc_read_weak(&_block->byref_obj->forwarding->captured_obj) somemessage]; -} - -void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) { - //_Block_byref_assign_copy(&dst->byref_obj, src->byref_obj); - _Block_object_assign(&dst->byref_obj, src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK); -} - -void __block_dispose_5(struct __block_literal_5 *src) { - //_Block_byref_release(src->byref_obj); - _Block_object_dispose(src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK); -} - -static struct __block_descriptor_5 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src); - void (*dispose_helper)(struct __block_literal_5 *); -} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5), __block_copy_5, __block_dispose_5 }; - -and within the compound statement: - - struct _block_byref_obj obj = {( .forwarding=&obj, .flags=(1<<25), .size=sizeof(struct _block_byref_obj), - .byref_keep=_block_byref_obj_keep, .byref_dispose=_block_byref_obj_dispose, - .captured_obj = )}; - - struct __block_literal_5 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<29), , - __block_invoke_5, - &__block_descriptor_5, - &obj, // a reference to the on-stack structure containing "captured_obj" - }; - - - functioncall(_block_literal->invoke(&_block_literal)); - - -4.0 C++ Support - -Within a block stack based C++ objects are copied as const copies using the const copy constructor. It is an error if a stack based C++ object is used within a block if it does not have a const copy constructor. In addition both copy and destroy helper routines must be synthesized for the block to support the Block_copy() operation, and the flags work marked with the (1<<26) bit in addition to the (1<<25) bit. The copy helper should call the constructor using appropriate offsets of the variable within the supplied stack based block source and heap based destination for all const constructed copies, and similarly should call the destructor in the destroy routine. - -As an example, suppose a C++ class FOO existed with a const copy constructor. Within a code block a stack version of a FOO object is declared and used within a Block literal expression: - -{ - FOO foo; - void (^block)(void) = ^{ printf("%d\n", foo.value()); }; -} - -The compiler would synthesize - -struct __block_literal_10 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_10 *); - struct __block_descriptor_10 *descriptor; - const FOO foo; -}; - -void __block_invoke_10(struct __block_literal_10 *_block) { - printf("%d\n", _block->foo.value()); -} - -void __block_literal_10(struct __block_literal_10 *dst, struct __block_literal_10 *src) { - comp_ctor(&dst->foo, &src->foo); -} - -void __block_dispose_10(struct __block_literal_10 *src) { - comp_dtor(&src->foo); -} - -static struct __block_descriptor_10 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_10 *dst, struct __block_literal_10 *src); - void (*dispose_helper)(struct __block_literal_10 *); -} __block_descriptor_10 = { 0, sizeof(struct __block_literal_10), __block_copy_10, __block_dispose_10 }; - -and the code would be: -{ - FOO foo; - comp_ctor(&foo); // default constructor - struct __block_literal_10 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<26)|(1<<29), , - __block_invoke_10, - &__block_descriptor_10, - }; - comp_ctor(&_block_literal->foo, &foo); // const copy into stack version - struct __block_literal_10 &block = &_block_literal; // assign literal to block variable - block->invoke(block); // invoke block - comp_dtor(&_block_literal->foo); // destroy stack version of const block copy - comp_dtor(&foo); // destroy original version -} - - -C++ objects stored in __block storage start out on the stack in a block_byref data structure as do other variables. Such objects (if not const objects) must support a regular copy constructor. The block_byref data structure will have copy and destroy helper routines synthesized by the compiler. The copy helper will have code created to perform the copy constructor based on the initial stack block_byref data structure, and will also set the (1<<26) bit in addition to the (1<<25) bit. The destroy helper will have code to do the destructor on the object stored within the supplied block_byref heap data structure. - -To support member variable and function access the compiler will synthesize a const pointer to a block version of the this pointer. - -5.0 Runtime Helper Functions - -The runtime helper functions are described in /usr/local/include/Block_private.h. To summarize their use, a block requires copy/dispose helpers if it imports any block variables, __block storage variables, __attribute__((NSObject)) variables, or C++ const copied objects with constructor/destructors. The (1<<26) bit is set and functions are generated. - -The block copy helper function should, for each of the variables of the type mentioned above, call - _Block_object_assign(&dst->target, src->target, BLOCK_FIELD_); -in the copy helper and - _Block_object_dispose(->target, BLOCK_FIELD_); -in the dispose helper where - is - -enum { - BLOCK_FIELD_IS_OBJECT = 3, // id, NSObject, __attribute__((NSObject)), block, ... - BLOCK_FIELD_IS_BLOCK = 7, // a block variable - BLOCK_FIELD_IS_BYREF = 8, // the on stack structure holding the __block variable - - BLOCK_FIELD_IS_WEAK = 16, // declared __weak - - BLOCK_BYREF_CALLER = 128, // called from byref copy/dispose helpers -}; - -and of course the CTORs/DTORs for const copied C++ objects. - -The block_byref data structure similarly requires copy/dispose helpers for block variables, __attribute__((NSObject)) variables, or C++ const copied objects with constructor/destructors, and again the (1<<26) bit is set and functions are generated in the same manner. - -Under ObjC we allow __weak as an attribute on __block variables, and this causes the addition of BLOCK_FIELD_IS_WEAK orred onto the BLOCK_FIELD_IS_BYREF flag when copying the block_byref structure in the block copy helper, and onto the BLOCK_FIELD_ field within the block_byref copy/dispose helper calls. - -The prototypes, and summary, of the helper functions are - -/* Certain field types require runtime assistance when being copied to the heap. The following function is used - to copy fields of types: blocks, pointers to byref structures, and objects (including __attribute__((NSObject)) pointers. - BLOCK_FIELD_IS_WEAK is orthogonal to the other choices which are mutually exclusive. - Only in a Block copy helper will one see BLOCK_FIELD_IS_BYREF. - */ -void _Block_object_assign(void *destAddr, const void *object, const int flags); - -/* Similarly a compiler generated dispose helper needs to call back for each field of the byref data structure. - (Currently the implementation only packs one field into the byref structure but in principle there could be more). - The same flags used in the copy helper should be used for each call generated to this function: - */ -void _Block_object_dispose(const void *object, const int flags); - -The following functions have been used and will continue to be supported until new compiler support is complete. - -// Obsolete functions. -// Copy helper callback for copying a block imported into a Block -// Called by copy_helper helper functions synthesized by the compiler. -// The address in the destination block of an imported Block is provided as the first argument -// and the value of the existing imported Block is the second. -// Use: _Block_object_assign(dest, src, BLOCK_FIELD_IS_BLOCK {| BLOCK_FIELD_IS_WEAK}); -void _Block_copy_assign(struct Block_basic **dest, const struct Block_basic *src, const int flags); - -// Destroy helper callback for releasing Blocks imported into a Block -// Called by dispose_helper helper functions synthesized by the compiler. -// The value of the imported Block variable is passed back. -// Use: _Block_object_dispose(src, BLOCK_FIELD_IS_BLOCK {| BLOCK_FIELD_IS_WEAK}); -void _Block_destroy(const struct Block_basic *src, const int flags); - -// Byref data block copy helper callback -// Called by block copy helpers when copying __block structures -// Use: _Block_object_assign(dest, src, BLOCK_FIELD_IS_BYREF {| BLOCK_FIELD_IS_WEAK}); -void _Block_byref_assign_copy(struct Block_byref **destp, struct Block_byref *src); - -// Byref data block release helper callback -// Called by block release helpers when releasing a Block -// Called at escape points in scope where __block variables live (under non-GC-only conditions) -// Use: _Block_object_dispose(src, BLOCK_FIELD_IS_BYREF {| BLOCK_FIELD_IS_WEAK}); -void §(struct Block_byref *shared_struct); - - diff --git a/include/clang/AST/DeclNodes.def b/include/clang/AST/DeclNodes.def deleted file mode 100644 index 5b03ff8d911..00000000000 --- a/include/clang/AST/DeclNodes.def +++ /dev/null @@ -1,165 +0,0 @@ -//===-- DeclNodes.def - Metadata about Decl AST nodes -----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the declaration nodes within the AST. The -// description of the declaration nodes uses six macros: -// -// DECL(Derived, Base) describes a normal declaration type Derived -// and specifies its base class. Note that Derived should not have -// the Decl suffix on it, while Base should. -// -// LAST_DECL(Derived, Base) is like DECL, but is used for the last -// declaration in the list. -// -// ABSTRACT_DECL(Derived, Base) describes an abstract class that is -// used to specify a classification of declarations. For example, -// TagDecl is an abstract class used to describe the various kinds of -// "tag" declarations (unions, structs, classes, enums). -// -// DECL_CONTEXT(Decl) specifies that Decl is a kind of declaration -// that is also a DeclContext. -// -// LAST_DECL_CONTEXT(Decl) is like DECL_CONTEXT, but is used for the -// last declaration context. -// -// DECL_RANGE(CommonBase, Start, End) specifies a range of -// declaration values that have a common (potentially indirect) base -// class. -// -// LAST_DECL_RANGE(CommonBase, Start, End) is like DECL_RANGE, but is -// used for the last declaration range. -// -// Note that, due to the use of ranges, the order of the these -// declarations is significant. A declaration should be listed under -// its base class. -// ===----------------------------------------------------------------------===// - -#ifndef DECL -# define DECL(Derived, Base) -#endif - -#ifndef LAST_DECL -# define LAST_DECL(Derived, Base) DECL(Derived, Base) -#endif - -#ifndef ABSTRACT_DECL -# define ABSTRACT_DECL(Derived, Base) -#endif - -#ifndef DECL_CONTEXT -# define DECL_CONTEXT(Decl) -#endif - -#ifndef DECL_CONTEXT_BASE -# define DECL_CONTEXT_BASE(Decl) DECL_CONTEXT(Decl) -#endif - -#ifndef LAST_DECL_CONTEXT -# define LAST_DECL_CONTEXT(Decl) DECL_CONTEXT(Decl) -#endif - -#ifndef DECL_RANGE -# define DECL_RANGE(CommonBase, Start, End) -#endif - -#ifndef LAST_DECL_RANGE -# define LAST_DECL_RANGE(CommonBase, Start, End) \ - DECL_RANGE(CommonBase, Start, End) -#endif - -DECL(TranslationUnit, Decl) -ABSTRACT_DECL(Named, Decl) - DECL(Namespace, NamedDecl) - DECL(UsingDirective, NamedDecl) - DECL(NamespaceAlias, NamedDecl) - ABSTRACT_DECL(Type, NamedDecl) - DECL(Typedef, TypeDecl) - DECL(UnresolvedUsingTypename, TypeDecl) - ABSTRACT_DECL(Tag, TypeDecl) - DECL(Enum, TagDecl) - DECL(Record, TagDecl) - DECL(CXXRecord, RecordDecl) - DECL(ClassTemplateSpecialization, CXXRecordDecl) - DECL(ClassTemplatePartialSpecialization, - ClassTemplateSpecializationDecl) - DECL(TemplateTypeParm, TypeDecl) - ABSTRACT_DECL(Value, NamedDecl) - DECL(EnumConstant, ValueDecl) - DECL(UnresolvedUsingValue, ValueDecl) - ABSTRACT_DECL(Declarator, ValueDecl) - DECL(Function, DeclaratorDecl) - DECL(CXXMethod, FunctionDecl) - DECL(CXXConstructor, CXXMethodDecl) - DECL(CXXDestructor, CXXMethodDecl) - DECL(CXXConversion, CXXMethodDecl) - DECL(Field, DeclaratorDecl) - DECL(ObjCIvar, FieldDecl) - DECL(ObjCAtDefsField, FieldDecl) - DECL(Var, DeclaratorDecl) - DECL(ImplicitParam, VarDecl) - DECL(ParmVar, VarDecl) - DECL(NonTypeTemplateParm, VarDecl) - ABSTRACT_DECL(Template, NamedDecl) - DECL(FunctionTemplate, TemplateDecl) - DECL(ClassTemplate, TemplateDecl) - DECL(TemplateTemplateParm, TemplateDecl) - DECL(Using, NamedDecl) - DECL(UsingShadow, NamedDecl) - DECL(ObjCMethod, NamedDecl) - ABSTRACT_DECL(ObjCContainer, NamedDecl) - DECL(ObjCCategory, ObjCContainerDecl) - DECL(ObjCProtocol, ObjCContainerDecl) - DECL(ObjCInterface, ObjCContainerDecl) - ABSTRACT_DECL(ObjCImpl, ObjCContainerDecl) - DECL(ObjCCategoryImpl, ObjCImplDecl) - DECL(ObjCImplementation, ObjCImplDecl) - DECL(ObjCProperty, NamedDecl) - DECL(ObjCCompatibleAlias, NamedDecl) -DECL(LinkageSpec, Decl) -DECL(ObjCPropertyImpl, Decl) -DECL(ObjCForwardProtocol, Decl) -DECL(ObjCClass, Decl) -DECL(FileScopeAsm, Decl) -DECL(Friend, Decl) -DECL(FriendTemplate, Decl) -DECL(StaticAssert, Decl) -LAST_DECL(Block, Decl) - -// Declaration contexts. DECL_CONTEXT_BASE indicates that it has subclasses. -DECL_CONTEXT(TranslationUnit) -DECL_CONTEXT(Namespace) -DECL_CONTEXT(LinkageSpec) -DECL_CONTEXT(ObjCMethod) -DECL_CONTEXT_BASE(Tag) -DECL_CONTEXT_BASE(Function) -DECL_CONTEXT_BASE(ObjCContainer) -LAST_DECL_CONTEXT(Block) - -// Declaration ranges -DECL_RANGE(Named, Namespace, ObjCCompatibleAlias) -DECL_RANGE(ObjCContainer, ObjCCategory, ObjCImplementation) -DECL_RANGE(Field, Field, ObjCAtDefsField) -DECL_RANGE(Type, Typedef, TemplateTypeParm) -DECL_RANGE(Tag, Enum, ClassTemplatePartialSpecialization) -DECL_RANGE(Record, Record, ClassTemplatePartialSpecialization) -DECL_RANGE(Value, EnumConstant, NonTypeTemplateParm) -DECL_RANGE(Declarator, Function, NonTypeTemplateParm) -DECL_RANGE(Function, Function, CXXConversion) -DECL_RANGE(Template, FunctionTemplate, TemplateTemplateParm) -DECL_RANGE(ObjCImpl, ObjCCategoryImpl, ObjCImplementation) -LAST_DECL_RANGE(Var, Var, NonTypeTemplateParm) - -#undef LAST_DECL_RANGE -#undef DECL_RANGE -#undef LAST_DECL_CONTEXT -#undef DECL_CONTEXT_BASE -#undef DECL_CONTEXT -#undef ABSTRACT_DECL -#undef LAST_DECL -#undef DECL diff --git a/include/clang/AST/StmtNodes.def b/include/clang/AST/StmtNodes.def deleted file mode 100644 index 3a23e49148d..00000000000 --- a/include/clang/AST/StmtNodes.def +++ /dev/null @@ -1,165 +0,0 @@ -//===-- StmtNodes.def - Metadata about Stmt AST nodes -----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the AST Node info database. -// -//===---------------------------------------------------------------------===// - -#ifndef FIRST_STMT -#define FIRST_STMT(CLASS) -#define LAST_STMT(CLASS) -#endif - -#ifndef FIRST_EXPR -#define FIRST_EXPR(CLASS) -#define LAST_EXPR(CLASS) -#endif - -#ifndef EXPR -# define EXPR(Type, Base) STMT(Type, Base) -#endif - -#ifndef ABSTRACT_EXPR -# define ABSTRACT_EXPR(Type, Base) EXPR(Type, Base) -#endif - -// Normal Statements. -STMT(NullStmt , Stmt) -FIRST_STMT(NullStmt) -STMT(CompoundStmt , Stmt) -STMT(CaseStmt , SwitchCase) -STMT(DefaultStmt , SwitchCase) -STMT(LabelStmt , Stmt) -STMT(IfStmt , Stmt) -STMT(SwitchStmt , Stmt) -STMT(WhileStmt , Stmt) -STMT(DoStmt , Stmt) -STMT(ForStmt , Stmt) -STMT(GotoStmt , Stmt) -STMT(IndirectGotoStmt, Stmt) -STMT(ContinueStmt , Stmt) -STMT(BreakStmt , Stmt) -STMT(ReturnStmt , Stmt) -STMT(DeclStmt , Stmt) -STMT(SwitchCase , Stmt) - -// GNU Stmt Extensions -STMT(AsmStmt , Stmt) - -// Obj-C statements -STMT(ObjCAtTryStmt , Stmt) -STMT(ObjCAtCatchStmt , Stmt) -STMT(ObjCAtFinallyStmt , Stmt) -STMT(ObjCAtThrowStmt , Stmt) -STMT(ObjCAtSynchronizedStmt , Stmt) -// Obj-C2 statements -STMT(ObjCForCollectionStmt, Stmt) - -// C++ statements -STMT(CXXCatchStmt, Stmt) -STMT(CXXTryStmt , Stmt) - -LAST_STMT(CXXTryStmt) - -// Expressions. -ABSTRACT_EXPR(Expr , Stmt) -EXPR(PredefinedExpr , Expr) -EXPR(DeclRefExpr , Expr) -EXPR(IntegerLiteral , Expr) -EXPR(FloatingLiteral , Expr) -EXPR(ImaginaryLiteral , Expr) -EXPR(StringLiteral , Expr) -EXPR(CharacterLiteral , Expr) -EXPR(ParenExpr , Expr) -EXPR(UnaryOperator , Expr) -EXPR(OffsetOfExpr , Expr) -EXPR(SizeOfAlignOfExpr , Expr) -EXPR(ArraySubscriptExpr , Expr) -EXPR(CallExpr , Expr) -EXPR(MemberExpr , Expr) -ABSTRACT_EXPR(CastExpr , Expr) -EXPR(BinaryOperator , Expr) -EXPR(CompoundAssignOperator, BinaryOperator) -EXPR(ConditionalOperator , Expr) -EXPR(ImplicitCastExpr , CastExpr) -ABSTRACT_EXPR(ExplicitCastExpr, CastExpr) -EXPR(CStyleCastExpr , ExplicitCastExpr) -EXPR(CompoundLiteralExpr , Expr) -EXPR(ExtVectorElementExpr , Expr) -EXPR(InitListExpr , Expr) -EXPR(DesignatedInitExpr , Expr) -EXPR(ImplicitValueInitExpr , Expr) -EXPR(ParenListExpr , Expr) -EXPR(VAArgExpr , Expr) - -// GNU Extensions. -EXPR(AddrLabelExpr , Expr) -EXPR(StmtExpr , Expr) -EXPR(TypesCompatibleExpr , Expr) -EXPR(ChooseExpr , Expr) -EXPR(GNUNullExpr , Expr) - -// C++ Expressions. -EXPR(CXXOperatorCallExpr , CallExpr) -EXPR(CXXMemberCallExpr , CallExpr) -ABSTRACT_EXPR(CXXNamedCastExpr , ExplicitCastExpr) -EXPR(CXXStaticCastExpr , CXXNamedCastExpr) -EXPR(CXXDynamicCastExpr , CXXNamedCastExpr) -EXPR(CXXReinterpretCastExpr , CXXNamedCastExpr) -EXPR(CXXConstCastExpr , CXXNamedCastExpr) -EXPR(CXXFunctionalCastExpr , ExplicitCastExpr) -EXPR(CXXTypeidExpr , Expr) -EXPR(CXXBoolLiteralExpr , Expr) -EXPR(CXXNullPtrLiteralExpr , Expr) -EXPR(CXXThisExpr , Expr) -EXPR(CXXThrowExpr , Expr) -EXPR(CXXDefaultArgExpr , Expr) -EXPR(CXXZeroInitValueExpr , Expr) -EXPR(CXXNewExpr , Expr) -EXPR(CXXDeleteExpr , Expr) -EXPR(CXXPseudoDestructorExpr, Expr) -EXPR(UnresolvedLookupExpr , Expr) -EXPR(UnaryTypeTraitExpr , Expr) -EXPR(DependentScopeDeclRefExpr , Expr) -EXPR(CXXConstructExpr , Expr) -EXPR(CXXBindTemporaryExpr , Expr) -EXPR(CXXBindReferenceExpr , Expr) -EXPR(CXXExprWithTemporaries , Expr) -EXPR(CXXTemporaryObjectExpr , CXXConstructExpr) -EXPR(CXXUnresolvedConstructExpr, Expr) -EXPR(CXXDependentScopeMemberExpr, Expr) -EXPR(UnresolvedMemberExpr , Expr) - -// Obj-C Expressions. -EXPR(ObjCStringLiteral , Expr) -EXPR(ObjCEncodeExpr , Expr) -EXPR(ObjCMessageExpr , Expr) -EXPR(ObjCSelectorExpr , Expr) -EXPR(ObjCProtocolExpr , Expr) -EXPR(ObjCIvarRefExpr , Expr) -EXPR(ObjCPropertyRefExpr , Expr) -EXPR(ObjCImplicitSetterGetterRefExpr , Expr) -EXPR(ObjCSuperExpr , Expr) -EXPR(ObjCIsaExpr , Expr) - -// Clang Extensions. -EXPR(ShuffleVectorExpr , Expr) -EXPR(BlockExpr , Expr) -EXPR(BlockDeclRefExpr , Expr) - -FIRST_EXPR(PredefinedExpr) -LAST_EXPR(BlockDeclRefExpr) - -#undef ABSTRACT_EXPR -#undef EXPR -#undef STMT -#undef FIRST_STMT -#undef LAST_STMT -#undef FIRST_EXPR -#undef LAST_EXPR diff --git a/lib/Headers/arm_neon.h b/lib/Headers/arm_neon.h deleted file mode 100644 index 4508a27f36a..00000000000 --- a/lib/Headers/arm_neon.h +++ /dev/null @@ -1,537 +0,0 @@ -/*===---- arm_neon.h - NEON intrinsics --------------------------------------=== - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - *===-----------------------------------------------------------------------=== - */ - -#ifndef __ARM_NEON_H -#define __ARM_NEON_H - -#ifndef __ARM_NEON__ -#error "NEON support not enabled" -#endif - -// NEON document appears to be specified in terms of stdint types. -#include - -// Define some NEON-specific scalar types for floats and polynomials. -typedef float float32_t; -typedef uint8_t poly8_t; - -// FIXME: probably need a 'poly' attribute or something for correct codegen to -// disambiguate from uint16_t. -typedef uint16_t poly16_t; - -typedef __attribute__(( __vector_size__(8) )) int8_t __neon_int8x8_t; -typedef __attribute__(( __vector_size__(16) )) int8_t __neon_int8x16_t; -typedef __attribute__(( __vector_size__(8) )) int16_t __neon_int16x4_t; -typedef __attribute__(( __vector_size__(16) )) int16_t __neon_int16x8_t; -typedef __attribute__(( __vector_size__(8) )) int32_t __neon_int32x2_t; -typedef __attribute__(( __vector_size__(16) )) int32_t __neon_int32x4_t; -typedef __attribute__(( __vector_size__(8) )) int64_t __neon_int64x1_t; -typedef __attribute__(( __vector_size__(16) )) int64_t __neon_int64x2_t; -typedef __attribute__(( __vector_size__(8) )) uint8_t __neon_uint8x8_t; -typedef __attribute__(( __vector_size__(16) )) uint8_t __neon_uint8x16_t; -typedef __attribute__(( __vector_size__(8) )) uint16_t __neon_uint16x4_t; -typedef __attribute__(( __vector_size__(16) )) uint16_t __neon_uint16x8_t; -typedef __attribute__(( __vector_size__(8) )) uint32_t __neon_uint32x2_t; -typedef __attribute__(( __vector_size__(16) )) uint32_t __neon_uint32x4_t; -typedef __attribute__(( __vector_size__(8) )) uint64_t __neon_uint64x1_t; -typedef __attribute__(( __vector_size__(16) )) uint64_t __neon_uint64x2_t; -typedef __attribute__(( __vector_size__(8) )) uint16_t __neon_float16x4_t; -typedef __attribute__(( __vector_size__(16) )) uint16_t __neon_float16x8_t; -typedef __attribute__(( __vector_size__(8) )) float32_t __neon_float32x2_t; -typedef __attribute__(( __vector_size__(16) )) float32_t __neon_float32x4_t; -typedef __attribute__(( __vector_size__(8) )) poly8_t __neon_poly8x8_t; -typedef __attribute__(( __vector_size__(16) )) poly8_t __neon_poly8x16_t; -typedef __attribute__(( __vector_size__(8) )) poly16_t __neon_poly16x4_t; -typedef __attribute__(( __vector_size__(16) )) poly16_t __neon_poly16x8_t; - -typedef struct __int8x8_t { - __neon_int8x8_t val; -} int8x8_t; - -typedef struct __int8x16_t { - __neon_int8x16_t val; -} int8x16_t; - -typedef struct __int16x4_t { - __neon_int16x4_t val; -} int16x4_t; - -typedef struct __int16x8_t { - __neon_int16x8_t val; -} int16x8_t; - -typedef struct __int32x2_t { - __neon_int32x2_t val; -} int32x2_t; - -typedef struct __int32x4_t { - __neon_int32x4_t val; -} int32x4_t; - -typedef struct __int64x1_t { - __neon_int64x1_t val; -} int64x1_t; - -typedef struct __int64x2_t { - __neon_int64x2_t val; -} int64x2_t; - -typedef struct __uint8x8_t { - __neon_uint8x8_t val; -} uint8x8_t; - -typedef struct __uint8x16_t { - __neon_uint8x16_t val; -} uint8x16_t; - -typedef struct __uint16x4_t { - __neon_uint16x4_t val; -} uint16x4_t; - -typedef struct __uint16x8_t { - __neon_uint16x8_t val; -} uint16x8_t; - -typedef struct __uint32x2_t { - __neon_uint32x2_t val; -} uint32x2_t; - -typedef struct __uint32x4_t { - __neon_uint32x4_t val; -} uint32x4_t; - -typedef struct __uint64x1_t { - __neon_uint64x1_t val; -} uint64x1_t; - -typedef struct __uint64x2_t { - __neon_uint64x2_t val; -} uint64x2_t; - -typedef struct __float16x4_t { - __neon_float16x4_t val; -} float16x4_t; - -typedef struct __float16x8_t { - __neon_float16x8_t val; -} float16x8_t; - -typedef struct __float32x2_t { - __neon_float32x2_t val; -} float32x2_t; - -typedef struct __float32x4_t { - __neon_float32x4_t val; -} float32x4_t; - -typedef struct __poly8x8_t { - __neon_poly8x8_t val; -} poly8x8_t; - -typedef struct __poly8x16_t { - __neon_poly8x16_t val; -} poly8x16_t; - -typedef struct __poly16x4_t { - __neon_poly16x4_t val; -} poly16x4_t; - -typedef struct __poly16x8_t { - __neon_poly16x8_t val; -} poly16x8_t; - -// FIXME: write tool to stamp out the structure-of-array types, possibly gen this whole file. - -// Intrinsics, per ARM document DUI0348B -#define __ai static __attribute__((__always_inline__)) - -#define INTTYPES_WIDE(op, builtin) \ - __ai int16x8_t op##_s8(int16x8_t a, int8x8_t b) { return (int16x8_t){ builtin(a.val, b.val) }; } \ - __ai int32x4_t op##_s16(int32x4_t a, int16x4_t b) { return (int32x4_t){ builtin(a.val, b.val) }; } \ - __ai int64x2_t op##_s32(int64x2_t a, int32x2_t b) { return (int64x2_t){ builtin(a.val, b.val) }; } \ - __ai uint16x8_t op##_u8(uint16x8_t a, uint8x8_t b) { return (uint16x8_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##_u16(uint32x4_t a, uint16x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } \ - __ai uint64x2_t op##_u32(uint64x2_t a, uint32x2_t b) { return (uint64x2_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_WIDENING(op, builtin) \ - __ai int16x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int16x8_t){ builtin(a.val, b.val) }; } \ - __ai int32x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int32x4_t){ builtin(a.val, b.val) }; } \ - __ai int64x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int64x2_t){ builtin(a.val, b.val) }; } \ - __ai uint16x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint16x8_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } \ - __ai uint64x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint64x2_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_WIDENING_MUL(op, builtin) \ - __ai int16x8_t op##_s8(int16x8_t a, int8x8_t b, int8x8_t c) { return (int16x8_t){ builtin(a.val, b.val, c.val) }; } \ - __ai int32x4_t op##_s16(int32x4_t a, int16x4_t b, int16x4_t c) { return (int32x4_t){ builtin(a.val, b.val, c.val) }; } \ - __ai int64x2_t op##_s32(int64x2_t a, int32x2_t b, int32x2_t c) { return (int64x2_t){ builtin(a.val, b.val, c.val) }; } \ - __ai uint16x8_t op##_u8(uint16x8_t a, uint8x8_t b, uint8x8_t c) { return (uint16x8_t){ builtin(a.val, b.val, c.val) }; } \ - __ai uint32x4_t op##_u16(uint32x4_t a, uint16x4_t b, uint16x4_t c) { return (uint32x4_t){ builtin(a.val, b.val, c.val) }; } \ - __ai uint64x2_t op##_u32(uint64x2_t a, uint32x2_t b, uint32x2_t c) { return (uint64x2_t){ builtin(a.val, b.val, c.val) }; } - -#define INTTYPES_NARROWING(op, builtin) \ - __ai int8x8_t op##_s16(int16x8_t a, int16x8_t b) { return (int8x8_t){ builtin(a.val, b.val) }; } \ - __ai int16x4_t op##_s32(int32x4_t a, int32x4_t b) { return (int16x4_t){ builtin(a.val, b.val) }; } \ - __ai int32x2_t op##_s64(int64x2_t a, int64x2_t b) { return (int32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint8x8_t op##_u16(uint16x8_t a, uint16x8_t b) { return (uint8x8_t){ builtin(a.val, b.val) }; } \ - __ai uint16x4_t op##_u32(uint32x4_t a, uint32x4_t b) { return (uint16x4_t){ builtin(a.val, b.val) }; } \ - __ai uint32x2_t op##_u64(uint64x2_t a, uint64x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_ADD_32(op, builtin) \ - __ai int8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){ builtin(a.val, b.val) }; } \ - __ai int16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){ builtin(a.val, b.val) }; } \ - __ai int32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){ builtin(a.val, b.val) }; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){ builtin(a.val, b.val) }; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } \ - __ai int8x16_t op##q_s8(int8x16_t a, int8x16_t b) { return (int8x16_t){ builtin(a.val, b.val) }; } \ - __ai int16x8_t op##q_s16(int16x8_t a, int16x8_t b) { return (int16x8_t){ builtin(a.val, b.val) }; } \ - __ai int32x4_t op##q_s32(int32x4_t a, int32x4_t b) { return (int32x4_t){ builtin(a.val, b.val) }; } \ - __ai uint8x16_t op##q_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){ builtin(a.val, b.val) }; } \ - __ai uint16x8_t op##q_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##q_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_ADD_64(op, builtin) \ - __ai int64x1_t op##_s64(int64x1_t a, int64x1_t b) { return (int64x1_t){ builtin(a.val, b.val) }; } \ - __ai uint64x1_t op##_u64(uint64x1_t a, uint64x1_t b) { return (uint64x1_t){ builtin(a.val, b.val) }; } \ - __ai int64x2_t op##q_s64(int64x2_t a, int64x2_t b) { return (int64x2_t){ builtin(a.val, b.val) }; } \ - __ai uint64x2_t op##q_u64(uint64x2_t a, uint64x2_t b) { return (uint64x2_t){ builtin(a.val, b.val) }; } - -#define FLOATTYPES_CMP(op, builtin) \ - __ai uint32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##q_f32(float32x4_t a, float32x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } - -#define INT_FLOAT_CMP_OP(op, cc) \ - __ai uint8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (uint8x8_t){(__neon_uint8x8_t)(a.val cc b.val)}; } \ - __ai uint16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (uint16x4_t){(__neon_uint16x4_t)(a.val cc b.val)}; } \ - __ai uint32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (uint32x2_t){(__neon_uint32x2_t)(a.val cc b.val)}; } \ - __ai uint32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (uint32x2_t){(__neon_uint32x2_t)(a.val cc b.val)}; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){a.val cc b.val}; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){a.val cc b.val}; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){a.val cc b.val}; } \ - __ai uint8x16_t op##q_s8(int8x16_t a, int8x16_t b) { return (uint8x16_t){(__neon_uint8x16_t)(a.val cc b.val)}; } \ - __ai uint16x8_t op##q_s16(int16x8_t a, int16x8_t b) { return (uint16x8_t){(__neon_uint16x8_t)(a.val cc b.val)}; } \ - __ai uint32x4_t op##q_s32(int32x4_t a, int32x4_t b) { return (uint32x4_t){(__neon_uint32x4_t)(a.val cc b.val)}; } \ - __ai uint32x4_t op##q_f32(float32x4_t a, float32x4_t b) { return (uint32x4_t){(__neon_uint32x4_t)(a.val cc b.val)}; } \ - __ai uint8x16_t op##q_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){a.val cc b.val}; } \ - __ai uint16x8_t op##q_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){a.val cc b.val}; } \ - __ai uint32x4_t op##q_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){a.val cc b.val}; } - -#define INT_UNARY(op, builtin) \ - __ai int8x8_t op##_s8(int8x8_t a) { return (int8x8_t){ builtin(a.val) }; } \ - __ai int16x4_t op##_s16(int16x4_t a) { return (int16x4_t){ builtin(a.val) }; } \ - __ai int32x2_t op##_s32(int32x2_t a) { return (int32x2_t){ builtin(a.val) }; } \ - __ai int8x16_t op##q_s8(int8x16_t a) { return (int8x16_t){ builtin(a.val) }; } \ - __ai int16x8_t op##q_s16(int16x8_t a) { return (int16x8_t){ builtin(a.val) }; } \ - __ai int32x4_t op##q_s32(int32x4_t a) { return (int32x4_t){ builtin(a.val) }; } - -#define FP_UNARY(op, builtin) \ - __ai float32x2_t op##_f32(float32x2_t a) { return (float32x2_t){ builtin(a.val) }; } \ - __ai float32x4_t op##q_f32(float32x4_t a) { return (float32x4_t){ builtin(a.val) }; } - -#define FP_BINARY(op, builtin) \ - __ai float32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (float32x2_t){ builtin(a.val, b.val) }; } \ - __ai float32x4_t op##q_f32(float32x4_t a, float32x4_t b) { return (float32x4_t){ builtin(a.val, b.val) }; } - -#define INT_FP_PAIRWISE_ADD(op, builtin) \ - __ai int8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){ builtin(a.val, b.val) }; } \ - __ai int16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){ builtin(a.val, b.val) }; } \ - __ai int32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){ builtin(a.val, b.val) }; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){ builtin(a.val, b.val) }; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } \ - __ai float32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (float32x2_t){ builtin(a.val, b.val) }; } - -#define INT_LOGICAL_OP(op, lop) \ - __ai int8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){ a.val lop b.val }; } \ - __ai int16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){ a.val lop b.val }; } \ - __ai int32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){ a.val lop b.val }; } \ - __ai int64x1_t op##_s64(int64x1_t a, int64x1_t b) { return (int64x1_t){ a.val lop b.val }; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){ a.val lop b.val }; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){ a.val lop b.val }; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){ a.val lop b.val }; } \ - __ai uint64x1_t op##_u64(uint64x1_t a, uint64x1_t b) { return (uint64x1_t){ a.val lop b.val }; } \ - __ai int8x16_t op##q_s8(int8x16_t a, int8x16_t b) { return (int8x16_t){ a.val lop b.val }; } \ - __ai int16x8_t op##q_s16(int16x8_t a, int16x8_t b) { return (int16x8_t){ a.val lop b.val }; } \ - __ai int32x4_t op##q_s32(int32x4_t a, int32x4_t b) { return (int32x4_t){ a.val lop b.val }; } \ - __ai int64x2_t op##q_s64(int64x2_t a, int64x2_t b) { return (int64x2_t){ a.val lop b.val }; } \ - __ai uint8x16_t op##q_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){ a.val lop b.val }; } \ - __ai uint16x8_t op##q_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){ a.val lop b.val }; } \ - __ai uint32x4_t op##q_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){ a.val lop b.val }; } \ - __ai uint64x2_t op##q_u64(uint64x2_t a, uint64x2_t b) { return (uint64x2_t){ a.val lop b.val }; } - -// vector add -__ai int8x8_t vadd_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){a.val + b.val}; } -__ai int16x4_t vadd_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){a.val + b.val}; } -__ai int32x2_t vadd_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){a.val + b.val}; } -__ai int64x1_t vadd_s64(int64x1_t a, int64x1_t b) { return (int64x1_t){a.val + b.val}; } -__ai float32x2_t vadd_f32(float32x2_t a, float32x2_t b) { return (float32x2_t){a.val + b.val}; } -__ai uint8x8_t vadd_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){a.val + b.val}; } -__ai uint16x4_t vadd_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){a.val + b.val}; } -__ai uint32x2_t vadd_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){a.val + b.val}; } -__ai uint64x1_t vadd_u64(uint64x1_t a, uint64x1_t b) { return (uint64x1_t){a.val + b.val}; } -__ai int8x16_t vaddq_s8(int8x16_t a, int8x16_t b) { return (int8x16_t){a.val + b.val}; } -__ai int16x8_t vaddq_s16(int16x8_t a, int16x8_t b) { return (int16x8_t){a.val + b.val}; } -__ai int32x4_t vaddq_s32(int32x4_t a, int32x4_t b) { return (int32x4_t){a.val + b.val}; } -__ai int64x2_t vaddq_s64(int64x2_t a, int64x2_t b) { return (int64x2_t){a.val + b.val}; } -__ai float32x4_t vaddq_f32(float32x4_t a, float32x4_t b) { return (float32x4_t){a.val + b.val}; } -__ai uint8x16_t vaddq_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){a.val + b.val}; } -__ai uint16x8_t vaddq_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){a.val + b.val}; } -__ai uint32x4_t vaddq_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){a.val + b.val}; } -__ai uint64x2_t vaddq_u64(uint64x2_t a, uint64x2_t b) { return (uint64x2_t){a.val + b.val}; } - -// vector long add -INTTYPES_WIDENING(vaddl, __builtin_neon_vaddl) - -// vector wide add -INTTYPES_WIDE(vaddw, __builtin_neon_vaddw) - -// halving add -// rounding halving add -INTTYPES_ADD_32(vhadd, __builtin_neon_vhadd) -INTTYPES_ADD_32(vrhadd, __builtin_neon_vrhadd) - -// saturating add -INTTYPES_ADD_32(vqadd, __builtin_neon_vqadd) -INTTYPES_ADD_64(vqadd, __builtin_neon_vqadd) - -// add high half -// rounding add high half -INTTYPES_NARROWING(vaddhn, __builtin_neon_vaddhn) -INTTYPES_NARROWING(vraddhn, __builtin_neon_vraddhn) - -// multiply -// mul-poly - -// multiple accumulate -// multiple subtract - -// multiple accumulate long -// multiple subtract long -INTTYPES_WIDENING_MUL(vmlal, __builtin_neon_vmlal) -INTTYPES_WIDENING_MUL(vmlsl, __builtin_neon_vmlsl) - -// saturating doubling multiply high -// saturating rounding doubling multiply high - -// saturating doubling multiply accumulate long -// saturating doubling multiply subtract long - -// long multiply -// long multiply-poly -INTTYPES_WIDENING(vmull, __builtin_neon_vmull) -__ai poly16x8_t vmull_p8(poly8x8_t a, poly8x8_t b) { return (poly16x8_t){ __builtin_neon_vmull(a.val, b.val) }; } - -// saturating doubling long multiply - -// subtract - -// long subtract -INTTYPES_WIDENING(vsubl, __builtin_neon_vsubl) - -// wide subtract -INTTYPES_WIDE(vsubw, __builtin_neon_vsubw) - -// saturating subtract -INTTYPES_ADD_32(vqsub, __builtin_neon_vqsub) -INTTYPES_ADD_64(vqsub, __builtin_neon_vqsub) - -// halving subtract -INTTYPES_ADD_32(vhsub, __builtin_neon_vhsub) - -// subtract high half -// rounding subtract high half -INTTYPES_NARROWING(vsubhn, __builtin_neon_vsubhn) -INTTYPES_NARROWING(vrsubhn, __builtin_neon_vrsubhn) - -// compare eq -// compare ge -// compare le -// compare gt -// compare lt -INT_FLOAT_CMP_OP(vceq, ==) -INT_FLOAT_CMP_OP(vcge, >=) -INT_FLOAT_CMP_OP(vcle, <=) -INT_FLOAT_CMP_OP(vcgt, >) -INT_FLOAT_CMP_OP(vclt, <) - -// compare eq-poly - -// compare abs ge -// compare abs le -// compare abs gt -// compare abs lt -FLOATTYPES_CMP(vcage, __builtin_neon_vcage) -FLOATTYPES_CMP(vcale, __builtin_neon_vcale) -FLOATTYPES_CMP(vcagt, __builtin_neon_vcagt) -FLOATTYPES_CMP(vcalt, __builtin_neon_vcalt) - -// test bits - -// abs diff -INTTYPES_ADD_32(vabd, __builtin_neon_vabd) -FP_BINARY(vabd, __builtin_neon_vabd) - -// abs diff long -INTTYPES_WIDENING(vabdl, __builtin_neon_vabdl) - -// abs diff accumulate -// abs diff accumulate long - -// max -// min -INTTYPES_ADD_32(vmax, __builtin_neon_vmax) -FP_BINARY(vmax, __builtin_neon_vmax) -INTTYPES_ADD_32(vmin, __builtin_neon_vmin) -FP_BINARY(vmin, __builtin_neon_vmin) - -// pairwise add -// pairwise max -// pairwise min -INT_FP_PAIRWISE_ADD(vpadd, __builtin_neon_vpadd) -INT_FP_PAIRWISE_ADD(vpmax, __builtin_neon_vpmax) -INT_FP_PAIRWISE_ADD(vpmin, __builtin_neon_vpmin) - -// long pairwise add -// long pairwise add accumulate - -// recip -// recip sqrt -FP_BINARY(vrecps, __builtin_neon_vrecps) -FP_BINARY(vrsqrts, __builtin_neon_vrsqrts) - -// shl by vec -// saturating shl by vec -// rounding shl by vec -// saturating rounding shl by vec - -// shr by constant -// shl by constant -// rounding shr by constant -// shr by constant and accumulate -// rounding shr by constant and accumulate -// saturating shl by constant -// s->u saturating shl by constant -// narrowing saturating shr by constant -// s->u narrowing saturating shr by constant -// s->u rounding narrowing saturating shr by constant -// narrowing saturating shr by constant -// rounding narrowing shr by constant -// rounding narrowing saturating shr by constant -// widening shl by constant - -// shr and insert -// shl and insert - -// loads and stores, single vector -// loads and stores, lane -// loads, dupe - -// loads and stores, arrays - -// vget,vgetq lane -// vset, vsetq lane - -// vcreate -// vdup, vdupq -// vmov, vmovq -// vdup_lane, vdupq_lane -// vcombine -// vget_high, vget_low - -// vcvt {u,s} <-> f, f <-> f16 -// narrow -// long move (unpack) -// saturating narrow -// saturating narrow s->u - -// table lookup -// extended table lookup - -// mla with scalar -// widening mla with scalar -// widening saturating doubling mla with scalar -// mls with scalar -// widening mls with scalar -// widening saturating doubling mls with scalar -// mul by scalar -// long mul with scalar -// long mul by scalar -// saturating doubling long mul with scalar -// saturating doubling long mul by scalar -// saturating doubling mul high with scalar -// saturating doubling mul high by scalar -// saturating rounding doubling mul high with scalar -// saturating rounding doubling mul high by scalar -// mla with scalar -// widening mla with sclar -// widening saturating doubling mla with scalar -// mls with scalar -// widening mls with scalar -// widening saturating doubling mls with scalar - -// extract - -// endian swap (vrev) - -// negate - -// abs -// saturating abs -// saturating negate -// count leading signs -INT_UNARY(vabs, __builtin_neon_vabs) -FP_UNARY(vabs, __builtin_neon_vabs) -INT_UNARY(vqabs, __builtin_neon_vqabs) -INT_UNARY(vqneg, __builtin_neon_vqneg) -INT_UNARY(vcls, __builtin_neon_vcls) - -// count leading zeroes -// popcount - -// recip_est -// recip_sqrt_est - -// not-poly -// not - -// and -// or -// xor -// andn -// orn -INT_LOGICAL_OP(vand, &) -INT_LOGICAL_OP(vorr, |) -INT_LOGICAL_OP(veor, ^) -INT_LOGICAL_OP(vbic, &~) -INT_LOGICAL_OP(vorn, |~) - -// bitselect - -// transpose elts -// interleave elts -// deinterleave elts - -// vreinterpret - -#endif /* __ARM_NEON_H */ diff --git a/lib/Headers/arm_neon.td b/lib/Headers/arm_neon.td deleted file mode 100644 index 7ffbfb4a46a..00000000000 --- a/lib/Headers/arm_neon.td +++ /dev/null @@ -1,341 +0,0 @@ -//===--- arm_neon.td - ARM NEON compiler interface ------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the TableGen definitions from which the ARM NEON header -// file will be generated. See ARM document DUI0348B. -// -//===----------------------------------------------------------------------===// - -class Op; - -def OP_NONE : Op; -def OP_ADD : Op; -def OP_SUB : Op; -def OP_MUL : Op; -def OP_MLA : Op; -def OP_MLS : Op; -def OP_MUL_N : Op; -def OP_MLA_N : Op; -def OP_MLS_N : Op; -def OP_EQ : Op; -def OP_GE : Op; -def OP_LE : Op; -def OP_GT : Op; -def OP_LT : Op; -def OP_NEG : Op; -def OP_NOT : Op; -def OP_AND : Op; -def OP_OR : Op; -def OP_XOR : Op; -def OP_ANDN : Op; -def OP_ORN : Op; -def OP_CAST : Op; -def OP_HI : Op; -def OP_LO : Op; -def OP_CONC : Op; -def OP_DUP : Op; -def OP_SEL : Op; -def OP_REV64 : Op; -def OP_REV32 : Op; -def OP_REV16 : Op; - -class Inst { - string Prototype = p; - string Types = t; - Op Operand = o; - bit isShift = 0; -} - -// Used to generate Builtins.def -class SInst : Inst {} -class IInst : Inst {} -class WInst : Inst {} - -// prototype: return (arg, arg, ...) -// v: void -// t: best-fit integer (int/poly args) -// x: signed integer (int/float args) -// u: unsigned integer (int/float args) -// f: float (int args) -// d: default -// w: double width elements, same num elts -// n: double width elements, half num elts -// h: half width elements, double num elts -// e: half width elements, double num elts, unsigned -// i: constant int -// l: constant uint64 -// s: scalar of element type -// a: scalar of element type (splat to vector type) -// k: default elt width, double num elts -// #: array of default vectors -// p: pointer type -// c: const pointer type - -// sizes: -// c: char -// s: short -// i: int -// l: long -// f: float -// h: half-float - -// size modifiers: -// U: unsigned -// Q: 128b -// P: polynomial - -//////////////////////////////////////////////////////////////////////////////// -// E.3.1 Addition -def VADD : Inst<"ddd", "csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUl", OP_ADD>; -def VADDL : SInst<"wdd", "csiUcUsUi">; -def VADDW : SInst<"wwd", "csiUcUsUi">; -def VHADD : SInst<"ddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VRHADD : SInst<"ddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VQADD : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VADDHN : IInst<"dww", "csiUcUsUi">; -def VRADDHN : IInst<"dww", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.2 Multiplication -def VMUL : Inst<"ddd", "csifUcUsUiPcQcQsQiQfQUcQUsQUiQPc", OP_MUL>; -def VMLA : Inst<"dddd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_MLA>; -def VMLAL : SInst<"wwdd", "csiUcUsUi">; -def VMLS : Inst<"dddd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_MLS>; -def VMLSL : SInst<"wwdd", "csiUcUsUi">; -def VQDMULH : SInst<"ddd", "siQsQi">; -def VQRDMULH : SInst<"ddd", "siQsQi">; -def VQDMLAL : SInst<"wwdd", "si">; -def VQDMLSL : SInst<"wwdd", "si">; -def VMULL : SInst<"wdd", "csiUcUsUiPc">; -def VQDMULL : SInst<"wdd", "si">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.3 Subtraction -def VSUB : Inst<"ddd", "csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUl", OP_SUB>; -def VSUBL : SInst<"wdd", "csiUcUsUi">; -def VSUBW : SInst<"wwd", "csiUcUsUi">; -def VQSUB : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VHSUB : SInst<"ddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VSUBHN : IInst<"dww", "csiUcUsUi">; -def VRSUBHN : IInst<"dww", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.4 Comparison -def VCEQ : Inst<"udd", "csifUcUsUiPcQcQsQiQfQUcQUsQUiQPc", OP_EQ>; -def VCGE : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_GE>; -def VCLE : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_LE>; -def VCGT : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_GT>; -def VCLT : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_LT>; -def VCAGE : IInst<"udd", "fQf">; -def VCALE : IInst<"udd", "fQf">; -def VCAGT : IInst<"udd", "fQf">; -def VCALT : IInst<"udd", "fQf">; -def VTST : WInst<"udd", "csiUcUsUiPcQcQsQiQUcQUsQUiQPc">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.5 Absolute Difference -def VABD : SInst<"ddd", "csiUcUsUifQcQsQiQUcQUsQUiQf">; -def VABDL : SInst<"wdd", "csiUcUsUi">; -def VABA : SInst<"dddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VABAL : SInst<"wwdd", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.6 Max/Min -def VMAX : SInst<"ddd", "csiUcUsUifQcQsQiQUcQUsQUiQf">; -def VMIN : SInst<"ddd", "csiUcUsUifQcQsQiQUcQUsQUiQf">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.7 Pairdise Addition -def VPADD : IInst<"ddd", "csiUcUsUif">; -def VPADDL : SInst<"nd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VPADAL : SInst<"nnd", "csiUcUsUiQcQsQiQUcQUsQUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.8-9 Folding Max/Min -def VPMAX : SInst<"ddd", "csiUcUsUif">; -def VPMIN : SInst<"ddd", "csiUcUsUif">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.10 Reciprocal/Sqrt -def VRECPS : IInst<"ddd", "fQf">; -def VRSQRTS : IInst<"ddd", "fQf">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.11 Shifts by signed variable -def VSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VRSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQRSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.12 Shifts by constant -let isShift = 1 in { -def VSHR_N : SInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VSHL_N : IInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VRSHR_N : SInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VSRA_N : SInst<"dddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VRSRA_N : SInst<"dddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQSHL_N : SInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQSHLU_N : SInst<"udi", "csilQcQsQiQl">; -def VSHRN_N : IInst<"hki", "silUsUiUl">; -def VQSHRUN_N : SInst<"eki", "sil">; -def VQRSHRUN_N : SInst<"eki", "sil">; -def VQSHRN_N : SInst<"hki", "silUsUiUl">; -def VRSHRN_N : IInst<"hki", "silUsUiUl">; -def VQRSHRN_N : SInst<"hki", "silUsUiUl">; -def VSHLL_N : SInst<"wdi", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.13 Shifts with insert -def VSRI_N : WInst<"dddi", "csilUcUsUiUlPcPsQcQsQiQlQUcQUsQUiQUlQPcQPs">; -def VSLI_N : WInst<"dddi", "csilUcUsUiUlPcPsQcQsQiQlQUcQUsQUiQUlQPcQPs">; -} - -//////////////////////////////////////////////////////////////////////////////// -// E.3.14 Loads and stores of a single vector -def VLD1 : WInst<"dc", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD1_LANE : WInst<"dci", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD1_DUP : WInst<"dc", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST1 : WInst<"vpd", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST1_LANE : WInst<"vpdi", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.15 Loads and stores of an N-element structure -def VLD2 : WInst<"2c", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD3 : WInst<"3c", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD4 : WInst<"4c", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD2_DUP : WInst<"2c", "UcUsUiUlcsilhfPcPs">; -def VLD3_DUP : WInst<"3c", "UcUsUiUlcsilhfPcPs">; -def VLD4_DUP : WInst<"4c", "UcUsUiUlcsilhfPcPs">; -def VLD2_LANE : WInst<"2ci", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VLD3_LANE : WInst<"3ci", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VLD4_LANE : WInst<"4ci", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VST2 : WInst<"vp2", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST3 : WInst<"vp3", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST4 : WInst<"vp4", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST2_LANE : WInst<"vp2i", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VST3_LANE : WInst<"vp3i", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VST4_LANE : WInst<"vp4i", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.16 Extract lanes from a vector -def VGET_LANE : IInst<"sdi", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.17 Set lanes within a vector -def VSET_LANE : IInst<"dsdi", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.18 Initialize a vector from bit pattern -def VCREATE: Inst<"dl", "csihfUcUsUiUlPcPsl", OP_CAST>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.19 Set all lanes to same value -def VDUP_N : Inst<"ds", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl", OP_DUP>; -def VMOV_N : Inst<"ds", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl", OP_DUP>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.20 Combining vectors -def VCOMBINE : Inst<"kdd", "csilhfUcUsUiUlPcPs", OP_CONC>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.21 Splitting vectors -def VGET_HIGH : Inst<"dk", "csilhfUcUsUiUlPcPs", OP_HI>; -def VGET_LOW : Inst<"dk", "csilhfUcUsUiUlPcPs", OP_LO>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.22 Converting vectors -def VCVT_S32 : SInst<"xd", "fQf">; -def VCVT_U32 : SInst<"ud", "fQf">; -def VCVT_F16 : SInst<"hk", "f">; -def VCVT_N_S32 : SInst<"xdi", "fQf">; -def VCVT_N_U32 : SInst<"udi", "fQf">; -def VCVT_F32 : SInst<"fd", "iUiQiQUi">; -def VCVT_F32_F16 : SInst<"kh", "f">; -def VCVT_N_F32 : SInst<"fdi", "iUiQiQUi">; -def VMOVN : IInst<"hk", "silUsUiUl">; -def VMOVL : SInst<"wd", "csiUcUsUi">; -def VQMOVN : SInst<"hk", "silUsUiUl">; -def VQMOVUN : SInst<"ek", "sil">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.23-24 Table lookup, Extended table lookup -def VTBL1 : WInst<"ddt", "UccPc">; -def VTBL2 : WInst<"d2t", "UccPc">; -def VTBL3 : WInst<"d3t", "UccPc">; -def VTBL4 : WInst<"d4t", "UccPc">; -def VTBX1 : WInst<"dddt", "UccPc">; -def VTBX2 : WInst<"dd2t", "UccPc">; -def VTBX3 : WInst<"dd3t", "UccPc">; -def VTBX4 : WInst<"dd4t", "UccPc">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.25 Operations with a scalar value -def VMLA_LANE : IInst<"ddddi", "siUsUifQsQiQUsQUiQf">; -def VMLAL_LANE : SInst<"wwddi", "siUsUi">; -def VQDMLAL_LANE : SInst<"wwddi", "si">; -def VMLS_LANE : IInst<"ddddi", "siUsUifQsQiQUsQUiQf">; -def VMLSL_LANE : SInst<"wwddi", "siUsUi">; -def VQDMLSL_LANE : SInst<"wwddi", "si">; -def VMUL_N : Inst<"dds", "sifUsUiQsQiQfQUsQUi", OP_MUL_N>; -def VMULL_N : SInst<"wda", "siUsUi">; -def VMULL_LANE : SInst<"wddi", "siUsUi">; -def VQDMULL_N : SInst<"wda", "si">; -def VQDMULL_LANE : SInst<"wddi", "si">; -def VQDMULH_N : SInst<"dda", "siQsQi">; -def VQDMULH_LANE : SInst<"dddi", "siQsQi">; -def VQRDMULH_N : SInst<"dda", "siQsQi">; -def VQRDMULH_LANE : SInst<"dddi", "siQsQi">; -def VMLA_N : Inst<"ddda", "siUsUifQsQiQUsQUiQf", OP_MLA_N>; -def VMLAL_N : SInst<"wwda", "siUsUi">; -def VQDMLAL_N : SInst<"wwda", "si">; -def VMLS_N : Inst<"ddds", "siUsUifQsQiQUsQUiQf", OP_MLS_N>; -def VMLSL_N : SInst<"wwda", "siUsUi">; -def VQDMLSL_N : SInst<"wwda", "si">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.26 Vector Extract -def VEXT : WInst<"dddi", "cUcPcsUsPsiUilUlQcQUcQPcQsQUsQPsQiQUiQlQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.27 Reverse vector elements (sdap endianness) -def VREV64 : Inst<"dd", "csiUcUsUiPcPsfQcQsQiQUcQUsQUiQPcQPsQf", OP_REV64>; -def VREV32 : Inst<"dd", "csUcUsPcQcQsQUcQUsQPc", OP_REV32>; -def VREV16 : Inst<"dd", "cUcPcQcQUcQPc", OP_REV16>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.28 Other single operand arithmetic -def VABS : SInst<"dd", "csifQcQsQiQf">; -def VQABS : SInst<"dd", "csiQcQsQi">; -def VNEG : Inst<"dd", "csifQcQsQiQf", OP_NEG>; -def VQNEG : SInst<"dd", "csiQcQsQi">; -def VCLS : SInst<"dd", "csiQcQsQi">; -def VCLZ : IInst<"dd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VCNT : WInst<"dd", "UccPcQUcQcQPc">; -def VRECPE : SInst<"dd", "fUiQfQUi">; -def VRSQRTE : SInst<"dd", "fUiQfQUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.29 Logical operations -def VMVN : Inst<"dd", "csiUcUsUiPcQcQsQiQUcQUsQUiQPc", OP_NOT>; -def VAND : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_AND>; -def VORR : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_OR>; -def VEOR : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_XOR>; -def VBIC : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_ANDN>; -def VORN : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_ORN>; -def VBSL : Inst<"dudd", "csilUcUsUiUlfPcPsQcQsQiQlQUcQUsQUiQUlQfQPcQPs", OP_SEL>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.30 Transposition operations -def VTRN: WInst<"2dd", "csiUcUsUifPcPsQcQsQiQUcQUsQUiQfQPcQPs">; -def VZIP: WInst<"2dd", "csUcUsfPcPsQcQsQiQUcQUsQUiQfQPcQPs">; -def VUZP: WInst<"2dd", "csiUcUsUifPcPsQcQsQiQUcQUsQUiQfQPcQPs">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.31 Vector reinterpret cast operations diff --git a/tools/CIndex/CIndex.cpp b/tools/CIndex/CIndex.cpp deleted file mode 100644 index 9cdb9659fe9..00000000000 --- a/tools/CIndex/CIndex.cpp +++ /dev/null @@ -1,2589 +0,0 @@ -//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the main API hooks in the Clang-C Source Indexing -// library. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CXCursor.h" -#include "CXSourceLocation.h" -#include "CIndexDiagnostic.h" - -#include "clang/Basic/Version.h" - -#include "clang/AST/DeclVisitor.h" -#include "clang/AST/StmtVisitor.h" -#include "clang/AST/TypeLocVisitor.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/FrontendDiagnostic.h" -#include "clang/Lex/Lexer.h" -#include "clang/Lex/PreprocessingRecord.h" -#include "clang/Lex/Preprocessor.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/System/Program.h" -#include "llvm/System/Signals.h" - -// Needed to define L_TMPNAM on some systems. -#include - -using namespace clang; -using namespace clang::cxcursor; -using namespace clang::cxstring; - -//===----------------------------------------------------------------------===// -// Crash Reporting. -//===----------------------------------------------------------------------===// - -#ifdef __APPLE__ -#define USE_CRASHTRACER -#include "clang/Analysis/Support/SaveAndRestore.h" -// Integrate with crash reporter. -extern "C" const char *__crashreporter_info__; -#define NUM_CRASH_STRINGS 32 -static unsigned crashtracer_counter = 0; -static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 }; -static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 }; -static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 }; - -static unsigned SetCrashTracerInfo(const char *str, - llvm::SmallString<1024> &AggStr) { - - unsigned slot = 0; - while (crashtracer_strings[slot]) { - if (++slot == NUM_CRASH_STRINGS) - slot = 0; - } - crashtracer_strings[slot] = str; - crashtracer_counter_id[slot] = ++crashtracer_counter; - - // We need to create an aggregate string because multiple threads - // may be in this method at one time. The crash reporter string - // will attempt to overapproximate the set of in-flight invocations - // of this function. Race conditions can still cause this goal - // to not be achieved. - { - llvm::raw_svector_ostream Out(AggStr); - for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i) - if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n'; - } - __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str(); - return slot; -} - -static void ResetCrashTracerInfo(unsigned slot) { - unsigned max_slot = 0; - unsigned max_value = 0; - - crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0; - - for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i) - if (agg_crashtracer_strings[i] && - crashtracer_counter_id[i] > max_value) { - max_slot = i; - max_value = crashtracer_counter_id[i]; - } - - __crashreporter_info__ = agg_crashtracer_strings[max_slot]; -} - -namespace { -class ArgsCrashTracerInfo { - llvm::SmallString<1024> CrashString; - llvm::SmallString<1024> AggregateString; - unsigned crashtracerSlot; -public: - ArgsCrashTracerInfo(llvm::SmallVectorImpl &Args) - : crashtracerSlot(0) - { - { - llvm::raw_svector_ostream Out(CrashString); - Out << "ClangCIndex [" << getClangFullVersion() << "]" - << "[createTranslationUnitFromSourceFile]: clang"; - for (llvm::SmallVectorImpl::iterator I=Args.begin(), - E=Args.end(); I!=E; ++I) - Out << ' ' << *I; - } - crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(), - AggregateString); - } - - ~ArgsCrashTracerInfo() { - ResetCrashTracerInfo(crashtracerSlot); - } -}; -} -#endif - -/// \brief The result of comparing two source ranges. -enum RangeComparisonResult { - /// \brief Either the ranges overlap or one of the ranges is invalid. - RangeOverlap, - - /// \brief The first range ends before the second range starts. - RangeBefore, - - /// \brief The first range starts after the second range ends. - RangeAfter -}; - -/// \brief Compare two source ranges to determine their relative position in -/// the translation unit. -static RangeComparisonResult RangeCompare(SourceManager &SM, - SourceRange R1, - SourceRange R2) { - assert(R1.isValid() && "First range is invalid?"); - assert(R2.isValid() && "Second range is invalid?"); - if (R1.getEnd() == R2.getBegin() || - SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) - return RangeBefore; - if (R2.getEnd() == R1.getBegin() || - SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) - return RangeAfter; - return RangeOverlap; -} - -/// \brief Translate a Clang source range into a CIndex source range. -/// -/// Clang internally represents ranges where the end location points to the -/// start of the token at the end. However, for external clients it is more -/// useful to have a CXSourceRange be a proper half-open interval. This routine -/// does the appropriate translation. -CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, - const LangOptions &LangOpts, - SourceRange R) { - // We want the last character in this location, so we will adjust the - // location accordingly. - // FIXME: How do do this with a macro instantiation location? - SourceLocation EndLoc = R.getEnd(); - if (!EndLoc.isInvalid() && EndLoc.isFileID()) { - unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts); - EndLoc = EndLoc.getFileLocWithOffset(Length); - } - - CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, - R.getBegin().getRawEncoding(), - EndLoc.getRawEncoding() }; - return Result; -} - -//===----------------------------------------------------------------------===// -// Cursor visitor. -//===----------------------------------------------------------------------===// - -namespace { - -// Cursor visitor. -class CursorVisitor : public DeclVisitor, - public TypeLocVisitor, - public StmtVisitor -{ - /// \brief The translation unit we are traversing. - ASTUnit *TU; - - /// \brief The parent cursor whose children we are traversing. - CXCursor Parent; - - /// \brief The declaration that serves at the parent of any statement or - /// expression nodes. - Decl *StmtParent; - - /// \brief The visitor function. - CXCursorVisitor Visitor; - - /// \brief The opaque client data, to be passed along to the visitor. - CXClientData ClientData; - - // MaxPCHLevel - the maximum PCH level of declarations that we will pass on - // to the visitor. Declarations with a PCH level greater than this value will - // be suppressed. - unsigned MaxPCHLevel; - - /// \brief When valid, a source range to which the cursor should restrict - /// its search. - SourceRange RegionOfInterest; - - using DeclVisitor::Visit; - using TypeLocVisitor::Visit; - using StmtVisitor::Visit; - - /// \brief Determine whether this particular source range comes before, comes - /// after, or overlaps the region of interest. - /// - /// \param R a half-open source range retrieved from the abstract syntax tree. - RangeComparisonResult CompareRegionOfInterest(SourceRange R); - -public: - CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData, - unsigned MaxPCHLevel, - SourceRange RegionOfInterest = SourceRange()) - : TU(TU), Visitor(Visitor), ClientData(ClientData), - MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest) - { - Parent.kind = CXCursor_NoDeclFound; - Parent.data[0] = 0; - Parent.data[1] = 0; - Parent.data[2] = 0; - StmtParent = 0; - } - - bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false); - - std::pair - getPreprocessedEntities(); - - bool VisitChildren(CXCursor Parent); - - // Declaration visitors - bool VisitAttributes(Decl *D); - bool VisitBlockDecl(BlockDecl *B); - bool VisitDeclContext(DeclContext *DC); - bool VisitTranslationUnitDecl(TranslationUnitDecl *D); - bool VisitTypedefDecl(TypedefDecl *D); - bool VisitTagDecl(TagDecl *D); - bool VisitEnumConstantDecl(EnumConstantDecl *D); - bool VisitDeclaratorDecl(DeclaratorDecl *DD); - bool VisitFunctionDecl(FunctionDecl *ND); - bool VisitFieldDecl(FieldDecl *D); - bool VisitVarDecl(VarDecl *); - bool VisitObjCMethodDecl(ObjCMethodDecl *ND); - bool VisitObjCContainerDecl(ObjCContainerDecl *D); - bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); - bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); - bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); - bool VisitObjCImplDecl(ObjCImplDecl *D); - bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); - bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); - // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations, - // etc. - // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. - bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D); - bool VisitObjCClassDecl(ObjCClassDecl *D); - - // Type visitors - // FIXME: QualifiedTypeLoc doesn't provide any location information - bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL); - bool VisitTypedefTypeLoc(TypedefTypeLoc TL); - bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL); - bool VisitTagTypeLoc(TagTypeLoc TL); - // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information - bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL); - bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL); - bool VisitPointerTypeLoc(PointerTypeLoc TL); - bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL); - bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL); - bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL); - bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL); - bool VisitFunctionTypeLoc(FunctionTypeLoc TL); - bool VisitArrayTypeLoc(ArrayTypeLoc TL); - // FIXME: Implement for TemplateSpecializationTypeLoc - // FIXME: Implement visitors here when the unimplemented TypeLocs get - // implemented - bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL); - bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL); - - // Statement visitors - bool VisitStmt(Stmt *S); - bool VisitDeclStmt(DeclStmt *S); - // FIXME: LabelStmt label? - bool VisitIfStmt(IfStmt *S); - bool VisitSwitchStmt(SwitchStmt *S); - bool VisitWhileStmt(WhileStmt *S); - bool VisitForStmt(ForStmt *S); - - // Expression visitors - bool VisitBlockExpr(BlockExpr *B); - bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E); - bool VisitExplicitCastExpr(ExplicitCastExpr *E); - bool VisitObjCMessageExpr(ObjCMessageExpr *E); - bool VisitObjCEncodeExpr(ObjCEncodeExpr *E); - bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); -}; - -} // end anonymous namespace - -RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { - return RangeCompare(TU->getSourceManager(), R, RegionOfInterest); -} - -/// \brief Visit the given cursor and, if requested by the visitor, -/// its children. -/// -/// \param Cursor the cursor to visit. -/// -/// \param CheckRegionOfInterest if true, then the caller already checked that -/// this cursor is within the region of interest. -/// -/// \returns true if the visitation should be aborted, false if it -/// should continue. -bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { - if (clang_isInvalid(Cursor.kind)) - return false; - - if (clang_isDeclaration(Cursor.kind)) { - Decl *D = getCursorDecl(Cursor); - assert(D && "Invalid declaration cursor"); - if (D->getPCHLevel() > MaxPCHLevel) - return false; - - if (D->isImplicit()) - return false; - } - - // If we have a range of interest, and this cursor doesn't intersect with it, - // we're done. - if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { - SourceRange Range = - cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor)); - if (Range.isInvalid() || CompareRegionOfInterest(Range)) - return false; - } - - switch (Visitor(Cursor, Parent, ClientData)) { - case CXChildVisit_Break: - return true; - - case CXChildVisit_Continue: - return false; - - case CXChildVisit_Recurse: - return VisitChildren(Cursor); - } - - return false; -} - -std::pair -CursorVisitor::getPreprocessedEntities() { - PreprocessingRecord &PPRec - = *TU->getPreprocessor().getPreprocessingRecord(); - - bool OnlyLocalDecls - = !TU->isMainFileAST() && TU->getOnlyLocalDecls(); - - // There is no region of interest; we have to walk everything. - if (RegionOfInterest.isInvalid()) - return std::make_pair(PPRec.begin(OnlyLocalDecls), - PPRec.end(OnlyLocalDecls)); - - // Find the file in which the region of interest lands. - SourceManager &SM = TU->getSourceManager(); - std::pair Begin - = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin()); - std::pair End - = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd()); - - // The region of interest spans files; we have to walk everything. - if (Begin.first != End.first) - return std::make_pair(PPRec.begin(OnlyLocalDecls), - PPRec.end(OnlyLocalDecls)); - - ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap - = TU->getPreprocessedEntitiesByFile(); - if (ByFileMap.empty()) { - // Build the mapping from files to sets of preprocessed entities. - for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls), - EEnd = PPRec.end(OnlyLocalDecls); - E != EEnd; ++E) { - std::pair P - = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin()); - ByFileMap[P.first].push_back(*E); - } - } - - return std::make_pair(ByFileMap[Begin.first].begin(), - ByFileMap[Begin.first].end()); -} - -/// \brief Visit the children of the given cursor. -/// -/// \returns true if the visitation should be aborted, false if it -/// should continue. -bool CursorVisitor::VisitChildren(CXCursor Cursor) { - if (clang_isReference(Cursor.kind)) { - // By definition, references have no children. - return false; - } - - // Set the Parent field to Cursor, then back to its old value once we're - // done. - class SetParentRAII { - CXCursor &Parent; - Decl *&StmtParent; - CXCursor OldParent; - - public: - SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent) - : Parent(Parent), StmtParent(StmtParent), OldParent(Parent) - { - Parent = NewParent; - if (clang_isDeclaration(Parent.kind)) - StmtParent = getCursorDecl(Parent); - } - - ~SetParentRAII() { - Parent = OldParent; - if (clang_isDeclaration(Parent.kind)) - StmtParent = getCursorDecl(Parent); - } - } SetParent(Parent, StmtParent, Cursor); - - if (clang_isDeclaration(Cursor.kind)) { - Decl *D = getCursorDecl(Cursor); - assert(D && "Invalid declaration cursor"); - return VisitAttributes(D) || Visit(D); - } - - if (clang_isStatement(Cursor.kind)) - return Visit(getCursorStmt(Cursor)); - if (clang_isExpression(Cursor.kind)) - return Visit(getCursorExpr(Cursor)); - - if (clang_isTranslationUnit(Cursor.kind)) { - ASTUnit *CXXUnit = getCursorASTUnit(Cursor); - if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && - RegionOfInterest.isInvalid()) { - const std::vector &TLDs = CXXUnit->getTopLevelDecls(); - for (std::vector::const_iterator it = TLDs.begin(), - ie = TLDs.end(); it != ie; ++it) { - if (Visit(MakeCXCursor(*it, CXXUnit), true)) - return true; - } - } else if (VisitDeclContext( - CXXUnit->getASTContext().getTranslationUnitDecl())) - return true; - - // Walk the preprocessing record. - if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { - // FIXME: Once we have the ability to deserialize a preprocessing record, - // do so. - PreprocessingRecord::iterator E, EEnd; - for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) { - if (MacroInstantiation *MI = dyn_cast(*E)) { - if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit))) - return true; - - continue; - } - - if (MacroDefinition *MD = dyn_cast(*E)) { - if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit))) - return true; - - continue; - } - } - } - return false; - } - - // Nothing to visit at the moment. - return false; -} - -bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { - for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I) - if (Decl *D = *I) - if (Visit(D)) - return true; - - return Visit(MakeCXCursor(B->getBody(), StmtParent, TU)); -} - -bool CursorVisitor::VisitDeclContext(DeclContext *DC) { - for (DeclContext::decl_iterator - I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) { - - CXCursor Cursor = MakeCXCursor(*I, TU); - - if (RegionOfInterest.isValid()) { - SourceRange Range = - cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor)); - if (Range.isInvalid()) - continue; - - switch (CompareRegionOfInterest(Range)) { - case RangeBefore: - // This declaration comes before the region of interest; skip it. - continue; - - case RangeAfter: - // This declaration comes after the region of interest; we're done. - return false; - - case RangeOverlap: - // This declaration overlaps the region of interest; visit it. - break; - } - } - - if (Visit(Cursor, true)) - return true; - } - - return false; -} - -bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { - llvm_unreachable("Translation units are visited directly by Visit()"); - return false; -} - -bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { - if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) - return Visit(TSInfo->getTypeLoc()); - - return false; -} - -bool CursorVisitor::VisitTagDecl(TagDecl *D) { - return VisitDeclContext(D); -} - -bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { - if (Expr *Init = D->getInitExpr()) - return Visit(MakeCXCursor(Init, StmtParent, TU)); - return false; -} - -bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { - if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return false; -} - -bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { - if (VisitDeclaratorDecl(ND)) - return true; - - if (ND->isThisDeclarationADefinition() && - Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { - if (VisitDeclaratorDecl(D)) - return true; - - if (Expr *BitWidth = D->getBitWidth()) - return Visit(MakeCXCursor(BitWidth, StmtParent, TU)); - - return false; -} - -bool CursorVisitor::VisitVarDecl(VarDecl *D) { - if (VisitDeclaratorDecl(D)) - return true; - - if (Expr *Init = D->getInit()) - return Visit(MakeCXCursor(Init, StmtParent, TU)); - - return false; -} - -bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { - if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - for (ObjCMethodDecl::param_iterator P = ND->param_begin(), - PEnd = ND->param_end(); - P != PEnd; ++P) { - if (Visit(MakeCXCursor(*P, TU))) - return true; - } - - if (ND->isThisDeclarationADefinition() && - Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { - return VisitDeclContext(D); -} - -bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { - if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), - TU))) - return true; - - ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); - for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), - E = ND->protocol_end(); I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return VisitObjCContainerDecl(ND); -} - -bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { - ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); - for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), - E = PID->protocol_end(); I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return VisitObjCContainerDecl(PID); -} - -bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { - // Issue callbacks for super class. - if (D->getSuperClass() && - Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), - D->getSuperClassLoc(), - TU))) - return true; - - ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); - for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), - E = D->protocol_end(); I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return VisitObjCContainerDecl(D); -} - -bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { - return VisitObjCContainerDecl(D); -} - -bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { - // 'ID' could be null when dealing with invalid code. - if (ObjCInterfaceDecl *ID = D->getClassInterface()) - if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) - return true; - - return VisitObjCImplDecl(D); -} - -bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { -#if 0 - // Issue callbacks for super class. - // FIXME: No source location information! - if (D->getSuperClass() && - Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), - D->getSuperClassLoc(), - TU))) - return true; -#endif - - return VisitObjCImplDecl(D); -} - -bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { - ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); - for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(), - E = D->protocol_end(); - I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) { - for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C) - if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { - ASTContext &Context = TU->getASTContext(); - - // Some builtin types (such as Objective-C's "id", "sel", and - // "Class") have associated declarations. Create cursors for those. - QualType VisitType; - switch (TL.getType()->getAs()->getKind()) { - case BuiltinType::Void: - case BuiltinType::Bool: - case BuiltinType::Char_U: - case BuiltinType::UChar: - case BuiltinType::Char16: - case BuiltinType::Char32: - case BuiltinType::UShort: - case BuiltinType::UInt: - case BuiltinType::ULong: - case BuiltinType::ULongLong: - case BuiltinType::UInt128: - case BuiltinType::Char_S: - case BuiltinType::SChar: - case BuiltinType::WChar: - case BuiltinType::Short: - case BuiltinType::Int: - case BuiltinType::Long: - case BuiltinType::LongLong: - case BuiltinType::Int128: - case BuiltinType::Float: - case BuiltinType::Double: - case BuiltinType::LongDouble: - case BuiltinType::NullPtr: - case BuiltinType::Overload: - case BuiltinType::Dependent: - break; - - case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor? - break; - - case BuiltinType::ObjCId: - VisitType = Context.getObjCIdType(); - break; - - case BuiltinType::ObjCClass: - VisitType = Context.getObjCClassType(); - break; - - case BuiltinType::ObjCSel: - VisitType = Context.getObjCSelType(); - break; - } - - if (!VisitType.isNull()) { - if (const TypedefType *Typedef = VisitType->getAs()) - return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), - TU)); - } - - return false; -} - -bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { - return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU)); -} - -bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { - return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); -} - -bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { - return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); -} - -bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { - if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) - return true; - - for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { - if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), - TU))) - return true; - } - - return false; -} - -bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { - if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc())) - return true; - - if (TL.hasProtocolsAsWritten()) { - for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { - if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), - TL.getProtocolLoc(I), - TU))) - return true; - } - } - - return false; -} - -bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) { - if (Visit(TL.getResultLoc())) - return true; - - for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) - if (Decl *D = TL.getArg(I)) - if (Visit(MakeCXCursor(D, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { - if (Visit(TL.getElementLoc())) - return true; - - if (Expr *Size = TL.getSizeExpr()) - return Visit(MakeCXCursor(Size, StmtParent, TU)); - - return false; -} - -bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { - return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); -} - -bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { - if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) - return Visit(TSInfo->getTypeLoc()); - - return false; -} - -bool CursorVisitor::VisitStmt(Stmt *S) { - for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end(); - Child != ChildEnd; ++Child) { - if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU))) - return true; - } - - return false; -} - -bool CursorVisitor::VisitDeclStmt(DeclStmt *S) { - for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); - D != DEnd; ++D) { - if (*D && Visit(MakeCXCursor(*D, TU))) - return true; - } - - return false; -} - -bool CursorVisitor::VisitIfStmt(IfStmt *S) { - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU))) - return true; - if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) { - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitWhileStmt(WhileStmt *S) { - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitForStmt(ForStmt *S) { - if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU))) - return true; - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU))) - return true; - if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitBlockExpr(BlockExpr *B) { - return Visit(B->getBlockDecl()); -} - -bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { - if (E->isArgumentType()) { - if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo()) - return Visit(TSInfo->getTypeLoc()); - - return false; - } - - return VisitExpr(E); -} - -bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { - if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return VisitCastExpr(E); -} - -bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { - if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return VisitExpr(E); -} - -bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) { - if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return VisitExpr(E); -} - -bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { - return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc()); -} - - -bool CursorVisitor::VisitAttributes(Decl *D) { - for (const Attr *A = D->getAttrs(); A; A = A->getNext()) - if (Visit(MakeCXCursor(A, D, TU))) - return true; - - return false; -} - -extern "C" { -CXIndex clang_createIndex(int excludeDeclarationsFromPCH, - int displayDiagnostics) { - CIndexer *CIdxr = new CIndexer(); - if (excludeDeclarationsFromPCH) - CIdxr->setOnlyLocalDecls(); - if (displayDiagnostics) - CIdxr->setDisplayDiagnostics(); - return CIdxr; -} - -void clang_disposeIndex(CXIndex CIdx) { - if (CIdx) - delete static_cast(CIdx); -} - -void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) { - if (CIdx) { - CIndexer *CXXIdx = static_cast(CIdx); - CXXIdx->setUseExternalASTGeneration(value); - } -} - -CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, - const char *ast_filename) { - if (!CIdx) - return 0; - - CIndexer *CXXIdx = static_cast(CIdx); - - llvm::IntrusiveRefCntPtr Diags; - return ASTUnit::LoadFromPCHFile(ast_filename, Diags, - CXXIdx->getOnlyLocalDecls(), - 0, 0, true); -} - -CXTranslationUnit -clang_createTranslationUnitFromSourceFile(CXIndex CIdx, - const char *source_filename, - int num_command_line_args, - const char **command_line_args, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files) { - if (!CIdx) - return 0; - - CIndexer *CXXIdx = static_cast(CIdx); - - // Configure the diagnostics. - DiagnosticOptions DiagOpts; - llvm::IntrusiveRefCntPtr Diags; - Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); - - llvm::SmallVector RemappedFiles; - for (unsigned I = 0; I != num_unsaved_files; ++I) { - llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); - const llvm::MemoryBuffer *Buffer - = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); - RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, - Buffer)); - } - - if (!CXXIdx->getUseExternalASTGeneration()) { - llvm::SmallVector Args; - - // The 'source_filename' argument is optional. If the caller does not - // specify it then it is assumed that the source file is specified - // in the actual argument list. - if (source_filename) - Args.push_back(source_filename); - Args.insert(Args.end(), command_line_args, - command_line_args + num_command_line_args); - Args.push_back("-Xclang"); - Args.push_back("-detailed-preprocessing-record"); - unsigned NumErrors = Diags->getNumErrors(); - -#ifdef USE_CRASHTRACER - ArgsCrashTracerInfo ACTI(Args); -#endif - - llvm::OwningPtr Unit( - ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), - Diags, - CXXIdx->getClangResourcesPath(), - CXXIdx->getOnlyLocalDecls(), - RemappedFiles.data(), - RemappedFiles.size(), - /*CaptureDiagnostics=*/true)); - - // FIXME: Until we have broader testing, just drop the entire AST if we - // encountered an error. - if (NumErrors != Diags->getNumErrors()) { - // Make sure to check that 'Unit' is non-NULL. - if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { - for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), - DEnd = Unit->stored_diag_end(); - D != DEnd; ++D) { - CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); - CXString Msg = clang_formatDiagnostic(&Diag, - clang_defaultDiagnosticDisplayOptions()); - fprintf(stderr, "%s\n", clang_getCString(Msg)); - clang_disposeString(Msg); - } -#ifdef LLVM_ON_WIN32 - // On Windows, force a flush, since there may be multiple copies of - // stderr and stdout in the file system, all with different buffers - // but writing to the same device. - fflush(stderr); -#endif - } - } - - return Unit.take(); - } - - // Build up the arguments for invoking 'clang'. - std::vector argv; - - // First add the complete path to the 'clang' executable. - llvm::sys::Path ClangPath = static_cast(CIdx)->getClangPath(); - argv.push_back(ClangPath.c_str()); - - // Add the '-emit-ast' option as our execution mode for 'clang'. - argv.push_back("-emit-ast"); - - // The 'source_filename' argument is optional. If the caller does not - // specify it then it is assumed that the source file is specified - // in the actual argument list. - if (source_filename) - argv.push_back(source_filename); - - // Generate a temporary name for the AST file. - argv.push_back("-o"); - char astTmpFile[L_tmpnam]; - argv.push_back(tmpnam(astTmpFile)); - - // Remap any unsaved files to temporary files. - std::vector TemporaryFiles; - std::vector RemapArgs; - if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles)) - return 0; - - // The pointers into the elements of RemapArgs are stable because we - // won't be adding anything to RemapArgs after this point. - for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i) - argv.push_back(RemapArgs[i].c_str()); - - // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'. - for (int i = 0; i < num_command_line_args; ++i) - if (const char *arg = command_line_args[i]) { - if (strcmp(arg, "-o") == 0) { - ++i; // Also skip the matching argument. - continue; - } - if (strcmp(arg, "-emit-ast") == 0 || - strcmp(arg, "-c") == 0 || - strcmp(arg, "-fsyntax-only") == 0) { - continue; - } - - // Keep the argument. - argv.push_back(arg); - } - - // Generate a temporary name for the diagnostics file. - char tmpFileResults[L_tmpnam]; - char *tmpResultsFileName = tmpnam(tmpFileResults); - llvm::sys::Path DiagnosticsFile(tmpResultsFileName); - TemporaryFiles.push_back(DiagnosticsFile); - argv.push_back("-fdiagnostics-binary"); - - argv.push_back("-Xclang"); - argv.push_back("-detailed-preprocessing-record"); - - // Add the null terminator. - argv.push_back(NULL); - - // Invoke 'clang'. - llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null - // on Unix or NUL (Windows). - std::string ErrMsg; - const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile, - NULL }; - llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL, - /* redirects */ &Redirects[0], - /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg); - - if (!ErrMsg.empty()) { - std::string AllArgs; - for (std::vector::iterator I = argv.begin(), E = argv.end(); - I != E; ++I) { - AllArgs += ' '; - if (*I) - AllArgs += *I; - } - - Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg; - } - - ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags, - CXXIdx->getOnlyLocalDecls(), - RemappedFiles.data(), - RemappedFiles.size(), - /*CaptureDiagnostics=*/true); - if (ATU) { - LoadSerializedDiagnostics(DiagnosticsFile, - num_unsaved_files, unsaved_files, - ATU->getFileManager(), - ATU->getSourceManager(), - ATU->getStoredDiagnostics()); - } else if (CXXIdx->getDisplayDiagnostics()) { - // We failed to load the ASTUnit, but we can still deserialize the - // diagnostics and emit them. - FileManager FileMgr; - Diagnostic Diag; - SourceManager SourceMgr(Diag); - // FIXME: Faked LangOpts! - LangOptions LangOpts; - llvm::SmallVector Diags; - LoadSerializedDiagnostics(DiagnosticsFile, - num_unsaved_files, unsaved_files, - FileMgr, SourceMgr, Diags); - for (llvm::SmallVector::iterator D = Diags.begin(), - DEnd = Diags.end(); - D != DEnd; ++D) { - CXStoredDiagnostic Diag(*D, LangOpts); - CXString Msg = clang_formatDiagnostic(&Diag, - clang_defaultDiagnosticDisplayOptions()); - fprintf(stderr, "%s\n", clang_getCString(Msg)); - clang_disposeString(Msg); - } - -#ifdef LLVM_ON_WIN32 - // On Windows, force a flush, since there may be multiple copies of - // stderr and stdout in the file system, all with different buffers - // but writing to the same device. - fflush(stderr); -#endif - } - - if (ATU) { - // Make the translation unit responsible for destroying all temporary files. - for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) - ATU->addTemporaryFile(TemporaryFiles[i]); - ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName())); - } else { - // Destroy all of the temporary files now; they can't be referenced any - // longer. - llvm::sys::Path(astTmpFile).eraseFromDisk(); - for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) - TemporaryFiles[i].eraseFromDisk(); - } - - return ATU; -} - -void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { - if (CTUnit) - delete static_cast(CTUnit); -} - -CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { - if (!CTUnit) - return createCXString(""); - - ASTUnit *CXXUnit = static_cast(CTUnit); - return createCXString(CXXUnit->getOriginalSourceFileName(), true); -} - -CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { - CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; - return Result; -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXSourceLocation and CXSourceRange Operations. -//===----------------------------------------------------------------------===// - -extern "C" { -CXSourceLocation clang_getNullLocation() { - CXSourceLocation Result = { { 0, 0 }, 0 }; - return Result; -} - -unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { - return (loc1.ptr_data[0] == loc2.ptr_data[0] && - loc1.ptr_data[1] == loc2.ptr_data[1] && - loc1.int_data == loc2.int_data); -} - -CXSourceLocation clang_getLocation(CXTranslationUnit tu, - CXFile file, - unsigned line, - unsigned column) { - if (!tu) - return clang_getNullLocation(); - - ASTUnit *CXXUnit = static_cast(tu); - SourceLocation SLoc - = CXXUnit->getSourceManager().getLocation( - static_cast(file), - line, column); - - return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); -} - -CXSourceRange clang_getNullRange() { - CXSourceRange Result = { { 0, 0 }, 0, 0 }; - return Result; -} - -CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { - if (begin.ptr_data[0] != end.ptr_data[0] || - begin.ptr_data[1] != end.ptr_data[1]) - return clang_getNullRange(); - - CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, - begin.int_data, end.int_data }; - return Result; -} - -void clang_getInstantiationLocation(CXSourceLocation location, - CXFile *file, - unsigned *line, - unsigned *column, - unsigned *offset) { - SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); - - if (!location.ptr_data[0] || Loc.isInvalid()) { - if (file) - *file = 0; - if (line) - *line = 0; - if (column) - *column = 0; - if (offset) - *offset = 0; - return; - } - - const SourceManager &SM = - *static_cast(location.ptr_data[0]); - SourceLocation InstLoc = SM.getInstantiationLoc(Loc); - - if (file) - *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); - if (line) - *line = SM.getInstantiationLineNumber(InstLoc); - if (column) - *column = SM.getInstantiationColumnNumber(InstLoc); - if (offset) - *offset = SM.getDecomposedLoc(InstLoc).second; -} - -CXSourceLocation clang_getRangeStart(CXSourceRange range) { - CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, - range.begin_int_data }; - return Result; -} - -CXSourceLocation clang_getRangeEnd(CXSourceRange range) { - CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, - range.end_int_data }; - return Result; -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXFile Operations. -//===----------------------------------------------------------------------===// - -extern "C" { -CXString clang_getFileName(CXFile SFile) { - if (!SFile) - return createCXString(NULL); - - FileEntry *FEnt = static_cast(SFile); - return createCXString(FEnt->getName()); -} - -time_t clang_getFileTime(CXFile SFile) { - if (!SFile) - return 0; - - FileEntry *FEnt = static_cast(SFile); - return FEnt->getModificationTime(); -} - -CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { - if (!tu) - return 0; - - ASTUnit *CXXUnit = static_cast(tu); - - FileManager &FMgr = CXXUnit->getFileManager(); - const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name)); - return const_cast(File); -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXCursor Operations. -//===----------------------------------------------------------------------===// - -static Decl *getDeclFromExpr(Stmt *E) { - if (DeclRefExpr *RefExpr = dyn_cast(E)) - return RefExpr->getDecl(); - if (MemberExpr *ME = dyn_cast(E)) - return ME->getMemberDecl(); - if (ObjCIvarRefExpr *RE = dyn_cast(E)) - return RE->getDecl(); - - if (CallExpr *CE = dyn_cast(E)) - return getDeclFromExpr(CE->getCallee()); - if (CastExpr *CE = dyn_cast(E)) - return getDeclFromExpr(CE->getSubExpr()); - if (ObjCMessageExpr *OME = dyn_cast(E)) - return OME->getMethodDecl(); - - return 0; -} - -static SourceLocation getLocationFromExpr(Expr *E) { - if (ObjCMessageExpr *Msg = dyn_cast(E)) - return /*FIXME:*/Msg->getLeftLoc(); - if (DeclRefExpr *DRE = dyn_cast(E)) - return DRE->getLocation(); - if (MemberExpr *Member = dyn_cast(E)) - return Member->getMemberLoc(); - if (ObjCIvarRefExpr *Ivar = dyn_cast(E)) - return Ivar->getLocation(); - return E->getLocStart(); -} - -extern "C" { - -unsigned clang_visitChildren(CXCursor parent, - CXCursorVisitor visitor, - CXClientData client_data) { - ASTUnit *CXXUnit = getCursorASTUnit(parent); - - unsigned PCHLevel = Decl::MaxPCHLevel; - - // Set the PCHLevel to filter out unwanted decls if requested. - if (CXXUnit->getOnlyLocalDecls()) { - PCHLevel = 0; - - // If the main input was an AST, bump the level. - if (CXXUnit->isMainFileAST()) - ++PCHLevel; - } - - CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel); - return CursorVis.VisitChildren(parent); -} - -static CXString getDeclSpelling(Decl *D) { - NamedDecl *ND = dyn_cast_or_null(D); - if (!ND) - return createCXString(""); - - if (ObjCMethodDecl *OMD = dyn_cast(ND)) - return createCXString(OMD->getSelector().getAsString()); - - if (ObjCCategoryImplDecl *CIMP = dyn_cast(ND)) - // No, this isn't the same as the code below. getIdentifier() is non-virtual - // and returns different names. NamedDecl returns the class name and - // ObjCCategoryImplDecl returns the category name. - return createCXString(CIMP->getIdentifier()->getNameStart()); - - if (ND->getIdentifier()) - return createCXString(ND->getIdentifier()->getNameStart()); - - return createCXString(""); -} - -CXString clang_getCursorSpelling(CXCursor C) { - if (clang_isTranslationUnit(C.kind)) - return clang_getTranslationUnitSpelling(C.data[2]); - - if (clang_isReference(C.kind)) { - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: { - ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; - return createCXString(Super->getIdentifier()->getNameStart()); - } - case CXCursor_ObjCClassRef: { - ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; - return createCXString(Class->getIdentifier()->getNameStart()); - } - case CXCursor_ObjCProtocolRef: { - ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; - assert(OID && "getCursorSpelling(): Missing protocol decl"); - return createCXString(OID->getIdentifier()->getNameStart()); - } - case CXCursor_TypeRef: { - TypeDecl *Type = getCursorTypeRef(C).first; - assert(Type && "Missing type decl"); - - return createCXString(getCursorContext(C).getTypeDeclType(Type). - getAsString()); - } - - default: - return createCXString(""); - } - } - - if (clang_isExpression(C.kind)) { - Decl *D = getDeclFromExpr(getCursorExpr(C)); - if (D) - return getDeclSpelling(D); - return createCXString(""); - } - - if (C.kind == CXCursor_MacroInstantiation) - return createCXString(getCursorMacroInstantiation(C)->getName() - ->getNameStart()); - - if (C.kind == CXCursor_MacroDefinition) - return createCXString(getCursorMacroDefinition(C)->getName() - ->getNameStart()); - - if (clang_isDeclaration(C.kind)) - return getDeclSpelling(getCursorDecl(C)); - - return createCXString(""); -} - -CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { - switch (Kind) { - case CXCursor_FunctionDecl: - return createCXString("FunctionDecl"); - case CXCursor_TypedefDecl: - return createCXString("TypedefDecl"); - case CXCursor_EnumDecl: - return createCXString("EnumDecl"); - case CXCursor_EnumConstantDecl: - return createCXString("EnumConstantDecl"); - case CXCursor_StructDecl: - return createCXString("StructDecl"); - case CXCursor_UnionDecl: - return createCXString("UnionDecl"); - case CXCursor_ClassDecl: - return createCXString("ClassDecl"); - case CXCursor_FieldDecl: - return createCXString("FieldDecl"); - case CXCursor_VarDecl: - return createCXString("VarDecl"); - case CXCursor_ParmDecl: - return createCXString("ParmDecl"); - case CXCursor_ObjCInterfaceDecl: - return createCXString("ObjCInterfaceDecl"); - case CXCursor_ObjCCategoryDecl: - return createCXString("ObjCCategoryDecl"); - case CXCursor_ObjCProtocolDecl: - return createCXString("ObjCProtocolDecl"); - case CXCursor_ObjCPropertyDecl: - return createCXString("ObjCPropertyDecl"); - case CXCursor_ObjCIvarDecl: - return createCXString("ObjCIvarDecl"); - case CXCursor_ObjCInstanceMethodDecl: - return createCXString("ObjCInstanceMethodDecl"); - case CXCursor_ObjCClassMethodDecl: - return createCXString("ObjCClassMethodDecl"); - case CXCursor_ObjCImplementationDecl: - return createCXString("ObjCImplementationDecl"); - case CXCursor_ObjCCategoryImplDecl: - return createCXString("ObjCCategoryImplDecl"); - case CXCursor_CXXMethod: - return createCXString("CXXMethod"); - case CXCursor_UnexposedDecl: - return createCXString("UnexposedDecl"); - case CXCursor_ObjCSuperClassRef: - return createCXString("ObjCSuperClassRef"); - case CXCursor_ObjCProtocolRef: - return createCXString("ObjCProtocolRef"); - case CXCursor_ObjCClassRef: - return createCXString("ObjCClassRef"); - case CXCursor_TypeRef: - return createCXString("TypeRef"); - case CXCursor_UnexposedExpr: - return createCXString("UnexposedExpr"); - case CXCursor_BlockExpr: - return createCXString("BlockExpr"); - case CXCursor_DeclRefExpr: - return createCXString("DeclRefExpr"); - case CXCursor_MemberRefExpr: - return createCXString("MemberRefExpr"); - case CXCursor_CallExpr: - return createCXString("CallExpr"); - case CXCursor_ObjCMessageExpr: - return createCXString("ObjCMessageExpr"); - case CXCursor_UnexposedStmt: - return createCXString("UnexposedStmt"); - case CXCursor_InvalidFile: - return createCXString("InvalidFile"); - case CXCursor_InvalidCode: - return createCXString("InvalidCode"); - case CXCursor_NoDeclFound: - return createCXString("NoDeclFound"); - case CXCursor_NotImplemented: - return createCXString("NotImplemented"); - case CXCursor_TranslationUnit: - return createCXString("TranslationUnit"); - case CXCursor_UnexposedAttr: - return createCXString("UnexposedAttr"); - case CXCursor_IBActionAttr: - return createCXString("attribute(ibaction)"); - case CXCursor_IBOutletAttr: - return createCXString("attribute(iboutlet)"); - case CXCursor_PreprocessingDirective: - return createCXString("preprocessing directive"); - case CXCursor_MacroDefinition: - return createCXString("macro definition"); - case CXCursor_MacroInstantiation: - return createCXString("macro instantiation"); - } - - llvm_unreachable("Unhandled CXCursorKind"); - return createCXString(NULL); -} - -enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, - CXCursor parent, - CXClientData client_data) { - CXCursor *BestCursor = static_cast(client_data); - *BestCursor = cursor; - return CXChildVisit_Recurse; -} - -CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { - if (!TU) - return clang_getNullCursor(); - - ASTUnit *CXXUnit = static_cast(TU); - - ASTUnit::ConcurrencyCheck Check(*CXXUnit); - - SourceLocation SLoc = cxloc::translateSourceLocation(Loc); - CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); - if (SLoc.isValid()) { - SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1)); - - // FIXME: Would be great to have a "hint" cursor, then walk from that - // hint cursor upward until we find a cursor whose source range encloses - // the region of interest, rather than starting from the translation unit. - CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); - CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, - Decl::MaxPCHLevel, RegionOfInterest); - CursorVis.VisitChildren(Parent); - } - return Result; -} - -CXCursor clang_getNullCursor(void) { - return MakeCXCursorInvalid(CXCursor_InvalidFile); -} - -unsigned clang_equalCursors(CXCursor X, CXCursor Y) { - return X == Y; -} - -unsigned clang_isInvalid(enum CXCursorKind K) { - return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; -} - -unsigned clang_isDeclaration(enum CXCursorKind K) { - return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; -} - -unsigned clang_isReference(enum CXCursorKind K) { - return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; -} - -unsigned clang_isExpression(enum CXCursorKind K) { - return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; -} - -unsigned clang_isStatement(enum CXCursorKind K) { - return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; -} - -unsigned clang_isTranslationUnit(enum CXCursorKind K) { - return K == CXCursor_TranslationUnit; -} - -unsigned clang_isPreprocessing(enum CXCursorKind K) { - return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; -} - -unsigned clang_isUnexposed(enum CXCursorKind K) { - switch (K) { - case CXCursor_UnexposedDecl: - case CXCursor_UnexposedExpr: - case CXCursor_UnexposedStmt: - case CXCursor_UnexposedAttr: - return true; - default: - return false; - } -} - -CXCursorKind clang_getCursorKind(CXCursor C) { - return C.kind; -} - -CXSourceLocation clang_getCursorLocation(CXCursor C) { - if (clang_isReference(C.kind)) { - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: { - std::pair P - = getCursorObjCSuperClassRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCProtocolRef: { - std::pair P - = getCursorObjCProtocolRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCClassRef: { - std::pair P - = getCursorObjCClassRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - case CXCursor_TypeRef: { - std::pair P = getCursorTypeRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - default: - // FIXME: Need a way to enumerate all non-reference cases. - llvm_unreachable("Missed a reference kind"); - } - } - - if (clang_isExpression(C.kind)) - return cxloc::translateSourceLocation(getCursorContext(C), - getLocationFromExpr(getCursorExpr(C))); - - if (C.kind == CXCursor_PreprocessingDirective) { - SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); - return cxloc::translateSourceLocation(getCursorContext(C), L); - } - - if (C.kind == CXCursor_MacroInstantiation) { - SourceLocation L - = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); - return cxloc::translateSourceLocation(getCursorContext(C), L); - } - - if (C.kind == CXCursor_MacroDefinition) { - SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); - return cxloc::translateSourceLocation(getCursorContext(C), L); - } - - if (!getCursorDecl(C)) - return clang_getNullLocation(); - - Decl *D = getCursorDecl(C); - SourceLocation Loc = D->getLocation(); - if (ObjCInterfaceDecl *Class = dyn_cast(D)) - Loc = Class->getClassLoc(); - return cxloc::translateSourceLocation(getCursorContext(C), Loc); -} - -CXSourceRange clang_getCursorExtent(CXCursor C) { - if (clang_isReference(C.kind)) { - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: { - std::pair P - = getCursorObjCSuperClassRef(C); - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCProtocolRef: { - std::pair P - = getCursorObjCProtocolRef(C); - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCClassRef: { - std::pair P - = getCursorObjCClassRef(C); - - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - case CXCursor_TypeRef: { - std::pair P = getCursorTypeRef(C); - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - default: - // FIXME: Need a way to enumerate all non-reference cases. - llvm_unreachable("Missed a reference kind"); - } - } - - if (clang_isExpression(C.kind)) - return cxloc::translateSourceRange(getCursorContext(C), - getCursorExpr(C)->getSourceRange()); - - if (clang_isStatement(C.kind)) - return cxloc::translateSourceRange(getCursorContext(C), - getCursorStmt(C)->getSourceRange()); - - if (C.kind == CXCursor_PreprocessingDirective) { - SourceRange R = cxcursor::getCursorPreprocessingDirective(C); - return cxloc::translateSourceRange(getCursorContext(C), R); - } - - if (C.kind == CXCursor_MacroInstantiation) { - SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); - return cxloc::translateSourceRange(getCursorContext(C), R); - } - - if (C.kind == CXCursor_MacroDefinition) { - SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); - return cxloc::translateSourceRange(getCursorContext(C), R); - } - - if (!getCursorDecl(C)) - return clang_getNullRange(); - - Decl *D = getCursorDecl(C); - return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange()); -} - -CXCursor clang_getCursorReferenced(CXCursor C) { - if (clang_isInvalid(C.kind)) - return clang_getNullCursor(); - - ASTUnit *CXXUnit = getCursorASTUnit(C); - if (clang_isDeclaration(C.kind)) - return C; - - if (clang_isExpression(C.kind)) { - Decl *D = getDeclFromExpr(getCursorExpr(C)); - if (D) - return MakeCXCursor(D, CXXUnit); - return clang_getNullCursor(); - } - - if (C.kind == CXCursor_MacroInstantiation) { - if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) - return MakeMacroDefinitionCursor(Def, CXXUnit); - } - - if (!clang_isReference(C.kind)) - return clang_getNullCursor(); - - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: - return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); - - case CXCursor_ObjCProtocolRef: { - return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); - - case CXCursor_ObjCClassRef: - return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); - - case CXCursor_TypeRef: - return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); - - default: - // We would prefer to enumerate all non-reference cursor kinds here. - llvm_unreachable("Unhandled reference cursor kind"); - break; - } - } - - return clang_getNullCursor(); -} - -CXCursor clang_getCursorDefinition(CXCursor C) { - if (clang_isInvalid(C.kind)) - return clang_getNullCursor(); - - ASTUnit *CXXUnit = getCursorASTUnit(C); - - bool WasReference = false; - if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { - C = clang_getCursorReferenced(C); - WasReference = true; - } - - if (C.kind == CXCursor_MacroInstantiation) - return clang_getCursorReferenced(C); - - if (!clang_isDeclaration(C.kind)) - return clang_getNullCursor(); - - Decl *D = getCursorDecl(C); - if (!D) - return clang_getNullCursor(); - - switch (D->getKind()) { - // Declaration kinds that don't really separate the notions of - // declaration and definition. - case Decl::Namespace: - case Decl::Typedef: - case Decl::TemplateTypeParm: - case Decl::EnumConstant: - case Decl::Field: - case Decl::ObjCIvar: - case Decl::ObjCAtDefsField: - case Decl::ImplicitParam: - case Decl::ParmVar: - case Decl::NonTypeTemplateParm: - case Decl::TemplateTemplateParm: - case Decl::ObjCCategoryImpl: - case Decl::ObjCImplementation: - case Decl::LinkageSpec: - case Decl::ObjCPropertyImpl: - case Decl::FileScopeAsm: - case Decl::StaticAssert: - case Decl::Block: - return C; - - // Declaration kinds that don't make any sense here, but are - // nonetheless harmless. - case Decl::TranslationUnit: - break; - - // Declaration kinds for which the definition is not resolvable. - case Decl::UnresolvedUsingTypename: - case Decl::UnresolvedUsingValue: - break; - - case Decl::UsingDirective: - return MakeCXCursor(cast(D)->getNominatedNamespace(), - CXXUnit); - - case Decl::NamespaceAlias: - return MakeCXCursor(cast(D)->getNamespace(), CXXUnit); - - case Decl::Enum: - case Decl::Record: - case Decl::CXXRecord: - case Decl::ClassTemplateSpecialization: - case Decl::ClassTemplatePartialSpecialization: - if (TagDecl *Def = cast(D)->getDefinition()) - return MakeCXCursor(Def, CXXUnit); - return clang_getNullCursor(); - - case Decl::Function: - case Decl::CXXMethod: - case Decl::CXXConstructor: - case Decl::CXXDestructor: - case Decl::CXXConversion: { - const FunctionDecl *Def = 0; - if (cast(D)->getBody(Def)) - return MakeCXCursor(const_cast(Def), CXXUnit); - return clang_getNullCursor(); - } - - case Decl::Var: { - // Ask the variable if it has a definition. - if (VarDecl *Def = cast(D)->getDefinition()) - return MakeCXCursor(Def, CXXUnit); - return clang_getNullCursor(); - } - - case Decl::FunctionTemplate: { - const FunctionDecl *Def = 0; - if (cast(D)->getTemplatedDecl()->getBody(Def)) - return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); - return clang_getNullCursor(); - } - - case Decl::ClassTemplate: { - if (RecordDecl *Def = cast(D)->getTemplatedDecl() - ->getDefinition()) - return MakeCXCursor( - cast(Def)->getDescribedClassTemplate(), - CXXUnit); - return clang_getNullCursor(); - } - - case Decl::Using: { - UsingDecl *Using = cast(D); - CXCursor Def = clang_getNullCursor(); - for (UsingDecl::shadow_iterator S = Using->shadow_begin(), - SEnd = Using->shadow_end(); - S != SEnd; ++S) { - if (Def != clang_getNullCursor()) { - // FIXME: We have no way to return multiple results. - return clang_getNullCursor(); - } - - Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(), - CXXUnit)); - } - - return Def; - } - - case Decl::UsingShadow: - return clang_getCursorDefinition( - MakeCXCursor(cast(D)->getTargetDecl(), - CXXUnit)); - - case Decl::ObjCMethod: { - ObjCMethodDecl *Method = cast(D); - if (Method->isThisDeclarationADefinition()) - return C; - - // Dig out the method definition in the associated - // @implementation, if we have it. - // FIXME: The ASTs should make finding the definition easier. - if (ObjCInterfaceDecl *Class - = dyn_cast(Method->getDeclContext())) - if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) - if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), - Method->isInstanceMethod())) - if (Def->isThisDeclarationADefinition()) - return MakeCXCursor(Def, CXXUnit); - - return clang_getNullCursor(); - } - - case Decl::ObjCCategory: - if (ObjCCategoryImplDecl *Impl - = cast(D)->getImplementation()) - return MakeCXCursor(Impl, CXXUnit); - return clang_getNullCursor(); - - case Decl::ObjCProtocol: - if (!cast(D)->isForwardDecl()) - return C; - return clang_getNullCursor(); - - case Decl::ObjCInterface: - // There are two notions of a "definition" for an Objective-C - // class: the interface and its implementation. When we resolved a - // reference to an Objective-C class, produce the @interface as - // the definition; when we were provided with the interface, - // produce the @implementation as the definition. - if (WasReference) { - if (!cast(D)->isForwardDecl()) - return C; - } else if (ObjCImplementationDecl *Impl - = cast(D)->getImplementation()) - return MakeCXCursor(Impl, CXXUnit); - return clang_getNullCursor(); - - case Decl::ObjCProperty: - // FIXME: We don't really know where to find the - // ObjCPropertyImplDecls that implement this property. - return clang_getNullCursor(); - - case Decl::ObjCCompatibleAlias: - if (ObjCInterfaceDecl *Class - = cast(D)->getClassInterface()) - if (!Class->isForwardDecl()) - return MakeCXCursor(Class, CXXUnit); - - return clang_getNullCursor(); - - case Decl::ObjCForwardProtocol: { - ObjCForwardProtocolDecl *Forward = cast(D); - if (Forward->protocol_size() == 1) - return clang_getCursorDefinition( - MakeCXCursor(*Forward->protocol_begin(), - CXXUnit)); - - // FIXME: Cannot return multiple definitions. - return clang_getNullCursor(); - } - - case Decl::ObjCClass: { - ObjCClassDecl *Class = cast(D); - if (Class->size() == 1) { - ObjCInterfaceDecl *IFace = Class->begin()->getInterface(); - if (!IFace->isForwardDecl()) - return MakeCXCursor(IFace, CXXUnit); - return clang_getNullCursor(); - } - - // FIXME: Cannot return multiple definitions. - return clang_getNullCursor(); - } - - case Decl::Friend: - if (NamedDecl *Friend = cast(D)->getFriendDecl()) - return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); - return clang_getNullCursor(); - - case Decl::FriendTemplate: - if (NamedDecl *Friend = cast(D)->getFriendDecl()) - return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); - return clang_getNullCursor(); - } - - return clang_getNullCursor(); -} - -unsigned clang_isCursorDefinition(CXCursor C) { - if (!clang_isDeclaration(C.kind)) - return 0; - - return clang_getCursorDefinition(C) == C; -} - -void clang_getDefinitionSpellingAndExtent(CXCursor C, - const char **startBuf, - const char **endBuf, - unsigned *startLine, - unsigned *startColumn, - unsigned *endLine, - unsigned *endColumn) { - assert(getCursorDecl(C) && "CXCursor has null decl"); - NamedDecl *ND = static_cast(getCursorDecl(C)); - FunctionDecl *FD = dyn_cast(ND); - CompoundStmt *Body = dyn_cast(FD->getBody()); - - SourceManager &SM = FD->getASTContext().getSourceManager(); - *startBuf = SM.getCharacterData(Body->getLBracLoc()); - *endBuf = SM.getCharacterData(Body->getRBracLoc()); - *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); - *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); - *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); - *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); -} - -void clang_enableStackTraces(void) { - llvm::sys::PrintStackTraceOnErrorSignal(); -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// Token-based Operations. -//===----------------------------------------------------------------------===// - -/* CXToken layout: - * int_data[0]: a CXTokenKind - * int_data[1]: starting token location - * int_data[2]: token length - * int_data[3]: reserved - * ptr_data: for identifiers and keywords, an IdentifierInfo*. - * otherwise unused. - */ -extern "C" { - -CXTokenKind clang_getTokenKind(CXToken CXTok) { - return static_cast(CXTok.int_data[0]); -} - -CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { - switch (clang_getTokenKind(CXTok)) { - case CXToken_Identifier: - case CXToken_Keyword: - // We know we have an IdentifierInfo*, so use that. - return createCXString(static_cast(CXTok.ptr_data) - ->getNameStart()); - - case CXToken_Literal: { - // We have stashed the starting pointer in the ptr_data field. Use it. - const char *Text = static_cast(CXTok.ptr_data); - return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); - } - - case CXToken_Punctuation: - case CXToken_Comment: - break; - } - - // We have to find the starting buffer pointer the hard way, by - // deconstructing the source location. - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit) - return createCXString(""); - - SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); - std::pair LocInfo - = CXXUnit->getSourceManager().getDecomposedLoc(Loc); - bool Invalid = false; - llvm::StringRef Buffer - = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); - if (Invalid) - return createCXString(""); - - return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); -} - -CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit) - return clang_getNullLocation(); - - return cxloc::translateSourceLocation(CXXUnit->getASTContext(), - SourceLocation::getFromRawEncoding(CXTok.int_data[1])); -} - -CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit) - return clang_getNullRange(); - - return cxloc::translateSourceRange(CXXUnit->getASTContext(), - SourceLocation::getFromRawEncoding(CXTok.int_data[1])); -} - -void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, - CXToken **Tokens, unsigned *NumTokens) { - if (Tokens) - *Tokens = 0; - if (NumTokens) - *NumTokens = 0; - - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit || !Tokens || !NumTokens) - return; - - ASTUnit::ConcurrencyCheck Check(*CXXUnit); - - SourceRange R = cxloc::translateCXSourceRange(Range); - if (R.isInvalid()) - return; - - SourceManager &SourceMgr = CXXUnit->getSourceManager(); - std::pair BeginLocInfo - = SourceMgr.getDecomposedLoc(R.getBegin()); - std::pair EndLocInfo - = SourceMgr.getDecomposedLoc(R.getEnd()); - - // Cannot tokenize across files. - if (BeginLocInfo.first != EndLocInfo.first) - return; - - // Create a lexer - bool Invalid = false; - llvm::StringRef Buffer - = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); - if (Invalid) - return; - - Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), - CXXUnit->getASTContext().getLangOptions(), - Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); - Lex.SetCommentRetentionState(true); - - // Lex tokens until we hit the end of the range. - const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; - llvm::SmallVector CXTokens; - Token Tok; - do { - // Lex the next token - Lex.LexFromRawLexer(Tok); - if (Tok.is(tok::eof)) - break; - - // Initialize the CXToken. - CXToken CXTok; - - // - Common fields - CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); - CXTok.int_data[2] = Tok.getLength(); - CXTok.int_data[3] = 0; - - // - Kind-specific fields - if (Tok.isLiteral()) { - CXTok.int_data[0] = CXToken_Literal; - CXTok.ptr_data = (void *)Tok.getLiteralData(); - } else if (Tok.is(tok::identifier)) { - // Lookup the identifier to determine whether we have a keyword. - std::pair LocInfo - = SourceMgr.getDecomposedLoc(Tok.getLocation()); - bool Invalid = false; - llvm::StringRef Buf - = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); - if (Invalid) - return; - - const char *StartPos = Buf.data() + LocInfo.second; - IdentifierInfo *II - = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); - CXTok.int_data[0] = II->getTokenID() == tok::identifier? - CXToken_Identifier - : CXToken_Keyword; - CXTok.ptr_data = II; - } else if (Tok.is(tok::comment)) { - CXTok.int_data[0] = CXToken_Comment; - CXTok.ptr_data = 0; - } else { - CXTok.int_data[0] = CXToken_Punctuation; - CXTok.ptr_data = 0; - } - CXTokens.push_back(CXTok); - } while (Lex.getBufferLocation() <= EffectiveBufferEnd); - - if (CXTokens.empty()) - return; - - *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); - memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); - *NumTokens = CXTokens.size(); -} - -typedef llvm::DenseMap AnnotateTokensData; - -enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, - CXCursor parent, - CXClientData client_data) { - AnnotateTokensData *Data = static_cast(client_data); - - // We only annotate the locations of declarations, simple - // references, and expressions which directly reference something. - CXCursorKind Kind = clang_getCursorKind(cursor); - if (clang_isDeclaration(Kind) || clang_isReference(Kind)) { - // Okay: We can annotate the location of this declaration with the - // declaration or reference - } else if (clang_isExpression(cursor.kind)) { - if (Kind != CXCursor_DeclRefExpr && - Kind != CXCursor_MemberRefExpr && - Kind != CXCursor_ObjCMessageExpr) - return CXChildVisit_Recurse; - - CXCursor Referenced = clang_getCursorReferenced(cursor); - if (Referenced == cursor || Referenced == clang_getNullCursor()) - return CXChildVisit_Recurse; - - // Okay: we can annotate the location of this expression - } else if (clang_isPreprocessing(cursor.kind)) { - // We can always annotate a preprocessing directive/macro instantiation. - } else { - // Nothing to annotate - return CXChildVisit_Recurse; - } - - CXSourceLocation Loc = clang_getCursorLocation(cursor); - (*Data)[Loc.int_data] = cursor; - return CXChildVisit_Recurse; -} - -void clang_annotateTokens(CXTranslationUnit TU, - CXToken *Tokens, unsigned NumTokens, - CXCursor *Cursors) { - if (NumTokens == 0) - return; - - // Any token we don't specifically annotate will have a NULL cursor. - for (unsigned I = 0; I != NumTokens; ++I) - Cursors[I] = clang_getNullCursor(); - - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit || !Tokens) - return; - - ASTUnit::ConcurrencyCheck Check(*CXXUnit); - - // Determine the region of interest, which contains all of the tokens. - SourceRange RegionOfInterest; - RegionOfInterest.setBegin( - cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); - SourceLocation End - = cxloc::translateSourceLocation(clang_getTokenLocation(TU, - Tokens[NumTokens - 1])); - RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End)); - - // A mapping from the source locations found when re-lexing or traversing the - // region of interest to the corresponding cursors. - AnnotateTokensData Annotated; - - // Relex the tokens within the source range to look for preprocessing - // directives. - SourceManager &SourceMgr = CXXUnit->getSourceManager(); - std::pair BeginLocInfo - = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); - std::pair EndLocInfo - = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); - - llvm::StringRef Buffer; - bool Invalid = false; - if (BeginLocInfo.first == EndLocInfo.first && - ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && - !Invalid) { - Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), - CXXUnit->getASTContext().getLangOptions(), - Buffer.begin(), Buffer.data() + BeginLocInfo.second, - Buffer.end()); - Lex.SetCommentRetentionState(true); - - // Lex tokens in raw mode until we hit the end of the range, to avoid - // entering #includes or expanding macros. - while (true) { - Token Tok; - Lex.LexFromRawLexer(Tok); - - reprocess: - if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { - // We have found a preprocessing directive. Gobble it up so that we - // don't see it while preprocessing these tokens later, but keep track of - // all of the token locations inside this preprocessing directive so that - // we can annotate them appropriately. - // - // FIXME: Some simple tests here could identify macro definitions and - // #undefs, to provide specific cursor kinds for those. - std::vector Locations; - do { - Locations.push_back(Tok.getLocation()); - Lex.LexFromRawLexer(Tok); - } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); - - using namespace cxcursor; - CXCursor Cursor - = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), - Locations.back()), - CXXUnit); - for (unsigned I = 0, N = Locations.size(); I != N; ++I) { - Annotated[Locations[I].getRawEncoding()] = Cursor; - } - - if (Tok.isAtStartOfLine()) - goto reprocess; - - continue; - } - - if (Tok.is(tok::eof)) - break; - } - } - - // Annotate all of the source locations in the region of interest that map to - // a specific cursor. - CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); - CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated, - Decl::MaxPCHLevel, RegionOfInterest); - AnnotateVis.VisitChildren(Parent); - - for (unsigned I = 0; I != NumTokens; ++I) { - // Determine whether we saw a cursor at this token's location. - AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); - if (Pos == Annotated.end()) - continue; - - Cursors[I] = Pos->second; - } -} - -void clang_disposeTokens(CXTranslationUnit TU, - CXToken *Tokens, unsigned NumTokens) { - free(Tokens); -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// Operations for querying linkage of a cursor. -//===----------------------------------------------------------------------===// - -extern "C" { -CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { - if (!clang_isDeclaration(cursor.kind)) - return CXLinkage_Invalid; - - Decl *D = cxcursor::getCursorDecl(cursor); - if (NamedDecl *ND = dyn_cast_or_null(D)) - switch (ND->getLinkage()) { - case NoLinkage: return CXLinkage_NoLinkage; - case InternalLinkage: return CXLinkage_Internal; - case UniqueExternalLinkage: return CXLinkage_UniqueExternal; - case ExternalLinkage: return CXLinkage_External; - }; - - return CXLinkage_Invalid; -} -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// Operations for querying language of a cursor. -//===----------------------------------------------------------------------===// - -static CXLanguageKind getDeclLanguage(const Decl *D) { - switch (D->getKind()) { - default: - break; - case Decl::ImplicitParam: - case Decl::ObjCAtDefsField: - case Decl::ObjCCategory: - case Decl::ObjCCategoryImpl: - case Decl::ObjCClass: - case Decl::ObjCCompatibleAlias: - case Decl::ObjCForwardProtocol: - case Decl::ObjCImplementation: - case Decl::ObjCInterface: - case Decl::ObjCIvar: - case Decl::ObjCMethod: - case Decl::ObjCProperty: - case Decl::ObjCPropertyImpl: - case Decl::ObjCProtocol: - return CXLanguage_ObjC; - case Decl::CXXConstructor: - case Decl::CXXConversion: - case Decl::CXXDestructor: - case Decl::CXXMethod: - case Decl::CXXRecord: - case Decl::ClassTemplate: - case Decl::ClassTemplatePartialSpecialization: - case Decl::ClassTemplateSpecialization: - case Decl::Friend: - case Decl::FriendTemplate: - case Decl::FunctionTemplate: - case Decl::LinkageSpec: - case Decl::Namespace: - case Decl::NamespaceAlias: - case Decl::NonTypeTemplateParm: - case Decl::StaticAssert: - case Decl::TemplateTemplateParm: - case Decl::TemplateTypeParm: - case Decl::UnresolvedUsingTypename: - case Decl::UnresolvedUsingValue: - case Decl::Using: - case Decl::UsingDirective: - case Decl::UsingShadow: - return CXLanguage_CPlusPlus; - } - - return CXLanguage_C; -} - -extern "C" { -CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { - if (clang_isDeclaration(cursor.kind)) - return getDeclLanguage(cxcursor::getCursorDecl(cursor)); - - return CXLanguage_Invalid; -} -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXString Operations. -//===----------------------------------------------------------------------===// - -extern "C" { -const char *clang_getCString(CXString string) { - return string.Spelling; -} - -void clang_disposeString(CXString string) { - if (string.MustFreeString && string.Spelling) - free((void*)string.Spelling); -} - -} // end: extern "C" - -namespace clang { namespace cxstring { -CXString createCXString(const char *String, bool DupString){ - CXString Str; - if (DupString) { - Str.Spelling = strdup(String); - Str.MustFreeString = 1; - } else { - Str.Spelling = String; - Str.MustFreeString = 0; - } - return Str; -} - -CXString createCXString(llvm::StringRef String, bool DupString) { - CXString Result; - if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { - char *Spelling = (char *)malloc(String.size() + 1); - memmove(Spelling, String.data(), String.size()); - Spelling[String.size()] = 0; - Result.Spelling = Spelling; - Result.MustFreeString = 1; - } else { - Result.Spelling = String.data(); - Result.MustFreeString = 0; - } - return Result; -} -}} - -//===----------------------------------------------------------------------===// -// Misc. utility functions. -//===----------------------------------------------------------------------===// - -extern "C" { - -CXString clang_getClangVersion() { - return createCXString(getClangFullVersion()); -} - -} // end: extern "C" diff --git a/tools/CIndex/CIndex.darwin.exports b/tools/CIndex/CIndex.darwin.exports deleted file mode 100644 index b3611680531..00000000000 --- a/tools/CIndex/CIndex.darwin.exports +++ /dev/null @@ -1,81 +0,0 @@ -_clang_annotateTokens -_clang_codeComplete -_clang_codeCompleteGetDiagnostic -_clang_codeCompleteGetNumDiagnostics -_clang_constructUSR_ObjCCategory -_clang_constructUSR_ObjCClass -_clang_constructUSR_ObjCIvar -_clang_constructUSR_ObjCMethod -_clang_constructUSR_ObjCProperty -_clang_constructUSR_ObjCProtocol -_clang_createIndex -_clang_createTranslationUnit -_clang_createTranslationUnitFromSourceFile -_clang_defaultDiagnosticDisplayOptions -_clang_disposeCodeCompleteResults -_clang_disposeDiagnostic -_clang_disposeIndex -_clang_disposeString -_clang_disposeTokens -_clang_disposeTranslationUnit -_clang_enableStackTraces -_clang_equalCursors -_clang_equalLocations -_clang_formatDiagnostic -_clang_getCString -_clang_getClangVersion -_clang_getCompletionChunkCompletionString -_clang_getCompletionChunkKind -_clang_getCompletionChunkText -_clang_getCursor -_clang_getCursorDefinition -_clang_getCursorExtent -_clang_getCursorKind -_clang_getCursorKindSpelling -_clang_getCursorLanguage -_clang_getCursorLinkage -_clang_getCursorLocation -_clang_getCursorReferenced -_clang_getCursorSpelling -_clang_getCursorUSR -_clang_getDefinitionSpellingAndExtent -_clang_getDiagnostic -_clang_getDiagnosticFixIt -_clang_getDiagnosticLocation -_clang_getDiagnosticNumFixIts -_clang_getDiagnosticNumRanges -_clang_getDiagnosticRange -_clang_getDiagnosticSeverity -_clang_getDiagnosticSpelling -_clang_getFile -_clang_getFileName -_clang_getFileTime -_clang_getInclusions -_clang_getInstantiationLocation -_clang_getLocation -_clang_getNullCursor -_clang_getNullLocation -_clang_getNullRange -_clang_getNumCompletionChunks -_clang_getNumDiagnostics -_clang_getRange -_clang_getRangeEnd -_clang_getRangeStart -_clang_getTokenExtent -_clang_getTokenKind -_clang_getTokenLocation -_clang_getTokenSpelling -_clang_getTranslationUnitCursor -_clang_getTranslationUnitSpelling -_clang_isCursorDefinition -_clang_isDeclaration -_clang_isExpression -_clang_isInvalid -_clang_isPreprocessing -_clang_isReference -_clang_isStatement -_clang_isTranslationUnit -_clang_isUnexposed -_clang_setUseExternalASTGeneration -_clang_tokenize -_clang_visitChildren diff --git a/tools/CIndex/CIndex.exports b/tools/CIndex/CIndex.exports deleted file mode 100644 index 991bb067f7d..00000000000 --- a/tools/CIndex/CIndex.exports +++ /dev/null @@ -1,81 +0,0 @@ -clang_annotateTokens -clang_codeComplete -clang_codeCompleteGetDiagnostic -clang_codeCompleteGetNumDiagnostics -clang_constructUSR_ObjCCategory -clang_constructUSR_ObjCClass -clang_constructUSR_ObjCIvar -clang_constructUSR_ObjCMethod -clang_constructUSR_ObjCProperty -clang_constructUSR_ObjCProtocol -clang_createIndex -clang_createTranslationUnit -clang_createTranslationUnitFromSourceFile -clang_defaultDiagnosticDisplayOptions -clang_disposeCodeCompleteResults -clang_disposeDiagnostic -clang_disposeIndex -clang_disposeString -clang_disposeTokens -clang_disposeTranslationUnit -clang_enableStackTraces -clang_equalCursors -clang_equalLocations -clang_formatDiagnostic -clang_getCString -clang_getClangVersion -clang_getCompletionChunkCompletionString -clang_getCompletionChunkKind -clang_getCompletionChunkText -clang_getCursor -clang_getCursorDefinition -clang_getCursorExtent -clang_getCursorKind -clang_getCursorKindSpelling -clang_getCursorLanguage -clang_getCursorLinkage -clang_getCursorLocation -clang_getCursorReferenced -clang_getCursorSpelling -clang_getCursorUSR -clang_getDefinitionSpellingAndExtent -clang_getDiagnostic -clang_getDiagnosticFixIt -clang_getDiagnosticLocation -clang_getDiagnosticNumFixIts -clang_getDiagnosticNumRanges -clang_getDiagnosticRange -clang_getDiagnosticSeverity -clang_getDiagnosticSpelling -clang_getFile -clang_getFileName -clang_getFileTime -clang_getInclusions -clang_getInstantiationLocation -clang_getLocation -clang_getNullCursor -clang_getNullLocation -clang_getNullRange -clang_getNumCompletionChunks -clang_getNumDiagnostics -clang_getRange -clang_getRangeEnd -clang_getRangeStart -clang_getTokenExtent -clang_getTokenKind -clang_getTokenLocation -clang_getTokenSpelling -clang_getTranslationUnitCursor -clang_getTranslationUnitSpelling -clang_isCursorDefinition -clang_isDeclaration -clang_isExpression -clang_isInvalid -clang_isPreprocessing -clang_isReference -clang_isStatement -clang_isTranslationUnit -clang_isUnexposed -clang_setUseExternalASTGeneration -clang_tokenize -clang_visitChildren diff --git a/tools/CIndex/CIndexCodeCompletion.cpp b/tools/CIndex/CIndexCodeCompletion.cpp deleted file mode 100644 index a21614c7473..00000000000 --- a/tools/CIndex/CIndexCodeCompletion.cpp +++ /dev/null @@ -1,512 +0,0 @@ -//===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the Clang-C Source Indexing library hooks for -// code completion. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CIndexDiagnostic.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/FrontendDiagnostic.h" -#include "clang/Sema/CodeCompleteConsumer.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/System/Program.h" - -#ifdef UDP_CODE_COMPLETION_LOGGER -#include "clang/Basic/Version.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/Timer.h" -#include "llvm/Support/raw_ostream.h" -#include -#include -#include -#include -#endif - -using namespace clang; -using namespace clang::cxstring; - -extern "C" { - -enum CXCompletionChunkKind -clang_getCompletionChunkKind(CXCompletionString completion_string, - unsigned chunk_number) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - if (!CCStr || chunk_number >= CCStr->size()) - return CXCompletionChunk_Text; - - switch ((*CCStr)[chunk_number].Kind) { - case CodeCompletionString::CK_TypedText: - return CXCompletionChunk_TypedText; - case CodeCompletionString::CK_Text: - return CXCompletionChunk_Text; - case CodeCompletionString::CK_Optional: - return CXCompletionChunk_Optional; - case CodeCompletionString::CK_Placeholder: - return CXCompletionChunk_Placeholder; - case CodeCompletionString::CK_Informative: - return CXCompletionChunk_Informative; - case CodeCompletionString::CK_ResultType: - return CXCompletionChunk_ResultType; - case CodeCompletionString::CK_CurrentParameter: - return CXCompletionChunk_CurrentParameter; - case CodeCompletionString::CK_LeftParen: - return CXCompletionChunk_LeftParen; - case CodeCompletionString::CK_RightParen: - return CXCompletionChunk_RightParen; - case CodeCompletionString::CK_LeftBracket: - return CXCompletionChunk_LeftBracket; - case CodeCompletionString::CK_RightBracket: - return CXCompletionChunk_RightBracket; - case CodeCompletionString::CK_LeftBrace: - return CXCompletionChunk_LeftBrace; - case CodeCompletionString::CK_RightBrace: - return CXCompletionChunk_RightBrace; - case CodeCompletionString::CK_LeftAngle: - return CXCompletionChunk_LeftAngle; - case CodeCompletionString::CK_RightAngle: - return CXCompletionChunk_RightAngle; - case CodeCompletionString::CK_Comma: - return CXCompletionChunk_Comma; - case CodeCompletionString::CK_Colon: - return CXCompletionChunk_Colon; - case CodeCompletionString::CK_SemiColon: - return CXCompletionChunk_SemiColon; - case CodeCompletionString::CK_Equal: - return CXCompletionChunk_Equal; - case CodeCompletionString::CK_HorizontalSpace: - return CXCompletionChunk_HorizontalSpace; - case CodeCompletionString::CK_VerticalSpace: - return CXCompletionChunk_VerticalSpace; - } - - // Should be unreachable, but let's be careful. - return CXCompletionChunk_Text; -} - -CXString clang_getCompletionChunkText(CXCompletionString completion_string, - unsigned chunk_number) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - if (!CCStr || chunk_number >= CCStr->size()) - return createCXString(0); - - switch ((*CCStr)[chunk_number].Kind) { - case CodeCompletionString::CK_TypedText: - case CodeCompletionString::CK_Text: - case CodeCompletionString::CK_Placeholder: - case CodeCompletionString::CK_CurrentParameter: - case CodeCompletionString::CK_Informative: - case CodeCompletionString::CK_LeftParen: - case CodeCompletionString::CK_RightParen: - case CodeCompletionString::CK_LeftBracket: - case CodeCompletionString::CK_RightBracket: - case CodeCompletionString::CK_LeftBrace: - case CodeCompletionString::CK_RightBrace: - case CodeCompletionString::CK_LeftAngle: - case CodeCompletionString::CK_RightAngle: - case CodeCompletionString::CK_Comma: - case CodeCompletionString::CK_ResultType: - case CodeCompletionString::CK_Colon: - case CodeCompletionString::CK_SemiColon: - case CodeCompletionString::CK_Equal: - case CodeCompletionString::CK_HorizontalSpace: - case CodeCompletionString::CK_VerticalSpace: - return createCXString((*CCStr)[chunk_number].Text, false); - - case CodeCompletionString::CK_Optional: - // Note: treated as an empty text block. - return createCXString(""); - } - - // Should be unreachable, but let's be careful. - return createCXString(0); -} - - -CXCompletionString -clang_getCompletionChunkCompletionString(CXCompletionString completion_string, - unsigned chunk_number) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - if (!CCStr || chunk_number >= CCStr->size()) - return 0; - - switch ((*CCStr)[chunk_number].Kind) { - case CodeCompletionString::CK_TypedText: - case CodeCompletionString::CK_Text: - case CodeCompletionString::CK_Placeholder: - case CodeCompletionString::CK_CurrentParameter: - case CodeCompletionString::CK_Informative: - case CodeCompletionString::CK_LeftParen: - case CodeCompletionString::CK_RightParen: - case CodeCompletionString::CK_LeftBracket: - case CodeCompletionString::CK_RightBracket: - case CodeCompletionString::CK_LeftBrace: - case CodeCompletionString::CK_RightBrace: - case CodeCompletionString::CK_LeftAngle: - case CodeCompletionString::CK_RightAngle: - case CodeCompletionString::CK_Comma: - case CodeCompletionString::CK_ResultType: - case CodeCompletionString::CK_Colon: - case CodeCompletionString::CK_SemiColon: - case CodeCompletionString::CK_Equal: - case CodeCompletionString::CK_HorizontalSpace: - case CodeCompletionString::CK_VerticalSpace: - return 0; - - case CodeCompletionString::CK_Optional: - // Note: treated as an empty text block. - return (*CCStr)[chunk_number].Optional; - } - - // Should be unreachable, but let's be careful. - return 0; -} - -unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - return CCStr? CCStr->size() : 0; -} - -static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd, - unsigned &Value) { - if (Memory + sizeof(unsigned) > MemoryEnd) - return true; - - memmove(&Value, Memory, sizeof(unsigned)); - Memory += sizeof(unsigned); - return false; -} - -/// \brief The CXCodeCompleteResults structure we allocate internally; -/// the client only sees the initial CXCodeCompleteResults structure. -struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults { - AllocatedCXCodeCompleteResults(); - ~AllocatedCXCodeCompleteResults(); - - /// \brief The memory buffer from which we parsed the results. We - /// retain this buffer because the completion strings point into it. - llvm::MemoryBuffer *Buffer; - - /// \brief Diagnostics produced while performing code completion. - llvm::SmallVector Diagnostics; - - /// \brief Diag object - Diagnostic Diag; - - /// \brief Language options used to adjust source locations. - LangOptions LangOpts; - - /// \brief Source manager, used for diagnostics. - SourceManager SourceMgr; - - /// \brief File manager, used for diagnostics. - FileManager FileMgr; - - /// \brief Temporary files that should be removed once we have finished - /// with the code-completion results. - std::vector TemporaryFiles; -}; - -AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults() - : CXCodeCompleteResults(), Buffer(0), SourceMgr(Diag) { } - -AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() { - for (unsigned I = 0, N = NumResults; I != N; ++I) - delete (CodeCompletionString *)Results[I].CompletionString; - delete [] Results; - delete Buffer; - - for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) - TemporaryFiles[I].eraseFromDisk(); -} - -CXCodeCompleteResults *clang_codeComplete(CXIndex CIdx, - const char *source_filename, - int num_command_line_args, - const char **command_line_args, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - const char *complete_filename, - unsigned complete_line, - unsigned complete_column) { -#ifdef UDP_CODE_COMPLETION_LOGGER -#ifdef UDP_CODE_COMPLETION_LOGGER_PORT - const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime(); -#endif -#endif - - // The indexer, which is mainly used to determine where diagnostics go. - CIndexer *CXXIdx = static_cast(CIdx); - - // Configure the diagnostics. - DiagnosticOptions DiagOpts; - llvm::IntrusiveRefCntPtr Diags; - Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); - - // The set of temporary files that we've built. - std::vector TemporaryFiles; - - // Build up the arguments for invoking 'clang'. - std::vector argv; - - // First add the complete path to the 'clang' executable. - llvm::sys::Path ClangPath = CXXIdx->getClangPath(); - argv.push_back(ClangPath.c_str()); - - // Add the '-fsyntax-only' argument so that we only perform a basic - // syntax check of the code. - argv.push_back("-fsyntax-only"); - - // Add the appropriate '-code-completion-at=file:line:column' argument - // to perform code completion, with an "-Xclang" preceding it. - std::string code_complete_at; - code_complete_at += complete_filename; - code_complete_at += ":"; - code_complete_at += llvm::utostr(complete_line); - code_complete_at += ":"; - code_complete_at += llvm::utostr(complete_column); - argv.push_back("-Xclang"); - argv.push_back("-code-completion-at"); - argv.push_back("-Xclang"); - argv.push_back(code_complete_at.c_str()); - argv.push_back("-Xclang"); - argv.push_back("-no-code-completion-debug-printer"); - argv.push_back("-Xclang"); - argv.push_back("-code-completion-macros"); - argv.push_back("-fdiagnostics-binary"); - - // Remap any unsaved files to temporary files. - std::vector RemapArgs; - if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles)) - return 0; - - // The pointers into the elements of RemapArgs are stable because we - // won't be adding anything to RemapArgs after this point. - for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i) - argv.push_back(RemapArgs[i].c_str()); - - // Add the source file name (FIXME: later, we'll want to build temporary - // file from the buffer, or just feed the source text via standard input). - if (source_filename) - argv.push_back(source_filename); - - // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'. - for (int i = 0; i < num_command_line_args; ++i) - if (const char *arg = command_line_args[i]) { - if (strcmp(arg, "-o") == 0) { - ++i; // Also skip the matching argument. - continue; - } - if (strcmp(arg, "-emit-ast") == 0 || - strcmp(arg, "-c") == 0 || - strcmp(arg, "-fsyntax-only") == 0) { - continue; - } - - // Keep the argument. - argv.push_back(arg); - } - - // Add the null terminator. - argv.push_back(NULL); - - // Generate a temporary name for the code-completion results file. - char tmpFile[L_tmpnam]; - char *tmpFileName = tmpnam(tmpFile); - llvm::sys::Path ResultsFile(tmpFileName); - TemporaryFiles.push_back(ResultsFile); - - // Generate a temporary name for the diagnostics file. - char tmpFileResults[L_tmpnam]; - char *tmpResultsFileName = tmpnam(tmpFileResults); - llvm::sys::Path DiagnosticsFile(tmpResultsFileName); - TemporaryFiles.push_back(DiagnosticsFile); - - // Invoke 'clang'. - llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null - // on Unix or NUL (Windows). - std::string ErrMsg; - const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, - &DiagnosticsFile, 0 }; - llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL, - /* redirects */ &Redirects[0], - /* secondsToWait */ 0, - /* memoryLimits */ 0, &ErrMsg); - - if (!ErrMsg.empty()) { - std::string AllArgs; - for (std::vector::iterator I = argv.begin(), E = argv.end(); - I != E; ++I) { - AllArgs += ' '; - if (*I) - AllArgs += *I; - } - - Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg; - } - - // Parse the resulting source file to find code-completion results. - using llvm::MemoryBuffer; - using llvm::StringRef; - AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults; - Results->Results = 0; - Results->NumResults = 0; - Results->Buffer = 0; - // FIXME: Set Results->LangOpts! - if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) { - llvm::SmallVector CompletionResults; - StringRef Buffer = F->getBuffer(); - for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size(); - Str < StrEnd;) { - unsigned KindValue; - if (ReadUnsigned(Str, StrEnd, KindValue)) - break; - - CodeCompletionString *CCStr - = CodeCompletionString::Deserialize(Str, StrEnd); - if (!CCStr) - continue; - - if (!CCStr->empty()) { - // Vend the code-completion result to the caller. - CXCompletionResult Result; - Result.CursorKind = (CXCursorKind)KindValue; - Result.CompletionString = CCStr; - CompletionResults.push_back(Result); - } - }; - - // Allocate the results. - Results->Results = new CXCompletionResult [CompletionResults.size()]; - Results->NumResults = CompletionResults.size(); - memcpy(Results->Results, CompletionResults.data(), - CompletionResults.size() * sizeof(CXCompletionResult)); - Results->Buffer = F; - } - - LoadSerializedDiagnostics(DiagnosticsFile, num_unsaved_files, unsaved_files, - Results->FileMgr, Results->SourceMgr, - Results->Diagnostics); - - // Make sure we delete temporary files when the code-completion results are - // destroyed. - Results->TemporaryFiles.swap(TemporaryFiles); - -#ifdef UDP_CODE_COMPLETION_LOGGER -#ifdef UDP_CODE_COMPLETION_LOGGER_PORT - const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime(); - llvm::SmallString<256> LogResult; - llvm::raw_svector_ostream os(LogResult); - - // Figure out the language and whether or not it uses PCH. - const char *lang = 0; - bool usesPCH = false; - - for (std::vector::iterator I = argv.begin(), E = argv.end(); - I != E; ++I) { - if (*I == 0) - continue; - if (strcmp(*I, "-x") == 0) { - if (I + 1 != E) { - lang = *(++I); - continue; - } - } - else if (strcmp(*I, "-include") == 0) { - if (I+1 != E) { - const char *arg = *(++I); - llvm::SmallString<512> pchName; - { - llvm::raw_svector_ostream os(pchName); - os << arg << ".pth"; - } - pchName.push_back('\0'); - struct stat stat_results; - if (stat(pchName.data(), &stat_results) == 0) - usesPCH = true; - continue; - } - } - } - - os << "{ "; - os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime()); - os << ", \"numRes\": " << Results->NumResults; - os << ", \"diags\": " << Results->Diagnostics.size(); - os << ", \"pch\": " << (usesPCH ? "true" : "false"); - os << ", \"lang\": \"" << (lang ? lang : "") << '"'; - const char *name = getlogin(); - os << ", \"user\": \"" << (name ? name : "unknown") << '"'; - os << ", \"clangVer\": \"" << getClangFullVersion() << '"'; - os << " }"; - - llvm::StringRef res = os.str(); - if (res.size() > 0) { - do { - // Setup the UDP socket. - struct sockaddr_in servaddr; - bzero(&servaddr, sizeof(servaddr)); - servaddr.sin_family = AF_INET; - servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT); - if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER, - &servaddr.sin_addr) <= 0) - break; - - int sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd < 0) - break; - - sendto(sockfd, res.data(), res.size(), 0, - (struct sockaddr *)&servaddr, sizeof(servaddr)); - close(sockfd); - } - while (false); - } -#endif -#endif - return Results; -} - -void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) { - if (!ResultsIn) - return; - - AllocatedCXCodeCompleteResults *Results - = static_cast(ResultsIn); - delete Results; -} - -unsigned -clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) { - AllocatedCXCodeCompleteResults *Results - = static_cast(ResultsIn); - if (!Results) - return 0; - - return Results->Diagnostics.size(); -} - -CXDiagnostic -clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn, - unsigned Index) { - AllocatedCXCodeCompleteResults *Results - = static_cast(ResultsIn); - if (!Results || Index >= Results->Diagnostics.size()) - return 0; - - return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts); -} - - -} // end extern "C" diff --git a/tools/CIndex/CIndexDiagnostic.cpp b/tools/CIndex/CIndexDiagnostic.cpp deleted file mode 100644 index 3db37b97da1..00000000000 --- a/tools/CIndex/CIndexDiagnostic.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/*===-- CIndexDiagnostics.cpp - Diagnostics C Interface ---------*- C++ -*-===*\ -|* *| -|* The LLVM Compiler Infrastructure *| -|* *| -|* This file is distributed under the University of Illinois Open Source *| -|* License. See LICENSE.TXT for details. *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* Implements the diagnostic functions of the Clang C interface. *| -|* *| -\*===----------------------------------------------------------------------===*/ -#include "CIndexDiagnostic.h" -#include "CIndexer.h" -#include "CXSourceLocation.h" - -#include "clang/Frontend/ASTUnit.h" -#include "clang/Frontend/FrontendDiagnostic.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/ADT/Twine.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/raw_ostream.h" - -using namespace clang; -using namespace clang::cxloc; -using namespace clang::cxstring; -using namespace llvm; - -//----------------------------------------------------------------------------- -// C Interface Routines -//----------------------------------------------------------------------------- -extern "C" { - -unsigned clang_getNumDiagnostics(CXTranslationUnit Unit) { - ASTUnit *CXXUnit = static_cast(Unit); - return CXXUnit? CXXUnit->stored_diag_size() : 0; -} - -CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, unsigned Index) { - ASTUnit *CXXUnit = static_cast(Unit); - if (!CXXUnit || Index >= CXXUnit->stored_diag_size()) - return 0; - - return new CXStoredDiagnostic(CXXUnit->stored_diag_begin()[Index], - CXXUnit->getASTContext().getLangOptions()); -} - -void clang_disposeDiagnostic(CXDiagnostic Diagnostic) { - CXStoredDiagnostic *Stored = static_cast(Diagnostic); - delete Stored; -} - -CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options) { - if (!Diagnostic) - return createCXString(""); - - CXDiagnosticSeverity Severity = clang_getDiagnosticSeverity(Diagnostic); - - // Ignore diagnostics that should be ignored. - if (Severity == CXDiagnostic_Ignored) - return createCXString(""); - - llvm::SmallString<256> Str; - llvm::raw_svector_ostream Out(Str); - - if (Options & CXDiagnostic_DisplaySourceLocation) { - // Print source location (file:line), along with optional column - // and source ranges. - CXFile File; - unsigned Line, Column; - clang_getInstantiationLocation(clang_getDiagnosticLocation(Diagnostic), - &File, &Line, &Column, 0); - if (File) { - CXString FName = clang_getFileName(File); - Out << clang_getCString(FName) << ":" << Line << ":"; - clang_disposeString(FName); - if (Options & CXDiagnostic_DisplayColumn) - Out << Column << ":"; - - if (Options & CXDiagnostic_DisplaySourceRanges) { - unsigned N = clang_getDiagnosticNumRanges(Diagnostic); - bool PrintedRange = false; - for (unsigned I = 0; I != N; ++I) { - CXFile StartFile, EndFile; - CXSourceRange Range = clang_getDiagnosticRange(Diagnostic, I); - - unsigned StartLine, StartColumn, EndLine, EndColumn; - clang_getInstantiationLocation(clang_getRangeStart(Range), - &StartFile, &StartLine, &StartColumn, - 0); - clang_getInstantiationLocation(clang_getRangeEnd(Range), - &EndFile, &EndLine, &EndColumn, 0); - - if (StartFile != EndFile || StartFile != File) - continue; - - Out << "{" << StartLine << ":" << StartColumn << "-" - << EndLine << ":" << EndColumn << "}"; - PrintedRange = true; - } - if (PrintedRange) - Out << ":"; - } - } - - Out << " "; - } - - /* Print warning/error/etc. */ - switch (Severity) { - case CXDiagnostic_Ignored: assert(0 && "impossible"); break; - case CXDiagnostic_Note: Out << "note: "; break; - case CXDiagnostic_Warning: Out << "warning: "; break; - case CXDiagnostic_Error: Out << "error: "; break; - case CXDiagnostic_Fatal: Out << "fatal error: "; break; - } - - CXString Text = clang_getDiagnosticSpelling(Diagnostic); - if (clang_getCString(Text)) - Out << clang_getCString(Text); - else - Out << ""; - clang_disposeString(Text); - return createCXString(Out.str(), true); -} - -unsigned clang_defaultDiagnosticDisplayOptions() { - return CXDiagnostic_DisplaySourceLocation | CXDiagnostic_DisplayColumn; -} - -enum CXDiagnosticSeverity clang_getDiagnosticSeverity(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag) - return CXDiagnostic_Ignored; - - switch (StoredDiag->Diag.getLevel()) { - case Diagnostic::Ignored: return CXDiagnostic_Ignored; - case Diagnostic::Note: return CXDiagnostic_Note; - case Diagnostic::Warning: return CXDiagnostic_Warning; - case Diagnostic::Error: return CXDiagnostic_Error; - case Diagnostic::Fatal: return CXDiagnostic_Fatal; - } - - llvm_unreachable("Invalid diagnostic level"); - return CXDiagnostic_Ignored; -} - -CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag || StoredDiag->Diag.getLocation().isInvalid()) - return clang_getNullLocation(); - - return translateSourceLocation(StoredDiag->Diag.getLocation().getManager(), - StoredDiag->LangOpts, - StoredDiag->Diag.getLocation()); -} - -CXString clang_getDiagnosticSpelling(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag) - return createCXString(""); - - return createCXString(StoredDiag->Diag.getMessage(), false); -} - -unsigned clang_getDiagnosticNumRanges(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag || StoredDiag->Diag.getLocation().isInvalid()) - return 0; - - return StoredDiag->Diag.range_size(); -} - -CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diag, unsigned Range) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag || Range >= StoredDiag->Diag.range_size() || - StoredDiag->Diag.getLocation().isInvalid()) - return clang_getNullRange(); - - return translateSourceRange(StoredDiag->Diag.getLocation().getManager(), - StoredDiag->LangOpts, - StoredDiag->Diag.range_begin()[Range]); -} - -unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag) - return 0; - - return StoredDiag->Diag.fixit_size(); -} - -CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic, unsigned FixIt, - CXSourceRange *ReplacementRange) { - CXStoredDiagnostic *StoredDiag - = static_cast(Diagnostic); - if (!StoredDiag || FixIt >= StoredDiag->Diag.fixit_size() || - StoredDiag->Diag.getLocation().isInvalid()) { - if (ReplacementRange) - *ReplacementRange = clang_getNullRange(); - - return createCXString(""); - } - - const FixItHint &Hint = StoredDiag->Diag.fixit_begin()[FixIt]; - if (ReplacementRange) { - if (Hint.RemoveRange.isInvalid()) { - // Create an empty range that refers to a single source - // location (which is the insertion point). - CXSourceRange Range = { - { (void *)&StoredDiag->Diag.getLocation().getManager(), - (void *)&StoredDiag->LangOpts }, - Hint.InsertionLoc.getRawEncoding(), - Hint.InsertionLoc.getRawEncoding() - }; - - *ReplacementRange = Range; - } else { - // Create a range that covers the entire replacement (or - // removal) range, adjusting the end of the range to point to - // the end of the token. - *ReplacementRange - = translateSourceRange(StoredDiag->Diag.getLocation().getManager(), - StoredDiag->LangOpts, - Hint.RemoveRange); - } - } - - return createCXString(Hint.CodeToInsert); -} - -} // end extern "C" - -void clang::LoadSerializedDiagnostics(const llvm::sys::Path &DiagnosticsPath, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - FileManager &FileMgr, - SourceManager &SourceMgr, - SmallVectorImpl &Diags) { - using llvm::MemoryBuffer; - using llvm::StringRef; - MemoryBuffer *F = MemoryBuffer::getFile(DiagnosticsPath.c_str()); - if (!F) - return; - - // Enter the unsaved files into the file manager. - for (unsigned I = 0; I != num_unsaved_files; ++I) { - const FileEntry *File = FileMgr.getVirtualFile(unsaved_files[I].Filename, - unsaved_files[I].Length, - 0); - if (!File) { - // FIXME: Hard to localize when we have no diagnostics engine! - Diags.push_back(StoredDiagnostic(Diagnostic::Fatal, - (Twine("could not remap from missing file ") + - unsaved_files[I].Filename).str())); - delete F; - return; - } - - MemoryBuffer *Buffer - = MemoryBuffer::getMemBuffer(unsaved_files[I].Contents, - unsaved_files[I].Contents + unsaved_files[I].Length); - if (!Buffer) { - delete F; - return; - } - - SourceMgr.overrideFileContents(File, Buffer); - SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User); - } - - // Parse the diagnostics, emitting them one by one until we've - // exhausted the data. - StringRef Buffer = F->getBuffer(); - const char *Memory = Buffer.data(), *MemoryEnd = Memory + Buffer.size(); - while (Memory != MemoryEnd) { - StoredDiagnostic Stored = StoredDiagnostic::Deserialize(FileMgr, SourceMgr, - Memory, MemoryEnd); - if (!Stored) - break; - - Diags.push_back(Stored); - } - delete F; -} diff --git a/tools/CIndex/CIndexDiagnostic.h b/tools/CIndex/CIndexDiagnostic.h deleted file mode 100644 index 919c21cfdbe..00000000000 --- a/tools/CIndex/CIndexDiagnostic.h +++ /dev/null @@ -1,53 +0,0 @@ -/*===-- CIndexDiagnostic.h - Diagnostics C Interface ------------*- C++ -*-===*\ -|* *| -|* The LLVM Compiler Infrastructure *| -|* *| -|* This file is distributed under the University of Illinois Open Source *| -|* License. See LICENSE.TXT for details. *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* Implements the diagnostic functions of the Clang C interface. *| -|* *| -\*===----------------------------------------------------------------------===*/ -#ifndef LLVM_CLANG_CINDEX_DIAGNOSTIC_H -#define LLVM_CLANG_CINDEX_DIAGNOSTIC_H - -struct CXUnsavedFile; - -namespace llvm { -template class SmallVectorImpl; -namespace sys { class Path; } -} - -namespace clang { - -class Diagnostic; -class FileManager; -class LangOptions; -class Preprocessor; -class StoredDiagnostic; -class SourceManager; - -/// \brief The storage behind a CXDiagnostic -struct CXStoredDiagnostic { - const StoredDiagnostic &Diag; - const LangOptions &LangOpts; - - CXStoredDiagnostic(const StoredDiagnostic &Diag, - const LangOptions &LangOpts) - : Diag(Diag), LangOpts(LangOpts) { } -}; - -/// \brief Given the path to a file that contains binary, serialized -/// diagnostics produced by Clang, load those diagnostics. -void LoadSerializedDiagnostics(const llvm::sys::Path &DiagnosticsPath, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - FileManager &FileMgr, - SourceManager &SourceMgr, - llvm::SmallVectorImpl &Diags); - -} // end namespace clang - -#endif // LLVM_CLANG_CINDEX_DIAGNOSTIC_H diff --git a/tools/CIndex/CIndexInclusionStack.cpp b/tools/CIndex/CIndexInclusionStack.cpp deleted file mode 100644 index e86323956f9..00000000000 --- a/tools/CIndex/CIndexInclusionStack.cpp +++ /dev/null @@ -1,67 +0,0 @@ -//===- CIndexInclusionStack.cpp - Clang-C Source Indexing Library ---------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines a callback mechanism for clients to get the inclusion -// stack from a translation unit. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CXSourceLocation.h" -#include "clang/AST/DeclVisitor.h" -#include "clang/Frontend/ASTUnit.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/raw_ostream.h" -using namespace clang; - -extern "C" { -void clang_getInclusions(CXTranslationUnit TU, CXInclusionVisitor CB, - CXClientData clientData) { - - ASTUnit *CXXUnit = static_cast(TU); - SourceManager &SM = CXXUnit->getSourceManager(); - ASTContext &Ctx = CXXUnit->getASTContext(); - - llvm::SmallVector InclusionStack; - unsigned i = SM.sloc_loaded_entry_size(); - unsigned n = SM.sloc_entry_size(); - - // In the case where all the SLocEntries are in an external source, traverse - // those SLocEntries as well. This is the case where we are looking - // at the inclusion stack of an AST/PCH file. - if (i >= n) - i = 0; - - for ( ; i < n ; ++i) { - - const SrcMgr::SLocEntry &SL = SM.getSLocEntry(i); - - if (!SL.isFile()) - continue; - - const SrcMgr::FileInfo &FI = SL.getFile(); - if (!FI.getContentCache()->Entry) - continue; - - // Build the inclusion stack. - SourceLocation L = FI.getIncludeLoc(); - InclusionStack.clear(); - while (L.isValid()) { - PresumedLoc PLoc = SM.getPresumedLoc(L); - InclusionStack.push_back(cxloc::translateSourceLocation(Ctx, L)); - L = PLoc.getIncludeLoc(); - } - - // Callback to the client. - // FIXME: We should have a function to construct CXFiles. - CB((CXFile) FI.getContentCache()->Entry, - InclusionStack.data(), InclusionStack.size(), clientData); - } -} -} // end extern C diff --git a/tools/CIndex/CIndexUSRs.cpp b/tools/CIndex/CIndexUSRs.cpp deleted file mode 100644 index 58870b930b1..00000000000 --- a/tools/CIndex/CIndexUSRs.cpp +++ /dev/null @@ -1,469 +0,0 @@ -//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the generation and use of USRs from CXEntities. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CXCursor.h" -#include "clang/AST/DeclVisitor.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/Lex/PreprocessingRecord.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/raw_ostream.h" - -using namespace clang; -using namespace clang::cxstring; - -//===----------------------------------------------------------------------===// -// USR generation. -//===----------------------------------------------------------------------===// - -namespace { -class USRGenerator : public DeclVisitor { - llvm::raw_ostream &Out; - bool IgnoreResults; - ASTUnit *AU; -public: - USRGenerator(ASTUnit *au, llvm::raw_ostream &out) - : Out(out), IgnoreResults(false), AU(au) {} - - bool ignoreResults() const { return IgnoreResults; } - - // Visitation methods from generating USRs from AST elements. - void VisitBlockDecl(BlockDecl *D); - void VisitDeclContext(DeclContext *D); - void VisitFieldDecl(FieldDecl *D); - void VisitFunctionDecl(FunctionDecl *D); - void VisitNamedDecl(NamedDecl *D); - void VisitNamespaceDecl(NamespaceDecl *D); - void VisitObjCClassDecl(ObjCClassDecl *CD); - void VisitObjCContainerDecl(ObjCContainerDecl *CD); - void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *P); - void VisitObjCMethodDecl(ObjCMethodDecl *MD); - void VisitObjCPropertyDecl(ObjCPropertyDecl *D); - void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); - void VisitTagDecl(TagDecl *D); - void VisitTypedefDecl(TypedefDecl *D); - void VisitVarDecl(VarDecl *D); - - /// Generate the string component containing the location of the - /// declaration. - void GenLoc(const Decl *D); - - /// String generation methods used both by the visitation methods - /// and from other clients that want to directly generate USRs. These - /// methods do not construct complete USRs (which incorporate the parents - /// of an AST element), but only the fragments concerning the AST element - /// itself. - - /// Generate a USR fragment for a named declaration. This does - /// not include the USR component for the parent. - void GenNamedDecl(llvm::StringRef name); - - /// Generate a USR for an Objective-C class. - void GenObjCClass(llvm::StringRef cls); - /// Generate a USR for an Objective-C class category. - void GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat); - /// Generate a USR fragment for an Objective-C instance variable. The - /// complete USR can be created by concatenating the USR for the - /// encompassing class with this USR fragment. - void GenObjCIvar(llvm::StringRef ivar); - /// Generate a USR fragment for an Objective-C method. - void GenObjCMethod(llvm::StringRef sel, bool isInstanceMethod); - /// Generate a USR fragment for an Objective-C property. - void GenObjCProperty(llvm::StringRef prop); - /// Generate a USR for an Objective-C protocol. - void GenObjCProtocol(llvm::StringRef prot); -}; - -class StringUSRGenerator { -private: - llvm::SmallString<1024> StrBuf; - llvm::raw_svector_ostream Out; - USRGenerator UG; -public: - StringUSRGenerator(const CXCursor *C = 0) - : Out(StrBuf), UG(C ? cxcursor::getCursorASTUnit(*C) : 0, Out) { - // Add the USR space prefix. - Out << "c:"; - } - - llvm::StringRef str() { - return Out.str(); - } - - USRGenerator* operator->() { return &UG; } - - template - llvm::raw_svector_ostream &operator<<(const T &x) { - Out << x; - return Out; - } -}; - -} // end anonymous namespace - -//===----------------------------------------------------------------------===// -// Generating USRs from ASTS. -//===----------------------------------------------------------------------===// - -void USRGenerator::VisitBlockDecl(BlockDecl *D) { - VisitDeclContext(D->getDeclContext()); - // FIXME: Better support for anonymous blocks. - Out << "@B@anon"; -} - -void USRGenerator::VisitDeclContext(DeclContext *DC) { - if (NamedDecl *D = dyn_cast(DC)) - Visit(D); -} - -void USRGenerator::VisitFieldDecl(FieldDecl *D) { - const std::string &s = D->getNameAsString(); - if (s.empty()) { - // Bit fields can be anonymous. - IgnoreResults = true; - return; - } - VisitDeclContext(D->getDeclContext()); - Out << (isa(D) ? "@" : "@FI@") << s; -} - -void USRGenerator::VisitFunctionDecl(FunctionDecl *D) { - VisitDeclContext(D->getDeclContext()); - Out << "@F@" << D; -} - -void USRGenerator::VisitNamedDecl(NamedDecl *D) { - VisitDeclContext(D->getDeclContext()); - const std::string &s = D->getNameAsString(); - // The string can be empty if the declaration has no name; e.g., it is - // the ParmDecl with no name for declaration of a function pointer type, e.g.: - // void (*f)(void *); - // In this case, don't generate a USR. - if (s.empty()) - IgnoreResults = true; - else - GenNamedDecl(s); -} - -void USRGenerator::VisitVarDecl(VarDecl *D) { - // VarDecls can be declared 'extern' within a function or method body, - // but their enclosing DeclContext is the function, not the TU. We need - // to check the storage class to correctly generate the USR. - if (!D->hasExternalStorage()) - VisitDeclContext(D->getDeclContext()); - - const std::string &s = D->getNameAsString(); - // The string can be empty if the declaration has no name; e.g., it is - // the ParmDecl with no name for declaration of a function pointer type, e.g.: - // void (*f)(void *); - // In this case, don't generate a USR. - if (s.empty()) - IgnoreResults = true; - else - GenNamedDecl(s); -} - -void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) { - VisitDeclContext(D->getDeclContext()); - Out << "@N@" << D; -} - -void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) { - Visit(cast(D->getDeclContext())); - GenObjCMethod(DeclarationName(D->getSelector()).getAsString(), - D->isInstanceMethod()); -} - -void USRGenerator::VisitObjCClassDecl(ObjCClassDecl *D) { - // FIXME: @class declarations can refer to multiple classes. We need - // to be able to traverse these. - IgnoreResults = true; -} - -void USRGenerator::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { - // FIXME: @protocol declarations can refer to multiple protocols. We need - // to be able to traverse these. - IgnoreResults = true; -} - -void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) { - switch (D->getKind()) { - default: - assert(false && "Invalid ObjC container."); - case Decl::ObjCInterface: - case Decl::ObjCImplementation: - GenObjCClass(D->getName()); - break; - case Decl::ObjCCategory: { - ObjCCategoryDecl *CD = cast(D); - ObjCInterfaceDecl *ID = CD->getClassInterface(); - if (!ID) { - // Handle invalid code where the @interface might not - // have been specified. - // FIXME: We should be able to generate this USR even if the - // @interface isn't available. - IgnoreResults = true; - return; - } - GenObjCCategory(ID->getName(), CD->getName()); - break; - } - case Decl::ObjCCategoryImpl: { - ObjCCategoryImplDecl *CD = cast(D); - ObjCInterfaceDecl *ID = CD->getClassInterface(); - if (!ID) { - // Handle invalid code where the @interface might not - // have been specified. - // FIXME: We should be able to generate this USR even if the - // @interface isn't available. - IgnoreResults = true; - return; - } - GenObjCCategory(ID->getName(), CD->getName()); - break; - } - case Decl::ObjCProtocol: - GenObjCProtocol(cast(D)->getName()); - break; - } -} - -void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { - Visit(cast(D->getDeclContext())); - GenObjCProperty(D->getName()); -} - -void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { - if (ObjCPropertyDecl *PD = D->getPropertyDecl()) { - VisitObjCPropertyDecl(PD); - return; - } - - IgnoreResults = true; -} - -void USRGenerator::VisitTagDecl(TagDecl *D) { - D = D->getCanonicalDecl(); - VisitDeclContext(D->getDeclContext()); - switch (D->getTagKind()) { - case TagDecl::TK_struct: Out << "@S"; break; - case TagDecl::TK_class: Out << "@C"; break; - case TagDecl::TK_union: Out << "@U"; break; - case TagDecl::TK_enum: Out << "@E"; break; - } - - const std::string &s = D->getNameAsString(); - const TypedefDecl *TD = 0; - if (s.empty()) { - TD = D->getTypedefForAnonDecl(); - Out << (TD ? 'A' : 'a'); - } - - // Add the location of the tag decl to handle resolution across - // translation units. - if (D->getLinkage() == NoLinkage) { - Out << '@'; - GenLoc(D); - if (IgnoreResults) - return; - } - - if (s.empty()) { - if (TD) - Out << '@' << TD; - } - else - Out << '@' << s; -} - -void USRGenerator::VisitTypedefDecl(TypedefDecl *D) { - DeclContext *DC = D->getDeclContext(); - if (NamedDecl *DCN = dyn_cast(DC)) - Visit(DCN); - Out << "@T@"; - if (D->getLinkage() == NoLinkage) { - GenLoc(D); - if (IgnoreResults) - return; - Out << '@'; - } - Out << D->getName(); -} - -void USRGenerator::GenLoc(const Decl *D) { - const SourceManager &SM = AU->getSourceManager(); - SourceLocation L = D->getLocStart(); - if (L.isInvalid()) { - IgnoreResults = true; - return; - } - L = SM.getInstantiationLoc(L); - const std::pair &Decomposed = SM.getDecomposedLoc(L); - const FileEntry *FE = SM.getFileEntryForID(Decomposed.first); - if (FE) { - llvm::sys::Path P(FE->getName()); - Out << P.getLast(); - } - else { - // This case really isn't interesting. - IgnoreResults = true; - return; - } - Out << '@' - << SM.getLineNumber(Decomposed.first, Decomposed.second) << ':' - << SM.getColumnNumber(Decomposed.first, Decomposed.second); -} - -//===----------------------------------------------------------------------===// -// General purpose USR generation methods. -//===----------------------------------------------------------------------===// - -void USRGenerator::GenNamedDecl(llvm::StringRef name) { - Out << "@" << name; -} - -void USRGenerator::GenObjCClass(llvm::StringRef cls) { - Out << "objc(cs)" << cls; -} - -void USRGenerator::GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat) { - Out << "objc(cy)" << cls << '@' << cat; -} - -void USRGenerator::GenObjCIvar(llvm::StringRef ivar) { - GenNamedDecl(ivar); -} - -void USRGenerator::GenObjCMethod(llvm::StringRef meth, bool isInstanceMethod) { - Out << (isInstanceMethod ? "(im)" : "(cm)") << meth; -} - -void USRGenerator::GenObjCProperty(llvm::StringRef prop) { - Out << "(py)" << prop; -} - -void USRGenerator::GenObjCProtocol(llvm::StringRef prot) { - Out << "objc(pl)" << prot; -} - -//===----------------------------------------------------------------------===// -// API hooks. -//===----------------------------------------------------------------------===// - -static inline llvm::StringRef extractUSRSuffix(llvm::StringRef s) { - return s.startswith("c:") ? s.substr(2) : ""; -} - -static CXString getDeclCursorUSR(const CXCursor &C) { - Decl *D = cxcursor::getCursorDecl(C); - - // Don't generate USRs for things with invalid locations. - if (!D || D->getLocStart().isInvalid()) - return createCXString(""); - - // Check if the cursor has 'NoLinkage'. - if (const NamedDecl *ND = dyn_cast(D)) - switch (ND->getLinkage()) { - case ExternalLinkage: - // Generate USRs for all entities with external linkage. - break; - case NoLinkage: - // We allow enums, typedefs, and structs that have no linkage to - // have USRs that are anchored to the file they were defined in - // (e.g., the header). This is a little gross, but in principal - // enums/anonymous structs/etc. defined in a common header file - // are referred to across multiple translation units. - if (isa(ND) || isa(ND) || - isa(ND) || isa(ND)) - break; - // Fall-through. - case InternalLinkage: - case UniqueExternalLinkage: - return createCXString(""); - } - - StringUSRGenerator SUG(&C); - SUG->Visit(D); - - if (SUG->ignoreResults()) - return createCXString(""); - - // For development testing. - // assert(SUG.str().size() > 2); - - // Return a copy of the string that must be disposed by the caller. - return createCXString(SUG.str(), true); -} - -extern "C" { - -CXString clang_getCursorUSR(CXCursor C) { - const CXCursorKind &K = clang_getCursorKind(C); - - if (clang_isDeclaration(K)) - return getDeclCursorUSR(C); - - if (K == CXCursor_MacroDefinition) { - StringUSRGenerator SUG(&C); - SUG << "macro@" - << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart(); - return createCXString(SUG.str(), true); - } - - return createCXString(""); -} - -CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) { - StringUSRGenerator SUG; - SUG << extractUSRSuffix(clang_getCString(classUSR)); - SUG->GenObjCIvar(name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCMethod(const char *name, - unsigned isInstanceMethod, - CXString classUSR) { - StringUSRGenerator SUG; - SUG << extractUSRSuffix(clang_getCString(classUSR)); - SUG->GenObjCMethod(name, isInstanceMethod); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCClass(const char *name) { - StringUSRGenerator SUG; - SUG->GenObjCClass(name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCProtocol(const char *name) { - StringUSRGenerator SUG; - SUG->GenObjCProtocol(name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCCategory(const char *class_name, - const char *category_name) { - StringUSRGenerator SUG; - SUG->GenObjCCategory(class_name, category_name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCProperty(const char *property, - CXString classUSR) { - StringUSRGenerator SUG; - SUG << extractUSRSuffix(clang_getCString(classUSR)); - SUG->GenObjCProperty(property); - return createCXString(SUG.str(), true); -} - -} // end extern "C" diff --git a/tools/CIndex/CIndexer.cpp b/tools/CIndex/CIndexer.cpp deleted file mode 100644 index d5131ff6d86..00000000000 --- a/tools/CIndex/CIndexer.cpp +++ /dev/null @@ -1,154 +0,0 @@ -//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the Clang-C Source Indexing library. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" - -#include "clang/AST/Decl.h" -#include "clang/AST/DeclVisitor.h" -#include "clang/AST/StmtVisitor.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/Version.h" -#include "clang/Sema/CodeCompleteConsumer.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/Config/config.h" -#include "llvm/Support/Compiler.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/System/Program.h" - -#include -#include -#include - -#ifdef LLVM_ON_WIN32 -#include -#else -#include -#endif - -using namespace clang; - -const llvm::sys::Path& CIndexer::getClangPath() { - // Did we already compute the path? - if (!ClangPath.empty()) - return ClangPath; - - // Find the location where this library lives (libCIndex.dylib). -#ifdef LLVM_ON_WIN32 - MEMORY_BASIC_INFORMATION mbi; - char path[MAX_PATH]; - VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi, - sizeof(mbi)); - GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH); - - llvm::sys::Path CIndexPath(path); - - CIndexPath.eraseComponent(); - CIndexPath.appendComponent("clang"); - CIndexPath.appendSuffix("exe"); - CIndexPath.makeAbsolute(); -#else - // This silly cast below avoids a C++ warning. - Dl_info info; - if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0) - assert(0 && "Call to dladdr() failed"); - - llvm::sys::Path CIndexPath(info.dli_fname); - - // We now have the CIndex directory, locate clang relative to it. - CIndexPath.eraseComponent(); - CIndexPath.appendComponent(".."); - CIndexPath.appendComponent("bin"); - CIndexPath.appendComponent("clang"); -#endif - - // Cache our result. - ClangPath = CIndexPath; - return ClangPath; -} - -std::string CIndexer::getClangResourcesPath() { - llvm::sys::Path P = getClangPath(); - - if (!P.empty()) { - P.eraseComponent(); // Remove /clang from foo/bin/clang - P.eraseComponent(); // Remove /bin from foo/bin - - // Get foo/lib/clang//include - P.appendComponent("lib"); - P.appendComponent("clang"); - P.appendComponent(CLANG_VERSION_STRING); - } - - return P.str(); -} - -static llvm::sys::Path GetTemporaryPath() { - // FIXME: This is lame; sys::Path should provide this function (in particular, - // it should know how to find the temporary files dir). - std::string Error; - const char *TmpDir = ::getenv("TMPDIR"); - if (!TmpDir) - TmpDir = ::getenv("TEMP"); - if (!TmpDir) - TmpDir = ::getenv("TMP"); - if (!TmpDir) - TmpDir = "/tmp"; - llvm::sys::Path P(TmpDir); - P.appendComponent("remap"); - if (P.makeUnique(false, &Error)) - return llvm::sys::Path(""); - - // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. - P.eraseFromDisk(false, 0); - - return P; -} - -bool clang::RemapFiles(unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - std::vector &RemapArgs, - std::vector &TemporaryFiles) { - for (unsigned i = 0; i != num_unsaved_files; ++i) { - // Write the contents of this unsaved file into the temporary file. - llvm::sys::Path SavedFile(GetTemporaryPath()); - if (SavedFile.empty()) - return true; - - std::string ErrorInfo; - llvm::raw_fd_ostream OS(SavedFile.c_str(), ErrorInfo); - if (!ErrorInfo.empty()) - return true; - - OS.write(unsaved_files[i].Contents, unsaved_files[i].Length); - OS.close(); - if (OS.has_error()) { - SavedFile.eraseFromDisk(); - return true; - } - - // Remap the file. - std::string RemapArg = unsaved_files[i].Filename; - RemapArg += ';'; - RemapArg += SavedFile.str(); - RemapArgs.push_back("-Xclang"); - RemapArgs.push_back("-remap-file"); - RemapArgs.push_back("-Xclang"); - RemapArgs.push_back(RemapArg); - TemporaryFiles.push_back(SavedFile); - } - - return false; -} - diff --git a/tools/CIndex/CIndexer.h b/tools/CIndex/CIndexer.h deleted file mode 100644 index 31bf779ea4a..00000000000 --- a/tools/CIndex/CIndexer.h +++ /dev/null @@ -1,78 +0,0 @@ -//===- CIndexer.h - Clang-C Source Indexing Library -----------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines CIndexer, a subclass of Indexer that provides extra -// functionality needed by the CIndex library. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_CINDEXER_H -#define LLVM_CLANG_CINDEXER_H - -#include "clang-c/Index.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/System/Path.h" -#include - -namespace clang { -namespace cxstring { - CXString createCXString(const char *String, bool DupString = false); - CXString createCXString(llvm::StringRef String, bool DupString = true); -} -} - -class CIndexer { - bool UseExternalASTGeneration; - bool OnlyLocalDecls; - bool DisplayDiagnostics; - - llvm::sys::Path ClangPath; - -public: - CIndexer() - : UseExternalASTGeneration(false), OnlyLocalDecls(false), - DisplayDiagnostics(false) { } - - /// \brief Whether we only want to see "local" declarations (that did not - /// come from a previous precompiled header). If false, we want to see all - /// declarations. - bool getOnlyLocalDecls() const { return OnlyLocalDecls; } - void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; } - - bool getDisplayDiagnostics() const { return DisplayDiagnostics; } - void setDisplayDiagnostics(bool Display = true) { - DisplayDiagnostics = Display; - } - - bool getUseExternalASTGeneration() const { return UseExternalASTGeneration; } - void setUseExternalASTGeneration(bool Value) { - UseExternalASTGeneration = Value; - } - - /// \brief Get the path of the clang binary. - const llvm::sys::Path& getClangPath(); - - /// \brief Get the path of the clang resource files. - std::string getClangResourcesPath(); -}; - -namespace clang { - /** - * \brief Given a set of "unsaved" files, create temporary files and - * construct the clang -cc1 argument list needed to perform the remapping. - * - * \returns true if an error occurred. - */ - bool RemapFiles(unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - std::vector &RemapArgs, - std::vector &TemporaryFiles); -} - -#endif diff --git a/tools/CIndex/CMakeLists.txt b/tools/CIndex/CMakeLists.txt deleted file mode 100644 index 609719e627f..00000000000 --- a/tools/CIndex/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -set(SHARED_LIBRARY TRUE) - -set(LLVM_NO_RTTI 1) - -set(LLVM_USED_LIBS - clangFrontend - clangDriver - clangSema - clangAnalysis - clangAST - clangParse - clangLex - clangBasic) - -set( LLVM_LINK_COMPONENTS - bitreader - mc - core - ) - -add_clang_library(CIndex - CIndex.cpp - CIndexCodeCompletion.cpp - CIndexDiagnostic.cpp - CIndexInclusionStack.cpp - CIndexUSRs.cpp - CIndexer.cpp - CXCursor.cpp - ../../include/clang-c/Index.h -) - -if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - # FIXME: Deal with LLVM_SUBMIT_VERSION? - - # FIXME: This uses a special darwin-specific exports file in order to - # get underscore-prefixed names. It would be better to have build rules - # which know how to produce a darwin-suitable exports file from the - # regular exports file. - set_target_properties(CIndex - PROPERTIES - LINK_FLAGS "-avoid-version -Wl,-exported_symbols_list -Wl,${CMAKE_CURRENT_SOURCE_DIR}/CIndex.darwin.exports -Wl,-dead_strip -Wl,-seg1addr -Wl,0xE0000000" - INSTALL_NAME_DIR "@executable_path/../lib" - ) -endif() - -if(MSVC) - # windows.h doesn't compile with /Za - get_target_property(NON_ANSI_COMPILE_FLAGS CIndex COMPILE_FLAGS) - string(REPLACE /Za "" NON_ANSI_COMPILE_FLAGS ${NON_ANSI_COMPILE_FLAGS}) - set_target_properties(CIndex PROPERTIES COMPILE_FLAGS ${NON_ANSI_COMPILE_FLAGS}) -endif(MSVC) - -set_target_properties(CIndex - PROPERTIES - LINKER_LANGUAGE CXX - DEFINE_SYMBOL _CINDEX_LIB_) diff --git a/tools/CIndex/CXCursor.cpp b/tools/CIndex/CXCursor.cpp deleted file mode 100644 index 3bc5d01fbad..00000000000 --- a/tools/CIndex/CXCursor.cpp +++ /dev/null @@ -1,369 +0,0 @@ -//===- CXCursor.cpp - Routines for manipulating CXCursors -----------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines routines for manipulating CXCursors. It should be the -// only file that has internal knowledge of the encoding of the data in -// CXCursor. -// -//===----------------------------------------------------------------------===// - -#include "CXCursor.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/AST/Decl.h" -#include "clang/AST/DeclObjC.h" -#include "clang/AST/Expr.h" -#include "llvm/Support/ErrorHandling.h" - -using namespace clang; - -CXCursor cxcursor::MakeCXCursorInvalid(CXCursorKind K) { - assert(K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid); - CXCursor C = { K, { 0, 0, 0 } }; - return C; -} - -static CXCursorKind GetCursorKind(Decl *D) { - assert(D && "Invalid arguments!"); - switch (D->getKind()) { - case Decl::Enum: return CXCursor_EnumDecl; - case Decl::EnumConstant: return CXCursor_EnumConstantDecl; - case Decl::Field: return CXCursor_FieldDecl; - case Decl::Function: - return CXCursor_FunctionDecl; - case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl; - case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl; - case Decl::ObjCClass: - // FIXME - return CXCursor_UnexposedDecl; - case Decl::ObjCForwardProtocol: - // FIXME - return CXCursor_UnexposedDecl; - case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl; - case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl; - case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl; - case Decl::ObjCMethod: - return cast(D)->isInstanceMethod() - ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl; - case Decl::CXXMethod: return CXCursor_CXXMethod; - case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl; - case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl; - case Decl::ParmVar: return CXCursor_ParmDecl; - case Decl::Typedef: return CXCursor_TypedefDecl; - case Decl::Var: return CXCursor_VarDecl; - default: - if (TagDecl *TD = dyn_cast(D)) { - switch (TD->getTagKind()) { - case TagDecl::TK_struct: return CXCursor_StructDecl; - case TagDecl::TK_class: return CXCursor_ClassDecl; - case TagDecl::TK_union: return CXCursor_UnionDecl; - case TagDecl::TK_enum: return CXCursor_EnumDecl; - } - } - - return CXCursor_UnexposedDecl; - } - - llvm_unreachable("Invalid Decl"); - return CXCursor_NotImplemented; -} - -static CXCursorKind GetCursorKind(const Attr *A) { - assert(A && "Invalid arguments!"); - switch (A->getKind()) { - default: break; - case Attr::IBActionKind: return CXCursor_IBActionAttr; - case Attr::IBOutletKind: return CXCursor_IBOutletAttr; - } - - return CXCursor_UnexposedAttr; -} - -CXCursor cxcursor::MakeCXCursor(const Attr *A, Decl *Parent, ASTUnit *TU) { - assert(A && Parent && TU && "Invalid arguments!"); - CXCursor C = { GetCursorKind(A), { Parent, (void*)A, TU } }; - return C; -} - -CXCursor cxcursor::MakeCXCursor(Decl *D, ASTUnit *TU) { - assert(D && TU && "Invalid arguments!"); - CXCursor C = { GetCursorKind(D), { D, 0, TU } }; - return C; -} - -CXCursor cxcursor::MakeCXCursor(Stmt *S, Decl *Parent, ASTUnit *TU) { - assert(S && TU && "Invalid arguments!"); - CXCursorKind K = CXCursor_NotImplemented; - - switch (S->getStmtClass()) { - case Stmt::NoStmtClass: - break; - - case Stmt::NullStmtClass: - case Stmt::CompoundStmtClass: - case Stmt::CaseStmtClass: - case Stmt::DefaultStmtClass: - case Stmt::LabelStmtClass: - case Stmt::IfStmtClass: - case Stmt::SwitchStmtClass: - case Stmt::WhileStmtClass: - case Stmt::DoStmtClass: - case Stmt::ForStmtClass: - case Stmt::GotoStmtClass: - case Stmt::IndirectGotoStmtClass: - case Stmt::ContinueStmtClass: - case Stmt::BreakStmtClass: - case Stmt::ReturnStmtClass: - case Stmt::DeclStmtClass: - case Stmt::SwitchCaseClass: - case Stmt::AsmStmtClass: - case Stmt::ObjCAtTryStmtClass: - case Stmt::ObjCAtCatchStmtClass: - case Stmt::ObjCAtFinallyStmtClass: - case Stmt::ObjCAtThrowStmtClass: - case Stmt::ObjCAtSynchronizedStmtClass: - case Stmt::ObjCForCollectionStmtClass: - case Stmt::CXXCatchStmtClass: - case Stmt::CXXTryStmtClass: - K = CXCursor_UnexposedStmt; - break; - - case Stmt::PredefinedExprClass: - case Stmt::IntegerLiteralClass: - case Stmt::FloatingLiteralClass: - case Stmt::ImaginaryLiteralClass: - case Stmt::StringLiteralClass: - case Stmt::CharacterLiteralClass: - case Stmt::ParenExprClass: - case Stmt::UnaryOperatorClass: - case Stmt::SizeOfAlignOfExprClass: - case Stmt::ArraySubscriptExprClass: - case Stmt::BinaryOperatorClass: - case Stmt::CompoundAssignOperatorClass: - case Stmt::ConditionalOperatorClass: - case Stmt::ImplicitCastExprClass: - case Stmt::CStyleCastExprClass: - case Stmt::CompoundLiteralExprClass: - case Stmt::ExtVectorElementExprClass: - case Stmt::InitListExprClass: - case Stmt::DesignatedInitExprClass: - case Stmt::ImplicitValueInitExprClass: - case Stmt::ParenListExprClass: - case Stmt::VAArgExprClass: - case Stmt::AddrLabelExprClass: - case Stmt::StmtExprClass: - case Stmt::TypesCompatibleExprClass: - case Stmt::ChooseExprClass: - case Stmt::GNUNullExprClass: - case Stmt::CXXStaticCastExprClass: - case Stmt::CXXDynamicCastExprClass: - case Stmt::CXXReinterpretCastExprClass: - case Stmt::CXXConstCastExprClass: - case Stmt::CXXFunctionalCastExprClass: - case Stmt::CXXTypeidExprClass: - case Stmt::CXXBoolLiteralExprClass: - case Stmt::CXXNullPtrLiteralExprClass: - case Stmt::CXXThisExprClass: - case Stmt::CXXThrowExprClass: - case Stmt::CXXDefaultArgExprClass: - case Stmt::CXXZeroInitValueExprClass: - case Stmt::CXXNewExprClass: - case Stmt::CXXDeleteExprClass: - case Stmt::CXXPseudoDestructorExprClass: - case Stmt::UnresolvedLookupExprClass: - case Stmt::UnaryTypeTraitExprClass: - case Stmt::DependentScopeDeclRefExprClass: - case Stmt::CXXBindTemporaryExprClass: - case Stmt::CXXBindReferenceExprClass: - case Stmt::CXXExprWithTemporariesClass: - case Stmt::CXXUnresolvedConstructExprClass: - case Stmt::CXXDependentScopeMemberExprClass: - case Stmt::UnresolvedMemberExprClass: - case Stmt::ObjCStringLiteralClass: - case Stmt::ObjCEncodeExprClass: - case Stmt::ObjCSelectorExprClass: - case Stmt::ObjCProtocolExprClass: - case Stmt::ObjCImplicitSetterGetterRefExprClass: - case Stmt::ObjCSuperExprClass: - case Stmt::ObjCIsaExprClass: - case Stmt::ShuffleVectorExprClass: - case Stmt::BlockExprClass: - K = CXCursor_UnexposedExpr; - break; - case Stmt::DeclRefExprClass: - case Stmt::BlockDeclRefExprClass: - // FIXME: UnresolvedLookupExpr? - // FIXME: DependentScopeDeclRefExpr? - K = CXCursor_DeclRefExpr; - break; - - case Stmt::MemberExprClass: - case Stmt::ObjCIvarRefExprClass: - case Stmt::ObjCPropertyRefExprClass: - // FIXME: UnresolvedMemberExpr? - // FIXME: CXXDependentScopeMemberExpr? - K = CXCursor_MemberRefExpr; - break; - - case Stmt::CallExprClass: - case Stmt::CXXOperatorCallExprClass: - case Stmt::CXXMemberCallExprClass: - case Stmt::CXXConstructExprClass: - case Stmt::CXXTemporaryObjectExprClass: - // FIXME: CXXUnresolvedConstructExpr - // FIXME: ObjCImplicitSetterGetterRefExpr? - K = CXCursor_CallExpr; - break; - - case Stmt::ObjCMessageExprClass: - K = CXCursor_ObjCMessageExpr; - break; - } - - CXCursor C = { K, { Parent, S, TU } }; - return C; -} - -CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super, - SourceLocation Loc, - ASTUnit *TU) { - assert(Super && TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_ObjCSuperClassRef, { Super, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorObjCSuperClassRef(CXCursor C) { - assert(C.kind == CXCursor_ObjCSuperClassRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakeCursorObjCProtocolRef(ObjCProtocolDecl *Super, - SourceLocation Loc, - ASTUnit *TU) { - assert(Super && TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_ObjCProtocolRef, { Super, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorObjCProtocolRef(CXCursor C) { - assert(C.kind == CXCursor_ObjCProtocolRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakeCursorObjCClassRef(ObjCInterfaceDecl *Class, - SourceLocation Loc, - ASTUnit *TU) { - // 'Class' can be null for invalid code. - if (!Class) - return MakeCXCursorInvalid(CXCursor_InvalidCode); - assert(TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_ObjCClassRef, { Class, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorObjCClassRef(CXCursor C) { - assert(C.kind == CXCursor_ObjCClassRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakeCursorTypeRef(TypeDecl *Type, SourceLocation Loc, - ASTUnit *TU) { - assert(Type && TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_TypeRef, { Type, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorTypeRef(CXCursor C) { - assert(C.kind == CXCursor_TypeRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range, - ASTUnit *TU) { - CXCursor C = { CXCursor_PreprocessingDirective, - { reinterpret_cast(Range.getBegin().getRawEncoding()), - reinterpret_cast(Range.getEnd().getRawEncoding()), - TU } - }; - return C; -} - -SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) { - assert(C.kind == CXCursor_PreprocessingDirective); - return SourceRange(SourceLocation::getFromRawEncoding( - reinterpret_cast (C.data[0])), - SourceLocation::getFromRawEncoding( - reinterpret_cast (C.data[1]))); -} - -CXCursor cxcursor::MakeMacroDefinitionCursor(MacroDefinition *MI, ASTUnit *TU) { - CXCursor C = { CXCursor_MacroDefinition, { MI, 0, TU } }; - return C; -} - -MacroDefinition *cxcursor::getCursorMacroDefinition(CXCursor C) { - assert(C.kind == CXCursor_MacroDefinition); - return static_cast(C.data[0]); -} - -CXCursor cxcursor::MakeMacroInstantiationCursor(MacroInstantiation *MI, - ASTUnit *TU) { - CXCursor C = { CXCursor_MacroInstantiation, { MI, 0, TU } }; - return C; -} - -MacroInstantiation *cxcursor::getCursorMacroInstantiation(CXCursor C) { - assert(C.kind == CXCursor_MacroInstantiation); - return static_cast(C.data[0]); -} - -Decl *cxcursor::getCursorDecl(CXCursor Cursor) { - return (Decl *)Cursor.data[0]; -} - -Expr *cxcursor::getCursorExpr(CXCursor Cursor) { - return dyn_cast_or_null(getCursorStmt(Cursor)); -} - -Stmt *cxcursor::getCursorStmt(CXCursor Cursor) { - if (Cursor.kind == CXCursor_ObjCSuperClassRef || - Cursor.kind == CXCursor_ObjCProtocolRef || - Cursor.kind == CXCursor_ObjCClassRef) - return 0; - - return (Stmt *)Cursor.data[1]; -} - -ASTContext &cxcursor::getCursorContext(CXCursor Cursor) { - return getCursorASTUnit(Cursor)->getASTContext(); -} - -ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) { - return static_cast(Cursor.data[2]); -} - -bool cxcursor::operator==(CXCursor X, CXCursor Y) { - return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] && - X.data[2] == Y.data[2]; -} diff --git a/tools/CIndex/CXCursor.h b/tools/CIndex/CXCursor.h deleted file mode 100644 index 1664f5a9ced..00000000000 --- a/tools/CIndex/CXCursor.h +++ /dev/null @@ -1,112 +0,0 @@ -//===- CXCursor.h - Routines for manipulating CXCursors -------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines routines for manipulating CXCursors. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_CXCURSOR_H -#define LLVM_CLANG_CXCURSOR_H - -#include "clang-c/Index.h" -#include "clang/Basic/SourceLocation.h" -#include - -namespace clang { - -class ASTContext; -class ASTUnit; -class Attr; -class Decl; -class Expr; -class MacroDefinition; -class MacroInstantiation; -class NamedDecl; -class ObjCInterfaceDecl; -class ObjCProtocolDecl; -class Stmt; -class TypeDecl; - -namespace cxcursor { - -CXCursor MakeCXCursor(const clang::Attr *A, clang::Decl *Parent, ASTUnit *TU); -CXCursor MakeCXCursor(clang::Decl *D, ASTUnit *TU); -CXCursor MakeCXCursor(clang::Stmt *S, clang::Decl *Parent, ASTUnit *TU); -CXCursor MakeCXCursorInvalid(CXCursorKind K); - -/// \brief Create an Objective-C superclass reference at the given location. -CXCursor MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super, - SourceLocation Loc, - ASTUnit *TU); - -/// \brief Unpack an ObjCSuperClassRef cursor into the interface it references -/// and optionally the location where the reference occurred. -std::pair - getCursorObjCSuperClassRef(CXCursor C); - -/// \brief Create an Objective-C protocol reference at the given location. -CXCursor MakeCursorObjCProtocolRef(ObjCProtocolDecl *Proto, SourceLocation Loc, - ASTUnit *TU); - -/// \brief Unpack an ObjCProtocolRef cursor into the protocol it references -/// and optionally the location where the reference occurred. -std::pair - getCursorObjCProtocolRef(CXCursor C); - -/// \brief Create an Objective-C class reference at the given location. -CXCursor MakeCursorObjCClassRef(ObjCInterfaceDecl *Class, SourceLocation Loc, - ASTUnit *TU); - -/// \brief Unpack an ObjCClassRef cursor into the class it references -/// and optionally the location where the reference occurred. -std::pair - getCursorObjCClassRef(CXCursor C); - -/// \brief Create a type reference at the given location. -CXCursor MakeCursorTypeRef(TypeDecl *Type, SourceLocation Loc, ASTUnit *TU); - -/// \brief Unpack a TypeRef cursor into the class it references -/// and optionally the location where the reference occurred. -std::pair getCursorTypeRef(CXCursor C); - -/// \brief Create a preprocessing directive cursor. -CXCursor MakePreprocessingDirectiveCursor(SourceRange Range, ASTUnit *TU); - -/// \brief Unpack a given preprocessing directive to retrieve its source range. -SourceRange getCursorPreprocessingDirective(CXCursor C); - -/// \brief Create a macro definition cursor. -CXCursor MakeMacroDefinitionCursor(MacroDefinition *, ASTUnit *TU); - -/// \brief Unpack a given macro definition cursor to retrieve its -/// source range. -MacroDefinition *getCursorMacroDefinition(CXCursor C); - -/// \brief Create a macro instantiation cursor. -CXCursor MakeMacroInstantiationCursor(MacroInstantiation *, ASTUnit *TU); - -/// \brief Unpack a given macro instantiation cursor to retrieve its -/// source range. -MacroInstantiation *getCursorMacroInstantiation(CXCursor C); - -Decl *getCursorDecl(CXCursor Cursor); -Expr *getCursorExpr(CXCursor Cursor); -Stmt *getCursorStmt(CXCursor Cursor); -ASTContext &getCursorContext(CXCursor Cursor); -ASTUnit *getCursorASTUnit(CXCursor Cursor); - -bool operator==(CXCursor X, CXCursor Y); - -inline bool operator!=(CXCursor X, CXCursor Y) { - return !(X == Y); -} - -}} // end namespace: clang::cxcursor - -#endif diff --git a/tools/CIndex/CXSourceLocation.h b/tools/CIndex/CXSourceLocation.h deleted file mode 100644 index 66566c12689..00000000000 --- a/tools/CIndex/CXSourceLocation.h +++ /dev/null @@ -1,75 +0,0 @@ -//===- CXSourceLocation.h - CXSourceLocations Utilities ---------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines routines for manipulating CXSourceLocations. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_CXSOURCELOCATION_H -#define LLVM_CLANG_CXSOURCELOCATION_H - -#include "clang-c/Index.h" -#include "clang/Basic/SourceLocation.h" -#include "clang/Basic/LangOptions.h" -#include "clang/AST/ASTContext.h" - -namespace clang { - -class SourceManager; - -namespace cxloc { - -/// \brief Translate a Clang source location into a CIndex source location. -static inline CXSourceLocation -translateSourceLocation(const SourceManager &SM, const LangOptions &LangOpts, - SourceLocation Loc) { - CXSourceLocation Result = { { (void*) &SM, (void*) &LangOpts, }, - Loc.getRawEncoding() }; - return Result; -} - -/// \brief Translate a Clang source location into a CIndex source location. -static inline CXSourceLocation translateSourceLocation(ASTContext &Context, - SourceLocation Loc) { - return translateSourceLocation(Context.getSourceManager(), - Context.getLangOptions(), - Loc); -} - -/// \brief Translate a Clang source range into a CIndex source range. -/// -/// Clang internally represents ranges where the end location points to the -/// start of the token at the end. However, for external clients it is more -/// useful to have a CXSourceRange be a proper half-open interval. This routine -/// does the appropriate translation. -CXSourceRange translateSourceRange(const SourceManager &SM, - const LangOptions &LangOpts, - SourceRange R); - -/// \brief Translate a Clang source range into a CIndex source range. -static inline CXSourceRange translateSourceRange(ASTContext &Context, - SourceRange R) { - return translateSourceRange(Context.getSourceManager(), - Context.getLangOptions(), - R); -} - -static inline SourceLocation translateSourceLocation(CXSourceLocation L) { - return SourceLocation::getFromRawEncoding(L.int_data); -} - -static inline SourceRange translateCXSourceRange(CXSourceRange R) { - return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data), - SourceLocation::getFromRawEncoding(R.end_int_data)); -} - - -}} // end namespace: clang::cxloc - -#endif diff --git a/tools/CIndex/Makefile b/tools/CIndex/Makefile deleted file mode 100644 index 391746d4d4f..00000000000 --- a/tools/CIndex/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -##===- tools/CIndex/Makefile -------------------------------*- Makefile -*-===## -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open Source -# License. See LICENSE.TXT for details. -# -##===----------------------------------------------------------------------===## - -LEVEL = ../../../.. -LIBRARYNAME = CIndex - -EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/CIndex.exports - -CPP.Flags += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include - -# Include this here so we can get the configuration of the targets -# that have been configured for construction. We have to do this -# early so we can set up LINK_COMPONENTS before including Makefile.rules -include $(LEVEL)/Makefile.config - -LINK_LIBS_IN_SHARED = 1 -SHARED_LIBRARY = 1 - -LINK_COMPONENTS := bitreader mc core -USEDLIBS = clangFrontend.a clangDriver.a clangSema.a \ - clangAnalysis.a clangAST.a clangParse.a clangLex.a clangBasic.a - -include $(LEVEL)/Makefile.common - -##===----------------------------------------------------------------------===## -# FIXME: This is copied from the 'lto' makefile. Should we share this? -##===----------------------------------------------------------------------===## - -ifeq ($(HOST_OS),Darwin) - # set dylib internal version number to llvmCore submission number - ifdef LLVM_SUBMIT_VERSION - LLVMLibsOptions := $(LLVMLibsOptions) -Wl,-current_version \ - -Wl,$(LLVM_SUBMIT_VERSION).$(LLVM_SUBMIT_SUBVERSION) \ - -Wl,-compatibility_version -Wl,1 - endif - # extra options to override libtool defaults - LLVMLibsOptions := $(LLVMLibsOptions) \ - -avoid-version \ - -Wl,-dead_strip \ - -Wl,-seg1addr -Wl,0xE0000000 - - # Mac OS X 10.4 and earlier tools do not allow a second -install_name on command line - DARWIN_VERS := $(shell echo $(TARGET_TRIPLE) | sed 's/.*darwin\([0-9]*\).*/\1/') - ifneq ($(DARWIN_VERS),8) - LLVMLibsOptions := $(LLVMLibsOptions) \ - -no-undefined -Wl,-install_name \ - -Wl,"@executable_path/../lib/lib$(LIBRARYNAME)$(SHLIBEXT)" - endif -endif diff --git a/tools/index-test/CMakeLists.txt b/tools/index-test/CMakeLists.txt deleted file mode 100644 index 9472e580fbc..00000000000 --- a/tools/index-test/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -set(LLVM_NO_RTTI 1) - -set( LLVM_USED_LIBS - clangIndex - clangFrontend - clangDriver - clangSema - clangAnalysis - clangAST - clangParse - clangLex - clangBasic - ) - -set( LLVM_LINK_COMPONENTS - bitreader - mc - core - ) - -add_clang_executable(index-test - index-test.cpp - ) diff --git a/tools/index-test/Makefile b/tools/index-test/Makefile deleted file mode 100644 index 4ee98fc7cc9..00000000000 --- a/tools/index-test/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -##===- tools/index-test/Makefile ---------------------------*- Makefile -*-===## -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open Source -# License. See LICENSE.TXT for details. -# -##===----------------------------------------------------------------------===## -LEVEL = ../../../.. - -TOOLNAME = index-test -CPPFLAGS += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include -CXXFLAGS = -fno-rtti -NO_INSTALL = 1 - -# No plugins, optimize startup time. -TOOL_NO_EXPORTS = 1 - -include $(LEVEL)/Makefile.config - -LINK_COMPONENTS := bitreader mc core -USEDLIBS = clangIndex.a clangFrontend.a clangDriver.a clangSema.a \ - clangAnalysis.a clangAST.a clangParse.a clangLex.a clangBasic.a - -include $(LLVM_SRC_ROOT)/Makefile.rules diff --git a/tools/index-test/index-test.cpp b/tools/index-test/index-test.cpp deleted file mode 100644 index ff9fd543115..00000000000 --- a/tools/index-test/index-test.cpp +++ /dev/null @@ -1,334 +0,0 @@ -//===--- index-test.cpp - Indexing test bed -------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This utility may be invoked in the following manner: -// index-test --help - Output help info. -// index-test [options] - Read from stdin. -// index-test [options] file - Read from "file". -// index-test [options] file1 file2 - Read these files. -// -// Files must be AST files. -// -//===----------------------------------------------------------------------===// -// -// -point-at [file:line:column] -// Point at a declaration/statement/expression. If no other operation is -// specified, prints some info about it. -// -// -print-refs -// Print ASTLocations that reference the -point-at node -// -// -print-defs -// Print ASTLocations that define the -point-at node -// -// -print-decls -// Print ASTLocations that declare the -point-at node -// -//===----------------------------------------------------------------------===// - -#include "clang/Index/Program.h" -#include "clang/Index/Indexer.h" -#include "clang/Index/Entity.h" -#include "clang/Index/TranslationUnit.h" -#include "clang/Index/ASTLocation.h" -#include "clang/Index/DeclReferenceMap.h" -#include "clang/Index/SelectorMap.h" -#include "clang/Index/Handlers.h" -#include "clang/Index/Analyzer.h" -#include "clang/Index/Utils.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/CompilerInvocation.h" -#include "clang/Frontend/DiagnosticOptions.h" -#include "clang/Frontend/TextDiagnosticPrinter.h" -#include "clang/Frontend/CommandLineSourceLoc.h" -#include "clang/AST/DeclObjC.h" -#include "clang/AST/ExprObjC.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/SourceManager.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/ManagedStatic.h" -#include "llvm/Support/PrettyStackTrace.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/System/Signals.h" -using namespace clang; -using namespace idx; - -class TUnit : public TranslationUnit { -public: - TUnit(ASTUnit *ast, const std::string &filename) - : AST(ast), Filename(filename), - DeclRefMap(ast->getASTContext()), - SelMap(ast->getASTContext()) { } - - virtual ASTContext &getASTContext() { return AST->getASTContext(); } - virtual DeclReferenceMap &getDeclReferenceMap() { return DeclRefMap; } - virtual SelectorMap &getSelectorMap() { return SelMap; } - - llvm::OwningPtr AST; - std::string Filename; - DeclReferenceMap DeclRefMap; - SelectorMap SelMap; -}; - -static llvm::cl::list -PointAtLocation("point-at", llvm::cl::Optional, - llvm::cl::value_desc("source-location"), - llvm::cl::desc("Point at the given source location of the first AST file")); - -enum ProgActions { - PrintPoint, // Just print the point-at node - PrintRefs, // Print references of the point-at node - PrintDefs, // Print definitions of the point-at node - PrintDecls // Print declarations of the point-at node -}; - -static llvm::cl::opt -ProgAction( - llvm::cl::desc("Choose action to perform on the pointed-at AST node:"), - llvm::cl::ZeroOrMore, - llvm::cl::init(PrintPoint), - llvm::cl::values( - clEnumValN(PrintRefs, "print-refs", - "Print references"), - clEnumValN(PrintDefs, "print-defs", - "Print definitions"), - clEnumValN(PrintDecls, "print-decls", - "Print declarations"), - clEnumValEnd)); - -static llvm::cl::opt -DisableFree("disable-free", - llvm::cl::desc("Disable freeing of memory on exit"), - llvm::cl::init(false)); - -static bool HadErrors = false; - -static void ProcessObjCMessage(ObjCMessageExpr *Msg, Indexer &Idxer) { - llvm::raw_ostream &OS = llvm::outs(); - typedef Storing ResultsTy; - ResultsTy Results; - - Analyzer Analyz(Idxer.getProgram(), Idxer); - - switch (ProgAction) { - default: assert(0); - case PrintRefs: - llvm::errs() << "Error: Cannot -print-refs on a ObjC message expression\n"; - HadErrors = true; - return; - - case PrintDecls: { - Analyz.FindObjCMethods(Msg, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) - I->print(OS); - break; - } - - case PrintDefs: { - Analyz.FindObjCMethods(Msg, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) { - const ObjCMethodDecl *D = cast(I->AsDecl()); - if (D->isThisDeclarationADefinition()) - I->print(OS); - } - break; - } - - } -} - -static void ProcessASTLocation(ASTLocation ASTLoc, Indexer &Idxer) { - assert(ASTLoc.isValid()); - - if (ObjCMessageExpr *Msg = - dyn_cast_or_null(ASTLoc.dyn_AsStmt())) - return ProcessObjCMessage(Msg, Idxer); - - Decl *D = ASTLoc.getReferencedDecl(); - if (D == 0) { - llvm::errs() << "Error: Couldn't get referenced Decl for the ASTLocation\n"; - HadErrors = true; - return; - } - - llvm::raw_ostream &OS = llvm::outs(); - typedef Storing ResultsTy; - ResultsTy Results; - - Analyzer Analyz(Idxer.getProgram(), Idxer); - - switch (ProgAction) { - default: assert(0); - case PrintRefs: { - Analyz.FindReferences(D, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) - I->print(OS); - break; - } - - case PrintDecls: { - Analyz.FindDeclarations(D, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) - I->print(OS); - break; - } - - case PrintDefs: { - Analyz.FindDeclarations(D, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) { - const Decl *D = I->AsDecl(); - bool isDef = false; - if (const FunctionDecl *FD = dyn_cast(D)) - isDef = FD->isThisDeclarationADefinition(); - else if (const VarDecl *VD = dyn_cast(D)) - isDef = VD->getInit() != 0; - else if (const ObjCMethodDecl *MD = dyn_cast(D)) - isDef = MD->isThisDeclarationADefinition(); - - if (isDef) - I->print(OS); - } - break; - } - - } -} - -static llvm::cl::opt -ASTFromSource("ast-from-source", - llvm::cl::desc("Treat the inputs as source files to parse")); - -static llvm::cl::list -CompilerArgs("arg", llvm::cl::desc("Extra arguments to use during parsing")); - -static llvm::cl::list -InputFilenames(llvm::cl::Positional, llvm::cl::desc("")); - -ASTUnit *CreateFromSource(const std::string &Filename, Diagnostic &Diags, - const char *Argv0) { - llvm::SmallVector Args; - Args.push_back(Filename.c_str()); - for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i) - Args.push_back(CompilerArgs[i].c_str()); - - void *MainAddr = (void*) (intptr_t) CreateFromSource; - std::string ResourceDir = - CompilerInvocation::GetResourcesPath(Argv0, MainAddr); - return ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), - Diags, ResourceDir); -} - -int main(int argc, char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(); - llvm::PrettyStackTraceProgram X(argc, argv); - llvm::cl::ParseCommandLineOptions(argc, argv, - "LLVM 'Clang' Indexing Test Bed: http://clang.llvm.org\n"); - - Program Prog; - Indexer Idxer(Prog); - llvm::SmallVector TUnits; - - DiagnosticOptions DiagOpts; - llvm::OwningPtr Diags( - CompilerInstance::createDiagnostics(DiagOpts, argc, argv)); - - // If no input was specified, read from stdin. - if (InputFilenames.empty()) - InputFilenames.push_back("-"); - - for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) { - const std::string &InFile = InputFilenames[i]; - llvm::OwningPtr AST; - if (ASTFromSource) - AST.reset(CreateFromSource(InFile, *Diags, argv[0])); - else - AST.reset(ASTUnit::LoadFromPCHFile(InFile, *Diags)); - if (!AST) - return 1; - - TUnit *TU = new TUnit(AST.take(), InFile); - TUnits.push_back(TU); - - Idxer.IndexAST(TU); - } - - ASTLocation ASTLoc; - const std::string &FirstFile = TUnits[0]->Filename; - ASTUnit *FirstAST = TUnits[0]->AST.get(); - - if (!PointAtLocation.empty()) { - const std::string &Filename = PointAtLocation[0].FileName; - const FileEntry *File = FirstAST->getFileManager().getFile(Filename); - if (File == 0) { - llvm::errs() << "File '" << Filename << "' does not exist\n"; - return 1; - } - - // Safety check. Using an out-of-date AST file will only lead to crashes - // or incorrect results. - // FIXME: Check all the source files that make up the AST file. - const FileEntry *ASTFile = FirstAST->getFileManager().getFile(FirstFile); - if (File->getModificationTime() > ASTFile->getModificationTime()) { - llvm::errs() << "[" << FirstFile << "] Error: " << - "Pointing at a source file which was modified after creating " - "the AST file\n"; - return 1; - } - - unsigned Line = PointAtLocation[0].Line; - unsigned Col = PointAtLocation[0].Column; - - SourceLocation Loc = - FirstAST->getSourceManager().getLocation(File, Line, Col); - if (Loc.isInvalid()) { - llvm::errs() << "[" << FirstFile << "] Error: " << - "Couldn't resolve source location (invalid location)\n"; - return 1; - } - - ASTLoc = ResolveLocationInAST(FirstAST->getASTContext(), Loc); - if (ASTLoc.isInvalid()) { - llvm::errs() << "[" << FirstFile << "] Error: " << - "Couldn't resolve source location (no declaration found)\n"; - return 1; - } - } - - if (ASTLoc.isValid()) { - if (ProgAction == PrintPoint) { - llvm::raw_ostream &OS = llvm::outs(); - ASTLoc.print(OS); - if (const char *Comment = - FirstAST->getASTContext().getCommentForDecl(ASTLoc.dyn_AsDecl())) - OS << "Comment associated with this declaration:\n" << Comment << "\n"; - } else { - ProcessASTLocation(ASTLoc, Idxer); - } - } - - if (HadErrors) - return 1; - - if (!DisableFree) { - for (int i=0, e=TUnits.size(); i != e; ++i) - delete TUnits[i]; - } - - // Managed static deconstruction. Useful for making things like - // -time-passes usable. - llvm::llvm_shutdown(); - - return 0; -} diff --git a/utils/pch-test.pl b/utils/pch-test.pl deleted file mode 100755 index 2e17117a2a2..00000000000 --- a/utils/pch-test.pl +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/perl -w - -# This tiny little script, which should be run from the clang -# directory (with clang-cc in your patch), tries to take each -# compilable Clang test and build a PCH file from that test, then read -# and dump the contents of the PCH file just created. -use POSIX; - -$exitcode = 0; -sub testfiles($$) { - my $suffix = shift; - my $language = shift; - my $passed = 0; - my $failed = 0; - my $skipped = 0; - - @files = `ls test/*/*.$suffix`; - foreach $file (@files) { - chomp($file); - my $code = system("clang-cc -fsyntax-only -x $language $file > /dev/null 2>&1"); - if ($code == 0) { - print("."); - $code = system("clang-cc -emit-pch -x $language -o $file.pch $file > /dev/null 2>&1"); - if ($code == 0) { - $code = system("clang-cc -include-pch $file.pch -x $language -ast-dump /dev/null > /dev/null 2>&1"); - if ($code == 0) { - $passed++; - } elsif (($code & 0xFF) == SIGINT) { - exit($exitcode); - } else { - print("\n---Failed to dump AST file for \"$file\"---\n"); - $exitcode = 1; - $failed++; - } - unlink "$file.pch"; - } elsif (($code & 0xFF) == SIGINT) { - exit($exitcode); - } else { - print("\n---Failed to build PCH file for \"$file\"---\n"); - $exitcode = 1; - $failed++; - } - } elsif (($code & 0xFF) == SIGINT) { - exit($exitcode); - } else { - print("x"); - $skipped++; - } - } - - print("\n\n$passed tests passed\n"); - print("$failed tests failed\n"); - print("$skipped tests skipped ('x')\n") -} - -printf("-----Testing precompiled headers for C-----\n"); -testfiles("c", "c"); -printf("\n-----Testing precompiled headers for Objective-C-----\n"); -testfiles("m", "objective-c"); -print("\n"); -exit($exitcode); diff --git a/win32/clangAST/clangAST.vcproj b/win32/clangAST/clangAST.vcproj deleted file mode 100644 index 8795412ba8c..00000000000 --- a/win32/clangAST/clangAST.vcproj +++ /dev/null @@ -1,347 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangAnalysis/clangAnalysis.vcproj b/win32/clangAnalysis/clangAnalysis.vcproj deleted file mode 100644 index c9850e059cf..00000000000 --- a/win32/clangAnalysis/clangAnalysis.vcproj +++ /dev/null @@ -1,351 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangBasic/clangBasic.vcproj b/win32/clangBasic/clangBasic.vcproj deleted file mode 100644 index d836a6604c7..00000000000 --- a/win32/clangBasic/clangBasic.vcproj +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangCodeGen/clangCodeGen.vcproj b/win32/clangCodeGen/clangCodeGen.vcproj deleted file mode 100644 index a819fd94d86..00000000000 --- a/win32/clangCodeGen/clangCodeGen.vcproj +++ /dev/null @@ -1,271 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangDriver/clangDriver.vcproj b/win32/clangDriver/clangDriver.vcproj deleted file mode 100644 index 0a744bbe4e9..00000000000 --- a/win32/clangDriver/clangDriver.vcproj +++ /dev/null @@ -1,270 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangLex/clangLex.vcproj b/win32/clangLex/clangLex.vcproj deleted file mode 100644 index 5bec4b8b8e7..00000000000 --- a/win32/clangLex/clangLex.vcproj +++ /dev/null @@ -1,283 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangLibDriver/clangLibDriver.vcproj b/win32/clangLibDriver/clangLibDriver.vcproj deleted file mode 100644 index de42ef72a78..00000000000 --- a/win32/clangLibDriver/clangLibDriver.vcproj +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangParse/clangParse.vcproj b/win32/clangParse/clangParse.vcproj deleted file mode 100644 index 4cf55253054..00000000000 --- a/win32/clangParse/clangParse.vcproj +++ /dev/null @@ -1,248 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangRewrite/clangRewrite.vcproj b/win32/clangRewrite/clangRewrite.vcproj deleted file mode 100644 index 7b1f898f9d6..00000000000 --- a/win32/clangRewrite/clangRewrite.vcproj +++ /dev/null @@ -1,191 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangSema/clangSema.vcproj b/win32/clangSema/clangSema.vcproj deleted file mode 100644 index 572c3effcaf..00000000000 --- a/win32/clangSema/clangSema.vcproj +++ /dev/null @@ -1,263 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/www/analyzer/menu.js b/www/analyzer/menu.js deleted file mode 100644 index 6b393c081c8..00000000000 --- a/www/analyzer/menu.js +++ /dev/null @@ -1,17 +0,0 @@ -startList = function() { - if (document.all&&document.getElementById) { - navRoot = document.getElementById("nav"); - for (i=0; i Date: Thu, 16 Sep 2010 22:11:55 +0000 Subject: [PATCH 0825/1624] The inflight bandwidth limiter was removed in r212765. --- share/man/man4/tcp.4 | 68 +------------------------------------------- 1 file changed, 1 insertion(+), 67 deletions(-) diff --git a/share/man/man4/tcp.4 b/share/man/man4/tcp.4 index 47c81f547d3..26afd8bdb6f 100644 --- a/share/man/man4/tcp.4 +++ b/share/man/man4/tcp.4 @@ -32,7 +32,7 @@ .\" From: @(#)tcp.4 8.1 (Berkeley) 6/5/93 .\" $FreeBSD$ .\" -.Dd August 16, 2008 +.Dd September 16, 2010 .Dt TCP 4 .Os .Sh NAME @@ -383,72 +383,6 @@ code. For this reason, we use 200ms of slop and a near-0 minimum, which gives us an effective minimum of 200ms (similar to .Tn Linux ) . -.It Va inflight.enable -Enable -.Tn TCP -bandwidth-delay product limiting. -An attempt will be made to calculate -the bandwidth-delay product for each individual -.Tn TCP -connection, and limit -the amount of inflight data being transmitted, to avoid building up -unnecessary packets in the network. -This option is recommended if you -are serving a lot of data over connections with high bandwidth-delay -products, such as modems, GigE links, and fast long-haul WANs, and/or -you have configured your machine to accommodate large -.Tn TCP -windows. -In such -situations, without this option, you may experience high interactive -latencies or packet loss due to the overloading of intermediate routers -and switches. -Note that bandwidth-delay product limiting only effects -the transmit side of a -.Tn TCP -connection. -.It Va inflight.debug -Enable debugging for the bandwidth-delay product algorithm. -.It Va inflight.min -This puts a lower bound on the bandwidth-delay product window, in bytes. -A value of 1024 is typically used for debugging. -6000-16000 is more typical in a production installation. -Setting this value too low may result in -slow ramp-up times for bursty connections. -Setting this value too high effectively disables the algorithm. -.It Va inflight.max -This puts an upper bound on the bandwidth-delay product window, in bytes. -This value should not generally be modified, but may be used to set a -global per-connection limit on queued data, potentially allowing you to -intentionally set a less than optimum limit, to smooth data flow over a -network while still being able to specify huge internal -.Tn TCP -buffers. -.It Va inflight.stab -The bandwidth-delay product algorithm requires a slightly larger window -than it otherwise calculates for stability. -This parameter determines the extra window in maximal packets / 10. -The default value of 20 represents 2 maximal packets. -Reducing this value is not recommended, but you may -come across a situation with very slow links where the -.Xr ping 8 -time -reduction of the default inflight code is not sufficient. -If this case occurs, you should first try reducing -.Va inflight.min -and, if that does not -work, reduce both -.Va inflight.min -and -.Va inflight.stab , -trying values of -15, 10, or 5 for the latter. -Never use a value less than 5. -Reducing -.Va inflight.stab -can lead to upwards of a 20% underutilization of the link -as well as reducing the algorithm's ability to adapt to changing -situations and should only be done as a last resort. .It Va rfc3042 Enable the Limited Transmit algorithm as described in RFC 3042. It helps avoid timeouts on lossy links and also when the congestion window From 9b91846ce46883d5478ab381c71245e12498a931 Mon Sep 17 00:00:00 2001 From: "David E. O'Brien" Date: Thu, 16 Sep 2010 22:31:03 +0000 Subject: [PATCH 0826/1624] + Add the SCRIPT environmental variable to the sub-shell. Its value is the name of the typescript file. + Add the 'command' argument (if supplied on the command line) to the typescript file. This creates a more complete typescript when invoked this way - more equal to invoking script without supplying the 'command' argument. --- usr.bin/script/script.1 | 13 +++++++++++++ usr.bin/script/script.c | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/usr.bin/script/script.1 b/usr.bin/script/script.1 index 1c93b3e48a1..08ad643d577 100644 --- a/usr.bin/script/script.1 +++ b/usr.bin/script/script.1 @@ -117,6 +117,19 @@ The results are meant to emulate a hardcopy terminal, not an addressable one. The following environment variable is utilized by .Nm : .Bl -tag -width SHELL +.It Ev SCRIPT +The +.Ev SCRIPT +environment variable is added to the sub-shell. +If +.Ev SCRIPT +already existed in the users environment, +its value is overwritten within the sub-shell. +The value of +.Ev SCRIPT +is the name of the +.Ar typescript +file. .It Ev SHELL If the variable .Ev SHELL diff --git a/usr.bin/script/script.c b/usr.bin/script/script.c index 64ca486d063..e8fa922839f 100644 --- a/usr.bin/script/script.c +++ b/usr.bin/script/script.c @@ -235,14 +235,21 @@ static void doshell(char **av) { const char *shell; + int k; shell = getenv("SHELL"); if (shell == NULL) shell = _PATH_BSHELL; + if (av[0]) + for (k = 0 ; av[k] ; ++k) + fprintf(fscript, "%s%s", k ? " " : "", av[k]); + fprintf(fscript, "\r\n"); + (void)close(master); (void)fclose(fscript); login_tty(slave); + setenv("SCRIPT", fname, 1); if (av[0]) { execvp(av[0], av); warn("%s", av[0]); From e5bc6d56e80f3b8d9e9d4e9834a34ac0cf4afb4d Mon Sep 17 00:00:00 2001 From: "David E. O'Brien" Date: Thu, 16 Sep 2010 22:38:27 +0000 Subject: [PATCH 0827/1624] Increase the hostname display width. Many machines are named with >12 characters. This still allows for 80 column output with load averages of 99.99, 99.99, 99.99. --- usr.bin/ruptime/ruptime.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/usr.bin/ruptime/ruptime.c b/usr.bin/ruptime/ruptime.c index 1e3356f6f86..58e598ced07 100644 --- a/usr.bin/ruptime/ruptime.c +++ b/usr.bin/ruptime/ruptime.c @@ -244,12 +244,12 @@ ruptime(const char *host, int aflg, int (*cmp)(const void *, const void *)) for (i = 0; i < (int)nhosts; i++) { hsp = &hs[i]; if (ISDOWN(hsp)) { - (void)printf("%-12.12s%s\n", hsp->hs_wd->wd_hostname, + (void)printf("%-25.25s%s\n", hsp->hs_wd->wd_hostname, interval(now - hsp->hs_wd->wd_recvtime, "down")); continue; } (void)printf( - "%-12.12s%s, %4d user%s load %*.2f, %*.2f, %*.2f\n", + "%-25.25s%s, %4d user%s load %*.2f, %*.2f, %*.2f\n", hsp->hs_wd->wd_hostname, interval((time_t)hsp->hs_wd->wd_sendtime - (time_t)hsp->hs_wd->wd_boottime, " up"), From 63feedfd4687b540b2087087a536edaeb63917b6 Mon Sep 17 00:00:00 2001 From: "Kenneth D. Merry" Date: Thu, 16 Sep 2010 22:54:56 +0000 Subject: [PATCH 0828/1624] MFp4 (//depot/projects/mps/...): According to the MPT2 spec, task management commands are serialized, and so no I/O should start while task management commands are active. So, to comply with that, freeze the SIM queue before we send any task management commands (abort, target reset, etc.) down to the IOC. We unfreeze the queue once the task management command completes. It isn't clear from the spec whether multiple simultaneous task management commands are supported. Right now it is possible to have multiple outstanding task management commands, especially in the abort case. Multiple outstanding aborts do complete successfully, so it may be supported. We also don't yet have any recovery mechanism (e.g. reset the IOC) if the task management command fails. --- sys/dev/mps/mps_sas.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/sys/dev/mps/mps_sas.c b/sys/dev/mps/mps_sas.c index b4f1e4c163d..5d29c9df5cf 100644 --- a/sys/dev/mps/mps_sas.c +++ b/sys/dev/mps/mps_sas.c @@ -438,6 +438,7 @@ mpssas_prepare_remove(struct mpssas_softc *sassc, MPI2_EVENT_SAS_TOPO_PHY_ENTRY cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE; cm->cm_complete = mpssas_remove_device; cm->cm_targ = targ; + xpt_freeze_simq(sc->sassc->sim, 1); mps_map_command(sc, cm); } @@ -453,6 +454,7 @@ mpssas_remove_device(struct mps_softc *sc, struct mps_command *cm) reply = (MPI2_SCSI_TASK_MANAGE_REPLY *)cm->cm_reply; handle = cm->cm_targ->handle; + xpt_release_simq(sc->sassc->sim, 1); if (reply->IOCStatus != MPI2_IOCSTATUS_SUCCESS) { mps_printf(sc, "Failure 0x%x reseting device 0x%04x\n", reply->IOCStatus, handle); @@ -983,6 +985,11 @@ mpssas_abort_complete(struct mps_softc *sc, struct mps_command *cm) mps_printf(sc, "%s: abort request on handle %#04x SMID %d " "complete\n", __func__, req->DevHandle, req->TaskMID); + /* + * Release the SIM queue, we froze it when we sent the abort. + */ + xpt_release_simq(sc->sassc->sim, 1); + mps_free_command(sc, cm); } @@ -1013,10 +1020,19 @@ mpssas_recovery(struct mps_softc *sc, struct mps_command *abort_cm) cm->cm_data = NULL; cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE; + /* + * Freeze the SIM queue while we issue the abort. According to the + * Fusion-MPT 2.0 spec, task management requests are serialized, + * and so the host should not send any I/O requests while task + * management requests are pending. + */ + xpt_freeze_simq(sc->sassc->sim, 1); + error = mps_map_command(sc, cm); if (error != 0) { mps_printf(sc, "%s: error mapping abort request!\n", __func__); + xpt_release_simq(sc->sassc->sim, 1); } #if 0 error = mpssas_reset(sc, targ, &resetcm); @@ -1361,7 +1377,13 @@ mpssas_resetdev(struct mpssas_softc *sassc, struct mps_command *cm) cm->cm_data = NULL; cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE; + xpt_freeze_simq(sassc->sim, 1); + error = mps_map_command(sassc->sc, cm); + + if (error != 0) + xpt_release_simq(sassc->sim, 1); + return (error); } @@ -1385,6 +1407,9 @@ mpssas_resetdev_complete(struct mps_softc *sc, struct mps_command *cm) ccb->ccb_h.status = CAM_REQ_CMP_ERR; mps_free_command(sc, cm); + + xpt_release_simq(sc->sassc->sim, 1); + xpt_done(ccb); } From dbb34a64a0849f52ab4ac9134ea2ad0daf3000fa Mon Sep 17 00:00:00 2001 From: Ed Maste Date: Thu, 16 Sep 2010 23:33:24 +0000 Subject: [PATCH 0829/1624] Use device_printf where possible, and otherwise at least include the driver name in printf strings. Reported by: Mark Johnston --- sys/dev/aac/aac.c | 2 +- sys/dev/aac/aac_cam.c | 2 +- sys/dev/aac/aac_disk.c | 13 ++++++++----- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/sys/dev/aac/aac.c b/sys/dev/aac/aac.c index 3071ddfc225..59b1394120b 100644 --- a/sys/dev/aac/aac.c +++ b/sys/dev/aac/aac.c @@ -391,7 +391,7 @@ aac_get_container_info(struct aac_softc *sc, struct aac_fib *fib, int cid) if (aac_sync_fib(sc, ContainerCommand, 0, fib, sizeof(struct aac_mntinfo))) { - printf("Error probing container %d\n", cid); + device_printf(sc->aac_dev, "Error probing container %d\n", cid); return (NULL); } diff --git a/sys/dev/aac/aac_cam.c b/sys/dev/aac/aac_cam.c index 4bfe0ed5747..2e5a659155e 100644 --- a/sys/dev/aac/aac_cam.c +++ b/sys/dev/aac/aac_cam.c @@ -569,7 +569,7 @@ aac_cam_reset_bus(struct cam_sim *sim, union ccb *ccb) sc = camsc->inf->aac_sc; if (sc == NULL) { - printf("Null sc?\n"); + printf("aac: Null sc?\n"); return (CAM_REQ_ABORTED); } diff --git a/sys/dev/aac/aac_disk.c b/sys/dev/aac/aac_disk.c index fa3b66b87c1..3c9720ddbc1 100644 --- a/sys/dev/aac/aac_disk.c +++ b/sys/dev/aac/aac_disk.c @@ -106,8 +106,9 @@ aac_disk_open(struct disk *dp) /* check that the controller is up and running */ if (sc->ad_controller->aac_state & AAC_STATE_SUSPEND) { - printf("Controller Suspended controller state = 0x%x\n", - sc->ad_controller->aac_state); + device_printf(sc->ad_controller->aac_dev, + "Controller Suspended controller state = 0x%x\n", + sc->ad_controller->aac_state); return(ENXIO); } @@ -252,7 +253,8 @@ aac_disk_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size if (!first) { first = 1; if (bus_dmamap_create(sc->aac_buffer_dmat, 0, &dump_datamap)) { - printf("bus_dmamap_create failed\n"); + device_printf(sc->aac_dev, + "bus_dmamap_create failed\n"); return (ENOMEM); } } @@ -305,8 +307,9 @@ aac_disk_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size size += fib->Header.Size; if (aac_sync_fib(sc, command, 0, fib, size)) { - printf("Error dumping block 0x%jx\n", - (uintmax_t)physical); + device_printf(sc->aac_dev, + "Error dumping block 0x%jx\n", + (uintmax_t)physical); return (EIO); } From 3441a301f2055f9828e0ea214bb20b9d5e9cd6d8 Mon Sep 17 00:00:00 2001 From: Andrew Thompson Date: Fri, 17 Sep 2010 01:09:12 +0000 Subject: [PATCH 0830/1624] Use getenv to find the mac address since it could be in the bootloader environment or command line and under different names. --- sys/mips/atheros/ar71xx_machdep.c | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/sys/mips/atheros/ar71xx_machdep.c b/sys/mips/atheros/ar71xx_machdep.c index 3c1bd5f2ca1..f9bacb6b94d 100644 --- a/sys/mips/atheros/ar71xx_machdep.c +++ b/sys/mips/atheros/ar71xx_machdep.c @@ -145,7 +145,7 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused, { uint64_t platform_counter_freq; int argc, i, count = 0; - char **argv, **envp; + char **argv, **envp, *var; vm_offset_t kernend; /* @@ -167,19 +167,9 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused, * Protect ourselves from garbage in registers */ if (MIPS_IS_VALID_PTR(envp)) { - for (i = 0; envp[i]; i += 2) - { + for (i = 0; envp[i]; i += 2) { if (strcmp(envp[i], "memsize") == 0) realmem = btoc(strtoul(envp[i+1], NULL, 16)); - else if (strcmp(envp[i], "ethaddr") == 0) { - count = sscanf(envp[i+1], "%x.%x.%x.%x.%x.%x", - &ar711_base_mac[0], &ar711_base_mac[1], - &ar711_base_mac[2], &ar711_base_mac[3], - &ar711_base_mac[4], &ar711_base_mac[5]); - if (count < 6) - memset(ar711_base_mac, 0, - sizeof(ar711_base_mac)); - } } } @@ -245,6 +235,18 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused, else printf ("envp is invalid\n"); + if ((var = getenv("ethaddr")) != NULL || + (var = getenv("kmac")) != NULL) { + count = sscanf(var, "%x%*c%x%*c%x%*c%x%*c%x%*c%x", + &ar711_base_mac[0], &ar711_base_mac[1], + &ar711_base_mac[2], &ar711_base_mac[3], + &ar711_base_mac[4], &ar711_base_mac[5]); + if (count < 6) + memset(ar711_base_mac, 0, + sizeof(ar711_base_mac)); + freeenv(var); + } + init_param2(physmem); mips_cpu_init(); pmap_bootstrap(); From 08e58cc093d3e269779d85351515f291b0818f61 Mon Sep 17 00:00:00 2001 From: Andrew Thompson Date: Fri, 17 Sep 2010 01:13:48 +0000 Subject: [PATCH 0831/1624] Make a note of which platforms the mac strings come from. Suggested by: adrian --- sys/mips/atheros/ar71xx_machdep.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sys/mips/atheros/ar71xx_machdep.c b/sys/mips/atheros/ar71xx_machdep.c index f9bacb6b94d..ec355cc4ec1 100644 --- a/sys/mips/atheros/ar71xx_machdep.c +++ b/sys/mips/atheros/ar71xx_machdep.c @@ -235,6 +235,10 @@ platform_start(__register_t a0 __unused, __register_t a1 __unused, else printf ("envp is invalid\n"); + /* + * "ethaddr" is passed via envp on RedBoot platforms + * "kmac" is passed via argv on RouterBOOT platforms + */ if ((var = getenv("ethaddr")) != NULL || (var = getenv("kmac")) != NULL) { count = sscanf(var, "%x%*c%x%*c%x%*c%x%*c%x%*c%x", From db1a9b7dfb12d58bbbd875ef252d10b597edbc0e Mon Sep 17 00:00:00 2001 From: Neel Natu Date: Fri, 17 Sep 2010 02:14:21 +0000 Subject: [PATCH 0832/1624] Get rid of unused macros. --- sys/mips/include/cpuregs.h | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/sys/mips/include/cpuregs.h b/sys/mips/include/cpuregs.h index 6c8f0a327fb..bc55a7eb2e9 100644 --- a/sys/mips/include/cpuregs.h +++ b/sys/mips/include/cpuregs.h @@ -58,10 +58,6 @@ #ifndef _MIPS_CPUREGS_H_ #define _MIPS_CPUREGS_H_ -#if defined(_KERNEL_OPT) -#include "opt_cputype.h" -#endif - /* * Address space. * 32-bit mips CPUS partition their 32-bit address space into four segments: @@ -71,8 +67,6 @@ * kseg1 0xa0000000 - 0xbfffffff Physical memory, uncached, unmapped * kseg2 0xc0000000 - 0xffffffff kernel-virtual, mapped * - * mips1 physical memory is limited to 512Mbytes, which is - * doubly mapped in kseg0 (cached) and kseg1 (uncached.) * Caching of mapped addresses is controlled by bits in the TLB entry. */ @@ -343,29 +337,6 @@ #define MIPS_SR_INT_IE 0x00010001 /* XXX */ #endif -/* - * These definitions are for MIPS32 processors. - */ -#define MIPS32_SR_RP 0x08000000 /* reduced power mode */ -#define MIPS32_SR_FR 0x04000000 /* 64-bit capable fpu */ -#define MIPS32_SR_RE 0x02000000 /* reverse user endian */ -#define MIPS32_SR_MX 0x01000000 /* MIPS64 */ -#define MIPS32_SR_PX 0x00800000 /* MIPS64 */ -#define MIPS32_SR_BEV 0x00400000 /* Use boot exception vector */ -#define MIPS32_SR_TS 0x00200000 /* TLB multiple match */ -#define MIPS32_SR_SOFT_RESET 0x00100000 /* soft reset occurred */ -#define MIPS32_SR_NMI 0x00080000 /* NMI occurred */ -#define MIPS32_SR_INT_MASK 0x0000ff00 -#define MIPS32_SR_KX 0x00000080 /* MIPS64 */ -#define MIPS32_SR_SX 0x00000040 /* MIPS64 */ -#define MIPS32_SR_UX 0x00000020 /* MIPS64 */ -#define MIPS32_SR_KSU_MASK 0x00000018 /* privilege mode */ -#define MIPS32_SR_KSU_USER 0x00000010 -#define MIPS32_SR_KSU_SUPER 0x00000008 -#define MIPS32_SR_KSU_KERNEL 0x00000000 -#define MIPS32_SR_ERL 0x00000004 /* error level */ -#define MIPS32_SR_EXL 0x00000002 /* exception level */ - #define MIPS_SR_SOFT_RESET MIPS3_SR_SR #define MIPS_SR_DIAG_CH MIPS3_SR_DIAG_CH #define MIPS_SR_DIAG_CE MIPS3_SR_DIAG_CE From 2f78c3e5a085d8c11b9267d45da96fecdfa04557 Mon Sep 17 00:00:00 2001 From: Neel Natu Date: Fri, 17 Sep 2010 02:20:12 +0000 Subject: [PATCH 0833/1624] Get rid of the unnecessary redirection of 'is_cacheable_mem()' to 'is_physical_memory()' through a macro. Implement 'is_cacheable_mem()' directly instead. --- sys/mips/include/md_var.h | 4 +--- sys/mips/mips/machdep.c | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/sys/mips/include/md_var.h b/sys/mips/include/md_var.h index ba3da96a958..fee2e44b31e 100644 --- a/sys/mips/include/md_var.h +++ b/sys/mips/include/md_var.h @@ -52,11 +52,9 @@ void cpu_swapin(struct proc *); uintptr_t MipsEmulateBranch(struct trapframe *, uintptr_t, int, uintptr_t); void MipsSwitchFPState(struct thread *, struct trapframe *); u_long kvtop(void *addr); -int is_physical_memory(vm_offset_t addr); +int is_cacheable_mem(vm_offset_t addr); void mips_generic_reset(void); -#define is_cacheable_mem(pa) is_physical_memory((pa)) - #define MIPS_DEBUG 0 #if MIPS_DEBUG diff --git a/sys/mips/mips/machdep.c b/sys/mips/mips/machdep.c index 120fde7a792..435b9b4d67a 100644 --- a/sys/mips/mips/machdep.c +++ b/sys/mips/mips/machdep.c @@ -497,7 +497,7 @@ cpu_idle_wakeup(int cpu) } int -is_physical_memory(vm_offset_t addr) +is_cacheable_mem(vm_offset_t addr) { int i; From 9500655e5a363267bc2642b276f263966e2f253c Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Fri, 17 Sep 2010 04:48:50 +0000 Subject: [PATCH 0834/1624] Add one-shot mode support to attimer (i8254) event timer. Unluckily, using one-shot mode is impossible, when same hardware used for time counting. Introduce new tunable hint.attimer.0.timecounter, setting which to 0 disables i8254 time counter and allows one-shot mode. Note, that on some systems there may be no other reliable enough time counters, so this tunable should be used with understanding. --- sys/x86/isa/clock.c | 115 +++++++++++++++++++++++++++----------------- 1 file changed, 71 insertions(+), 44 deletions(-) diff --git a/sys/x86/isa/clock.c b/sys/x86/isa/clock.c index 2c0e7888b5d..4fb41d8deb7 100644 --- a/sys/x86/isa/clock.c +++ b/sys/x86/isa/clock.c @@ -95,7 +95,7 @@ int clkintr_pending; u_int i8254_freq = TIMER_FREQ; TUNABLE_INT("hw.i8254.freq", &i8254_freq); int i8254_max_count; -static int i8254_real_max_count; +static int i8254_timecounter = 1; struct mtx clock_lock; static struct intsrc *i8254_intsrc; @@ -116,7 +116,11 @@ struct attimer_softc { void *intr_handler; struct timecounter tc; struct eventtimer et; - uint32_t intr_period; + int mode; +#define MODE_STOP 0 +#define MODE_PERIODIC 1 +#define MODE_ONESHOT 2 + uint32_t period; }; static struct attimer_softc *attimer_sc = NULL; @@ -129,14 +133,14 @@ static struct attimer_softc *attimer_sc = NULL; static u_char timer2_state; static unsigned i8254_get_timecount(struct timecounter *tc); -static void set_i8254_freq(u_int freq, uint32_t intr_period); +static void set_i8254_freq(int mode, uint32_t period); static int clkintr(void *arg) { struct attimer_softc *sc = (struct attimer_softc *)arg; - if (sc->intr_period != 0) { + if (i8254_timecounter && sc->period != 0) { mtx_lock_spin(&clock_lock); if (i8254_ticked) i8254_ticked = 0; @@ -148,7 +152,7 @@ clkintr(void *arg) mtx_unlock_spin(&clock_lock); } - if (sc && sc->et.et_active) + if (sc && sc->et.et_active && sc->mode != MODE_STOP) sc->et.et_event_cb(&sc->et, sc->et.et_arg); #ifdef DEV_MCA @@ -361,27 +365,37 @@ DELAY(int n) } static void -set_i8254_freq(u_int freq, uint32_t intr_period) +set_i8254_freq(int mode, uint32_t period) { - int new_i8254_real_max_count; + int val; mtx_lock_spin(&clock_lock); - i8254_freq = freq; - if (intr_period == 0) - new_i8254_real_max_count = 0x10000; - else { - new_i8254_real_max_count = - min(((uint64_t)i8254_freq * intr_period) >> 32, 0x10000); - } - if (new_i8254_real_max_count != i8254_real_max_count) { - i8254_real_max_count = new_i8254_real_max_count; - if (i8254_real_max_count == 0x10000) - i8254_max_count = 0xffff; - else - i8254_max_count = i8254_real_max_count; + if (period == 0) + val = 0x10000; + else + val = min(((uint64_t)i8254_freq * period) >> 32, 0x10000); + if (val == 0x10000) + i8254_max_count = 0xffff; + else + i8254_max_count = val; + if (mode == MODE_STOP && i8254_timecounter) + mode = MODE_PERIODIC; + switch (mode) { + case MODE_STOP: + outb(TIMER_MODE, TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT); + outb(TIMER_CNTR0, 0xff); + outb(TIMER_CNTR0, 0xff); + break; + case MODE_PERIODIC: outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT); - outb(TIMER_CNTR0, i8254_real_max_count & 0xff); - outb(TIMER_CNTR0, i8254_real_max_count >> 8); + outb(TIMER_CNTR0, val & 0xff); + outb(TIMER_CNTR0, val >> 8); + break; + case MODE_ONESHOT: + outb(TIMER_MODE, TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT); + outb(TIMER_CNTR0, val & 0xff); + outb(TIMER_CNTR0, val >> 8); + break; } mtx_unlock_spin(&clock_lock); } @@ -390,11 +404,10 @@ static void i8254_restore(void) { - mtx_lock_spin(&clock_lock); - outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT); - outb(TIMER_CNTR0, i8254_real_max_count & 0xff); - outb(TIMER_CNTR0, i8254_real_max_count >> 8); - mtx_unlock_spin(&clock_lock); + if (attimer_sc) + set_i8254_freq(attimer_sc->mode, attimer_sc->period); + else + set_i8254_freq(0, 0); } #ifndef __amd64__ @@ -428,7 +441,7 @@ i8254_init(void) if (pc98_machine_type & M_8M) i8254_freq = 1996800L; /* 1.9968 MHz */ #endif - set_i8254_freq(i8254_freq, 0); + set_i8254_freq(0, 0); } void @@ -459,11 +472,12 @@ sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS) freq = i8254_freq; error = sysctl_handle_int(oidp, &freq, 0, req); if (error == 0 && req->newptr != NULL) { + i8254_freq = freq; if (attimer_sc) { - set_i8254_freq(freq, attimer_sc->intr_period); + set_i8254_freq(attimer_sc->mode, attimer_sc->period); attimer_sc->tc.tc_frequency = freq; } else { - set_i8254_freq(freq, 0); + set_i8254_freq(0, 0); } } return (error); @@ -481,7 +495,7 @@ i8254_get_timecount(struct timecounter *tc) uint16_t count; u_int high, low; - if (sc->intr_period == 0) + if (sc->period == 0) return (i8254_max_count - getit()); #ifdef __amd64__ @@ -517,13 +531,19 @@ attimer_start(struct eventtimer *et, { device_t dev = (device_t)et->et_priv; struct attimer_softc *sc = device_get_softc(dev); - - sc->intr_period = period->frac >> 32; - set_i8254_freq(i8254_freq, sc->intr_period); + + if (period != NULL) { + sc->mode = MODE_PERIODIC; + sc->period = period->frac >> 32; + } else { + sc->mode = MODE_ONESHOT; + sc->period = first->frac >> 32; + } if (!sc->intr_en) { i8254_intsrc->is_pic->pic_enable_source(i8254_intsrc); sc->intr_en = 1; } + set_i8254_freq(sc->mode, sc->period); return (0); } @@ -533,8 +553,9 @@ attimer_stop(struct eventtimer *et) device_t dev = (device_t)et->et_priv; struct attimer_softc *sc = device_get_softc(dev); - sc->intr_period = 0; - set_i8254_freq(i8254_freq, sc->intr_period); + sc->mode = MODE_STOP; + sc->period = 0; + set_i8254_freq(sc->mode, sc->period); return (0); } @@ -630,14 +651,18 @@ attimer_attach(device_t dev) i8254_intsrc = intr_lookup_source(0); if (i8254_intsrc != NULL) i8254_pending = i8254_intsrc->is_pic->pic_source_pending; - set_i8254_freq(i8254_freq, 0); - sc->tc.tc_get_timecount = i8254_get_timecount; - sc->tc.tc_counter_mask = 0xffff; - sc->tc.tc_frequency = i8254_freq; - sc->tc.tc_name = "i8254"; - sc->tc.tc_quality = 0; - sc->tc.tc_priv = dev; - tc_init(&sc->tc); + resource_int_value(device_get_name(dev), device_get_unit(dev), + "timecounter", &i8254_timecounter); + set_i8254_freq(0, 0); + if (i8254_timecounter) { + sc->tc.tc_get_timecount = i8254_get_timecount; + sc->tc.tc_counter_mask = 0xffff; + sc->tc.tc_frequency = i8254_freq; + sc->tc.tc_name = "i8254"; + sc->tc.tc_quality = 0; + sc->tc.tc_priv = dev; + tc_init(&sc->tc); + } if (resource_int_value(device_get_name(dev), device_get_unit(dev), "clock", &i) != 0 || i != 0) { sc->intr_rid = 0; @@ -663,6 +688,8 @@ attimer_attach(device_t dev) i8254_intsrc->is_pic->pic_enable_intr(i8254_intsrc); sc->et.et_name = "i8254"; sc->et.et_flags = ET_FLAGS_PERIODIC; + if (!i8254_timecounter) + sc->et.et_flags |= ET_FLAGS_ONESHOT; sc->et.et_quality = 100; sc->et.et_frequency = i8254_freq; sc->et.et_min_period.sec = 0; From 74f3a46a7d5f6829610436de74471217d1e4e24b Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Fri, 17 Sep 2010 04:55:01 +0000 Subject: [PATCH 0835/1624] Add attimer(4) manual page. --- share/man/man4/Makefile | 4 +++ share/man/man4/attimer.4 | 69 ++++++++++++++++++++++++++++++++++++ share/man/man4/hpet.4 | 1 + share/man/man7/eventtimers.7 | 1 + 4 files changed, 75 insertions(+) create mode 100644 share/man/man4/attimer.4 diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile index 6e3fd709d92..5f25131cf64 100644 --- a/share/man/man4/Makefile +++ b/share/man/man4/Makefile @@ -50,6 +50,7 @@ MAN= aac.4 \ atkbd.4 \ atkbdc.4 \ ${_atp.4} \ + ${attimer.4} \ audit.4 \ auditpipe.4 \ aue.4 \ @@ -547,6 +548,7 @@ MLINKS+=hatm.4 if_hatm.4 MLINKS+=hme.4 if_hme.4 MLINKS+=hpet.4 acpi_hpet.4 MLINKS+=${_hptrr.4} ${_rr232x.4} +MLINKS+=${_attimer.4} ${_i8254.4} MLINKS+=idt.4 if_idt.4 MLINKS+=igb.4 if_igb.4 MLINKS+=ip.4 rawip.4 @@ -643,6 +645,7 @@ _acpi_sony.4= acpi_sony.4 _acpi_toshiba.4=acpi_toshiba.4 _acpi_wmi.4= acpi_wmi.4 _aesni.4= aesni.4 +_attimer.4= attimer.4 _aibs.4= aibs.4 _amdsbwd.4= amdsbwd.4 _amdsmb.4= amdsmb.4 @@ -655,6 +658,7 @@ _dpms.4= dpms.4 _hptiop.4= hptiop.4 _hptmv.4= hptmv.4 _hptrr.4= hptrr.4 +_i8254.4= i8254.4 _ichwd.4= ichwd.4 _if_ndis.4= if_ndis.4 _if_nfe.4= if_nfe.4 diff --git a/share/man/man4/attimer.4 b/share/man/man4/attimer.4 new file mode 100644 index 00000000000..c5ca05bf0bc --- /dev/null +++ b/share/man/man4/attimer.4 @@ -0,0 +1,69 @@ +.\" Copyright (c) 2010 Alexander Motin +.\" 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. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. +.\" +.\" $FreeBSD$ +.\" +.Dd September 14, 2010 +.Dt attimer 4 +.Os +.Sh NAME +.Nm attimer +.Nd i8254 Programmable Interval Timer (AT Timer) driver +.Sh SYNOPSIS +This driver is a mandatory part of x86 kernels. +.Pp +The following tunables are settable from the +.Xr loader 8 : +.Bl -ohang +.It Va hint.attimer. Ns Ar X Ns Va .clock +controls event timers functionality support. Setting to 0, disables it. +Default value is 1. +.It Va hint.attimer. Ns Ar X Ns Va .timecounter +controls time counter functionality support. Setting to 0, disables it. +Default value is 1. +.El +.Sh DESCRIPTION +This driver uses i8254 Programmable Interval Timer (AT Timer) hardware +to supply kernel with one time counter and one event timer, and generate +sound tones for system speaker. +This hardware includes three channels. +Each channel includes 16bit counter, counting down with known, +platform-dependent frequency. +Counters can operate in several different modes, including periodic and +one-shot. +Output of each channel has platform-defined wiring: one channel is wired +to the interrupt controller and may be used as event timer, one channel is +wired to speaker and used to generate sound tones, and one timer is reserved +for platform purposes. +.Pp +Driver uses single hardware channel to provide both time counter and event +timer functionality. +To make it possible, respective counter must be running in periodic more. +As result, one-shot event timer mode supported only when time counter +functionality is disabled. +.Pp +Event timer provided by the driver is irrelevant to CPU power states. +.Sh SEE ALSO +.Xr hpet 4 , +.Xr eventtimers 7 diff --git a/share/man/man4/hpet.4 b/share/man/man4/hpet.4 index 3a71e71aaa8..f6d324e230e 100644 --- a/share/man/man4/hpet.4 +++ b/share/man/man4/hpet.4 @@ -94,6 +94,7 @@ group is bound to specific CPU core. This is possible only when each of these comparators has own unsharable IRQ. .Sh SEE ALSO .Xr acpi 4 , +.Xr attimer 4 , .Xr eventtimers 7 .Sh HISTORY The diff --git a/share/man/man7/eventtimers.7 b/share/man/man7/eventtimers.7 index 8fb69122bc0..102ce4590eb 100644 --- a/share/man/man7/eventtimers.7 +++ b/share/man/man7/eventtimers.7 @@ -128,4 +128,5 @@ and runs in periodic mode, this option has no effect - all interrupts are always generating. .El .Sh SEE ALSO +.Xr attimer 4 , .Xr hpet 4 From 7c1353491f668d6d0167ddcd0c6cb084756fa811 Mon Sep 17 00:00:00 2001 From: Andriy Gapon Date: Fri, 17 Sep 2010 07:14:07 +0000 Subject: [PATCH 0836/1624] zfs arc_reclaim_needed: more reasonable threshold for available pages vm_paging_target() is not a trigger of any kind for pageademon, but rather a "soft" target for it when it's already triggered. Thus, trying to keep 2048 pages above that level at the expense of ARC was simply driving ARC size into the ground even with normal memory loads. Instead, use a threshold at which a pagedaemon scan is triggered, so that ARC reclaiming helps with pagedaemon's task, but the latter still recycles active and inactive pages. PR: kern/146410, kern/138790 MFC after: 3 weeks --- sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c index 32c079a9be5..d2309b27c7a 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c @@ -2161,10 +2161,10 @@ arc_reclaim_needed(void) return (0); /* - * If pages are needed or we're within 2048 pages - * of needing to page need to reclaim + * Cooperate with pagedaemon when it's time for it to scan + * and reclaim some pages. */ - if (vm_pages_needed || (vm_paging_target() > -2048)) + if (vm_paging_need()) return (1); #if 0 From 44532bc5cd08f71e1fe42720454e2580fc508c66 Mon Sep 17 00:00:00 2001 From: Andriy Gapon Date: Fri, 17 Sep 2010 07:17:38 +0000 Subject: [PATCH 0837/1624] zfs arc_reclaim_needed: remove redundant checks for arc_c_max and arc_c_max Those checks are not present in upstream code and they are enforced in actual calculations of delta by which ARC size can be grown or should be reduced. MFC after: 3 weeks --- sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c index d2309b27c7a..ce07a5c525c 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c @@ -2155,10 +2155,6 @@ arc_reclaim_needed(void) #ifdef _KERNEL if (needfree) return (1); - if (arc_size > arc_c_max) - return (1); - if (arc_size <= arc_c_min) - return (0); /* * Cooperate with pagedaemon when it's time for it to scan From 921d3fd122d4f7eaefbe17ac2c7f033808b3a3cb Mon Sep 17 00:00:00 2001 From: Andriy Gapon Date: Fri, 17 Sep 2010 07:20:20 +0000 Subject: [PATCH 0838/1624] zfs+sendfile: advance uio_offset upon reading as well Picked from analogous code in tmpfs. MFC after: 1 week --- sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c index 18ff03bb21c..383832661f1 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c @@ -523,8 +523,10 @@ again: if (error == 0) vm_page_set_valid(m, off, bytes); vm_page_wakeup(m); - if (error == 0) + if (error == 0) { uio->uio_resid -= bytes; + uio->uio_offset += bytes; + } } else { dirbytes += bytes; } From 9d5eb9aa5ddf47c87f0a63fcca449c964c4ca966 Mon Sep 17 00:00:00 2001 From: Andriy Gapon Date: Fri, 17 Sep 2010 07:34:50 +0000 Subject: [PATCH 0839/1624] zfs arc_reclaim_needed: fix typo in mismerge in r212780 PR: kern/146410, kern/138790 MFC after: 3 weeks X-MFC with: r212780 --- sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c index ce07a5c525c..f34a48ef169 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c @@ -2160,7 +2160,7 @@ arc_reclaim_needed(void) * Cooperate with pagedaemon when it's time for it to scan * and reclaim some pages. */ - if (vm_paging_need()) + if (vm_paging_needed()) return (1); #if 0 From 0b750af1b1b1330e6d5159a0c54267b2f4b1adb5 Mon Sep 17 00:00:00 2001 From: Andriy Gapon Date: Fri, 17 Sep 2010 07:36:32 +0000 Subject: [PATCH 0840/1624] amd64: reduce VM_KMEM_SIZE_SCALE to 1 allowing kernel to use more memory KVA space is abundant on amd64, so there is no reason to limit kernel map size to a fraction of available physical memory. In fact, it could be larger than physical memory. This should help with memory auto-tuning for ZFS and shouldn't affect other workloads. This should reduce number of circumstances for "kmem_map too small" panics, but probably won't eliminate them entirely due to potential kmem fragmentation. In fact, you might want/need to limit maximum ARC size after this commit if you need to resrve more memory for applications. This change was discussed on arch@ and nobody said "don't do it". MFC after: 6 weeks --- sys/amd64/include/vmparam.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/amd64/include/vmparam.h b/sys/amd64/include/vmparam.h index f86b184d7b6..dd0c0c9b555 100644 --- a/sys/amd64/include/vmparam.h +++ b/sys/amd64/include/vmparam.h @@ -205,7 +205,7 @@ * is the total KVA space allocated for kmem_map. */ #ifndef VM_KMEM_SIZE_SCALE -#define VM_KMEM_SIZE_SCALE (3) +#define VM_KMEM_SIZE_SCALE (1) #endif /* From 890ef4f4fe4a93a23d7b49d23abcd70a153acdbb Mon Sep 17 00:00:00 2001 From: John Hay Date: Fri, 17 Sep 2010 07:40:02 +0000 Subject: [PATCH 0841/1624] Chase the ports list to make snapshots work again with NOPORTS set. --- release/Makefile.inc.docports | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/release/Makefile.inc.docports b/release/Makefile.inc.docports index 610fae3622c..f4b238a07c1 100644 --- a/release/Makefile.inc.docports +++ b/release/Makefile.inc.docports @@ -26,9 +26,12 @@ MINIMALDOCPORTS= \ MINIMALDOCPORTS+= \ ports/archivers/unzip \ ports/converters/libiconv \ + ports/devel/autoconf267 \ + ports/devel/autoconf-wrapper \ ports/devel/gettext \ ports/devel/gmake \ - ports/devel/libtool15 \ + ports/devel/libtool22 \ + ports/devel/m4 \ ports/devel/pkg-config \ ports/graphics/gd \ ports/graphics/jbigkit \ @@ -37,6 +40,7 @@ MINIMALDOCPORTS+= \ ports/graphics/png \ ports/graphics/scr2png \ ports/graphics/tiff \ + ports/misc/help2man \ ports/print/freetype2 \ ports/print/ghostscript8 \ ports/print/ghostscript8-nox11 \ From 479c85c65b3d50d4260fecf166a802813adc968d Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Fri, 17 Sep 2010 07:44:01 +0000 Subject: [PATCH 0842/1624] Fix typo ${attimer.4} -> ${_attimer.4}. --- share/man/man4/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile index 5f25131cf64..3bb4e90cf23 100644 --- a/share/man/man4/Makefile +++ b/share/man/man4/Makefile @@ -50,7 +50,7 @@ MAN= aac.4 \ atkbd.4 \ atkbdc.4 \ ${_atp.4} \ - ${attimer.4} \ + ${_attimer.4} \ audit.4 \ auditpipe.4 \ aue.4 \ From c45456fb44c60cc99f80a77d53bacdc9a894e22a Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Fri, 17 Sep 2010 08:44:54 +0000 Subject: [PATCH 0843/1624] Add atrtc(4) manual page. --- share/man/man4/Makefile | 2 ++ share/man/man4/atrtc.4 | 56 ++++++++++++++++++++++++++++++++++++ share/man/man4/attimer.4 | 1 + share/man/man4/hpet.4 | 1 + share/man/man7/eventtimers.7 | 1 + 5 files changed, 61 insertions(+) create mode 100644 share/man/man4/atrtc.4 diff --git a/share/man/man4/Makefile b/share/man/man4/Makefile index 3bb4e90cf23..0310f0d9458 100644 --- a/share/man/man4/Makefile +++ b/share/man/man4/Makefile @@ -50,6 +50,7 @@ MAN= aac.4 \ atkbd.4 \ atkbdc.4 \ ${_atp.4} \ + ${_atrtc.4} \ ${_attimer.4} \ audit.4 \ auditpipe.4 \ @@ -645,6 +646,7 @@ _acpi_sony.4= acpi_sony.4 _acpi_toshiba.4=acpi_toshiba.4 _acpi_wmi.4= acpi_wmi.4 _aesni.4= aesni.4 +_atrtc.4= atrtc.4 _attimer.4= attimer.4 _aibs.4= aibs.4 _amdsbwd.4= amdsbwd.4 diff --git a/share/man/man4/atrtc.4 b/share/man/man4/atrtc.4 new file mode 100644 index 00000000000..35e770dd221 --- /dev/null +++ b/share/man/man4/atrtc.4 @@ -0,0 +1,56 @@ +.\" Copyright (c) 2010 Alexander Motin +.\" 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. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. +.\" +.\" $FreeBSD$ +.\" +.Dd September 17, 2010 +.Dt atrtc 4 +.Os +.Sh NAME +.Nm atrtc +.Nd AT Real-Time Clock (RTC) driver +.Sh SYNOPSIS +This driver is a mandatory part of i386/amd64 kernels. +.Pp +The following tunable is settable from the +.Xr loader 8 : +.Bl -ohang +.It Va hint.atrtc. Ns Ar X Ns Va .clock +controls event timers functionality support. Setting to 0, disables it. +Default value is 1. +.El +.Sh DESCRIPTION +This driver uses RTC hardware to supply kernel with time-of-day clock +with 1 second resolution and one event timer. +This hardware uses base frequency of 32768Hz for advancing time-of-day clock +and generating periodic interrupts. +Interrupts could be generated with fixed number of frequencies, from 2Hz to +8192Hz, obtained by dividing base frequency by one of supported power-of-2 +divisors. +.Pp +Event timer provided by the driver is irrelevant to CPU power states. +.Sh SEE ALSO +.Xr attimer 4 , +.Xr hpet 4 , +.Xr eventtimers 7 diff --git a/share/man/man4/attimer.4 b/share/man/man4/attimer.4 index c5ca05bf0bc..b149a085e32 100644 --- a/share/man/man4/attimer.4 +++ b/share/man/man4/attimer.4 @@ -65,5 +65,6 @@ functionality is disabled. .Pp Event timer provided by the driver is irrelevant to CPU power states. .Sh SEE ALSO +.Xr atrtc 4 , .Xr hpet 4 , .Xr eventtimers 7 diff --git a/share/man/man4/hpet.4 b/share/man/man4/hpet.4 index f6d324e230e..f787895cc5d 100644 --- a/share/man/man4/hpet.4 +++ b/share/man/man4/hpet.4 @@ -94,6 +94,7 @@ group is bound to specific CPU core. This is possible only when each of these comparators has own unsharable IRQ. .Sh SEE ALSO .Xr acpi 4 , +.Xr atrtc 4 , .Xr attimer 4 , .Xr eventtimers 7 .Sh HISTORY diff --git a/share/man/man7/eventtimers.7 b/share/man/man7/eventtimers.7 index 102ce4590eb..6c9552aed2f 100644 --- a/share/man/man7/eventtimers.7 +++ b/share/man/man7/eventtimers.7 @@ -129,4 +129,5 @@ always generating. .El .Sh SEE ALSO .Xr attimer 4 , +.Xr atrtc 4 , .Xr hpet 4 From 59b3a4ebb59dad37f3c09d7a86345ed1c778f977 Mon Sep 17 00:00:00 2001 From: "David E. O'Brien" Date: Fri, 17 Sep 2010 09:14:40 +0000 Subject: [PATCH 0844/1624] Correct some non-code typos. --- sys/ufs/ffs/ffs_vfsops.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/sys/ufs/ffs/ffs_vfsops.c b/sys/ufs/ffs/ffs_vfsops.c index ccf346debd2..0a9b6395905 100644 --- a/sys/ufs/ffs/ffs_vfsops.c +++ b/sys/ufs/ffs/ffs_vfsops.c @@ -318,7 +318,7 @@ ffs_mount(struct mount *mp) fs->fs_fsmnt); if (fs->fs_flags & FS_SUJ) printf( -"WARNING: Forced mount will invalidated journal contents\n"); +"WARNING: Forced mount will invalidate journal contents\n"); return (EPERM); } } @@ -362,7 +362,7 @@ ffs_mount(struct mount *mp) * Soft updates is incompatible with "async", * so if we are doing softupdates stop the user * from setting the async flag in an update. - * Softdep_mount() clears it in an initial mount + * Softdep_mount() clears it in an initial mount * or ro->rw remount. */ if (mp->mnt_flag & MNT_SOFTDEP) { @@ -387,7 +387,7 @@ ffs_mount(struct mount *mp) mp->mnt_flag |= MNT_NFS4ACLS; MNT_IUNLOCK(mp); } - + /* * If this is a snapshot request, take the snapshot. */ @@ -720,8 +720,7 @@ ffs_mountfs(devvp, mp, td) if (ronly || (mp->mnt_flag & MNT_FORCE) || ((fs->fs_flags & (FS_SUJ | FS_NEEDSFSCK)) == 0 && (fs->fs_flags & FS_DOSOFTDEP))) { - printf( -"WARNING: %s was not properly dismounted\n", + printf("WARNING: %s was not properly dismounted\n", fs->fs_fsmnt); } else { printf( @@ -729,7 +728,7 @@ ffs_mountfs(devvp, mp, td) fs->fs_fsmnt); if (fs->fs_flags & FS_SUJ) printf( -"WARNING: Forced mount will invalidated journal contents\n"); +"WARNING: Forced mount will invalidate journal contents\n"); error = EPERM; goto out; } @@ -840,7 +839,7 @@ ffs_mountfs(devvp, mp, td) mp->mnt_stat.f_fsid.val[0] = fs->fs_id[0]; mp->mnt_stat.f_fsid.val[1] = fs->fs_id[1]; nmp = NULL; - if (fs->fs_id[0] == 0 || fs->fs_id[1] == 0 || + if (fs->fs_id[0] == 0 || fs->fs_id[1] == 0 || (nmp = vfs_getvfs(&mp->mnt_stat.f_fsid))) { if (nmp) vfs_rel(nmp); @@ -873,8 +872,7 @@ ffs_mountfs(devvp, mp, td) MNT_IUNLOCK(mp); #else - printf( -"WARNING: %s: ACLs flag on fs but no ACLs support\n", + printf("WARNING: %s: ACLs flag on fs but no ACLs support\n", mp->mnt_stat.f_mntonname); #endif } @@ -1682,7 +1680,7 @@ ffs_sbupdate(mp, waitfor, suspended) int i, size, error, allerror = 0; if (fs->fs_ronly == 1 && - (mp->um_mountp->mnt_flag & (MNT_RDONLY | MNT_UPDATE)) != + (mp->um_mountp->mnt_flag & (MNT_RDONLY | MNT_UPDATE)) != (MNT_RDONLY | MNT_UPDATE)) panic("ffs_sbupdate: write read-only filesystem"); /* @@ -1836,7 +1834,7 @@ ffs_backgroundwritedone(struct buf *bp) * * Note that we set B_CACHE here, indicating that buffer is * fully valid and thus cacheable. This is true even of NFS - * now so we set it generally. This could be set either here + * now so we set it generally. This could be set either here * or in biodone() since the I/O is synchronous. We put it * here. */ @@ -1885,7 +1883,7 @@ ffs_bufwrite(struct buf *bp) * This optimization eats a lot of memory. If we have a page * or buffer shortfall we can't do it. */ - if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) && + if (dobkgrdwrite && (bp->b_xflags & BX_BKGRDWRITE) && (bp->b_flags & B_ASYNC) && !vm_page_count_severe() && !buf_dirty_count_severe()) { @@ -1927,7 +1925,7 @@ ffs_bufwrite(struct buf *bp) bundirty(bp); #else bundirty(bp); -#endif +#endif /* * Initiate write on the copy, release the original to From aa997bb9473a6e3d131da09a20c3ea405a346bbf Mon Sep 17 00:00:00 2001 From: Andriy Gapon Date: Fri, 17 Sep 2010 09:50:36 +0000 Subject: [PATCH 0845/1624] nextboot: warn about limitations of /boot/nextboot.conf on ZFS MFC after: 1 week --- sbin/reboot/nextboot.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sbin/reboot/nextboot.sh b/sbin/reboot/nextboot.sh index 56e53f60a1a..bb90c63d13c 100644 --- a/sbin/reboot/nextboot.sh +++ b/sbin/reboot/nextboot.sh @@ -50,6 +50,14 @@ if [ ${force} = "NO" -a ! -d /boot/${kernel} ]; then exit 1 fi +df -Tn "/boot/" 2>/dev/null | while read _fs _type _other ; do + [ "zfs" = "${_type}" ] || continue + cat 1>&2 <<-EOF + WARNING: loader(8) has only R/O support for ZFS + nextboot.conf will NOT be reset in case of kernel boot failure + EOF +done + cat > ${nextboot_file} << EOF nextboot_enable="YES" kernel="${kernel}" From c42040571e1b645e6818f52194a54285c8568c0b Mon Sep 17 00:00:00 2001 From: "Jayachandran C." Date: Fri, 17 Sep 2010 10:28:10 +0000 Subject: [PATCH 0846/1624] Fixes for XLR network accelerator driver (nlge). - Process some tx done messages in the transmit path, to ensure that the XLR NA tx done FIFO does not overflow. - Add a message ring handler API to process atmost a given number of messages from a specified bucket mask. This will be used to process the tx done messages - Add a callout to restart transmit in the case transmit gets blocked. - Update enable_msgring_int() and disable_msgring_int(), remove unused args and make static. Obtained from: Sriram Gorti (srgorti at netlogicmicro dot com) --- sys/mips/rmi/dev/nlge/if_nlge.c | 101 ++++++++++++++++++++++---------- sys/mips/rmi/dev/nlge/if_nlge.h | 1 + sys/mips/rmi/fmn.c | 54 +++++++++-------- sys/mips/rmi/msgring.h | 7 ++- 4 files changed, 104 insertions(+), 59 deletions(-) diff --git a/sys/mips/rmi/dev/nlge/if_nlge.c b/sys/mips/rmi/dev/nlge/if_nlge.c index 1a217c0445b..46d92868035 100644 --- a/sys/mips/rmi/dev/nlge/if_nlge.c +++ b/sys/mips/rmi/dev/nlge/if_nlge.c @@ -207,6 +207,9 @@ static void release_tx_desc(vm_paddr_t phy_addr); static int send_fmn_msg_tx(struct nlge_softc *, struct msgrng_msg *, uint32_t n_entries); +static void +nl_tx_q_wakeup(void *addr); + //#define DEBUG #ifdef DEBUG static int mac_debug = 1; @@ -424,6 +427,10 @@ nlna_attach(device_t dev) XLR_CACHELINE_SIZE, 0); } + /* Other per NA s/w initialization */ + callout_init(&sc->tx_thr, CALLOUT_MPSAFE); + callout_reset(&sc->tx_thr, hz, nl_tx_q_wakeup, sc); + /* Enable NA interrupts */ nlna_setup_intr(sc); @@ -655,15 +662,23 @@ nlge_msgring_handler(int bucket, int size, int code, int stid, } if (ctrl == CTRL_REG_FREE || ctrl == CTRL_JUMBO_FREE) { - if (is_p2p) { - release_tx_desc(phys_addr); - } else { - m_freem((struct mbuf *)(uintptr_t)phys_addr); - } - ifp = sc->nlge_if; - if (ifp->if_drv_flags & IFF_DRV_OACTIVE){ - ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; + if (!tx_error) { + if (is_p2p) { + release_tx_desc(phys_addr); + } else { + m_freem((struct mbuf *)(uintptr_t)phys_addr); + } + NLGE_LOCK(sc); + if (ifp->if_drv_flags & IFF_DRV_OACTIVE){ + ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; + callout_reset(&na_sc->tx_thr, hz, + nl_tx_q_wakeup, na_sc); + } + NLGE_UNLOCK(sc); + } else { + printf("ERROR: Tx fb error (%d) on port %d\n", tx_error, + port); } atomic_incr_long((tx_error) ? &ifp->if_oerrors: &ifp->if_opackets); } else if (ctrl == CTRL_SNGL || ctrl == CTRL_START) { @@ -687,7 +702,24 @@ nlge_start(struct ifnet *ifp) nlge_start_locked(ifp, sc); //NLGE_UNLOCK(sc); } - + +static void +nl_tx_q_wakeup(void *addr) +{ + struct nlna_softc *na_sc; + struct nlge_softc *sc; + int i; + + na_sc = (struct nlna_softc *) addr; + for (i = 0; i < XLR_MAX_MACS; i++) { + sc = na_sc->child_sc[i]; + if (sc == NULL) + continue; + nlge_start_locked(sc->nlge_if, sc); + } + callout_reset(&na_sc->tx_thr, 5 * hz, nl_tx_q_wakeup, na_sc); +} + static void nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc) { @@ -696,20 +728,30 @@ nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc) struct nlge_tx_desc *tx_desc; uint64_t fr_stid; uint32_t cpu; - uint32_t n_entries; + uint32_t n_entries; uint32_t tid; int ret; - int sent; cpu = xlr_core_id(); tid = xlr_thr_id(); - fr_stid = cpu * 8 + tid + 4; + /* H/w threads [0, 2] --> bucket 6 and [1, 3] --> bucket 7 */ + fr_stid = cpu * 8 + 6 + (tid % 2); if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { return; } do { + /* + * First, remove some freeback messages before transmitting + * any new packets. However, cap the number of messages + * drained to permit this thread to continue with its + * transmission. + * + * Mask for buckets {6, 7} is 0xc0 + */ + xlr_msgring_handler(0xc0, 4); + /* Grab a packet off the queue. */ IF_DEQUEUE(&ifp->if_snd, m); if (m == NULL) { @@ -721,8 +763,8 @@ nlge_start_locked(struct ifnet *ifp, struct nlge_softc *sc) if (ret) { goto fail; } - sent = send_fmn_msg_tx(sc, &msg, n_entries); - if (sent != 0) { + ret = send_fmn_msg_tx(sc, &msg, n_entries); + if (ret != 0) { goto fail; } } while(1); @@ -734,20 +776,10 @@ fail: uma_zfree(nl_tx_desc_zone, tx_desc); } if (m != NULL) { - /* - * TBD: It is observed that only when both of the statements - * below are not enabled, traffic continues till the end. - * Otherwise, the port locks up in the middle and never - * recovers from it. The current theory for this behavior - * is that the queue is full and the upper layer is neither - * able to add to it not invoke nlge_start to drian the - * queue. The driver may have to do something in addition - * to reset'ing the OACTIVE bit when a trasnmit free-back - * is received. - */ - //ifp->if_drv_flags |= IFF_DRV_OACTIVE; - //IF_PREPEND(&ifp->if_snd, m); - m_freem(m); + NLGE_LOCK(sc); + ifp->if_drv_flags |= IFF_DRV_OACTIVE; + NLGE_UNLOCK(sc); + IF_PREPEND(&ifp->if_snd, m); atomic_incr_long(&ifp->if_iqdrops); } return; @@ -1020,7 +1052,7 @@ nlna_submit_rx_free_desc(struct nlna_softc *sc, uint32_t n_desc) msgrng_flags = msgrng_access_enable(); ret = message_send(1, code, stid, &msg); msgrng_restore(msgrng_flags); - KASSERT(n++ < 100000, ("Too many credit fails\n")); + KASSERT(n++ < 100000, ("Too many credit fails in rx path\n")); } while (ret != 0); } } @@ -1942,9 +1974,14 @@ send_fmn_msg_tx(struct nlge_softc *sc, struct msgrng_msg *msg, ret = message_send(n_entries, MSGRNG_CODE_MAC, sc->tx_bucket_id, msg); msgrng_restore(msgrng_flags); - KASSERT(i++ < 100000, ("Too many credit fails\n")); - } while (ret != 0); - return (0); + if (ret == 0) + return (0); + i++; + } while (i < 100000); + + KASSERT(i < 100000, ("Too many credit fails in tx path\n")); + + return (1); } static void diff --git a/sys/mips/rmi/dev/nlge/if_nlge.h b/sys/mips/rmi/dev/nlge/if_nlge.h index 0347071ca4c..39450fb8b20 100644 --- a/sys/mips/rmi/dev/nlge/if_nlge.h +++ b/sys/mips/rmi/dev/nlge/if_nlge.h @@ -1110,6 +1110,7 @@ struct nlna_softc { int mac_type; xlr_reg_t *base; + struct callout tx_thr; struct fr_desc *frin_spill; struct fr_desc *frout_spill; union rx_tx_desc *class_0_spill; diff --git a/sys/mips/rmi/fmn.c b/sys/mips/rmi/fmn.c index f10d3ff6f9d..f55f39f16c8 100644 --- a/sys/mips/rmi/fmn.c +++ b/sys/mips/rmi/fmn.c @@ -60,11 +60,6 @@ __FBSDID("$FreeBSD$"); #include #include -void -disable_msgring_int(void *arg); -void -enable_msgring_int(void *arg); - /* definitions */ struct tx_stn_handler { void (*action) (int, int, int, int, struct msgrng_msg *, void *); @@ -101,14 +96,12 @@ do { \ static struct mtx msgrng_lock; static int msgring_int_enabled; static int msgring_pop_num_buckets; -static uint32_t msgring_pop_bucket_mask; +static uint8_t msgring_pop_bucket_mask; static int msgring_int_type; static int msgring_watermark_count; static uint32_t msgring_thread_mask; uint32_t msgrng_msg_cycles = 0; -void xlr_msgring_handler(struct trapframe *); - void xlr_msgring_cpu_init(void) { @@ -174,28 +167,34 @@ xlr_msgring_config(void) msgring_thread_mask = 0x01; } -void -xlr_msgring_handler(struct trapframe *tf) +/* + * Drain out max_messages for the buckets set in the bucket mask. + * Use max_messages = 0 to drain out all messages. + */ +uint32_t +xlr_msgring_handler(uint8_t bucket_mask, uint32_t max_messages) { - unsigned long mflags; int bucket = 0; int size = 0, code = 0, rx_stid = 0, tx_stid = 0; struct msgrng_msg msg; - unsigned int bucket_empty_bm = 0; + uint8_t bucket_empty_bm = 0; unsigned int status = 0; + unsigned long mflags; + uint32_t n_msgs; + n_msgs = 0; mflags = msgrng_access_enable(); - /* First Drain all the high priority messages */ for (;;) { - bucket_empty_bm = (msgrng_read_status() >> 24) & msgring_pop_bucket_mask; + bucket_empty_bm = (msgrng_read_status() >> 24) & bucket_mask; /* all buckets empty, break */ - if (bucket_empty_bm == msgring_pop_bucket_mask) + if (bucket_empty_bm == bucket_mask) break; for (bucket = 0; bucket < msgring_pop_num_buckets; bucket++) { - if ((bucket_empty_bm & (1 << bucket)) /* empty */ ) + if (!((1 << bucket) & bucket_mask) /* bucket not in mask */ + || (bucket_empty_bm & (1 << bucket))) /* empty */ continue; status = message_receive(bucket, &size, &code, &rx_stid, &msg); @@ -203,6 +202,7 @@ xlr_msgring_handler(struct trapframe *tf) continue; tx_stid = xlr_board_info.msgmap[rx_stid]; + n_msgs++; if (!tx_stn_handlers[tx_stid].action) { printf("[%s]: No Handler for message from stn_id=%d, bucket=%d, " @@ -215,13 +215,19 @@ xlr_msgring_handler(struct trapframe *tf) &msg, tx_stn_handlers[tx_stid].dev_id); mflags = msgrng_access_enable(); } + if (max_messages > 0 && n_msgs >= max_messages) + goto done; } } + +done: msgrng_restore(mflags); + + return (n_msgs); } -void -enable_msgring_int(void *arg) +static void +enable_msgring_int(void) { uint32_t config, mflags; @@ -232,8 +238,8 @@ enable_msgring_int(void *arg) msgrng_restore(mflags); } -void -disable_msgring_int(void *arg) +static void +disable_msgring_int(void) { uint32_t config, mflags; @@ -259,7 +265,7 @@ msgring_process_fast_intr(void *arg) * Interrupt thread will enable the interrupts after processing all * messages */ - disable_msgring_int(NULL); + disable_msgring_int(); atomic_store_rel_int(&it->i_pending, 1); thread_lock(td); if (TD_AWAITING_INTR(td)) { @@ -291,7 +297,7 @@ msgring_process(void *arg) atomic_store_rel_ptr((volatile uintptr_t *)&msgring_ithreads[ithd->i_core], (uintptr_t)arg); - enable_msgring_int(NULL); + enable_msgring_int(); while (1) { while (ithd->i_pending) { @@ -300,9 +306,9 @@ msgring_process(void *arg) * make sure that this write posts before any of the * memory or device accesses in the handlers. */ - xlr_msgring_handler(NULL); + xlr_msgring_handler(msgring_pop_bucket_mask, 0); atomic_store_rel_int(&ithd->i_pending, 0); - enable_msgring_int(NULL); + enable_msgring_int(); } if (!ithd->i_pending) { thread_lock(td); diff --git a/sys/mips/rmi/msgring.h b/sys/mips/rmi/msgring.h index ae3d9d49dce..c55d0deeeb0 100644 --- a/sys/mips/rmi/msgring.h +++ b/sys/mips/rmi/msgring.h @@ -386,10 +386,11 @@ enum { MAX_TX_STNS }; -extern int register_msgring_handler(int major, +int register_msgring_handler(int major, void (*action) (int, int, int, int, struct msgrng_msg *, void *), void *dev_id); -extern void xlr_msgring_cpu_init(void); -extern void xlr_msgring_config(void); +uint32_t xlr_msgring_handler(uint8_t bucket_mask, uint32_t max_messages); +void xlr_msgring_cpu_init(void); +void xlr_msgring_config(void); #endif From 5ab44ccaf20068f07aed14481c74fcc7140f5a57 Mon Sep 17 00:00:00 2001 From: Martin Matuska Date: Fri, 17 Sep 2010 14:15:03 +0000 Subject: [PATCH 0847/1624] Remove duplicate include of Approved by: delphij (mentor) MFC after: 3 days --- cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c | 1 - 1 file changed, 1 deletion(-) diff --git a/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c b/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c index 471efe29d87..913118764ff 100644 --- a/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c +++ b/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c @@ -40,7 +40,6 @@ #include #include #include -#include #include #include "zfs_namecheck.h" From d39c594d39df7f283c2fb8a704a3f31c501180d9 Mon Sep 17 00:00:00 2001 From: Dimitry Andric Date: Fri, 17 Sep 2010 15:48:55 +0000 Subject: [PATCH 0848/1624] Vendor import of llvm r114020 (from the release_28 branch): http://llvm.org/svn/llvm-project/llvm/branches/release_28@114020 Approved by: rpaulo (mentor) --- CMakeLists.txt | 42 +- CREDITS.TXT | 32 +- Makefile | 14 +- Makefile.config.in | 18 +- Makefile.rules | 264 +- README.txt | 3 +- autoconf/configure.ac | 86 +- autoconf/m4/link_options.m4 | 21 + bindings/ada/llvm/llvm.ads | 36 +- bindings/ocaml/llvm/llvm.ml | 12 +- bindings/ocaml/llvm/llvm.mli | 28 +- bindings/ocaml/llvm/llvm_ocaml.c | 30 +- cmake/config-ix.cmake | 10 + cmake/modules/CMakeLists.txt | 12 + cmake/modules/ChooseMSVCCRT.cmake | 106 + cmake/modules/LLVM.cmake | 29 + cmake/modules/LLVMConfig.cmake | 48 +- cmake/modules/LLVMLibDeps.cmake | 33 +- cmake/modules/VersionFromVCS.cmake | 33 + configure | 155 +- docs/AliasAnalysis.html | 10 +- docs/BitCodeFormat.html | 17 +- docs/CMake.html | 45 +- docs/CodeGenerator.html | 6 +- docs/CommandGuide/bugpoint.pod | 4 + docs/CommandGuide/index.html | 5 +- docs/CommandGuide/llvm-diff.pod | 53 + docs/DeveloperPolicy.html | 54 +- docs/GCCFEBuildInstrs.html | 16 +- docs/GetElementPtr.html | 13 +- docs/GoldPlugin.html | 8 +- docs/LangRef.html | 129 +- docs/MakefileGuide.html | 5 +- docs/Passes.html | 49 +- docs/ProgrammersManual.html | 6 +- docs/ReleaseNotes.html | 598 +-- docs/TestingGuide.html | 229 +- docs/WritingAnLLVMBackend.html | 5 +- docs/WritingAnLLVMPass.html | 59 +- docs/tutorial/LangImpl3.html | 10 +- docs/tutorial/LangImpl5.html | 6 +- docs/tutorial/LangImpl6.html | 4 +- docs/tutorial/LangImpl7.html | 6 +- examples/BrainF/BrainF.cpp | 11 +- examples/Fibonacci/fibonacci.cpp | 14 +- examples/Makefile | 9 +- include/llvm-c/Core.h | 20 +- include/llvm-c/EnhancedDisassembly.h | 17 +- include/llvm-c/ExecutionEngine.h | 2 + include/llvm-c/Target.h | 47 +- include/llvm-c/lto.h | 24 +- include/llvm/ADT/APInt.h | 4 +- include/llvm/ADT/DenseMap.h | 3 +- include/llvm/ADT/DenseSet.h | 6 + include/llvm/ADT/DepthFirstIterator.h | 10 + include/llvm/ADT/FoldingSet.h | 177 +- include/llvm/ADT/ImmutableIntervalMap.h | 10 +- include/llvm/ADT/NullablePtr.h | 52 + include/llvm/ADT/STLExtras.h | 4 +- include/llvm/ADT/ScopedHashTable.h | 7 +- include/llvm/ADT/SmallVector.h | 32 +- include/llvm/ADT/StringMap.h | 4 + include/llvm/ADT/StringRef.h | 13 +- include/llvm/ADT/StringSet.h | 7 +- include/llvm/ADT/StringSwitch.h | 20 + include/llvm/ADT/Triple.h | 32 +- include/llvm/ADT/ValueMap.h | 18 +- include/llvm/ADT/ilist.h | 1 - include/llvm/Analysis/AliasAnalysis.h | 109 +- include/llvm/Analysis/AliasSetTracker.h | 10 +- include/llvm/Analysis/DOTGraphTraitsPass.h | 4 +- include/llvm/Analysis/DebugInfo.h | 61 +- include/llvm/Analysis/Dominators.h | 9 +- include/llvm/Analysis/FindUsedTypes.h | 2 +- include/llvm/Analysis/IntervalPartition.h | 2 +- include/llvm/Analysis/LazyValueInfo.h | 12 +- include/llvm/Analysis/LibCallAliasAnalysis.h | 25 +- include/llvm/Analysis/LibCallSemantics.h | 5 +- .../llvm/Analysis/LoopDependenceAnalysis.h | 2 +- include/llvm/Analysis/LoopInfo.h | 26 +- include/llvm/Analysis/LoopPass.h | 12 +- include/llvm/Analysis/Passes.h | 18 +- include/llvm/Analysis/PointerTracking.h | 1 + include/llvm/Analysis/PostDominators.h | 4 +- include/llvm/Analysis/RegionInfo.h | 630 ++++ include/llvm/Analysis/RegionIterator.h | 342 ++ include/llvm/Analysis/RegionPrinter.h | 26 + include/llvm/Analysis/ScalarEvolution.h | 47 +- .../llvm/Analysis/ScalarEvolutionExpander.h | 14 +- .../Analysis/ScalarEvolutionExpressions.h | 48 +- include/llvm/Analysis/ValueTracking.h | 19 - ...ionWriter.h => AssemblyAnnotationWriter.h} | 17 +- include/llvm/AutoUpgrade.h | 5 + include/llvm/Bitcode/Archive.h | 6 +- include/llvm/Bitcode/BitstreamWriter.h | 8 +- include/llvm/Bitcode/LLVMBitCodes.h | 31 +- include/llvm/CallGraphSCCPass.h | 5 +- include/llvm/CodeGen/AsmPrinter.h | 13 +- include/llvm/CodeGen/CalcSpillWeights.h | 29 +- include/llvm/CodeGen/CallingConvLower.h | 6 + include/llvm/CodeGen/FunctionLoweringInfo.h | 10 + include/llvm/CodeGen/ISDOpcodes.h | 9 +- include/llvm/CodeGen/LiveInterval.h | 37 +- include/llvm/CodeGen/LiveIntervalAnalysis.h | 48 +- include/llvm/CodeGen/LiveStackAnalysis.h | 2 +- include/llvm/CodeGen/LiveVariables.h | 2 +- include/llvm/CodeGen/MachineFrameInfo.h | 167 +- include/llvm/CodeGen/MachineFunction.h | 2 +- include/llvm/CodeGen/MachineFunctionPass.h | 3 +- include/llvm/CodeGen/MachineInstr.h | 6 +- include/llvm/CodeGen/MachineLoopInfo.h | 2 +- include/llvm/CodeGen/MachineModuleInfo.h | 2 +- include/llvm/CodeGen/Passes.h | 62 +- include/llvm/CodeGen/ProcessImplicitDefs.h | 2 +- include/llvm/CodeGen/SchedulerRegistry.h | 13 +- include/llvm/CodeGen/SelectionDAG.h | 4 - include/llvm/CodeGen/SlotIndexes.h | 45 +- .../CodeGen/TargetLoweringObjectFileImpl.h | 1 - include/llvm/CodeGen/ValueTypes.h | 112 +- include/llvm/CompilerDriver/Action.h | 14 +- include/llvm/CompilerDriver/AutoGenerated.h | 40 + include/llvm/CompilerDriver/BuiltinOptions.h | 4 + include/llvm/CompilerDriver/Common.td | 43 +- .../llvm/CompilerDriver/CompilationGraph.h | 95 +- include/llvm/CompilerDriver/Error.h | 20 +- include/llvm/CompilerDriver/ForceLinkage.h | 122 - .../llvm/CompilerDriver/ForceLinkageMacros.h | 29 - include/llvm/CompilerDriver/Main.h | 21 + include/llvm/CompilerDriver/Main.inc | 14 +- include/llvm/CompilerDriver/Plugin.h | 81 - include/llvm/CompilerDriver/Tool.h | 38 +- include/llvm/Config/config.h.cmake | 20 +- include/llvm/Config/config.h.in | 17 + include/llvm/Config/llvm-config.h.cmake | 97 + include/llvm/Config/llvm-config.h.in | 97 + include/llvm/Constants.h | 44 - include/llvm/DerivedTypes.h | 66 +- .../llvm/ExecutionEngine/JITMemoryManager.h | 9 +- include/llvm/GlobalValue.h | 46 +- include/llvm/Instruction.h | 12 +- include/llvm/Instructions.h | 96 +- include/llvm/IntrinsicInst.h | 16 +- include/llvm/Intrinsics.td | 69 +- include/llvm/IntrinsicsARM.td | 119 +- include/llvm/IntrinsicsPowerPC.td | 47 +- include/llvm/IntrinsicsX86.td | 482 ++- include/llvm/LLVMContext.h | 5 +- include/llvm/LinkAllPasses.h | 12 +- include/llvm/LinkAllVMCore.h | 1 - include/llvm/Linker.h | 1 - include/llvm/MC/ELFObjectWriter.h | 46 + include/llvm/MC/MCAsmInfo.h | 14 + include/llvm/MC/MCAssembler.h | 23 +- include/llvm/MC/MCContext.h | 60 +- include/llvm/MC/MCDwarf.h | 156 + include/llvm/MC/MCELFSymbolFlags.h | 54 + include/llvm/MC/MCObjectStreamer.h | 11 + include/llvm/MC/MCObjectWriter.h | 2 +- include/llvm/MC/MCParser/AsmParser.h | 152 - include/llvm/MC/MCParser/MCAsmParser.h | 30 +- .../llvm/MC/MCParser/MCAsmParserExtension.h | 18 +- include/llvm/MC/MCParser/MCParsedAsmOperand.h | 8 +- include/llvm/MC/MCSectionELF.h | 10 +- include/llvm/MC/MCStreamer.h | 30 +- include/llvm/Metadata.h | 56 +- include/llvm/Module.h | 29 +- include/llvm/Pass.h | 71 +- include/llvm/PassAnalysisSupport.h | 50 +- include/llvm/PassManager.h | 1 - include/llvm/PassManagers.h | 58 +- include/llvm/PassRegistry.h | 71 + include/llvm/PassSupport.h | 41 +- include/llvm/Support/COFF.h | 87 +- include/llvm/Support/CallSite.h | 63 +- include/llvm/Support/Casting.h | 67 - include/llvm/Support/CommandLine.h | 27 +- include/llvm/Support/Compiler.h | 5 +- include/llvm/Support/ConstantRange.h | 38 +- include/llvm/Support/CrashRecoveryContext.h | 84 + include/llvm/Support/DataFlow.h | 2 +- include/llvm/Support/ELF.h | 83 +- include/llvm/Support/ErrorHandling.h | 12 + include/llvm/Support/GraphWriter.h | 12 +- include/llvm/Support/IRBuilder.h | 20 - include/llvm/Support/IRReader.h | 10 +- include/llvm/Support/MachO.h | 638 ++++ include/llvm/Support/MathExtras.h | 6 +- include/llvm/Support/PassNameParser.h | 24 +- include/llvm/Support/PatternMatch.h | 7 + include/llvm/Support/PrettyStackTrace.h | 14 +- include/llvm/Support/Regex.h | 15 +- include/llvm/Support/Registry.h | 2 + include/llvm/Support/SlowOperationInformer.h | 65 - include/llvm/Support/SourceMgr.h | 4 +- include/llvm/Support/StandardPasses.h | 3 +- include/llvm/Support/SystemUtils.h | 7 +- include/llvm/Support/TypeBuilder.h | 2 +- include/llvm/Support/raw_ostream.h | 125 +- include/llvm/System/Memory.h | 1 - include/llvm/System/Path.h | 5 +- include/llvm/System/Process.h | 2 - include/llvm/System/Program.h | 3 - include/llvm/System/Signals.h | 4 + include/llvm/System/ThreadLocal.h | 13 + include/llvm/Target/Target.td | 7 +- include/llvm/Target/TargetAsmParser.h | 14 +- include/llvm/Target/TargetCallingConv.td | 9 +- include/llvm/Target/TargetData.h | 42 +- include/llvm/Target/TargetInstrDesc.h | 14 +- include/llvm/Target/TargetInstrInfo.h | 53 +- include/llvm/Target/TargetLowering.h | 140 +- include/llvm/Target/TargetMachine.h | 38 +- include/llvm/Target/TargetOpcodes.h | 2 +- include/llvm/Target/TargetOptions.h | 23 +- include/llvm/Target/TargetRegisterInfo.h | 67 +- include/llvm/Target/TargetRegistry.h | 17 +- include/llvm/Target/TargetSelect.h | 25 +- include/llvm/Transforms/IPO.h | 5 +- include/llvm/Transforms/IPO/InlinerPass.h | 4 +- include/llvm/Transforms/Scalar.h | 47 +- include/llvm/Transforms/Utils/Cloning.h | 15 +- include/llvm/Transforms/Utils/Local.h | 2 - include/llvm/Transforms/Utils/SSAUpdater.h | 18 +- include/llvm/Transforms/Utils/SSI.h | 93 - .../Transforms/Utils/UnifyFunctionExitNodes.h | 2 +- .../llvm}/Transforms/Utils/ValueMapper.h | 12 +- include/llvm/Type.h | 18 +- include/llvm/Use.h | 24 - include/llvm/Value.h | 6 +- include/llvm/ValueSymbolTable.h | 88 - lib/Analysis/AliasAnalysis.cpp | 241 +- lib/Analysis/AliasAnalysisCounter.cpp | 20 +- lib/Analysis/AliasAnalysisEvaluator.cpp | 50 +- lib/Analysis/AliasDebugger.cpp | 17 +- lib/Analysis/AliasSetTracker.cpp | 153 +- lib/Analysis/BasicAliasAnalysis.cpp | 586 ++- lib/Analysis/CFGPrinter.cpp | 30 +- lib/Analysis/CMakeLists.txt | 3 + lib/Analysis/CaptureTracking.cpp | 2 +- lib/Analysis/ConstantFolding.cpp | 4 +- lib/Analysis/DbgInfoPrinter.cpp | 6 +- lib/Analysis/DebugInfo.cpp | 192 +- lib/Analysis/DomPrinter.cpp | 65 +- lib/Analysis/IPA/CallGraph.cpp | 15 +- lib/Analysis/IPA/CallGraphSCCPass.cpp | 12 +- lib/Analysis/IPA/FindUsedTypes.cpp | 4 +- lib/Analysis/IPA/GlobalsModRef.cpp | 81 +- lib/Analysis/IVUsers.cpp | 39 +- lib/Analysis/InlineCost.cpp | 8 +- lib/Analysis/InstCount.cpp | 6 +- lib/Analysis/IntervalPartition.cpp | 6 +- lib/Analysis/LazyValueInfo.cpp | 587 ++- lib/Analysis/LibCallAliasAnalysis.cpp | 14 +- lib/Analysis/LibCallSemantics.cpp | 3 +- lib/Analysis/Lint.cpp | 11 +- lib/Analysis/LiveValues.cpp | 6 +- lib/Analysis/LoopDependenceAnalysis.cpp | 4 +- lib/Analysis/LoopInfo.cpp | 45 +- lib/Analysis/LoopPass.cpp | 16 +- lib/Analysis/MemoryDependenceAnalysis.cpp | 44 +- lib/Analysis/ModuleDebugInfoPrinter.cpp | 7 +- lib/Analysis/PointerTracking.cpp | 55 +- lib/Analysis/PostDominators.cpp | 8 +- lib/Analysis/ProfileEstimatorPass.cpp | 14 +- lib/Analysis/ProfileInfo.cpp | 13 +- lib/Analysis/ProfileInfoLoaderPass.cpp | 14 +- lib/Analysis/ProfileVerifierPass.cpp | 8 +- lib/Analysis/RegionInfo.cpp | 749 ++++ lib/Analysis/RegionPrinter.cpp | 186 + lib/Analysis/ScalarEvolution.cpp | 747 ++-- lib/Analysis/ScalarEvolutionAliasAnalysis.cpp | 17 +- lib/Analysis/ScalarEvolutionExpander.cpp | 74 +- lib/Analysis/ScalarEvolutionNormalization.cpp | 114 +- lib/Analysis/TypeBasedAliasAnalysis.cpp | 191 + lib/Analysis/ValueTracking.cpp | 238 +- lib/AsmParser/LLLexer.cpp | 2 +- lib/AsmParser/LLParser.cpp | 161 +- lib/AsmParser/LLParser.h | 14 +- lib/AsmParser/LLToken.h | 4 +- lib/AsmParser/Parser.cpp | 3 +- lib/Bitcode/Reader/BitcodeReader.cpp | 119 +- lib/Bitcode/Reader/BitcodeReader.h | 12 +- lib/Bitcode/Writer/BitcodeWriter.cpp | 138 +- lib/Bitcode/Writer/BitcodeWriterPass.cpp | 2 +- lib/Bitcode/Writer/ValueEnumerator.cpp | 149 +- lib/Bitcode/Writer/ValueEnumerator.h | 9 +- lib/CodeGen/AggressiveAntiDepBreaker.cpp | 32 +- lib/CodeGen/AggressiveAntiDepBreaker.h | 10 +- lib/CodeGen/Analysis.cpp | 4 +- lib/CodeGen/AsmPrinter/AsmPrinter.cpp | 88 +- lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp | 4 +- .../AsmPrinter/AsmPrinterInlineAsm.cpp | 13 +- lib/CodeGen/AsmPrinter/DwarfDebug.cpp | 862 +++-- lib/CodeGen/AsmPrinter/DwarfDebug.h | 28 +- lib/CodeGen/AsmPrinter/DwarfException.cpp | 2 +- lib/CodeGen/BranchFolding.cpp | 2 +- lib/CodeGen/CMakeLists.txt | 6 +- lib/CodeGen/CalcSpillWeights.cpp | 278 +- lib/CodeGen/CodePlacementOpt.cpp | 2 +- lib/CodeGen/CriticalAntiDepBreaker.cpp | 27 +- lib/CodeGen/CriticalAntiDepBreaker.h | 7 +- lib/CodeGen/DeadMachineInstructionElim.cpp | 21 +- lib/CodeGen/DwarfEHPrepare.cpp | 290 +- lib/CodeGen/ELF.h | 120 +- lib/CodeGen/ELFCodeEmitter.cpp | 2 +- lib/CodeGen/ELFWriter.cpp | 30 +- lib/CodeGen/ELFWriter.h | 13 +- lib/CodeGen/GCMetadata.cpp | 12 +- lib/CodeGen/GCStrategy.cpp | 9 +- lib/CodeGen/IfConversion.cpp | 5 +- lib/CodeGen/InlineSpiller.cpp | 118 +- lib/CodeGen/IntrinsicLowering.cpp | 3 +- lib/CodeGen/LLVMTargetMachine.cpp | 81 +- lib/CodeGen/LiveInterval.cpp | 164 +- lib/CodeGen/LiveIntervalAnalysis.cpp | 79 +- lib/CodeGen/LiveStackAnalysis.cpp | 3 +- lib/CodeGen/LiveVariables.cpp | 18 +- lib/CodeGen/LocalStackSlotAllocation.cpp | 354 ++ lib/CodeGen/LowerSubregs.cpp | 22 +- lib/CodeGen/MachineBasicBlock.cpp | 32 +- lib/CodeGen/MachineCSE.cpp | 41 +- lib/CodeGen/MachineDominators.cpp | 8 +- lib/CodeGen/MachineFunction.cpp | 3 +- lib/CodeGen/MachineFunctionAnalysis.cpp | 4 +- lib/CodeGen/MachineFunctionPrinterPass.cpp | 2 +- lib/CodeGen/MachineInstr.cpp | 33 +- lib/CodeGen/MachineLICM.cpp | 21 +- lib/CodeGen/MachineLoopInfo.cpp | 6 +- lib/CodeGen/MachineModuleInfo.cpp | 15 +- lib/CodeGen/MachineSink.cpp | 138 +- lib/CodeGen/MachineVerifier.cpp | 230 +- lib/CodeGen/OptimizeExts.cpp | 220 -- lib/CodeGen/OptimizePHIs.cpp | 20 +- lib/CodeGen/PBQP/HeuristicBase.h | 8 +- lib/CodeGen/PBQP/HeuristicSolver.h | 9 + lib/CodeGen/PBQP/Heuristics/Briggs.h | 8 +- lib/CodeGen/PBQP/Solution.h | 31 + lib/CodeGen/PHIElimination.cpp | 36 +- lib/CodeGen/PHIElimination.h | 10 +- lib/CodeGen/PeepholeOptimizer.cpp | 287 ++ lib/CodeGen/PostRASchedulerList.cpp | 7 +- lib/CodeGen/PreAllocSplitting.cpp | 15 +- lib/CodeGen/ProcessImplicitDefs.cpp | 18 +- lib/CodeGen/PrologEpilogInserter.cpp | 243 +- lib/CodeGen/PrologEpilogInserter.h | 9 +- lib/CodeGen/RegAllocFast.cpp | 136 +- lib/CodeGen/RegAllocLinearScan.cpp | 154 +- lib/CodeGen/RegAllocPBQP.cpp | 47 +- lib/CodeGen/RegisterCoalescer.cpp | 3 +- lib/CodeGen/RegisterScavenging.cpp | 34 +- lib/CodeGen/RenderMachineFunction.cpp | 1014 +++++ lib/CodeGen/RenderMachineFunction.h | 336 ++ lib/CodeGen/ScheduleDAGInstrs.cpp | 9 +- lib/CodeGen/ScheduleDAGInstrs.h | 4 +- lib/CodeGen/SelectionDAG/DAGCombiner.cpp | 15 +- lib/CodeGen/SelectionDAG/FastISel.cpp | 17 +- .../SelectionDAG/FunctionLoweringInfo.cpp | 67 +- lib/CodeGen/SelectionDAG/LegalizeDAG.cpp | 26 +- .../SelectionDAG/LegalizeIntegerTypes.cpp | 20 +- lib/CodeGen/SelectionDAG/LegalizeTypes.h | 24 +- .../SelectionDAG/LegalizeVectorTypes.cpp | 406 +- lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp | 74 +- .../SelectionDAG/ScheduleDAGRRList.cpp | 423 ++- .../SelectionDAG/ScheduleDAGSDNodes.cpp | 5 +- lib/CodeGen/SelectionDAG/SelectionDAG.cpp | 40 +- .../SelectionDAG/SelectionDAGBuilder.cpp | 660 ++-- .../SelectionDAG/SelectionDAGBuilder.h | 37 +- lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp | 44 +- .../SelectionDAG/SelectionDAGPrinter.cpp | 2 +- lib/CodeGen/SelectionDAG/TargetLowering.cpp | 182 +- lib/CodeGen/SimpleRegisterCoalescing.cpp | 161 +- lib/CodeGen/SimpleRegisterCoalescing.h | 3 +- lib/CodeGen/SjLjEHPrepare.cpp | 2 +- lib/CodeGen/SlotIndexes.cpp | 3 +- lib/CodeGen/Spiller.cpp | 98 +- lib/CodeGen/Spiller.h | 19 +- lib/CodeGen/SplitKit.cpp | 1097 ++++++ lib/CodeGen/SplitKit.h | 321 ++ lib/CodeGen/Splitter.cpp | 817 ++++ lib/CodeGen/Splitter.h | 99 + lib/CodeGen/StackProtector.cpp | 8 +- lib/CodeGen/StackSlotColoring.cpp | 9 +- lib/CodeGen/StrongPHIElimination.cpp | 9 +- lib/CodeGen/TailDuplication.cpp | 19 +- lib/CodeGen/TargetInstrInfoImpl.cpp | 13 - lib/CodeGen/TargetLoweringObjectFileImpl.cpp | 6 +- lib/CodeGen/TwoAddressInstructionPass.cpp | 50 +- lib/CodeGen/UnreachableBlockElim.cpp | 15 +- lib/CodeGen/VirtRegMap.cpp | 3 +- lib/CodeGen/VirtRegMap.h | 7 +- lib/CodeGen/VirtRegRewriter.cpp | 101 +- lib/CompilerDriver/Action.cpp | 13 +- lib/CompilerDriver/BuiltinOptions.cpp | 4 +- lib/CompilerDriver/CompilationGraph.cpp | 289 +- lib/CompilerDriver/Main.cpp | 127 +- lib/CompilerDriver/Makefile | 36 +- lib/CompilerDriver/Plugin.cpp | 78 - .../ExecutionEngineBindings.cpp | 4 + lib/ExecutionEngine/JIT/Intercept.cpp | 12 + lib/ExecutionEngine/JIT/JIT.cpp | 10 +- .../JIT/JITDebugRegisterer.cpp | 10 +- lib/ExecutionEngine/JIT/JITDwarfEmitter.cpp | 440 --- lib/ExecutionEngine/JIT/JITDwarfEmitter.h | 16 - lib/ExecutionEngine/JIT/JITEmitter.cpp | 307 +- lib/Linker/LinkModules.cpp | 180 +- lib/MC/CMakeLists.txt | 3 + lib/MC/ELFObjectWriter.cpp | 973 +++++ lib/MC/MCAsmInfo.cpp | 2 + lib/MC/MCAsmInfoDarwin.cpp | 3 + lib/MC/MCAsmStreamer.cpp | 3 +- lib/MC/MCAssembler.cpp | 74 +- lib/MC/MCContext.cpp | 88 +- lib/MC/MCDisassembler/CMakeLists.txt | 7 + .../MC/MCDisassembler}/EDDisassembler.cpp | 41 +- .../MC/MCDisassembler}/EDDisassembler.h | 37 +- lib/MC/MCDisassembler/EDInfo.h | 73 + .../edis => lib/MC/MCDisassembler}/EDInst.cpp | 2 +- .../edis => lib/MC/MCDisassembler}/EDInst.h | 21 +- .../MC/MCDisassembler}/EDOperand.cpp | 8 +- .../MC/MCDisassembler}/EDOperand.h | 19 +- .../MC/MCDisassembler}/EDToken.cpp | 8 +- .../edis => lib/MC/MCDisassembler}/EDToken.h | 12 +- lib/MC/MCDisassembler/Makefile | 14 + lib/MC/MCDwarf.cpp | 21 + lib/MC/MCELFStreamer.cpp | 408 ++ lib/MC/MCMachOStreamer.cpp | 277 +- lib/MC/MCNullStreamer.cpp | 1 + lib/MC/MCObjectStreamer.cpp | 48 + lib/MC/MCParser/AsmLexer.cpp | 28 +- lib/MC/MCParser/AsmParser.cpp | 702 +++- lib/MC/MCParser/DarwinAsmParser.cpp | 237 +- lib/MC/MCParser/ELFAsmParser.cpp | 235 +- lib/MC/MCParser/MCAsmParser.cpp | 15 +- lib/MC/MCParser/TargetAsmParser.cpp | 2 +- lib/MC/MCStreamer.cpp | 3 +- lib/MC/MachObjectWriter.cpp | 2 +- lib/MC/Makefile | 2 +- lib/MC/WinCOFFObjectWriter.cpp | 737 +++- lib/MC/WinCOFFStreamer.cpp | 229 +- lib/Support/APFloat.cpp | 1 + lib/Support/APInt.cpp | 17 +- lib/Support/CMakeLists.txt | 2 +- lib/Support/ConstantRange.cpp | 128 +- lib/Support/CrashRecoveryContext.cpp | 204 + lib/Support/ErrorHandling.cpp | 34 +- lib/Support/FoldingSet.cpp | 89 +- lib/Support/PrettyStackTrace.cpp | 5 +- lib/Support/SlowOperationInformer.cpp | 67 - lib/Support/SmallVector.cpp | 2 +- lib/Support/Statistic.cpp | 14 +- lib/Support/StringRef.cpp | 27 +- lib/Support/SystemUtils.cpp | 10 + lib/Support/Triple.cpp | 243 +- lib/Support/raw_ostream.cpp | 97 +- lib/System/DynamicLibrary.cpp | 6 + lib/System/Path.cpp | 40 +- lib/System/RWMutex.cpp | 18 +- lib/System/ThreadLocal.cpp | 5 + lib/System/Unix/Path.inc | 12 +- lib/System/Unix/Signals.inc | 44 + lib/System/Unix/ThreadLocal.inc | 1 + lib/System/Win32/Path.inc | 16 +- lib/System/Win32/Signals.inc | 14 + lib/System/Win32/ThreadLocal.inc | 4 + lib/Target/ARM/ARM.h | 60 +- lib/Target/ARM/ARM.td | 76 +- lib/Target/ARM/ARMAddressingModes.h | 20 +- .../ARM/{AsmPrinter => }/ARMAsmPrinter.cpp | 171 +- lib/Target/ARM/ARMBaseInstrInfo.cpp | 134 +- lib/Target/ARM/ARMBaseInstrInfo.h | 81 +- lib/Target/ARM/ARMBaseRegisterInfo.cpp | 563 ++- lib/Target/ARM/ARMBaseRegisterInfo.h | 29 +- lib/Target/ARM/ARMCallingConv.td | 4 +- lib/Target/ARM/ARMCodeEmitter.cpp | 72 +- lib/Target/ARM/ARMConstantIslandPass.cpp | 96 +- lib/Target/ARM/ARMExpandPseudoInsts.cpp | 361 +- lib/Target/ARM/ARMFastISel.cpp | 665 ++++ lib/Target/ARM/ARMGlobalMerge.cpp | 212 ++ lib/Target/ARM/ARMISelDAGToDAG.cpp | 369 +- lib/Target/ARM/ARMISelLowering.cpp | 635 +++- lib/Target/ARM/ARMISelLowering.h | 42 +- lib/Target/ARM/ARMInstrFormats.td | 290 +- lib/Target/ARM/ARMInstrInfo.td | 406 +- lib/Target/ARM/ARMInstrNEON.td | 627 +++- lib/Target/ARM/ARMInstrThumb.td | 19 +- lib/Target/ARM/ARMInstrThumb2.td | 732 ++-- lib/Target/ARM/ARMInstrVFP.td | 76 +- lib/Target/ARM/ARMLoadStoreOptimizer.cpp | 139 +- .../ARM/{AsmPrinter => }/ARMMCInstLower.cpp | 0 .../ARM/{AsmPrinter => }/ARMMCInstLower.h | 0 lib/Target/ARM/ARMMachineFunctionInfo.h | 11 +- lib/Target/ARM/ARMRegisterInfo.td | 176 +- lib/Target/ARM/ARMSubtarget.cpp | 5 + lib/Target/ARM/ARMSubtarget.h | 22 +- lib/Target/ARM/ARMTargetMachine.cpp | 16 +- lib/Target/ARM/ARMTargetMachine.h | 1 + lib/Target/ARM/AsmParser/ARMAsmParser.cpp | 245 +- lib/Target/ARM/AsmPrinter/ARMInstPrinter.cpp | 66 +- lib/Target/ARM/AsmPrinter/ARMInstPrinter.h | 2 + lib/Target/ARM/AsmPrinter/CMakeLists.txt | 2 - lib/Target/ARM/CMakeLists.txt | 10 +- .../ARM/Disassembler/ARMDisassembler.cpp | 13 +- .../ARM/Disassembler/ARMDisassemblerCore.cpp | 183 +- .../ARM/Disassembler/ARMDisassemblerCore.h | 66 +- .../ARM/Disassembler/ThumbDisassemblerCore.h | 227 +- lib/Target/ARM/Makefile | 5 +- lib/Target/ARM/NEONMoveFix.cpp | 2 +- lib/Target/ARM/NEONPreAllocPass.cpp | 147 +- lib/Target/ARM/README.txt | 42 +- lib/Target/ARM/Thumb1RegisterInfo.cpp | 369 +- lib/Target/ARM/Thumb1RegisterInfo.h | 22 +- lib/Target/ARM/Thumb2ITBlockPass.cpp | 64 +- lib/Target/ARM/Thumb2InstrInfo.cpp | 8 +- lib/Target/ARM/Thumb2SizeReduction.cpp | 14 +- lib/Target/Alpha/AlphaBranchSelector.cpp | 2 +- lib/Target/Alpha/AlphaCodeEmitter.cpp | 2 +- lib/Target/Alpha/AlphaISelDAGToDAG.cpp | 4 +- lib/Target/Alpha/AlphaInstrInfo.cpp | 26 - lib/Target/Alpha/AlphaInstrInfo.h | 6 - lib/Target/Alpha/AlphaLLRP.cpp | 2 +- lib/Target/Alpha/AlphaRegisterInfo.cpp | 6 +- lib/Target/Alpha/AlphaRegisterInfo.h | 5 +- .../Alpha/AsmPrinter/AlphaAsmPrinter.cpp | 2 - lib/Target/Blackfin/BlackfinInstrInfo.cpp | 28 - lib/Target/Blackfin/BlackfinInstrInfo.h | 4 - lib/Target/Blackfin/BlackfinRegisterInfo.cpp | 16 +- lib/Target/Blackfin/BlackfinRegisterInfo.h | 7 +- lib/Target/CBackend/CBackend.cpp | 12 +- lib/Target/CellSPU/SPUCallingConv.td | 24 +- lib/Target/CellSPU/SPUISelDAGToDAG.cpp | 44 +- lib/Target/CellSPU/SPUISelLowering.cpp | 105 +- lib/Target/CellSPU/SPUInstrInfo.cpp | 142 - lib/Target/CellSPU/SPUInstrInfo.h | 6 - lib/Target/CellSPU/SPUInstrInfo.td | 156 +- lib/Target/CellSPU/SPUOperands.td | 6 - lib/Target/CellSPU/SPURegisterInfo.cpp | 11 +- lib/Target/CellSPU/SPURegisterInfo.h | 5 +- lib/Target/CellSPU/SPURegisterInfo.td | 2 +- lib/Target/CppBackend/CPPBackend.cpp | 17 +- .../MBlaze/AsmPrinter/MBlazeAsmPrinter.cpp | 10 - lib/Target/MBlaze/MBlaze.td | 2 +- lib/Target/MBlaze/MBlazeCallingConv.td | 2 +- lib/Target/MBlaze/MBlazeDelaySlotFiller.cpp | 2 +- lib/Target/MBlaze/MBlazeISelDAGToDAG.cpp | 2 +- lib/Target/MBlaze/MBlazeInstrFPU.td | 2 +- lib/Target/MBlaze/MBlazeInstrFSL.td | 2 +- lib/Target/MBlaze/MBlazeInstrFormats.td | 2 +- lib/Target/MBlaze/MBlazeInstrInfo.cpp | 35 - lib/Target/MBlaze/MBlazeInstrInfo.h | 6 - lib/Target/MBlaze/MBlazeInstrInfo.td | 2 +- lib/Target/MBlaze/MBlazeIntrinsics.td | 12 +- lib/Target/MBlaze/MBlazeRegisterInfo.cpp | 5 +- lib/Target/MBlaze/MBlazeRegisterInfo.h | 5 +- lib/Target/MBlaze/MBlazeRegisterInfo.td | 2 +- lib/Target/MBlaze/MBlazeSchedule.td | 2 +- lib/Target/MSIL/CMakeLists.txt | 3 - lib/Target/MSIL/MSILWriter.cpp | 1706 --------- lib/Target/MSIL/MSILWriter.h | 258 -- lib/Target/MSIL/Makefile | 16 - lib/Target/MSIL/README.TXT | 26 - lib/Target/MSIL/TargetInfo/CMakeLists.txt | 6 - lib/Target/MSIL/TargetInfo/MSILTargetInfo.cpp | 26 - lib/Target/MSIL/TargetInfo/Makefile | 15 - lib/Target/MSP430/MSP430BranchSelector.cpp | 7 +- lib/Target/MSP430/MSP430InstrInfo.cpp | 23 +- lib/Target/MSP430/MSP430InstrInfo.h | 4 - lib/Target/MSP430/MSP430RegisterInfo.cpp | 12 +- lib/Target/MSP430/MSP430RegisterInfo.h | 7 +- lib/Target/Mangler.cpp | 3 +- lib/Target/Mips/AsmPrinter/MipsAsmPrinter.cpp | 20 + lib/Target/Mips/Mips.td | 2 +- lib/Target/Mips/MipsCallingConv.td | 2 +- lib/Target/Mips/MipsDelaySlotFiller.cpp | 2 +- lib/Target/Mips/MipsISelDAGToDAG.cpp | 11 +- lib/Target/Mips/MipsISelLowering.cpp | 8 +- lib/Target/Mips/MipsInstrFPU.td | 2 +- lib/Target/Mips/MipsInstrFormats.td | 2 +- lib/Target/Mips/MipsInstrInfo.cpp | 47 - lib/Target/Mips/MipsInstrInfo.h | 6 - lib/Target/Mips/MipsInstrInfo.td | 9 +- lib/Target/Mips/MipsRegisterInfo.cpp | 6 +- lib/Target/Mips/MipsRegisterInfo.h | 5 +- lib/Target/Mips/MipsRegisterInfo.td | 2 +- lib/Target/Mips/MipsSchedule.td | 2 +- lib/Target/PIC16/CMakeLists.txt | 2 +- lib/Target/PIC16/PIC16.h | 7 +- lib/Target/PIC16/PIC16ISelLowering.cpp | 10 + lib/Target/PIC16/PIC16ISelLowering.h | 5 +- lib/Target/PIC16/PIC16InstrInfo.cpp | 15 - lib/Target/PIC16/PIC16InstrInfo.h | 4 - lib/Target/PIC16/PIC16MemSelOpt.cpp | 2 +- lib/Target/PIC16/PIC16Passes/PIC16Cloner.cpp | 2 +- lib/Target/PIC16/PIC16Passes/PIC16Cloner.h | 2 +- lib/Target/PIC16/PIC16Passes/PIC16Overlay.cpp | 5 +- lib/Target/PIC16/PIC16Passes/PIC16Overlay.h | 2 +- lib/Target/PIC16/PIC16RegisterInfo.cpp | 9 +- lib/Target/PIC16/PIC16RegisterInfo.h | 5 +- .../PowerPC/AsmPrinter/PPCAsmPrinter.cpp | 14 + lib/Target/PowerPC/PPCBranchSelector.cpp | 7 +- lib/Target/PowerPC/PPCCallingConv.td | 2 +- lib/Target/PowerPC/PPCCodeEmitter.cpp | 4 +- lib/Target/PowerPC/PPCISelLowering.cpp | 39 +- lib/Target/PowerPC/PPCInstrInfo.cpp | 82 +- lib/Target/PowerPC/PPCInstrInfo.h | 6 - lib/Target/PowerPC/PPCInstrInfo.td | 19 +- lib/Target/PowerPC/PPCRegisterInfo.cpp | 22 +- lib/Target/PowerPC/PPCRegisterInfo.h | 5 +- lib/Target/PowerPC/PPCSubtarget.cpp | 4 + lib/Target/PowerPC/PPCSubtarget.h | 4 + lib/Target/README.txt | 18 +- lib/Target/Sparc/DelaySlotFiller.cpp | 2 +- lib/Target/Sparc/FPMover.cpp | 2 +- lib/Target/Sparc/Sparc.td | 2 +- lib/Target/Sparc/SparcISelDAGToDAG.cpp | 8 +- lib/Target/Sparc/SparcInstrInfo.cpp | 40 - lib/Target/Sparc/SparcInstrInfo.h | 6 - lib/Target/Sparc/SparcInstrInfo.td | 12 +- lib/Target/Sparc/SparcRegisterInfo.cpp | 6 +- lib/Target/Sparc/SparcRegisterInfo.h | 5 +- lib/Target/SystemZ/SystemZInstrInfo.cpp | 25 - lib/Target/SystemZ/SystemZInstrInfo.h | 3 - lib/Target/SystemZ/SystemZRegisterInfo.cpp | 9 +- lib/Target/SystemZ/SystemZRegisterInfo.h | 7 +- lib/Target/TargetData.cpp | 62 +- lib/Target/TargetMachine.cpp | 20 +- lib/Target/TargetRegisterInfo.cpp | 14 +- lib/Target/X86/AsmParser/X86AsmParser.cpp | 274 +- lib/Target/X86/AsmPrinter/CMakeLists.txt | 3 +- .../X86/AsmPrinter/X86ATTInstPrinter.cpp | 5 + lib/Target/X86/AsmPrinter/X86ATTInstPrinter.h | 3 + lib/Target/X86/AsmPrinter/X86InstComments.cpp | 232 ++ lib/Target/X86/AsmPrinter/X86InstComments.h | 25 + .../X86/AsmPrinter/X86IntelInstPrinter.cpp | 5 + .../X86/AsmPrinter/X86IntelInstPrinter.h | 4 + lib/Target/X86/CMakeLists.txt | 10 +- lib/Target/X86/README-FPStack.txt | 4 +- lib/Target/X86/README-SSE.txt | 42 +- lib/Target/X86/README.txt | 104 +- lib/Target/X86/SSEDomainFix.cpp | 2 +- lib/Target/X86/X86.h | 5 - lib/Target/X86/X86.td | 4 +- lib/Target/X86/X86AsmBackend.cpp | 45 +- .../X86/{AsmPrinter => }/X86AsmPrinter.cpp | 51 +- .../X86/{AsmPrinter => }/X86AsmPrinter.h | 6 +- lib/Target/X86/X86CallingConv.td | 32 +- lib/Target/X86/X86CodeEmitter.cpp | 119 +- lib/Target/X86/X86FastISel.cpp | 29 +- lib/Target/X86/X86FloatingPoint.cpp | 473 ++- lib/Target/X86/X86FloatingPointRegKill.cpp | 153 - lib/Target/X86/X86ISelDAGToDAG.cpp | 37 +- lib/Target/X86/X86ISelLowering.cpp | 1227 +++++- lib/Target/X86/X86ISelLowering.h | 58 +- lib/Target/X86/X86Instr64bit.td | 156 +- lib/Target/X86/X86InstrFMA.td | 60 + lib/Target/X86/X86InstrFPStack.td | 6 +- lib/Target/X86/X86InstrFormats.td | 33 +- lib/Target/X86/X86InstrFragmentsSIMD.td | 80 +- lib/Target/X86/X86InstrInfo.cpp | 692 +--- lib/Target/X86/X86InstrInfo.h | 30 +- lib/Target/X86/X86InstrInfo.td | 145 +- lib/Target/X86/X86InstrMMX.td | 2 +- lib/Target/X86/X86InstrSSE.td | 1935 +++++++--- lib/Target/X86/X86MCAsmInfo.cpp | 3 + lib/Target/X86/X86MCCodeEmitter.cpp | 57 +- .../X86/{AsmPrinter => }/X86MCInstLower.cpp | 119 +- .../X86/{AsmPrinter => }/X86MCInstLower.h | 13 +- lib/Target/X86/X86RegisterInfo.cpp | 103 +- lib/Target/X86/X86RegisterInfo.h | 9 +- lib/Target/X86/X86RegisterInfo.td | 17 +- lib/Target/X86/X86ShuffleDecode.h | 155 + lib/Target/X86/X86Subtarget.cpp | 10 +- lib/Target/X86/X86Subtarget.h | 8 + lib/Target/X86/X86TargetMachine.cpp | 44 +- .../XCore/AsmPrinter/XCoreAsmPrinter.cpp | 12 +- lib/Target/XCore/CMakeLists.txt | 2 +- lib/Target/XCore/XCoreISelDAGToDAG.cpp | 21 +- lib/Target/XCore/XCoreInstrInfo.cpp | 29 +- lib/Target/XCore/XCoreInstrInfo.h | 6 - lib/Target/XCore/XCoreInstrInfo.td | 12 +- lib/Target/XCore/XCoreRegisterInfo.cpp | 14 +- lib/Target/XCore/XCoreRegisterInfo.h | 5 +- lib/Transforms/Hello/Hello.cpp | 11 +- lib/Transforms/IPO/ArgumentPromotion.cpp | 13 +- lib/Transforms/IPO/ConstantMerge.cpp | 34 +- .../IPO/DeadArgumentElimination.cpp | 26 +- lib/Transforms/IPO/DeadTypeElimination.cpp | 4 +- lib/Transforms/IPO/ExtractGV.cpp | 153 +- lib/Transforms/IPO/FunctionAttrs.cpp | 12 +- lib/Transforms/IPO/GlobalDCE.cpp | 5 +- lib/Transforms/IPO/GlobalOpt.cpp | 12 +- lib/Transforms/IPO/IPConstantPropagation.cpp | 10 +- lib/Transforms/IPO/InlineAlways.cpp | 6 +- lib/Transforms/IPO/InlineSimple.cpp | 8 +- lib/Transforms/IPO/Inliner.cpp | 12 +- lib/Transforms/IPO/Internalize.cpp | 8 +- lib/Transforms/IPO/LoopExtractor.cpp | 23 +- lib/Transforms/IPO/LowerSetJmp.cpp | 4 +- lib/Transforms/IPO/MergeFunctions.cpp | 658 ++-- lib/Transforms/IPO/PartialInlining.cpp | 10 +- lib/Transforms/IPO/PartialSpecialization.cpp | 46 +- lib/Transforms/IPO/PruneEH.cpp | 6 +- lib/Transforms/IPO/StripDeadPrototypes.cpp | 6 +- lib/Transforms/IPO/StripSymbols.cpp | 36 +- lib/Transforms/IPO/StructRetPromotion.cpp | 26 +- lib/Transforms/InstCombine/InstCombine.h | 2 +- .../InstCombine/InstCombineAndOrXor.cpp | 46 +- .../InstCombine/InstCombineCalls.cpp | 35 +- .../InstCombine/InstCombineCasts.cpp | 287 +- .../InstCombine/InstCombineCompares.cpp | 2 +- .../InstCombineLoadStoreAlloca.cpp | 22 +- .../InstCombine/InstCombineSelect.cpp | 28 - .../InstCombine/InstCombineShifts.cpp | 307 +- .../InstCombine/InstructionCombining.cpp | 4 +- .../Instrumentation/EdgeProfiling.cpp | 6 +- .../Instrumentation/OptimalEdgeProfiling.cpp | 8 +- lib/Transforms/Scalar/ABCD.cpp | 1112 ------ lib/Transforms/Scalar/ADCE.cpp | 4 +- lib/Transforms/Scalar/BasicBlockPlacement.cpp | 6 +- lib/Transforms/Scalar/CMakeLists.txt | 3 +- lib/Transforms/Scalar/CodeGenPrepare.cpp | 36 +- lib/Transforms/Scalar/ConstantProp.cpp | 6 +- .../Scalar/CorrelatedValuePropagation.cpp | 200 + lib/Transforms/Scalar/DCE.cpp | 10 +- .../Scalar/DeadStoreElimination.cpp | 7 +- lib/Transforms/Scalar/GEPSplitter.cpp | 6 +- lib/Transforms/Scalar/GVN.cpp | 15 +- lib/Transforms/Scalar/IndVarSimplify.cpp | 18 +- lib/Transforms/Scalar/JumpThreading.cpp | 217 +- lib/Transforms/Scalar/LICM.cpp | 738 ++-- lib/Transforms/Scalar/LoopDeletion.cpp | 7 +- lib/Transforms/Scalar/LoopIndexSplit.cpp | 12 +- lib/Transforms/Scalar/LoopRotation.cpp | 34 +- lib/Transforms/Scalar/LoopStrengthReduce.cpp | 182 +- lib/Transforms/Scalar/LoopUnrollPass.cpp | 23 +- lib/Transforms/Scalar/LoopUnswitch.cpp | 30 +- lib/Transforms/Scalar/LowerAtomic.cpp | 161 + lib/Transforms/Scalar/MemCpyOptimizer.cpp | 21 +- lib/Transforms/Scalar/Reassociate.cpp | 5 +- lib/Transforms/Scalar/Reg2Mem.cpp | 8 +- lib/Transforms/Scalar/SCCP.cpp | 41 +- .../Scalar/ScalarReplAggregates.cpp | 49 +- lib/Transforms/Scalar/SimplifyCFGPass.cpp | 10 +- .../Scalar/SimplifyHalfPowrLibCalls.cpp | 6 +- lib/Transforms/Scalar/SimplifyLibCalls.cpp | 27 +- lib/Transforms/Scalar/Sink.cpp | 5 +- lib/Transforms/Scalar/TailDuplication.cpp | 4 +- .../Scalar/TailRecursionElimination.cpp | 64 +- lib/Transforms/Utils/BasicBlockUtils.cpp | 25 +- lib/Transforms/Utils/BasicInliner.cpp | 4 +- lib/Transforms/Utils/BreakCriticalEdges.cpp | 10 +- lib/Transforms/Utils/BuildLibCalls.cpp | 21 +- lib/Transforms/Utils/CMakeLists.txt | 1 - lib/Transforms/Utils/CloneFunction.cpp | 86 +- lib/Transforms/Utils/CloneModule.cpp | 30 +- lib/Transforms/Utils/InlineFunction.cpp | 11 +- lib/Transforms/Utils/InstructionNamer.cpp | 8 +- lib/Transforms/Utils/LCSSA.cpp | 27 +- lib/Transforms/Utils/Local.cpp | 3 + lib/Transforms/Utils/LoopSimplify.cpp | 42 +- lib/Transforms/Utils/LoopUnroll.cpp | 6 + lib/Transforms/Utils/LowerInvoke.cpp | 11 +- lib/Transforms/Utils/LowerSwitch.cpp | 16 +- lib/Transforms/Utils/Mem2Reg.cpp | 7 +- .../Utils/PromoteMemoryToRegister.cpp | 17 +- lib/Transforms/Utils/SSAUpdater.cpp | 40 +- lib/Transforms/Utils/SSI.cpp | 432 --- lib/Transforms/Utils/SimplifyCFG.cpp | 56 +- .../Utils/UnifyFunctionExitNodes.cpp | 6 +- lib/Transforms/Utils/ValueMapper.cpp | 84 +- lib/VMCore/AsmWriter.cpp | 167 +- lib/VMCore/AutoUpgrade.cpp | 217 +- lib/VMCore/CMakeLists.txt | 1 + lib/VMCore/ConstantFold.cpp | 40 - lib/VMCore/Constants.cpp | 121 +- lib/VMCore/ConstantsContext.h | 16 +- lib/VMCore/Core.cpp | 92 +- lib/VMCore/Dominators.cpp | 145 +- lib/VMCore/Globals.cpp | 9 +- lib/VMCore/InlineAsm.cpp | 2 +- lib/VMCore/Instruction.cpp | 4 +- lib/VMCore/Instructions.cpp | 49 +- lib/VMCore/LLVMContext.cpp | 13 +- lib/VMCore/LLVMContextImpl.cpp | 3 - lib/VMCore/LLVMContextImpl.h | 5 - lib/VMCore/Metadata.cpp | 170 +- lib/VMCore/Module.cpp | 23 +- lib/VMCore/Pass.cpp | 293 +- lib/VMCore/PassManager.cpp | 330 +- lib/VMCore/PassRegistry.cpp | 159 + lib/VMCore/PrintModulePass.cpp | 18 +- lib/VMCore/Type.cpp | 257 +- lib/VMCore/TypesContext.h | 78 +- lib/VMCore/Use.cpp | 19 +- lib/VMCore/Value.cpp | 35 +- lib/VMCore/ValueSymbolTable.cpp | 2 - lib/VMCore/Verifier.cpp | 125 +- runtime/libprofile/Makefile | 8 +- ...xported_symbols.lst => libprofile.exports} | 0 .../BasicAA/args-rets-allocas-loads.ll | 220 +- test/Analysis/BasicAA/constant-over-index.ll | 5 +- test/Analysis/BasicAA/featuretest.ll | 50 +- test/Analysis/BasicAA/gep-alias.ll | 12 +- test/Analysis/BasicAA/getmodrefinfo-cs-cs.ll | 26 + test/Analysis/BasicAA/modref.ll | 11 + .../RegionInfo/20100809_bb_not_in_domtree.ll | 20 + test/Analysis/RegionInfo/block_sort.ll | 42 + test/Analysis/RegionInfo/cond_loop.ll | 33 + .../RegionInfo/condition_complicated.ll | 60 + .../RegionInfo/condition_complicated_2.ll | 44 + .../RegionInfo/condition_forward_edge.ll | 26 + .../RegionInfo/condition_same_exit.ll | 31 + test/Analysis/RegionInfo/condition_simple.ll | 28 + .../ABCD => Analysis/RegionInfo}/dg.exp | 0 test/Analysis/RegionInfo/exit_in_condition.ll | 38 + test/Analysis/RegionInfo/infinite_loop.ll | 20 + test/Analysis/RegionInfo/infinite_loop_2.ll | 36 + test/Analysis/RegionInfo/infinite_loop_3.ll | 52 + test/Analysis/RegionInfo/infinite_loop_4.ll | 48 + .../RegionInfo/loop_with_condition.ll | 46 + test/Analysis/RegionInfo/loops_1.ll | 40 + test/Analysis/RegionInfo/loops_2.ll | 49 + test/Analysis/RegionInfo/mix_1.ll | 69 + .../RegionInfo/multiple_exiting_edge.ll | 38 + test/Analysis/RegionInfo/nested_loops.ll | 33 + test/Analysis/RegionInfo/next.ll | 49 + test/Analysis/RegionInfo/paper.ll | 55 + .../RegionInfo/two_loops_same_header.ll | 46 + test/Analysis/ScalarEvolution/avoid-smax-1.ll | 2 +- .../ScalarEvolution/max-trip-count.ll | 42 +- test/Archive/README.txt | 2 +- test/Assembler/2010-01-06-UnionType.ll | 3 - test/Assembler/align-inst-alloca.ll | 6 + test/Assembler/align-inst-load.ll | 6 + test/Assembler/align-inst-store.ll | 6 + test/Assembler/align-inst.ll | 10 + test/Assembler/comment.ll | 20 + test/Assembler/getelementptr.ll | 4 +- test/Bindings/Ocaml/analysis.ml | 2 +- test/Bindings/Ocaml/bitreader.ml | 2 +- test/Bindings/Ocaml/bitwriter.ml | 2 +- test/Bindings/Ocaml/executionengine.ml | 2 +- test/Bindings/Ocaml/scalar_opts.ml | 6 +- test/Bindings/Ocaml/target.ml | 7 +- test/Bindings/Ocaml/vmcore.ml | 42 +- test/Bitcode/AutoUpgradeGlobals.ll | 3 + test/Bitcode/AutoUpgradeGlobals.ll.bc | Bin 0 -> 312 bytes test/Bitcode/neon-intrinsics.ll | 213 ++ test/Bitcode/neon-intrinsics.ll.bc | Bin 0 -> 5764 bytes test/BugPoint/crash-narrowfunctiontest.ll | 4 +- test/BugPoint/metadata.ll | 35 + test/BugPoint/remove_arguments_test.ll | 4 +- test/CMakeLists.txt | 17 + test/CodeGen/ARM/2007-01-19-InfiniteLoop.ll | 6 +- .../ARM/2007-03-26-RegScavengerAssert.ll | 2 +- .../2007-05-31-RegScavengerInfiniteLoop.ll | 2 +- test/CodeGen/ARM/2009-12-02-vtrn-undef.ll | 14 + test/CodeGen/ARM/2010-05-20-NEONSpillCrash.ll | 22 +- test/CodeGen/ARM/2010-05-21-BuildVector.ll | 4 +- .../CodeGen/ARM/2010-06-11-vmovdrr-bitcast.ll | 4 +- test/CodeGen/ARM/2010-06-21-nondarwin-tc.ll | 1 + .../ARM/2010-06-29-PartialRedefFastAlloc.ll | 4 +- test/CodeGen/ARM/2010-07-26-GlobalMerge.ll | 95 + test/CodeGen/ARM/2010-08-04-EHCrash.ll | 65 + test/CodeGen/ARM/arguments.ll | 42 +- test/CodeGen/ARM/bfi.ll | 40 + test/CodeGen/ARM/call-tc.ll | 1 + test/CodeGen/ARM/code-placement.ll | 29 + test/CodeGen/ARM/div.ll | 10 - test/CodeGen/ARM/fast-isel.ll | 39 + test/CodeGen/ARM/fnmuls.ll | 12 +- test/CodeGen/ARM/fpcmp-opt.ll | 2 +- test/CodeGen/ARM/fpowi.ll | 2 +- test/CodeGen/ARM/long_shift.ll | 6 +- test/CodeGen/ARM/lsr-on-unrolled-loops.ll | 19 +- test/CodeGen/ARM/pack.ll | 32 +- test/CodeGen/ARM/reg_sequence.ll | 73 +- test/CodeGen/ARM/remat.ll | 2 +- test/CodeGen/ARM/select.ll | 25 + test/CodeGen/ARM/spill-q.ll | 8 +- test/CodeGen/ARM/t2-imm.ll | 6 +- test/CodeGen/ARM/vaba.ll | 128 +- test/CodeGen/ARM/vabd.ll | 38 +- test/CodeGen/ARM/vadd.ll | 82 +- test/CodeGen/ARM/vext.ll | 20 + test/CodeGen/ARM/vld1.ll | 53 +- test/CodeGen/ARM/vld2.ll | 36 +- test/CodeGen/ARM/vld3.ll | 36 +- test/CodeGen/ARM/vld4.ll | 36 +- test/CodeGen/ARM/vldlane.ll | 84 +- test/CodeGen/ARM/vmla.ll | 78 +- test/CodeGen/ARM/vmls.ll | 78 +- test/CodeGen/ARM/vmov.ll | 30 +- test/CodeGen/ARM/vmul.ll | 68 +- test/CodeGen/ARM/vrev.ll | 18 + test/CodeGen/ARM/vst1.ll | 40 +- test/CodeGen/ARM/vst2.ll | 36 +- test/CodeGen/ARM/vst3.ll | 38 +- test/CodeGen/ARM/vst4.ll | 36 +- test/CodeGen/ARM/vstlane.ll | 84 +- test/CodeGen/ARM/vsub.ll | 82 +- test/CodeGen/ARM/vtrn.ll | 27 + test/CodeGen/ARM/vuzp.ll | 27 + test/CodeGen/ARM/vzip.ll | 27 + test/CodeGen/Alpha/2010-08-01-mulreduce64.ll | 11 + test/CodeGen/CellSPU/arg_ret.ll | 33 + test/CodeGen/CellSPU/bigstack.ll | 6 +- test/CodeGen/CellSPU/call.ll | 26 +- test/CodeGen/CellSPU/call_indirect.ll | 2 +- test/CodeGen/CellSPU/shuffles.ll | 23 + test/CodeGen/CellSPU/v2f32.ll | 75 + test/CodeGen/CellSPU/v2i32.ll | 64 + .../Generic/2010-07-27-DAGCombineCrash.ll | 6 + test/CodeGen/Mips/2008-06-05-Carry.ll | 2 +- test/CodeGen/Mips/2008-07-03-SRet.ll | 2 +- test/CodeGen/Mips/2008-07-05-ByVal.ll | 2 +- test/CodeGen/Mips/2008-07-06-fadd64.ll | 2 +- test/CodeGen/Mips/2008-07-07-FPExtend.ll | 2 +- test/CodeGen/Mips/2008-07-07-Float2Int.ll | 2 +- .../Mips/2008-07-07-IntDoubleConvertions.ll | 2 +- .../Mips/2008-07-15-InternalConstant.ll | 2 +- test/CodeGen/Mips/2008-07-15-SmallSection.ll | 2 +- test/CodeGen/Mips/2008-07-16-SignExtInReg.ll | 2 +- test/CodeGen/Mips/2008-07-22-Cstpool.ll | 2 +- test/CodeGen/Mips/2008-07-23-fpcmp.ll | 2 +- test/CodeGen/Mips/2008-07-29-icmp.ll | 2 +- test/CodeGen/Mips/2008-07-31-fcopysign.ll | 2 +- test/CodeGen/Mips/2008-08-01-AsmInline.ll | 2 +- test/CodeGen/Mips/2008-08-03-fabs64.ll | 2 +- test/CodeGen/Mips/2008-08-04-Bitconvert.ll | 2 +- test/CodeGen/Mips/2008-08-06-Alloca.ll | 2 +- test/CodeGen/Mips/2008-08-07-CC.ll | 2 +- test/CodeGen/Mips/2008-08-07-FPRound.ll | 2 +- test/CodeGen/Mips/2008-08-08-ctlz.ll | 2 +- test/CodeGen/Mips/2010-07-20-Select.ll | 21 + test/CodeGen/Mips/2010-07-20-Switch.ll | 33 + .../PowerPC/2008-01-25-EmptyFunction.ll | 8 - test/CodeGen/PowerPC/empty-functions.ll | 12 + test/CodeGen/PowerPC/vec_constants.ll | 18 +- test/CodeGen/SystemZ/05-MemLoadsStores.ll | 2 +- test/CodeGen/SystemZ/05-MemLoadsStores16.ll | 2 +- test/CodeGen/SystemZ/07-BrUnCond.ll | 2 +- test/CodeGen/SystemZ/09-DynamicAlloca.ll | 2 +- test/CodeGen/SystemZ/09-Globals.ll | 2 +- test/CodeGen/SystemZ/10-FuncsPic.ll | 2 +- test/CodeGen/SystemZ/10-GlobalsPic.ll | 2 +- test/CodeGen/SystemZ/11-BSwap.ll | 2 +- test/CodeGen/SystemZ/2009-06-02-Rotate.ll | 2 +- test/CodeGen/SystemZ/2009-07-04-Shl32.ll | 2 +- test/CodeGen/SystemZ/2009-07-05-Shifts.ll | 2 +- .../2009-07-10-BadIncomingArgOffset.ll | 2 +- .../SystemZ/2009-07-11-FloatBitConvert.ll | 2 +- .../SystemZ/2009-07-11-InvalidRIISel.ll | 2 +- .../Thumb/2007-05-05-InvalidPushPop.ll | 2 +- .../CodeGen/Thumb/2010-07-15-debugOrdering.ll | 147 + test/CodeGen/Thumb/barrier.ll | 24 + test/CodeGen/Thumb/dyn-stackalloc.ll | 2 +- test/CodeGen/Thumb/large-stack.ll | 29 +- test/CodeGen/Thumb/vargs.ll | 2 +- .../Thumb2/2009-10-15-ITBlockBranch.ll | 4 +- test/CodeGen/Thumb2/2010-04-15-DynAllocBug.ll | 13 +- .../Thumb2/2010-08-10-VarSizedAllocaBug.ll | 53 + test/CodeGen/Thumb2/bfi.ll | 40 + test/CodeGen/Thumb2/cortex-fp.ll | 24 + test/CodeGen/Thumb2/crash.ll | 6 +- test/CodeGen/Thumb2/div.ll | 2 +- test/CodeGen/Thumb2/ldr-str-imm12.ll | 8 +- test/CodeGen/Thumb2/lsr-deficiency.ll | 4 +- test/CodeGen/Thumb2/machine-licm-vdup.ll | 38 + test/CodeGen/Thumb2/machine-licm.ll | 8 +- test/CodeGen/Thumb2/thumb2-and2.ll | 2 +- test/CodeGen/Thumb2/thumb2-badreg-operands.ll | 15 + test/CodeGen/Thumb2/thumb2-barrier.ll | 17 + test/CodeGen/Thumb2/thumb2-call-tc.ll | 1 + test/CodeGen/Thumb2/thumb2-cmp.ll | 14 + test/CodeGen/Thumb2/thumb2-ifcvt1-tc.ll | 1 + test/CodeGen/Thumb2/thumb2-pack.ll | 32 +- test/CodeGen/Thumb2/thumb2-spill-q.ll | 8 +- test/CodeGen/Thumb2/thumb2-uxtb.ll | 2 +- test/CodeGen/X86/2006-05-22-FPSetEQ.ll | 2 +- test/CodeGen/X86/2007-06-14-branchfold.ll | 133 - test/CodeGen/X86/2008-01-25-EmptyFunction.ll | 8 - .../X86}/2008-08-06-CmpStride.ll | 0 .../X86}/2009-02-09-ivs-different-sizes.ll | 0 test/CodeGen/X86/2009-02-26-MachineLICMBug.ll | 2 +- test/CodeGen/X86/2009-03-13-PHIElimBug.ll | 2 +- test/CodeGen/X86/2009-03-16-PHIElimInLPad.ll | 2 +- test/CodeGen/X86/2009-03-23-MultiUseSched.ll | 2 +- .../X86}/2010-01-18-DbgValue.ll | 5 +- .../X86}/2010-02-01-DbgValueCrash.ll | 1 - .../X86}/2010-05-25-DotDebugLoc.ll | 2 +- .../X86}/2010-05-28-Crash.ll | 0 .../X86}/2010-06-01-DeadArg-DbgInfo.ll | 0 test/CodeGen/X86/2010-07-11-FPStackLoneUse.ll | 28 + test/CodeGen/X86/2010-07-15-Crash.ll | 12 + test/CodeGen/X86/2010-07-29-SetccSimplify.ll | 14 + .../X86/2010-08-04-MaskedSignedCompare.ll | 36 + test/CodeGen/X86/2010-08-04-MingWCrash.ll | 39 + test/CodeGen/X86/2010-08-10-DbgConstant.ll | 25 + .../2010-09-01-RemoveCopyByCommutingDef.ll | 28 + test/CodeGen/X86/GC/dg.exp | 4 +- test/CodeGen/X86/MachineSink-PHIUse.ll | 39 + test/CodeGen/X86/avx-128.ll | 12 + test/CodeGen/X86/avx-256.ll | 15 + test/CodeGen/X86/avx-intrinsics-x86.ll | 2587 +++++++++++++ test/CodeGen/X86/avx-intrinsics-x86_64.ll | 50 + test/CodeGen/X86/barrier-sse.ll | 21 + test/CodeGen/X86/barrier.ll | 7 + test/CodeGen/X86/call-imm.ll | 2 +- .../change-compare-stride-trickiness-0.ll | 0 .../change-compare-stride-trickiness-1.ll | 0 .../change-compare-stride-trickiness-2.ll | 0 test/CodeGen/X86/constant-pool-remat-0.ll | 4 +- test/CodeGen/X86/critical-edge-split.ll | 2 +- test/CodeGen/X86/dllexport.ll | 2 +- test/CodeGen/X86/dyn-stackalloc.ll | 6 +- test/CodeGen/X86/empty-functions.ll | 15 + test/CodeGen/X86/fabs.ll | 2 +- test/CodeGen/X86/fast-isel-atomic.ll | 17 + test/CodeGen/X86/fast-isel-cmp-branch.ll | 29 + test/CodeGen/X86/fast-isel-gep.ll | 4 +- test/CodeGen/X86/fast-isel-shift-imm.ll | 2 +- test/CodeGen/X86/force-align-stack.ll | 21 + .../X86}/insert-positions.ll | 0 test/CodeGen/X86/int-intrinsic.ll | 20 + test/CodeGen/X86/licm-nested.ll | 2 +- test/CodeGen/X86/lock-inst-encoding.ll | 22 + test/CodeGen/X86/loop-strength-reduce4.ll | 4 +- test/CodeGen/X86/lsr-interesting-step.ll | 51 + test/CodeGen/X86/lsr-normalization.ll | 99 + test/CodeGen/X86/lsr-reuse.ll | 4 +- test/CodeGen/X86/lsr-static-addr.ll | 31 + test/CodeGen/X86/lsr-wrap.ll | 2 +- test/CodeGen/X86/narrow_op-2.ll | 25 - test/CodeGen/X86/phi-immediate-factoring.ll | 2 +- test/CodeGen/X86/pr7882.ll | 17 + test/CodeGen/X86/shl-anyext.ll | 40 + test/CodeGen/X86/sibcall.ll | 2 + test/CodeGen/X86/sse-minmax.ll | 4 +- test/CodeGen/X86/sse1.ll | 45 + test/CodeGen/X86/sse2.ll | 168 +- test/CodeGen/X86/sse41.ll | 25 + test/CodeGen/X86/stack-color-with-reg.ll | 361 -- test/CodeGen/X86/stdcall.ll | 2 +- test/CodeGen/X86/store-narrow.ll | 31 +- test/CodeGen/X86/tailcall-fastisel.ll | 14 +- test/CodeGen/X86/twoaddr-coalesce.ll | 2 +- test/CodeGen/X86/v2f32.ll | 57 +- test/CodeGen/X86/vec_cast.ll | 21 +- test/CodeGen/X86/vec_insert-6.ll | 2 +- test/CodeGen/X86/vec_insert-9.ll | 2 +- test/CodeGen/X86/vec_shift4.ll | 25 + test/CodeGen/X86/vec_shuffle-10.ll | 25 - test/CodeGen/X86/vec_shuffle-19.ll | 2 +- test/CodeGen/X86/vec_shuffle-20.ll | 2 +- test/CodeGen/X86/vec_shuffle-24.ll | 3 +- test/CodeGen/X86/vec_shuffle-3.ll | 20 - test/CodeGen/X86/vec_shuffle-37.ll | 14 + test/CodeGen/X86/vec_shuffle-4.ll | 12 - test/CodeGen/X86/vec_shuffle-5.ll | 13 - test/CodeGen/X86/vec_shuffle-6.ll | 42 - test/CodeGen/X86/vec_shuffle-7.ll | 11 - test/CodeGen/X86/vec_shuffle-8.ll | 10 - test/CodeGen/X86/vec_shuffle-9.ll | 21 - test/CodeGen/X86/widen_shuffle-1.ll | 8 +- test/CodeGen/X86/win_chkstk.ll | 45 + test/CodeGen/X86/zero-remat.ll | 2 +- test/DebugInfo/2010-07-19-Crash.ll | 24 + test/DebugInfo/2010-08-04-StackVariable.ll | 124 + test/DebugInfo/printdbginfo2.ll | 2 +- test/Feature/NamedMDNode.ll | 2 +- test/Feature/linker_private_linkages.ll | 1 + test/Feature/metadata.ll | 6 +- test/Feature/unions.ll | 14 - test/FrontendC++/2009-07-15-LineNumbers.cpp | 2 +- test/FrontendC++/2010-07-19-nowarn.cpp | 21 + test/FrontendC++/2010-07-23-DeclLoc.cpp | 86 + test/FrontendC++/2010-08-31-ByValArg.cpp | 53 + .../2008-03-24-BitField-And-Alloca.c | 2 +- test/FrontendC/2010-05-18-asmsched.c | 4 +- .../2010-07-14-overconservative-align.c | 4 +- test/FrontendC/2010-07-14-ref-off-end.c | 4 +- test/FrontendC/2010-07-27-MinNoFoldConst.c | 18 + test/FrontendC/2010-08-12-asm-aggr-arg.c | 16 + test/FrontendC/asm-reg-var-local.c | 32 + test/FrontendC/cstring-align.c | 14 +- test/FrontendC/misaligned-param.c | 15 + test/FrontendC/vla-1.c | 5 +- test/FrontendC/vla-2.c | 10 + .../2010-08-02-NonPODObjectValue.mm | 27 + test/FrontendObjC++/2010-08-04-Template.mm | 10 + test/FrontendObjC++/2010-08-06-X.Y-syntax.mm | 16 + test/FrontendObjC/2009-08-17-DebugInfo.m | 2 +- test/Integer/a15.ll | 27 - test/Integer/a15.ll.out | 21 - test/Integer/a17.ll | 25 - test/Integer/a17.ll.out | 20 - test/Integer/a31.ll | 25 - test/Integer/a31.ll.out | 20 - test/Integer/a33.ll | 26 - test/Integer/a33.ll.out | 20 - test/Integer/a63.ll | 25 - test/Integer/a63.ll.out | 20 - test/Integer/a7.ll | 31 - test/Integer/a7.ll.out | 25 - test/Integer/a9.ll | 25 - test/Integer/a9.ll.out | 19 - test/LLVMC/Alias.td | 24 + test/LLVMC/AppendCmdHook.td | 4 +- test/LLVMC/EmptyCompilationGraph.td | 2 +- test/LLVMC/EnvParentheses.td | 4 +- test/LLVMC/ExternOptions.td | 26 - test/LLVMC/ForwardAs.td | 6 +- test/LLVMC/ForwardTransformedValue.td | 12 +- test/LLVMC/ForwardValue.td | 12 +- test/LLVMC/HookWithArguments.td | 4 +- test/LLVMC/HookWithInFile.td | 4 +- test/LLVMC/Init.td | 4 +- test/LLVMC/LanguageMap.td | 29 + test/LLVMC/MultiValuedOption.td | 6 +- test/LLVMC/MultipleCompilationGraphs.td | 2 +- test/LLVMC/MultiplePluginPriorities.td | 17 - test/LLVMC/NoActions.td | 4 +- test/LLVMC/NoCompilationGraph.td | 2 +- test/LLVMC/OneOrMore.td | 4 +- test/LLVMC/OptionPreprocessor.td | 4 +- test/LLVMC/OutputSuffixHook.td | 8 +- test/LLVMC/TestWarnings.td | 2 +- test/Linker/metadata-a.ll | 15 + test/Linker/metadata-b.ll | 9 + test/MC/AsmParser/ARM/arm_instructions.s | 8 + test/MC/AsmParser/ELF/dg.exp | 6 + test/MC/AsmParser/ELF/directive_previous.s | 13 + test/MC/AsmParser/ELF/directive_section.s | 23 + .../AsmParser/X86/x86_32-avx-clmul-encoding.s | 42 + test/MC/AsmParser/X86/x86_32-avx-encoding.s | 3241 ++++++++++++++++ test/MC/AsmParser/X86/x86_32-encoding.s | 2889 +------------- test/MC/AsmParser/X86/x86_32-fma3-encoding.s | 674 ++++ test/MC/AsmParser/X86/x86_32-new-encoder.s | 8 + .../AsmParser/X86/x86_64-avx-clmul-encoding.s | 42 + test/MC/AsmParser/X86/x86_64-avx-encoding.s | 3318 +++++++++++++++++ test/MC/AsmParser/X86/x86_64-encoding.s | 2892 +------------- test/MC/AsmParser/X86/x86_64-fma3-encoding.s | 674 ++++ test/MC/AsmParser/X86/x86_64-new-encoder.s | 13 +- .../MC/AsmParser/X86/x86_instruction_errors.s | 5 + test/MC/AsmParser/X86/x86_instructions.s | 26 +- test/MC/AsmParser/X86/x86_operands.s | 2 - test/MC/AsmParser/dg.exp | 5 +- test/MC/AsmParser/directive_abort.s | 6 +- test/MC/AsmParser/directive_elf_size.s | 8 + test/MC/AsmParser/directive_values.s | 17 + test/MC/AsmParser/dollars-in-identifiers.s | 7 + .../MC/AsmParser/macro-def-in-instantiation.s | 13 + test/MC/AsmParser/macros-parsing.s | 23 + test/MC/AsmParser/macros.s | 39 + test/MC/COFF/basic-coff.ll | 136 + test/MC/COFF/dg.exp | 5 + test/MC/COFF/switch-relocations.ll | 34 + test/MC/COFF/symbol-fragment-offset.ll | 182 + test/MC/Disassembler/arm-tests.txt | 34 + test/MC/Disassembler/neon-tests.txt | 3 + test/MC/Disassembler/thumb-tests.txt | 12 + test/MC/ELF/bss.ll | 8 + test/MC/ELF/dg.exp | 5 + test/Makefile | 39 +- test/Other/close-stderr.ll | 9 + test/Other/constant-fold-gep.ll | 42 - test/Other/inline-asm-newline-terminator.ll | 1 - test/Other/lint.ll | 4 +- test/Scripts/coff-dump.py | 566 +++ test/Scripts/coff-dump.py.bat | 4 + test/TableGen/FieldAccess.td | 14 + test/TableGen/ListManip.td | 10 + test/TestRunner.sh | 37 +- test/Transforms/ABCD/basic.ll | 27 - test/Transforms/ConstProp/constant-expr.ll | 4 +- test/Transforms/ConstantMerge/dont-merge.ll | 14 + .../2010-09-02-Trunc.ll | 25 + .../CorrelatedValuePropagation/basic.ll | 83 + .../CorrelatedValuePropagation/dg.exp | 3 + .../GVN/2009-07-13-MemDepSortFail.ll | 2 +- .../GlobalOpt/2008-07-17-addrspace.ll | 2 +- test/Transforms/GlobalOpt/crash.ll | 15 + .../IPConstantProp/2009-09-24-byval-ptr.ll | 4 +- .../2003-12-10-IndVarDeadCode.ll | 25 - .../IndVarSimplify/2009-05-24-useafterfree.ll | 2 +- test/Transforms/IndVarSimplify/crash.ll | 36 + .../IndVarSimplify/loop_evaluate10.ll | 2 +- test/Transforms/IndVarSimplify/uglygep.ll | 40 + test/Transforms/InstCombine/align-addr.ll | 33 +- test/Transforms/InstCombine/align-inc.ll | 12 - test/Transforms/InstCombine/bit-checks.ll | 11 + .../InstCombine/bitcast-scalar-to-vector.ll | 14 - test/Transforms/InstCombine/bitcast.ll | 105 + test/Transforms/InstCombine/intrinsics.ll | 34 +- test/Transforms/InstCombine/phi.ll | 21 + test/Transforms/InstCombine/shift-simplify.ll | 42 - .../InstCombine/shift-trunc-shift.ll | 10 - test/Transforms/InstCombine/shift.ll | 102 +- test/Transforms/InstCombine/sqrt.ll | 32 + test/Transforms/InstCombine/trunc-mask-ext.ll | 38 - test/Transforms/InstCombine/trunc.ll | 99 + .../InstCombine/urem-simplify-bug.ll | 2 +- .../JumpThreading/2010-08-26-and.ll | 162 + test/Transforms/JumpThreading/basic.ll | 68 +- test/Transforms/JumpThreading/crash.ll | 50 + test/Transforms/JumpThreading/lvi-load.ll | 49 + .../LCSSA/2006-06-03-IncorrectIDFPhis.ll | 4 +- test/Transforms/LICM/crash.ll | 61 + test/Transforms/LICM/hoisting.ll | 16 + test/Transforms/LICM/scalar_promote.ll | 59 +- test/Transforms/LICM/sinking.ll | 14 + test/Transforms/LoopRotate/phi-duplicate.ll | 22 +- .../2010-07-15-IncorrectDomFrontierUpdate.ll | 20 + .../LoopSimplify/indirectbr-backedge.ll | 35 + test/Transforms/LoopSimplify/preserve-scev.ll | 50 + test/Transforms/LoopStrengthReduce/pr3571.ll | 2 +- test/Transforms/LoopStrengthReduce/uglygep.ll | 1 - test/Transforms/LoopUnswitch/infinite-loop.ll | 53 + test/Transforms/LowerAtomic/atomic-load.ll | 40 + test/Transforms/LowerAtomic/atomic-swap.ll | 26 + test/Transforms/LowerAtomic/barrier.ll | 10 + test/Transforms/{SSI => LowerAtomic}/dg.exp | 0 .../MergeFunc/vectors-and-arrays.ll | 18 + .../PartialSpecialize/two-specializations.ll | 22 +- test/Transforms/SCCP/ipsccp-addr-taken.ll | 28 + test/Transforms/SSI/2009-07-09-Invoke.ll | 71 - .../SSI/2009-08-15-UnreachableBB.ll | 19 - test/Transforms/SSI/2009-08-17-CritEdge.ll | 15 - .../SSI/2009-08-19-UnreachableBB2.ll | 22 - test/Transforms/SSI/ssiphi.ll | 22 - test/Transforms/ScalarRepl/vector_promote.ll | 43 +- .../2008-04-27-MultipleReturnCrash.ll | 2 +- test/Transforms/SimplifyCFG/basictest.ll | 1 - test/Transforms/SimplifyCFG/indirectbr.ll | 64 + .../StripSymbols/2010-08-25-crash.ll | 19 + .../TailCallElim/accum_recursion.ll | 65 +- .../accum_recursion_constant_arg.ll | 20 - test/Transforms/TailCallElim/switch.ll | 34 - .../TailDup/2008-06-11-AvoidDupLoopHeader.ll | 2 +- test/Verifier/2010-08-07-PointerIntrinsic.ll | 21 + test/lit.cfg | 21 +- tools/CMakeLists.txt | 2 + tools/Makefile | 20 +- tools/bugpoint-passes/CMakeLists.txt | 3 + tools/bugpoint-passes/Makefile | 23 + .../TestPasses.cpp | 16 +- tools/bugpoint-passes/bugpoint.exports | 0 tools/bugpoint/BugDriver.cpp | 29 +- tools/bugpoint/BugDriver.h | 67 +- tools/bugpoint/CMakeLists.txt | 1 - tools/bugpoint/CrashDebugger.cpp | 73 +- tools/bugpoint/ExecutionDriver.cpp | 24 +- tools/bugpoint/ExtractFunction.cpp | 91 +- tools/bugpoint/FindBugs.cpp | 8 +- tools/bugpoint/Miscompilation.cpp | 157 +- tools/bugpoint/OptimizerDriver.cpp | 113 +- tools/bugpoint/ToolRunner.cpp | 12 +- tools/bugpoint/bugpoint.cpp | 26 +- tools/edis/CMakeLists.txt | 14 +- tools/edis/EDInfo.td | 1 - tools/edis/EDMain.cpp | 160 +- tools/edis/Makefile | 30 +- tools/gold/README.txt | 4 +- tools/gold/gold-plugin.cpp | 40 +- tools/llc/llc.cpp | 151 +- tools/lli/lli.cpp | 3 +- tools/llvm-as/llvm-as.cpp | 18 +- tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp | 17 +- tools/llvm-config/CMakeLists.txt | 2 +- tools/llvm-diff/CMakeLists.txt | 6 + tools/llvm-diff/DifferenceEngine.cpp | 676 ++++ tools/llvm-diff/DifferenceEngine.h | 179 + .../plugins/Plugin => llvm-diff}/Makefile | 16 +- tools/llvm-diff/llvm-diff.cpp | 331 ++ tools/llvm-dis/llvm-dis.cpp | 47 +- tools/llvm-extract/llvm-extract.cpp | 38 +- tools/llvm-ld/llvm-ld.cpp | 38 +- tools/llvm-link/llvm-link.cpp | 19 +- tools/llvm-mc/CMakeLists.txt | 3 +- tools/llvm-mc/Disassembler.cpp | 182 +- tools/llvm-mc/Disassembler.h | 7 +- tools/llvm-mc/Makefile | 4 +- tools/llvm-mc/llvm-mc.cpp | 177 +- tools/llvm-nm/llvm-nm.cpp | 15 +- tools/llvm-prof/llvm-prof.cpp | 15 +- tools/llvm-shlib/Makefile | 53 +- tools/llvmc/CMakeLists.txt | 2 +- tools/llvmc/Makefile | 8 +- tools/llvmc/doc/LLVMC-Reference.rst | 9 +- tools/llvmc/example/Hello/Hello.cpp | 33 - tools/llvmc/example/Simple/PluginMain.cpp | 1 - tools/llvmc/example/Skeleton/Makefile | 24 - tools/llvmc/example/Skeleton/driver/Makefile | 13 - tools/llvmc/example/Skeleton/plugins/Makefile | 18 - .../Skeleton/plugins/Plugin/PluginMain.cpp | 1 - tools/llvmc/example/mcc16/Makefile | 18 - tools/llvmc/example/mcc16/driver/Makefile | 13 - tools/llvmc/example/mcc16/plugins/Makefile | 18 - tools/llvmc/examples/Hello/Hello.cpp | 29 + .../{example => examples}/Hello/Makefile | 4 +- .../{example/Simple => examples}/Makefile | 7 +- .../Clang => examples/Simple}/Makefile | 6 +- tools/llvmc/examples/Simple/Simple.cpp | 2 + .../{example => examples}/Simple/Simple.td | 24 +- .../Skeleton/AutoGenerated.td} | 4 +- tools/llvmc/examples/Skeleton/Hooks.cpp | 12 + .../{driver => examples/Skeleton}/Main.cpp | 3 +- tools/llvmc/examples/Skeleton/Makefile | 20 + .../{example => examples}/Skeleton/README | 2 +- .../mcc16/Hooks.cpp} | 35 +- .../mcc16/driver => examples/mcc16}/Main.cpp | 17 +- .../{plugins/Base => examples/mcc16}/Makefile | 6 +- .../PIC16Base.td => examples/mcc16/PIC16.td} | 50 +- .../llvmc/{example => examples}/mcc16/README | 2 +- tools/llvmc/plugins/Base/PluginMain.cpp | 1 - tools/llvmc/plugins/Clang/PluginMain.cpp | 1 - tools/llvmc/plugins/Makefile | 18 - tools/llvmc/src/AutoGenerated.td | 17 + tools/llvmc/{plugins/Base => src}/Base.td.in | 109 +- tools/llvmc/{plugins/Clang => src}/Clang.td | 68 +- tools/llvmc/{plugins/Base => src}/Hooks.cpp | 0 .../{example/Skeleton/driver => src}/Main.cpp | 4 +- tools/llvmc/{driver => src}/Makefile | 5 +- tools/lto/LTOCodeGenerator.cpp | 50 +- tools/lto/LTOCodeGenerator.h | 6 +- tools/lto/LTOModule.cpp | 869 +++-- tools/lto/LTOModule.h | 1 + tools/lto/Makefile | 13 +- tools/lto/lto.cpp | 28 +- tools/lto/lto.exports | 3 + tools/opt/AnalysisWrappers.cpp | 22 +- tools/opt/GraphPrinters.cpp | 38 +- tools/opt/PrintSCC.cpp | 40 +- tools/opt/opt.cpp | 137 +- unittests/ADT/SmallVectorTest.cpp | 4 +- unittests/ADT/StringRefTest.cpp | 9 + unittests/ADT/TripleTest.cpp | 117 +- .../PIC16Base => unittests/Analysis}/Makefile | 14 +- unittests/Analysis/ScalarEvolutionTest.cpp | 82 + unittests/ExecutionEngine/JIT/JITTest.cpp | 27 - unittests/Makefile | 2 +- unittests/Makefile.unittest | 4 +- unittests/Support/Casting.cpp | 154 + unittests/Support/ConstantRangeTest.cpp | 69 +- unittests/Support/ValueHandleTest.cpp | 1 - unittests/VMCore/DerivedTypesTest.cpp | 57 +- unittests/VMCore/InstructionsTest.cpp | 4 +- unittests/VMCore/MetadataTest.cpp | 7 +- unittests/VMCore/PassManagerTest.cpp | 12 +- utils/FileCheck/FileCheck.cpp | 160 +- utils/FileUpdate/FileUpdate.cpp | 24 +- utils/Makefile | 7 +- utils/RegressionFinder.pl | 186 - utils/TableGen/ARMDecoderEmitter.cpp | 61 +- utils/TableGen/AsmMatcherEmitter.cpp | 164 +- utils/TableGen/AsmWriterEmitter.cpp | 2 +- utils/TableGen/CallingConvEmitter.cpp | 2 + utils/TableGen/ClangAttrEmitter.cpp | 582 ++- utils/TableGen/ClangAttrEmitter.h | 39 + utils/TableGen/CodeGenDAGPatterns.cpp | 4 +- utils/TableGen/CodeGenInstruction.cpp | 1 + utils/TableGen/CodeGenInstruction.h | 1 + utils/TableGen/CodeGenIntrinsics.h | 2 +- utils/TableGen/CodeGenRegisters.h | 32 + utils/TableGen/CodeGenTarget.cpp | 10 +- utils/TableGen/DAGISelEmitter.cpp | 48 - utils/TableGen/DAGISelEmitter.h | 2 - utils/TableGen/DAGISelMatcherEmitter.cpp | 2 +- utils/TableGen/DAGISelMatcherGen.cpp | 7 +- utils/TableGen/EDEmitter.cpp | 59 +- utils/TableGen/EDEmitter.h | 3 - utils/TableGen/FastISelEmitter.cpp | 24 +- utils/TableGen/InstrInfoEmitter.cpp | 1 + utils/TableGen/IntrinsicEmitter.cpp | 4 +- utils/TableGen/LLVMCConfigurationEmitter.cpp | 656 ++-- utils/TableGen/NeonEmitter.cpp | 11 +- utils/TableGen/Record.cpp | 28 +- utils/TableGen/Record.h | 12 +- utils/TableGen/RegisterInfoEmitter.cpp | 30 +- utils/TableGen/TableGen.cpp | 98 +- utils/buildit/GNUmakefile | 16 +- utils/buildit/build_llvm | 33 +- utils/lit/lit/ExampleTests/lit.cfg | 3 + .../lit/ExampleTests/required-and-missing.c | 4 + .../lit/ExampleTests/required-and-present.c | 2 + utils/lit/lit/TestFormats.py | 7 + utils/lit/lit/TestRunner.py | 86 +- utils/lit/lit/TestingConfig.py | 9 +- utils/lit/lit/lit.py | 5 +- utils/llvm-lit/Makefile | 21 + utils/llvm-lit/llvm-lit.in | 21 + utils/llvm.grm | 4 + utils/llvmdo | 4 - utils/mkpatch | 37 - utils/userloc.pl | 216 -- utils/valgrind/i386-pc-linux-gnu.supp | 34 + utils/valgrind/x86_64-pc-linux-gnu.supp | 43 +- utils/vim/llvm.vim | 10 +- utils/vim/vimrc | 129 +- 1399 files changed, 60896 insertions(+), 33583 deletions(-) create mode 100644 cmake/modules/CMakeLists.txt create mode 100644 cmake/modules/ChooseMSVCCRT.cmake create mode 100644 cmake/modules/LLVM.cmake create mode 100644 cmake/modules/VersionFromVCS.cmake create mode 100644 docs/CommandGuide/llvm-diff.pod create mode 100644 include/llvm/ADT/NullablePtr.h create mode 100644 include/llvm/Analysis/RegionInfo.h create mode 100644 include/llvm/Analysis/RegionIterator.h create mode 100644 include/llvm/Analysis/RegionPrinter.h rename include/llvm/Assembly/{AsmAnnotationWriter.h => AssemblyAnnotationWriter.h} (73%) create mode 100644 include/llvm/CompilerDriver/AutoGenerated.h delete mode 100644 include/llvm/CompilerDriver/ForceLinkage.h delete mode 100644 include/llvm/CompilerDriver/ForceLinkageMacros.h create mode 100644 include/llvm/CompilerDriver/Main.h delete mode 100644 include/llvm/CompilerDriver/Plugin.h create mode 100644 include/llvm/Config/llvm-config.h.cmake create mode 100644 include/llvm/Config/llvm-config.h.in create mode 100644 include/llvm/MC/ELFObjectWriter.h create mode 100644 include/llvm/MC/MCDwarf.h create mode 100644 include/llvm/MC/MCELFSymbolFlags.h delete mode 100644 include/llvm/MC/MCParser/AsmParser.h create mode 100644 include/llvm/PassRegistry.h create mode 100644 include/llvm/Support/CrashRecoveryContext.h delete mode 100644 include/llvm/Support/SlowOperationInformer.h delete mode 100644 include/llvm/Transforms/Utils/SSI.h rename {lib => include/llvm}/Transforms/Utils/ValueMapper.h (65%) create mode 100644 lib/Analysis/RegionInfo.cpp create mode 100644 lib/Analysis/RegionPrinter.cpp create mode 100644 lib/Analysis/TypeBasedAliasAnalysis.cpp create mode 100644 lib/CodeGen/LocalStackSlotAllocation.cpp delete mode 100644 lib/CodeGen/OptimizeExts.cpp create mode 100644 lib/CodeGen/PeepholeOptimizer.cpp create mode 100644 lib/CodeGen/RenderMachineFunction.cpp create mode 100644 lib/CodeGen/RenderMachineFunction.h create mode 100644 lib/CodeGen/SplitKit.cpp create mode 100644 lib/CodeGen/SplitKit.h create mode 100644 lib/CodeGen/Splitter.cpp create mode 100644 lib/CodeGen/Splitter.h delete mode 100644 lib/CompilerDriver/Plugin.cpp create mode 100644 lib/MC/ELFObjectWriter.cpp create mode 100644 lib/MC/MCDisassembler/CMakeLists.txt rename {tools/edis => lib/MC/MCDisassembler}/EDDisassembler.cpp (89%) rename {tools/edis => lib/MC/MCDisassembler}/EDDisassembler.h (91%) create mode 100644 lib/MC/MCDisassembler/EDInfo.h rename {tools/edis => lib/MC/MCDisassembler}/EDInst.cpp (100%) rename {tools/edis => lib/MC/MCDisassembler}/EDInst.h (95%) rename {tools/edis => lib/MC/MCDisassembler}/EDOperand.cpp (98%) rename {tools/edis => lib/MC/MCDisassembler}/EDOperand.h (88%) rename {tools/edis => lib/MC/MCDisassembler}/EDToken.cpp (98%) rename {tools/edis => lib/MC/MCDisassembler}/EDToken.h (97%) create mode 100644 lib/MC/MCDisassembler/Makefile create mode 100644 lib/MC/MCDwarf.cpp create mode 100644 lib/MC/MCELFStreamer.cpp create mode 100644 lib/Support/CrashRecoveryContext.cpp delete mode 100644 lib/Support/SlowOperationInformer.cpp rename lib/Target/ARM/{AsmPrinter => }/ARMAsmPrinter.cpp (94%) create mode 100644 lib/Target/ARM/ARMFastISel.cpp create mode 100644 lib/Target/ARM/ARMGlobalMerge.cpp rename lib/Target/ARM/{AsmPrinter => }/ARMMCInstLower.cpp (100%) rename lib/Target/ARM/{AsmPrinter => }/ARMMCInstLower.h (100%) delete mode 100644 lib/Target/MSIL/CMakeLists.txt delete mode 100644 lib/Target/MSIL/MSILWriter.cpp delete mode 100644 lib/Target/MSIL/MSILWriter.h delete mode 100644 lib/Target/MSIL/Makefile delete mode 100644 lib/Target/MSIL/README.TXT delete mode 100644 lib/Target/MSIL/TargetInfo/CMakeLists.txt delete mode 100644 lib/Target/MSIL/TargetInfo/MSILTargetInfo.cpp delete mode 100644 lib/Target/MSIL/TargetInfo/Makefile create mode 100644 lib/Target/X86/AsmPrinter/X86InstComments.cpp create mode 100644 lib/Target/X86/AsmPrinter/X86InstComments.h rename lib/Target/X86/{AsmPrinter => }/X86AsmPrinter.cpp (93%) rename lib/Target/X86/{AsmPrinter => }/X86AsmPrinter.h (96%) delete mode 100644 lib/Target/X86/X86FloatingPointRegKill.cpp create mode 100644 lib/Target/X86/X86InstrFMA.td rename lib/Target/X86/{AsmPrinter => }/X86MCInstLower.cpp (86%) rename lib/Target/X86/{AsmPrinter => }/X86MCInstLower.h (82%) create mode 100644 lib/Target/X86/X86ShuffleDecode.h delete mode 100644 lib/Transforms/Scalar/ABCD.cpp create mode 100644 lib/Transforms/Scalar/CorrelatedValuePropagation.cpp create mode 100644 lib/Transforms/Scalar/LowerAtomic.cpp delete mode 100644 lib/Transforms/Utils/SSI.cpp create mode 100644 lib/VMCore/PassRegistry.cpp rename runtime/libprofile/{exported_symbols.lst => libprofile.exports} (100%) create mode 100644 test/Analysis/BasicAA/getmodrefinfo-cs-cs.ll create mode 100644 test/Analysis/RegionInfo/20100809_bb_not_in_domtree.ll create mode 100644 test/Analysis/RegionInfo/block_sort.ll create mode 100644 test/Analysis/RegionInfo/cond_loop.ll create mode 100644 test/Analysis/RegionInfo/condition_complicated.ll create mode 100644 test/Analysis/RegionInfo/condition_complicated_2.ll create mode 100644 test/Analysis/RegionInfo/condition_forward_edge.ll create mode 100644 test/Analysis/RegionInfo/condition_same_exit.ll create mode 100644 test/Analysis/RegionInfo/condition_simple.ll rename test/{Transforms/ABCD => Analysis/RegionInfo}/dg.exp (100%) create mode 100644 test/Analysis/RegionInfo/exit_in_condition.ll create mode 100644 test/Analysis/RegionInfo/infinite_loop.ll create mode 100644 test/Analysis/RegionInfo/infinite_loop_2.ll create mode 100644 test/Analysis/RegionInfo/infinite_loop_3.ll create mode 100644 test/Analysis/RegionInfo/infinite_loop_4.ll create mode 100644 test/Analysis/RegionInfo/loop_with_condition.ll create mode 100644 test/Analysis/RegionInfo/loops_1.ll create mode 100644 test/Analysis/RegionInfo/loops_2.ll create mode 100644 test/Analysis/RegionInfo/mix_1.ll create mode 100644 test/Analysis/RegionInfo/multiple_exiting_edge.ll create mode 100644 test/Analysis/RegionInfo/nested_loops.ll create mode 100644 test/Analysis/RegionInfo/next.ll create mode 100644 test/Analysis/RegionInfo/paper.ll create mode 100644 test/Analysis/RegionInfo/two_loops_same_header.ll delete mode 100644 test/Assembler/2010-01-06-UnionType.ll create mode 100644 test/Assembler/align-inst-alloca.ll create mode 100644 test/Assembler/align-inst-load.ll create mode 100644 test/Assembler/align-inst-store.ll create mode 100644 test/Assembler/align-inst.ll create mode 100644 test/Assembler/comment.ll create mode 100644 test/Bitcode/AutoUpgradeGlobals.ll create mode 100644 test/Bitcode/AutoUpgradeGlobals.ll.bc create mode 100644 test/Bitcode/neon-intrinsics.ll create mode 100644 test/Bitcode/neon-intrinsics.ll.bc create mode 100644 test/BugPoint/metadata.ll create mode 100644 test/CodeGen/ARM/2010-07-26-GlobalMerge.ll create mode 100644 test/CodeGen/ARM/2010-08-04-EHCrash.ll create mode 100644 test/CodeGen/ARM/bfi.ll create mode 100644 test/CodeGen/ARM/code-placement.ll create mode 100644 test/CodeGen/ARM/fast-isel.ll create mode 100644 test/CodeGen/Alpha/2010-08-01-mulreduce64.ll create mode 100644 test/CodeGen/CellSPU/arg_ret.ll create mode 100644 test/CodeGen/CellSPU/v2f32.ll create mode 100644 test/CodeGen/CellSPU/v2i32.ll create mode 100644 test/CodeGen/Generic/2010-07-27-DAGCombineCrash.ll create mode 100644 test/CodeGen/Mips/2010-07-20-Select.ll create mode 100644 test/CodeGen/Mips/2010-07-20-Switch.ll delete mode 100644 test/CodeGen/PowerPC/2008-01-25-EmptyFunction.ll create mode 100644 test/CodeGen/PowerPC/empty-functions.ll create mode 100644 test/CodeGen/Thumb/2010-07-15-debugOrdering.ll create mode 100644 test/CodeGen/Thumb/barrier.ll create mode 100644 test/CodeGen/Thumb2/2010-08-10-VarSizedAllocaBug.ll create mode 100644 test/CodeGen/Thumb2/bfi.ll create mode 100644 test/CodeGen/Thumb2/cortex-fp.ll create mode 100644 test/CodeGen/Thumb2/machine-licm-vdup.ll create mode 100644 test/CodeGen/Thumb2/thumb2-badreg-operands.ll create mode 100644 test/CodeGen/Thumb2/thumb2-barrier.ll delete mode 100644 test/CodeGen/X86/2007-06-14-branchfold.ll delete mode 100644 test/CodeGen/X86/2008-01-25-EmptyFunction.ll rename test/{Transforms/LoopStrengthReduce => CodeGen/X86}/2008-08-06-CmpStride.ll (100%) rename test/{Transforms/LoopStrengthReduce => CodeGen/X86}/2009-02-09-ivs-different-sizes.ll (100%) rename test/{DebugInfo => CodeGen/X86}/2010-01-18-DbgValue.ll (93%) rename test/{DebugInfo => CodeGen/X86}/2010-02-01-DbgValueCrash.ll (98%) rename test/{DebugInfo => CodeGen/X86}/2010-05-25-DotDebugLoc.ll (99%) rename test/{DebugInfo => CodeGen/X86}/2010-05-28-Crash.ll (100%) rename test/{DebugInfo => CodeGen/X86}/2010-06-01-DeadArg-DbgInfo.ll (100%) create mode 100644 test/CodeGen/X86/2010-07-11-FPStackLoneUse.ll create mode 100644 test/CodeGen/X86/2010-07-15-Crash.ll create mode 100644 test/CodeGen/X86/2010-07-29-SetccSimplify.ll create mode 100644 test/CodeGen/X86/2010-08-04-MaskedSignedCompare.ll create mode 100644 test/CodeGen/X86/2010-08-04-MingWCrash.ll create mode 100644 test/CodeGen/X86/2010-08-10-DbgConstant.ll create mode 100644 test/CodeGen/X86/2010-09-01-RemoveCopyByCommutingDef.ll create mode 100644 test/CodeGen/X86/MachineSink-PHIUse.ll create mode 100644 test/CodeGen/X86/avx-128.ll create mode 100644 test/CodeGen/X86/avx-256.ll create mode 100644 test/CodeGen/X86/avx-intrinsics-x86.ll create mode 100644 test/CodeGen/X86/avx-intrinsics-x86_64.ll create mode 100644 test/CodeGen/X86/barrier-sse.ll create mode 100644 test/CodeGen/X86/barrier.ll rename test/{Transforms/LoopStrengthReduce => CodeGen/X86}/change-compare-stride-trickiness-0.ll (100%) rename test/{Transforms/LoopStrengthReduce => CodeGen/X86}/change-compare-stride-trickiness-1.ll (100%) rename test/{Transforms/LoopStrengthReduce => CodeGen/X86}/change-compare-stride-trickiness-2.ll (100%) create mode 100644 test/CodeGen/X86/empty-functions.ll create mode 100644 test/CodeGen/X86/fast-isel-atomic.ll create mode 100644 test/CodeGen/X86/fast-isel-cmp-branch.ll create mode 100644 test/CodeGen/X86/force-align-stack.ll rename test/{Transforms/LoopStrengthReduce => CodeGen/X86}/insert-positions.ll (100%) create mode 100644 test/CodeGen/X86/int-intrinsic.ll create mode 100644 test/CodeGen/X86/lock-inst-encoding.ll create mode 100644 test/CodeGen/X86/lsr-interesting-step.ll create mode 100644 test/CodeGen/X86/lsr-normalization.ll create mode 100644 test/CodeGen/X86/lsr-static-addr.ll delete mode 100644 test/CodeGen/X86/narrow_op-2.ll create mode 100644 test/CodeGen/X86/pr7882.ll create mode 100644 test/CodeGen/X86/shl-anyext.ll create mode 100644 test/CodeGen/X86/sse1.ll delete mode 100644 test/CodeGen/X86/stack-color-with-reg.ll create mode 100644 test/CodeGen/X86/vec_shift4.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-10.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-3.ll create mode 100644 test/CodeGen/X86/vec_shuffle-37.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-4.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-5.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-6.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-7.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-8.ll delete mode 100644 test/CodeGen/X86/vec_shuffle-9.ll create mode 100644 test/CodeGen/X86/win_chkstk.ll create mode 100644 test/DebugInfo/2010-07-19-Crash.ll create mode 100644 test/DebugInfo/2010-08-04-StackVariable.ll delete mode 100644 test/Feature/unions.ll create mode 100644 test/FrontendC++/2010-07-19-nowarn.cpp create mode 100644 test/FrontendC++/2010-07-23-DeclLoc.cpp create mode 100644 test/FrontendC++/2010-08-31-ByValArg.cpp create mode 100644 test/FrontendC/2010-07-27-MinNoFoldConst.c create mode 100644 test/FrontendC/2010-08-12-asm-aggr-arg.c create mode 100644 test/FrontendC/asm-reg-var-local.c create mode 100644 test/FrontendC/misaligned-param.c create mode 100644 test/FrontendC/vla-2.c create mode 100644 test/FrontendObjC++/2010-08-02-NonPODObjectValue.mm create mode 100644 test/FrontendObjC++/2010-08-04-Template.mm create mode 100644 test/FrontendObjC++/2010-08-06-X.Y-syntax.mm delete mode 100644 test/Integer/a15.ll delete mode 100644 test/Integer/a15.ll.out delete mode 100644 test/Integer/a17.ll delete mode 100644 test/Integer/a17.ll.out delete mode 100644 test/Integer/a31.ll delete mode 100644 test/Integer/a31.ll.out delete mode 100644 test/Integer/a33.ll delete mode 100644 test/Integer/a33.ll.out delete mode 100644 test/Integer/a63.ll delete mode 100644 test/Integer/a63.ll.out delete mode 100644 test/Integer/a7.ll delete mode 100644 test/Integer/a7.ll.out delete mode 100644 test/Integer/a9.ll delete mode 100644 test/Integer/a9.ll.out create mode 100644 test/LLVMC/Alias.td delete mode 100644 test/LLVMC/ExternOptions.td create mode 100644 test/LLVMC/LanguageMap.td delete mode 100644 test/LLVMC/MultiplePluginPriorities.td create mode 100644 test/Linker/metadata-a.ll create mode 100644 test/Linker/metadata-b.ll create mode 100644 test/MC/AsmParser/ARM/arm_instructions.s create mode 100644 test/MC/AsmParser/ELF/dg.exp create mode 100644 test/MC/AsmParser/ELF/directive_previous.s create mode 100644 test/MC/AsmParser/ELF/directive_section.s create mode 100644 test/MC/AsmParser/X86/x86_32-avx-clmul-encoding.s create mode 100644 test/MC/AsmParser/X86/x86_32-avx-encoding.s create mode 100644 test/MC/AsmParser/X86/x86_32-fma3-encoding.s create mode 100644 test/MC/AsmParser/X86/x86_64-avx-clmul-encoding.s create mode 100644 test/MC/AsmParser/X86/x86_64-avx-encoding.s create mode 100644 test/MC/AsmParser/X86/x86_64-fma3-encoding.s create mode 100644 test/MC/AsmParser/X86/x86_instruction_errors.s create mode 100644 test/MC/AsmParser/directive_elf_size.s create mode 100644 test/MC/AsmParser/dollars-in-identifiers.s create mode 100644 test/MC/AsmParser/macro-def-in-instantiation.s create mode 100644 test/MC/AsmParser/macros-parsing.s create mode 100644 test/MC/AsmParser/macros.s create mode 100644 test/MC/COFF/basic-coff.ll create mode 100644 test/MC/COFF/dg.exp create mode 100644 test/MC/COFF/switch-relocations.ll create mode 100644 test/MC/COFF/symbol-fragment-offset.ll create mode 100644 test/MC/ELF/bss.ll create mode 100644 test/MC/ELF/dg.exp create mode 100644 test/Other/close-stderr.ll create mode 100755 test/Scripts/coff-dump.py create mode 100644 test/Scripts/coff-dump.py.bat create mode 100644 test/TableGen/FieldAccess.td create mode 100644 test/TableGen/ListManip.td delete mode 100644 test/Transforms/ABCD/basic.ll create mode 100644 test/Transforms/CorrelatedValuePropagation/2010-09-02-Trunc.ll create mode 100644 test/Transforms/CorrelatedValuePropagation/basic.ll create mode 100644 test/Transforms/CorrelatedValuePropagation/dg.exp delete mode 100644 test/Transforms/IndVarSimplify/2003-12-10-IndVarDeadCode.ll create mode 100644 test/Transforms/IndVarSimplify/uglygep.ll delete mode 100644 test/Transforms/InstCombine/align-inc.ll delete mode 100644 test/Transforms/InstCombine/bitcast-scalar-to-vector.ll create mode 100644 test/Transforms/InstCombine/bitcast.ll delete mode 100644 test/Transforms/InstCombine/shift-simplify.ll delete mode 100644 test/Transforms/InstCombine/shift-trunc-shift.ll create mode 100644 test/Transforms/InstCombine/sqrt.ll delete mode 100644 test/Transforms/InstCombine/trunc-mask-ext.ll create mode 100644 test/Transforms/InstCombine/trunc.ll create mode 100644 test/Transforms/JumpThreading/2010-08-26-and.ll create mode 100644 test/Transforms/JumpThreading/lvi-load.ll create mode 100644 test/Transforms/LICM/crash.ll create mode 100644 test/Transforms/LoopSimplify/2010-07-15-IncorrectDomFrontierUpdate.ll create mode 100644 test/Transforms/LoopSimplify/indirectbr-backedge.ll create mode 100644 test/Transforms/LoopSimplify/preserve-scev.ll create mode 100644 test/Transforms/LoopUnswitch/infinite-loop.ll create mode 100644 test/Transforms/LowerAtomic/atomic-load.ll create mode 100644 test/Transforms/LowerAtomic/atomic-swap.ll create mode 100644 test/Transforms/LowerAtomic/barrier.ll rename test/Transforms/{SSI => LowerAtomic}/dg.exp (100%) create mode 100644 test/Transforms/MergeFunc/vectors-and-arrays.ll create mode 100644 test/Transforms/SCCP/ipsccp-addr-taken.ll delete mode 100644 test/Transforms/SSI/2009-07-09-Invoke.ll delete mode 100644 test/Transforms/SSI/2009-08-15-UnreachableBB.ll delete mode 100644 test/Transforms/SSI/2009-08-17-CritEdge.ll delete mode 100644 test/Transforms/SSI/2009-08-19-UnreachableBB2.ll delete mode 100644 test/Transforms/SSI/ssiphi.ll create mode 100644 test/Transforms/SimplifyCFG/indirectbr.ll create mode 100644 test/Transforms/StripSymbols/2010-08-25-crash.ll delete mode 100644 test/Transforms/TailCallElim/accum_recursion_constant_arg.ll delete mode 100644 test/Transforms/TailCallElim/switch.ll create mode 100644 test/Verifier/2010-08-07-PointerIntrinsic.ll create mode 100644 tools/bugpoint-passes/CMakeLists.txt create mode 100644 tools/bugpoint-passes/Makefile rename tools/{bugpoint => bugpoint-passes}/TestPasses.cpp (91%) create mode 100644 tools/bugpoint-passes/bugpoint.exports delete mode 100644 tools/edis/EDInfo.td create mode 100644 tools/llvm-diff/CMakeLists.txt create mode 100644 tools/llvm-diff/DifferenceEngine.cpp create mode 100644 tools/llvm-diff/DifferenceEngine.h rename tools/{llvmc/example/Skeleton/plugins/Plugin => llvm-diff}/Makefile (58%) create mode 100644 tools/llvm-diff/llvm-diff.cpp delete mode 100644 tools/llvmc/example/Hello/Hello.cpp delete mode 100644 tools/llvmc/example/Simple/PluginMain.cpp delete mode 100644 tools/llvmc/example/Skeleton/Makefile delete mode 100644 tools/llvmc/example/Skeleton/driver/Makefile delete mode 100644 tools/llvmc/example/Skeleton/plugins/Makefile delete mode 100644 tools/llvmc/example/Skeleton/plugins/Plugin/PluginMain.cpp delete mode 100644 tools/llvmc/example/mcc16/Makefile delete mode 100644 tools/llvmc/example/mcc16/driver/Makefile delete mode 100644 tools/llvmc/example/mcc16/plugins/Makefile create mode 100644 tools/llvmc/examples/Hello/Hello.cpp rename tools/llvmc/{example => examples}/Hello/Makefile (78%) rename tools/llvmc/{example/Simple => examples}/Makefile (68%) rename tools/llvmc/{plugins/Clang => examples/Simple}/Makefile (73%) create mode 100644 tools/llvmc/examples/Simple/Simple.cpp rename tools/llvmc/{example => examples}/Simple/Simple.td (53%) rename tools/llvmc/{example/Skeleton/plugins/Plugin/Plugin.td => examples/Skeleton/AutoGenerated.td} (52%) create mode 100644 tools/llvmc/examples/Skeleton/Hooks.cpp rename tools/llvmc/{driver => examples/Skeleton}/Main.cpp (83%) create mode 100644 tools/llvmc/examples/Skeleton/Makefile rename tools/llvmc/{example => examples}/Skeleton/README (80%) rename tools/llvmc/{example/mcc16/plugins/PIC16Base/PluginMain.cpp => examples/mcc16/Hooks.cpp} (79%) rename tools/llvmc/{example/mcc16/driver => examples/mcc16}/Main.cpp (90%) rename tools/llvmc/{plugins/Base => examples/mcc16}/Makefile (73%) rename tools/llvmc/{example/mcc16/plugins/PIC16Base/PIC16Base.td => examples/mcc16/PIC16.td} (87%) rename tools/llvmc/{example => examples}/mcc16/README (96%) delete mode 100644 tools/llvmc/plugins/Base/PluginMain.cpp delete mode 100644 tools/llvmc/plugins/Clang/PluginMain.cpp delete mode 100644 tools/llvmc/plugins/Makefile create mode 100644 tools/llvmc/src/AutoGenerated.td rename tools/llvmc/{plugins/Base => src}/Base.td.in (84%) rename tools/llvmc/{plugins/Clang => src}/Clang.td (55%) rename tools/llvmc/{plugins/Base => src}/Hooks.cpp (100%) rename tools/llvmc/{example/Skeleton/driver => src}/Main.cpp (83%) rename tools/llvmc/{driver => src}/Makefile (72%) rename {tools/llvmc/example/mcc16/plugins/PIC16Base => unittests/Analysis}/Makefile (53%) create mode 100644 unittests/Analysis/ScalarEvolutionTest.cpp create mode 100644 unittests/Support/Casting.cpp delete mode 100755 utils/RegressionFinder.pl create mode 100644 utils/lit/lit/ExampleTests/required-and-missing.c create mode 100644 utils/lit/lit/ExampleTests/required-and-present.c create mode 100644 utils/llvm-lit/Makefile create mode 100644 utils/llvm-lit/llvm-lit.in delete mode 100755 utils/mkpatch delete mode 100755 utils/userloc.pl diff --git a/CMakeLists.txt b/CMakeLists.txt index d4f2221c9fd..a6099d17c56 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,10 +1,20 @@ # See docs/CMake.html for instructions about how to build LLVM with CMake. project(LLVM) -cmake_minimum_required(VERSION 2.6.1) +cmake_minimum_required(VERSION 2.8) + +# Add path for custom modules +set(CMAKE_MODULE_PATH + ${CMAKE_MODULE_PATH} + "${CMAKE_CURRENT_SOURCE_DIR}/cmake" + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules" + ) + +set(PACKAGE_VERSION "2.8") +include(VersionFromVCS) +add_version_info_from_vcs(PACKAGE_VERSION) set(PACKAGE_NAME llvm) -set(PACKAGE_VERSION 2.8svn) set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") set(PACKAGE_BUGREPORT "llvmbugs@cs.uiuc.edu") @@ -53,7 +63,6 @@ set(LLVM_ALL_TARGETS CppBackend Mips MBlaze - MSIL MSP430 PIC16 PowerPC @@ -124,13 +133,6 @@ configure_file( set(llvm_builded_incs_dir ${LLVM_BINARY_DIR}/include/llvm) -# Add path for custom modules -set(CMAKE_MODULE_PATH - ${CMAKE_MODULE_PATH} - "${LLVM_MAIN_SRC_DIR}/cmake" - "${LLVM_MAIN_SRC_DIR}/cmake/modules" - ) - include(AddLLVMDefinitions) if(WIN32) @@ -214,14 +216,8 @@ if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) if( MSVC ) - # List of valid CRTs for MSVC - set(MSVC_CRT - MD - MDd - MT - MTd) + include(ChooseMSVCCRT) - set(LLVM_USE_CRT "" CACHE STRING "Specify VC++ CRT to use for debug/release configurations.") add_llvm_definitions( -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS ) add_llvm_definitions( -D_SCL_SECURE_NO_WARNINGS -DCRT_NONSTDC_NO_WARNINGS ) add_llvm_definitions( -D_SCL_SECURE_NO_DEPRECATE ) @@ -231,15 +227,6 @@ if( MSVC ) # Suppress 'new behavior: elements of array 'array' will be default initialized' add_llvm_definitions( -wd4351 ) - if (NOT ${LLVM_USE_CRT} STREQUAL "") - list(FIND MSVC_CRT ${LLVM_USE_CRT} idx) - if (idx LESS 0) - message(FATAL_ERROR "Invalid value for LLVM_USE_CRT: ${LLVM_USE_CRT}. Valid options are one of: ${MSVC_CRT}") - endif (idx LESS 0) - add_llvm_definitions("/${LLVM_USE_CRT}") - message(STATUS "Using VC++ CRT: ${LLVM_USE_CRT}") - endif (NOT ${LLVM_USE_CRT} STREQUAL "") - # Enable warnings if (LLVM_ENABLE_WARNINGS) add_llvm_definitions( /W4 /Wall ) @@ -308,6 +295,7 @@ add_subdirectory(lib/Analysis) add_subdirectory(lib/Analysis/IPA) add_subdirectory(lib/MC) add_subdirectory(lib/MC/MCParser) +add_subdirectory(lib/MC/MCDisassembler) add_subdirectory(test) add_subdirectory(utils/FileCheck) @@ -372,6 +360,8 @@ add_subdirectory(tools) option(LLVM_BUILD_EXAMPLES "Build LLVM example programs." OFF) add_subdirectory(examples) +add_subdirectory(cmake/modules) + install(DIRECTORY include/ DESTINATION include FILES_MATCHING diff --git a/CREDITS.TXT b/CREDITS.TXT index e58b85fdbd9..aeecfe2e21e 100644 --- a/CREDITS.TXT +++ b/CREDITS.TXT @@ -134,6 +134,11 @@ N: Gabor Greif E: ggreif@gmail.com D: Improvements for space efficiency +N: James Grosbach +E: grosbach@apple.com +D: SjLj exception handling support +D: General fixes and improvements for the ARM back-end + N: Lang Hames E: lhames@gmail.com D: PBQP-based register allocator @@ -247,6 +252,12 @@ N: Scott Michel E: scottm@aero.org D: Added STI Cell SPU backend. +N: Takumi Nakamura +E: geek4civic@gmail.com +E: chapuni@hf.rim.or.jp +D: Cygwin and MinGW support. +S: Yokohama, Japan + N: Edward O'Callaghan E: eocallaghan@auroraux.org W: http://www.auroraux.org @@ -277,6 +288,11 @@ N: Sandeep Patel E: deeppatel1987@gmail.com D: ARM calling conventions rewrite, hard float support +N: Wesley Peck +E: peckw@wesleypeck.com +W: http://wesleypeck.com/ +D: MicroBlaze backend + N: Vladimir Prus W: http://vladimir_prus.blogspot.com E: ghost@cs.msu.su @@ -288,7 +304,10 @@ D: MSIL backend N: Duncan Sands E: baldrick@free.fr -D: Ada front-end, exception handling improvements +D: Ada support in llvm-gcc +D: Dragonegg plugin +D: Exception handling improvements +D: Type legalizer rewrite N: Ruchira Sasanka E: sasanka@uiuc.edu @@ -306,6 +325,10 @@ N: Anand Shukla E: ashukla@cs.uiuc.edu D: The `paths' pass +N: Michael J. Spencer +E: bigcheesegs@gmail.com +D: Shepherding Windows COFF support into MC. + N: Reid Spencer E: rspencer@reidspencer.com W: http://reidspencer.com/ @@ -329,14 +352,9 @@ E: xerxes@zafena.se D: Cmake dependency chain and various bug fixes N: Bill Wendling -E: isanbard@gmail.com +E: wendling@apple.com D: Bunches of stuff N: Bob Wilson E: bob.wilson@acm.org D: Advanced SIMD (NEON) support in the ARM backend - -N: Wesley Peck -E: peckw@wesleypeck.com -W: http://wesleypeck.com/ -D: MicroBlaze backend diff --git a/Makefile b/Makefile index d42f887b6b1..ae650b7f2d9 100644 --- a/Makefile +++ b/Makefile @@ -64,7 +64,8 @@ endif ifeq ($(MAKECMDGOALS),install-clang) DIRS := tools/clang/tools/driver tools/clang/lib/Headers \ - tools/clang/runtime tools/clang/docs + tools/clang/runtime tools/clang/docs \ + tools/lto OPTIONAL_DIRS := NO_INSTALL = 1 endif @@ -78,7 +79,8 @@ ifeq ($(MAKECMDGOALS),install-clang-c) endif ifeq ($(MAKECMDGOALS),clang-only) - DIRS := $(filter-out tools runtime docs unittests, $(DIRS)) tools/clang + DIRS := $(filter-out tools runtime docs unittests, $(DIRS)) \ + tools/clang tools/lto OPTIONAL_DIRS := endif @@ -110,7 +112,8 @@ cross-compile-build-tools: --host=$(BUILD_TRIPLE) --target=$(BUILD_TRIPLE); \ cd .. ; \ fi; \ - ($(MAKE) -C BuildTools \ + (unset SDKROOT; \ + $(MAKE) -C BuildTools \ BUILD_DIRS_ONLY=1 \ UNIVERSAL= \ ENABLE_OPTIMIZED=$(ENABLE_OPTIMIZED) \ @@ -167,7 +170,7 @@ FilesToConfig := \ include/llvm/Config/AsmParsers.def \ include/llvm/Config/Disassemblers.def \ include/llvm/System/DataTypes.h \ - tools/llvmc/plugins/Base/Base.td + tools/llvmc/src/Base.td FilesToConfigPATH := $(addprefix $(LLVM_OBJ_ROOT)/,$(FilesToConfig)) all-local:: $(FilesToConfigPATH) @@ -192,9 +195,6 @@ endif check-llvm2cpp: $(Verb)$(MAKE) check TESTSUITE=Feature RUNLLVM2CPP=1 -check-one: - $(Verb)$(MAKE) -C test check-one TESTONE=$(TESTONE) - srpm: $(LLVM_OBJ_ROOT)/llvm.spec rpmbuild -bs $(LLVM_OBJ_ROOT)/llvm.spec diff --git a/Makefile.config.in b/Makefile.config.in index 1d54b317c3e..5ebd80384fb 100644 --- a/Makefile.config.in +++ b/Makefile.config.in @@ -39,14 +39,18 @@ ifndef PROJECT_NAME PROJECT_NAME := $(LLVMPackageName) endif -PROJ_OBJ_DIR := $(shell $(PWD)) -PROJ_OBJ_ROOT := $(shell cd $(PROJ_OBJ_DIR)/$(LEVEL); $(PWD)) +# The macro below is expanded when 'realpath' is not built-in. +# Built-in 'realpath' is available on GNU Make 3.81. +realpath = $(shell cd $(1); $(PWD)) + +PROJ_OBJ_DIR := $(call realpath, .) +PROJ_OBJ_ROOT := $(call realpath, $(PROJ_OBJ_DIR)/$(LEVEL)) ifeq ($(PROJECT_NAME),llvm) -LLVM_SRC_ROOT := $(shell cd @abs_top_srcdir@; $(PWD)) -LLVM_OBJ_ROOT := $(shell cd @abs_top_builddir@; $(PWD)) -PROJ_SRC_ROOT := $(shell cd $(LLVM_SRC_ROOT); $(PWD)) -PROJ_SRC_DIR := $(shell cd $(LLVM_SRC_ROOT)/$(patsubst $(PROJ_OBJ_ROOT)%,%,$(PROJ_OBJ_DIR)); $(PWD)) +LLVM_SRC_ROOT := $(call realpath, @abs_top_srcdir@) +LLVM_OBJ_ROOT := $(call realpath, @abs_top_builddir@) +PROJ_SRC_ROOT := $(LLVM_SRC_ROOT) +PROJ_SRC_DIR := $(call realpath, $(LLVM_SRC_ROOT)/$(patsubst $(PROJ_OBJ_ROOT)%,%,$(PROJ_OBJ_DIR))) prefix := @prefix@ PROJ_prefix := $(prefix) PROJ_VERSION := $(LLVMVersion) @@ -66,7 +70,7 @@ endif ifndef LLVM_OBJ_ROOT $(error Projects must define LLVM_OBJ_ROOT) endif -PROJ_SRC_DIR := $(shell cd $(PROJ_SRC_ROOT)/$(patsubst $(PROJ_OBJ_ROOT)%,%,$(PROJ_OBJ_DIR)); $(PWD)) +PROJ_SRC_DIR := $(call realpath, $(PROJ_SRC_ROOT)/$(patsubst $(PROJ_OBJ_ROOT)%,%,$(PROJ_OBJ_DIR))) prefix := $(PROJ_INSTALL_ROOT) PROJ_prefix := $(prefix) ifndef PROJ_VERSION diff --git a/Makefile.rules b/Makefile.rules index 12582f6f91d..2e18c66e2b7 100644 --- a/Makefile.rules +++ b/Makefile.rules @@ -196,105 +196,15 @@ install-local:: all-local install-bytecode:: install-bytecode-local ############################################################################### -# LLVMC: Provide rules for compiling llvmc plugins +# LLVMC: Provide rules for compiling llvmc-based driver ############################################################################### -ifdef LLVMC_PLUGIN - -LIBRARYNAME := $(patsubst %,plugin_llvmc_%,$(LLVMC_PLUGIN)) -CPP.Flags += -DLLVMC_PLUGIN_NAME=$(LLVMC_PLUGIN) -REQUIRES_EH := 1 - -ifeq ($(ENABLE_LLVMC_DYNAMIC),1) - LD.Flags += -lCompilerDriver -endif - -# Build a dynamic library if the user runs `make` directly from the plugin -# directory. -ifndef LLVMC_BUILTIN_PLUGIN - LOADABLE_MODULE = 1 -endif - -# TableGen stuff... -ifneq ($(BUILT_SOURCES),) - LLVMC_BUILD_AUTOGENERATED_INC=1 -endif - -endif # LLVMC_PLUGIN - ifdef LLVMC_BASED_DRIVER TOOLNAME = $(LLVMC_BASED_DRIVER) -REQUIRES_EH := 1 - -ifeq ($(ENABLE_LLVMC_DYNAMIC),1) - LD.Flags += -lCompilerDriver -else - LLVMLIBS = CompilerDriver.a - LINK_COMPONENTS = support system -endif - -# Preprocessor magic that generates references to static variables in built-in -# plugins. -ifneq ($(LLVMC_BUILTIN_PLUGINS),) - -USEDLIBS += $(patsubst %,plugin_llvmc_%.a,$(LLVMC_BUILTIN_PLUGINS)) - -LLVMC_BUILTIN_PLUGIN_1 = $(word 1, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_2 = $(word 2, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_3 = $(word 3, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_4 = $(word 4, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_5 = $(word 5, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_6 = $(word 6, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_7 = $(word 7, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_8 = $(word 8, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_9 = $(word 9, $(LLVMC_BUILTIN_PLUGINS)) -LLVMC_BUILTIN_PLUGIN_10 = $(word 10, $(LLVMC_BUILTIN_PLUGINS)) - - -ifneq ($(LLVMC_BUILTIN_PLUGIN_1),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_1=$(LLVMC_BUILTIN_PLUGIN_1) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_2),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_2=$(LLVMC_BUILTIN_PLUGIN_2) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_3),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_3=$(LLVMC_BUILTIN_PLUGIN_3) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_4),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_4=$(LLVMC_BUILTIN_PLUGIN_4) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_5),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_5=$(LLVMC_BUILTIN_PLUGIN_5) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_6),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_5=$(LLVMC_BUILTIN_PLUGIN_6) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_7),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_5=$(LLVMC_BUILTIN_PLUGIN_7) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_8),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_5=$(LLVMC_BUILTIN_PLUGIN_8) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_9),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_5=$(LLVMC_BUILTIN_PLUGIN_9) -endif - -ifneq ($(LLVMC_BUILTIN_PLUGIN_10),) -CPP.Flags += -DLLVMC_BUILTIN_PLUGIN_5=$(LLVMC_BUILTIN_PLUGIN_10) -endif - - -endif +LLVMLIBS = CompilerDriver.a +LINK_COMPONENTS = support system endif # LLVMC_BASED_DRIVER @@ -500,6 +410,26 @@ LLVMLibDir := $(LLVM_OBJ_ROOT)/$(BuildMode)/lib LLVMToolDir := $(LLVM_OBJ_ROOT)/$(BuildMode)/bin LLVMExmplDir:= $(LLVM_OBJ_ROOT)/$(BuildMode)/examples +#-------------------------------------------------------------------- +# Locations of shared libraries +#-------------------------------------------------------------------- + +SharedPrefix := lib +SharedLibDir := $(LibDir) +LLVMSharedLibDir := $(LLVMLibDir) + +# Win32.DLL prefers to be located on the "PATH" of binaries. +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) + SharedLibDir := $(ToolDir) + LLVMSharedLibDir := $(LLVMToolDir) + + ifeq ($(HOST_OS),Cygwin) + SharedPrefix := cyg + else + SharedPrefix := + endif +endif + #-------------------------------------------------------------------- # LLVM Capable Compiler #-------------------------------------------------------------------- @@ -573,12 +503,7 @@ ifeq ($(HOST_OS),Darwin) SharedLinkOptions += -mmacosx-version-min=$(DARWIN_VERSION) endif else - ifeq ($(HOST_OS),Cygwin) - SharedLinkOptions=-shared -nostdlib -Wl,--export-all-symbols \ - -Wl,--enable-auto-import -Wl,--enable-auto-image-base - else - SharedLinkOptions=-shared - endif + SharedLinkOptions=-shared endif ifeq ($(TARGET_OS),Darwin) @@ -588,11 +513,13 @@ ifeq ($(TARGET_OS),Darwin) endif ifdef SHARED_LIBRARY +ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) ifneq ($(HOST_OS),Darwin) LD.Flags += $(RPATH) -Wl,'$$ORIGIN' else ifneq ($(DARWIN_MAJVERS),4) - LD.Flags += $(RPATH) -Wl,$(LibDir) + LD.Flags += $(RPATH) -Wl,$(SharedLibDir) +endif endif endif endif @@ -621,8 +548,8 @@ ifndef KEEP_SYMBOLS endif # Adjust linker flags for building an executable -ifneq ($(HOST_OS),Darwin) -ifneq ($(DARWIN_MAJVERS),4) +ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) +ifneq ($(HOST_OS), Darwin) ifdef TOOLNAME LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib' ifdef EXAMPLE_TOOL @@ -631,12 +558,12 @@ ifdef TOOLNAME LD.Flags += $(RPATH) -Wl,$(ToolDir) $(RDYNAMIC) endif endif -endif else ifneq ($(DARWIN_MAJVERS),4) LD.Flags += $(RPATH) -Wl,@executable_path/../lib endif endif +endif #---------------------------------------------------------- @@ -963,6 +890,13 @@ LLVMUsedLibs := $(patsubst %.a.o, lib%.a, $(addsuffix .o, $(LLVMLIBS))) LLVMLibsPaths := $(addprefix $(LLVMLibDir)/,$(LLVMUsedLibs)) endif +# Win32.DLL may refer to other components. +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) + ifdef LOADABLE_MODULE + LINK_COMPONENTS := all + endif +endif + ifndef IS_CLEANING_TARGET ifdef LINK_COMPONENTS @@ -975,12 +909,28 @@ $(LLVM_CONFIG): $(ToolDir)/$(strip $(TOOLNAME))$(EXEEXT): $(LLVM_CONFIG) ifeq ($(ENABLE_SHARED), 1) +# We can take the "auto-import" feature to get rid of using dllimport. +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) +LLVMLibsOptions += -Wl,--enable-auto-import,--enable-runtime-pseudo-reloc \ + -L $(SharedLibDir) +endif LLVMLibsOptions += -lLLVM-$(LLVMVersion) -LLVMLibsPaths += $(LibDir)/libLLVM-$(LLVMVersion)$(SHLIBEXT) +LLVMLibsPaths += $(SharedLibDir)/$(SharedPrefix)LLVM-$(LLVMVersion)$(SHLIBEXT) else -LLVMLibsOptions += $(shell $(LLVM_CONFIG) --libs $(LINK_COMPONENTS)) -LLVMLibsPaths += $(LLVM_CONFIG) \ - $(shell $(LLVM_CONFIG) --libfiles $(LINK_COMPONENTS)) + +ifndef NO_LLVM_CONFIG +LLVMConfigLibs := $(shell $(LLVM_CONFIG) --libs $(LINK_COMPONENTS) || echo Error) +ifeq ($(LLVMConfigLibs),Error) +$(error llvm-config --libs failed) +endif +LLVMLibsOptions += $(LLVMConfigLibs) +LLVMConfigLibfiles := $(shell $(LLVM_CONFIG) --libfiles $(LINK_COMPONENTS) || echo Error) +ifeq ($(LLVMConfigLibfiles),Error) +$(error llvm-config --libfiles failed) +endif +LLVMLibsPaths += $(LLVM_CONFIG) $(LLVMConfigLibfiles) +endif + endif endif endif @@ -1011,12 +961,25 @@ $(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir clean-local:: -$(Verb) $(RM) -f $(NativeExportsFile) else +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) +# GNU ld Win32 accepts .DEF files that contain "DATA" entries. +NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE:.exports=.def)) +$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir + $(Echo) Generating $(notdir $@) + $(Verb) $(ECHO) "EXPORTS" > $@ + $(Verb) $(CAT) $< >> $@ +clean-local:: + -$(Verb) $(RM) -f $(NativeExportsFile) +else +# Default behavior: just use the exports file verbatim. NativeExportsFile := $(EXPORTED_SYMBOL_FILE) endif endif +endif # Now add the linker command-line options to use the native export file. +# Darwin ifeq ($(HOST_OS),Darwin) LLVMLibsOptions += -Wl,-exported_symbols_list,$(NativeExportsFile) endif @@ -1026,6 +989,12 @@ ifeq ($(HAVE_LINK_VERSION_SCRIPT),1) LLVMLibsOptions += -Wl,--version-script,$(NativeExportsFile) endif +# Windows +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) +# LLVMLibsOptions is invalidated at processing tools/llvm-shlib. +SharedLinkOptions += $(NativeExportsFile) +endif + endif ############################################################################### @@ -1100,10 +1069,10 @@ ifdef LIBRARYNAME LIBRARYNAME := $(strip $(LIBRARYNAME)) ifdef LOADABLE_MODULE LibName.A := $(LibDir)/$(LIBRARYNAME).a -LibName.SO := $(LibDir)/$(LIBRARYNAME)$(SHLIBEXT) +LibName.SO := $(SharedLibDir)/$(LIBRARYNAME)$(SHLIBEXT) else LibName.A := $(LibDir)/lib$(LIBRARYNAME).a -LibName.SO := $(LibDir)/lib$(LIBRARYNAME)$(SHLIBEXT) +LibName.SO := $(SharedLibDir)/$(SharedPrefix)$(LIBRARYNAME)$(SHLIBEXT) endif LibName.O := $(LibDir)/$(LIBRARYNAME).o LibName.BCA:= $(LibDir)/lib$(LIBRARYNAME).bca @@ -1128,14 +1097,14 @@ SharedLibKindMessage := "Loadable Module" else SharedLibKindMessage := "Shared Library" endif -$(LibName.SO): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths) $(LibDir)/.dir +$(LibName.SO): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths) $(SharedLibDir)/.dir $(Echo) Linking $(BuildMode) $(SharedLibKindMessage) \ - $(LIBRARYNAME)$(SHLIBEXT) + $(notdir $@) $(Verb) $(Link) $(SharedLinkOptions) -o $@ $(ObjectsO) \ $(ProjLibsOptions) $(LLVMLibsOptions) $(LIBS) else -$(LibName.SO): $(ObjectsO) $(LibDir)/.dir - $(Echo) Linking $(BuildMode) Shared Library $(basename $@) +$(LibName.SO): $(ObjectsO) $(SharedLibDir)/.dir + $(Echo) Linking $(BuildMode) Shared Library $(notdir $@) $(Verb) $(Link) $(SharedLinkOptions) -o $@ $(ObjectsO) endif @@ -1151,21 +1120,23 @@ uninstall-local:: $(Echo) Uninstall circumvented with NO_INSTALL else -ifdef LOADABLE_MODULE -DestSharedLib = $(DESTDIR)$(PROJ_libdir)/$(LIBRARYNAME)$(SHLIBEXT) +# Win32.DLL prefers to be located on the "PATH" of binaries. +ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW)) +DestSharedLibDir := $(DESTDIR)$(PROJ_bindir) else -DestSharedLib = $(DESTDIR)$(PROJ_libdir)/lib$(LIBRARYNAME)$(SHLIBEXT) +DestSharedLibDir := $(DESTDIR)$(PROJ_libdir) endif +DestSharedLib := $(DestSharedLibDir)/$(SharedPrefix)$(LIBRARYNAME)$(SHLIBEXT) install-local:: $(DestSharedLib) -$(DestSharedLib): $(LibName.SO) $(DESTDIR)$(PROJ_libdir) +$(DestSharedLib): $(LibName.SO) $(DestSharedLibDir) $(Echo) Installing $(BuildMode) Shared Library $(DestSharedLib) $(Verb) $(INSTALL) $(LibName.SO) $(DestSharedLib) uninstall-local:: $(Echo) Uninstalling $(BuildMode) Shared Library $(DestSharedLib) - -$(Verb) $(RM) -f $(DESTDIR)$(PROJ_libdir)/lib$(LIBRARYNAME).* + -$(Verb) $(RM) -f $(DestSharedLibDir)/$(SharedPrefix)$(LIBRARYNAME).* endif endif @@ -1341,10 +1312,33 @@ endif endif ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux NetBSD FreeBSD)) +ifneq ($(ARCH), Mips) LD.Flags += -Wl,--version-script=$(LLVM_SRC_ROOT)/autoconf/ExportMap.map endif endif +endif +#--------------------------------------------------------- +# Tool Version Info Support +#--------------------------------------------------------- + +ifeq ($(HOST_OS),Darwin) +ifdef TOOL_INFO_PLIST + +LD.Flags += -Wl,-sectcreate,__TEXT,__info_plist,$(ObjDir)/$(TOOL_INFO_PLIST) + +$(ToolBuildPath): $(ObjDir)/$(TOOL_INFO_PLIST) + +$(ObjDir)/$(TOOL_INFO_PLIST): $(PROJ_SRC_DIR)/$(TOOL_INFO_PLIST).in $(ObjDir)/.dir + $(Echo) "Creating $(TOOLNAME) '$(TOOL_INFO_PLIST)' file..." + $(Verb)sed -e "s#@TOOL_INFO_UTI@#$(TOOL_INFO_UTI)#g" \ + -e "s#@TOOL_INFO_NAME@#$(TOOL_INFO_NAME)#g" \ + -e "s#@TOOL_INFO_VERSION@#$(TOOL_INFO_VERSION)#g" \ + -e "s#@TOOL_INFO_BUILD_VERSION@#$(TOOL_INFO_BUILD_VERSION)#g" \ + $< > $@ + +endif +endif #--------------------------------------------------------- # Provide targets for building the tools @@ -1377,7 +1371,7 @@ $(ToolAliasBuildPath): $(ToolBuildPath) $(Echo) Creating $(BuildMode) Alias $(TOOLALIAS) $(StripWarnMsg) $(Verb) $(RM) -f $(ToolAliasBuildPath) $(Verb) $(AliasTool) $(TOOLEXENAME) $(ToolAliasBuildPath) - $(Echo) ======= Finished Creating $(BuildMode) Alias $(TOOLNAME) \ + $(Echo) ======= Finished Creating $(BuildMode) Alias $(TOOLALIAS) \ $(StripWarnMsg) endif @@ -1626,7 +1620,7 @@ ifdef TARGET TABLEGEN_INC_FILES_COMMON = 1 endif -ifdef LLVMC_BUILD_AUTOGENERATED_INC +ifdef LLVMC_BASED_DRIVER TABLEGEN_INC_FILES_COMMON = 1 endif @@ -1750,20 +1744,26 @@ clean-local:: endif # TARGET -ifdef LLVMC_BUILD_AUTOGENERATED_INC +ifdef LLVMC_BASED_DRIVER -LLVMCPluginSrc := $(sort $(strip $(wildcard $(PROJ_SRC_DIR)/*.td)) \ - $(strip $(wildcard $(PROJ_OBJ_DIR)/*.td))) +TDSrc := $(sort $(strip $(wildcard $(PROJ_SRC_DIR)/*.td)) \ + $(strip $(wildcard $(PROJ_OBJ_DIR)/*.td))) -TDFiles := $(LLVMCPluginSrc) \ - $(strip $(wildcard $(LLVM_SRC_ROOT)/include/llvm/CompilerDriver/*.td)) +TDCommon := $(strip $(wildcard \ + $(LLVM_SRC_ROOT)/include/llvm/CompilerDriver/*.td)) -$(ObjDir)/AutoGenerated.inc.tmp: $(LLVMCPluginSrc) $(ObjDir)/.dir \ - $(TBLGEN) $(TD_COMMON) - $(Echo) "Building LLVMC configuration library with tblgen" +TDFiles := $(TDSrc) $(TDCommon) + +$(INCTMPFiles) : $(TBLGEN) $(TDFiles) + +$(ObjDir)/%.inc.tmp: %.td $(ObjDir)/.dir + $(Echo) "Building LLVMC compilation graph description with tblgen" $(Verb) $(TableGen) -gen-llvmc -o $(call SYSPATH, $@) $< -endif # LLVMC_BUILD_AUTOGENERATED_INC +clean-local:: + -$(Verb) $(RM) -f $(INCFiles) + +endif # LLVMC_BASED_DRIVER ############################################################################### # OTHER RULES: Other rules needed @@ -1840,11 +1840,13 @@ check:: $(EchoCmd) No test directory ; \ fi -check-lit:: +check-lit:: check + +check-dg:: $(Verb) if test -d "$(PROJ_OBJ_ROOT)/test" ; then \ if test -f "$(PROJ_OBJ_ROOT)/test/Makefile" ; then \ $(EchoCmd) Running test suite ; \ - $(MAKE) -C $(PROJ_OBJ_ROOT)/test check-local-lit ; \ + $(MAKE) -C $(PROJ_OBJ_ROOT)/test check-local-dg ; \ else \ $(EchoCmd) No Makefile in test directory ; \ fi ; \ diff --git a/README.txt b/README.txt index 2ebe271b8e5..f54f5bf1b37 100644 --- a/README.txt +++ b/README.txt @@ -1,4 +1,4 @@ -Low Level Virtual Machine (LLVM) +\Low Level Virtual Machine (LLVM) ================================ This directory and its subdirectories contain source code for the Low Level @@ -13,3 +13,4 @@ assistance with LLVM. If you're writing a package for LLVM, see docs/Packaging.html for our suggestions. + diff --git a/autoconf/configure.ac b/autoconf/configure.ac index be320cf3981..de327449e23 100644 --- a/autoconf/configure.ac +++ b/autoconf/configure.ac @@ -31,7 +31,7 @@ dnl=== dnl===-----------------------------------------------------------------------=== dnl Initialize autoconf and define the package name, version number and dnl email address for reporting bugs. -AC_INIT([[llvm]],[[2.8svn]],[llvmbugs@cs.uiuc.edu]) +AC_INIT([[llvm]],[[2.8rc]],[llvmbugs@cs.uiuc.edu]) dnl Provide a copyright substitution and ensure the copyright notice is included dnl in the output of --version option of the generated configure script. @@ -101,7 +101,6 @@ for i in `ls ${srcdir}/projects` do if test -d ${srcdir}/projects/${i} ; then case ${i} in - CVS) ;; sample) AC_CONFIG_SUBDIRS([projects/sample]) ;; privbracket) AC_CONFIG_SUBDIRS([projects/privbracket]) ;; llvm-stacker) AC_CONFIG_SUBDIRS([projects/llvm-stacker]) ;; @@ -299,7 +298,7 @@ dnl Set the LINKALL and NOLINKALL Makefile variables based on the platform AC_SUBST(LINKALL,$llvm_cv_link_all_option) AC_SUBST(NOLINKALL,$llvm_cv_no_link_all_option) -dnl Set the "LLVM_ON_*" variables based on llvm_cvs_platform_type +dnl Set the "LLVM_ON_*" variables based on llvm_cv_platform_type dnl This is used by lib/System to determine the basic kind of implementation dnl to use. case $llvm_cv_platform_type in @@ -369,13 +368,13 @@ else AC_SUBST(LLVM_CROSS_COMPILING, [0]) fi -dnl Check to see if there's a "CVS" (or .svn or .git) directory indicating -dnl that this build is being done from a checkout. This sets up several -dnl defaults for the command line switches. When we build with a CVS directory, +dnl Check to see if there's a .svn or .git directory indicating that this +dnl build is being done from a checkout. This sets up several defaults for +dnl the command line switches. When we build with a checkout directory, dnl we get a debug with assertions turned on. Without, we assume a source dnl release and we get an optimized build without assertions. dnl See --enable-optimized and --enable-assertions below -if test -d "CVS" -o -d "${srcdir}/CVS" -o -d ".svn" -o -d "${srcdir}/.svn" -o -d ".git" -o -d "${srcdir}/.git"; then +if test -d ".svn" -o -d "${srcdir}/.svn" -o -d ".git" -o -d "${srcdir}/.git"; then cvsbuild="yes" optimize="no" AC_SUBST(CVSBUILD,[[CVSBUILD=1]]) @@ -392,7 +391,7 @@ dnl===-----------------------------------------------------------------------=== dnl --enable-optimized : check whether they want to do an optimized build: AC_ARG_ENABLE(optimized, AS_HELP_STRING( - --enable-optimized,[Compile with optimizations enabled (default is NO)]),,enableval=$optimize) + --enable-optimized,[Compile with optimizations enabled (default is YES)]),,enableval="yes") if test ${enableval} = "no" ; then AC_SUBST(ENABLE_OPTIMIZED,[[]]) else @@ -410,7 +409,7 @@ fi dnl --enable-assertions : check whether they want to turn on assertions or not: AC_ARG_ENABLE(assertions,AS_HELP_STRING( - --enable-assertions,[Compile with assertion checks enabled (default is YES)]),, enableval="yes") + --enable-assertions,[Compile with assertion checks enabled (default is NO)]),, enableval="no") if test ${enableval} = "yes" ; then AC_SUBST(DISABLE_ASSERTIONS,[[]]) else @@ -544,13 +543,13 @@ TARGETS_TO_BUILD="" AC_ARG_ENABLE([targets],AS_HELP_STRING([--enable-targets], [Build specific host targets: all or target1,target2,... Valid targets are: host, x86, x86_64, sparc, powerpc, alpha, arm, mips, spu, pic16, - xcore, msp430, systemz, blackfin, cbe, msil, and cpp (default=all)]),, + xcore, msp430, systemz, blackfin, cbe, and cpp (default=all)]),, enableval=all) if test "$enableval" = host-only ; then enableval=host fi case "$enableval" in - all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha ARM Mips CellSPU PIC16 XCore MSP430 SystemZ Blackfin CBackend MSIL CppBackend MBlaze" ;; + all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha ARM Mips CellSPU PIC16 XCore MSP430 SystemZ Blackfin CBackend CppBackend MBlaze" ;; *)for a_target in `echo $enableval|sed -e 's/,/ /g' ` ; do case "$a_target" in x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;; @@ -567,7 +566,6 @@ case "$enableval" in systemz) TARGETS_TO_BUILD="SystemZ $TARGETS_TO_BUILD" ;; blackfin) TARGETS_TO_BUILD="Blackfin $TARGETS_TO_BUILD" ;; cbe) TARGETS_TO_BUILD="CBackend $TARGETS_TO_BUILD" ;; - msil) TARGETS_TO_BUILD="MSIL $TARGETS_TO_BUILD" ;; cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;; mblaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;; host) case "$llvm_cv_target_arch" in @@ -598,9 +596,17 @@ AC_SUBST(TARGETS_TO_BUILD,$TARGETS_TO_BUILD) # If so, define LLVM_NATIVE_ARCH to that LLVM target. for a_target in $TARGETS_TO_BUILD; do if test "$a_target" = "$LLVM_NATIVE_ARCH"; then - LLVM_NATIVE_ARCHTARGET="${LLVM_NATIVE_ARCH}Target" - AC_DEFINE_UNQUOTED(LLVM_NATIVE_ARCH,$LLVM_NATIVE_ARCHTARGET, + AC_DEFINE_UNQUOTED(LLVM_NATIVE_ARCH, $LLVM_NATIVE_ARCH, [LLVM architecture name for the native architecture, if available]) + LLVM_NATIVE_TARGET="LLVMInitialize${LLVM_NATIVE_ARCH}Target" + LLVM_NATIVE_TARGETINFO="LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo" + LLVM_NATIVE_ASMPRINTER="LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter" + AC_DEFINE_UNQUOTED(LLVM_NATIVE_TARGET, $LLVM_NATIVE_TARGET, + [LLVM name for the native Target init function, if available]) + AC_DEFINE_UNQUOTED(LLVM_NATIVE_TARGETINFO, $LLVM_NATIVE_TARGETINFO, + [LLVM name for the native TargetInfo init function, if available]) + AC_DEFINE_UNQUOTED(LLVM_NATIVE_ASMPRINTER, $LLVM_NATIVE_ASMPRINTER, + [LLVM name for the native AsmPrinter init function, if available]) fi done @@ -857,35 +863,6 @@ AC_ARG_ENABLE(libffi,AS_HELP_STRING( esac], llvm_cv_enable_libffi=no) -dnl Only Windows needs dynamic libCompilerDriver to support plugins. -if test "$llvm_cv_os_type" = "Win32" ; then - llvmc_dynamic="yes" -else - llvmc_dynamic="no" -fi - -dnl --enable-llvmc-dynamic : should LLVMC link libCompilerDriver dynamically? -AC_ARG_ENABLE(llvmc-dynamic,AS_HELP_STRING( ---enable-llvmc-dynamic, -[Link LLVMC dynamically (default is NO, unless on Win32)]),, -enableval=$llvmc_dynamic) -if test ${enableval} = "yes" && test "$ENABLE_PIC" -eq 1 ; then - AC_SUBST(ENABLE_LLVMC_DYNAMIC,[[ENABLE_LLVMC_DYNAMIC=1]]) -else - AC_SUBST(ENABLE_LLVMC_DYNAMIC,[[]]) -fi - -dnl --enable-llvmc-dynamic-plugins : should LLVMC support dynamic plugins? -AC_ARG_ENABLE(llvmc-dynamic-plugins,AS_HELP_STRING( ---enable-llvmc-dynamic-plugins, -[Enable dynamic LLVMC plugins (default is YES)]),, -enableval=yes) -if test ${enableval} = "yes" ; then - AC_SUBST(ENABLE_LLVMC_DYNAMIC_PLUGINS,[[ENABLE_LLVMC_DYNAMIC_PLUGINS=1]]) -else - AC_SUBST(ENABLE_LLVMC_DYNAMIC_PLUGINS,[[]]) -fi - dnl===-----------------------------------------------------------------------=== dnl=== dnl=== SECTION 4: Check for programs we need and that they are the right version @@ -1011,6 +988,13 @@ fi dnl Find the install program AC_PROG_INSTALL +dnl Prepend src dir to install path dir if it's a relative path +dnl This is a hack for installs that take place in something other +dnl than the top level. +case "$INSTALL" in + [[\\/$]]* | ?:[[\\/]]* ) ;; + *) INSTALL="\\\$(TOPSRCDIR)/$INSTALL" ;; +esac dnl Checks for documentation and testing tools that we can do without. If these dnl are not found then they are set to "true" which always succeeds but does @@ -1033,6 +1017,9 @@ AC_PATH_PROGS(OCAMLDEP, [ocamldep]) AC_PATH_PROGS(OCAMLDOC, [ocamldoc]) AC_PATH_PROGS(GAS, [gas as]) +dnl Get the version of the linker in use. +AC_LINK_GET_VERSION + dnl Determine whether the linker supports the -R option. AC_LINK_USE_R @@ -1345,6 +1332,9 @@ fi dnl atomic builtins are required for threading support. AC_MSG_CHECKING(for GCC atomic builtins) +dnl Since we'll be using these atomic builtins in C++ files we should test +dnl the C++ compiler. +AC_LANG_PUSH([C++]) AC_LINK_IFELSE( AC_LANG_SOURCE( [[int main() { @@ -1356,13 +1346,13 @@ AC_LINK_IFELSE( return 0; } ]]), + AC_LANG_POP([C++]) AC_MSG_RESULT(yes) AC_DEFINE(LLVM_MULTITHREADED, 1, Build multithreading support into LLVM), AC_MSG_RESULT(no) AC_DEFINE(LLVM_MULTITHREADED, 0, Build multithreading support into LLVM) AC_MSG_WARN([LLVM will be built thread-unsafe because atomic builtins are missing])) - dnl===-----------------------------------------------------------------------=== dnl=== dnl=== SECTION 9: Additional checks, variables, etc. @@ -1549,7 +1539,11 @@ dnl WARNING: dnl If you add or remove any of the following config headers, then dnl you MUST also update Makefile.rules so that the variable FilesToConfig dnl contains the same list of files as AC_CONFIG_HEADERS below. This ensures the dnl files can be updated automatically when their *.in sources change. -AC_CONFIG_HEADERS([include/llvm/Config/config.h]) +AC_CONFIG_HEADERS([include/llvm/Config/config.h include/llvm/Config/llvm-config.h]) +AH_TOP([#ifndef CONFIG_H +#define CONFIG_H]) +AH_BOTTOM([#endif]) + AC_CONFIG_FILES([include/llvm/Config/Targets.def]) AC_CONFIG_FILES([include/llvm/Config/AsmPrinters.def]) AC_CONFIG_FILES([include/llvm/Config/AsmParsers.def]) @@ -1563,7 +1557,7 @@ dnl Configure the RPM spec file for LLVM AC_CONFIG_FILES([llvm.spec]) dnl Configure llvmc's Base plugin -AC_CONFIG_FILES([tools/llvmc/plugins/Base/Base.td]) +AC_CONFIG_FILES([tools/llvmc/src/Base.td]) dnl Do the first stage of configuration for llvm-config.in. AC_CONFIG_FILES([tools/llvm-config/llvm-config.in]) diff --git a/autoconf/m4/link_options.m4 b/autoconf/m4/link_options.m4 index b48710c094d..4c5f2f435d0 100644 --- a/autoconf/m4/link_options.m4 +++ b/autoconf/m4/link_options.m4 @@ -1,3 +1,24 @@ +# +# Get the linker version string. +# +# This macro is specific to LLVM. +# +AC_DEFUN([AC_LINK_GET_VERSION], + [AC_CACHE_CHECK([for linker version],[llvm_cv_link_version], + [ + version_string="$(ld -v 2>&1 | head -1)" + + # Check for ld64. + if (echo "$version_string" | grep -q "ld64"); then + llvm_cv_link_version=$(echo "$version_string" | sed -e "s#.*ld64-\([^ ]*\)#\1#") + else + llvm_cv_link_version=$(echo "$version_string" | sed -e "s#[^0-9]*\([0-9.]*\).*#\1#") + fi + ]) + AC_DEFINE_UNQUOTED([HOST_LINK_VERSION],"$llvm_cv_link_version", + [Linker version detected at compile time.]) +]) + # # Determine if the system can handle the -R option being passed to the linker. # diff --git a/bindings/ada/llvm/llvm.ads b/bindings/ada/llvm/llvm.ads index ce74e670a68..20fc940f8c2 100644 --- a/bindings/ada/llvm/llvm.ads +++ b/bindings/ada/llvm/llvm.ads @@ -317,25 +317,27 @@ package llvm is LLVMGhostLinkage, LLVMCommonLinkage, LLVMLinkerPrivateLinkage, - LLVMLinkerPrivateWeakLinkage); + LLVMLinkerPrivateWeakLinkage, + LinkerPrivateWeakDefAutoLinkage); for LLVMLinkage use - (LLVMExternalLinkage => 0, - LLVMAvailableExternallyLinkage => 1, - LLVMLinkOnceAnyLinkage => 2, - LLVMLinkOnceODRLinkage => 3, - LLVMWeakAnyLinkage => 4, - LLVMWeakODRLinkage => 5, - LLVMAppendingLinkage => 6, - LLVMInternalLinkage => 7, - LLVMPrivateLinkage => 8, - LLVMDLLImportLinkage => 9, - LLVMDLLExportLinkage => 10, - LLVMExternalWeakLinkage => 11, - LLVMGhostLinkage => 12, - LLVMCommonLinkage => 13, - LLVMLinkerPrivateLinkage => 14, - LLVMLinkerPrivateWeakLinkage => 15); + (LLVMExternalLinkage => 0, + LLVMAvailableExternallyLinkage => 1, + LLVMLinkOnceAnyLinkage => 2, + LLVMLinkOnceODRLinkage => 3, + LLVMWeakAnyLinkage => 4, + LLVMWeakODRLinkage => 5, + LLVMAppendingLinkage => 6, + LLVMInternalLinkage => 7, + LLVMPrivateLinkage => 8, + LLVMDLLImportLinkage => 9, + LLVMDLLExportLinkage => 10, + LLVMExternalWeakLinkage => 11, + LLVMGhostLinkage => 12, + LLVMCommonLinkage => 13, + LLVMLinkerPrivateLinkage => 14, + LLVMLinkerPrivateWeakLinkage => 15, + LinkerPrivateWeakDefAutoLinkage => 16); pragma Convention (C, LLVMLinkage); diff --git a/bindings/ocaml/llvm/llvm.ml b/bindings/ocaml/llvm/llvm.ml index 7ab6f51efb9..462eb201694 100644 --- a/bindings/ocaml/llvm/llvm.ml +++ b/bindings/ocaml/llvm/llvm.ml @@ -35,7 +35,6 @@ module TypeKind = struct | Opaque | Vector | Metadata - | Union end module Linkage = struct @@ -210,11 +209,6 @@ external struct_element_types : lltype -> lltype array = "llvm_struct_element_types" external is_packed : lltype -> bool = "llvm_is_packed" -(*--... Operations on union types ..........................................--*) -external union_type : llcontext -> lltype array -> lltype = "llvm_union_type" -external union_element_types : lltype -> lltype array - = "llvm_union_element_types" - (*--... Operations on pointer, vector, and array types .....................--*) external array_type : lltype -> int -> lltype = "llvm_array_type" external pointer_type : lltype -> lltype = "llvm_pointer_type" @@ -280,6 +274,8 @@ let fold_right_uses f v init = (*--... Operations on users ................................................--*) external operand : llvalue -> int -> llvalue = "llvm_operand" +external set_operand : llvalue -> int -> llvalue -> unit = "llvm_set_operand" +external num_operands : llvalue -> int = "llvm_num_operands" (*--... Operations on constants of (mostly) any type .......................--*) external is_constant : llvalue -> bool = "llvm_is_constant" @@ -319,7 +315,6 @@ external const_struct : llcontext -> llvalue array -> llvalue external const_packed_struct : llcontext -> llvalue array -> llvalue = "llvm_const_packed_struct" external const_vector : llvalue array -> llvalue = "llvm_const_vector" -external const_union : lltype -> llvalue -> llvalue = "LLVMConstUnion" (*--... Constant expressions ...............................................--*) external align_of : lltype -> llvalue = "LLVMAlignOf" @@ -1050,9 +1045,6 @@ let rec string_of_lltype ty = if is_packed ty then "<" ^ s ^ ">" else s - | TypeKind.Union -> "union { " ^ (concat2 ", " ( - Array.map string_of_lltype (union_element_types ty) - )) ^ " }" | TypeKind.Array -> "[" ^ (string_of_int (array_length ty)) ^ " x " ^ (string_of_lltype (element_type ty)) ^ "]" | TypeKind.Vector -> "<" ^ (string_of_int (vector_size ty)) ^ diff --git a/bindings/ocaml/llvm/llvm.mli b/bindings/ocaml/llvm/llvm.mli index 742265cd3d5..ba3bbe248b7 100644 --- a/bindings/ocaml/llvm/llvm.mli +++ b/bindings/ocaml/llvm/llvm.mli @@ -72,7 +72,6 @@ module TypeKind : sig | Opaque | Vector | Metadata - | Union end (** The linkage of a global value, accessed with {!linkage} and @@ -408,19 +407,6 @@ external struct_element_types : lltype -> lltype array external is_packed : lltype -> bool = "llvm_is_packed" -(** {7 Operations on union types} *) - -(** [union_type context tys] returns the union type in the context [context] - containing the types in the array [tys]. See the method - [llvm::UnionType::get] *) -external union_type : llcontext -> lltype array -> lltype = "llvm_union_type" - -(** [union_element_types uty] returns the constituent types of the union type - [uty]. See the method [llvm::UnionType::getElementType]. *) -external union_element_types : lltype -> lltype array - = "llvm_union_element_types" - - (** {7 Operations on pointer, vector, and array types} *) (** [array_type ty n] returns the array type containing [n] elements of type @@ -557,6 +543,14 @@ val fold_right_uses : (lluse -> 'a -> 'a) -> llvalue -> 'a -> 'a method [llvm::User::getOperand]. *) external operand : llvalue -> int -> llvalue = "llvm_operand" +(** [set_operand v i o] sets the operand of the value [v] at the index [i] to + the value [o]. + See the method [llvm::User::setOperand]. *) +external set_operand : llvalue -> int -> llvalue -> unit = "llvm_set_operand" + +(** [num_operands v] returns the number of operands for the value [v]. + See the method [llvm::User::getNumOperands]. *) +external num_operands : llvalue -> int = "llvm_num_operands" (** {7 Operations on constants of (mostly) any type} *) @@ -689,10 +683,6 @@ external const_packed_struct : llcontext -> llvalue array -> llvalue values [elts]. See the method [llvm::ConstantVector::get]. *) external const_vector : llvalue array -> llvalue = "llvm_const_vector" -(** [const_union ty v] returns the union constant of type [union_type tys] and - containing the value [v]. See the method [llvm::ConstantUnion::get]. *) -external const_union : lltype -> llvalue -> llvalue = "LLVMConstUnion" - (** {7 Constant expressions} *) @@ -991,7 +981,7 @@ external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue = "LLVMConstInsertElement" (** [const_shufflevector a b mask] returns a constant [shufflevector]. - See the LLVM Language Reference for details on the [sufflevector] + See the LLVM Language Reference for details on the [shufflevector] instruction. See the method [llvm::ConstantExpr::getShuffleVector]. *) external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue diff --git a/bindings/ocaml/llvm/llvm_ocaml.c b/bindings/ocaml/llvm/llvm_ocaml.c index c4355ba2dbf..ef2e3d66629 100644 --- a/bindings/ocaml/llvm/llvm_ocaml.c +++ b/bindings/ocaml/llvm/llvm_ocaml.c @@ -318,21 +318,6 @@ CAMLprim value llvm_is_packed(LLVMTypeRef StructTy) { return Val_bool(LLVMIsPackedStruct(StructTy)); } -/*--... Operations on union types ..........................................--*/ - -/* llcontext -> lltype array -> lltype */ -CAMLprim LLVMTypeRef llvm_union_type(LLVMContextRef C, value ElementTypes) { - return LLVMUnionTypeInContext(C, (LLVMTypeRef *) ElementTypes, - Wosize_val(ElementTypes)); -} - -/* lltype -> lltype array */ -CAMLprim value llvm_union_element_types(LLVMTypeRef UnionTy) { - value Tys = alloc(LLVMCountUnionElementTypes(UnionTy), 0); - LLVMGetUnionElementTypes(UnionTy, (LLVMTypeRef *) Tys); - return Tys; -} - /*--... Operations on array, pointer, and vector types .....................--*/ /* lltype -> int -> lltype */ @@ -452,6 +437,17 @@ CAMLprim LLVMValueRef llvm_operand(LLVMValueRef V, value I) { return LLVMGetOperand(V, Int_val(I)); } +/* llvalue -> int -> llvalue -> unit */ +CAMLprim value llvm_set_operand(LLVMValueRef U, value I, LLVMValueRef V) { + LLVMSetOperand(U, Int_val(I), V); + return Val_unit; +} + +/* llvalue -> int */ +CAMLprim value llvm_num_operands(LLVMValueRef V) { + return Val_int(LLVMGetNumOperands(V)); +} + /*--... Operations on constants of (mostly) any type .......................--*/ /* llvalue -> bool */ @@ -964,8 +960,8 @@ CAMLprim LLVMValueRef llvm_param(LLVMValueRef Fn, value Index) { return LLVMGetParam(Fn, Int_val(Index)); } -/* llvalue -> int -> llvalue */ -CAMLprim value llvm_params(LLVMValueRef Fn, value Index) { +/* llvalue -> llvalue */ +CAMLprim value llvm_params(LLVMValueRef Fn) { value Params = alloc(LLVMCountParams(Fn), 0); LLVMGetParams(Fn, (LLVMValueRef *) Op_val(Params)); return Params; diff --git a/cmake/config-ix.cmake b/cmake/config-ix.cmake index d9450d92585..f75e5dfb265 100755 --- a/cmake/config-ix.cmake +++ b/cmake/config-ix.cmake @@ -214,6 +214,9 @@ if (LLVM_NATIVE_ARCH) set(LLVM_NATIVE_ARCH) else () message(STATUS "Native target architecture is ${LLVM_NATIVE_ARCH}") + set(LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target) + set(LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo) + set(LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter) endif () endif() @@ -259,11 +262,18 @@ else( ENABLE_THREADS ) message(STATUS "Threads disabled.") endif() +set(LLVM_PREFIX ${CMAKE_INSTALL_PREFIX}) + configure_file( ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/config.h.cmake ${LLVM_BINARY_DIR}/include/llvm/Config/config.h ) +configure_file( + ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/llvm-config.h.cmake + ${LLVM_BINARY_DIR}/include/llvm/Config/llvm-config.h + ) + configure_file( ${LLVM_MAIN_INCLUDE_DIR}/llvm/System/DataTypes.h.cmake ${LLVM_BINARY_DIR}/include/llvm/System/DataTypes.h diff --git a/cmake/modules/CMakeLists.txt b/cmake/modules/CMakeLists.txt new file mode 100644 index 00000000000..416d7f47856 --- /dev/null +++ b/cmake/modules/CMakeLists.txt @@ -0,0 +1,12 @@ +set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/share/llvm/cmake") + +configure_file( + LLVM.cmake + ${llvm_cmake_builddir}/LLVM.cmake + @ONLY) + +install(FILES + ${llvm_cmake_builddir}/LLVM.cmake + LLVMConfig.cmake + LLVMLibDeps.cmake + DESTINATION share/llvm/cmake) diff --git a/cmake/modules/ChooseMSVCCRT.cmake b/cmake/modules/ChooseMSVCCRT.cmake new file mode 100644 index 00000000000..eb78f45c885 --- /dev/null +++ b/cmake/modules/ChooseMSVCCRT.cmake @@ -0,0 +1,106 @@ +# The macro choose_msvc_crt() takes a list of possible +# C runtimes to choose from, in the form of compiler flags, +# to present to the user. (MTd for /MTd, etc) +# +# The macro is invoked at the end of the file. +# +# CMake already sets CRT flags in the CMAKE_CXX_FLAGS_* and +# CMAKE_C_FLAGS_* variables by default. To let the user +# override that for each build type: +# 1. Detect which CRT is already selected, and reflect this in +# LLVM_USE_CRT_* so the user can have a better idea of what +# changes they're making. +# 2. Replace the flags in both variables with the new flag via a regex. +# 3. set() the variables back into the cache so the changes +# are user-visible. + +### Helper macros: ### +macro(make_crt_regex regex crts) + set(${regex} "") + foreach(crt ${${crts}}) + # Trying to match the beginning or end of the string with stuff + # like [ ^]+ didn't work, so use a bunch of parentheses instead. + set(${regex} "${${regex}}|(^| +)/${crt}($| +)") + endforeach(crt) + string(REGEX REPLACE "^\\|" "" ${regex} "${${regex}}") +endmacro(make_crt_regex) + +macro(get_current_crt crt_current regex flagsvar) + # Find the selected-by-CMake CRT for each build type, if any. + # Strip off the leading slash and any whitespace. + string(REGEX MATCH "${${regex}}" ${crt_current} "${${flagsvar}}") + string(REPLACE "/" " " ${crt_current} "${${crt_current}}") + string(STRIP "${${crt_current}}" ${crt_current}) +endmacro(get_current_crt) + +# Replaces or adds a flag to a variable. +# Expects 'flag' to be padded with spaces. +macro(set_flag_in_var flagsvar regex flag) + string(REGEX MATCH "${${regex}}" current_flag "${${flagsvar}}") + if("${current_flag}" STREQUAL "") + set(${flagsvar} "${${flagsvar}}${${flag}}") + else() + string(REGEX REPLACE "${${regex}}" "${${flag}}" ${flagsvar} "${${flagsvar}}") + endif() + string(STRIP "${${flagsvar}}" ${flagsvar}) + # Make sure this change gets reflected in the cache/gui. + # CMake requires the docstring parameter whenever set() touches the cache, + # so get the existing docstring and re-use that. + get_property(flagsvar_docs CACHE ${flagsvar} PROPERTY HELPSTRING) + set(${flagsvar} "${${flagsvar}}" CACHE STRING "${flagsvar_docs}" FORCE) +endmacro(set_flag_in_var) + + +macro(choose_msvc_crt MSVC_CRT) + if(LLVM_USE_CRT) + message(FATAL_ERROR + "LLVM_USE_CRT is deprecated. Use the CMAKE_BUILD_TYPE-specific +variables (LLVM_USE_CRT_DEBUG, etc) instead.") + endif() + + make_crt_regex(MSVC_CRT_REGEX ${MSVC_CRT}) + + foreach(build_type ${CMAKE_CONFIGURATION_TYPES}) + string(TOUPPER "${build_type}" build) + if (NOT LLVM_USE_CRT_${build}) + get_current_crt(LLVM_USE_CRT_${build} + MSVC_CRT_REGEX + CMAKE_CXX_FLAGS_${build}) + set(LLVM_USE_CRT_${build} + "${LLVM_USE_CRT_${build}}" + CACHE STRING "Specify VC++ CRT to use for ${build_type} configurations." + FORCE) + set_property(CACHE LLVM_USE_CRT_${build} + PROPERTY STRINGS "";${${MSVC_CRT}}) + endif(NOT LLVM_USE_CRT_${build}) + endforeach(build_type) + + foreach(build_type ${CMAKE_CONFIGURATION_TYPES}) + string(TOUPPER "${build_type}" build) + if ("${LLVM_USE_CRT_${build}}" STREQUAL "") + set(flag_string " ") + else() + set(flag_string " /${LLVM_USE_CRT_${build}} ") + list(FIND ${MSVC_CRT} ${LLVM_USE_CRT_${build}} idx) + if (idx LESS 0) + message(FATAL_ERROR + "Invalid value for LLVM_USE_CRT_${build}: ${LLVM_USE_CRT_${build}}. Valid options are one of: ${${MSVC_CRT}}") + endif (idx LESS 0) + message(STATUS "Using ${build_type} VC++ CRT: ${LLVM_USE_CRT_${build}}") + endif() + foreach(lang C CXX) + set_flag_in_var(CMAKE_${lang}_FLAGS_${build} MSVC_CRT_REGEX flag_string) + endforeach(lang) + endforeach(build_type) +endmacro(choose_msvc_crt MSVC_CRT) + + +# List of valid CRTs for MSVC +set(MSVC_CRT + MD + MDd + MT + MTd) + +choose_msvc_crt(MSVC_CRT) + diff --git a/cmake/modules/LLVM.cmake b/cmake/modules/LLVM.cmake new file mode 100644 index 00000000000..9621454f411 --- /dev/null +++ b/cmake/modules/LLVM.cmake @@ -0,0 +1,29 @@ +# This file provides information and services to the final user. + +set(LLVM_COMMON_DEPENDS @LLVM_COMMON_DEPENDS@) + +set(llvm_libs @llvm_libs@) + +set(llvm_lib_targets @llvm_lib_targets@) + +set(LLVM_TARGETS_TO_BUILD @LLVM_TARGETS_TO_BUILD@) + +set(LLVM_TOOLS_BINARY_DIR @LLVM_TOOLS_BINARY_DIR@) + +set(LLVM_ENABLE_THREADS @LLVM_ENABLE_THREADS@) + +set(LLVM_NATIVE_ARCH @LLVM_NATIVE_ARCH@) + +# We try to include using the current setting of CMAKE_MODULE_PATH, +# which suppossedly was filled by the user with the directory where +# this file was installed: +include( LLVMConfig OPTIONAL RESULT_VARIABLE LLVMCONFIG_INCLUDED ) + +# If failed, we assume that this is an un-installed build: +if( NOT LLVMCONFIG_INCLUDED ) + set(CMAKE_MODULE_PATH + ${CMAKE_MODULE_PATH} + "@LLVM_SOURCE_DIR@/cmake/modules") + include( LLVMConfig ) +endif() + diff --git a/cmake/modules/LLVMConfig.cmake b/cmake/modules/LLVMConfig.cmake index 0744b50d648..e5497084be8 100755 --- a/cmake/modules/LLVMConfig.cmake +++ b/cmake/modules/LLVMConfig.cmake @@ -16,6 +16,26 @@ function(get_system_libs return_var) endfunction(get_system_libs) +function(is_llvm_target_library library return_var) + # Sets variable `return_var' to ON if `library' corresponds to a + # LLVM supported target. To OFF if it doesn't. + set(${return_var} OFF PARENT_SCOPE) + string(TOUPPER "${library}" capitalized_lib) + string(TOUPPER "${LLVM_ALL_TARGETS}" targets) + foreach(t ${targets}) + if( capitalized_lib STREQUAL "LLVM${t}" OR + capitalized_lib STREQUAL "LLVM${t}CODEGEN" OR + capitalized_lib STREQUAL "LLVM${t}ASMPARSER" OR + capitalized_lib STREQUAL "LLVM${t}ASMPRINTER" OR + capitalized_lib STREQUAL "LLVM${t}DISASSEMBLER" OR + capitalized_lib STREQUAL "LLVM${t}INFO" ) + set(${return_var} ON PARENT_SCOPE) + break() + endif() + endforeach() +endfunction(is_llvm_target_library) + + macro(llvm_config executable) explicit_llvm_config(${executable} ${ARGN}) endmacro(llvm_config) @@ -29,6 +49,14 @@ function(explicit_llvm_config executable) endfunction(explicit_llvm_config) +# This is a variant intended for the final user: +function(llvm_map_components_to_libraries OUT_VAR) + explicit_map_components_to_libraries(result ${ARGN}) + get_system_libs(sys_result) + set( ${OUT_VAR} ${result} ${sys_result} PARENT_SCOPE ) +endfunction(llvm_map_components_to_libraries) + + function(explicit_map_components_to_libraries out_libs) set( link_components ${ARGN} ) foreach(c ${link_components}) @@ -86,16 +114,24 @@ function(explicit_map_components_to_libraries out_libs) list(GET expanded_components 0 c) string(TOUPPER "${c}" capitalized) list(FIND capitalized_libs ${capitalized} idx) + set(add_it ON) if( idx LESS 0 ) - message(FATAL_ERROR "Library ${c} not found in list of llvm libraries.") + # The library is unkown. Maybe is an ommitted target? + is_llvm_target_library(${c} iltl_result) + if( NOT iltl_result ) + message(FATAL_ERROR "Library ${c} not found in list of llvm libraries.") + endif() + set(add_it OFF) endif( idx LESS 0 ) list(GET llvm_libs ${idx} canonical_lib) list(REMOVE_ITEM result ${canonical_lib}) - list(APPEND result ${canonical_lib}) foreach(c ${MSVC_LIB_DEPS_${canonical_lib}}) list(REMOVE_ITEM expanded_components ${c}) endforeach() - list(APPEND expanded_components ${MSVC_LIB_DEPS_${canonical_lib}}) + if( add_it ) + list(APPEND result ${canonical_lib}) + list(APPEND expanded_components ${MSVC_LIB_DEPS_${canonical_lib}}) + endif() list(REMOVE_AT expanded_components 0) list(LENGTH expanded_components lst_size) endwhile( 0 LESS ${lst_size} ) @@ -115,13 +151,13 @@ endfunction(explicit_map_components_to_libraries) # The format generated by GenLibDeps.pl -# LLVMARMAsmPrinter.o: LLVMARMCodeGen.o libLLVMAsmPrinter.a libLLVMCodeGen.a libLLVMCore.a libLLVMSupport.a libLLVMTarget.a +# libLLVMARMAsmPrinter.a: libLLVMMC.a libLLVMSupport.a # is translated to: -# set(MSVC_LIB_DEPS_LLVMARMAsmPrinter LLVMARMCodeGen LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMSupport LLVMTarget) +# set(MSVC_LIB_DEPS_LLVMARMAsmPrinter LLVMMC LLVMSupport) -# It is necessary to remove the `lib' prefix and the `.a'. +# It is necessary to remove the `lib' prefix and the `.a' suffix. # This 'sed' script should do the trick: # sed -e s'#\.a##g' -e 's#libLLVM#LLVM#g' -e 's#: # #' -e 's#\(.*\)#set(MSVC_LIB_DEPS_\1)#' ~/llvm/tools/llvm-config/LibDeps.txt diff --git a/cmake/modules/LLVMLibDeps.cmake b/cmake/modules/LLVMLibDeps.cmake index c9798485dec..e639b04e980 100644 --- a/cmake/modules/LLVMLibDeps.cmake +++ b/cmake/modules/LLVMLibDeps.cmake @@ -1,6 +1,6 @@ -set(MSVC_LIB_DEPS_LLVMARMAsmParser LLVMARMInfo LLVMMCParser LLVMSupport) -set(MSVC_LIB_DEPS_LLVMARMAsmPrinter LLVMARMCodeGen LLVMARMInfo LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMTarget) -set(MSVC_LIB_DEPS_LLVMARMCodeGen LLVMARMInfo LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) +set(MSVC_LIB_DEPS_LLVMARMAsmParser LLVMARMInfo LLVMMC LLVMMCParser LLVMSupport LLVMTarget) +set(MSVC_LIB_DEPS_LLVMARMAsmPrinter LLVMMC LLVMSupport) +set(MSVC_LIB_DEPS_LLVMARMCodeGen LLVMARMInfo LLVMAnalysis LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMARMInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMAlphaAsmPrinter LLVMAlphaInfo LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMAlphaCodeGen LLVMAlphaInfo LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) @@ -8,9 +8,9 @@ set(MSVC_LIB_DEPS_LLVMAlphaInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMAnalysis LLVMCore LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMArchive LLVMBitReader LLVMCore LLVMSupport LLVMSystem) set(MSVC_LIB_DEPS_LLVMAsmParser LLVMCore LLVMSupport) -set(MSVC_LIB_DEPS_LLVMAsmPrinter LLVMAnalysis LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMSystem LLVMTarget) +set(MSVC_LIB_DEPS_LLVMAsmPrinter LLVMAnalysis LLVMCodeGen LLVMCore LLVMMC LLVMMCParser LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMBitReader LLVMCore LLVMSupport) -set(MSVC_LIB_DEPS_LLVMBitWriter LLVMCore LLVMSupport LLVMSystem) +set(MSVC_LIB_DEPS_LLVMBitWriter LLVMCore LLVMSupport) set(MSVC_LIB_DEPS_LLVMBlackfinAsmPrinter LLVMAsmPrinter LLVMBlackfinInfo LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMBlackfinCodeGen LLVMBlackfinInfo LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMBlackfinInfo LLVMSupport) @@ -27,29 +27,28 @@ set(MSVC_LIB_DEPS_LLVMExecutionEngine LLVMCore LLVMSupport LLVMSystem LLVMTarget set(MSVC_LIB_DEPS_LLVMInstCombine LLVMAnalysis LLVMCore LLVMSupport LLVMSystem LLVMTarget LLVMTransformUtils) set(MSVC_LIB_DEPS_LLVMInstrumentation LLVMAnalysis LLVMCore LLVMSupport LLVMSystem LLVMTransformUtils) set(MSVC_LIB_DEPS_LLVMInterpreter LLVMCodeGen LLVMCore LLVMExecutionEngine LLVMSupport LLVMSystem LLVMTarget) -set(MSVC_LIB_DEPS_LLVMJIT LLVMAnalysis LLVMCodeGen LLVMCore LLVMExecutionEngine LLVMMC LLVMSupport LLVMSystem LLVMTarget) -set(MSVC_LIB_DEPS_LLVMLinker LLVMArchive LLVMBitReader LLVMCore LLVMSupport LLVMSystem) +set(MSVC_LIB_DEPS_LLVMJIT LLVMCodeGen LLVMCore LLVMExecutionEngine LLVMMC LLVMSupport LLVMSystem LLVMTarget) +set(MSVC_LIB_DEPS_LLVMLinker LLVMArchive LLVMBitReader LLVMCore LLVMSupport LLVMSystem LLVMTransformUtils) set(MSVC_LIB_DEPS_LLVMMBlazeAsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMBlazeCodeGen LLVMMBlazeInfo LLVMMC LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMMBlazeCodeGen LLVMCodeGen LLVMCore LLVMMBlazeInfo LLVMMC LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMMBlazeInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMMC LLVMSupport LLVMSystem) +set(MSVC_LIB_DEPS_LLVMMCDisassembler LLVMARMAsmParser LLVMARMCodeGen LLVMARMInfo LLVMAlphaAsmPrinter LLVMAlphaCodeGen LLVMAlphaInfo LLVMBlackfinAsmPrinter LLVMBlackfinCodeGen LLVMBlackfinInfo LLVMCBackend LLVMCBackendInfo LLVMCellSPUAsmPrinter LLVMCellSPUCodeGen LLVMCellSPUInfo LLVMCppBackend LLVMCppBackendInfo LLVMMBlazeAsmPrinter LLVMMBlazeCodeGen LLVMMBlazeInfo LLVMMC LLVMMCParser LLVMMSP430AsmPrinter LLVMMSP430CodeGen LLVMMSP430Info LLVMMipsAsmPrinter LLVMMipsCodeGen LLVMMipsInfo LLVMPIC16AsmPrinter LLVMPIC16CodeGen LLVMPIC16Info LLVMPowerPCAsmPrinter LLVMPowerPCCodeGen LLVMPowerPCInfo LLVMSparcAsmPrinter LLVMSparcCodeGen LLVMSparcInfo LLVMSupport LLVMSystem LLVMSystemZAsmPrinter LLVMSystemZCodeGen LLVMSystemZInfo LLVMX86AsmParser LLVMX86CodeGen LLVMX86Disassembler LLVMX86Info LLVMXCoreAsmPrinter LLVMXCoreCodeGen LLVMXCoreInfo) set(MSVC_LIB_DEPS_LLVMMCParser LLVMMC LLVMSupport) -set(MSVC_LIB_DEPS_LLVMMSIL LLVMAnalysis LLVMCodeGen LLVMCore LLVMMSILInfo LLVMScalarOpts LLVMSupport LLVMTarget LLVMTransformUtils LLVMipa) -set(MSVC_LIB_DEPS_LLVMMSILInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMMSP430AsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMMSP430Info LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMMSP430CodeGen LLVMCodeGen LLVMCore LLVMMC LLVMMSP430Info LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMMSP430Info LLVMSupport) set(MSVC_LIB_DEPS_LLVMMipsAsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMMipsCodeGen LLVMMipsInfo LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMMipsCodeGen LLVMCodeGen LLVMCore LLVMMC LLVMMipsInfo LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMMipsInfo LLVMSupport) -set(MSVC_LIB_DEPS_LLVMPIC16 LLVMAnalysis LLVMCodeGen LLVMCore LLVMMC LLVMPIC16Info LLVMSelectionDAG LLVMSupport LLVMTarget) -set(MSVC_LIB_DEPS_LLVMPIC16AsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMPIC16 LLVMPIC16Info LLVMSupport LLVMTarget) +set(MSVC_LIB_DEPS_LLVMPIC16AsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMPIC16CodeGen LLVMPIC16Info LLVMSupport LLVMTarget) +set(MSVC_LIB_DEPS_LLVMPIC16CodeGen LLVMAnalysis LLVMCodeGen LLVMCore LLVMMC LLVMPIC16Info LLVMSelectionDAG LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMPIC16Info LLVMSupport) -set(MSVC_LIB_DEPS_LLVMPowerPCAsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMPowerPCInfo LLVMSupport LLVMTarget) +set(MSVC_LIB_DEPS_LLVMPowerPCAsmPrinter LLVMAnalysis LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMPowerPCInfo LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMPowerPCCodeGen LLVMCodeGen LLVMCore LLVMMC LLVMPowerPCInfo LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMPowerPCInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMScalarOpts LLVMAnalysis LLVMCore LLVMInstCombine LLVMSupport LLVMSystem LLVMTarget LLVMTransformUtils) -set(MSVC_LIB_DEPS_LLVMSelectionDAG LLVMAnalysis LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMSystem LLVMTarget) +set(MSVC_LIB_DEPS_LLVMSelectionDAG LLVMAnalysis LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMSparcAsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSparcInfo LLVMSupport LLVMTarget) set(MSVC_LIB_DEPS_LLVMSparcCodeGen LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSparcInfo LLVMSupport LLVMSystem LLVMTarget) set(MSVC_LIB_DEPS_LLVMSparcInfo LLVMSupport) @@ -61,12 +60,12 @@ set(MSVC_LIB_DEPS_LLVMSystemZInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMTarget LLVMCore LLVMMC LLVMSupport) set(MSVC_LIB_DEPS_LLVMTransformUtils LLVMAnalysis LLVMCore LLVMSupport LLVMSystem LLVMTarget LLVMipa) set(MSVC_LIB_DEPS_LLVMX86AsmParser LLVMMC LLVMMCParser LLVMSupport LLVMTarget LLVMX86Info) -set(MSVC_LIB_DEPS_LLVMX86AsmPrinter LLVMAnalysis LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMTarget LLVMX86CodeGen LLVMX86Info) -set(MSVC_LIB_DEPS_LLVMX86CodeGen LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget LLVMX86Info) +set(MSVC_LIB_DEPS_LLVMX86AsmPrinter LLVMMC LLVMSupport) +set(MSVC_LIB_DEPS_LLVMX86CodeGen LLVMAnalysis LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMSystem LLVMTarget LLVMX86AsmPrinter LLVMX86Info) set(MSVC_LIB_DEPS_LLVMX86Disassembler LLVMMC LLVMSupport LLVMX86Info) set(MSVC_LIB_DEPS_LLVMX86Info LLVMSupport) -set(MSVC_LIB_DEPS_LLVMXCore LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMTarget LLVMXCoreInfo) set(MSVC_LIB_DEPS_LLVMXCoreAsmPrinter LLVMAsmPrinter LLVMCodeGen LLVMCore LLVMMC LLVMSupport LLVMTarget LLVMXCoreInfo) +set(MSVC_LIB_DEPS_LLVMXCoreCodeGen LLVMCodeGen LLVMCore LLVMMC LLVMSelectionDAG LLVMSupport LLVMTarget LLVMXCoreInfo) set(MSVC_LIB_DEPS_LLVMXCoreInfo LLVMSupport) set(MSVC_LIB_DEPS_LLVMipa LLVMAnalysis LLVMCore LLVMSupport LLVMSystem) -set(MSVC_LIB_DEPS_LLVMipo LLVMAnalysis LLVMCore LLVMSupport LLVMSystem LLVMTarget LLVMTransformUtils LLVMipa) +set(MSVC_LIB_DEPS_LLVMipo LLVMAnalysis LLVMCore LLVMScalarOpts LLVMSupport LLVMSystem LLVMTarget LLVMTransformUtils LLVMipa) diff --git a/cmake/modules/VersionFromVCS.cmake b/cmake/modules/VersionFromVCS.cmake new file mode 100644 index 00000000000..1016df22590 --- /dev/null +++ b/cmake/modules/VersionFromVCS.cmake @@ -0,0 +1,33 @@ +# Adds version control information to the variable VERS. For +# determining the Version Control System used (if any) it inspects the +# existence of certain subdirectories under CMAKE_CURRENT_SOURCE_DIR. + +function(add_version_info_from_vcs VERS) + set(result ${${VERS}}) + if( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.svn ) + set(result "${result}svn") + find_package(Subversion) + if( Subversion_FOUND ) + subversion_wc_info( ${CMAKE_CURRENT_SOURCE_DIR} Project ) + if( Project_WC_REVISION ) + set(result "${result}-r${Project_WC_REVISION}") + endif() + endif() + elseif( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git ) + set(result "${result}git") + # Try to get a ref-id + find_program(git_executable NAMES git git.exe git.cmd) + if( git_executable ) + execute_process(COMMAND ${git_executable} show-ref HEAD + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + TIMEOUT 5 + RESULT_VARIABLE git_result + OUTPUT_VARIABLE git_output) + if( git_result EQUAL 0 ) + string(SUBSTRING ${git_output} 0 7 git_ref_id) + set(result "${result}-${git_ref_id}") + endif() + endif() + endif() + set(${VERS} ${result} PARENT_SCOPE) +endfunction(add_version_info_from_vcs) diff --git a/configure b/configure index dc1b5b3fbe3..d2b98bfe661 100755 --- a/configure +++ b/configure @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.60 for llvm 2.8svn. +# Generated by GNU Autoconf 2.60 for llvm 2.8rc. # # Report bugs to . # @@ -561,8 +561,8 @@ SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='llvm' PACKAGE_TARNAME='-llvm-' -PACKAGE_VERSION='2.8svn' -PACKAGE_STRING='llvm 2.8svn' +PACKAGE_VERSION='2.8rc' +PACKAGE_STRING='llvm 2.8rc' PACKAGE_BUGREPORT='llvmbugs@cs.uiuc.edu' ac_unique_file="lib/VMCore/Module.cpp" @@ -703,8 +703,6 @@ ENABLE_BUILT_CLANG OPTIMIZE_OPTION EXTRA_OPTIONS BINUTILS_INCDIR -ENABLE_LLVMC_DYNAMIC -ENABLE_LLVMC_DYNAMIC_PLUGINS CXX CXXFLAGS ac_ct_CXX @@ -1320,7 +1318,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures llvm 2.8svn to adapt to many kinds of systems. +\`configure' configures llvm 2.8rc to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1386,7 +1384,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of llvm 2.8svn:";; + short | recursive ) echo "Configuration of llvm 2.8rc:";; esac cat <<\_ACEOF @@ -1416,17 +1414,13 @@ Optional Features: --enable-targets Build specific host targets: all or target1,target2,... Valid targets are: host, x86, x86_64, sparc, powerpc, alpha, arm, mips, spu, - pic16, xcore, msp430, systemz, blackfin, cbe, msil, - and cpp (default=all) + pic16, xcore, msp430, systemz, blackfin, cbe, and + cpp (default=all) --enable-cbe-printf-a Enable C Backend output with hex floating point via %a (default is YES) --enable-bindings Build specific language bindings: all,auto,none,{binding-name} (default=auto) --enable-libffi Check for the presence of libffi (default is NO) - --enable-llvmc-dynamic Link LLVMC dynamically (default is NO, unless on - Win32) - --enable-llvmc-dynamic-plugins - Enable dynamic LLVMC plugins (default is YES) --enable-ltdl-install install libltdl Optional Packages: @@ -1539,7 +1533,7 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -llvm configure 2.8svn +llvm configure 2.8rc generated by GNU Autoconf 2.60 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, @@ -1555,7 +1549,7 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by llvm $as_me 2.8svn, which was +It was created by llvm $as_me 2.8rc, which was generated by GNU Autoconf 2.60. Invocation command line was $ $0 $@ @@ -1988,7 +1982,6 @@ for i in `ls ${srcdir}/projects` do if test -d ${srcdir}/projects/${i} ; then case ${i} in - CVS) ;; sample) subdirs="$subdirs projects/sample" ;; privbracket) subdirs="$subdirs projects/privbracket" @@ -4691,7 +4684,7 @@ else fi -if test -d "CVS" -o -d "${srcdir}/CVS" -o -d ".svn" -o -d "${srcdir}/.svn" -o -d ".git" -o -d "${srcdir}/.git"; then +if test -d ".svn" -o -d "${srcdir}/.svn" -o -d ".git" -o -d "${srcdir}/.git"; then cvsbuild="yes" optimize="no" CVSBUILD=CVSBUILD=1 @@ -4706,7 +4699,7 @@ fi if test "${enable_optimized+set}" = set; then enableval=$enable_optimized; else - enableval=$optimize + enableval="yes" fi if test ${enableval} = "no" ; then @@ -4736,7 +4729,7 @@ fi if test "${enable_assertions+set}" = set; then enableval=$enable_assertions; else - enableval="yes" + enableval="no" fi if test ${enableval} = "yes" ; then @@ -4962,7 +4955,7 @@ if test "$enableval" = host-only ; then enableval=host fi case "$enableval" in - all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha ARM Mips CellSPU PIC16 XCore MSP430 SystemZ Blackfin CBackend MSIL CppBackend MBlaze" ;; + all) TARGETS_TO_BUILD="X86 Sparc PowerPC Alpha ARM Mips CellSPU PIC16 XCore MSP430 SystemZ Blackfin CBackend CppBackend MBlaze" ;; *)for a_target in `echo $enableval|sed -e 's/,/ /g' ` ; do case "$a_target" in x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;; @@ -4979,7 +4972,6 @@ case "$enableval" in systemz) TARGETS_TO_BUILD="SystemZ $TARGETS_TO_BUILD" ;; blackfin) TARGETS_TO_BUILD="Blackfin $TARGETS_TO_BUILD" ;; cbe) TARGETS_TO_BUILD="CBackend $TARGETS_TO_BUILD" ;; - msil) TARGETS_TO_BUILD="MSIL $TARGETS_TO_BUILD" ;; cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;; mblaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;; host) case "$llvm_cv_target_arch" in @@ -5015,10 +5007,27 @@ TARGETS_TO_BUILD=$TARGETS_TO_BUILD # If so, define LLVM_NATIVE_ARCH to that LLVM target. for a_target in $TARGETS_TO_BUILD; do if test "$a_target" = "$LLVM_NATIVE_ARCH"; then - LLVM_NATIVE_ARCHTARGET="${LLVM_NATIVE_ARCH}Target" cat >>confdefs.h <<_ACEOF -#define LLVM_NATIVE_ARCH $LLVM_NATIVE_ARCHTARGET +#define LLVM_NATIVE_ARCH $LLVM_NATIVE_ARCH +_ACEOF + + LLVM_NATIVE_TARGET="LLVMInitialize${LLVM_NATIVE_ARCH}Target" + LLVM_NATIVE_TARGETINFO="LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo" + LLVM_NATIVE_ASMPRINTER="LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter" + +cat >>confdefs.h <<_ACEOF +#define LLVM_NATIVE_TARGET $LLVM_NATIVE_TARGET +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define LLVM_NATIVE_TARGETINFO $LLVM_NATIVE_TARGETINFO +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define LLVM_NATIVE_ASMPRINTER $LLVM_NATIVE_ASMPRINTER _ACEOF fi @@ -5374,42 +5383,6 @@ else fi -if test "$llvm_cv_os_type" = "Win32" ; then - llvmc_dynamic="yes" -else - llvmc_dynamic="no" -fi - -# Check whether --enable-llvmc-dynamic was given. -if test "${enable_llvmc_dynamic+set}" = set; then - enableval=$enable_llvmc_dynamic; -else - enableval=$llvmc_dynamic -fi - -if test ${enableval} = "yes" && test "$ENABLE_PIC" -eq 1 ; then - ENABLE_LLVMC_DYNAMIC=ENABLE_LLVMC_DYNAMIC=1 - -else - ENABLE_LLVMC_DYNAMIC= - -fi - -# Check whether --enable-llvmc-dynamic-plugins was given. -if test "${enable_llvmc_dynamic_plugins+set}" = set; then - enableval=$enable_llvmc_dynamic_plugins; -else - enableval=yes -fi - -if test ${enableval} = "yes" ; then - ENABLE_LLVMC_DYNAMIC_PLUGINS=ENABLE_LLVMC_DYNAMIC_PLUGINS=1 - -else - ENABLE_LLVMC_DYNAMIC_PLUGINS= - -fi - ac_ext=c ac_cpp='$CPP $CPPFLAGS' @@ -8004,6 +7977,10 @@ test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' +case "$INSTALL" in + [\\/$]* | ?:[\\/]* ) ;; + *) INSTALL="\\\$(TOPSRCDIR)/$INSTALL" ;; +esac # Extract the first word of "bzip2", so it can be a program name with args. set dummy bzip2; ac_word=$2 @@ -8721,6 +8698,31 @@ fi done +{ echo "$as_me:$LINENO: checking for linker version" >&5 +echo $ECHO_N "checking for linker version... $ECHO_C" >&6; } +if test "${llvm_cv_link_version+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + + version_string="$(ld -v 2>&1 | head -1)" + + # Check for ld64. + if (echo "$version_string" | grep -q "ld64"); then + llvm_cv_link_version=$(echo "$version_string" | sed -e "s#.*ld64-\([^ ]*\)#\1#") + else + llvm_cv_link_version=$(echo "$version_string" | sed -e "s#[^0-9]*\([0-9.]*\).*#\1#") + fi + +fi +{ echo "$as_me:$LINENO: result: $llvm_cv_link_version" >&5 +echo "${ECHO_T}$llvm_cv_link_version" >&6; } + +cat >>confdefs.h <<_ACEOF +#define HOST_LINK_VERSION "$llvm_cv_link_version" +_ACEOF + + + { echo "$as_me:$LINENO: checking for compiler -Wl,-R option" >&5 echo $ECHO_N "checking for compiler -Wl,-R option... $ECHO_C" >&6; } if test "${llvm_cv_link_use_r+set}" = set; then @@ -11387,7 +11389,7 @@ else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <&5 echo $ECHO_N "checking for GCC atomic builtins... $ECHO_C" >&6; } +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -20041,6 +20049,12 @@ eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + { echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6; } @@ -20067,7 +20081,6 @@ rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext - if test "$llvm_cv_os_type" = "Linux" -a "$llvm_cv_target_arch" = "x86_64" ; then { echo "$as_me:$LINENO: checking for 32-bit userspace on 64-bit system" >&5 echo $ECHO_N "checking for 32-bit userspace on 64-bit system... $ECHO_C" >&6; } @@ -20563,7 +20576,12 @@ fi -ac_config_headers="$ac_config_headers include/llvm/Config/config.h" +ac_config_headers="$ac_config_headers include/llvm/Config/config.h include/llvm/Config/llvm-config.h" + + + + + ac_config_files="$ac_config_files include/llvm/Config/Targets.def" @@ -20582,7 +20600,7 @@ ac_config_files="$ac_config_files Makefile.config" ac_config_files="$ac_config_files llvm.spec" -ac_config_files="$ac_config_files tools/llvmc/plugins/Base/Base.td" +ac_config_files="$ac_config_files tools/llvmc/src/Base.td" ac_config_files="$ac_config_files tools/llvm-config/llvm-config.in" @@ -21027,7 +21045,7 @@ exec 6>&1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by llvm $as_me 2.8svn, which was +This file was extended by llvm $as_me 2.8rc, which was generated by GNU Autoconf 2.60. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -21080,7 +21098,7 @@ Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF ac_cs_version="\\ -llvm config.status 2.8svn +llvm config.status 2.8rc configured by $0, generated by GNU Autoconf 2.60, with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" @@ -21194,6 +21212,7 @@ for ac_config_target in $ac_config_targets do case $ac_config_target in "include/llvm/Config/config.h") CONFIG_HEADERS="$CONFIG_HEADERS include/llvm/Config/config.h" ;; + "include/llvm/Config/llvm-config.h") CONFIG_HEADERS="$CONFIG_HEADERS include/llvm/Config/llvm-config.h" ;; "include/llvm/Config/Targets.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/Targets.def" ;; "include/llvm/Config/AsmPrinters.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/AsmPrinters.def" ;; "include/llvm/Config/AsmParsers.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/AsmParsers.def" ;; @@ -21201,7 +21220,7 @@ do "include/llvm/System/DataTypes.h") CONFIG_HEADERS="$CONFIG_HEADERS include/llvm/System/DataTypes.h" ;; "Makefile.config") CONFIG_FILES="$CONFIG_FILES Makefile.config" ;; "llvm.spec") CONFIG_FILES="$CONFIG_FILES llvm.spec" ;; - "tools/llvmc/plugins/Base/Base.td") CONFIG_FILES="$CONFIG_FILES tools/llvmc/plugins/Base/Base.td" ;; + "tools/llvmc/src/Base.td") CONFIG_FILES="$CONFIG_FILES tools/llvmc/src/Base.td" ;; "tools/llvm-config/llvm-config.in") CONFIG_FILES="$CONFIG_FILES tools/llvm-config/llvm-config.in" ;; "setup") CONFIG_COMMANDS="$CONFIG_COMMANDS setup" ;; "Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS Makefile" ;; @@ -21421,8 +21440,6 @@ ENABLE_BUILT_CLANG!$ENABLE_BUILT_CLANG$ac_delim OPTIMIZE_OPTION!$OPTIMIZE_OPTION$ac_delim EXTRA_OPTIONS!$EXTRA_OPTIONS$ac_delim BINUTILS_INCDIR!$BINUTILS_INCDIR$ac_delim -ENABLE_LLVMC_DYNAMIC!$ENABLE_LLVMC_DYNAMIC$ac_delim -ENABLE_LLVMC_DYNAMIC_PLUGINS!$ENABLE_LLVMC_DYNAMIC_PLUGINS$ac_delim CXX!$CXX$ac_delim CXXFLAGS!$CXXFLAGS$ac_delim ac_ct_CXX!$ac_ct_CXX$ac_delim @@ -21514,7 +21531,7 @@ LIBOBJS!$LIBOBJS$ac_delim LTLIBOBJS!$LTLIBOBJS$ac_delim _ACEOF - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 95; then + if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 93; then break elif $ac_last_try; then { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 diff --git a/docs/AliasAnalysis.html b/docs/AliasAnalysis.html index a23d90848e4..cffaa820622 100644 --- a/docs/AliasAnalysis.html +++ b/docs/AliasAnalysis.html @@ -238,10 +238,10 @@ a location, ModRef is returned.

The AliasAnalysis class also provides a getModRefInfo method for testing dependencies between function calls. This method takes two -call sites (CS1 & CS2), returns NoModRef if the two calls refer to disjoint -memory locations, Ref if CS1 reads memory written by CS2, Mod if CS1 writes to -memory read or written by CS2, or ModRef if CS1 might read or write memory -accessed by CS2. Note that this relation is not commutative.

+call sites (CS1 & CS2), returns NoModRef if neither call writes to memory +read or written by the other, Ref if CS1 reads memory written by CS2, Mod if CS1 +writes to memory read or written by CS2, or ModRef if CS1 might read or write +memory written to by CS2. Note that this relation is not commutative.

@@ -998,7 +998,7 @@ analysis directly.

Chris Lattner
LLVM Compiler Infrastructure
- Last modified: $Date: 2010-07-07 16:27:09 +0200 (Wed, 07 Jul 2010) $ + Last modified: $Date: 2010-08-31 01:47:24 +0200 (Tue, 31 Aug 2010) $ diff --git a/docs/BitCodeFormat.html b/docs/BitCodeFormat.html index f1f175d7055..bd53a1edd76 100644 --- a/docs/BitCodeFormat.html +++ b/docs/BitCodeFormat.html @@ -1367,21 +1367,6 @@ type to the type table.

- - - -
- -

[UNION, ...eltty...]

- -

The UNION record (code 17) adds a union type to -the type table. The eltty operand fields are zero or more type -indices representing the element types of the union. -

- -
- @@ -1489,7 +1474,7 @@ name. Each entry corresponds to a single named type. src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"> Chris Lattner
The LLVM Compiler Infrastructure
-Last modified: $Date: 2010-05-22 00:20:54 +0200 (Sat, 22 May 2010) $ +Last modified: $Date: 2010-08-28 06:09:24 +0200 (Sat, 28 Aug 2010) $ diff --git a/docs/CMake.html b/docs/CMake.html index 40a2cec8e91..ca0b50f628e 100644 --- a/docs/CMake.html +++ b/docs/CMake.html @@ -313,9 +313,15 @@
-

LLVM testing is not supported on Visual Studio.

+

Testing is performed when the check target is built. For + instance, if you are using makefiles, execute this command while on + the top level of your build directory:

-

TODO

+
+

make check

+
+ +

Testing is not supported on Visual Studio.

@@ -348,7 +354,38 @@
-

TODO

+

The most difficult part of adding LLVM to the build of a project + is to determine the set of LLVM libraries corresponding to the set + of required LLVM features. What follows is an example of how to + obtain this information:

+ +
+
+    # A convenience variable:
+    set(LLVM_ROOT "" CACHE PATH "Root of LLVM install.")
+    # A bit of a sanity check:
+    if( NOT EXISTS ${LLVM_ROOT}/include/llvm )
+    message(FATAL_ERROR "LLVM_ROOT (${LLVM_ROOT}) is not a valid LLVM install")
+    endif()
+    # We incorporate the CMake features provided by LLVM:
+    set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${LLVM_ROOT}/share/llvm/cmake")
+    include(LLVM)
+    # Now set the header and library paths:
+    include_directories( ${LLVM_ROOT}/include )
+    link_directories( ${LLVM_ROOT}/lib )
+    # Let's suppose we want to build a JIT compiler with support for
+    # binary code (no interpreter):
+    llvm_map_components_to_libraries(REQ_LLVM_LIBRARIES jit native)
+    # Finally, we link the LLVM libraries to our executable:
+    target_link_libraries(mycompiler ${REQ_LLVM_LIBRARIES})
+    
+
+ +

This assumes that LLVM_ROOT points to an install of LLVM. The + procedure works too for uninstalled builds although we need to take + care to add an include_directories for the location of the + headers on the LLVM source directory (if we are building + out-of-source.)

@@ -377,7 +414,7 @@ Oscar Fuentes
LLVM Compiler Infrastructure
- Last modified: $Date: 2008-12-31 03:59:36 +0100 (Wed, 31 Dec 2008) $ + Last modified: $Date: 2010-08-09 03:59:36 +0100 (Mon, 9 Aug 2010) $ diff --git a/docs/CodeGenerator.html b/docs/CodeGenerator.html index 407178777a3..4b2e261094b 100644 --- a/docs/CodeGenerator.html +++ b/docs/CodeGenerator.html @@ -1457,8 +1457,8 @@ bool RegMapping_Fer::compatible_class(MachineFunction &mf, order to get and store values in memory. To assign a physical register to a virtual register present in a given operand, use MachineOperand::setReg(p_reg). To insert a store instruction, - use TargetRegisterInfo::storeRegToStackSlot(...), and to insert a - load instruction, use TargetRegisterInfo::loadRegFromStackSlot.

+ use TargetInstrInfo::storeRegToStackSlot(...), and to insert a + load instruction, use TargetInstrInfo::loadRegFromStackSlot.

The indirect mapping shields the application developer from the complexities of inserting load and store instructions. In order to map a virtual register @@ -2162,7 +2162,7 @@ MOVSX32rm16 -> movsx, 32-bit register, 16-bit memory Chris Lattner
The LLVM Compiler Infrastructure
- Last modified: $Date: 2010-06-15 23:58:33 +0200 (Tue, 15 Jun 2010) $ + Last modified: $Date: 2010-09-01 00:01:07 +0200 (Wed, 01 Sep 2010) $ diff --git a/docs/CommandGuide/bugpoint.pod b/docs/CommandGuide/bugpoint.pod index 7afeea1aba5..1870a0d84b6 100644 --- a/docs/CommandGuide/bugpoint.pod +++ b/docs/CommandGuide/bugpoint.pod @@ -67,6 +67,10 @@ tool. Pass all arguments specified after B<--gcc-tool-args> to the invocation of B. +=item B<--opt-args> I + +Pass all arguments specified after B<--opt-args> to the invocation of B. + =item B<--disable-{dce,simplifycfg}> Do not run the specified passes to clean up and reduce the size of the test diff --git a/docs/CommandGuide/index.html b/docs/CommandGuide/index.html index 62cb7765a47..67f0cfc1a11 100644 --- a/docs/CommandGuide/index.html +++ b/docs/CommandGuide/index.html @@ -72,6 +72,9 @@ options) arguments to the tool you are interested in.

  • llvmc - a generic customizable compiler driver
  • +
  • llvm-diff - + structurally compare two modules
  • + @@ -148,7 +151,7 @@ options) arguments to the tool you are interested in.

    src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"> LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-05-11 18:47:42 +0200 (Tue, 11 May 2010) $ + Last modified: $Date: 2010-09-08 01:32:02 +0200 (Wed, 08 Sep 2010) $ diff --git a/docs/CommandGuide/llvm-diff.pod b/docs/CommandGuide/llvm-diff.pod new file mode 100644 index 00000000000..c8cfdb3be94 --- /dev/null +++ b/docs/CommandGuide/llvm-diff.pod @@ -0,0 +1,53 @@ +=pod + +=head1 NAME + +llvm-diff - LLVM structural 'diff' + +=head1 SYNOPSIS + +B [I] I I [I] + +=head1 DESCRIPTION + +B compares the structure of two LLVM modules, primarily +focusing on differences in function definitions. Insignificant +differences, such as changes in the ordering of globals or in the +names of local values, are ignored. + +An input module will be interpreted as an assembly file if its name +ends in '.ll'; otherwise it will be read in as a bitcode file. + +If a list of global names is given, just the values with those names +are compared; otherwise, all global values are compared, and +diagnostics are produced for globals which only appear in one module +or the other. + +B compares two functions by comparing their basic blocks, +beginning with the entry blocks. If the terminators seem to match, +then the corresponding successors are compared; otherwise they are +ignored. This algorithm is very sensitive to changes in control flow, +which tend to stop any downstream changes from being detected. + +B is intended as a debugging tool for writers of LLVM +passes and frontends. It does not have a stable output format. + +=head1 EXIT STATUS + +If B finds no differences between the modules, it will exit +with 0 and produce no output. Otherwise it will exit with a non-zero +value. + +=head1 BUGS + +Many important differences, like changes in linkage or function +attributes, are not diagnosed. + +Changes in memory behavior (for example, coalescing loads) can cause +massive detected differences in blocks. + +=head1 AUTHORS + +Maintained by the LLVM Team (L). + +=cut diff --git a/docs/DeveloperPolicy.html b/docs/DeveloperPolicy.html index 37bfb8990e0..47352009ea0 100644 --- a/docs/DeveloperPolicy.html +++ b/docs/DeveloperPolicy.html @@ -43,7 +43,8 @@ is to eliminate miscommunication, rework, and confusion that might arise from the distributed nature of LLVM's development. By stating the policy in clear terms, we hope each developer can know ahead of time what to expect when - making LLVM contributions.

    + making LLVM contributions. This policy covers all llvm.org subprojects, + including Clang, LLDB, etc.

    This policy is also designed to accomplish the following objectives:

      @@ -77,17 +78,28 @@
      -

      Developers should stay informed by reading at least the - llvmdev email - list. If you are doing anything more than just casual work on LLVM, it is - suggested that you also subscribe to the - llvm-commits - list and pay attention to changes being made by others.

      +

      Developers should stay informed by reading at least the "dev" mailing list + for the projects you are interested in, such as + llvmdev for + LLVM, cfe-dev + for Clang, or lldb-dev + for LLDB. If you are doing anything more than just casual work on LLVM, it + is suggested that you also subscribe to the "commits" mailing list for the + subproject you're interested in, such as + llvm-commits, + cfe-commits, + or lldb-commits. + Reading the "commits" list and paying attention to changes being made by + others is a good way to see what other people are interested in and watching + the flow of the project as a whole.

      We recommend that active developers register an email account with LLVM Bugzilla and preferably subscribe to the llvm-bugs - email list to keep track of bugs and enhancements occurring in LLVM.

      + email list to keep track of bugs and enhancements occurring in LLVM. We + really appreciate people who are proactive at catching incoming bugs in their + components and dealing with them promptly.

      @@ -107,18 +119,13 @@ patches may not apply correctly if the underlying code changes between the time the patch was created and the time it is applied. -
    1. Patches should be made with this command: -
      -
      -svn diff
      -
      -
      - or with the utility utils/mkpatch, which makes it easy to read - the diff.
    2. +
    3. Patches should be made with svn diff, or similar. If you use + a different tool, make sure it uses the diff -u format and + that it doesn't contain clutter which makes it hard to read.
    4. -
    5. Patches should not include differences in generated code such as the code - generated by autoconf or tblgen. The - utils/mkpatch utility takes care of this for you.
    6. +
    7. If you are modifying generated files, such as the top-level + configure script, please separate out those changes into + a separate patch from the rest of your changes.

    When sending a patch to a mailing list, it is a good idea to send it as an @@ -239,8 +246,9 @@ svn diff them short. -

    Note that llvm/test is designed for regression and small feature tests - only. More extensive test cases (e.g., entire applications, benchmarks, etc) +

    Note that llvm/test and clang/test are designed for regression and small + feature tests only. More extensive test cases (e.g., entire applications, + benchmarks, etc) should be added to the llvm-test test suite. The llvm-test suite is for coverage (correctness, performance, etc) testing, not feature or regression testing.

    @@ -263,7 +271,7 @@ svn diff testcase so we know if the fix/feature ever regresses in the future. -
  • Code must pass the dejagnu (llvm/test) test suite.
  • +
  • Code must pass the llvm/test test suite.
  • The code must not cause regressions on a reasonable subset of llvm-test, where "reasonable" depends on the contributor's judgement and the scope of @@ -601,7 +609,7 @@ Changes Written by the LLVM Oversight Group
    The LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-05-07 02:28:04 +0200 (Fri, 07 May 2010) $ + Last modified: $Date: 2010-09-02 02:09:17 +0200 (Thu, 02 Sep 2010) $ diff --git a/docs/GCCFEBuildInstrs.html b/docs/GCCFEBuildInstrs.html index f4eccf79a2a..0b2827c9d5c 100644 --- a/docs/GCCFEBuildInstrs.html +++ b/docs/GCCFEBuildInstrs.html @@ -84,7 +84,7 @@ top-level README.LLVM file, adding ",ada" to EXTRALANGS, for example:
  • The build requires having a compiler that supports Ada, C and C++. The Ada front-end is written in Ada so an Ada compiler is needed to build it. Compilers known to work with the - LLVM 2.5 release + LLVM 2.7 release are gcc-4.2 and the 2005, 2006 and 2007 versions of the GNAT GPL Edition. @@ -116,9 +116,9 @@ top-level README.LLVM file, adding ",ada" to EXTRALANGS, for example: and unpack it:

    -wget http://llvm.org/releases/2.5/llvm-2.5.tar.gz
    -tar xzf llvm-2.5.tar.gz
    -mv llvm-2.5 llvm
    +wget http://llvm.org/releases/2.7/llvm-2.7.tgz
    +tar xzf llvm-2.7.tgz
    +mv llvm-2.7 llvm
     

    or check out the @@ -133,9 +133,9 @@ mv llvm-2.5 llvm and unpack it:

    -wget http://llvm.org/releases/2.5/llvm-gcc-4.2-2.5.source.tar.gz
    -tar xzf llvm-gcc-4.2-2.5.source.tar.gz
    -mv llvm-gcc4.2-2.5.source llvm-gcc-4.2
    +wget http://llvm.org/releases/2.7/llvm-gcc-4.2-2.7.source.tgz
    +tar xzf llvm-gcc-4.2-2.7.source.tgz
    +mv llvm-gcc-4.2-2.7.source llvm-gcc-4.2
     

    or check out the @@ -272,7 +272,7 @@ More information is available in the FAQ. src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"> LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-05-07 02:28:04 +0200 (Fri, 07 May 2010) $ + Last modified: $Date: 2010-08-31 21:40:21 +0200 (Tue, 31 Aug 2010) $ diff --git a/docs/GetElementPtr.html b/docs/GetElementPtr.html index aa874ae4751..d840c9788ac 100644 --- a/docs/GetElementPtr.html +++ b/docs/GetElementPtr.html @@ -26,7 +26,6 @@

  • Why don't GEP x,0,0,1 and GEP x,1 alias?
  • Why do GEP x,1,0,0 and GEP x,1 alias?
  • Can GEP index into vector elements? -
  • Can GEP index into unions?
  • What effect do address spaces have on GEPs?
  • How is GEP different from ptrtoint, arithmetic, and inttoptr?
  • I'm writing a backend for a target which needs custom lowering for GEP. How do I do this? @@ -369,16 +368,6 @@ idx3 = (char*) &MyVar + 8 - -
    -

    Unknown.

    - -
    - - - @@ -730,7 +719,7 @@ idx3 = (char*) &MyVar + 8 Valid HTML 4.01 The LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-07-06 17:26:33 +0200 (Tue, 06 Jul 2010) $ + Last modified: $Date: 2010-08-28 06:09:24 +0200 (Sat, 28 Aug 2010) $ diff --git a/docs/GoldPlugin.html b/docs/GoldPlugin.html index 66e099bad0a..3f2e9fb2e64 100644 --- a/docs/GoldPlugin.html +++ b/docs/GoldPlugin.html @@ -79,7 +79,7 @@ placed. the plugin .so file. To find out what link command gcc would run in a given situation, run gcc -v [...] and look for the line where it runs collect2. Replace that with - ld-new -plugin /path/to/libLLVMgold.so to test it out. Once you're + ld-new -plugin /path/to/LLVMgold.so to test it out. Once you're ready to switch to using gold, backup your existing /usr/bin/ld then replace it with ld-new.

    You can produce bitcode files from llvm-gcc using @@ -91,7 +91,7 @@ placed. linker, which is why you need gold to be the installed system linker in your path.

    If you want ar and nm to work seamlessly as well, install - libLLVMgold.so to /usr/lib/bfd-plugins. If you built your + LLVMgold.so to /usr/lib/bfd-plugins. If you built your own gold, be sure to install the ar and nm-new you built to /usr/bin.

    @@ -157,9 +157,9 @@ $ llvm-gcc -use-gold-plugin a.a b.o -o main # <-- link with LLVMgold plugin bitcode, everything is in place for an easy to use LTO build of autotooled projects:

      -
    • Follow the instructions on how to build libLLVMgold.so.
    • +
    • Follow the instructions on how to build LLVMgold.so.
    • Install the newly built binutils to $PREFIX
    • -
    • Copy Release/lib/libLLVMgold.so to +
    • Copy Release/lib/LLVMgold.so to $PREFIX/libexec/gcc/x86_64-unknown-linux-gnu/4.2.1/ and $PREFIX/lib/bfd-plugins/
    • Set environment variables ($PREFIX is where you installed llvm-gcc and diff --git a/docs/LangRef.html b/docs/LangRef.html index 4b4348d07f2..b717531e347 100644 --- a/docs/LangRef.html +++ b/docs/LangRef.html @@ -25,6 +25,7 @@
    • 'private' Linkage
    • 'linker_private' Linkage
    • 'linker_private_weak' Linkage
    • +
    • 'linker_private_weak_def_auto' Linkage
    • 'internal' Linkage
    • 'available_externally' Linkage
    • 'linkonce' Linkage
    • @@ -73,7 +74,6 @@
    • Array Type
    • Structure Type
    • Packed Structure Type
    • -
    • Union Type
    • Vector Type
    • @@ -491,20 +491,21 @@ the "hello world" module:

      -; Declare the string constant as a global constant.
      -@.LC0 = internal constant [13 x i8] c"hello world\0A\00"    ; [13 x i8]*
      +; Declare the string constant as a global constant. 
      +@.LC0 = internal constant [13 x i8] c"hello world\0A\00"      ; [13 x i8]* 
       
      -; External declaration of the puts function
      -declare i32 @puts(i8*)                                     ; i32 (i8*)* 
      +; External declaration of the puts function 
      +declare i32 @puts(i8*)                                      ; i32 (i8*)*  
       
       ; Definition of main function
      -define i32 @main() {                                        ; i32()* 
      -  ; Convert [13 x i8]* to i8  *...
      -  %cast210 = getelementptr [13 x i8]* @.LC0, i64 0, i64 0   ; i8*
      +define i32 @main() {   ; i32()*  
      +  ; Convert [13 x i8]* to i8  *... 
      +  %cast210 = getelementptr [13 x i8]* @.LC0, i64 0, i64 0   ; i8* 
       
      -  ; Call puts function to write out the string to stdout.
      -  call i32 @puts(i8* %cast210)                             ; i32
      -  ret i32 0
      } + ; Call puts function to write out the string to stdout.  + call i32 @puts(i8* %cast210) ; i32  + ret i32 0  +} ; Named metadata !1 = metadata !{i32 41} @@ -556,6 +557,15 @@ define i32 @main() { ; i32()* linker. The symbols are removed by the linker from the final linked image (executable or dynamic library). +
      linker_private_weak_def_auto
      +
      Similar to "linker_private_weak", but it's known that the address + of the object is not taken. For instance, functions that had an inline + definition, but the compiler decided not to inline it. Note, + unlike linker_private and linker_private_weak, + linker_private_weak_def_auto may have only default + visibility. The symbols are removed by the linker from the final linked + image (executable or dynamic library).
      +
      internal
      Similar to private, but the value shows as a local symbol (STB_LOCAL in the case of ELF) in the object file. This @@ -788,7 +798,7 @@ define i32 @main() { ; i32()*

      You may give a name to any type except - "void". Type name aliases may be used anywhere a type + "void". Type name aliases may be used anywhere a type is expected with the syntax "%mytype".

      Note that type names are aliases for the structural type that they indicate, @@ -949,15 +959,17 @@ define [linkage] [visibility]

      Named metadata is a collection of metadata. Metadata - nodes (but not metadata strings) and null are the only valid operands for + nodes (but not metadata strings) are the only valid operands for a named metadata.

      Syntax:
      -; An unnamed metadata node, which is referenced by the named metadata.
      +; Some unnamed metadata nodes, which are referenced by the named metadata.
      +!0 = metadata !{metadata !"zero"}
       !1 = metadata !{metadata !"one"}
      +!2 = metadata !{metadata !"two"}
       ; A named metadata.
      -!name = !{null, !1}
      +!name = !{!0, !1, !2}
       
      @@ -1462,7 +1474,6 @@ Classifications pointer, vector, structure, - union, array, label, metadata. @@ -1482,7 +1493,6 @@ Classifications pointer, structure, packed structure, - union, vector, opaque. @@ -1630,8 +1640,8 @@ Classifications

      Aggregate Types are a subset of derived types that can contain multiple member types. Arrays, - structs, vectors and - unions are aggregate types.

      + structs, and vectors are + aggregate types.

      @@ -1701,9 +1711,7 @@ Classifications
      Overview:

      The function type can be thought of as a function signature. It consists of a return type and a list of formal parameter types. The return type of a - function type is a scalar type, a void type, a struct type, or a union - type. If the return type is a struct type then all struct elements must be - of first class types, and the struct must have at least one element.

      + function type is a first class type or a void type.

      Syntax:
      @@ -1824,53 +1832,6 @@ Classifications 
       
       
       
      -
      -
      -
      -
      - -
      Overview:
      -

      A union type describes an object with size and alignment suitable for - an object of any one of a given set of types (also known as an "untagged" - union). It is similar in concept and usage to a - struct, except that all members of the union - have an offset of zero. The elements of a union may be any type that has a - size. Unions must have at least one member - empty unions are not allowed. -

      - -

      The size of the union as a whole will be the size of its largest member, - and the alignment requirements of the union as a whole will be the largest - alignment requirement of any member.

      - -

      Union members are accessed using 'load and - 'store' by getting a pointer to a field with - the 'getelementptr' instruction. - Since all members are at offset zero, the getelementptr instruction does - not affect the address, only the type of the resulting pointer.

      - -
      Syntax:
      -
      -  union { <type list> }
      -
      - -
      Examples:
      - - - - - - - - -
      union { i32, i32*, float }A union of three types: an i32, a pointer to - an i32, and a float.
      - union { float, i32 (i32) * }A union, where the first element is a float and the - second element is a pointer to a - function that takes an i32, returning - an i32.
      - -
      - @@ -2112,14 +2073,6 @@ Classifications the number and types of elements must match those specified by the type. -
      Union constants
      -
      Union constants are represented with notation similar to a structure with - a single element - that is, a single typed element surrounded - by braces ({})). For example: "{ i32 4 }". The - union type can be initialized with a single-element - struct as long as the type of the struct element matches the type of - one of the union members.
      -
      Array constants
      Array constants are represented with notation similar to array type definitions (a comma separated list of elements, surrounded by square @@ -4140,7 +4093,7 @@ Instruction
      Arguments:

      The first operand of an 'extractvalue' instruction is a value - of struct, union or + of struct or array type. The operands are constant indices to specify which value to extract in a similar manner as indices in a 'getelementptr' instruction.

      @@ -4174,7 +4127,7 @@ Instruction
      Arguments:

      The first operand of an 'insertvalue' instruction is a value - of struct, union or + of struct or array type. The second operand is a first-class value to insert. The following operands are constant indices indicating the position at which to insert the value in a similar manner as indices in a @@ -4407,12 +4360,12 @@ Instruction indexes a value of the type pointed to (not necessarily the value directly pointed to, since the first index can be non-zero), etc. The first type indexed into must be a pointer value, subsequent types can be arrays, - vectors, structs and unions. Note that subsequent types being indexed into + vectors, and structs. Note that subsequent types being indexed into can never be pointers, since that would require loading the pointer before continuing calculation.

      The type of each index argument depends on the type it is indexing into. - When indexing into a (optionally packed) structure or union, only i32 + When indexing into a (optionally packed) structure, only i32 integer constants are allowed. When indexing into an array, pointer or vector, integers of any width are allowed, and they are not required to be constant.

      @@ -6117,8 +6070,8 @@ LLVM.

      Syntax:

      This is an overloaded intrinsic. You can use llvm.memset on any integer bit - width and for different address spaces. Not all targets support all bit - widths however.

      + width and for different address spaces. However, not all targets support all + bit widths.

         declare void @llvm.memset.p0i8.i32(i8* <dest>, i8 <val>,
      @@ -6132,14 +6085,14 @@ LLVM.

      particular byte value.

      Note that, unlike the standard libc function, the llvm.memset - intrinsic does not return a value, takes extra alignment/volatile arguments, - and the destination can be in an arbitrary address space.

      + intrinsic does not return a value and takes extra alignment/volatile + arguments. Also, the destination can be in an arbitrary address space.

      Arguments:

      The first argument is a pointer to the destination to fill, the second is the - byte value to fill it with, the third argument is an integer argument + byte value with which to fill it, the third argument is an integer argument specifying the number of bytes to fill, and the fourth argument is the known - alignment of destination location.

      + alignment of the destination location.

      If the call to this intrinsic has an alignment value that is not 0 or 1, then the caller guarantees that the destination pointer is aligned to that @@ -7746,7 +7699,7 @@ LLVM.

      Chris Lattner
      The LLVM Compiler Infrastructure
      - Last modified: $Date: 2010-07-13 21:48:13 +0200 (Tue, 13 Jul 2010) $ + Last modified: $Date: 2010-08-28 06:09:24 +0200 (Sat, 28 Aug 2010) $ diff --git a/docs/MakefileGuide.html b/docs/MakefileGuide.html index dd904786600..38b7ae19fa6 100644 --- a/docs/MakefileGuide.html +++ b/docs/MakefileGuide.html @@ -785,6 +785,9 @@ not.
      PROJ_SRC_DIR
      The directory which contains the source files to be built.
      +
      BUILD_EXAMPLES
      +
      If set to 1, build examples in examples and (if building + Clang) tools/clang/examples directories.
      BZIP2(configured)
      The path to the bzip2 tool.
      CC(configured)
      @@ -1025,7 +1028,7 @@ Reid Spencer
      The LLVM Compiler Infrastructure
      - Last modified: $Date: 2010-07-07 09:48:00 +0200 (Wed, 07 Jul 2010) $ + Last modified: $Date: 2010-07-24 19:54:00 +0200 (Sat, 24 Jul 2010) $ diff --git a/docs/Passes.html b/docs/Passes.html index 70d909796e6..0358745f79f 100644 --- a/docs/Passes.html +++ b/docs/Passes.html @@ -120,6 +120,7 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if ! -print-used-typesFind Used Types -profile-estimatorEstimate profiling information -profile-loaderLoad profile information from llvmprof.out +-regionsDetect single entry single exit regions in a function -profile-verifierVerify profiling information -scalar-evolutionScalar Evolution Analysis -scev-aaScalarEvolution-based Alias Analysis @@ -166,6 +167,7 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if ! -loop-unrollUnroll loops -loop-unswitchUnswitch loops -loopsimplifyCanonicalize natural loops +-loweratomicLower atomic intrinsics -lowerinvokeLower invoke and unwind, for unwindless code generators -lowersetjmpLower Set Jump -lowerswitchLower SwitchInst's to branches @@ -647,7 +649,7 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if !

      This pass, only available in opt, prints the call graph to - standard output in a human-readable form. + standard error in a human-readable form.

      @@ -658,7 +660,7 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if !

      This pass, only available in opt, prints the SCCs of the call - graph to standard output in a human-readable form. + graph to standard error in a human-readable form.

      @@ -669,7 +671,7 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if !

      This pass, only available in opt, prints the SCCs of each - function CFG to standard output in a human-readable form. + function CFG to standard error in a human-readable form.

      @@ -678,15 +680,13 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if ! -print-dbginfo: Print debug info in human readable form

      -

      Pass that prints instructions, and associated debug info: +

      Pass that prints instructions, and associated debug info:

      • source/line/col information
      • original variable name
      • original type name
      - -

      @@ -771,6 +771,17 @@ perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print "

      \n" if !

      Pass that checks profiling information for plausibility.

      + +
      +

      + The RegionInfo pass detects single entry single exit regions in a + function, where a region is defined as any subgraph that is connected to the + remaining graph at only two spots. Furthermore, an hierarchical region tree is + built. +

      +
      @@ -1535,6 +1546,24 @@ if (X < 3) {

      + + +
      +

      + This pass lowers atomic intrinsics to non-atomic form for use in a known + non-preemptible environment. +

      + +

      + The pass does not verify that the environment is non-preemptible (in + general this would require knowledge of the entire call graph of the + program including any libraries which may not be available in bitcode form); + it simply lowers every atomic intrinsic. +

      +
      +
  • -strip-debug-declare: Strip all llvm.dbg.declare intrinsics
    -

    This pass implements code stripping. Specifically, it can delete: +

    This pass implements code stripping. Specifically, it can delete:

    • names for virtual registers
    • symbols for internal globals and functions
    • debug information
    +

    Note that this transformation makes code much less readable, so it should only be used in situations where the 'strip' utility would be used, such as reducing code size or making it harder to reverse engineer code. @@ -1946,12 +1976,13 @@ if (X < 3) { -strip-nondebug: Strip all symbols, except dbg symbols, from a module

    -

    This pass implements code stripping. Specifically, it can delete: +

    This pass implements code stripping. Specifically, it can delete:

    • names for virtual registers
    • symbols for internal globals and functions
    • debug information
    +

    Note that this transformation makes code much less readable, so it should only be used in situations where the 'strip' utility would be used, such as reducing code size or making it harder to reverse engineer code. @@ -2211,7 +2242,7 @@ if (X < 3) { Reid Spencer
    LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-07-06 17:52:15 +0200 (Tue, 06 Jul 2010) $ + Last modified: $Date: 2010-08-20 03:03:44 +0200 (Fri, 20 Aug 2010) $ diff --git a/docs/ProgrammersManual.html b/docs/ProgrammersManual.html index 9992cd91b65..8fdd8a00b9b 100644 --- a/docs/ProgrammersManual.html +++ b/docs/ProgrammersManual.html @@ -309,8 +309,6 @@ to write maintainable code more than where to put your curly braces.

      -
    1. CVS -Branch and Tag Primer
    2. Using static and shared libraries across platforms
    @@ -1436,7 +1434,7 @@ to the key string for a value.

    The StringMap is very fast for several reasons: quadratic probing is very cache efficient for lookups, the hash value of strings in buckets is not -recomputed when lookup up an element, StringMap rarely has to touch the +recomputed when looking up an element, StringMap rarely has to touch the memory for unrelated objects when looking up a value (even when hash collisions happen), hash table growth does not recompute the hash values for strings already in the table, and each pair in the map is store in a single allocation @@ -3942,7 +3940,7 @@ arguments. An argument has a pointer to the parent Function.

    Dinakar Dhurjati and Chris Lattner
    The LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-07-15 00:38:02 +0200 (Thu, 15 Jul 2010) $ + Last modified: $Date: 2010-08-04 17:59:16 +0200 (Wed, 04 Aug 2010) $ diff --git a/docs/ReleaseNotes.html b/docs/ReleaseNotes.html index a5a35dd84e6..d346e1ccb1f 100644 --- a/docs/ReleaseNotes.html +++ b/docs/ReleaseNotes.html @@ -67,9 +67,7 @@ Almost dead code. include/llvm/Analysis/LiveValues.h => Dan lib/Transforms/IPO/MergeFunctions.cpp => consider for 2.8. llvm/Analysis/PointerTracking.h => Edwin wants this, consider for 2.8. - ABCD, GEPSplitterPass - MSIL backend? - lib/Transforms/Utils/SSI.cpp -> ABCD depends on it. + GEPSplitterPass --> @@ -78,6 +76,7 @@ Almost dead code. strong phi elim llvm.dbg.value: variable debug info for optimized code loop dependence analysis + TBAA --> @@ -312,171 +251,13 @@ LLVM MC Project Blog Post.

    An exciting aspect of LLVM is that it is used as an enabling technology for a lot of other language and tools projects. This section lists some of the - projects that have already been updated to work with LLVM 2.7.

    -
    - - -
    -Pure -
    - -
    -

    -Pure -is an algebraic/functional programming language based on term rewriting. -Programs are collections of equations which are used to evaluate expressions in -a symbolic fashion. Pure offers dynamic typing, eager and lazy evaluation, -lexical closures, a hygienic macro system (also based on term rewriting), -built-in list and matrix support (including list and matrix comprehensions) and -an easy-to-use C interface. The interpreter uses LLVM as a backend to - JIT-compile Pure programs to fast native code.

    - -

    Pure versions 0.43 and later have been tested and are known to work with -LLVM 2.7 (and continue to work with older LLVM releases >= 2.5).

    - -
    - - - - -
    -

    -Roadsend PHP (rphp) is an open -source implementation of the PHP programming -language that uses LLVM for its optimizer, JIT and static compiler. This is a -reimplementation of an earlier project that is now based on LLVM. -

    -
    - - - - -
    -

    -Unladen Swallow is a -branch of Python intended to be fully -compatible and significantly faster. It uses LLVM's optimization passes and JIT -compiler. -

    -
    - - - - -
    -

    -TCE is a toolset for designing -application-specific processors (ASP) based on the Transport triggered -architecture (TTA). The toolset provides a complete co-design flow from C/C++ -programs down to synthesizable VHDL and parallel program binaries. Processor -customization points include the register files, function units, supported -operations, and the interconnection network.

    - -

    TCE uses llvm-gcc/Clang and LLVM for C/C++ language support, target -independent optimizations and also for parts of code generation. It generates -new LLVM-based code generators "on the fly" for the designed TTA processors and -loads them in to the compiler backend as runtime libraries to avoid per-target -recompilation of larger parts of the compiler chain.

    - -
    - - - - -
    -

    -SAFECode is a memory safe C -compiler built using LLVM. It takes standard, unannotated C code, analyzes the -code to ensure that memory accesses and array indexing operations are safe, and -instruments the code with run-time checks when safety cannot be proven -statically. -

    -
    - - - - -
    -

    -IcedTea provides a -harness to build OpenJDK using only free software build tools and to provide -replacements for the not-yet free parts of OpenJDK. One of the extensions that -IcedTea provides is a new JIT compiler named Shark which uses LLVM -to provide native code generation without introducing processor-dependent -code. -

    -

    Icedtea6 1.8 and later have been tested and are known to work with -LLVM 2.7 (and continue to work with older LLVM releases >= 2.6 as well). -

    -
    - - - - -
    -

    -LLVM-Lua uses LLVM - to add JIT and static compiling support to the Lua VM. Lua -bytecode is analyzed to remove type checks, then LLVM is used to compile the -bytecode down to machine code. -

    -

    LLVM-Lua 1.2.0 have been tested and is known to work with LLVM 2.7. -

    -
    - - - - -
    -

    -MacRuby is an implementation of Ruby based on -core Mac OS technologies, sponsored by Apple Inc. It uses LLVM at runtime for -optimization passes, JIT compilation and exception handling. It also allows -static (ahead-of-time) compilation of Ruby code straight to machine code. -

    -

    The upcoming MacRuby 0.6 release works with LLVM 2.7. -

    -
    - - - - -
    -

    -GHC is an open source, -state-of-the-art programming suite for Haskell, a standard lazy -functional programming language. It includes an optimizing static -compiler generating good code for a variety of platforms, together -with an interactive system for convenient, quick development.

    - -

    In addition to the existing C and native code generators, GHC now -supports an LLVM -code generator. GHC supports LLVM 2.7.

    - + projects that have already been updated to work with LLVM 2.8.

    @@ -496,29 +277,11 @@ in this section.
    -

    In addition to changes to the code, between LLVM 2.6 and 2.7, a number of +

    In addition to changes to the code, between LLVM 2.7 and 2.8, a number of organization changes have happened:

      -
    • LLVM has a new official logo!
    • - -
    • Ted Kremenek and Doug Gregor have stepped forward as Code Owners of the - Clang static analyzer and the Clang frontend, respectively.
    • - -
    • LLVM now has an official Blog at - http://blog.llvm.org. This is a great way - to learn about new LLVM-related features as they are implemented. Several - features in this release are already explained on the blog.
    • - -
    • The LLVM web pages are now checked into the SVN server, in the "www", - "www-pubs" and "www-releases" SVN modules. Previously they were hidden in a - largely inaccessible old CVS server.
    • - -
    • llvm.org is now hosted on a new (and much - faster) server. It is still graciously hosted at the University of Illinois - of Urbana Champaign.
    @@ -529,43 +292,10 @@ organization changes have happened:
    -

    LLVM 2.7 includes several major new capabilities:

    +

    LLVM 2.8 includes several major new capabilities:

      -
    • 2.7 includes initial support for the MicroBlaze target. - MicroBlaze is a soft processor core designed for Xilinx FPGAs.
    • - -
    • 2.7 includes a new LLVM IR "extensible metadata" feature. This feature - supports many different use cases, including allowing front-end authors to - encode source level information into LLVM IR, which is consumed by later - language-specific passes. This is a great way to do high-level optimizations - like devirtualization, type-based alias analysis, etc. See the - Extensible Metadata Blog Post for more information.
    • - -
    • 2.7 encodes debug information -in a completely new way, built on extensible metadata. The new implementation -is much more memory efficient and paves the way for improvements to optimized -code debugging experience.
    • - -
    • 2.7 now directly supports taking the address of a label and doing an - indirect branch through a pointer. This is particularly useful for - interpreter loops, and is used to implement the GCC "address of label" - extension. For more information, see the -Address of Label and Indirect Branches in LLVM IR Blog Post. - -
    • 2.7 is the first release to start supporting APIs for assembling and - disassembling target machine code. These APIs are useful for a variety of - low level clients, and are surfaced in the new "enhanced disassembly" API. - For more information see the The X86 - Disassembler Blog Post for more information.
    • - -
    • 2.7 includes major parts of the work required by the new MC Project, - see the MC update above for more information.
    • - +
    • .
    @@ -580,30 +310,56 @@ Address of Label and Indirect Branches in LLVM IR Blog Post. expose new optimization opportunities:

      -
    • LLVM IR now supports a 16-bit "half float" data type through two new intrinsics and APFloat support.
    • -
    • LLVM IR supports two new function - attributes: inlinehint and alignstack(n). The former is a hint to the - optimizer that a function was declared 'inline' and thus the inliner should - weight it higher when considering inlining it. The later - indicates to the code generator that the function diverges from the platform - ABI on stack alignment.
    • -
    • The new llvm.objectsize intrinsic - allows the optimizer to infer the sizes of memory objects in some cases. - This intrinsic is used to implement the GCC __builtin_object_size - extension.
    • -
    • LLVM IR now supports marking load and store instructions with "non-temporal" hints (building on the new - metadata feature). This hint encourages the code - generator to generate non-temporal accesses when possible, which are useful - for code that is carefully managing cache behavior. Currently, only the - X86 backend provides target support for this feature.
    • - -
    • LLVM 2.7 has pre-alpha support for unions in LLVM IR. - Unfortunately, this support is not really usable in 2.7, so if you're - interested in pushing it forward, please help contribute to LLVM mainline.
    • +
    • LLVM 2.8 changes the internal order of operands in InvokeInst + and CallInst. + To be portable across releases, resort to CallSite and the + high-level accessors, such as getCalledValue and setUnwindDest. +
    • +
    • + You can no longer pass use_iterators directly to cast<> (and similar), because + these routines tend to perform costly dereference operations more than once. You + have to dereference the iterators yourself and pass them in. +
    • +
    • + llvm.memcpy.*, llvm.memset.*, llvm.memmove.* (and possibly other?) intrinsics + take an extra parameter now (i1 isVolatile), totaling 5 parameters. + If you were creating these intrinsic calls and prototypes yourself (as opposed + to using Intrinsic::getDeclaration), you can use UpgradeIntrinsicFunction/UpgradeIntrinsicCall + to be portable accross releases. + Note that you cannot use Intrinsic::getDeclaration() in a backwards compatible + way (needs 2/3 types now, in 2.7 it needed just 1). +
    • +
    • + SetCurrentDebugLocation takes a DebugLoc now instead of a MDNode. + Change your code to use + SetCurrentDebugLocation(DebugLoc::getFromDILocation(...)). +
    • +
    • + VISIBILITY_HIDDEN is gone. +
    • +
    • + The RegisterPass and RegisterAnalysisGroup templates are + considered deprecated, but continue to function in LLVM 2.8. Clients are + strongly advised to use the upcoming INITIALIZE_PASS() and + INITIALIZE_AG_PASS() macros instead. +
    • + SMDiagnostic takes different parameters now. //FIXME: how to upgrade? +
    • +
    • + The constructor for the Triple class no longer tries to understand odd triple + specifications. Frontends should ensure that they only pass valid triples to + LLVM. The Triple::normalize utility method has been added to help front-ends + deal with funky triples. +
    • + Some APIs got renamed: +
        +
      • llvm_report_error -> report_fatal_error
      • +
      • llvm_install_error_handler -> install_fatal_error_handler
      • +
      • llvm::DwarfExceptionHandling -> llvm::JITExceptionHandling
      • +
      +
    @@ -620,48 +376,7 @@ release includes a few major enhancements and additions to the optimizers:

      -
    • The inliner now merges arrays stack objects in different callees when - inlining multiple call sites into one function. This reduces the stack size - of the resultant function.
    • -
    • The -basicaa alias analysis pass (which is the default) has been improved to - be less dependent on "type safe" pointers. It can now look through bitcasts - and other constructs more aggressively, allowing better load/store - optimization.
    • -
    • The load elimination optimization in the GVN Pass [intro - blog post] has been substantially improved to be more aggressive about - partial redundancy elimination and do more aggressive phi translation. Please - see the - Advanced Topics in Redundant Load Elimination with a Focus on PHI Translation - Blog Post for more details.
    • -
    • The module target data string now - includes a notion of 'native' integer data types for the target. This - helps mid-level optimizations avoid promoting complex sequences of - operations to data types that are not natively supported (e.g. converting - i32 operations to i64 on 32-bit chips).
    • -
    • The mid-level optimizer is now conservative when operating on a module with - no target data. Previously, it would default to SparcV9 settings, which is - not what most people expected.
    • -
    • Jump threading is now much more aggressive at simplifying correlated - conditionals and threading blocks with otherwise complex logic. It has - subsumed the old "Conditional Propagation" pass, and -condprop has been - removed from LLVM 2.7.
    • -
    • The -instcombine pass has been refactored from being one huge file to being - a library of its own. Internally, it uses a customized IRBuilder to clean - it up and simplify it.
    • - -
    • The optimal edge profiling pass is reliable and much more complete than in - 2.6. It can be used with the llvm-prof tool but isn't wired up to the - llvm-gcc and clang command line options yet.
    • - -
    • A new experimental alias analysis implementation, -scev-aa, has been added. - It uses LLVM's Scalar Evolution implementation to do symbolic analysis of - pointer offset expressions to disambiguate pointers. It can catch a few - cases that basicaa cannot, particularly in complex loop nests.
    • - -
    • The default pass ordering has been tweaked for improved optimization - effectiveness.
    • +
    @@ -676,19 +391,7 @@ href="http://blog.llvm.org/2009/12/introduction-to-load-elimination-in-gvn.html"
      -
    • The JIT now supports generating debug information and is compatible with -the new GDB 7.0 (and later) interfaces for registering dynamically generated -debug info.
    • - -
    • The JIT now defaults -to compiling eagerly to avoid a race condition in the lazy JIT. -Clients that still want the lazy JIT can switch it on by calling -ExecutionEngine::DisableLazyCompilation(false).
    • - -
    • It is now possible to create more than one JIT instance in the same process. -These JITs can generate machine code in parallel, -although you -still have to obey the other threading restrictions.
    • +
    @@ -706,49 +409,7 @@ infrastructure, which allows us to implement more aggressive algorithms and make it run faster:

      -
    • The 'llc -asm-verbose' option (which is now the default) has been enhanced - to emit many useful comments to .s files indicating information about spill - slots and loop nest structure. This should make it much easier to read and - understand assembly files. This is wired up in llvm-gcc and clang to - the -fverbose-asm option.
    • - -
    • New LSR with "full strength reduction" mode, which can reduce address - register pressure in loops where address generation is important.
    • - -
    • A new codegen level Common Subexpression Elimination pass (MachineCSE) - is available and enabled by default. It catches redundancies exposed by - lowering.
    • -
    • A new pre-register-allocation tail duplication pass is available and enabled - by default, it can substantially improve branch prediction quality in some - cases.
    • -
    • A new sign and zero extension optimization pass (OptimizeExtsPass) - is available and enabled by default. This pass can takes advantage - architecture features like x86-64 implicit zero extension behavior and - sub-registers.
    • -
    • The code generator now supports a mode where it attempts to preserve the - order of instructions in the input code. This is important for source that - is hand scheduled and extremely sensitive to scheduling. It is compatible - with the GCC -fno-schedule-insns option.
    • -
    • The target-independent code generator now supports generating code with - arbitrary numbers of result values. Returning more values than was - previously supported is handled by returning through a hidden pointer. In - 2.7, only the X86 and XCore targets have adopted support for this - though.
    • -
    • The code generator now supports generating code that follows the - Glasgow Haskell Compiler Calling - Convention and ABI.
    • -
    • The "DAG instruction - selection" phase of the code generator has been largely rewritten for - 2.7. Previously, tblgen spit out tons of C++ code which was compiled and - linked into the target to do the pattern matching, now it emits a much - smaller table which is read by the target-independent code. The primary - advantages of this approach is that the size and compile time of various - targets is much improved. The X86 code generator shrunk by 1.5MB of code, - for example.
    • -
    • Almost the entire code generator has switched to emitting code through the - MC interfaces instead of printing textually to the .s file. This led to a - number of cleanups and speedups. In 2.7, debug an exception handling - information does not go through MC yet.
    • +
    • MachO writer works.
    @@ -762,11 +423,9 @@ it run faster:

      -
    • The X86 backend now optimizes tails calls much more aggressively for - functions that use the standard C calling convention.
    • -
    • The X86 backend now models scalar SSE registers as subregs of the SSE vector - registers, making the code generator more aggressive in cases where scalars - and vector types are mixed.
    • +
    • The X86 backend now supports holding X87 floating point stack values + in registers across basic blocks, dramatically improving performance of code + that uses long double, and when targetting CPUs that don't support SSE.
    @@ -783,27 +442,7 @@ it run faster:

      -
    • The ARM backend now generates instructions in unified assembly syntax.
    • - -
    • llvm-gcc now has complete support for the ARM v7 NEON instruction set. This - support differs slightly from the GCC implementation. Please see the - - ARM Advanced SIMD (NEON) Intrinsics and Types in LLVM Blog Post for - helpful information if migrating code from GCC to LLVM-GCC.
    • - -
    • The ARM and Thumb code generators now use register scavenging for stack - object address materialization. This allows the use of R3 as a general - purpose register in Thumb1 code, as it was previous reserved for use in - stack address materialization. Secondly, sequential uses of the same - value will now re-use the materialized constant.
    • - -
    • The ARM backend now has good support for ARMv4 targets and has been tested - on StrongARM hardware. Previously, LLVM only supported ARMv4T and - newer chips.
    • - -
    • Atomic builtins are now supported for ARMv6 and ARMv7 (__sync_synchronize, - __sync_fetch_and_add, etc.).
    • +
    @@ -822,34 +461,7 @@ href="http://blog.llvm.org/2010/04/arm-advanced-simd-neon-intrinsics-and.html">

      -
    • The optimizer uses the new CodeMetrics class to measure the size of code. - Various passes (like the inliner, loop unswitcher, etc) all use this to make - more accurate estimates of the code size impact of various - optimizations.
    • -
    • A new - llvm/Analysis/InstructionSimplify.h interface is available for doing - symbolic simplification of instructions (e.g. a+0 -> a) - without requiring the instruction to exist. This centralizes a lot of - ad-hoc symbolic manipulation code scattered in various passes.
    • -
    • The optimizer now uses a new SSAUpdater - class which efficiently supports - doing unstructured SSA update operations. This centralized a bunch of code - scattered throughout various passes (e.g. jump threading, lcssa, - loop rotate, etc) for doing this sort of thing. The code generator has a - similar - MachineSSAUpdater class.
    • -
    • The - llvm/Support/Regex.h header exposes a platform independent regular - expression API. Building on this, the FileCheck utility now supports - regular exressions.
    • -
    • raw_ostream now supports a circular "debug stream" accessed with "dbgs()". - By default, this stream works the same way as "errs()", but if you pass - -debug-buffer-size=1000 to opt, the debug stream is capped to a - fixed sized circular buffer and the output is printed at the end of the - program's execution. This is helpful if you have a long lived compiler - process and you're interested in seeing snapshots in time.
    • +
    @@ -864,16 +476,7 @@ href="http://blog.llvm.org/2010/04/arm-advanced-simd-neon-intrinsics-and.html">

    Other miscellaneous features include:

      -
    • You can now build LLVM as a big dynamic library (e.g. "libllvm2.7.so"). To - get this, configure LLVM with the --enable-shared option.
    • - -
    • LLVM command line tools now overwrite their output by default. Previously, - they would only do this with -f. This makes them more convenient to use, and - behave more like standard unix tools.
    • - -
    • The opt and llc tools now autodetect whether their input is a .ll or .bc - file, and automatically do the right thing. This means you don't need to - explicitly use the llvm-as tool for most things.
    • +
    @@ -887,48 +490,21 @@ href="http://blog.llvm.org/2010/04/arm-advanced-simd-neon-intrinsics-and.html">

    If you're already an LLVM user or developer with out-of-tree changes based -on LLVM 2.6, this section lists some "gotchas" that you may run into upgrading +on LLVM 2.7, this section lists some "gotchas" that you may run into upgrading from the previous release.

      - -
    • -The Andersen's alias analysis ("anders-aa") pass, the Predicate Simplifier -("predsimplify") pass, the LoopVR pass, the GVNPRE pass, and the random sampling -profiling ("rsprofiling") passes have all been removed. They were not being -actively maintained and had substantial problems. If you are interested in -these components, you are welcome to ressurect them from SVN, fix the -correctness problems, and resubmit them to mainline.
    • - -
    • LLVM now defaults to building most libraries with RTTI turned off, providing -a code size reduction. Packagers who are interested in building LLVM to support -plugins that require RTTI information should build with "make REQUIRE_RTTI=1" -and should read the new Advice on Packaging LLVM -document.
    • - -
    • The LLVM interpreter now defaults to not using libffi even -if you have it installed. This makes it more likely that an LLVM built on one -system will work when copied to a similar system. To use libffi, -configure with --enable-libffi.
    • - -
    • Debug information uses a completely different representation, an LLVM 2.6 -.bc file should work with LLVM 2.7, but debug info won't come forward.
    • - -
    • The LLVM 2.6 (and earlier) "malloc" and "free" instructions got removed, - along with LowerAllocations pass. Now you should just use a call to the - malloc and free functions in libc. These calls are optimized as well as - the old instructions were.
    • +
    • .ll file doesn't produce #uses comments anymore, to get them, run a .bc file + through "llvm-dis --show-annotations".
    • +
    • MSIL Backend removed.
    • +
    • ABCD and SSI passes removed.
    • +
    • 'Union' LLVM IR feature removed.

    In addition, many APIs have changed in this release. Some of the major LLVM API changes are:

      - -
    • The add, sub, and mul instructions no longer -support floating-point operands. The fadd, fsub, and -fmul instructions should be used for this purpose instead.
    • -
    @@ -985,6 +561,9 @@ See: Broken versions of GCC and other to However, A Modern GCC Build for x86/x86-64 has been made available from the third party AuroraUX Project that has been meticulously tested for bootstrapping LLVM & Clang. +
  • There have been reports of Solaris and/or OpenSolaris build failures due +to an incompatibility in the nm program as well. The nm from binutils does seem +to work.
  • @@ -1004,11 +583,10 @@ components, please contact us on the LLVMdev list.

      -
    • The MSIL, Alpha, SPU, MIPS, PIC16, Blackfin, MSP430, SystemZ and MicroBlaze +
    • The Alpha, SPU, MIPS, PIC16, Blackfin, MSP430, SystemZ and MicroBlaze backends are experimental.
    • llc "-filetype=asm" (the default) is the only - supported value for this option. The MachO writer is experimental, and - works much better in mainline SVN.
    • + supported value for this option. XXX Update me
    @@ -1025,8 +603,6 @@ href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">LLVMdev list.

    all inline assembly that uses the X86 floating point stack. It supports the 'f' and 't' constraints, but not 'u'. -
  • The X86 backend generates inefficient floating point code when configured - to generate code for systems that don't have SSE2.
  • Win64 code generation wasn't widely tested. Everything should work, but we expect small issues to happen. Also, llvm-gcc cannot build the mingw64 runtime currently due to lack of support for the 'u' inline assembly @@ -1230,7 +806,7 @@ lists.

    src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"> LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-05-07 02:28:04 +0200 (Fri, 07 May 2010) $ + Last modified: $Date: 2010-09-03 01:22:50 +0200 (Fri, 03 Sep 2010) $ diff --git a/docs/TestingGuide.html b/docs/TestingGuide.html index 3149f46cb5c..c7353ebb0d4 100644 --- a/docs/TestingGuide.html +++ b/docs/TestingGuide.html @@ -16,22 +16,22 @@
  • Requirements
  • LLVM testing infrastructure organization
  • Quick start
  • -
  • DejaGNU structure +
  • Regression test structure
  • Test suite structure
  • @@ -43,12 +43,10 @@
  • Writing custom tests for llvm-test
  • -
  • Running the nightly tester
  • -

    Written by John T. Criswell, Reid Spencer, and Tanya Lattner

    +

    Written by John T. Criswell, Daniel Dunbar, Reid Spencer, and Tanya Lattner

    @@ -57,9 +55,9 @@
    -

    This document is the reference manual for the LLVM testing infrastructure. It documents -the structure of the LLVM testing infrastructure, the tools needed to use it, -and how to add and run tests.

    +

    This document is the reference manual for the LLVM testing infrastructure. It +documents the structure of the LLVM testing infrastructure, the tools needed to +use it, and how to add and run tests.

    @@ -69,17 +67,9 @@ and how to add and run tests.

    -

    In order to use the LLVM testing infrastructure, you will need all of the software -required to build LLVM, plus the following:

    - -
    -
    DejaGNU
    -
    The Feature and Regressions tests are organized and run by DejaGNU.
    -
    Expect
    -
    Expect is required by DejaGNU.
    -
    tcl
    -
    Tcl is required by DejaGNU.
    -
    +

    In order to use the LLVM testing infrastructure, you will need all of the +software required to build LLVM, as well +as Python 2.4 or later.

    @@ -89,29 +79,28 @@ required to build LLVM, plus the following:

    -

    The LLVM testing infrastructure contains two major categories of tests: code -fragments and whole programs. Code fragments are referred to as the "DejaGNU -tests" and are in the llvm module in subversion under the -llvm/test directory. The whole programs tests are referred to as the -"Test suite" and are in the test-suite module in subversion. +

    The LLVM testing infrastructure contains two major categories of tests: +regression tests and whole programs. The regression tests are contained inside +the LLVM repository itself under llvm/test and are expected to always +pass -- they should be run before every commit. The whole programs tests are +referred to as the "LLVM test suite" and are in the test-suite module +in subversion.

    - +
    -

    Code fragments are small pieces of code that test a specific -feature of LLVM or trigger a specific bug in LLVM. They are usually -written in LLVM assembly language, but can be written in other -languages if the test targets a particular language front end (and the -appropriate --with-llvmgcc options were used -at configure time of the llvm module). These tests -are driven by the DejaGNU testing framework, which is hidden behind a -few simple makefiles.

    +

    The regression tests are small pieces of code that test a specific feature of +LLVM or trigger a specific bug in LLVM. They are usually written in LLVM +assembly language, but can be written in other languages if the test targets a +particular language front end (and the appropriate --with-llvmgcc +options were used at configure time of the llvm module). These +tests are driven by the 'lit' testing tool, which is part of LLVM.

    These code fragments are not complete programs. The code generated from them is never executed to determine correct behavior.

    @@ -158,8 +147,8 @@ generates code.

    -

    The tests are located in two separate Subversion modules. The - DejaGNU tests are in the main "llvm" module under the directory +

    The tests are located in two separate Subversion modules. The regressions + tests are in the main "llvm" module under the directory llvm/test (so you get these tests for free with the main llvm tree). The more comprehensive test suite that includes whole programs in C and C++ is in the test-suite module. This module should @@ -171,10 +160,10 @@ the test-suite directory will be automatically configured. Alternatively, you can configure the test-suite module manually.

    - + -

    To run all of the simple tests in LLVM using DejaGNU, use the master Makefile - in the llvm/test directory:

    +

    To run all of the LLVM regression tests, use master Makefile in + the llvm/test directory:

    @@ -190,26 +179,14 @@ Alternatively, you can configure the test-suite module manually.

    -

    To run only a subdirectory of tests in llvm/test using DejaGNU (ie. -Transforms), just set the TESTSUITE variable to the path of the -subdirectory (relative to llvm/test):

    +

    If you have Clang checked out and built, +you can run the LLVM and Clang tests simultaneously using:

    + +

    or

    -% gmake TESTSUITE=Transforms check
    -
    -
    - -

    Note: If you are running the tests with objdir != subdir, you -must have run the complete testsuite before you can specify a -subdirectory.

    - -

    To run only a single test, set TESTONE to its path (relative to -llvm/test) and make the check-one target:

    - -
    -
    -% gmake TESTONE=Feature/basictest.ll check-one
    +% gmake check-all
     
    @@ -222,6 +199,27 @@ subdirectory.

    +

    To run individual tests or subsets of tests, you can use the 'llvm-lit' +script which is built as part of LLVM. For example, to run the +'Integer/BitCast.ll' test by itself you can run:

    + +
    +
    +% llvm-lit ~/llvm/test/Integer/BitCast.ll 
    +
    +
    + +

    or to run all of the ARM CodeGen tests:

    + +
    +
    +% llvm-lit ~/llvm/test/CodeGen/ARM
    +
    +
    + +

    For more information on using the 'lit' tool, see 'llvm-lit --help' or the +'lit' man page.

    + @@ -275,11 +273,11 @@ that subdirectory.

    - +
    -

    The LLVM DejaGNU tests are driven by DejaGNU together with GNU Make and are - located in the llvm/test directory. +

    The LLVM regression tests are driven by 'lit' and are located in + the llvm/test directory.

    This directory contains a large array of small tests that exercise various features of LLVM and to ensure that regressions do not @@ -302,23 +300,24 @@ that subdirectory.

    - +
    -

    The DejaGNU structure is very simple, but does require some information to - be set. This information is gathered via configure and is written - to a file, site.exp in llvm/test. The llvm/test - Makefile does this work for you.

    +

    The regression test structure is very simple, but does require some + information to be set. This information is gathered via configure and + is written to a file, lit.site.cfg + in llvm/test. The llvm/test Makefile does this work for + you.

    -

    In order for DejaGNU to work, each directory of tests must have a - dg.exp file. DejaGNU looks for this file to determine how to run the - tests. This file is just a Tcl script and it can do anything you want, but - we've standardized it for the LLVM regression tests. If you're adding a +

    In order for the regression tests to work, each directory of tests must + have a dg.exp file. Lit looks for this file to determine how to + run the tests. This file is just a Tcl script and it can do anything you want, + but we've standardized it for the LLVM regression tests. If you're adding a directory of tests, just copy dg.exp from another directory to get - running. The standard dg.exp simply loads a Tcl - library (test/lib/llvm.exp) and calls the llvm_runtests - function defined in that library with a list of file names to run. The names - are obtained by using Tcl's glob command. Any directory that contains only + running. The standard dg.exp simply loads a Tcl library + (test/lib/llvm.exp) and calls the llvm_runtests function + defined in that library with a list of file names to run. The names are + obtained by using Tcl's glob command. Any directory that contains only directories does not need the dg.exp file.

    The llvm-runtests function lookas at each file that is passed to @@ -379,7 +378,8 @@ that subdirectory.

    There are some quoting rules that you must pay attention to when writing your RUN lines. In general nothing needs to be quoted. Tcl won't strip off any - ' or " so they will get passed to the invoked program. For example:

    + quote characters so they will get passed to the invoked program. For + example:

    @@ -696,7 +696,7 @@ define two separate CHECK lines that match on the same line.
     
    -
    Variables and +
    @@ -792,7 +792,7 @@ substitutions
    - +

    To make RUN line writing easier, there are several shell scripts located @@ -818,7 +818,7 @@ substitutions

    Sometimes it is necessary to mark a test case as "expected fail" or XFAIL. You can easily mark a test as XFAIL just by including XFAIL: on a line near the top of the file. This signals that the test case should succeed - if the test fails. Such test cases are counted separately by DejaGnu. To + if the test fails. Such test cases are counted separately by the testing tool. To specify an expected fail, use the XFAIL keyword in the comments of the test program followed by a colon and one or more regular expressions (separated by a comma). The regular expressions allow you to XFAIL the test conditionally by @@ -906,9 +906,10 @@ benchmarks, regression tests, code that is strange grammatically, etc. These organizations should be relatively self explanatory.

    Some tests are known to fail. Some are bugs that we have not fixed yet; -others are features that we haven't added yet (or may never add). In DejaGNU, -the result for such tests will be XFAIL (eXpected FAILure). In this way, you -can tell the difference between an expected and unexpected failure.

    +others are features that we haven't added yet (or may never add). In the +regression tests, the result for such tests will be XFAIL (eXpected FAILure). +In this way, you can tell the difference between an expected and unexpected +failure.

    The tests in the test suite have no such feature at this time. If the test passes, only warnings and other miscellaneous output will be generated. If @@ -1135,66 +1136,6 @@ example reports that can do fancy stuff.

    - - - - -
    - -

    -The LLVM Nightly Testers -automatically check out an LLVM tree, build it, run the "nightly" -program test (described above), run all of the DejaGNU tests, -delete the checked out tree, and then submit the results to -http://llvm.org/nightlytest/. -After test results are submitted to -http://llvm.org/nightlytest/, -they are processed and displayed on the tests page. An email to - -llvm-testresults@cs.uiuc.edu summarizing the results is also generated. -This testing scheme is designed to ensure that programs don't break as well -as keep track of LLVM's progress over time.

    - -

    If you'd like to set up an instance of the nightly tester to run on your -machine, take a look at the comments at the top of the -utils/NewNightlyTest.pl file. If you decide to set up a nightly tester -please choose a unique nickname and invoke utils/NewNightlyTest.pl -with the "-nickname [yournickname]" command line option. - -

    You can create a shell script to encapsulate the running of the script. -The optimized x86 Linux nightly test is run from just such a script:

    - -
    -
    -#!/bin/bash
    -BASE=/proj/work/llvm/nightlytest
    -export BUILDDIR=$BASE/build 
    -export WEBDIR=$BASE/testresults 
    -export LLVMGCCDIR=/proj/work/llvm/cfrontend/install
    -export PATH=/proj/install/bin:$LLVMGCCDIR/bin:$PATH
    -export LD_LIBRARY_PATH=/proj/install/lib
    -cd $BASE
    -cp /proj/work/llvm/llvm/utils/NewNightlyTest.pl .
    -nice ./NewNightlyTest.pl -nice -release -verbose -parallel -enable-linscan \
    -   -nickname NightlyTester -noexternals > output.log 2>&1 
    -
    -
    - -

    It is also possible to specify the the location your nightly test results -are submitted. You can do this by passing the command line option -"-submit-server [server_address]" and "-submit-script [script_on_server]" to -utils/NewNightlyTest.pl. For example, to submit to the llvm.org -nightly test results page, you would invoke the nightly test script with -"-submit-server llvm.org -submit-script /nightlytest/NightlyTestAccept.cgi". -If these options are not specified, the nightly test script sends the results -to the llvm.org nightly test results page.

    - -

    Take a look at the NewNightlyTest.pl file to see what all of the -flags and strings do. If you start running the nightly tests, please let us -know. Thanks!

    - -
    -
    @@ -1204,9 +1145,9 @@ know. Thanks!

    Valid HTML 4.01 - John T. Criswell, Reid Spencer, and Tanya Lattner
    + John T. Criswell, Daniel Dunbar, Reid Spencer, and Tanya Lattner
    The LLVM Compiler Infrastructure
    - Last modified: $Date: 2010-05-07 02:28:04 +0200 (Fri, 07 May 2010) $ + Last modified: $Date: 2010-08-02 03:20:23 +0200 (Mon, 02 Aug 2010) $ diff --git a/docs/WritingAnLLVMBackend.html b/docs/WritingAnLLVMBackend.html index aa2612c2e92..2dc0ef772cc 100644 --- a/docs/WritingAnLLVMBackend.html +++ b/docs/WritingAnLLVMBackend.html @@ -1299,9 +1299,6 @@ implementation in SparcInstrInfo.cpp:

  • Blocks
  • Function Overloading in C
  • @@ -301,32 +302,34 @@ not yet implemented will be noted.

    C++0x attributes

    Use __has_feature(cxx_attributes) to determine if support for -attribute parsing with C++0x's square bracket notation is enabled. +attribute parsing with C++0x's square bracket notation is enabled.

    C++0x deleted functions

    Use __has_feature(cxx_deleted_functions) to determine if support for -deleted function definitions (with = delete) is enabled. +deleted function definitions (with = delete) is enabled.

    C++ TR concepts

    Use __has_feature(cxx_concepts) to determine if support for -concepts is enabled. clang does not currently implement this feature. +concepts is enabled. clang does not currently implement this feature.

    C++0x lambdas

    Use __has_feature(cxx_lambdas) to determine if support for -lambdas is enabled. clang does not currently implement this feature. +lambdas is enabled. clang does not currently implement this feature.

    C++0x nullptr

    Use __has_feature(cxx_nullptr) to determine if support for -nullptr is enabled. clang does not yet fully implement this feature. +nullptr is enabled. clang does not yet fully implement this +feature.

    C++0x rvalue references

    Use __has_feature(cxx_rvalue_references) to determine if support for -rvalue references is enabled. clang does not yet fully implement this feature. +rvalue references is enabled. clang does not yet fully implement this +feature.

    C++0x static_assert()

    @@ -339,12 +342,17 @@ compile-time assertions using static_assert is enabled.

    is supported using the auto specifier. If this is disabled, auto will instead be a storage class specifier, as in C or C++98.

    -

    C++0x variadic templates

    +

    C++0x variadic templates

    Use __has_feature(cxx_variadic_templates) to determine if support for templates taking any number of arguments with the ellipsis notation is enabled. clang does not yet fully implement this feature.

    +

    C++0x inline namespaces

    + +

    Use __has_feature(cxx_inline_namespaces) to determine if support for +inline namespaces is enabled.

    +

    Blocks

    diff --git a/docs/UsersManual.html b/docs/UsersManual.html index 51e699fc32c..75241610a32 100644 --- a/docs/UsersManual.html +++ b/docs/UsersManual.html @@ -39,6 +39,7 @@ td {
  • Diagnostic Categories
  • Controlling Diagnostics via Command Line Flags
  • Controlling Diagnostics via Pragmas
  • +
  • Controlling Static Analyzer Diagnostics
  • Precompiled Headers
  • Controlling Code Generation
  • @@ -358,6 +359,18 @@ exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expre

    The {}'s are generated by -fdiagnostics-print-source-range-info.

    + +
    +-fdiagnostics-parseable-fixits: +Print Fix-Its in a machine parseable form.
    +

    This option makes Clang print available Fix-Its in a machine parseable format at the end of diagnostics. The following example illustrates the format:

    + +
    + fix-it:"t.cpp":{7:25-7:29}:"Gamma"
    +
    + +

    The range printed is a half-open range, so in this example the characters at column 25 up to but not including column 29 on line 7 in t.cpp should be replaced with the string "Gamma". Either the range or the replacement string may be empty (representing strict insertions and strict erasures, respectively). Both the file name and the insertion string escape backslash (as "\\"), tabs (as "\t"), newlines (as "\n"), double quotes(as "\"") and non-printable characters (as octal "\xxx").

    +
    @@ -579,6 +592,42 @@ GCC do not support the exact same set of warnings, so even when using GCC compatible #pragmas there is no guarantee that they will have identical behaviour on both compilers.

    +

    Controlling Static Analyzer Diagnostics

    + +

    While not strictly part of the compiler, the diagnostics from Clang's static analyzer can also be influenced +by the user via changes to the source code. This can be done in two ways: + +

      + +
    • Annotations: The static analyzer recognizes various GCC-style +attributes (e.g., __attribute__((nonnull)))) that can either suppress +static analyzer warnings or teach the analyzer about code invariants which +enable it to find more bugs. While many of these attributes are standard GCC +attributes, additional ones have added to Clang to specifically support the +static analyzer. Detailed information on these annotations can be found in the +analyzer's +documentation.
    • + +
    • __clang_analyzer__: When the static analyzer is using Clang +to parse source files, it implicitly defines the preprocessor macro +__clang_analyzer__. While discouraged, code can use this macro to +selectively exclude code the analyzer examines. Here is an example: + +
      +#ifndef __clang_analyzer__
      +// Code not to be analyzed
      +#endif
      +
      + +In general, this usage is discouraged. Instead, we prefer that users file bugs +against the analyzer when it flags false positives. There is also active +discussion of allowing users in the future to selectively silence specific +analyzer warnings (some which can already be done using annotations).
    • + +
    +

    Precompiled Headers

    @@ -789,11 +838,6 @@ soon. the uses described in the bug, this is likely to be implemented at some point, at least partially. -
  • clang does not support #pragma align -(bug 3811). This is a -relatively small feature, so it is likely to be implemented relatively -soon.
  • -
  • clang does not support code generation for local variables pinned to registers (bug 3933). This is a relatively small feature, so it is likely to be implemented diff --git a/docs/tools/clang.pod b/docs/tools/clang.pod index 0c1ab574d53..032efcfcabc 100644 --- a/docs/tools/clang.pod +++ b/docs/tools/clang.pod @@ -168,6 +168,10 @@ Enable support for Pascal-style strings with "\pfoo". Enable support for Microsoft extensions. +=item B<-fborland-extensions> + +Enable support for Borland extensions. + =item B<-fwritable-strings> Make all string literals default to writable. This disables uniquing of @@ -395,6 +399,7 @@ Show commands to run and use verbose output. B<-fshow-source-location> B<-fcaret-diagnostics> B<-fdiagnostics-fixit-info> +B<-fdiagnostics-parseable-fixits> B<-fdiagnostics-print-source-range-info> B<-fprint-source-range-info> B<-fdiagnostics-show-option> @@ -515,7 +520,6 @@ targets. =head1 BUGS -Clang currently does not have C++ support, and this manual page is incomplete. To report bugs, please visit L. Most bug reports should include preprocessed source files (use the B<-E> option) and the full output of the compiler, along with information to reproduce. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index d2738c69035..9a32ee40652 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,4 +1,3 @@ add_subdirectory(clang-interpreter) add_subdirectory(PrintFunctionNames) -add_subdirectory(wpa) diff --git a/examples/Makefile b/examples/Makefile index c4af2526339..8cb431d7391 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -9,6 +9,6 @@ CLANG_LEVEL := .. -PARALLEL_DIRS := clang-interpreter PrintFunctionNames wpa +PARALLEL_DIRS := clang-interpreter PrintFunctionNames include $(CLANG_LEVEL)/Makefile diff --git a/examples/PrintFunctionNames/Makefile b/examples/PrintFunctionNames/Makefile index 0ff5189437c..125ac4854ff 100644 --- a/examples/PrintFunctionNames/Makefile +++ b/examples/PrintFunctionNames/Makefile @@ -10,10 +10,15 @@ CLANG_LEVEL := ../.. LIBRARYNAME = PrintFunctionNames +# If we don't need RTTI or EH, there's no reason to export anything +# from the plugin. +ifneq ($(REQUIRES_RTTI), 1) +ifneq ($(REQUIRES_EH), 1) +EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/PrintFunctionNames.exports +endif +endif + LINK_LIBS_IN_SHARED = 1 SHARED_LIBRARY = 1 -USEDLIBS = clangIndex.a clangFrontend.a clangDriver.a clangSema.a \ - clangAnalysis.a clangAST.a clangParse.a clangLex.a clangBasic.a - include $(CLANG_LEVEL)/Makefile diff --git a/examples/PrintFunctionNames/PrintFunctionNames.cpp b/examples/PrintFunctionNames/PrintFunctionNames.cpp index 397cf843fa7..cc138f56dbb 100644 --- a/examples/PrintFunctionNames/PrintFunctionNames.cpp +++ b/examples/PrintFunctionNames/PrintFunctionNames.cpp @@ -15,6 +15,7 @@ #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/AST.h" +#include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" using namespace clang; @@ -29,7 +30,7 @@ public: llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n"; } } -}; +}; class PrintFunctionNamesAction : public PluginASTAction { protected: @@ -37,15 +38,26 @@ protected: return new PrintFunctionsConsumer(); } - bool ParseArgs(const std::vector& args) { - for (unsigned i=0; i& args) { + for (unsigned i = 0, e = args.size(); i != e; ++i) { llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n"; + + // Example error handling. + if (args[i] == "-an-error") { + Diagnostic &D = CI.getDiagnostics(); + unsigned DiagID = D.getCustomDiagID( + Diagnostic::Error, "invalid argument '" + args[i] + "'"); + D.Report(DiagID); + return false; + } + } if (args.size() && args[0] == "help") PrintHelp(llvm::errs()); return true; } - void PrintHelp(llvm::raw_ostream& ros) { + void PrintHelp(llvm::raw_ostream& ros) { ros << "Help for PrintFunctionNames plugin goes here\n"; } @@ -53,5 +65,5 @@ protected: } -FrontendPluginRegistry::Add +static FrontendPluginRegistry::Add X("print-fns", "print function names"); diff --git a/examples/PrintFunctionNames/PrintFunctionNames.exports b/examples/PrintFunctionNames/PrintFunctionNames.exports new file mode 100644 index 00000000000..0ff590d30d7 --- /dev/null +++ b/examples/PrintFunctionNames/PrintFunctionNames.exports @@ -0,0 +1 @@ +_ZN4llvm8Registry* diff --git a/examples/clang-interpreter/CMakeLists.txt b/examples/clang-interpreter/CMakeLists.txt index 1aa9b2b5922..73f28bb7a2e 100644 --- a/examples/clang-interpreter/CMakeLists.txt +++ b/examples/clang-interpreter/CMakeLists.txt @@ -2,10 +2,12 @@ set(LLVM_NO_RTTI 1) set(LLVM_USED_LIBS clangFrontend + clangSerialization clangDriver clangCodeGen clangSema clangChecker + clangIndex clangAnalysis clangRewrite clangAST diff --git a/examples/clang-interpreter/Makefile b/examples/clang-interpreter/Makefile index 6fa58d22cbd..2f5e017af80 100644 --- a/examples/clang-interpreter/Makefile +++ b/examples/clang-interpreter/Makefile @@ -17,8 +17,8 @@ TOOL_NO_EXPORTS = 1 LINK_COMPONENTS := jit interpreter nativecodegen bitreader bitwriter ipo \ selectiondag asmparser -USEDLIBS = clangFrontend.a clangDriver.a clangCodeGen.a clangSema.a \ - clangChecker.a clangAnalysis.a clangRewrite.a clangAST.a \ - clangParse.a clangLex.a clangBasic.a +USEDLIBS = clangFrontend.a clangSerialization.a clangDriver.a clangCodeGen.a \ + clangSema.a clangChecker.a clangAnalysis.a clangRewrite.a \ + clangAST.a clangParse.a clangLex.a clangBasic.a include $(CLANG_LEVEL)/Makefile diff --git a/examples/clang-interpreter/main.cpp b/examples/clang-interpreter/main.cpp index ec4e8619829..2ccba8b24a8 100644 --- a/examples/clang-interpreter/main.cpp +++ b/examples/clang-interpreter/main.cpp @@ -66,11 +66,11 @@ int Execute(llvm::Module *Mod, char * const *envp) { int main(int argc, const char **argv, char * const *envp) { void *MainAddr = (void*) (intptr_t) GetExecutablePath; llvm::sys::Path Path = GetExecutablePath(argv[0]); - TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions()); + TextDiagnosticPrinter *DiagClient = + new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions()); - Diagnostic Diags(&DiagClient); - Driver TheDriver(Path.getBasename(), Path.getDirname(), - llvm::sys::getHostTriple(), + Diagnostic Diags(DiagClient); + Driver TheDriver(Path.str(), llvm::sys::getHostTriple(), "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false, Diags); TheDriver.setTitle("clang interpreter"); diff --git a/examples/wpa/CMakeLists.txt b/examples/wpa/CMakeLists.txt index c2b2ce63a93..13e4298c1f2 100644 --- a/examples/wpa/CMakeLists.txt +++ b/examples/wpa/CMakeLists.txt @@ -6,6 +6,7 @@ set(LLVM_USED_LIBS clangDriver clangSema clangAnalysis + clangSerialization clangChecker clangRewrite clangAST diff --git a/examples/wpa/Makefile b/examples/wpa/Makefile index bd6ebfdc9bf..0a70ea6359c 100644 --- a/examples/wpa/Makefile +++ b/examples/wpa/Makefile @@ -17,7 +17,7 @@ TOOL_NO_EXPORTS = 1 LINK_COMPONENTS := asmparser bitreader mc core USEDLIBS = clangChecker.a clangIndex.a clangFrontend.a clangDriver.a \ - clangSema.a clangAnalysis.a clangAST.a clangParse.a clangLex.a \ - clangBasic.a + clangSema.a clangAnalysis.a clangSerialization.a \ + clangAST.a clangParse.a clangLex.a clangBasic.a include $(CLANG_LEVEL)/Makefile diff --git a/examples/wpa/clang-wpa.cpp b/examples/wpa/clang-wpa.cpp index 74ec368cfbe..41dca0dc451 100644 --- a/examples/wpa/clang-wpa.cpp +++ b/examples/wpa/clang-wpa.cpp @@ -62,6 +62,10 @@ public: return AST->getPreprocessor(); } + virtual Diagnostic &getDiagnostic() { + return AST->getDiagnostics(); + } + virtual DeclReferenceMap &getDeclReferenceMap() { return DeclRefMap; } @@ -87,7 +91,7 @@ int main(int argc, char **argv) { = CompilerInstance::createDiagnostics(DiagOpts, argc, argv); for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) { const std::string &InFile = InputFilenames[i]; - llvm::OwningPtr AST(ASTUnit::LoadFromPCHFile(InFile, Diags)); + llvm::OwningPtr AST(ASTUnit::LoadFromASTFile(InFile, Diags)); if (!AST) return 1; @@ -129,17 +133,18 @@ int main(int argc, char **argv) { AnalysisManager AMgr(TU->getASTContext(), PP.getDiagnostics(), PP.getLangOptions(), /* PathDiagnostic */ 0, CreateRegionStoreManager, - CreateRangeConstraintManager, + CreateRangeConstraintManager, &Idxer, /* MaxNodes */ 300000, /* MaxLoop */ 3, /* VisualizeEG */ false, /* VisualizeEGUbi */ false, /* PurgeDead */ true, /* EagerlyAssume */ false, - /* TrimGraph */ false, /* InlineCall */ true); + /* TrimGraph */ false, /* InlineCall */ true, + /* UseUnoptimizedCFG */ false); GRTransferFuncs* TF = MakeCFRefCountTF(AMgr.getASTContext(), /*GC*/false, AMgr.getLangOptions()); GRExprEngine Eng(AMgr, TF); - Eng.ExecuteWorkList(AMgr.getStackFrame(FD), AMgr.getMaxNodes()); + Eng.ExecuteWorkList(AMgr.getStackFrame(FD, TU), AMgr.getMaxNodes()); return 0; } diff --git a/include/clang-c/Index.h b/include/clang-c/Index.h index b377b6d5fe2..4631c65bf05 100644 --- a/include/clang-c/Index.h +++ b/include/clang-c/Index.h @@ -97,6 +97,27 @@ struct CXUnsavedFile { unsigned long Length; }; +/** + * \brief Describes the availability of a particular entity, which indicates + * whether the use of this entity will result in a warning or error due to + * it being deprecated or unavailable. + */ +enum CXAvailabilityKind { + /** + * \brief The entity is available. + */ + CXAvailability_Available, + /** + * \brief The entity is available, but has been deprecated (and its use is + * not recommended). + */ + CXAvailability_Deprecated, + /** + * \brief The entity is not available; any use of it will be an error. + */ + CXAvailability_NotAvailable +}; + /** * \defgroup CINDEX_STRING String manipulation routines * @@ -624,7 +645,7 @@ CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnitFromSourceFile( CXIndex CIdx, const char *source_filename, int num_clang_command_line_args, - const char **clang_command_line_args, + const char * const *clang_command_line_args, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files); @@ -634,11 +655,261 @@ CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnitFromSourceFile( CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnit(CXIndex, const char *ast_filename); +/** + * \brief Flags that control the creation of translation units. + * + * The enumerators in this enumeration type are meant to be bitwise + * ORed together to specify which options should be used when + * constructing the translation unit. + */ +enum CXTranslationUnit_Flags { + /** + * \brief Used to indicate that no special translation-unit options are + * needed. + */ + CXTranslationUnit_None = 0x0, + + /** + * \brief Used to indicate that the parser should construct a "detailed" + * preprocessing record, including all macro definitions and instantiations. + * + * Constructing a detailed preprocessing record requires more memory + * and time to parse, since the information contained in the record + * is usually not retained. However, it can be useful for + * applications that require more detailed information about the + * behavior of the preprocessor. + */ + CXTranslationUnit_DetailedPreprocessingRecord = 0x01, + + /** + * \brief Used to indicate that the translation unit is incomplete. + * + * When a translation unit is considered "incomplete", semantic + * analysis that is typically performed at the end of the + * translation unit will be suppressed. For example, this suppresses + * the completion of tentative declarations in C and of + * instantiation of implicitly-instantiation function templates in + * C++. This option is typically used when parsing a header with the + * intent of producing a precompiled header. + */ + CXTranslationUnit_Incomplete = 0x02, + + /** + * \brief Used to indicate that the translation unit should be built with an + * implicit precompiled header for the preamble. + * + * An implicit precompiled header is used as an optimization when a + * particular translation unit is likely to be reparsed many times + * when the sources aren't changing that often. In this case, an + * implicit precompiled header will be built containing all of the + * initial includes at the top of the main file (what we refer to as + * the "preamble" of the file). In subsequent parses, if the + * preamble or the files in it have not changed, \c + * clang_reparseTranslationUnit() will re-use the implicit + * precompiled header to improve parsing performance. + */ + CXTranslationUnit_PrecompiledPreamble = 0x04, + + /** + * \brief Used to indicate that the translation unit should cache some + * code-completion results with each reparse of the source file. + * + * Caching of code-completion results is a performance optimization that + * introduces some overhead to reparsing but improves the performance of + * code-completion operations. + */ + CXTranslationUnit_CacheCompletionResults = 0x08 +}; + +/** + * \brief Returns the set of flags that is suitable for parsing a translation + * unit that is being edited. + * + * The set of flags returned provide options for \c clang_parseTranslationUnit() + * to indicate that the translation unit is likely to be reparsed many times, + * either explicitly (via \c clang_reparseTranslationUnit()) or implicitly + * (e.g., by code completion (\c clang_codeCompletionAt())). The returned flag + * set contains an unspecified set of optimizations (e.g., the precompiled + * preamble) geared toward improving the performance of these routines. The + * set of optimizations enabled may change from one version to the next. + */ +CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void); + +/** + * \brief Parse the given source file and the translation unit corresponding + * to that file. + * + * This routine is the main entry point for the Clang C API, providing the + * ability to parse a source file into a translation unit that can then be + * queried by other functions in the API. This routine accepts a set of + * command-line arguments so that the compilation can be configured in the same + * way that the compiler is configured on the command line. + * + * \param CIdx The index object with which the translation unit will be + * associated. + * + * \param source_filename The name of the source file to load, or NULL if the + * source file is included in \p clang_command_line_args. + * + * \param command_line_args The command-line arguments that would be + * passed to the \c clang executable if it were being invoked out-of-process. + * These command-line options will be parsed and will affect how the translation + * unit is parsed. Note that the following options are ignored: '-c', + * '-emit-ast', '-fsyntex-only' (which is the default), and '-o '. + * + * \param num_command_line_args The number of command-line arguments in + * \p command_line_args. + * + * \param unsaved_files the files that have not yet been saved to disk + * but may be required for parsing, including the contents of + * those files. The contents and name of these files (as specified by + * CXUnsavedFile) are copied when necessary, so the client only needs to + * guarantee their validity until the call to this function returns. + * + * \param num_unsaved_files the number of unsaved file entries in \p + * unsaved_files. + * + * \param options A bitmask of options that affects how the translation unit + * is managed but not its compilation. This should be a bitwise OR of the + * CXTranslationUnit_XXX flags. + * + * \returns A new translation unit describing the parsed code and containing + * any diagnostics produced by the compiler. If there is a failure from which + * the compiler cannot recover, returns NULL. + */ +CINDEX_LINKAGE CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, + const char *source_filename, + const char * const *command_line_args, + int num_command_line_args, + struct CXUnsavedFile *unsaved_files, + unsigned num_unsaved_files, + unsigned options); + +/** + * \brief Flags that control how translation units are saved. + * + * The enumerators in this enumeration type are meant to be bitwise + * ORed together to specify which options should be used when + * saving the translation unit. + */ +enum CXSaveTranslationUnit_Flags { + /** + * \brief Used to indicate that no special saving options are needed. + */ + CXSaveTranslationUnit_None = 0x0 +}; + +/** + * \brief Returns the set of flags that is suitable for saving a translation + * unit. + * + * The set of flags returned provide options for + * \c clang_saveTranslationUnit() by default. The returned flag + * set contains an unspecified set of options that save translation units with + * the most commonly-requested data. + */ +CINDEX_LINKAGE unsigned clang_defaultSaveOptions(CXTranslationUnit TU); + +/** + * \brief Saves a translation unit into a serialized representation of + * that translation unit on disk. + * + * Any translation unit that was parsed without error can be saved + * into a file. The translation unit can then be deserialized into a + * new \c CXTranslationUnit with \c clang_createTranslationUnit() or, + * if it is an incomplete translation unit that corresponds to a + * header, used as a precompiled header when parsing other translation + * units. + * + * \param TU The translation unit to save. + * + * \param FileName The file to which the translation unit will be saved. + * + * \param options A bitmask of options that affects how the translation unit + * is saved. This should be a bitwise OR of the + * CXSaveTranslationUnit_XXX flags. + * + * \returns Zero if the translation unit was saved successfully, a + * non-zero value otherwise. + */ +CINDEX_LINKAGE int clang_saveTranslationUnit(CXTranslationUnit TU, + const char *FileName, + unsigned options); + /** * \brief Destroy the specified CXTranslationUnit object. */ CINDEX_LINKAGE void clang_disposeTranslationUnit(CXTranslationUnit); +/** + * \brief Flags that control the reparsing of translation units. + * + * The enumerators in this enumeration type are meant to be bitwise + * ORed together to specify which options should be used when + * reparsing the translation unit. + */ +enum CXReparse_Flags { + /** + * \brief Used to indicate that no special reparsing options are needed. + */ + CXReparse_None = 0x0 +}; + +/** + * \brief Returns the set of flags that is suitable for reparsing a translation + * unit. + * + * The set of flags returned provide options for + * \c clang_reparseTranslationUnit() by default. The returned flag + * set contains an unspecified set of optimizations geared toward common uses + * of reparsing. The set of optimizations enabled may change from one version + * to the next. + */ +CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU); + +/** + * \brief Reparse the source files that produced this translation unit. + * + * This routine can be used to re-parse the source files that originally + * created the given translation unit, for example because those source files + * have changed (either on disk or as passed via \p unsaved_files). The + * source code will be reparsed with the same command-line options as it + * was originally parsed. + * + * Reparsing a translation unit invalidates all cursors and source locations + * that refer into that translation unit. This makes reparsing a translation + * unit semantically equivalent to destroying the translation unit and then + * creating a new translation unit with the same command-line arguments. + * However, it may be more efficient to reparse a translation + * unit using this routine. + * + * \param TU The translation unit whose contents will be re-parsed. The + * translation unit must originally have been built with + * \c clang_createTranslationUnitFromSourceFile(). + * + * \param num_unsaved_files The number of unsaved file entries in \p + * unsaved_files. + * + * \param unsaved_files The files that have not yet been saved to disk + * but may be required for parsing, including the contents of + * those files. The contents and name of these files (as specified by + * CXUnsavedFile) are copied when necessary, so the client only needs to + * guarantee their validity until the call to this function returns. + * + * \param options A bitset of options composed of the flags in CXReparse_Flags. + * The function \c clang_defaultReparseOptions() produces a default set of + * options recommended for most uses, based on the translation unit. + * + * \returns 0 if the sources could be reparsed. A non-zero value will be + * returned if reparsing was impossible, such that the translation unit is + * invalid. In such cases, the only valid call for \p TU is + * \c clang_disposeTranslationUnit(TU). + */ +CINDEX_LINKAGE int clang_reparseTranslationUnit(CXTranslationUnit TU, + unsigned num_unsaved_files, + struct CXUnsavedFile *unsaved_files, + unsigned options); + /** * @} */ @@ -705,9 +976,33 @@ enum CXCursorKind { CXCursor_Namespace = 22, /** \brief A linkage specification, e.g. 'extern "C"'. */ CXCursor_LinkageSpec = 23, - + /** \brief A C++ constructor. */ + CXCursor_Constructor = 24, + /** \brief A C++ destructor. */ + CXCursor_Destructor = 25, + /** \brief A C++ conversion function. */ + CXCursor_ConversionFunction = 26, + /** \brief A C++ template type parameter. */ + CXCursor_TemplateTypeParameter = 27, + /** \brief A C++ non-type template parameter. */ + CXCursor_NonTypeTemplateParameter = 28, + /** \brief A C++ template template parameter. */ + CXCursor_TemplateTemplateParameter = 29, + /** \brief A C++ function template. */ + CXCursor_FunctionTemplate = 30, + /** \brief A C++ class template. */ + CXCursor_ClassTemplate = 31, + /** \brief A C++ class template partial specialization. */ + CXCursor_ClassTemplatePartialSpecialization = 32, + /** \brief A C++ namespace alias declaration. */ + CXCursor_NamespaceAlias = 33, + /** \brief A C++ using directive. */ + CXCursor_UsingDirective = 34, + /** \brief A using declaration. */ + CXCursor_UsingDeclaration = 35, + CXCursor_FirstDecl = CXCursor_UnexposedDecl, - CXCursor_LastDecl = CXCursor_LinkageSpec, + CXCursor_LastDecl = CXCursor_UsingDeclaration, /* References */ CXCursor_FirstRef = 40, /* Decl references */ @@ -730,7 +1025,17 @@ enum CXCursorKind { * referenced by the type of size is the typedef for size_type. */ CXCursor_TypeRef = 43, - CXCursor_LastRef = 43, + CXCursor_CXXBaseSpecifier = 44, + /** + * \brief A reference to a class template, function template, or template + * template parameter. + */ + CXCursor_TemplateRef = 45, + /** + * \brief A reference to a namespace or namespace alias. + */ + CXCursor_NamespaceRef = 46, + CXCursor_LastRef = CXCursor_NamespaceRef, /* Error conditions */ CXCursor_FirstInvalid = 70, @@ -948,6 +1253,16 @@ enum CXLinkageKind { */ CINDEX_LINKAGE enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor); +/** + * \brief Determine the availability of the entity that this cursor refers to. + * + * \param cursor The cursor to query. + * + * \returns The availability of the cursor. + */ +CINDEX_LINKAGE enum CXAvailabilityKind +clang_getCursorAvailability(CXCursor cursor); + /** * \brief Describe the "language" of the entity referred to by a cursor. */ @@ -1023,7 +1338,7 @@ CINDEX_LINKAGE CXSourceRange clang_getCursorExtent(CXCursor); /** * @} */ - + /** * \defgroup CINDEX_TYPES Type information for CXCursors * @@ -1151,6 +1466,53 @@ CINDEX_LINKAGE CXType clang_getResultType(CXType T); */ CINDEX_LINKAGE CXType clang_getCursorResultType(CXCursor C); +/** + * \brief Return 1 if the CXType is a POD (plain old data) type, and 0 + * otherwise. + */ +CINDEX_LINKAGE unsigned clang_isPODType(CXType T); + +/** + * \brief Returns 1 if the base class specified by the cursor with kind + * CX_CXXBaseSpecifier is virtual. + */ +CINDEX_LINKAGE unsigned clang_isVirtualBase(CXCursor); + +/** + * \brief Represents the C++ access control level to a base class for a + * cursor with kind CX_CXXBaseSpecifier. + */ +enum CX_CXXAccessSpecifier { + CX_CXXInvalidAccessSpecifier, + CX_CXXPublic, + CX_CXXProtected, + CX_CXXPrivate +}; + +/** + * \brief Returns the access control level for the C++ base specifier + * represented by a cursor with kind CX_CXXBaseSpecifier. + */ +CINDEX_LINKAGE enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor); + +/** + * @} + */ + +/** + * \defgroup CINDEX_ATTRIBUTES Information for attributes + * + * @{ + */ + + +/** + * \brief For cursors representing an iboutletcollection attribute, + * this function returns the collection element type. + * + */ +CINDEX_LINKAGE CXType clang_getIBOutletCollectionType(CXCursor); + /** * @} */ @@ -1364,10 +1726,60 @@ CINDEX_LINKAGE unsigned clang_isCursorDefinition(CXCursor); */ /** - * \brief Determine if a C++ member function is declared 'static'. + * \brief Determine if a C++ member function or member function template is + * declared 'static'. */ CINDEX_LINKAGE unsigned clang_CXXMethod_isStatic(CXCursor C); +/** + * \brief Given a cursor that represents a template, determine + * the cursor kind of the specializations would be generated by instantiating + * the template. + * + * This routine can be used to determine what flavor of function template, + * class template, or class template partial specialization is stored in the + * cursor. For example, it can describe whether a class template cursor is + * declared with "struct", "class" or "union". + * + * \param C The cursor to query. This cursor should represent a template + * declaration. + * + * \returns The cursor kind of the specializations that would be generated + * by instantiating the template \p C. If \p C is not a template, returns + * \c CXCursor_NoDeclFound. + */ +CINDEX_LINKAGE enum CXCursorKind clang_getTemplateCursorKind(CXCursor C); + +/** + * \brief Given a cursor that may represent a specialization or instantiation + * of a template, retrieve the cursor that represents the template that it + * specializes or from which it was instantiated. + * + * This routine determines the template involved both for explicit + * specializations of templates and for implicit instantiations of the template, + * both of which are referred to as "specializations". For a class template + * specialization (e.g., \c std::vector), this routine will return + * either the primary template (\c std::vector) or, if the specialization was + * instantiated from a class template partial specialization, the class template + * partial specialization. For a class template partial specialization and a + * function template specialization (including instantiations), this + * this routine will return the specialized template. + * + * For members of a class template (e.g., member functions, member classes, or + * static data members), returns the specialized or instantiated member. + * Although not strictly "templates" in the C++ language, members of class + * templates have the same notions of specializations and instantiations that + * templates do, so this routine treats them similarly. + * + * \param C A cursor that may be a specialization of a template or a member + * of a template. + * + * \returns If the given cursor is a specialization or instantiation of a + * template or a member thereof, the template or member that it specializes or + * from which it was instantiated. Otherwise, returns a NULL cursor. + */ +CINDEX_LINKAGE CXCursor clang_getSpecializedCursorTemplate(CXCursor C); + /** * @} */ @@ -1816,6 +2228,17 @@ clang_getNumCompletionChunks(CXCompletionString completion_string); CINDEX_LINKAGE unsigned clang_getCompletionPriority(CXCompletionString completion_string); +/** + * \brief Determine the availability of the entity that this code-completion + * string refers to. + * + * \param completion_string The completion string to query. + * + * \returns The availability of the completion string. + */ +CINDEX_LINKAGE enum CXAvailabilityKind +clang_getCompletionAvailability(CXCompletionString completion_string); + /** * \brief Contains the results of code-completion. * @@ -1922,19 +2345,134 @@ CINDEX_LINKAGE CXCodeCompleteResults *clang_codeComplete(CXIndex CIdx, const char *source_filename, int num_command_line_args, - const char **command_line_args, + const char * const *command_line_args, unsigned num_unsaved_files, struct CXUnsavedFile *unsaved_files, const char *complete_filename, unsigned complete_line, unsigned complete_column); +/** + * \brief Flags that can be passed to \c clang_codeCompleteAt() to + * modify its behavior. + * + * The enumerators in this enumeration can be bitwise-OR'd together to + * provide multiple options to \c clang_codeCompleteAt(). + */ +enum CXCodeComplete_Flags { + /** + * \brief Whether to include macros within the set of code + * completions returned. + */ + CXCodeComplete_IncludeMacros = 0x01, + + /** + * \brief Whether to include code patterns for language constructs + * within the set of code completions, e.g., for loops. + */ + CXCodeComplete_IncludeCodePatterns = 0x02 +}; + +/** + * \brief Returns a default set of code-completion options that can be + * passed to\c clang_codeCompleteAt(). + */ +CINDEX_LINKAGE unsigned clang_defaultCodeCompleteOptions(void); + +/** + * \brief Perform code completion at a given location in a translation unit. + * + * This function performs code completion at a particular file, line, and + * column within source code, providing results that suggest potential + * code snippets based on the context of the completion. The basic model + * for code completion is that Clang will parse a complete source file, + * performing syntax checking up to the location where code-completion has + * been requested. At that point, a special code-completion token is passed + * to the parser, which recognizes this token and determines, based on the + * current location in the C/Objective-C/C++ grammar and the state of + * semantic analysis, what completions to provide. These completions are + * returned via a new \c CXCodeCompleteResults structure. + * + * Code completion itself is meant to be triggered by the client when the + * user types punctuation characters or whitespace, at which point the + * code-completion location will coincide with the cursor. For example, if \c p + * is a pointer, code-completion might be triggered after the "-" and then + * after the ">" in \c p->. When the code-completion location is afer the ">", + * the completion results will provide, e.g., the members of the struct that + * "p" points to. The client is responsible for placing the cursor at the + * beginning of the token currently being typed, then filtering the results + * based on the contents of the token. For example, when code-completing for + * the expression \c p->get, the client should provide the location just after + * the ">" (e.g., pointing at the "g") to this code-completion hook. Then, the + * client can filter the results based on the current token text ("get"), only + * showing those results that start with "get". The intent of this interface + * is to separate the relatively high-latency acquisition of code-completion + * results from the filtering of results on a per-character basis, which must + * have a lower latency. + * + * \param TU The translation unit in which code-completion should + * occur. The source files for this translation unit need not be + * completely up-to-date (and the contents of those source files may + * be overridden via \p unsaved_files). Cursors referring into the + * translation unit may be invalidated by this invocation. + * + * \param complete_filename The name of the source file where code + * completion should be performed. This filename may be any file + * included in the translation unit. + * + * \param complete_line The line at which code-completion should occur. + * + * \param complete_column The column at which code-completion should occur. + * Note that the column should point just after the syntactic construct that + * initiated code completion, and not in the middle of a lexical token. + * + * \param unsaved_files the Tiles that have not yet been saved to disk + * but may be required for parsing or code completion, including the + * contents of those files. The contents and name of these files (as + * specified by CXUnsavedFile) are copied when necessary, so the + * client only needs to guarantee their validity until the call to + * this function returns. + * + * \param num_unsaved_files The number of unsaved file entries in \p + * unsaved_files. + * + * \param options Extra options that control the behavior of code + * completion, expressed as a bitwise OR of the enumerators of the + * CXCodeComplete_Flags enumeration. The + * \c clang_defaultCodeCompleteOptions() function returns a default set + * of code-completion options. + * + * \returns If successful, a new \c CXCodeCompleteResults structure + * containing code-completion results, which should eventually be + * freed with \c clang_disposeCodeCompleteResults(). If code + * completion fails, returns NULL. + */ +CINDEX_LINKAGE +CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, + const char *complete_filename, + unsigned complete_line, + unsigned complete_column, + struct CXUnsavedFile *unsaved_files, + unsigned num_unsaved_files, + unsigned options); + +/** + * \brief Sort the code-completion results in case-insensitive alphabetical + * order. + * + * \param Results The set of results to sort. + * \param NumResults The number of results in \p Results. + */ +CINDEX_LINKAGE +void clang_sortCodeCompletionResults(CXCompletionResult *Results, + unsigned NumResults); + /** * \brief Free the given set of code-completion results. */ CINDEX_LINKAGE void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results); - + /** * \brief Determine the number of diagnostics produced prior to the * location where code completion was performed. diff --git a/include/clang/AST/ASTConsumer.h b/include/clang/AST/ASTConsumer.h index 06113954fc4..84833c099f9 100644 --- a/include/clang/AST/ASTConsumer.h +++ b/include/clang/AST/ASTConsumer.h @@ -18,9 +18,10 @@ namespace clang { class ASTContext; class CXXRecordDecl; class DeclGroupRef; - class TagDecl; class HandleTagDeclDefinition; + class ASTDeserializationListener; // layering violation because void* is ugly class SemaConsumer; // layering violation required for safe SemaConsumer + class TagDecl; class VarDecl; /// ASTConsumer - This is an abstract interface that should be implemented by @@ -48,6 +49,11 @@ public: /// elements). Use Decl::getNextDeclarator() to walk the chain. virtual void HandleTopLevelDecl(DeclGroupRef D); + /// HandleInterestingDecl - Handle the specified interesting declaration. This + /// is called by the AST reader when deserializing things that might interest + /// the consumer. The default implementation forwards to HandleTopLevelDecl. + virtual void HandleInterestingDecl(DeclGroupRef D); + /// HandleTranslationUnit - This method is called when the ASTs for entire /// translation unit have been parsed. virtual void HandleTranslationUnit(ASTContext &Ctx) {} @@ -80,6 +86,12 @@ public: /// it was actually used. virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {} + /// \brief If the consumer is interested in entities being deserialized from + /// AST files, it should return a pointer to a ASTDeserializationListener here + /// + /// The return type is void* because ASTDS lives in Frontend. + virtual ASTDeserializationListener *GetASTDeserializationListener() { return 0; } + /// PrintStats - If desired, print any statistics. virtual void PrintStats() {} diff --git a/include/clang/AST/ASTContext.h b/include/clang/AST/ASTContext.h index 3799451360f..ae4ee946fe2 100644 --- a/include/clang/AST/ASTContext.h +++ b/include/clang/AST/ASTContext.h @@ -18,7 +18,6 @@ #include "clang/Basic/LangOptions.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/PartialDiagnostic.h" -#include "clang/AST/Attr.h" #include "clang/AST/Decl.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/PrettyPrinter.h" @@ -50,6 +49,7 @@ namespace clang { class SelectorTable; class SourceManager; class TargetInfo; + class CXXABI; // Decls class DeclContext; class CXXMethodDecl; @@ -198,7 +198,7 @@ class ASTContext { /// /// Since so few decls have attrs, we keep them in a hash map instead of /// wasting space in the Decl class. - llvm::DenseMap DeclAttrs; + llvm::DenseMap DeclAttrs; /// \brief Keeps track of the static data member templates from which /// static data members of class template specializations were instantiated. @@ -275,13 +275,18 @@ class ASTContext { /// this ASTContext object. LangOptions LangOpts; - /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects. - bool FreeMemory; - llvm::MallocAllocator MallocAlloc; + /// \brief The allocator used to create AST objects. + /// + /// AST objects are never destructed; rather, all memory associated with the + /// AST objects will be released when the ASTContext itself is destroyed. llvm::BumpPtrAllocator BumpAlloc; /// \brief Allocator for partial diagnostics. PartialDiagnostic::StorageAllocator DiagAllocator; + + /// \brief The current C++ ABI. + llvm::OwningPtr ABI; + CXXABI *createCXXABI(const TargetInfo &T); public: const TargetInfo &Target; @@ -301,13 +306,9 @@ public: SourceManager& getSourceManager() { return SourceMgr; } const SourceManager& getSourceManager() const { return SourceMgr; } void *Allocate(unsigned Size, unsigned Align = 8) { - return FreeMemory ? MallocAlloc.Allocate(Size, Align) : - BumpAlloc.Allocate(Size, Align); - } - void Deallocate(void *Ptr) { - if (FreeMemory) - MallocAlloc.Deallocate(Ptr); + return BumpAlloc.Allocate(Size, Align); } + void Deallocate(void *Ptr) { } PartialDiagnostic::StorageAllocator &getDiagAllocator() { return DiagAllocator; @@ -320,10 +321,10 @@ public: } /// \brief Retrieve the attributes for the given declaration. - Attr*& getDeclAttrs(const Decl *D) { return DeclAttrs[D]; } + AttrVec& getDeclAttrs(const Decl *D); /// \brief Erase the attributes corresponding to the given declaration. - void eraseDeclAttrs(const Decl *D) { DeclAttrs.erase(D); } + void eraseDeclAttrs(const Decl *D); /// \brief If this variable is an instantiated static data member of a /// class template specialization, returns the templated static data member @@ -393,7 +394,7 @@ public: ASTContext(const LangOptions& LOpts, SourceManager &SM, const TargetInfo &t, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, - bool FreeMemory = true, unsigned size_reserve=0); + unsigned size_reserve); ~ASTContext(); @@ -520,7 +521,7 @@ public: llvm::SmallVectorImpl &Layout); /// This builds the struct used for __block variables. - QualType BuildByRefType(const char *DeclName, QualType Ty); + QualType BuildByRefType(llvm::StringRef DeclName, QualType Ty); /// Returns true iff we need copy/dispose helpers for the given type. bool BlockRequiresCopying(QualType Ty); @@ -873,7 +874,8 @@ public: return getExtQualType(T, Qs); } - DeclarationName getNameForTemplate(TemplateName Name); + DeclarationNameInfo getNameForTemplate(TemplateName Name, + SourceLocation NameLoc); TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End); @@ -909,6 +911,11 @@ public: /// Qualifiers::GC getObjCGCAttrKind(const QualType &Ty) const; + /// areCompatibleVectorTypes - Return true if the given vector types either + /// are of the same unqualified type or if one is GCC and other - equivalent + /// AltiVec vector type. + bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec); + /// isObjCNSObjectType - Return true if this is an NSObject object with /// its NSObject attribute set. bool isObjCNSObjectType(QualType Ty) const; @@ -1002,13 +1009,12 @@ public: /// of class definition. const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD); - void CollectObjCIvars(const ObjCInterfaceDecl *OI, - llvm::SmallVectorImpl &Fields); - void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, llvm::SmallVectorImpl &Ivars); - void CollectNonClassIvars(const ObjCInterfaceDecl *OI, - llvm::SmallVectorImpl &Ivars); + + void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, + llvm::SmallVectorImpl &Ivars); + unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI); void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet &Protocols); @@ -1067,8 +1073,6 @@ public: bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2); - /// \brief Retrieves the "canonical" declaration of - /// \brief Retrieves the "canonical" nested name specifier for a /// given nested name specifier. /// @@ -1218,7 +1222,8 @@ public: //===--------------------------------------------------------------------===// /// Compatibility predicates used to check assignment expressions. - bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1 + bool typesAreCompatible(QualType T1, QualType T2, + bool CompareUnqualified = false); // C99 6.2.7p1 bool typesAreBlockPointerCompatible(QualType, QualType); @@ -1235,6 +1240,8 @@ public: bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, bool ForCompare); + bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS); + // Check the safety of assignment from LHS to RHS bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT); @@ -1246,10 +1253,13 @@ public: bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT); - + bool canBindObjCObjectType(QualType To, QualType From); + // Functions for calculating composite types - QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false); - QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false); + QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, + bool Unqualified = false); + QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, + bool Unqualified = false); QualType mergeObjCGCQualifiers(QualType, QualType); @@ -1257,6 +1267,10 @@ public: /// that are common to binary operators (C99 6.3.1.8, C++ [expr]p9) /// and returns the result type of that conversion. QualType UsualArithmeticConversionsType(QualType lhs, QualType rhs); + + void ResetObjCLayout(const ObjCContainerDecl *CD) { + ObjCLayouts[CD] = 0; + } //===--------------------------------------------------------------------===// // Integer Predicates @@ -1337,6 +1351,17 @@ public: /// when it is called. void AddDeallocation(void (*Callback)(void*), void *Data); + GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD); + GVALinkage GetGVALinkageForVariable(const VarDecl *VD); + + /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH + /// lazily, only when used; this is only relevant for function or file scoped + /// var definitions. + /// + /// \returns true if the function/var must be CodeGen'ed/deserialized even if + /// it is not used. + bool DeclMustBeEmitted(const Decl *D); + //===--------------------------------------------------------------------===// // Statistics //===--------------------------------------------------------------------===// @@ -1386,7 +1411,7 @@ private: const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D, const ObjCImplementationDecl *Impl); - + private: /// \brief A set of deallocations that should be performed when the /// ASTContext is destroyed. diff --git a/include/clang/AST/ASTImporter.h b/include/clang/AST/ASTImporter.h index 7975c437887..9380058118c 100644 --- a/include/clang/AST/ASTImporter.h +++ b/include/clang/AST/ASTImporter.h @@ -14,8 +14,8 @@ #ifndef LLVM_CLANG_AST_ASTIMPORTER_H #define LLVM_CLANG_AST_ASTIMPORTER_H -#include "clang/AST/Type.h" #include "clang/AST/DeclarationName.h" +#include "clang/AST/Type.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" diff --git a/include/clang/AST/Attr.h b/include/clang/AST/Attr.h index 9faa62eef6f..62ca49fbf3b 100644 --- a/include/clang/AST/Attr.h +++ b/include/clang/AST/Attr.h @@ -15,8 +15,11 @@ #define LLVM_CLANG_AST_ATTR_H #include "llvm/Support/Casting.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "clang/Basic/AttrKinds.h" +#include "clang/AST/Type.h" +#include "clang/Basic/SourceLocation.h" #include #include #include @@ -27,28 +30,39 @@ namespace clang { class IdentifierInfo; class ObjCInterfaceDecl; class Expr; + class QualType; + class FunctionDecl; + class TypeSourceInfo; } // Defined in ASTContext.h void *operator new(size_t Bytes, clang::ASTContext &C, size_t Alignment = 16) throw (); +// FIXME: Being forced to not have a default argument here due to redeclaration +// rules on default arguments sucks +void *operator new[](size_t Bytes, clang::ASTContext &C, + size_t Alignment) throw (); // It is good practice to pair new/delete operators. Also, MSVC gives many // warnings if a matching delete overload is not declared, even though the // throw() spec guarantees it will not be implicitly called. void operator delete(void *Ptr, clang::ASTContext &C, size_t) throw (); +void operator delete[](void *Ptr, clang::ASTContext &C, size_t) + throw (); namespace clang { /// Attr - This represents one attribute. class Attr { private: - Attr *Next; - attr::Kind AttrKind; + SourceLocation Loc; + unsigned AttrKind : 16; bool Inherited : 1; protected: + virtual ~Attr(); + void* operator new(size_t bytes) throw() { assert(0 && "Attrs cannot be allocated with regular 'new'."); return 0; @@ -57,41 +71,36 @@ protected: assert(0 && "Attrs cannot be released with regular 'delete'."); } -protected: - Attr(attr::Kind AK) : Next(0), AttrKind(AK), Inherited(false) {} - virtual ~Attr() { - assert(Next == 0 && "Destroy didn't work"); - } public: - virtual void Destroy(ASTContext &C); + // Forward so that the regular new and delete do not hide global ones. + void* operator new(size_t Bytes, ASTContext &C, + size_t Alignment = 16) throw() { + return ::operator new(Bytes, C, Alignment); + } + void operator delete(void *Ptr, ASTContext &C, + size_t Alignment) throw() { + return ::operator delete(Ptr, C, Alignment); + } + +protected: + Attr(attr::Kind AK, SourceLocation L) + : Loc(L), AttrKind(AK), Inherited(false) {} + +public: /// \brief Whether this attribute should be merged to new /// declarations. virtual bool isMerged() const { return true; } - attr::Kind getKind() const { return AttrKind; } - - Attr *getNext() { return Next; } - const Attr *getNext() const { return Next; } - void setNext(Attr *next) { Next = next; } - - template const T *getNext() const { - for (const Attr *attr = getNext(); attr; attr = attr->getNext()) - if (const T *V = dyn_cast(attr)) - return V; - return 0; + attr::Kind getKind() const { + return static_cast(AttrKind); } + SourceLocation getLocation() const { return Loc; } + void setLocation(SourceLocation L) { Loc = L; } + bool isInherited() const { return Inherited; } - void setInherited(bool value) { Inherited = value; } - - void addAttr(Attr *attr) { - assert((attr != 0) && "addAttr(): attr is null"); - - // FIXME: This doesn't preserve the order in any way. - attr->Next = Next; - Next = attr; - } + void setInherited(bool I) { Inherited = I; } // Clone this attribute. virtual Attr* clone(ASTContext &C) const = 0; @@ -101,490 +110,112 @@ public: }; #include "clang/AST/Attrs.inc" - -class AttrWithString : public Attr { -private: - const char *Str; - unsigned StrLen; -protected: - AttrWithString(attr::Kind AK, ASTContext &C, llvm::StringRef s); - llvm::StringRef getString() const { return llvm::StringRef(Str, StrLen); } - void ReplaceString(ASTContext &C, llvm::StringRef newS); -public: - virtual void Destroy(ASTContext &C); -}; -#define DEF_SIMPLE_ATTR(ATTR) \ -class ATTR##Attr : public Attr { \ -public: \ - ATTR##Attr() : Attr(attr::ATTR) {} \ - virtual Attr *clone(ASTContext &C) const; \ - static bool classof(const Attr *A) { return A->getKind() == attr::ATTR; } \ - static bool classof(const ATTR##Attr *A) { return true; } \ +/// AttrVec - A vector of Attr, which is how they are stored on the AST. +typedef llvm::SmallVector AttrVec; +typedef llvm::SmallVector ConstAttrVec; + +/// DestroyAttrs - Destroy the contents of an AttrVec. +inline void DestroyAttrs (AttrVec& V, ASTContext &C) { } -DEF_SIMPLE_ATTR(Packed); +/// specific_attr_iterator - Iterates over a subrange of an AttrVec, only +/// providing attributes that are of a specifc type. +template +class specific_attr_iterator { + /// Current - The current, underlying iterator. + /// In order to ensure we don't dereference an invalid iterator unless + /// specifically requested, we don't necessarily advance this all the + /// way. Instead, we advance it when an operation is requested; if the + /// operation is acting on what should be a past-the-end iterator, + /// then we offer no guarantees, but this way we do not dererence a + /// past-the-end iterator when we move to a past-the-end position. + mutable AttrVec::const_iterator Current; -/// \brief Attribute for specifying a maximum field alignment; this is only -/// valid on record decls. -class MaxFieldAlignmentAttr : public Attr { - unsigned Alignment; + void AdvanceToNext() const { + while (!llvm::isa(*Current)) + ++Current; + } + + void AdvanceToNext(AttrVec::const_iterator I) const { + while (Current != I && !llvm::isa(*Current)) + ++Current; + } public: - MaxFieldAlignmentAttr(unsigned alignment) - : Attr(attr::MaxFieldAlignment), Alignment(alignment) {} + typedef SpecificAttr* value_type; + typedef SpecificAttr* reference; + typedef SpecificAttr* pointer; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; - /// getAlignment - The specified alignment in bits. - unsigned getAlignment() const { return Alignment; } + specific_attr_iterator() : Current() { } + explicit specific_attr_iterator(AttrVec::const_iterator i) : Current(i) { } - virtual Attr* clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::MaxFieldAlignment; + reference operator*() const { + AdvanceToNext(); + return llvm::cast(*Current); } - static bool classof(const MaxFieldAlignmentAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(AlignMac68k); - -/// \brief Atribute for specifying the alignment of a variable or type. -/// -/// This node will either contain the precise Alignment (in bits, not bytes!) -/// or will contain the expression for the alignment attribute in the case of -/// a dependent expression within a class or function template. At template -/// instantiation time these are transformed into concrete attributes. -class AlignedAttr : public Attr { - unsigned Alignment; - Expr *AlignmentExpr; -public: - AlignedAttr(unsigned alignment) - : Attr(attr::Aligned), Alignment(alignment), AlignmentExpr(0) {} - AlignedAttr(Expr *E) - : Attr(attr::Aligned), Alignment(0), AlignmentExpr(E) {} - - /// getAlignmentExpr - Get a dependent alignment expression if one is present. - Expr *getAlignmentExpr() const { - return AlignmentExpr; + pointer operator->() const { + AdvanceToNext(); + return llvm::cast(*Current); } - /// isDependent - Is the alignment a dependent expression - bool isDependent() const { - return getAlignmentExpr(); + specific_attr_iterator& operator++() { + ++Current; + return *this; + } + specific_attr_iterator operator++(int) { + specific_attr_iterator Tmp(*this); + ++(*this); + return Tmp; } - /// getAlignment - The specified alignment in bits. Requires !isDependent(). - unsigned getAlignment() const { - assert(!isDependent() && "Cannot get a value dependent alignment"); - return Alignment; - } - - /// getMaxAlignment - Get the maximum alignment of attributes on this list. - unsigned getMaxAlignment() const { - const AlignedAttr *Next = getNext(); - if (Next) - return std::max(Next->getMaxAlignment(), getAlignment()); + friend bool operator==(specific_attr_iterator Left, + specific_attr_iterator Right) { + if (Left.Current < Right.Current) + Left.AdvanceToNext(Right.Current); else - return getAlignment(); + Right.AdvanceToNext(Left.Current); + return Left.Current == Right.Current; } - - virtual Attr* clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::Aligned; + friend bool operator!=(specific_attr_iterator Left, + specific_attr_iterator Right) { + return !(Left == Right); } - static bool classof(const AlignedAttr *A) { return true; } }; -class AnnotateAttr : public AttrWithString { -public: - AnnotateAttr(ASTContext &C, llvm::StringRef ann) - : AttrWithString(attr::Annotate, C, ann) {} - - llvm::StringRef getAnnotation() const { return getString(); } - - virtual Attr* clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::Annotate; - } - static bool classof(const AnnotateAttr *A) { return true; } -}; - -class AsmLabelAttr : public AttrWithString { -public: - AsmLabelAttr(ASTContext &C, llvm::StringRef L) - : AttrWithString(attr::AsmLabel, C, L) {} - - llvm::StringRef getLabel() const { return getString(); } - - virtual Attr* clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::AsmLabel; - } - static bool classof(const AsmLabelAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(AlwaysInline); - -class AliasAttr : public AttrWithString { -public: - AliasAttr(ASTContext &C, llvm::StringRef aliasee) - : AttrWithString(attr::Alias, C, aliasee) {} - - llvm::StringRef getAliasee() const { return getString(); } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::Alias; } - static bool classof(const AliasAttr *A) { return true; } -}; - -class ConstructorAttr : public Attr { - int priority; -public: - ConstructorAttr(int p) : Attr(attr::Constructor), priority(p) {} - - int getPriority() const { return priority; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) - { return A->getKind() == attr::Constructor; } - static bool classof(const ConstructorAttr *A) { return true; } -}; - -class DestructorAttr : public Attr { - int priority; -public: - DestructorAttr(int p) : Attr(attr::Destructor), priority(p) {} - - int getPriority() const { return priority; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) - { return A->getKind() == attr::Destructor; } - static bool classof(const DestructorAttr *A) { return true; } -}; - -class IBOutletAttr : public Attr { -public: - IBOutletAttr() : Attr(attr::IBOutlet) {} - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::IBOutlet; - } - static bool classof(const IBOutletAttr *A) { return true; } -}; - -class IBOutletCollectionAttr : public Attr { - const ObjCInterfaceDecl *D; -public: - IBOutletCollectionAttr(const ObjCInterfaceDecl *d = 0) - : Attr(attr::IBOutletCollection), D(d) {} - - const ObjCInterfaceDecl *getClass() const { return D; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::IBOutletCollection; - } - static bool classof(const IBOutletCollectionAttr *A) { return true; } -}; - -class IBActionAttr : public Attr { -public: - IBActionAttr() : Attr(attr::IBAction) {} - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::IBAction; - } - static bool classof(const IBActionAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(AnalyzerNoReturn); -DEF_SIMPLE_ATTR(Deprecated); -DEF_SIMPLE_ATTR(GNUInline); -DEF_SIMPLE_ATTR(Malloc); -DEF_SIMPLE_ATTR(NoReturn); -DEF_SIMPLE_ATTR(NoInstrumentFunction); - -class SectionAttr : public AttrWithString { -public: - SectionAttr(ASTContext &C, llvm::StringRef N) - : AttrWithString(attr::Section, C, N) {} - - llvm::StringRef getName() const { return getString(); } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::Section; - } - static bool classof(const SectionAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(Unavailable); -DEF_SIMPLE_ATTR(Unused); -DEF_SIMPLE_ATTR(Used); -DEF_SIMPLE_ATTR(Weak); -DEF_SIMPLE_ATTR(WeakImport); -DEF_SIMPLE_ATTR(WeakRef); -DEF_SIMPLE_ATTR(NoThrow); -DEF_SIMPLE_ATTR(Const); -DEF_SIMPLE_ATTR(Pure); - -class NonNullAttr : public Attr { - unsigned* ArgNums; - unsigned Size; -public: - NonNullAttr(ASTContext &C, unsigned* arg_nums = 0, unsigned size = 0); - - virtual void Destroy(ASTContext &C); - - typedef const unsigned *iterator; - iterator begin() const { return ArgNums; } - iterator end() const { return ArgNums + Size; } - unsigned size() const { return Size; } - - bool isNonNull(unsigned arg) const { - return ArgNums ? std::binary_search(ArgNums, ArgNums+Size, arg) : true; - } - - virtual Attr *clone(ASTContext &C) const; - - static bool classof(const Attr *A) { return A->getKind() == attr::NonNull; } - static bool classof(const NonNullAttr *A) { return true; } -}; - -class FormatAttr : public AttrWithString { - int formatIdx, firstArg; -public: - FormatAttr(ASTContext &C, llvm::StringRef type, int idx, int first) - : AttrWithString(attr::Format, C, type), formatIdx(idx), firstArg(first) {} - - llvm::StringRef getType() const { return getString(); } - void setType(ASTContext &C, llvm::StringRef type); - int getFormatIdx() const { return formatIdx; } - int getFirstArg() const { return firstArg; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::Format; } - static bool classof(const FormatAttr *A) { return true; } -}; - -class FormatArgAttr : public Attr { - int formatIdx; -public: - FormatArgAttr(int idx) : Attr(attr::FormatArg), formatIdx(idx) {} - int getFormatIdx() const { return formatIdx; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::FormatArg; } - static bool classof(const FormatArgAttr *A) { return true; } -}; - -class SentinelAttr : public Attr { - int sentinel, NullPos; -public: - SentinelAttr(int sentinel_val, int nullPos) : Attr(attr::Sentinel), - sentinel(sentinel_val), NullPos(nullPos) {} - int getSentinel() const { return sentinel; } - int getNullPos() const { return NullPos; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::Sentinel; } - static bool classof(const SentinelAttr *A) { return true; } -}; - -class VisibilityAttr : public Attr { -public: - /// @brief An enumeration for the kinds of visibility of symbols. - enum VisibilityTypes { - DefaultVisibility = 0, - HiddenVisibility, - ProtectedVisibility - }; -private: - VisibilityTypes VisibilityType; -public: - VisibilityAttr(VisibilityTypes v) : Attr(attr::Visibility), - VisibilityType(v) {} - - VisibilityTypes getVisibility() const { return VisibilityType; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) - { return A->getKind() == attr::Visibility; } - static bool classof(const VisibilityAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(FastCall); -DEF_SIMPLE_ATTR(StdCall); -DEF_SIMPLE_ATTR(ThisCall); -DEF_SIMPLE_ATTR(CDecl); -DEF_SIMPLE_ATTR(TransparentUnion); -DEF_SIMPLE_ATTR(ObjCNSObject); -DEF_SIMPLE_ATTR(ObjCException); - -class OverloadableAttr : public Attr { -public: - OverloadableAttr() : Attr(attr::Overloadable) { } - - virtual bool isMerged() const { return false; } - - virtual Attr *clone(ASTContext &C) const; - - static bool classof(const Attr *A) - { return A->getKind() == attr::Overloadable; } - static bool classof(const OverloadableAttr *) { return true; } -}; - -class BlocksAttr : public Attr { -public: - enum BlocksAttrTypes { - ByRef = 0 - }; -private: - BlocksAttrTypes BlocksAttrType; -public: - BlocksAttr(BlocksAttrTypes t) : Attr(attr::Blocks), BlocksAttrType(t) {} - - BlocksAttrTypes getType() const { return BlocksAttrType; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::Blocks; } - static bool classof(const BlocksAttr *A) { return true; } -}; - -class FunctionDecl; - -class CleanupAttr : public Attr { - FunctionDecl *FD; - -public: - CleanupAttr(FunctionDecl *fd) : Attr(attr::Cleanup), FD(fd) {} - - const FunctionDecl *getFunctionDecl() const { return FD; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::Cleanup; } - static bool classof(const CleanupAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(NoDebug); -DEF_SIMPLE_ATTR(WarnUnusedResult); -DEF_SIMPLE_ATTR(NoInline); - -class RegparmAttr : public Attr { - unsigned NumParams; - -public: - RegparmAttr(unsigned np) : Attr(attr::Regparm), NumParams(np) {} - - unsigned getNumParams() const { return NumParams; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { return A->getKind() == attr::Regparm; } - static bool classof(const RegparmAttr *A) { return true; } -}; - -class ReqdWorkGroupSizeAttr : public Attr { - unsigned X, Y, Z; -public: - ReqdWorkGroupSizeAttr(unsigned X, unsigned Y, unsigned Z) - : Attr(attr::ReqdWorkGroupSize), X(X), Y(Y), Z(Z) {} - - unsigned getXDim() const { return X; } - unsigned getYDim() const { return Y; } - unsigned getZDim() const { return Z; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) { - return A->getKind() == attr::ReqdWorkGroupSize; - } - static bool classof(const ReqdWorkGroupSizeAttr *A) { return true; } -}; - -class InitPriorityAttr : public Attr { - unsigned Priority; -public: - InitPriorityAttr(unsigned priority) - : Attr(attr::InitPriority), Priority(priority) {} - - virtual void Destroy(ASTContext &C) { Attr::Destroy(C); } - - unsigned getPriority() const { return Priority; } - - virtual Attr *clone(ASTContext &C) const; - - static bool classof(const Attr *A) - { return A->getKind() == attr::InitPriority; } - static bool classof(const InitPriorityAttr *A) { return true; } -}; - -// Checker-specific attributes. -DEF_SIMPLE_ATTR(CFReturnsNotRetained); -DEF_SIMPLE_ATTR(CFReturnsRetained); -DEF_SIMPLE_ATTR(NSReturnsNotRetained); -DEF_SIMPLE_ATTR(NSReturnsRetained); - -// Target-specific attributes -DEF_SIMPLE_ATTR(DLLImport); -DEF_SIMPLE_ATTR(DLLExport); - -class MSP430InterruptAttr : public Attr { - unsigned Number; - -public: - MSP430InterruptAttr(unsigned n) : Attr(attr::MSP430Interrupt), Number(n) {} - - unsigned getNumber() const { return Number; } - - virtual Attr *clone(ASTContext &C) const; - - // Implement isa/cast/dyncast/etc. - static bool classof(const Attr *A) - { return A->getKind() == attr::MSP430Interrupt; } - static bool classof(const MSP430InterruptAttr *A) { return true; } -}; - -DEF_SIMPLE_ATTR(X86ForceAlignArgPointer); - -#undef DEF_SIMPLE_ATTR +template +inline specific_attr_iterator specific_attr_begin(const AttrVec& vec) { + return specific_attr_iterator(vec.begin()); +} +template +inline specific_attr_iterator specific_attr_end(const AttrVec& vec) { + return specific_attr_iterator(vec.end()); +} + +template +inline bool hasSpecificAttr(const AttrVec& vec) { + return specific_attr_begin(vec) != specific_attr_end(vec); +} +template +inline T *getSpecificAttr(const AttrVec& vec) { + specific_attr_iterator i = specific_attr_begin(vec); + if (i != specific_attr_end(vec)) + return *i; + else + return 0; +} + +/// getMaxAlignment - Returns the highest alignment value found among +/// AlignedAttrs in an AttrVec, or 0 if there are none. +inline unsigned getMaxAttrAlignment(const AttrVec& V, ASTContext &Ctx) { + unsigned Align = 0; + specific_attr_iterator i(V.begin()), e(V.end()); + for(; i != e; ++i) + Align = std::max(Align, i->getAlignment(Ctx)); + return Align; +} } // end namespace clang diff --git a/include/clang/AST/CMakeLists.txt b/include/clang/AST/CMakeLists.txt index 3b090715e08..800c58361b0 100644 --- a/include/clang/AST/CMakeLists.txt +++ b/include/clang/AST/CMakeLists.txt @@ -5,6 +5,12 @@ tablegen(Attrs.inc add_custom_target(ClangAttrClasses DEPENDS Attrs.inc) +tablegen(AttrImpl.inc + -gen-clang-attr-impl + -I ${CMAKE_CURRENT_SOURCE_DIR}/../../) +add_custom_target(ClangAttrImpl + DEPENDS AttrImpl.inc) + set(LLVM_TARGET_DEFINITIONS ../Basic/StmtNodes.td) tablegen(StmtNodes.inc -gen-clang-stmt-nodes) diff --git a/include/clang/AST/CanonicalType.h b/include/clang/AST/CanonicalType.h index 9f97fd8a7ae..dad4dfc926e 100644 --- a/include/clang/AST/CanonicalType.h +++ b/include/clang/AST/CanonicalType.h @@ -273,6 +273,9 @@ public: LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isArrayType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasPointerRepresentation) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasObjCPointerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasIntegerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasSignedIntegerRepresentation) + LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasUnsignedIntegerRepresentation) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasFloatingRepresentation) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isPromotableIntegerType) LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSignedIntegerType) @@ -700,9 +703,9 @@ inline CanQual CanQual::getNonReferenceType() const { template CanQual CanQual::getFromOpaquePtr(void *Ptr) { CanQual Result; - Result.Stored.setFromOpaqueValue(Ptr); - assert((!Result || Result.Stored.isCanonical()) - && "Type is not canonical!"); + Result.Stored = QualType::getFromOpaquePtr(Ptr); + assert((!Result || Result.Stored.getAsOpaquePtr() == (void*)-1 || + Result.Stored.isCanonical()) && "Type is not canonical!"); return Result; } diff --git a/include/clang/AST/Decl.h b/include/clang/AST/Decl.h index 39cd51f606b..67492553221 100644 --- a/include/clang/AST/Decl.h +++ b/include/clang/AST/Decl.h @@ -118,16 +118,6 @@ public: return getIdentifier() ? getIdentifier()->getName() : ""; } - /// getNameAsCString - Get the name of identifier for this declaration as a - /// C string (const char*). This requires that the declaration have a name - /// and that it be a simple identifier. - // - // FIXME: Deprecated, move clients to getName(). - const char *getNameAsCString() const { - assert(Name.isIdentifier() && "Name is not a simple identifier"); - return getIdentifier() ? getIdentifier()->getNameStart() : ""; - } - /// getNameAsString - Get a human-readable name for the declaration, even if /// it is one of the special kinds of names (C++ constructor, Objective-C /// selector, etc). Creating this name requires expensive string @@ -229,6 +219,8 @@ inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, /// NamespaceDecl - Represent a C++ namespace. class NamespaceDecl : public NamedDecl, public DeclContext { + bool IsInline : 1; + SourceLocation LBracLoc, RBracLoc; // For extended namespace definitions: @@ -239,7 +231,7 @@ class NamespaceDecl : public NamedDecl, public DeclContext { // there will be one NamespaceDecl for each declaration. // NextNamespace points to the next extended declaration. // OrigNamespace points to the original namespace declaration. - // OrigNamespace of the first namespace decl points to itself. + // OrigNamespace of the first namespace decl points to its anonymous namespace NamespaceDecl *NextNamespace; /// \brief A pointer to either the original namespace definition for @@ -258,28 +250,36 @@ class NamespaceDecl : public NamedDecl, public DeclContext { NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id) : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace), - NextNamespace(0), OrigOrAnonNamespace(0, true) { } + IsInline(false), NextNamespace(0), OrigOrAnonNamespace(0, true) { } public: static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id); - virtual void Destroy(ASTContext& C); - - // \brief Returns true if this is an anonymous namespace declaration. - // - // For example: + /// \brief Returns true if this is an anonymous namespace declaration. + /// + /// For example: /// \code - // namespace { - // ... - // }; - // \endcode - // q.v. C++ [namespace.unnamed] + /// namespace { + /// ... + /// }; + /// \endcode + /// q.v. C++ [namespace.unnamed] bool isAnonymousNamespace() const { return !getIdentifier(); } - /// \brief Return the next extended namespace declaration or null if this + /// \brief Returns true if this is an inline namespace declaration. + bool isInline() const { + return IsInline; + } + + /// \brief Set whether this is an inline namespace declaration. + void setInline(bool Inline) { + IsInline = Inline; + } + + /// \brief Return the next extended namespace declaration or null if there /// is none. NamespaceDecl *getNextNamespace() { return NextNamespace; } const NamespaceDecl *getNextNamespace() const { return NextNamespace; } @@ -345,8 +345,8 @@ public: return static_cast(const_cast(DC)); } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// ValueDecl - Represent the declaration of a variable (in which case it is @@ -392,8 +392,6 @@ struct QualifierInfo { unsigned NumTPLists, TemplateParameterList **TPLists); - void Destroy(ASTContext &Context); - private: // Copy constructor and copy assignment are disabled. QualifierInfo(const QualifierInfo&); @@ -421,9 +419,6 @@ protected: : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo) {} public: - virtual ~DeclaratorDecl(); - virtual void Destroy(ASTContext &C); - TypeSourceInfo *getTypeSourceInfo() const { return hasExtInfo() ? getExtInfo()->TInfo @@ -507,36 +502,11 @@ struct EvaluatedStmt { APValue Evaluated; }; -// \brief Describes the kind of template specialization that a -// particular template specialization declaration represents. -enum TemplateSpecializationKind { - /// This template specialization was formed from a template-id but - /// has not yet been declared, defined, or instantiated. - TSK_Undeclared = 0, - /// This template specialization was implicitly instantiated from a - /// template. (C++ [temp.inst]). - TSK_ImplicitInstantiation, - /// This template specialization was declared or defined by an - /// explicit specialization (C++ [temp.expl.spec]) or partial - /// specialization (C++ [temp.class.spec]). - TSK_ExplicitSpecialization, - /// This template specialization was instantiated from a template - /// due to an explicit instantiation declaration request - /// (C++0x [temp.explicit]). - TSK_ExplicitInstantiationDeclaration, - /// This template specialization was instantiated from a template - /// due to an explicit instantiation definition request - /// (C++ [temp.explicit]). - TSK_ExplicitInstantiationDefinition -}; - /// VarDecl - An instance of this class is created to represent a variable /// declaration or definition. class VarDecl : public DeclaratorDecl, public Redeclarable { public: - enum StorageClass { - None, Auto, Register, Extern, Static, PrivateExtern - }; + typedef clang::StorageClass StorageClass; /// getStorageClassSpecifierString - Return the string used to /// specify the storage class \arg SC. @@ -568,10 +538,6 @@ private: bool ThreadSpecified : 1; bool HasCXXDirectInit : 1; - /// DeclaredInCondition - Whether this variable was declared in a - /// condition, e.g., if (int x = foo()) { ... }. - bool DeclaredInCondition : 1; - /// \brief Whether this variable is the exception variable in a C++ catch /// or an Objective-C @catch statement. bool ExceptionVar : 1; @@ -587,7 +553,7 @@ protected: StorageClass SCAsWritten) : DeclaratorDecl(DK, DC, L, Id, T, TInfo), Init(), ThreadSpecified(false), HasCXXDirectInit(false), - DeclaredInCondition(false), ExceptionVar(false), NRVOVariable(false) { + ExceptionVar(false), NRVOVariable(false) { SClass = SC; SClassAsWritten = SCAsWritten; } @@ -609,9 +575,6 @@ public: QualType T, TypeSourceInfo *TInfo, StorageClass S, StorageClass SCAsWritten); - virtual void Destroy(ASTContext& C); - virtual ~VarDecl(); - virtual SourceLocation getInnerLocStart() const; virtual SourceRange getSourceRange() const; @@ -619,8 +582,14 @@ public: StorageClass getStorageClassAsWritten() const { return (StorageClass) SClassAsWritten; } - void setStorageClass(StorageClass SC) { SClass = SC; } - void setStorageClassAsWritten(StorageClass SC) { SClassAsWritten = SC; } + void setStorageClass(StorageClass SC) { + assert(isLegalForVariable(SC)); + SClass = SC; + } + void setStorageClassAsWritten(StorageClass SC) { + assert(isLegalForVariable(SC)); + SClassAsWritten = SC; + } void setThreadSpecified(bool T) { ThreadSpecified = T; } bool isThreadSpecified() const { @@ -630,25 +599,26 @@ public: /// hasLocalStorage - Returns true if a variable with function scope /// is a non-static local variable. bool hasLocalStorage() const { - if (getStorageClass() == None) + if (getStorageClass() == SC_None) return !isFileVarDecl(); // Return true for: Auto, Register. // Return false for: Extern, Static, PrivateExtern. - return getStorageClass() <= Register; + return getStorageClass() >= SC_Auto; } /// isStaticLocal - Returns true if a variable with function scope is a /// static local variable. bool isStaticLocal() const { - return getStorageClass() == Static && !isFileVarDecl(); + return getStorageClass() == SC_Static && !isFileVarDecl(); } /// hasExternStorage - Returns true if a variable has extern or /// __private_extern__ storage. bool hasExternalStorage() const { - return getStorageClass() == Extern || getStorageClass() == PrivateExtern; + return getStorageClass() == SC_Extern || + getStorageClass() == SC_PrivateExtern; } /// hasGlobalStorage - Returns true for all variables that do not @@ -670,7 +640,7 @@ public: if (getKind() != Decl::Var) return false; if (const DeclContext *DC = getDeclContext()) - return DC->getLookupContext()->isFunctionOrMethod(); + return DC->getRedeclContext()->isFunctionOrMethod(); return false; } @@ -679,10 +649,8 @@ public: bool isFunctionOrMethodVarDecl() const { if (getKind() != Decl::Var) return false; - if (const DeclContext *DC = getDeclContext()) - return DC->getLookupContext()->isFunctionOrMethod() && - DC->getLookupContext()->getDeclKind() != Decl::Block; - return false; + const DeclContext *DC = getDeclContext()->getRedeclContext(); + return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; } /// \brief Determines whether this is a static data member. @@ -696,7 +664,7 @@ public: /// \endcode bool isStaticDataMember() const { // If it wasn't static, it would be a FieldDecl. - return getDeclContext()->isRecord(); + return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); } virtual VarDecl *getCanonicalDecl(); @@ -743,11 +711,10 @@ public: bool isFileVarDecl() const { if (getKind() != Decl::Var) return false; - if (const DeclContext *Ctx = getDeclContext()) { - Ctx = Ctx->getLookupContext(); - if (isa(Ctx) || isa(Ctx) ) - return true; - } + + if (getDeclContext()->getRedeclContext()->isFileContext()) + return true; + if (isStaticDataMember()) return true; @@ -912,18 +879,6 @@ public: return HasCXXDirectInit; } - /// isDeclaredInCondition - Whether this variable was declared as - /// part of a condition in an if/switch/while statement, e.g., - /// @code - /// if (int x = foo()) { ... } - /// @endcode - bool isDeclaredInCondition() const { - return DeclaredInCondition; - } - void setDeclaredInCondition(bool InCondition) { - DeclaredInCondition = InCondition; - } - /// \brief Determine whether this variable is the exception variable in a /// C++ catch statememt or an Objective-C @catch statement. bool isExceptionVariable() const { @@ -973,7 +928,7 @@ class ImplicitParamDecl : public VarDecl { protected: ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType Tw) - : VarDecl(DK, DC, L, Id, Tw, /*TInfo=*/0, VarDecl::None, VarDecl::None) {} + : VarDecl(DK, DC, L, Id, Tw, /*TInfo=*/0, SC_None, SC_None) {} public: static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, @@ -1117,9 +1072,7 @@ public: class FunctionDecl : public DeclaratorDecl, public DeclContext, public Redeclarable { public: - enum StorageClass { - None, Extern, Static, PrivateExtern - }; + typedef clang::StorageClass StorageClass; /// \brief The kind of templated function a FunctionDecl can be. enum TemplatedKind { @@ -1179,11 +1132,15 @@ private: DependentFunctionTemplateSpecializationInfo *> TemplateOrSpecialization; + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in the DeclaratorDecl base class. + DeclarationNameLoc DNLoc; + protected: - FunctionDecl(Kind DK, DeclContext *DC, SourceLocation L, - DeclarationName N, QualType T, TypeSourceInfo *TInfo, + FunctionDecl(Kind DK, DeclContext *DC, const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, StorageClass S, StorageClass SCAsWritten, bool isInline) - : DeclaratorDecl(DK, DC, L, N, T, TInfo), + : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo), DeclContext(DK), ParamInfo(0), Body(), SClass(S), SClassAsWritten(SCAsWritten), IsInline(isInline), @@ -1191,10 +1148,9 @@ protected: HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false), IsCopyAssignment(false), HasImplicitReturnZero(false), - EndRangeLoc(L), TemplateOrSpecialization() {} - - virtual ~FunctionDecl() {} - virtual void Destroy(ASTContext& C); + EndRangeLoc(NameInfo.getEndLoc()), + TemplateOrSpecialization(), + DNLoc(NameInfo.getInfo()) {} typedef Redeclarable redeclarable_base; virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); } @@ -1211,11 +1167,27 @@ public: static FunctionDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, - StorageClass S = None, - StorageClass SCAsWritten = None, + StorageClass S = SC_None, + StorageClass SCAsWritten = SC_None, + bool isInline = false, + bool hasWrittenPrototype = true) { + DeclarationNameInfo NameInfo(N, L); + return FunctionDecl::Create(C, DC, NameInfo, T, TInfo, S, SCAsWritten, + isInline, hasWrittenPrototype); + } + + static FunctionDecl *Create(ASTContext &C, DeclContext *DC, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + StorageClass S = SC_None, + StorageClass SCAsWritten = SC_None, bool isInline = false, bool hasWrittenPrototype = true); + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); + } + virtual void getNameForDiagnostic(std::string &S, const PrintingPolicy &Policy, bool Qualified) const; @@ -1245,7 +1217,7 @@ public: /// set that function declaration to the actual declaration /// containing the body (if there is one). /// NOTE: For checking if there is a body, use hasBody() instead, to avoid - /// unnecessary PCH de-serialization of the body. + /// unnecessary AST de-serialization of the body. Stmt *getBody(const FunctionDecl *&Definition) const; virtual Stmt *getBody() const { @@ -1389,12 +1361,18 @@ public: } StorageClass getStorageClass() const { return StorageClass(SClass); } - void setStorageClass(StorageClass SC) { SClass = SC; } + void setStorageClass(StorageClass SC) { + assert(isLegalForFunction(SC)); + SClass = SC; + } StorageClass getStorageClassAsWritten() const { return StorageClass(SClassAsWritten); } - void setStorageClassAsWritten(StorageClass SC) { SClassAsWritten = SC; } + void setStorageClassAsWritten(StorageClass SC) { + assert(isLegalForFunction(SC)); + SClassAsWritten = SC; + } /// \brief Determine whether the "inline" keyword was specified for this /// function. @@ -1632,8 +1610,8 @@ public: return static_cast(const_cast(DC)); } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; @@ -1705,7 +1683,6 @@ protected: const llvm::APSInt &V) : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} - virtual ~EnumConstantDecl() {} public: static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, @@ -1713,8 +1690,6 @@ public: QualType T, Expr *E, const llvm::APSInt &V); - virtual void Destroy(ASTContext& C); - const Expr *getInitExpr() const { return (const Expr*) Init; } Expr *getInitExpr() { return (Expr*) Init; } const llvm::APSInt &getInitVal() const { return Val; } @@ -1722,6 +1697,8 @@ public: void setInitExpr(Expr *E) { Init = (Stmt*) E; } void setInitVal(const llvm::APSInt &V) { Val = V; } + SourceRange getSourceRange() const; + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const EnumConstantDecl *D) { return true; } @@ -1770,8 +1747,6 @@ class TypedefDecl : public TypeDecl, public Redeclarable { IdentifierInfo *Id, TypeSourceInfo *TInfo) : TypeDecl(Typedef, DC, L, Id), TInfo(TInfo) {} - virtual ~TypedefDecl(); - protected: typedef Redeclarable redeclarable_base; virtual TypedefDecl *getNextRedeclaration() { return RedeclLink.getNext(); } @@ -1832,6 +1807,9 @@ private: /// it is a declaration ("struct foo;"). bool IsDefinition : 1; + /// IsBeingDefined - True if this is currently being defined. + bool IsBeingDefined : 1; + /// IsEmbeddedInDeclarator - True if this tag declaration is /// "embedded" (i.e., defined or declared for the very first time) /// in the syntax of a declarator. @@ -1873,6 +1851,7 @@ protected: "EnumDecl not matched with TTK_Enum"); TagDeclKind = TK; IsDefinition = false; + IsBeingDefined = false; IsEmbeddedInDeclarator = false; setPreviousDeclaration(PrevDecl); } @@ -1881,8 +1860,6 @@ protected: virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); } public: - void Destroy(ASTContext &C); - typedef redeclarable_base::redecl_iterator redecl_iterator; redecl_iterator redecls_begin() const { return redeclarable_base::redecls_begin(); @@ -1911,11 +1888,22 @@ public: return const_cast(this)->getCanonicalDecl(); } + /// isThisDeclarationADefinition() - Return true if this declaration + /// defines the type. Provided for consistency. + bool isThisDeclarationADefinition() const { + return isDefinition(); + } + /// isDefinition - Return true if this decl has its body specified. bool isDefinition() const { return IsDefinition; } + /// isBeingDefined - Return true if this decl is currently being defined. + bool isBeingDefined() const { + return IsBeingDefined; + } + bool isEmbeddedInDeclarator() const { return IsEmbeddedInDeclarator; } @@ -2003,8 +1991,8 @@ public: return static_cast(const_cast(DC)); } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// EnumDecl - Represents an enum. As an extension, we allow forward-declared @@ -2037,6 +2025,8 @@ class EnumDecl : public TagDecl { IdentifierInfo *Id, EnumDecl *PrevDecl, SourceLocation TKL) : TagDecl(Enum, TTK_Enum, DC, L, Id, PrevDecl, TKL), InstantiatedFrom(0) { IntegerType = QualType(); + NumNegativeBits = 0; + NumPositiveBits = 0; } public: EnumDecl *getCanonicalDecl() { @@ -2058,8 +2048,6 @@ public: SourceLocation TKL, EnumDecl *PrevDecl); static EnumDecl *Create(ASTContext &C, EmptyShell Empty); - virtual void Destroy(ASTContext& C); - /// completeDefinition - When created, the EnumDecl corresponds to a /// forward-declared enum. This method is used to mark the /// declaration as being defined; it's enumerators have already been @@ -2167,7 +2155,6 @@ protected: RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, RecordDecl *PrevDecl, SourceLocation TKL); - virtual ~RecordDecl(); public: static RecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC, @@ -2183,8 +2170,6 @@ public: return cast_or_null(TagDecl::getPreviousDeclaration()); } - virtual void Destroy(ASTContext& C); - bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } @@ -2307,9 +2292,6 @@ protected: IsVariadic(false), ParamInfo(0), NumParams(0), Body(0), SignatureAsWritten(0) {} - virtual ~BlockDecl(); - virtual void Destroy(ASTContext& C); - public: static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); diff --git a/include/clang/AST/DeclBase.h b/include/clang/AST/DeclBase.h index be30b8ed296..1369c2b5955 100644 --- a/include/clang/AST/DeclBase.h +++ b/include/clang/AST/DeclBase.h @@ -222,11 +222,13 @@ protected: // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum unsigned Access : 2; friend class CXXClassMemberWrapper; - - // PCHLevel - the "level" of precompiled header/AST file from which this - // declaration was built. - unsigned PCHLevel : 3; - + + /// PCHLevel - the "level" of AST file from which this declaration was built. + unsigned PCHLevel : 2; + + /// ChangedAfterLoad - if this declaration has changed since being loaded + bool ChangedAfterLoad : 1; + /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. unsigned IdentifierNamespace : 15; @@ -243,7 +245,7 @@ protected: : NextDeclInContext(0), DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(0), HasAttrs(false), Implicit(false), Used(false), - Access(AS_none), PCHLevel(0), + Access(AS_none), PCHLevel(0), ChangedAfterLoad(false), IdentifierNamespace(getIdentifierNamespaceForKind(DK)) { if (Decl::CollectingStats()) add(DK); } @@ -251,7 +253,7 @@ protected: Decl(Kind DK, EmptyShell Empty) : NextDeclInContext(0), DeclKind(DK), InvalidDecl(0), HasAttrs(false), Implicit(false), Used(false), - Access(AS_none), PCHLevel(0), + Access(AS_none), PCHLevel(0), ChangedAfterLoad(false), IdentifierNamespace(getIdentifierNamespaceForKind(DK)) { if (Decl::CollectingStats()) add(DK); } @@ -305,24 +307,52 @@ public: } bool hasAttrs() const { return HasAttrs; } - void initAttrs(Attr *attrs); - void addAttr(Attr *attr); - const Attr *getAttrs() const { - if (!HasAttrs) return 0; // common case, no attributes. - return getAttrsImpl(); // Uncommon case, out of line hash lookup. + void setAttrs(const AttrVec& Attrs); + AttrVec& getAttrs() { + return const_cast(const_cast(this)->getAttrs()); } + const AttrVec &getAttrs() const; void swapAttrs(Decl *D); - void invalidateAttrs(); + void dropAttrs(); - template const T *getAttr() const { - for (const Attr *attr = getAttrs(); attr; attr = attr->getNext()) - if (const T *V = dyn_cast(attr)) - return V; - return 0; + void addAttr(Attr *A) { + if (hasAttrs()) + getAttrs().push_back(A); + else + setAttrs(AttrVec(1, A)); } + typedef AttrVec::const_iterator attr_iterator; + + // FIXME: Do not rely on iterators having comparable singular values. + // Note that this should error out if they do not. + attr_iterator attr_begin() const { + return hasAttrs() ? getAttrs().begin() : 0; + } + attr_iterator attr_end() const { + return hasAttrs() ? getAttrs().end() : 0; + } + + template + specific_attr_iterator specific_attr_begin() const { + return specific_attr_iterator(attr_begin()); + } + template + specific_attr_iterator specific_attr_end() const { + return specific_attr_iterator(attr_end()); + } + + template T *getAttr() const { + return hasAttrs() ? getSpecificAttr(getAttrs()) : 0; + } template bool hasAttr() const { - return getAttr() != 0; + return hasAttrs() && hasSpecificAttr(getAttrs()); + } + + /// getMaxAlignment - return the maximum alignment specified by attributes + /// on this decl, 0 if there are none. + unsigned getMaxAlignment() const { + return hasAttrs() ? getMaxAttrAlignment(getAttrs(), getASTContext()) : 0; } /// setInvalidDecl - Indicates the Decl had a semantic error. This @@ -343,22 +373,21 @@ public: /// (in addition to the "used" bit set by \c setUsed()) when determining /// whether the function is used. bool isUsed(bool CheckUsedAttr = true) const; - + void setUsed(bool U = true) { Used = U; } /// \brief Retrieve the level of precompiled header from which this /// declaration was generated. /// /// The PCH level of a declaration describes where the declaration originated - /// from. A PCH level of 0 indicates that the declaration was not from a - /// precompiled header. A PCH level of 1 indicates that the declaration was - /// from a top-level precompiled header; 2 indicates that the declaration - /// comes from a precompiled header on which the top-level precompiled header - /// depends, and so on. + /// from. A PCH level of 0 indicates that the declaration was parsed from + /// source. A PCH level of 1 indicates that the declaration was loaded from + /// a top-level AST file. A PCH level 2 indicates that the declaration was + /// loaded from a PCH file the AST file depends on, and so on. unsigned getPCHLevel() const { return PCHLevel; } /// \brief The maximum PCH level that any declaration may have. - static const unsigned MaxPCHLevel = 7; + static const unsigned MaxPCHLevel = 3; /// \brief Set the PCH level of this declaration. void setPCHLevel(unsigned Level) { @@ -366,6 +395,19 @@ public: PCHLevel = Level; } + /// \brief Query whether this declaration was changed in a significant way + /// since being loaded from an AST file. + /// + /// In an epic violation of layering, what is "significant" is entirely + /// up to the serialization system, but implemented in AST and Sema. + bool isChangedSinceDeserialization() const { return ChangedAfterLoad; } + + /// \brief Mark this declaration as having changed since deserialization, or + /// reset the flag. + void setChangedSinceDeserialization(bool Changed) { + ChangedAfterLoad = Changed; + } + unsigned getIdentifierNamespace() const { return IdentifierNamespace; } @@ -411,10 +453,10 @@ public: void setLexicalDeclContext(DeclContext *DC); - // isDefinedOutsideFunctionOrMethod - This predicate returns true if this - // scoped decl is defined outside the current function or method. This is - // roughly global variables and functions, but also handles enums (which could - // be defined inside or outside a function etc). + /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this + /// scoped decl is defined outside the current function or method. This is + /// roughly global variables and functions, but also handles enums (which + /// could be defined inside or outside a function etc). bool isDefinedOutsideFunctionOrMethod() const; /// \brief Retrieves the "canonical" declaration of the given declaration. @@ -572,9 +614,6 @@ public: static DeclContext *castToDeclContext(const Decl *); static Decl *castFromDeclContext(const DeclContext *); - /// Destroy - Call destructors and release memory. - virtual void Destroy(ASTContext& C); - void print(llvm::raw_ostream &Out, unsigned Indentation = 0) const; void print(llvm::raw_ostream &Out, const PrintingPolicy &Policy, unsigned Indentation = 0) const; @@ -603,6 +642,29 @@ public: virtual void print(llvm::raw_ostream &OS) const; }; +class DeclContextLookupResult + : public std::pair { +public: + DeclContextLookupResult(NamedDecl **I, NamedDecl **E) + : std::pair(I, E) {} + DeclContextLookupResult() + : std::pair() {} + + using std::pair::operator=; +}; + +class DeclContextLookupConstResult + : public std::pair { +public: + DeclContextLookupConstResult(std::pair R) + : std::pair(R) {} + DeclContextLookupConstResult(NamedDecl * const *I, NamedDecl * const *E) + : std::pair(I, E) {} + DeclContextLookupConstResult() + : std::pair() {} + + using std::pair::operator=; +}; /// DeclContext - This is used only as base class of specific decl types that /// can act as declaration contexts. These decls are (only the top classes @@ -654,8 +716,6 @@ protected: ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0), LastDecl(0) { } - void DestroyDecls(ASTContext &C); - public: ~DeclContext(); @@ -724,6 +784,8 @@ public: return DeclKind == Decl::Namespace; } + bool isInlineNamespace() const; + /// \brief Determines whether this context is dependent on a /// template parameter. bool isDependentContext() const; @@ -742,19 +804,18 @@ public: /// Here, E is a transparent context, so its enumerator (Val1) will /// appear (semantically) that it is in the same context of E. /// Examples of transparent contexts include: enumerations (except for - /// C++0x scoped enums), C++ linkage specifications, and C++0x - /// inline namespaces. + /// C++0x scoped enums), and C++ linkage specifications. bool isTransparentContext() const; /// \brief Determine whether this declaration context is equivalent /// to the declaration context DC. - bool Equals(DeclContext *DC) { + bool Equals(const DeclContext *DC) const { return DC && this->getPrimaryContext() == DC->getPrimaryContext(); } /// \brief Determine whether this declaration context encloses the /// declaration context DC. - bool Encloses(DeclContext *DC); + bool Encloses(const DeclContext *DC) const; /// getPrimaryContext - There may be many different /// declarations of the same entity (including forward declarations @@ -767,13 +828,12 @@ public: return const_cast(this)->getPrimaryContext(); } - /// getLookupContext - Retrieve the innermost non-transparent - /// context of this context, which corresponds to the innermost - /// location from which name lookup can find the entities in this - /// context. - DeclContext *getLookupContext(); - const DeclContext *getLookupContext() const { - return const_cast(this)->getLookupContext(); + /// getRedeclContext - Retrieve the context in which an entity conflicts with + /// other entities of the same name, or where it is a redeclaration if the + /// two entities are compatible. This skips through transparent contexts. + DeclContext *getRedeclContext(); + const DeclContext *getRedeclContext() const { + return const_cast(this)->getRedeclContext(); } /// \brief Retrieve the nearest enclosing namespace context. @@ -782,6 +842,14 @@ public: return const_cast(this)->getEnclosingNamespaceContext(); } + /// \brief Test if this context is part of the enclosing namespace set of + /// the context NS, as defined in C++0x [namespace.def]p9. If either context + /// isn't a namespace, this is equivalent to Equals(). + /// + /// The enclosing namespace set of a namespace is the namespace and, if it is + /// inline, its enclosing namespace, recursively. + bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; + /// getNextContext - If this is a DeclContext that may have other /// DeclContexts that are semantically connected but syntactically /// different, such as C++ namespaces, this routine retrieves the @@ -845,6 +913,12 @@ public: decl_iterator decls_end() const; bool decls_empty() const; + /// noload_decls_begin/end - Iterate over the declarations stored in this + /// context that are currently loaded; don't attempt to retrieve anything + /// from an external source. + decl_iterator noload_decls_begin() const; + decl_iterator noload_decls_end() const; + /// specific_decl_iterator - Iterates over a subrange of /// declarations stored in a DeclContext, providing only those that /// are of type SpecificDecl (or a class derived from it). This @@ -1020,9 +1094,8 @@ public: /// access to the results of lookup up a name within this context. typedef NamedDecl * const * lookup_const_iterator; - typedef std::pair lookup_result; - typedef std::pair - lookup_const_result; + typedef DeclContextLookupResult lookup_result; + typedef DeclContextLookupConstResult lookup_const_result; /// lookup - Find the declarations (if any) with the given Name in /// this context. Returns a range of iterators that contains all of @@ -1052,6 +1125,14 @@ public: /// the declaration chains. void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable = true); + /// \brief Deserialize all the visible declarations from external storage. + /// + /// Name lookup deserializes visible declarations lazily, thus a DeclContext + /// may not have a complete name lookup table. This function deserializes + /// the rest of visible declarations from the external storage and completes + /// the name lookup table. + void MaterializeVisibleDeclsFromExternalStorage(); + /// udir_iterator - Iterates through the using-directives stored /// within this context. typedef UsingDirectiveDecl * const * udir_iterator; @@ -1109,7 +1190,6 @@ public: private: void LoadLexicalDeclsFromExternalStorage() const; - void LoadVisibleDeclsFromExternalStorage() const; friend class DependentDiagnostic; StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; @@ -1123,7 +1203,6 @@ inline bool Decl::isTemplateParameter() const { getKind() == TemplateTemplateParm; } - // Specialization selected when ToTy is not a known subclass of DeclContext. template ::value> diff --git a/include/clang/AST/DeclCXX.h b/include/clang/AST/DeclCXX.h index 41474ab21e3..a9802bfcaf4 100644 --- a/include/clang/AST/DeclCXX.h +++ b/include/clang/AST/DeclCXX.h @@ -17,6 +17,7 @@ #include "clang/AST/Expr.h" #include "clang/AST/Decl.h" +#include "clang/AST/TypeLoc.h" #include "clang/AST/UnresolvedSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SmallPtrSet.h" @@ -159,7 +160,6 @@ class CXXBaseSpecifier { /// Range - The source code range that covers the full base /// specifier, including the "virtual" (if present) and access /// specifier (if present). - // FIXME: Move over to a TypeLoc! SourceRange Range; /// Virtual - Whether this is a virtual base class or not. @@ -177,15 +177,17 @@ class CXXBaseSpecifier { /// VC++ bug. unsigned Access : 2; - /// BaseType - The type of the base class. This will be a class or - /// struct (or a typedef of such). - QualType BaseType; + /// BaseTypeInfo - The type of the base class. This will be a class or struct + /// (or a typedef of such). The source code range does not include the + /// "virtual" or access specifier. + TypeSourceInfo *BaseTypeInfo; public: CXXBaseSpecifier() { } - CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A, QualType T) - : Range(R), Virtual(V), BaseOfClass(BC), Access(A), BaseType(T) { } + CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A, + TypeSourceInfo *TInfo) + : Range(R), Virtual(V), BaseOfClass(BC), Access(A), BaseTypeInfo(TInfo) { } /// getSourceRange - Retrieves the source range that contains the /// entire base specifier. @@ -195,7 +197,7 @@ public: /// class (or not). bool isVirtual() const { return Virtual; } - /// \brief Determine whether this base class if a base of a class declared + /// \brief Determine whether this base class is a base of a class declared /// with the 'class' keyword (vs. one declared with the 'struct' keyword). bool isBaseOfClass() const { return BaseOfClass; } @@ -221,7 +223,10 @@ public: /// getType - Retrieves the type of the base class. This type will /// always be an unqualified class type. - QualType getType() const { return BaseType; } + QualType getType() const { return BaseTypeInfo->getType(); } + + /// getTypeLoc - Retrieves the type and source location of the base class. + TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; } }; /// CXXRecordDecl - Represents a C++ struct/union/class. @@ -400,8 +405,6 @@ protected: CXXRecordDecl *PrevDecl, SourceLocation TKL = SourceLocation()); - ~CXXRecordDecl(); - public: /// base_class_iterator - Iterator that traverses the base classes /// of a class. @@ -449,8 +452,6 @@ public: bool DelayTypeCreation = false); static CXXRecordDecl *Create(ASTContext &C, EmptyShell Empty); - virtual void Destroy(ASTContext& C); - bool isDynamicClass() const { return data().Polymorphic || data().NumVBases != 0; } @@ -1056,29 +1057,30 @@ public: return true; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// CXXMethodDecl - Represents a static or instance method of a /// struct/union/class. class CXXMethodDecl : public FunctionDecl { protected: - CXXMethodDecl(Kind DK, CXXRecordDecl *RD, SourceLocation L, - DeclarationName N, QualType T, TypeSourceInfo *TInfo, + CXXMethodDecl(Kind DK, CXXRecordDecl *RD, + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, bool isStatic, StorageClass SCAsWritten, bool isInline) - : FunctionDecl(DK, RD, L, N, T, TInfo, (isStatic ? Static : None), + : FunctionDecl(DK, RD, NameInfo, T, TInfo, (isStatic ? SC_Static : SC_None), SCAsWritten, isInline) {} public: static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD, - SourceLocation L, DeclarationName N, - QualType T, TypeSourceInfo *TInfo, - bool isStatic = false, - StorageClass SCAsWritten = FunctionDecl::None, - bool isInline = false); + const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, + bool isStatic = false, + StorageClass SCAsWritten = SC_None, + bool isInline = false); - bool isStatic() const { return getStorageClass() == Static; } + bool isStatic() const { return getStorageClass() == SC_Static; } bool isInstance() const { return !isStatic(); } bool isVirtual() const { @@ -1249,9 +1251,6 @@ public: VarDecl **Indices, unsigned NumIndices); - /// \brief Destroy the base or member initializer. - void Destroy(ASTContext &Context); - /// isBaseInitializer - Returns true when this initializer is /// initializing a base class. bool isBaseInitializer() const { return BaseOrMember.is(); } @@ -1285,7 +1284,7 @@ public: /// getMember - If this is a member initializer, returns the /// declaration of the non-static data member being /// initialized. Otherwise, returns NULL. - FieldDecl *getMember() { + FieldDecl *getMember() const { if (isMemberInitializer()) return BaseOrMember.get(); else @@ -1363,7 +1362,7 @@ public: reinterpret_cast(this + 1)[I] = Index; } - Expr *getInit() { return static_cast(Init); } + Expr *getInit() const { return static_cast(Init); } }; /// CXXConstructorDecl - Represents a C++ constructor within a @@ -1394,22 +1393,21 @@ class CXXConstructorDecl : public CXXMethodDecl { CXXBaseOrMemberInitializer **BaseOrMemberInitializers; unsigned NumBaseOrMemberInitializers; - CXXConstructorDecl(CXXRecordDecl *RD, SourceLocation L, - DeclarationName N, QualType T, TypeSourceInfo *TInfo, + CXXConstructorDecl(CXXRecordDecl *RD, const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, bool isExplicitSpecified, bool isInline, bool isImplicitlyDeclared) - : CXXMethodDecl(CXXConstructor, RD, L, N, T, TInfo, false, - FunctionDecl::None, isInline), + : CXXMethodDecl(CXXConstructor, RD, NameInfo, T, TInfo, false, + SC_None, isInline), IsExplicitSpecified(isExplicitSpecified), ImplicitlyDefined(false), BaseOrMemberInitializers(0), NumBaseOrMemberInitializers(0) { setImplicit(isImplicitlyDeclared); } - virtual void Destroy(ASTContext& C); public: static CXXConstructorDecl *Create(ASTContext &C, EmptyShell Empty); static CXXConstructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, - SourceLocation L, DeclarationName N, + const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared); @@ -1519,8 +1517,8 @@ public: static bool classof(const CXXConstructorDecl *D) { return true; } static bool classofKind(Kind K) { return K == CXXConstructor; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// CXXDestructorDecl - Represents a C++ destructor within a @@ -1543,11 +1541,10 @@ class CXXDestructorDecl : public CXXMethodDecl { FunctionDecl *OperatorDelete; - CXXDestructorDecl(CXXRecordDecl *RD, SourceLocation L, - DeclarationName N, QualType T, - bool isInline, bool isImplicitlyDeclared) - : CXXMethodDecl(CXXDestructor, RD, L, N, T, /*TInfo=*/0, false, - FunctionDecl::None, isInline), + CXXDestructorDecl(CXXRecordDecl *RD, const DeclarationNameInfo &NameInfo, + QualType T, bool isInline, bool isImplicitlyDeclared) + : CXXMethodDecl(CXXDestructor, RD, NameInfo, T, /*TInfo=*/0, false, + SC_None, isInline), ImplicitlyDefined(false), OperatorDelete(0) { setImplicit(isImplicitlyDeclared); } @@ -1555,7 +1552,7 @@ class CXXDestructorDecl : public CXXMethodDecl { public: static CXXDestructorDecl *Create(ASTContext& C, EmptyShell Empty); static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, - SourceLocation L, DeclarationName N, + const DeclarationNameInfo &NameInfo, QualType T, bool isInline, bool isImplicitlyDeclared); @@ -1585,8 +1582,8 @@ public: static bool classof(const CXXDestructorDecl *D) { return true; } static bool classofKind(Kind K) { return K == CXXDestructor; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// CXXConversionDecl - Represents a C++ conversion function within a @@ -1604,17 +1601,17 @@ class CXXConversionDecl : public CXXMethodDecl { /// explicitly wrote a cast. This is a C++0x feature. bool IsExplicitSpecified : 1; - CXXConversionDecl(CXXRecordDecl *RD, SourceLocation L, - DeclarationName N, QualType T, TypeSourceInfo *TInfo, + CXXConversionDecl(CXXRecordDecl *RD, const DeclarationNameInfo &NameInfo, + QualType T, TypeSourceInfo *TInfo, bool isInline, bool isExplicitSpecified) - : CXXMethodDecl(CXXConversion, RD, L, N, T, TInfo, false, - FunctionDecl::None, isInline), + : CXXMethodDecl(CXXConversion, RD, NameInfo, T, TInfo, false, + SC_None, isInline), IsExplicitSpecified(isExplicitSpecified) { } public: static CXXConversionDecl *Create(ASTContext &C, EmptyShell Empty); static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD, - SourceLocation L, DeclarationName N, + const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isExplicit); @@ -1642,8 +1639,8 @@ public: static bool classof(const CXXConversionDecl *D) { return true; } static bool classofKind(Kind K) { return K == CXXConversion; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// LinkageSpecDecl - This represents a linkage specification. For example: @@ -1710,7 +1707,9 @@ public: // artificial name, for all using-directives in order to store // them in DeclContext effectively. class UsingDirectiveDecl : public NamedDecl { - + /// \brief The location of the "using" keyword. + SourceLocation UsingLoc; + /// SourceLocation - Location of 'namespace' token. SourceLocation NamespaceLoc; @@ -1722,10 +1721,6 @@ class UsingDirectiveDecl : public NamedDecl { /// name, if any. NestedNameSpecifier *Qualifier; - /// IdentLoc - Location of nominated namespace-name identifier. - // FIXME: We don't store location of scope specifier. - SourceLocation IdentLoc; - /// NominatedNamespace - Namespace nominated by using-directive. NamedDecl *NominatedNamespace; @@ -1740,17 +1735,16 @@ class UsingDirectiveDecl : public NamedDecl { return DeclarationName::getUsingDirectiveName(); } - UsingDirectiveDecl(DeclContext *DC, SourceLocation L, + UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespcLoc, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor) - : NamedDecl(UsingDirective, DC, L, getName()), + : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc), NamespaceLoc(NamespcLoc), QualifierRange(QualifierRange), - Qualifier(Qualifier), IdentLoc(IdentLoc), - NominatedNamespace(Nominated), + Qualifier(Qualifier), NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) { } @@ -1759,18 +1753,10 @@ public: /// that qualifies the namespace name. SourceRange getQualifierRange() const { return QualifierRange; } - /// \brief Set the source range of the nested-name-specifier that - /// qualifies the namespace name. - void setQualifierRange(SourceRange R) { QualifierRange = R; } - /// \brief Retrieve the nested-name-specifier that qualifies the /// name of the namespace. NestedNameSpecifier *getQualifier() const { return Qualifier; } - /// \brief Set the nested-name-specifier that qualifes the name of the - /// namespace. - void setQualifier(NestedNameSpecifier *NNS) { Qualifier = NNS; } - NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; } const NamedDecl *getNominatedNamespaceAsWritten() const { return NominatedNamespace; @@ -1783,34 +1769,23 @@ public: return const_cast(this)->getNominatedNamespace(); } - /// setNominatedNamespace - Set the namespace nominataed by the - /// using-directive. - void setNominatedNamespace(NamedDecl* NS); - /// \brief Returns the common ancestor context of this using-directive and /// its nominated namespace. DeclContext *getCommonAncestor() { return CommonAncestor; } const DeclContext *getCommonAncestor() const { return CommonAncestor; } - /// \brief Set the common ancestor context of this using-directive and its - /// nominated namespace. - void setCommonAncestor(DeclContext* Cxt) { CommonAncestor = Cxt; } - + /// \brief Return the location of the "using" keyword. + SourceLocation getUsingLoc() const { return UsingLoc; } + // FIXME: Could omit 'Key' in name. /// getNamespaceKeyLocation - Returns location of namespace keyword. SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; } - /// setNamespaceKeyLocation - Set the the location of the namespacekeyword. - void setNamespaceKeyLocation(SourceLocation L) { NamespaceLoc = L; } - /// getIdentLocation - Returns location of identifier. - SourceLocation getIdentLocation() const { return IdentLoc; } - - /// setIdentLocation - set the location of the identifier. - void setIdentLocation(SourceLocation L) { IdentLoc = L; } + SourceLocation getIdentLocation() const { return getLocation(); } static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, + SourceLocation UsingLoc, SourceLocation NamespaceLoc, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, @@ -1818,12 +1793,18 @@ public: NamedDecl *Nominated, DeclContext *CommonAncestor); + SourceRange getSourceRange() const { + return SourceRange(UsingLoc, getLocation()); + } + static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const UsingDirectiveDecl *D) { return true; } static bool classofKind(Kind K) { return K == UsingDirective; } // Friend for getUsingDirectiveName. friend class DeclContext; + + friend class ASTDeclReader; }; /// NamespaceAliasDecl - Represents a C++ namespace alias. For example: @@ -1832,7 +1813,8 @@ public: /// namespace Foo = Bar; /// @endcode class NamespaceAliasDecl : public NamedDecl { - SourceLocation AliasLoc; + /// \brief The location of the "namespace" keyword. + SourceLocation NamespaceLoc; /// \brief The source range that covers the nested-name-specifier /// preceding the namespace name. @@ -1849,15 +1831,17 @@ class NamespaceAliasDecl : public NamedDecl { /// NamespaceDecl or a NamespaceAliasDecl. NamedDecl *Namespace; - NamespaceAliasDecl(DeclContext *DC, SourceLocation L, + NamespaceAliasDecl(DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, SourceLocation IdentLoc, NamedDecl *Namespace) - : NamedDecl(NamespaceAlias, DC, L, Alias), AliasLoc(AliasLoc), - QualifierRange(QualifierRange), Qualifier(Qualifier), - IdentLoc(IdentLoc), Namespace(Namespace) { } + : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), + NamespaceLoc(NamespaceLoc), QualifierRange(QualifierRange), + Qualifier(Qualifier), IdentLoc(IdentLoc), Namespace(Namespace) { } + friend class ASTDeclReader; + public: /// \brief Retrieve the source range of the nested-name-specifier /// that qualifiers the namespace name. @@ -1889,41 +1873,31 @@ public: /// Returns the location of the alias name, i.e. 'foo' in /// "namespace foo = ns::bar;". - SourceLocation getAliasLoc() const { return AliasLoc; } - - /// Set the location o;f the alias name, e.e., 'foo' in - /// "namespace foo = ns::bar;". - void setAliasLoc(SourceLocation L) { AliasLoc = L; } + SourceLocation getAliasLoc() const { return getLocation(); } /// Returns the location of the 'namespace' keyword. - SourceLocation getNamespaceLoc() const { return getLocation(); } + SourceLocation getNamespaceLoc() const { return NamespaceLoc; } /// Returns the location of the identifier in the named namespace. SourceLocation getTargetNameLoc() const { return IdentLoc; } - /// Set the location of the identifier in the named namespace. - void setTargetNameLoc(SourceLocation L) { IdentLoc = L; } - /// \brief Retrieve the namespace that this alias refers to, which /// may either be a NamespaceDecl or a NamespaceAliasDecl. NamedDecl *getAliasedNamespace() const { return Namespace; } - /// \brief Set the namespace or namespace alias pointed to by this - /// alias decl. - void setAliasedNamespace(NamedDecl *ND) { - assert((isa(ND) || isa(ND)) && - "expecting namespace or namespace alias decl"); - Namespace = ND; - } - static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, SourceLocation AliasLoc, + SourceLocation NamespaceLoc, + SourceLocation AliasLoc, IdentifierInfo *Alias, SourceRange QualifierRange, NestedNameSpecifier *Qualifier, SourceLocation IdentLoc, NamedDecl *Namespace); + virtual SourceRange getSourceRange() const { + return SourceRange(NamespaceLoc, IdentLoc); + } + static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const NamespaceAliasDecl *D) { return true; } static bool classofKind(Kind K) { return K == NamespaceAlias; } @@ -2002,6 +1976,10 @@ class UsingDecl : public NamedDecl { /// \brief Target nested name specifier. NestedNameSpecifier* TargetNestedName; + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in the ValueDecl base class. + DeclarationNameLoc DNLoc; + /// \brief The collection of shadow declarations associated with /// this using declaration. This set can change as a class is /// processed. @@ -2010,34 +1988,31 @@ class UsingDecl : public NamedDecl { // \brief Has 'typename' keyword. bool IsTypeName; - UsingDecl(DeclContext *DC, SourceLocation L, SourceRange NNR, + UsingDecl(DeclContext *DC, SourceRange NNR, SourceLocation UL, NestedNameSpecifier* TargetNNS, - DeclarationName Name, bool IsTypeNameArg) - : NamedDecl(Using, DC, L, Name), + const DeclarationNameInfo &NameInfo, bool IsTypeNameArg) + : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()), NestedNameRange(NNR), UsingLocation(UL), TargetNestedName(TargetNNS), - IsTypeName(IsTypeNameArg) { + DNLoc(NameInfo.getInfo()), IsTypeName(IsTypeNameArg) { } public: - // FIXME: Should be const? /// \brief Returns the source range that covers the nested-name-specifier /// preceding the namespace name. - SourceRange getNestedNameRange() { return NestedNameRange; } + SourceRange getNestedNameRange() const { return NestedNameRange; } /// \brief Set the source range of the nested-name-specifier. void setNestedNameRange(SourceRange R) { NestedNameRange = R; } - // FIXME; Should be const? // FIXME: Naming is inconsistent with other get*Loc functions. /// \brief Returns the source location of the "using" keyword. - SourceLocation getUsingLocation() { return UsingLocation; } + SourceLocation getUsingLocation() const { return UsingLocation; } /// \brief Set the source location of the 'using' keyword. void setUsingLocation(SourceLocation L) { UsingLocation = L; } - /// \brief Get the target nested name declaration. - NestedNameSpecifier* getTargetNestedNameDecl() { + NestedNameSpecifier* getTargetNestedNameDecl() const { return TargetNestedName; } @@ -2046,6 +2021,10 @@ public: TargetNestedName = NNS; } + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); + } + /// \brief Return true if the using declaration has 'typename'. bool isTypeName() const { return IsTypeName; } @@ -2076,15 +2055,21 @@ public: } static UsingDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation IdentL, SourceRange NNR, SourceLocation UsingL, - NestedNameSpecifier* TargetNNS, DeclarationName Name, bool IsTypeNameArg); + SourceRange NNR, SourceLocation UsingL, + NestedNameSpecifier* TargetNNS, + const DeclarationNameInfo &NameInfo, + bool IsTypeNameArg); + + SourceRange getSourceRange() const { + return SourceRange(UsingLocation, getNameInfo().getEndLoc()); + } static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const UsingDecl *D) { return true; } static bool classofKind(Kind K) { return K == Using; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// UnresolvedUsingValueDecl - Represents a dependent using @@ -2105,14 +2090,18 @@ class UnresolvedUsingValueDecl : public ValueDecl { NestedNameSpecifier *TargetNestedNameSpecifier; + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in the ValueDecl base class. + DeclarationNameLoc DNLoc; + UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty, SourceLocation UsingLoc, SourceRange TargetNNR, NestedNameSpecifier *TargetNNS, - SourceLocation TargetNameLoc, - DeclarationName TargetName) - : ValueDecl(UnresolvedUsingValue, DC, TargetNameLoc, TargetName, Ty), - TargetNestedNameRange(TargetNNR), UsingLocation(UsingLoc), - TargetNestedNameSpecifier(TargetNNS) + const DeclarationNameInfo &NameInfo) + : ValueDecl(UnresolvedUsingValue, DC, + NameInfo.getLoc(), NameInfo.getName(), Ty), + TargetNestedNameRange(TargetNNR), UsingLocation(UsingLoc), + TargetNestedNameSpecifier(TargetNNS), DNLoc(NameInfo.getInfo()) { } public: @@ -2125,7 +2114,7 @@ public: void setTargetNestedNameRange(SourceRange R) { TargetNestedNameRange = R; } /// \brief Get target nested name declaration. - NestedNameSpecifier* getTargetNestedNameSpecifier() { + NestedNameSpecifier* getTargetNestedNameSpecifier() const { return TargetNestedNameSpecifier; } @@ -2140,10 +2129,18 @@ public: /// \brief Set the source location of the 'using' keyword. void setUsingLoc(SourceLocation L) { UsingLocation = L; } + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); + } + static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceRange TargetNNR, NestedNameSpecifier *TargetNNS, - SourceLocation TargetNameLoc, DeclarationName TargetName); + const DeclarationNameInfo &NameInfo); + + SourceRange getSourceRange() const { + return SourceRange(UsingLocation, getNameInfo().getEndLoc()); + } static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const UnresolvedUsingValueDecl *D) { return true; } @@ -2181,43 +2178,34 @@ class UnresolvedUsingTypenameDecl : public TypeDecl { TypenameLocation(TypenameLoc), TargetNestedNameSpecifier(TargetNNS) { } + friend class ASTDeclReader; + public: /// \brief Returns the source range that covers the nested-name-specifier /// preceding the namespace name. SourceRange getTargetNestedNameRange() const { return TargetNestedNameRange; } - /// \brief Set the source range coverting the nested-name-specifier preceding - /// the namespace name. - void setTargetNestedNameRange(SourceRange R) { TargetNestedNameRange = R; } - /// \brief Get target nested name declaration. NestedNameSpecifier* getTargetNestedNameSpecifier() { return TargetNestedNameSpecifier; } - /// \brief Set the nested name declaration. - void setTargetNestedNameSpecifier(NestedNameSpecifier* NNS) { - TargetNestedNameSpecifier = NNS; - } - /// \brief Returns the source location of the 'using' keyword. SourceLocation getUsingLoc() const { return UsingLocation; } - /// \brief Set the source location of the 'using' keyword. - void setUsingLoc(SourceLocation L) { UsingLocation = L; } - /// \brief Returns the source location of the 'typename' keyword. SourceLocation getTypenameLoc() const { return TypenameLocation; } - /// \brief Set the source location of the 'typename' keyword. - void setTypenameLoc(SourceLocation L) { TypenameLocation = L; } - static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, SourceRange TargetNNR, NestedNameSpecifier *TargetNNS, SourceLocation TargetNameLoc, DeclarationName TargetName); + SourceRange getSourceRange() const { + return SourceRange(UsingLocation, getLocation()); + } + static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const UnresolvedUsingTypenameDecl *D) { return true; } static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; } @@ -2243,12 +2231,11 @@ public: StringLiteral *getMessage() { return Message; } const StringLiteral *getMessage() const { return Message; } - virtual ~StaticAssertDecl(); - virtual void Destroy(ASTContext& C); - static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(StaticAssertDecl *D) { return true; } static bool classofKind(Kind K) { return K == StaticAssert; } + + friend class ASTDeclReader; }; /// Insertion operator for diagnostics. This allows sending AccessSpecifier's diff --git a/include/clang/AST/DeclContextInternals.h b/include/clang/AST/DeclContextInternals.h index 9602b677fca..97da6ca9a1e 100644 --- a/include/clang/AST/DeclContextInternals.h +++ b/include/clang/AST/DeclContextInternals.h @@ -29,108 +29,54 @@ class DependentDiagnostic; /// StoredDeclsList - This is an array of decls optimized a common case of only /// containing one entry. struct StoredDeclsList { - /// The kind of data encoded in this list. - enum DataKind { - /// \brief The data is a NamedDecl*. - DK_Decl = 0, - /// \brief The data is a declaration ID (an unsigned value), - /// shifted left by 2 bits. - DK_DeclID = 1, - /// \brief The data is a pointer to a vector (of type VectorTy) - /// that contains declarations. - DK_Decl_Vector = 2, - /// \brief The data is a pointer to a vector (of type VectorTy) - /// that contains declaration ID. - DK_ID_Vector = 3 - }; - /// VectorTy - When in vector form, this is what the Data pointer points to. - typedef llvm::SmallVector VectorTy; + /// DeclsTy - When in vector form, this is what the Data pointer points to. + typedef llvm::SmallVector DeclsTy; - /// \brief The stored data, which will be either a declaration ID, a - /// pointer to a NamedDecl, or a pointer to a vector. - uintptr_t Data; + /// \brief The stored data, which will be either a pointer to a NamedDecl, + /// or a pointer to a vector. + llvm::PointerUnion Data; public: - StoredDeclsList() : Data(0) {} + StoredDeclsList() {} StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) { - if (VectorTy *RHSVec = RHS.getAsVector()) { - VectorTy *New = new VectorTy(*RHSVec); - Data = reinterpret_cast(New) | (Data & 0x03); - } + if (DeclsTy *RHSVec = RHS.getAsVector()) + Data = new DeclsTy(*RHSVec); } ~StoredDeclsList() { // If this is a vector-form, free the vector. - if (VectorTy *Vector = getAsVector()) + if (DeclsTy *Vector = getAsVector()) delete Vector; } StoredDeclsList &operator=(const StoredDeclsList &RHS) { - if (VectorTy *Vector = getAsVector()) + if (DeclsTy *Vector = getAsVector()) delete Vector; Data = RHS.Data; - if (VectorTy *RHSVec = RHS.getAsVector()) { - VectorTy *New = new VectorTy(*RHSVec); - Data = reinterpret_cast(New) | (Data & 0x03); - } + if (DeclsTy *RHSVec = RHS.getAsVector()) + Data = new DeclsTy(*RHSVec); return *this; } - bool isNull() const { return (Data & ~0x03) == 0; } + bool isNull() const { return Data.isNull(); } NamedDecl *getAsDecl() const { - if ((Data & 0x03) != DK_Decl) - return 0; - - return reinterpret_cast(Data & ~0x03); + return Data.dyn_cast(); } - VectorTy *getAsVector() const { - if ((Data & 0x03) != DK_ID_Vector && (Data & 0x03) != DK_Decl_Vector) - return 0; - - return reinterpret_cast(Data & ~0x03); + DeclsTy *getAsVector() const { + return Data.dyn_cast(); } void setOnlyValue(NamedDecl *ND) { assert(!getAsVector() && "Not inline"); - Data = reinterpret_cast(ND); - } - - void setFromDeclIDs(const llvm::SmallVectorImpl &Vec) { - if (Vec.size() > 1) { - VectorTy *Vector = getAsVector(); - if (!Vector) { - Vector = new VectorTy; - Data = reinterpret_cast(Vector) | DK_ID_Vector; - } - - Vector->resize(Vec.size()); - std::copy(Vec.begin(), Vec.end(), Vector->begin()); - return; - } - - if (VectorTy *Vector = getAsVector()) - delete Vector; - - if (Vec.empty()) - Data = 0; - else - Data = (Vec[0] << 2) | DK_DeclID; - } - - /// \brief Force the stored declarations list to contain actual - /// declarations. - /// - /// This routine will resolve any declaration IDs for declarations - /// that may not yet have been loaded from external storage. - void materializeDecls(ASTContext &Context); - - bool hasDeclarationIDs() const { - DataKind DK = (DataKind)(Data & 0x03); - return DK == DK_DeclID || DK == DK_ID_Vector; + Data = ND; + // Make sure that Data is a plain NamedDecl* so we can use its address + // at getLookupResult. + assert(*(NamedDecl **)&Data == ND && + "PointerUnion mangles the NamedDecl pointer!"); } void remove(NamedDecl *D) { @@ -138,30 +84,26 @@ public: if (NamedDecl *Singleton = getAsDecl()) { assert(Singleton == D && "list is different singleton"); (void)Singleton; - Data = 0; + Data = (NamedDecl *)0; return; } - VectorTy &Vec = *getAsVector(); - VectorTy::iterator I = std::find(Vec.begin(), Vec.end(), - reinterpret_cast(D)); + DeclsTy &Vec = *getAsVector(); + DeclsTy::iterator I = std::find(Vec.begin(), Vec.end(), D); assert(I != Vec.end() && "list does not contain decl"); Vec.erase(I); - assert(std::find(Vec.begin(), Vec.end(), reinterpret_cast(D)) + assert(std::find(Vec.begin(), Vec.end(), D) == Vec.end() && "list still contains decl"); } /// getLookupResult - Return an array of all the decls that this list /// represents. - DeclContext::lookup_result getLookupResult(ASTContext &Context) { + DeclContext::lookup_result getLookupResult() { if (isNull()) return DeclContext::lookup_result(DeclContext::lookup_iterator(0), DeclContext::lookup_iterator(0)); - if (hasDeclarationIDs()) - materializeDecls(Context); - // If we have a single NamedDecl, return it. if (getAsDecl()) { assert(!isNull() && "Empty list isn't allowed"); @@ -172,19 +114,15 @@ public: } assert(getAsVector() && "Must have a vector at this point"); - VectorTy &Vector = *getAsVector(); + DeclsTy &Vector = *getAsVector(); // Otherwise, we have a range result. - return DeclContext::lookup_result((NamedDecl **)&Vector[0], - (NamedDecl **)&Vector[0]+Vector.size()); + return DeclContext::lookup_result(&Vector[0], &Vector[0]+Vector.size()); } /// HandleRedeclaration - If this is a redeclaration of an existing decl, /// replace the old one with D and return true. Otherwise return false. - bool HandleRedeclaration(ASTContext &Context, NamedDecl *D) { - if (hasDeclarationIDs()) - materializeDecls(Context); - + bool HandleRedeclaration(NamedDecl *D) { // Most decls only have one entry in their list, special case it. if (NamedDecl *OldD = getAsDecl()) { if (!D->declarationReplaces(OldD)) @@ -194,12 +132,12 @@ public: } // Determine if this declaration is actually a redeclaration. - VectorTy &Vec = *getAsVector(); - for (VectorTy::iterator OD = Vec.begin(), ODEnd = Vec.end(); + DeclsTy &Vec = *getAsVector(); + for (DeclsTy::iterator OD = Vec.begin(), ODEnd = Vec.end(); OD != ODEnd; ++OD) { - NamedDecl *OldD = reinterpret_cast(*OD); + NamedDecl *OldD = *OD; if (D->declarationReplaces(OldD)) { - *OD = reinterpret_cast(D); + *OD = D; return true; } } @@ -211,17 +149,15 @@ public: /// not a redeclaration to merge it into the appropriate place in our list. /// void AddSubsequentDecl(NamedDecl *D) { - assert(!hasDeclarationIDs() && "Must materialize before adding decls"); - // If this is the second decl added to the list, convert this to vector // form. if (NamedDecl *OldD = getAsDecl()) { - VectorTy *VT = new VectorTy(); - VT->push_back(reinterpret_cast(OldD)); - Data = reinterpret_cast(VT) | DK_Decl_Vector; + DeclsTy *VT = new DeclsTy(); + VT->push_back(OldD); + Data = VT; } - VectorTy &Vec = *getAsVector(); + DeclsTy &Vec = *getAsVector(); // Using directives end up in a special entry which contains only // other using directives, so all this logic is wasted for them. @@ -232,32 +168,30 @@ public: // iterator which points at the first tag will start a span of // decls that only contains tags. if (D->hasTagIdentifierNamespace()) - Vec.push_back(reinterpret_cast(D)); + Vec.push_back(D); // Resolved using declarations go at the front of the list so that // they won't show up in other lookup results. Unresolved using // declarations (which are always in IDNS_Using | IDNS_Ordinary) // follow that so that the using declarations will be contiguous. else if (D->getIdentifierNamespace() & Decl::IDNS_Using) { - VectorTy::iterator I = Vec.begin(); + DeclsTy::iterator I = Vec.begin(); if (D->getIdentifierNamespace() != Decl::IDNS_Using) { while (I != Vec.end() && - reinterpret_cast(*I) - ->getIdentifierNamespace() == Decl::IDNS_Using) + (*I)->getIdentifierNamespace() == Decl::IDNS_Using) ++I; } - Vec.insert(I, reinterpret_cast(D)); + Vec.insert(I, D); // All other declarations go at the end of the list, but before any // tag declarations. But we can be clever about tag declarations // because there can only ever be one in a scope. - } else if (reinterpret_cast(Vec.back()) - ->hasTagIdentifierNamespace()) { - uintptr_t TagD = Vec.back(); - Vec.back() = reinterpret_cast(D); + } else if (Vec.back()->hasTagIdentifierNamespace()) { + NamedDecl *TagD = Vec.back(); + Vec.back() = D; Vec.push_back(TagD); } else - Vec.push_back(reinterpret_cast(D)); + Vec.push_back(D); } }; diff --git a/include/clang/AST/DeclFriend.h b/include/clang/AST/DeclFriend.h index 2807d16379a..4b5e6fd48bb 100644 --- a/include/clang/AST/DeclFriend.h +++ b/include/clang/AST/DeclFriend.h @@ -68,16 +68,16 @@ public: SourceLocation FriendL); static FriendDecl *Create(ASTContext &C, EmptyShell Empty); - /// If this friend declaration names an (untemplated but - /// possibly dependent) type, return the type; otherwise - /// return null. This is used only for C++0x's unelaborated - /// friend type declarations. + /// If this friend declaration names an (untemplated but possibly + /// dependent) type, return the type; otherwise return null. This + /// is used for elaborated-type-specifiers and, in C++0x, for + /// arbitrary friend type declarations. TypeSourceInfo *getFriendType() const { return Friend.dyn_cast(); } - /// If this friend declaration doesn't name an unelaborated - /// type, return the inner declaration. + /// If this friend declaration doesn't name a type, return the inner + /// declaration. NamedDecl *getFriendDecl() const { return Friend.dyn_cast(); } @@ -92,8 +92,8 @@ public: static bool classof(const FriendDecl *D) { return true; } static bool classofKind(Kind K) { return K == Decl::Friend; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// An iterator over the friend declarations of a class. diff --git a/include/clang/AST/DeclGroup.h b/include/clang/AST/DeclGroup.h index e1fae8f2ae6..030291ea734 100644 --- a/include/clang/AST/DeclGroup.h +++ b/include/clang/AST/DeclGroup.h @@ -34,7 +34,6 @@ private: public: static DeclGroup *Create(ASTContext &C, Decl **Decls, unsigned NumDecls); - void Destroy(ASTContext& C); unsigned size() const { return NumDecls; } diff --git a/include/clang/AST/DeclObjC.h b/include/clang/AST/DeclObjC.h index 30f63d89595..ad26748e134 100644 --- a/include/clang/AST/DeclObjC.h +++ b/include/clang/AST/DeclObjC.h @@ -21,7 +21,6 @@ namespace clang { class Expr; class Stmt; class FunctionDecl; -class AttributeList; class RecordDecl; class ObjCIvarDecl; class ObjCMethodDecl; @@ -41,12 +40,6 @@ protected: public: ObjCListBase() : List(0), NumElts(0) {} - ~ObjCListBase() { - assert(List == 0 && "Destroy should have been called before dtor"); - } - - void Destroy(ASTContext &Ctx); - unsigned size() const { return NumElts; } bool empty() const { return NumElts == 0; } @@ -92,7 +85,6 @@ public: void set(ObjCProtocolDecl* const* InList, unsigned Elts, const SourceLocation *Locs, ASTContext &Ctx); - void Destroy(ASTContext &Ctx); }; @@ -128,6 +120,9 @@ private: // Synthesized declaration method for a property setter/getter bool IsSynthesized : 1; + + // Method has a definition. + bool IsDefined : 1; // NOTE: VC++ treats enums as signed, avoid using ImplementationControl enum /// @required/@optional @@ -171,29 +166,25 @@ private: bool isInstance = true, bool isVariadic = false, bool isSynthesized = false, + bool isDefined = false, ImplementationControl impControl = None, unsigned numSelectorArgs = 0) : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo), DeclContext(ObjCMethod), IsInstance(isInstance), IsVariadic(isVariadic), IsSynthesized(isSynthesized), + IsDefined(isDefined), DeclImplementation(impControl), objcDeclQualifier(OBJC_TQ_None), NumSelectorArgs(numSelectorArgs), MethodDeclType(T), ResultTInfo(ResultTInfo), EndLoc(endLoc), Body(0), SelfDecl(0), CmdDecl(0) {} - virtual ~ObjCMethodDecl() {} - /// \brief A definition will return its interface declaration. /// An interface declaration will return its definition. /// Otherwise it will return itself. virtual ObjCMethodDecl *getNextRedeclaration(); public: - - /// Destroy - Call destructors and release memory. - virtual void Destroy(ASTContext& C); - static ObjCMethodDecl *Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, @@ -203,6 +194,7 @@ public: bool isInstance = true, bool isVariadic = false, bool isSynthesized = false, + bool isDefined = false, ImplementationControl impControl = None, unsigned numSelectorArgs = 0); @@ -296,6 +288,9 @@ public: bool isSynthesized() const { return IsSynthesized; } void setSynthesized(bool isSynth) { IsSynthesized = isSynth; } + + bool isDefined() const { return IsDefined; } + void setDefined(bool isDefined) { IsDefined = isDefined; } // Related to protocols declared in @protocol void setDeclImplementation(ImplementationControl ic) { @@ -326,21 +321,6 @@ public: } }; -/// ObjCMethodList - a linked list of methods with different signatures. -struct ObjCMethodList { - ObjCMethodDecl *Method; - ObjCMethodList *Next; - - ObjCMethodList() { - Method = 0; - Next = 0; - } - ObjCMethodList(ObjCMethodDecl *M, ObjCMethodList *C) { - Method = M; - Next = C; - } -}; - /// ObjCContainerDecl - Represents a container for method declarations. /// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl, /// ObjCProtocolDecl, and ObjCImplDecl. @@ -355,8 +335,6 @@ public: IdentifierInfo *Id) : NamedDecl(DK, DC, L, Id), DeclContext(DK) {} - virtual ~ObjCContainerDecl() {} - // Iterator access to properties. typedef specific_decl_iterator prop_iterator; prop_iterator prop_begin() const { @@ -465,12 +443,19 @@ class ObjCInterfaceDecl : public ObjCContainerDecl { /// Class's super class. ObjCInterfaceDecl *SuperClass; - /// Protocols referenced in interface header declaration + /// Protocols referenced in the @interface declaration ObjCProtocolList ReferencedProtocols; + + /// Protocols reference in both the @interface and class extensions. + ObjCList AllReferencedProtocols; /// List of categories defined for this class. /// FIXME: Why is this a linked list?? ObjCCategoryDecl *CategoryList; + + /// IvarList - List of all ivars defined by this class; including class + /// extensions and implementation. This list is built lazily. + ObjCIvarDecl *IvarList; bool ForwardDecl:1; // declared with @class. bool InternalInterface:1; // true - no @interface for @implementation @@ -482,13 +467,7 @@ class ObjCInterfaceDecl : public ObjCContainerDecl { ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, SourceLocation CLoc, bool FD, bool isInternal); - virtual ~ObjCInterfaceDecl() {} - public: - - /// Destroy - Call destructors and release memory. - virtual void Destroy(ASTContext& C); - static ObjCInterfaceDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, @@ -513,25 +492,49 @@ public: } typedef ObjCProtocolList::iterator protocol_iterator; - protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();} - protocol_iterator protocol_end() const { return ReferencedProtocols.end(); } + + protocol_iterator protocol_begin() const { + return ReferencedProtocols.begin(); + } + protocol_iterator protocol_end() const { + return ReferencedProtocols.end(); + } + typedef ObjCProtocolList::loc_iterator protocol_loc_iterator; + protocol_loc_iterator protocol_loc_begin() const { return ReferencedProtocols.loc_begin(); } + protocol_loc_iterator protocol_loc_end() const { return ReferencedProtocols.loc_end(); } - unsigned protocol_size() const { return ReferencedProtocols.size(); } + + typedef ObjCList::iterator all_protocol_iterator; + + all_protocol_iterator all_referenced_protocol_begin() const { + return AllReferencedProtocols.empty() ? protocol_begin() + : AllReferencedProtocols.begin(); + } + all_protocol_iterator all_referenced_protocol_end() const { + return AllReferencedProtocols.empty() ? protocol_end() + : AllReferencedProtocols.end(); + } typedef specific_decl_iterator ivar_iterator; + ivar_iterator ivar_begin() const { return ivar_iterator(decls_begin()); } ivar_iterator ivar_end() const { return ivar_iterator(decls_end()); } + unsigned ivar_size() const { return std::distance(ivar_begin(), ivar_end()); } + bool ivar_empty() const { return ivar_begin() == ivar_end(); } - + + ObjCIvarDecl *all_declared_ivar_begin(); + void setIvarList(ObjCIvarDecl *ivar) { IvarList = ivar; } + /// setProtocolList - Set the list of protocols that this interface /// implements. void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num, @@ -543,7 +546,6 @@ public: /// into the protocol list for this class. void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List, unsigned Num, - const SourceLocation *Locs, ASTContext &C); bool isForwardDecl() const { return ForwardDecl; } @@ -625,6 +627,9 @@ public: static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const ObjCInterfaceDecl *D) { return true; } static bool classofKind(Kind K) { return K == ObjCInterface; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC @@ -650,21 +655,26 @@ public: private: ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation L, IdentifierInfo *Id, - QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW) + QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW, + bool synthesized) : FieldDecl(ObjCIvar, DC, L, Id, T, TInfo, BW, /*Mutable=*/false), - DeclAccess(ac) {} + NextIvar(0), DeclAccess(ac), Synthesized(synthesized) {} public: static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, - AccessControl ac, Expr *BW = NULL); + AccessControl ac, Expr *BW = NULL, + bool synthesized=false); /// \brief Return the class interface that this ivar is logically contained /// in; this is either the interface where the ivar was declared, or the /// interface the ivar is conceptually a part of in the case of synthesized /// ivars. const ObjCInterfaceDecl *getContainingInterface() const; + + ObjCIvarDecl *getNextIvar() { return NextIvar; } + void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; } void setAccessControl(AccessControl ac) { DeclAccess = ac; } @@ -674,13 +684,21 @@ public: return DeclAccess == None ? Protected : AccessControl(DeclAccess); } + void setSynthesize(bool synth) { Synthesized = synth; } + bool getSynthesize() const { return Synthesized; } + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const ObjCIvarDecl *D) { return true; } static bool classofKind(Kind K) { return K == ObjCIvar; } private: + /// NextIvar - Next Ivar in the list of ivars declared in class; class's + /// extensions and class's implementation + ObjCIvarDecl *NextIvar; + // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum unsigned DeclAccess : 3; + unsigned Synthesized : 1; }; @@ -700,8 +718,6 @@ public: IdentifierInfo *Id, QualType T, Expr *BW); - virtual void Destroy(ASTContext& C); - // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const ObjCAtDefsFieldDecl *D) { return true; } @@ -745,15 +761,10 @@ class ObjCProtocolDecl : public ObjCContainerDecl { isForwardProtoDecl(true) { } - virtual ~ObjCProtocolDecl() {} - public: static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id); - /// Destroy - Call destructors and release memory. - virtual void Destroy(ASTContext& C); - const ObjCProtocolList &getReferencedProtocols() const { return ReferencedProtocols; } @@ -822,12 +833,7 @@ private: ObjCClassDecl(DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *const *Elts, const SourceLocation *Locs, unsigned nElts, ASTContext &C); - virtual ~ObjCClassDecl() {} public: - - /// Destroy - Call destructors and release memory. - virtual void Destroy(ASTContext& C); - static ObjCClassDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *const *Elts = 0, const SourceLocation *Locs = 0, @@ -860,7 +866,6 @@ class ObjCForwardProtocolDecl : public Decl { ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L, ObjCProtocolDecl *const *Elts, unsigned nElts, const SourceLocation *Locs, ASTContext &C); - virtual ~ObjCForwardProtocolDecl() {} public: static ObjCForwardProtocolDecl *Create(ASTContext &C, DeclContext *DC, @@ -874,9 +879,6 @@ public: return Create(C, DC, L, 0, 0, 0); } - /// Destroy - Call destructors and release memory. - virtual void Destroy(ASTContext& C); - typedef ObjCProtocolList::iterator protocol_iterator; protocol_iterator protocol_begin() const {return ReferencedProtocols.begin();} protocol_iterator protocol_end() const { return ReferencedProtocols.end(); } @@ -928,6 +930,9 @@ class ObjCCategoryDecl : public ObjCContainerDecl { /// FIXME: this should not be a singly-linked list. Move storage elsewhere. ObjCCategoryDecl *NextClassCategory; + /// true of class extension has at least one bitfield ivar. + bool HasSynthBitfield : 1; + /// \brief The location of the '@' in '@interface' SourceLocation AtLoc; @@ -938,8 +943,8 @@ class ObjCCategoryDecl : public ObjCContainerDecl { SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, IdentifierInfo *Id) : ObjCContainerDecl(ObjCCategory, DC, ClassNameLoc, Id), - ClassInterface(0), NextClassCategory(0), AtLoc(AtLoc), - CategoryNameLoc(CategoryNameLoc) { + ClassInterface(0), NextClassCategory(0), HasSynthBitfield(false), + AtLoc(AtLoc), CategoryNameLoc(CategoryNameLoc) { } public: @@ -991,6 +996,9 @@ public: bool IsClassExtension() const { return getIdentifier() == 0; } const ObjCCategoryDecl *getNextClassExtension() const; + bool hasSynthBitfield() const { return HasSynthBitfield; } + void setHasSynthBitfield (bool val) { HasSynthBitfield = val; } + typedef specific_decl_iterator ivar_iterator; ivar_iterator ivar_begin() const { return ivar_iterator(decls_begin()); @@ -1032,8 +1040,6 @@ protected: ClassInterface(classInterface) {} public: - virtual ~ObjCImplDecl() {} - const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; } ObjCInterfaceDecl *getClassInterface() { return ClassInterface; } void setClassInterface(ObjCInterfaceDecl *IFace); @@ -1165,11 +1171,15 @@ class ObjCImplementationDecl : public ObjCImplDecl { CXXBaseOrMemberInitializer **IvarInitializers; unsigned NumIvarInitializers; + /// true of class extension has at least one bitfield ivar. + bool HasSynthBitfield : 1; + ObjCImplementationDecl(DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *classInterface, ObjCInterfaceDecl *superDecl) : ObjCImplDecl(ObjCImplementation, DC, L, classInterface), - SuperClass(superDecl), IvarInitializers(0), NumIvarInitializers(0) {} + SuperClass(superDecl), IvarInitializers(0), NumIvarInitializers(0), + HasSynthBitfield(false) {} public: static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, @@ -1207,6 +1217,9 @@ public: void setIvarInitializers(ASTContext &C, CXXBaseOrMemberInitializer ** initializers, unsigned numInitializers); + + bool hasSynthBitfield() const { return HasSynthBitfield; } + void setHasSynthBitfield (bool val) { HasSynthBitfield = val; } /// getIdentifier - Get the identifier that names the class /// interface associated with this implementation. @@ -1262,6 +1275,9 @@ public: static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const ObjCImplementationDecl *D) { return true; } static bool classofKind(Kind K) { return K == ObjCImplementation; } + + friend class ASTDeclReader; + friend class ASTDeclWriter; }; llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, diff --git a/include/clang/AST/DeclTemplate.h b/include/clang/AST/DeclTemplate.h index 135dd3ae78d..b532668242f 100644 --- a/include/clang/AST/DeclTemplate.h +++ b/include/clang/AST/DeclTemplate.h @@ -23,6 +23,7 @@ namespace clang { class TemplateParameterList; class TemplateDecl; +class RedeclarableTemplateDecl; class FunctionTemplateDecl; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; @@ -193,13 +194,6 @@ public: TemplateArgumentList() : NumFlatArguments(0), NumStructuredArguments(0) { } - /// Used to release the memory associated with a TemplateArgumentList - /// object. FIXME: This is currently not called anywhere, but the - /// memory will still be freed when using a BumpPtrAllocator. - void Destroy(ASTContext &C); - - ~TemplateArgumentList(); - /// \brief Copies the template arguments into a locally new[]'d array. void init(ASTContext &Context, const TemplateArgument *Args, unsigned NumArgs); @@ -255,8 +249,6 @@ protected: : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl), TemplateParams(Params) { } public: - ~TemplateDecl(); - /// Get the list of template parameters TemplateParameterList *getTemplateParameters() const { return TemplateParams; @@ -268,6 +260,7 @@ public: // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const TemplateDecl *D) { return true; } + static bool classof(const RedeclarableTemplateDecl *D) { return true; } static bool classof(const FunctionTemplateDecl *D) { return true; } static bool classof(const ClassTemplateDecl *D) { return true; } static bool classof(const TemplateTemplateParmDecl *D) { return true; } @@ -490,122 +483,179 @@ public: } }; -/// Declaration of a template function. -class FunctionTemplateDecl : public TemplateDecl { - static void DeallocateCommon(void *Ptr); - -protected: - /// \brief Data that is common to all of the declarations of a given - /// function template. - struct Common { - Common() : InstantiatedFromMember(0, false) { } +/// Declaration of a redeclarable template. +class RedeclarableTemplateDecl : public TemplateDecl { - /// \brief The function template specializations for this function - /// template, including explicit specializations and instantiations. - llvm::FoldingSet Specializations; - - /// \brief The member function template from which this was most - /// directly instantiated (or null). - /// - /// The boolean value indicates whether this member function template - /// was explicitly specialized. - llvm::PointerIntPair InstantiatedFromMember; - }; - - /// \brief A pointer to the previous declaration (if this is a redeclaration) - /// or to the data that is common to all declarations of this function - /// template. - llvm::PointerUnion CommonOrPrev; - - /// \brief Retrieves the "common" pointer shared by all - /// (re-)declarations of the same function template. Calling this routine - /// may implicitly allocate memory for the common pointer. - Common *getCommonPtr(); - - FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, - TemplateParameterList *Params, NamedDecl *Decl) - : TemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl), - CommonOrPrev((Common*)0) { } - -public: - void Destroy(ASTContext &C); - - /// Get the underlying function declaration of the template. - FunctionDecl *getTemplatedDecl() const { - return static_cast(TemplatedDecl); + RedeclarableTemplateDecl *getPreviousDeclarationImpl() { + return CommonOrPrev.dyn_cast(); } - /// \brief Retrieve the set of function template specializations of this - /// function template. - llvm::FoldingSet &getSpecializations() { - return getCommonPtr()->Specializations; - } + RedeclarableTemplateDecl *getCanonicalDeclImpl(); - /// \brief Retrieve the previous declaration of this function template, or - /// NULL if no such declaration exists. - const FunctionTemplateDecl *getPreviousDeclaration() const { - return CommonOrPrev.dyn_cast(); - } + void setPreviousDeclarationImpl(RedeclarableTemplateDecl *Prev); - /// \brief Retrieve the previous declaration of this function template, or - /// NULL if no such declaration exists. - FunctionTemplateDecl *getPreviousDeclaration() { - return CommonOrPrev.dyn_cast(); - } - - /// \brief Set the previous declaration of this function template. - void setPreviousDeclaration(FunctionTemplateDecl *Prev) { - if (Prev) - CommonOrPrev = Prev; - } - - virtual FunctionTemplateDecl *getCanonicalDecl(); - - /// \brief Retrieve the member function template that this function template - /// was instantiated from. - /// - /// This routine will return non-NULL for member function templates of - /// class templates. For example, given: - /// - /// \code - /// template - /// struct X { - /// template void f(); - /// }; - /// \endcode - /// - /// X::A is a CXXMethodDecl (whose parent is X, a - /// ClassTemplateSpecializationDecl) for which getPrimaryTemplate() will - /// return X::f, a FunctionTemplateDecl (whose parent is again - /// X) for which getInstantiatedFromMemberTemplate() will return - /// X::f, a FunctionTemplateDecl (whose parent is X, a - /// ClassTemplateDecl). - /// - /// \returns NULL if this is not an instantiation of a member function - /// template. - FunctionTemplateDecl *getInstantiatedFromMemberTemplate() { + RedeclarableTemplateDecl *getInstantiatedFromMemberTemplateImpl() { return getCommonPtr()->InstantiatedFromMember.getPointer(); } - void setInstantiatedFromMemberTemplate(FunctionTemplateDecl *FTD) { + void setInstantiatedFromMemberTemplateImpl(RedeclarableTemplateDecl *TD) { assert(!getCommonPtr()->InstantiatedFromMember.getPointer()); - getCommonPtr()->InstantiatedFromMember.setPointer(FTD); + getCommonPtr()->InstantiatedFromMember.setPointer(TD); + } + +protected: + template struct SpecEntryTraits { + typedef EntryType DeclType; + + static DeclType *getMostRecentDeclaration(EntryType *D) { + return D->getMostRecentDeclaration(); + } + }; + + template , + typename _DeclType = typename _SETraits::DeclType> + class SpecIterator : public std::iterator { + typedef _SETraits SETraits; + typedef _DeclType DeclType; + + typedef typename llvm::FoldingSet::iterator SetIteratorType; + + SetIteratorType SetIter; + + public: + SpecIterator() : SetIter() {} + SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {} + + DeclType *operator*() const { + return SETraits::getMostRecentDeclaration(&*SetIter); + } + DeclType *operator->() const { return **this; } + + SpecIterator &operator++() { ++SetIter; return *this; } + SpecIterator operator++(int) { + SpecIterator tmp(*this); + ++(*this); + return tmp; + } + + bool operator==(SpecIterator Other) const { + return SetIter == Other.SetIter; + } + bool operator!=(SpecIterator Other) const { + return SetIter != Other.SetIter; + } + }; + + template + SpecIterator makeSpecIterator(llvm::FoldingSet &Specs, + bool isEnd) { + return SpecIterator(isEnd ? Specs.end() : Specs.begin()); + } + + template typename SpecEntryTraits::DeclType* + findSpecializationImpl(llvm::FoldingSet &Specs, + const TemplateArgument *Args, unsigned NumArgs, + void *&InsertPos); + + struct CommonBase { + CommonBase() : InstantiatedFromMember(0, false) { } + + /// \brief The template from which this was most + /// directly instantiated (or null). + /// + /// The boolean value indicates whether this template + /// was explicitly specialized. + llvm::PointerIntPair + InstantiatedFromMember; + + /// \brief The latest declaration of this template. + RedeclarableTemplateDecl *Latest; + }; + + /// \brief A pointer to the previous declaration (if this is a redeclaration) + /// or to the data that is common to all declarations of this template. + llvm::PointerUnion CommonOrPrev; + + /// \brief Retrieves the "common" pointer shared by all (re-)declarations of + /// the same template. Calling this routine may implicitly allocate memory + /// for the common pointer. + CommonBase *getCommonPtr(); + + virtual CommonBase *newCommon() = 0; + + // Construct a template decl with name, parameters, and templated element. + RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, + DeclarationName Name, TemplateParameterList *Params, + NamedDecl *Decl) + : TemplateDecl(DK, DC, L, Name, Params, Decl), + CommonOrPrev((CommonBase*)0) { } + +public: + template friend class RedeclarableTemplate; + + RedeclarableTemplateDecl *getCanonicalDecl() { + return getCanonicalDeclImpl(); + } + + /// \brief Retrieve the previous declaration of this template, or + /// NULL if no such declaration exists. + RedeclarableTemplateDecl *getPreviousDeclaration() { + return getPreviousDeclarationImpl(); + } + + /// \brief Retrieve the previous declaration of this template, or + /// NULL if no such declaration exists. + const RedeclarableTemplateDecl *getPreviousDeclaration() const { + return + const_cast(this)->getPreviousDeclaration(); + } + + /// \brief Retrieve the first declaration of this template, or itself + /// if this the first one. + RedeclarableTemplateDecl *getFirstDeclaration() { + return getCanonicalDecl(); + } + + /// \brief Retrieve the first declaration of this template, or itself + /// if this the first one. + const RedeclarableTemplateDecl *getFirstDeclaration() const { + return + const_cast(this)->getFirstDeclaration(); + } + + /// \brief Retrieve the most recent declaration of this template, or itself + /// if this the most recent one. + RedeclarableTemplateDecl *getMostRecentDeclaration() { + return getCommonPtr()->Latest; + } + + /// \brief Retrieve the most recent declaration of this template, or itself + /// if this the most recent one. + const RedeclarableTemplateDecl *getMostRecentDeclaration() const { + return + const_cast(this)->getMostRecentDeclaration(); } /// \brief Determines whether this template was a specialization of a /// member template. /// - /// In the following example, the function template \c X::f is a - /// member specialization. + /// In the following example, the function template \c X::f and the + /// member template \c X::Inner are member specializations. /// /// \code /// template /// struct X { /// template void f(T, U); + /// template struct Inner; /// }; /// /// template<> template /// void X::f(int, T); + /// template<> template + /// struct X::Inner { /* ... */ }; /// \endcode bool isMemberSpecialization() { return getCommonPtr()->InstantiatedFromMember.getInt(); @@ -618,6 +668,197 @@ public: getCommonPtr()->InstantiatedFromMember.setInt(true); } + /// \brief Retrieve the previous declaration of this template, or + /// NULL if no such declaration exists. + RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() { + return getInstantiatedFromMemberTemplateImpl(); + } + + virtual RedeclarableTemplateDecl *getNextRedeclaration(); + + // Implement isa/cast/dyncast/etc. + static bool classof(const Decl *D) { return classofKind(D->getKind()); } + static bool classof(const RedeclarableTemplateDecl *D) { return true; } + static bool classof(const FunctionTemplateDecl *D) { return true; } + static bool classof(const ClassTemplateDecl *D) { return true; } + static bool classofKind(Kind K) { + return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate; + } + + friend class ASTDeclReader; + friend class ASTDeclWriter; +}; + +template +class RedeclarableTemplate { + RedeclarableTemplateDecl *thisDecl() { + return static_cast(this); + } + +public: + /// \brief Retrieve the previous declaration of this function template, or + /// NULL if no such declaration exists. + decl_type *getPreviousDeclaration() { + return static_cast(thisDecl()->getPreviousDeclarationImpl()); + } + + /// \brief Retrieve the previous declaration of this function template, or + /// NULL if no such declaration exists. + const decl_type *getPreviousDeclaration() const { + return const_cast(this)->getPreviousDeclaration(); + } + + /// \brief Set the previous declaration of this function template. + void setPreviousDeclaration(decl_type *Prev) { + thisDecl()->setPreviousDeclarationImpl(Prev); + } + + decl_type *getCanonicalDecl() { + return static_cast(thisDecl()->getCanonicalDeclImpl()); + } + + const decl_type *getCanonicalDecl() const { + return const_cast(this)->getCanonicalDecl(); + } + + /// \brief Retrieve the member template that this template was instantiated + /// from. + /// + /// This routine will return non-NULL for member templates of + /// class templates. For example, given: + /// + /// \code + /// template + /// struct X { + /// template void f(); + /// template struct A {}; + /// }; + /// \endcode + /// + /// X::f is a CXXMethodDecl (whose parent is X, a + /// ClassTemplateSpecializationDecl) for which getPrimaryTemplate() will + /// return X::f, a FunctionTemplateDecl (whose parent is again + /// X) for which getInstantiatedFromMemberTemplate() will return + /// X::f, a FunctionTemplateDecl (whose parent is X, a + /// ClassTemplateDecl). + /// + /// X::A is a ClassTemplateSpecializationDecl (whose parent + /// is X, also a CTSD) for which getSpecializedTemplate() will + /// return X::A, a ClassTemplateDecl (whose parent is again + /// X) for which getInstantiatedFromMemberTemplate() will return + /// X::A, a ClassTemplateDecl (whose parent is X, also a CTD). + /// + /// \returns NULL if this is not an instantiation of a member template. + decl_type *getInstantiatedFromMemberTemplate() { + return static_cast( + thisDecl()->getInstantiatedFromMemberTemplateImpl()); + } + + void setInstantiatedFromMemberTemplate(decl_type *TD) { + thisDecl()->setInstantiatedFromMemberTemplateImpl(TD); + } +}; + +template <> struct RedeclarableTemplateDecl:: +SpecEntryTraits { + typedef FunctionDecl DeclType; + + static DeclType * + getMostRecentDeclaration(FunctionTemplateSpecializationInfo *I) { + return I->Function->getMostRecentDeclaration(); + } +}; + +/// Declaration of a template function. +class FunctionTemplateDecl : public RedeclarableTemplateDecl, + public RedeclarableTemplate { + static void DeallocateCommon(void *Ptr); + +protected: + typedef RedeclarableTemplate redeclarable_base; + + /// \brief Data that is common to all of the declarations of a given + /// function template. + struct Common : CommonBase { + /// \brief The function template specializations for this function + /// template, including explicit specializations and instantiations. + llvm::FoldingSet Specializations; + }; + + FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, + TemplateParameterList *Params, NamedDecl *Decl) + : RedeclarableTemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { } + + CommonBase *newCommon(); + + Common *getCommonPtr() { + return static_cast(RedeclarableTemplateDecl::getCommonPtr()); + } + + friend void FunctionDecl::setFunctionTemplateSpecialization( + FunctionTemplateDecl *Template, + const TemplateArgumentList *TemplateArgs, + void *InsertPos, + TemplateSpecializationKind TSK, + const TemplateArgumentListInfo *TemplateArgsAsWritten, + SourceLocation PointOfInstantiation); + + /// \brief Retrieve the set of function template specializations of this + /// function template. + llvm::FoldingSet &getSpecializations() { + return getCommonPtr()->Specializations; + } + +public: + /// Get the underlying function declaration of the template. + FunctionDecl *getTemplatedDecl() const { + return static_cast(TemplatedDecl); + } + + /// Returns whether this template declaration defines the primary + /// pattern. + bool isThisDeclarationADefinition() const { + return getTemplatedDecl()->isThisDeclarationADefinition(); + } + + /// \brief Return the specialization with the provided arguments if it exists, + /// otherwise return the insertion point. + FunctionDecl *findSpecialization(const TemplateArgument *Args, + unsigned NumArgs, void *&InsertPos); + + FunctionTemplateDecl *getCanonicalDecl() { + return redeclarable_base::getCanonicalDecl(); + } + const FunctionTemplateDecl *getCanonicalDecl() const { + return redeclarable_base::getCanonicalDecl(); + } + + /// \brief Retrieve the previous declaration of this function template, or + /// NULL if no such declaration exists. + FunctionTemplateDecl *getPreviousDeclaration() { + return redeclarable_base::getPreviousDeclaration(); + } + + /// \brief Retrieve the previous declaration of this function template, or + /// NULL if no such declaration exists. + const FunctionTemplateDecl *getPreviousDeclaration() const { + return redeclarable_base::getPreviousDeclaration(); + } + + FunctionTemplateDecl *getInstantiatedFromMemberTemplate() { + return redeclarable_base::getInstantiatedFromMemberTemplate(); + } + + typedef SpecIterator spec_iterator; + + spec_iterator spec_begin() { + return makeSpecIterator(getSpecializations(), false); + } + + spec_iterator spec_end() { + return makeSpecIterator(getSpecializations(), true); + } + /// Create a template function node. static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, @@ -630,8 +871,8 @@ public: static bool classof(const FunctionTemplateDecl *D) { return true; } static bool classofKind(Kind K) { return K == FunctionTemplate; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; //===----------------------------------------------------------------------===// @@ -781,8 +1022,7 @@ class NonTypeTemplateParmDecl NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo) - : VarDecl(NonTypeTemplateParm, DC, L, Id, T, TInfo, VarDecl::None, - VarDecl::None), + : VarDecl(NonTypeTemplateParm, DC, L, Id, T, TInfo, SC_None, SC_None), TemplateParmPosition(D, P), DefaultArgumentAndInherited(0, false) { } @@ -904,13 +1144,20 @@ public: DefaultArgumentWasInherited = false; } + SourceRange getSourceRange() const { + SourceLocation End = getLocation(); + if (hasDefaultArgument() && !defaultArgumentWasInherited()) + End = getDefaultArgument().getSourceRange().getEnd(); + return SourceRange(getTemplateParameters()->getTemplateLoc(), End); + } + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const TemplateTemplateParmDecl *D) { return true; } static bool classofKind(Kind K) { return K == TemplateTemplateParm; } - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// \brief Represents a class template specialization, which refers to @@ -991,12 +1238,21 @@ public: static ClassTemplateSpecializationDecl * Create(ASTContext &Context, EmptyShell Empty); - virtual void Destroy(ASTContext& C); - virtual void getNameForDiagnostic(std::string &S, const PrintingPolicy &Policy, bool Qualified) const; + ClassTemplateSpecializationDecl *getMostRecentDeclaration() { + CXXRecordDecl *Recent + = cast(CXXRecordDecl::getMostRecentDeclaration()); + if (!isa(Recent)) { + // FIXME: Does injected class name need to be in the redeclarations chain? + assert(Recent->isInjectedClassName() && Recent->getPreviousDeclaration()); + Recent = Recent->getPreviousDeclaration(); + } + return cast(Recent); + } + /// \brief Retrieve the template that this specialization specializes. ClassTemplateDecl *getSpecializedTemplate() const; @@ -1044,7 +1300,8 @@ public: if (getSpecializationKind() != TSK_ImplicitInstantiation && getSpecializationKind() != TSK_ExplicitInstantiationDefinition && getSpecializationKind() != TSK_ExplicitInstantiationDeclaration) - return (ClassTemplateDecl*)0; + return llvm::PointerUnion(); if (SpecializedPartialSpecialization *PartialSpec = SpecializedTemplate.dyn_cast()) @@ -1123,7 +1380,8 @@ public: /// \brief Sets the type of this specialization as it was written by /// the user. This will be a class template specialization type. void setTypeAsWritten(TypeSourceInfo *T) { - if (!ExplicitInfo) ExplicitInfo = new ExplicitSpecializationInfo; + if (!ExplicitInfo) + ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo; ExplicitInfo->TypeAsWritten = T; } /// \brief Gets the type of this specialization as it was written by @@ -1138,13 +1396,15 @@ public: } /// \brief Sets the location of the extern keyword. void setExternLoc(SourceLocation Loc) { - if (!ExplicitInfo) ExplicitInfo = new ExplicitSpecializationInfo; + if (!ExplicitInfo) + ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo; ExplicitInfo->ExternLoc = Loc; } /// \brief Sets the location of the template keyword. void setTemplateKeywordLoc(SourceLocation Loc) { - if (!ExplicitInfo) ExplicitInfo = new ExplicitSpecializationInfo; + if (!ExplicitInfo) + ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo; ExplicitInfo->TemplateKeywordLoc = Loc; } /// \brief Gets the location of the template keyword, if present. @@ -1242,6 +1502,11 @@ public: static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, EmptyShell Empty); + ClassTemplatePartialSpecializationDecl *getMostRecentDeclaration() { + return cast( + ClassTemplateSpecializationDecl::getMostRecentDeclaration()); + } + /// Get the list of template parameters TemplateParameterList *getTemplateParameters() const { return TemplateParams; @@ -1355,15 +1620,16 @@ public: }; /// Declaration of a class template. -class ClassTemplateDecl : public TemplateDecl { +class ClassTemplateDecl : public RedeclarableTemplateDecl, + public RedeclarableTemplate { static void DeallocateCommon(void *Ptr); protected: + typedef RedeclarableTemplate redeclarable_base; + /// \brief Data that is common to all of the declarations of a given /// class template. - struct Common { - Common() : InstantiatedFromMember(0, 0) {} - + struct Common : CommonBase { /// \brief The class template specializations for this class /// template, including explicit specializations and instantiations. llvm::FoldingSet Specializations; @@ -1375,67 +1641,8 @@ protected: /// \brief The injected-class-name type for this class template. QualType InjectedClassNameType; - - /// \brief The templated member class from which this was most - /// directly instantiated (or null). - /// - /// The boolean value indicates whether this member class template - /// was explicitly specialized. - llvm::PointerIntPair InstantiatedFromMember; }; - /// \brief A pointer to the previous declaration (if this is a redeclaration) - /// or to the data that is common to all declarations of this class template. - llvm::PointerUnion CommonOrPrev; - - /// \brief Retrieves the "common" pointer shared by all - /// (re-)declarations of the same class template. Calling this routine - /// may implicitly allocate memory for the common pointer. - Common *getCommonPtr(); - - ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, - TemplateParameterList *Params, NamedDecl *Decl) - : TemplateDecl(ClassTemplate, DC, L, Name, Params, Decl), - CommonOrPrev((Common*)0) { } - -public: - /// Get the underlying class declarations of the template. - CXXRecordDecl *getTemplatedDecl() const { - return static_cast(TemplatedDecl); - } - - /// \brief Retrieve the previous declaration of this class template, or - /// NULL if no such declaration exists. - const ClassTemplateDecl *getPreviousDeclaration() const { - return CommonOrPrev.dyn_cast(); - } - - /// \brief Retrieve the previous declaration of this function template, or - /// NULL if no such declaration exists. - ClassTemplateDecl *getPreviousDeclaration() { - return CommonOrPrev.dyn_cast(); - } - - /// \brief Set the previous declaration of this class template. - void setPreviousDeclaration(ClassTemplateDecl *Prev) { - if (Prev) - CommonOrPrev = Prev; - } - - virtual ClassTemplateDecl *getCanonicalDecl(); - - const ClassTemplateDecl *getCanonicalDecl() const { - return const_cast(this)->getCanonicalDecl(); - } - - /// Create a class template node. - static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC, - SourceLocation L, - DeclarationName Name, - TemplateParameterList *Params, - NamedDecl *Decl, - ClassTemplateDecl *PrevDecl); - /// \brief Retrieve the set of specializations of this class template. llvm::FoldingSet &getSpecializations() { return getCommonPtr()->Specializations; @@ -1448,6 +1655,89 @@ public: return getCommonPtr()->PartialSpecializations; } + ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, + TemplateParameterList *Params, NamedDecl *Decl) + : RedeclarableTemplateDecl(ClassTemplate, DC, L, Name, Params, Decl) { } + + CommonBase *newCommon(); + + Common *getCommonPtr() { + return static_cast(RedeclarableTemplateDecl::getCommonPtr()); + } + +public: + /// Get the underlying class declarations of the template. + CXXRecordDecl *getTemplatedDecl() const { + return static_cast(TemplatedDecl); + } + + /// Returns whether this template declaration defines the primary + /// class pattern. + bool isThisDeclarationADefinition() const { + return getTemplatedDecl()->isThisDeclarationADefinition(); + } + + /// Create a class template node. + static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC, + SourceLocation L, + DeclarationName Name, + TemplateParameterList *Params, + NamedDecl *Decl, + ClassTemplateDecl *PrevDecl); + + /// \brief Return the specialization with the provided arguments if it exists, + /// otherwise return the insertion point. + ClassTemplateSpecializationDecl * + findSpecialization(const TemplateArgument *Args, unsigned NumArgs, + void *&InsertPos); + + /// \brief Insert the specified specialization knowing that it is not already + /// in. InsertPos must be obtained from findSpecialization. + void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos) { + getSpecializations().InsertNode(D, InsertPos); + } + + ClassTemplateDecl *getCanonicalDecl() { + return redeclarable_base::getCanonicalDecl(); + } + const ClassTemplateDecl *getCanonicalDecl() const { + return redeclarable_base::getCanonicalDecl(); + } + + /// \brief Retrieve the previous declaration of this class template, or + /// NULL if no such declaration exists. + ClassTemplateDecl *getPreviousDeclaration() { + return redeclarable_base::getPreviousDeclaration(); + } + + /// \brief Retrieve the previous declaration of this class template, or + /// NULL if no such declaration exists. + const ClassTemplateDecl *getPreviousDeclaration() const { + return redeclarable_base::getPreviousDeclaration(); + } + + ClassTemplateDecl *getInstantiatedFromMemberTemplate() { + return redeclarable_base::getInstantiatedFromMemberTemplate(); + } + + /// \brief Return the partial specialization with the provided arguments if it + /// exists, otherwise return the insertion point. + ClassTemplatePartialSpecializationDecl * + findPartialSpecialization(const TemplateArgument *Args, unsigned NumArgs, + void *&InsertPos); + + /// \brief Insert the specified partial specialization knowing that it is not + /// already in. InsertPos must be obtained from findPartialSpecialization. + void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, + void *InsertPos) { + getPartialSpecializations().InsertNode(D, InsertPos); + } + + /// \brief Return the next partial specialization sequence number. + unsigned getNextPartialSpecSequenceNumber() { + return getPartialSpecializations().size(); + } + /// \brief Retrieve the partial specializations as an ordered list. void getPartialSpecializations( llvm::SmallVectorImpl &PS); @@ -1455,12 +1745,24 @@ public: /// \brief Find a class template partial specialization with the given /// type T. /// - /// \brief A dependent type that names a specialization of this class + /// \param T a dependent type that names a specialization of this class /// template. /// /// \returns the class template partial specialization that exactly matches /// the type \p T, or NULL if no such partial specialization exists. ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T); + + /// \brief Find a class template partial specialization which was instantiated + /// from the given member partial specialization. + /// + /// \param D a member class template partial specialization. + /// + /// \returns the class template partial specialization which was instantiated + /// from the given member partial specialization, or NULL if no such partial + /// specialization exists. + ClassTemplatePartialSpecializationDecl * + findPartialSpecInstantiatedFromMember( + ClassTemplatePartialSpecializationDecl *D); /// \brief Retrieve the template specialization type of the /// injected-class-name for this class template. @@ -1478,78 +1780,45 @@ public: /// \endcode QualType getInjectedClassNameSpecialization(); - /// \brief Retrieve the member class template that this class template was - /// derived from. - /// - /// This routine will return non-NULL for templated member classes of - /// class templates. For example, given: - /// - /// \code - /// template - /// struct X { - /// template struct A {}; - /// }; - /// \endcode - /// - /// X::A is a ClassTemplateSpecializationDecl (whose parent - /// is X, also a CTSD) for which getSpecializedTemplate() will - /// return X::A, a TemplateClassDecl (whose parent is again - /// X) for which getInstantiatedFromMemberTemplate() will return - /// X::A, a TemplateClassDecl (whose parent is X, also a TCD). - /// - /// \returns null if this is not an instantiation of a member class template. - ClassTemplateDecl *getInstantiatedFromMemberTemplate() { - return getCommonPtr()->InstantiatedFromMember.getPointer(); + typedef SpecIterator spec_iterator; + + spec_iterator spec_begin() { + return makeSpecIterator(getSpecializations(), false); } - void setInstantiatedFromMemberTemplate(ClassTemplateDecl *CTD) { - assert(!getCommonPtr()->InstantiatedFromMember.getPointer()); - getCommonPtr()->InstantiatedFromMember.setPointer(CTD); + spec_iterator spec_end() { + return makeSpecIterator(getSpecializations(), true); } - /// \brief Determines whether this template was a specialization of a - /// member template. - /// - /// In the following example, the member template \c X::Inner is a - /// member specialization. - /// - /// \code - /// template - /// struct X { - /// template struct Inner; - /// }; - /// - /// template<> template - /// struct X::Inner { /* ... */ }; - /// \endcode - bool isMemberSpecialization() { - return getCommonPtr()->InstantiatedFromMember.getInt(); + typedef SpecIterator + partial_spec_iterator; + + partial_spec_iterator partial_spec_begin() { + return makeSpecIterator(getPartialSpecializations(), false); } - - /// \brief Note that this member template is a specialization. - void setMemberSpecialization() { - assert(getCommonPtr()->InstantiatedFromMember.getPointer() && - "Only member templates can be member template specializations"); - getCommonPtr()->InstantiatedFromMember.setInt(true); + + partial_spec_iterator partial_spec_end() { + return makeSpecIterator(getPartialSpecializations(), true); } - + // Implement isa/cast/dyncast support static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classof(const ClassTemplateDecl *D) { return true; } static bool classofKind(Kind K) { return K == ClassTemplate; } - virtual void Destroy(ASTContext& C); - - friend class PCHDeclReader; - friend class PCHDeclWriter; + friend class ASTDeclReader; + friend class ASTDeclWriter; }; /// Declaration of a friend template. For example: /// /// template class A { /// friend class MyVector; // not a friend template -/// template friend class B; // friend template +/// template friend class B; // not a friend template /// template friend class Foo::Nested; // friend template +/// }; +/// NOTE: This class is not currently in use. All of the above +/// will yield a FriendDecl, not a FriendTemplateDecl. class FriendTemplateDecl : public Decl { public: typedef llvm::PointerUnion FriendUnion; @@ -1580,6 +1849,12 @@ private: FriendLoc(FriendLoc) {} + FriendTemplateDecl(EmptyShell Empty) + : Decl(Decl::FriendTemplate, Empty), + NumParams(0), + Params(0) + {} + public: static FriendTemplateDecl *Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, @@ -1588,6 +1863,8 @@ public: FriendUnion Friend, SourceLocation FriendLoc); + static FriendTemplateDecl *Create(ASTContext &Context, EmptyShell Empty); + /// If this friend declaration names a templated type (or /// a dependent member type of a templated type), return that /// type; otherwise return null. @@ -1620,6 +1897,8 @@ public: static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classofKind(Kind K) { return K == Decl::FriendTemplate; } static bool classof(const FriendTemplateDecl *D) { return true; } + + friend class ASTDeclReader; }; /// Implementation of inline functions that require the template declarations diff --git a/include/clang/AST/DeclarationName.h b/include/clang/AST/DeclarationName.h index 8a771d513c4..8bb62759752 100644 --- a/include/clang/AST/DeclarationName.h +++ b/include/clang/AST/DeclarationName.h @@ -30,6 +30,7 @@ namespace clang { class IdentifierInfo; class MultiKeywordSelector; class UsingDirectiveDecl; + class TypeSourceInfo; /// DeclarationName - The name of a declaration. In the common case, /// this just stores an IdentifierInfo pointer to a normal @@ -367,6 +368,146 @@ public: DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II); }; +/// DeclarationNameLoc - Additional source/type location info +/// for a declaration name. Needs a DeclarationName in order +/// to be interpreted correctly. +struct DeclarationNameLoc { + union { + // The source location for identifier stored elsewhere. + // struct {} Identifier; + + // Type info for constructors, destructors and conversion functions. + // Locations (if any) for the tilde (destructor) or operator keyword + // (conversion) are stored elsewhere. + struct { + TypeSourceInfo* TInfo; + } NamedType; + + // The location (if any) of the operator keyword is stored elsewhere. + struct { + unsigned BeginOpNameLoc; + unsigned EndOpNameLoc; + } CXXOperatorName; + + // The location (if any) of the operator keyword is stored elsewhere. + struct { + unsigned OpNameLoc; + } CXXLiteralOperatorName; + + // struct {} CXXUsingDirective; + // struct {} ObjCZeroArgSelector; + // struct {} ObjCOneArgSelector; + // struct {} ObjCMultiArgSelector; + }; + + DeclarationNameLoc(DeclarationName Name); + // FIXME: this should go away once all DNLocs are properly initialized. + DeclarationNameLoc() { NamedType.TInfo = 0; } +}; // struct DeclarationNameLoc + + +/// DeclarationNameInfo - A collector data type for bundling together +/// a DeclarationName and the correspnding source/type location info. +struct DeclarationNameInfo { +private: + /// Name - The declaration name, also encoding name kind. + DeclarationName Name; + /// Loc - The main source location for the declaration name. + SourceLocation NameLoc; + /// Info - Further source/type location info for special kinds of names. + DeclarationNameLoc LocInfo; + +public: + // FIXME: remove it. + DeclarationNameInfo() {} + + DeclarationNameInfo(DeclarationName Name, SourceLocation NameLoc) + : Name(Name), NameLoc(NameLoc), LocInfo(Name) {} + + DeclarationNameInfo(DeclarationName Name, SourceLocation NameLoc, + DeclarationNameLoc LocInfo) + : Name(Name), NameLoc(NameLoc), LocInfo(LocInfo) {} + + /// getName - Returns the embedded declaration name. + DeclarationName getName() const { return Name; } + /// setName - Sets the embedded declaration name. + void setName(DeclarationName N) { Name = N; } + + /// getLoc - Returns the main location of the declaration name. + SourceLocation getLoc() const { return NameLoc; } + /// setLoc - Sets the main location of the declaration name. + void setLoc(SourceLocation L) { NameLoc = L; } + + const DeclarationNameLoc &getInfo() const { return LocInfo; } + DeclarationNameLoc &getInfo() { return LocInfo; } + void setInfo(const DeclarationNameLoc &Info) { LocInfo = Info; } + + /// getNamedTypeInfo - Returns the source type info associated to + /// the name. Assumes it is a constructor, destructor or conversion. + TypeSourceInfo *getNamedTypeInfo() const { + assert(Name.getNameKind() == DeclarationName::CXXConstructorName || + Name.getNameKind() == DeclarationName::CXXDestructorName || + Name.getNameKind() == DeclarationName::CXXConversionFunctionName); + return LocInfo.NamedType.TInfo; + } + /// setNamedTypeInfo - Sets the source type info associated to + /// the name. Assumes it is a constructor, destructor or conversion. + void setNamedTypeInfo(TypeSourceInfo *TInfo) { + assert(Name.getNameKind() == DeclarationName::CXXConstructorName || + Name.getNameKind() == DeclarationName::CXXDestructorName || + Name.getNameKind() == DeclarationName::CXXConversionFunctionName); + LocInfo.NamedType.TInfo = TInfo; + } + + /// getCXXOperatorNameRange - Gets the range of the operator name + /// (without the operator keyword). Assumes it is a (non-literal) operator. + SourceRange getCXXOperatorNameRange() const { + assert(Name.getNameKind() == DeclarationName::CXXOperatorName); + return SourceRange( + SourceLocation::getFromRawEncoding(LocInfo.CXXOperatorName.BeginOpNameLoc), + SourceLocation::getFromRawEncoding(LocInfo.CXXOperatorName.EndOpNameLoc) + ); + } + /// setCXXOperatorNameRange - Sets the range of the operator name + /// (without the operator keyword). Assumes it is a C++ operator. + void setCXXOperatorNameRange(SourceRange R) { + assert(Name.getNameKind() == DeclarationName::CXXOperatorName); + LocInfo.CXXOperatorName.BeginOpNameLoc = R.getBegin().getRawEncoding(); + LocInfo.CXXOperatorName.EndOpNameLoc = R.getEnd().getRawEncoding(); + } + + /// getCXXLiteralOperatorNameLoc - Returns the location of the literal + /// operator name (not the operator keyword). + /// Assumes it is a literal operator. + SourceLocation getCXXLiteralOperatorNameLoc() const { + assert(Name.getNameKind() == DeclarationName::CXXLiteralOperatorName); + return SourceLocation:: + getFromRawEncoding(LocInfo.CXXLiteralOperatorName.OpNameLoc); + } + /// setCXXLiteralOperatorNameLoc - Sets the location of the literal + /// operator name (not the operator keyword). + /// Assumes it is a literal operator. + void setCXXLiteralOperatorNameLoc(SourceLocation Loc) { + assert(Name.getNameKind() == DeclarationName::CXXLiteralOperatorName); + LocInfo.CXXLiteralOperatorName.OpNameLoc = Loc.getRawEncoding(); + } + + /// getAsString - Retrieve the human-readable string for this name. + std::string getAsString() const; + + /// printName - Print the human-readable name to a stream. + void printName(llvm::raw_ostream &OS) const; + + /// getBeginLoc - Retrieve the location of the first token. + SourceLocation getBeginLoc() const { return NameLoc; } + /// getEndLoc - Retrieve the location of the last token. + SourceLocation getEndLoc() const; + /// getSourceRange - The range of the declaration name. + SourceRange getSourceRange() const { + return SourceRange(getBeginLoc(), getEndLoc()); + } +}; + /// Insertion operator for diagnostics. This allows sending DeclarationName's /// into a diagnostic with <<. inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, @@ -385,6 +526,12 @@ inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, return PD; } +inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, + DeclarationNameInfo DNInfo) { + DNInfo.printName(OS); + return OS; +} + } // end namespace clang namespace llvm { diff --git a/include/clang/AST/Expr.h b/include/clang/AST/Expr.h index ade2b09c80c..48130becf3b 100644 --- a/include/clang/AST/Expr.h +++ b/include/clang/AST/Expr.h @@ -18,6 +18,7 @@ #include "clang/AST/Stmt.h" #include "clang/AST/Type.h" #include "clang/AST/DeclAccessPair.h" +#include "clang/AST/OperationKinds.h" #include "clang/AST/ASTVector.h" #include "clang/AST/UsuallyTinyPtrVector.h" #include "llvm/ADT/APSInt.h" @@ -42,7 +43,7 @@ namespace clang { class TemplateArgumentListInfo; /// \brief A simple array of base specifiers. -typedef UsuallyTinyPtrVector CXXBaseSpecifierArray; +typedef llvm::SmallVector CXXCastPath; /// Expr - This represents one expression. Note that Expr's are subclasses of /// Stmt. This allows an expression to be transparently used any place a Stmt @@ -61,8 +62,14 @@ protected: /// (C++ [temp.dep.constexpr]). bool ValueDependent : 1; + /// ValueKind - The value classification of this expression. + /// Only actually used by certain subclasses. + unsigned ValueKind : 2; + + enum { BitsRemaining = 28 }; + Expr(StmtClass SC, QualType T, bool TD, bool VD) - : Stmt(SC), TypeDependent(TD), ValueDependent(VD) { + : Stmt(SC), TypeDependent(TD), ValueDependent(VD), ValueKind(0) { setType(T); } @@ -258,7 +265,6 @@ public: /// function returning an rvalue reference. /// lvalues and xvalues are collectively referred to as glvalues, while /// prvalues and xvalues together form rvalues. - /// If a Classification Classify(ASTContext &Ctx) const { return ClassifyImpl(Ctx, 0); } @@ -310,7 +316,7 @@ public: } /// isConstantInitializer - Returns true if this expression is a constant /// initializer, which can be emitted at compile-time. - bool isConstantInitializer(ASTContext &Ctx) const; + bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const; /// EvalResult is a struct with detailed info about an evaluated expression. struct EvalResult { @@ -521,10 +527,14 @@ class DeclRefExpr : public Expr { // (2) the declaration's name was followed by an explicit template // argument list. llvm::PointerIntPair DecoratedD; - + // Loc - The location of the declaration name itself. SourceLocation Loc; + /// DNLoc - Provides source/type location info for the + /// declaration name embedded in DecoratedD. + DeclarationNameLoc DNLoc; + /// \brief Retrieve the qualifier that preceded the declaration name, if any. NameQualifier *getNameQualifier() { if ((DecoratedD.getInt() & HasQualifierFlag) == 0) @@ -537,31 +547,17 @@ class DeclRefExpr : public Expr { const NameQualifier *getNameQualifier() const { return const_cast(this)->getNameQualifier(); } - - /// \brief Retrieve the explicit template argument list that followed the - /// member template name, if any. - ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() { - if ((DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag) == 0) - return 0; - - if ((DecoratedD.getInt() & HasQualifierFlag) == 0) - return reinterpret_cast(this + 1); - - return reinterpret_cast( - getNameQualifier() + 1); - } - - /// \brief Retrieve the explicit template argument list that followed the - /// member template name, if any. - const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const { - return const_cast(this)->getExplicitTemplateArgumentList(); - } - + DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange, ValueDecl *D, SourceLocation NameLoc, const TemplateArgumentListInfo *TemplateArgs, QualType T); + DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange, + ValueDecl *D, const DeclarationNameInfo &NameInfo, + const TemplateArgumentListInfo *TemplateArgs, + QualType T); + /// \brief Construct an empty declaration reference expression. explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) { } @@ -584,6 +580,14 @@ public: QualType T, const TemplateArgumentListInfo *TemplateArgs = 0); + static DeclRefExpr *Create(ASTContext &Context, + NestedNameSpecifier *Qualifier, + SourceRange QualifierRange, + ValueDecl *D, + const DeclarationNameInfo &NameInfo, + QualType T, + const TemplateArgumentListInfo *TemplateArgs = 0); + /// \brief Construct an empty declaration reference expression. static DeclRefExpr *CreateEmpty(ASTContext &Context, bool HasQualifier, unsigned NumTemplateArgs); @@ -592,6 +596,10 @@ public: const ValueDecl *getDecl() const { return DecoratedD.getPointer(); } void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); } + DeclarationNameInfo getNameInfo() const { + return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc); + } + SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } virtual SourceRange getSourceRange() const; @@ -619,53 +627,77 @@ public: return getNameQualifier()->NNS; } - /// \brief Determines whether this member expression actually had a C++ - /// template argument list explicitly specified, e.g., x.f. - bool hasExplicitTemplateArgumentList() const { - return DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag; + bool hasExplicitTemplateArgs() const { + return (DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag); + } + + /// \brief Retrieve the explicit template argument list that followed the + /// member template name. + ExplicitTemplateArgumentList &getExplicitTemplateArgs() { + assert(hasExplicitTemplateArgs()); + + if ((DecoratedD.getInt() & HasQualifierFlag) == 0) + return *reinterpret_cast(this + 1); + + return *reinterpret_cast( + getNameQualifier() + 1); + } + + /// \brief Retrieve the explicit template argument list that followed the + /// member template name. + const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const { + return const_cast(this)->getExplicitTemplateArgs(); } + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getExplicitTemplateArgsOpt() const { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); + } + /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { - if (hasExplicitTemplateArgumentList()) - getExplicitTemplateArgumentList()->copyInto(List); + if (hasExplicitTemplateArgs()) + getExplicitTemplateArgs().copyInto(List); } /// \brief Retrieve the location of the left angle bracket following the /// member name ('<'), if any. SourceLocation getLAngleLoc() const { - if (!hasExplicitTemplateArgumentList()) + if (!hasExplicitTemplateArgs()) return SourceLocation(); - return getExplicitTemplateArgumentList()->LAngleLoc; + return getExplicitTemplateArgs().LAngleLoc; } /// \brief Retrieve the template arguments provided as part of this /// template-id. const TemplateArgumentLoc *getTemplateArgs() const { - if (!hasExplicitTemplateArgumentList()) + if (!hasExplicitTemplateArgs()) return 0; - return getExplicitTemplateArgumentList()->getTemplateArgs(); + return getExplicitTemplateArgs().getTemplateArgs(); } /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { - if (!hasExplicitTemplateArgumentList()) + if (!hasExplicitTemplateArgs()) return 0; - return getExplicitTemplateArgumentList()->NumTemplateArgs; + return getExplicitTemplateArgs().NumTemplateArgs; } /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). SourceLocation getRAngleLoc() const { - if (!hasExplicitTemplateArgumentList()) + if (!hasExplicitTemplateArgs()) return SourceLocation(); - return getExplicitTemplateArgumentList()->RAngleLoc; + return getExplicitTemplateArgs().RAngleLoc; } static bool classof(const Stmt *T) { @@ -677,8 +709,8 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); - friend class PCHStmtReader; - friend class PCHStmtWriter; + friend class ASTStmtReader; + friend class ASTStmtWriter; }; /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__. @@ -725,28 +757,84 @@ public: virtual child_iterator child_end(); }; -class IntegerLiteral : public Expr { - llvm::APInt Value; - SourceLocation Loc; -public: - // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, - // or UnsignedLongLongTy - IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l) - : Expr(IntegerLiteralClass, type, false, false), Value(V), Loc(l) { - assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); +/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without +/// leaking memory. +/// +/// For large floats/integers, APFloat/APInt will allocate memory from the heap +/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator +/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with +/// the APFloat/APInt values will never get freed. APNumericStorage uses +/// ASTContext's allocator for memory allocation. +class APNumericStorage { + unsigned BitWidth; + union { + uint64_t VAL; ///< Used to store the <= 64 bits integer value. + uint64_t *pVal; ///< Used to store the >64 bits integer value. + }; + + bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } + + APNumericStorage(const APNumericStorage&); // do not implement + APNumericStorage& operator=(const APNumericStorage&); // do not implement + +protected: + APNumericStorage() : BitWidth(0), VAL(0) { } + + llvm::APInt getIntValue() const { + unsigned NumWords = llvm::APInt::getNumWords(BitWidth); + if (NumWords > 1) + return llvm::APInt(BitWidth, NumWords, pVal); + else + return llvm::APInt(BitWidth, VAL); } + void setIntValue(ASTContext &C, const llvm::APInt &Val); +}; + +class APIntStorage : public APNumericStorage { +public: + llvm::APInt getValue() const { return getIntValue(); } + void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); } +}; + +class APFloatStorage : public APNumericStorage { +public: + llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); } + void setValue(ASTContext &C, const llvm::APFloat &Val) { + setIntValue(C, Val.bitcastToAPInt()); + } +}; + +class IntegerLiteral : public Expr { + APIntStorage Num; + SourceLocation Loc; /// \brief Construct an empty integer literal. explicit IntegerLiteral(EmptyShell Empty) : Expr(IntegerLiteralClass, Empty) { } - const llvm::APInt &getValue() const { return Value; } +public: + // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, + // or UnsignedLongLongTy + IntegerLiteral(ASTContext &C, const llvm::APInt &V, + QualType type, SourceLocation l) + : Expr(IntegerLiteralClass, type, false, false), Loc(l) { + assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); + setValue(C, V); + } + + // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, + // or UnsignedLongLongTy + static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V, + QualType type, SourceLocation l); + static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty); + + llvm::APInt getValue() const { return Num.getValue(); } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } /// \brief Retrieve the location of the literal. SourceLocation getLocation() const { return Loc; } - void setValue(const llvm::APInt &Val) { Value = Val; } + void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); } void setLocation(SourceLocation Location) { Loc = Location; } static bool classof(const Stmt *T) { @@ -795,21 +883,30 @@ public: }; class FloatingLiteral : public Expr { - llvm::APFloat Value; + APFloatStorage Num; bool IsExact : 1; SourceLocation Loc; -public: - FloatingLiteral(const llvm::APFloat &V, bool isexact, + + FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L) - : Expr(FloatingLiteralClass, Type, false, false), Value(V), - IsExact(isexact), Loc(L) {} + : Expr(FloatingLiteralClass, Type, false, false), + IsExact(isexact), Loc(L) { + setValue(C, V); + } /// \brief Construct an empty floating-point literal. explicit FloatingLiteral(EmptyShell Empty) - : Expr(FloatingLiteralClass, Empty), Value(0.0) { } + : Expr(FloatingLiteralClass, Empty), IsExact(false) { } - const llvm::APFloat &getValue() const { return Value; } - void setValue(const llvm::APFloat &Val) { Value = Val; } +public: + static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V, + bool isexact, QualType Type, SourceLocation L); + static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty); + + llvm::APFloat getValue() const { return Num.getValue(); } + void setValue(ASTContext &C, const llvm::APFloat &Val) { + Num.setValue(C, Val); + } bool isExact() const { return IsExact; } void setExact(bool E) { IsExact = E; } @@ -889,9 +986,6 @@ class StringLiteral : public Expr { StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, false, false) {} -protected: - virtual void DoDestroy(ASTContext &C); - public: /// This is the "fully general" constructor that allows representation of /// strings formed from multiple concatenated tokens. @@ -912,8 +1006,7 @@ public: llvm::StringRef getString() const { return llvm::StringRef(StrData, ByteLength); } - // FIXME: These are deprecated, replace with StringRef. - const char *getStrData() const { return StrData; } + unsigned getByteLength() const { return ByteLength; } /// \brief Sets the string data to the given string data. @@ -1009,40 +1102,27 @@ public: /// applied to a non-complex value, the former returns its operand and the /// later returns zero in the type of the operand. /// -/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose -/// subexpression is a compound literal with the various MemberExpr and -/// ArraySubscriptExpr's applied to it. (This is only used in C) -/// class UnaryOperator : public Expr { public: - // Note that additions to this should also update the StmtVisitor class. - enum Opcode { - PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators - PreInc, PreDec, // [C99 6.5.3.1] Prefix increment and decrement operators. - AddrOf, Deref, // [C99 6.5.3.2] Address and indirection operators. - Plus, Minus, // [C99 6.5.3.3] Unary arithmetic operators. - Not, LNot, // [C99 6.5.3.3] Unary arithmetic operators. - Real, Imag, // "__real expr"/"__imag expr" Extension. - Extension, // __extension__ marker. - OffsetOf // __builtin_offsetof - }; + typedef UnaryOperatorKind Opcode; + private: - Stmt *Val; - Opcode Opc; + unsigned Opc : 5; SourceLocation Loc; + Stmt *Val; public: UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l) : Expr(UnaryOperatorClass, type, - input->isTypeDependent() && opc != OffsetOf, + input->isTypeDependent() || type->isDependentType(), input->isValueDependent()), - Val(input), Opc(opc), Loc(l) {} + Opc(opc), Loc(l), Val(input) {} /// \brief Build an empty unary operator. explicit UnaryOperator(EmptyShell Empty) - : Expr(UnaryOperatorClass, Empty), Opc(AddrOf) { } + : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { } - Opcode getOpcode() const { return Opc; } + Opcode getOpcode() const { return static_cast(Opc); } void setOpcode(Opcode O) { Opc = O; } Expr *getSubExpr() const { return cast(Val); } @@ -1054,21 +1134,26 @@ public: /// isPostfix - Return true if this is a postfix operation, like x++. static bool isPostfix(Opcode Op) { - return Op == PostInc || Op == PostDec; + return Op == UO_PostInc || Op == UO_PostDec; } /// isPostfix - Return true if this is a prefix operation, like --x. static bool isPrefix(Opcode Op) { - return Op == PreInc || Op == PreDec; + return Op == UO_PreInc || Op == UO_PreDec; } - bool isPrefix() const { return isPrefix(Opc); } - bool isPostfix() const { return isPostfix(Opc); } - bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; } - bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; } - bool isOffsetOfOp() const { return Opc == OffsetOf; } - static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; } - bool isArithmeticOp() const { return isArithmeticOp(Opc); } + bool isPrefix() const { return isPrefix(getOpcode()); } + bool isPostfix() const { return isPostfix(getOpcode()); } + bool isIncrementOp() const { + return Opc == UO_PreInc || Opc == UO_PostInc; + } + bool isIncrementDecrementOp() const { + return Opc <= UO_PreDec; + } + static bool isArithmeticOp(Opcode Op) { + return Op >= UO_Plus && Op <= UO_LNot; + } + bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "sizeof" or "[pre]++" @@ -1310,9 +1395,6 @@ class SizeOfAlignOfExpr : public Expr { } Argument; SourceLocation OpLoc, RParenLoc; -protected: - virtual void DoDestroy(ASTContext& C); - public: SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo, QualType resultType, SourceLocation op, @@ -1485,8 +1567,6 @@ protected: CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation rparenloc); - virtual void DoDestroy(ASTContext& C); - public: CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t, SourceLocation rparenloc); @@ -1494,8 +1574,6 @@ public: /// \brief Build an empty call expression. CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty); - ~CallExpr() {} - const Expr *getCallee() const { return cast(SubExprs[FN]); } Expr *getCallee() { return cast(SubExprs[FN]); } void setCallee(Expr *F) { SubExprs[FN] = F; } @@ -1594,6 +1672,10 @@ class MemberExpr : public Expr { /// MemberLoc - This is the location of the member name. SourceLocation MemberLoc; + /// MemberDNLoc - Provides source/type location info for the + /// declaration name embedded in MemberDecl. + DeclarationNameLoc MemberDNLoc; + /// IsArrow - True if this is "X->F", false if this is "X.F". bool IsArrow : 1; @@ -1621,37 +1703,33 @@ class MemberExpr : public Expr { return const_cast(this)->getMemberQualifier(); } - /// \brief Retrieve the explicit template argument list that followed the - /// member template name, if any. - ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() { - if (!HasExplicitTemplateArgumentList) - return 0; - - if (!HasQualifierOrFoundDecl) - return reinterpret_cast(this + 1); - - return reinterpret_cast( - getMemberQualifier() + 1); - } - - /// \brief Retrieve the explicit template argument list that followed the - /// member template name, if any. - const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const { - return const_cast(this)->getExplicitTemplateArgumentList(); - } - public: + MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, + const DeclarationNameInfo &NameInfo, QualType ty) + : Expr(MemberExprClass, ty, + base->isTypeDependent(), base->isValueDependent()), + Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()), + MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow), + HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) { + assert(memberdecl->getDeclName() == NameInfo.getName()); + } + + // NOTE: this constructor should be used only when it is known that + // the member name can not provide additional syntactic info + // (i.e., source locations for C++ operator names or type source info + // for constructors, destructors and conversion oeprators). MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl, SourceLocation l, QualType ty) : Expr(MemberExprClass, ty, base->isTypeDependent(), base->isValueDependent()), - Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow), + Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(), + IsArrow(isarrow), HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {} static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow, NestedNameSpecifier *qual, SourceRange qualrange, ValueDecl *memberdecl, DeclAccessPair founddecl, - SourceLocation l, + DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *targs, QualType ty); @@ -1700,15 +1778,42 @@ public: /// \brief Determines whether this member expression actually had a C++ /// template argument list explicitly specified, e.g., x.f. - bool hasExplicitTemplateArgumentList() const { + bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgumentList; } /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { - if (hasExplicitTemplateArgumentList()) - getExplicitTemplateArgumentList()->copyInto(List); + if (hasExplicitTemplateArgs()) + getExplicitTemplateArgs().copyInto(List); + } + + /// \brief Retrieve the explicit template argument list that + /// follow the member template name. This must only be called on an + /// expression with explicit template arguments. + ExplicitTemplateArgumentList &getExplicitTemplateArgs() { + assert(HasExplicitTemplateArgumentList); + if (!HasQualifierOrFoundDecl) + return *reinterpret_cast(this + 1); + + return *reinterpret_cast( + getMemberQualifier() + 1); + } + + /// \brief Retrieve the explicit template argument list that + /// followed the member template name. This must only be called on + /// an expression with explicit template arguments. + const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const { + return const_cast(this)->getExplicitTemplateArgs(); + } + + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); } /// \brief Retrieve the location of the left angle bracket following the @@ -1717,7 +1822,7 @@ public: if (!HasExplicitTemplateArgumentList) return SourceLocation(); - return getExplicitTemplateArgumentList()->LAngleLoc; + return getExplicitTemplateArgs().LAngleLoc; } /// \brief Retrieve the template arguments provided as part of this @@ -1726,7 +1831,7 @@ public: if (!HasExplicitTemplateArgumentList) return 0; - return getExplicitTemplateArgumentList()->getTemplateArgs(); + return getExplicitTemplateArgs().getTemplateArgs(); } /// \brief Retrieve the number of template arguments provided as part of this @@ -1735,7 +1840,7 @@ public: if (!HasExplicitTemplateArgumentList) return 0; - return getExplicitTemplateArgumentList()->NumTemplateArgs; + return getExplicitTemplateArgs().NumTemplateArgs; } /// \brief Retrieve the location of the right angle bracket following the @@ -1744,7 +1849,13 @@ public: if (!HasExplicitTemplateArgumentList) return SourceLocation(); - return getExplicitTemplateArgumentList()->RAngleLoc; + return getExplicitTemplateArgs().RAngleLoc; + } + + /// \brief Retrieve the member declaration name info. + DeclarationNameInfo getMemberNameInfo() const { + return DeclarationNameInfo(MemberDecl->getDeclName(), + MemberLoc, MemberDNLoc); } bool isArrow() const { return IsArrow; } @@ -1758,9 +1869,8 @@ public: virtual SourceRange getSourceRange() const { // If we have an implicit base (like a C++ implicit this), // make sure not to return its location - SourceLocation EndLoc = MemberLoc; - if (HasExplicitTemplateArgumentList) - EndLoc = getRAngleLoc(); + SourceLocation EndLoc = (HasExplicitTemplateArgumentList) + ? getRAngleLoc() : getMemberNameInfo().getEndLoc(); SourceLocation BaseLoc = getBase()->getLocStart(); if (BaseLoc.isInvalid()) @@ -1843,110 +1953,13 @@ public: /// classes). class CastExpr : public Expr { public: - /// CastKind - the kind of cast this represents. - enum CastKind { - /// CK_Unknown - Unknown cast kind. - /// FIXME: The goal is to get rid of this and make all casts have a - /// kind so that the AST client doesn't have to try to figure out what's - /// going on. - CK_Unknown, - - /// CK_BitCast - Used for reinterpret_cast. - CK_BitCast, - - /// CK_LValueBitCast - Used for reinterpret_cast of expressions to - /// a reference type. - CK_LValueBitCast, - - /// CK_NoOp - Used for const_cast. - CK_NoOp, - - /// CK_BaseToDerived - Base to derived class casts. - CK_BaseToDerived, - - /// CK_DerivedToBase - Derived to base class casts. - CK_DerivedToBase, - - /// CK_UncheckedDerivedToBase - Derived to base class casts that - /// assume that the derived pointer is not null. - CK_UncheckedDerivedToBase, - - /// CK_Dynamic - Dynamic cast. - CK_Dynamic, - - /// CK_ToUnion - Cast to union (GCC extension). - CK_ToUnion, - - /// CK_ArrayToPointerDecay - Array to pointer decay. - CK_ArrayToPointerDecay, - - // CK_FunctionToPointerDecay - Function to pointer decay. - CK_FunctionToPointerDecay, - - /// CK_NullToMemberPointer - Null pointer to member pointer. - CK_NullToMemberPointer, - - /// CK_BaseToDerivedMemberPointer - Member pointer in base class to - /// member pointer in derived class. - CK_BaseToDerivedMemberPointer, - - /// CK_DerivedToBaseMemberPointer - Member pointer in derived class to - /// member pointer in base class. - CK_DerivedToBaseMemberPointer, - - /// CK_UserDefinedConversion - Conversion using a user defined type - /// conversion function. - CK_UserDefinedConversion, - - /// CK_ConstructorConversion - Conversion by constructor - CK_ConstructorConversion, - - /// CK_IntegralToPointer - Integral to pointer - CK_IntegralToPointer, - - /// CK_PointerToIntegral - Pointer to integral - CK_PointerToIntegral, - - /// CK_ToVoid - Cast to void. - CK_ToVoid, - - /// CK_VectorSplat - Casting from an integer/floating type to an extended - /// vector type with the same element type as the src type. Splats the - /// src expression into the destination expression. - CK_VectorSplat, - - /// CK_IntegralCast - Casting between integral types of different size. - CK_IntegralCast, - - /// CK_IntegralToFloating - Integral to floating point. - CK_IntegralToFloating, - - /// CK_FloatingToIntegral - Floating point to integral. - CK_FloatingToIntegral, - - /// CK_FloatingCast - Casting between floating types of different size. - CK_FloatingCast, - - /// CK_MemberPointerToBoolean - Member pointer to boolean - CK_MemberPointerToBoolean, - - /// CK_AnyPointerToObjCPointerCast - Casting any pointer to objective-c - /// pointer - CK_AnyPointerToObjCPointerCast, - /// CK_AnyPointerToBlockPointerCast - Casting any pointer to block - /// pointer - CK_AnyPointerToBlockPointerCast - - }; + typedef clang::CastKind CastKind; private: - CastKind Kind; + unsigned Kind : 5; + unsigned BasePathSize : BitsRemaining - 5; Stmt *Op; - /// BasePath - For derived-to-base and base-to-derived casts, the base array - /// contains the inheritance path. - CXXBaseSpecifierArray BasePath; - void CheckBasePath() const { #ifndef NDEBUG switch (getCastKind()) { @@ -1955,7 +1968,7 @@ private: case CK_DerivedToBaseMemberPointer: case CK_BaseToDerived: case CK_BaseToDerivedMemberPointer: - assert(!BasePath.empty() && "Cast kind should have a base path!"); + assert(!path_empty() && "Cast kind should have a base path!"); break; // These should not have an inheritance path. @@ -1981,15 +1994,21 @@ private: case CK_MemberPointerToBoolean: case CK_AnyPointerToObjCPointerCast: case CK_AnyPointerToBlockPointerCast: - assert(BasePath.empty() && "Cast kind should not have a base path!"); + case CK_ObjCObjectLValueCast: + assert(path_empty() && "Cast kind should not have a base path!"); break; } #endif } + const CXXBaseSpecifier * const *path_buffer() const { + return const_cast(this)->path_buffer(); + } + CXXBaseSpecifier **path_buffer(); + protected: CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath) : + unsigned BasePathSize) : Expr(SC, ty, // Cast expressions are type-dependent if the type is // dependent (C++ [temp.dep.expr]p3). @@ -1997,18 +2016,16 @@ protected: // Cast expressions are value-dependent if the type is // dependent or if the subexpression is value-dependent. ty->isDependentType() || (op && op->isValueDependent())), - Kind(kind), Op(op), BasePath(BasePath) { - CheckBasePath(); - } + Kind(kind), BasePathSize(BasePathSize), Op(op) { + CheckBasePath(); + } /// \brief Construct an empty cast. - CastExpr(StmtClass SC, EmptyShell Empty) - : Expr(SC, Empty) { } - - virtual void DoDestroy(ASTContext &C); + CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) + : Expr(SC, Empty), BasePathSize(BasePathSize) { } public: - CastKind getCastKind() const { return Kind; } + CastKind getCastKind() const { return static_cast(Kind); } void setCastKind(CastKind K) { Kind = K; } const char *getCastKindName() const; @@ -2024,8 +2041,16 @@ public: return const_cast(this)->getSubExprAsWritten(); } - const CXXBaseSpecifierArray& getBasePath() const { return BasePath; } - CXXBaseSpecifierArray& getBasePath() { return BasePath; } + typedef CXXBaseSpecifier **path_iterator; + typedef const CXXBaseSpecifier * const *path_const_iterator; + bool path_empty() const { return BasePathSize == 0; } + unsigned path_size() const { return BasePathSize; } + path_iterator path_begin() { return path_buffer(); } + path_iterator path_end() { return path_buffer() + path_size(); } + path_const_iterator path_begin() const { return path_buffer(); } + path_const_iterator path_end() const { return path_buffer() + path_size(); } + + void setCastPath(const CXXCastPath &Path); static bool classof(const Stmt *T) { return T->getStmtClass() >= firstCastExprConstant && @@ -2045,38 +2070,57 @@ public: /// /// In C, implicit casts always produce rvalues. However, in C++, an /// implicit cast whose result is being bound to a reference will be -/// an lvalue. For example: +/// an lvalue or xvalue. For example: /// /// @code /// class Base { }; /// class Derived : public Base { }; +/// Derived &&ref(); /// void f(Derived d) { -/// Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base +/// Base& b = d; // initializer is an ImplicitCastExpr +/// // to an lvalue of type Base +/// Base&& r = ref(); // initializer is an ImplicitCastExpr +/// // to an xvalue of type Base /// } /// @endcode class ImplicitCastExpr : public CastExpr { - /// LvalueCast - Whether this cast produces an lvalue. - bool LvalueCast; - -public: - ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath, bool Lvalue) - : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePath), - LvalueCast(Lvalue) { } +private: + ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, + unsigned BasePathLength, ExprValueKind VK) + : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePathLength) { + ValueKind = VK; + } /// \brief Construct an empty implicit cast. - explicit ImplicitCastExpr(EmptyShell Shell) - : CastExpr(ImplicitCastExprClass, Shell) { } + explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) + : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } + +public: + enum OnStack_t { OnStack }; + ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, + ExprValueKind VK) + : CastExpr(ImplicitCastExprClass, ty, kind, op, 0) { + ValueKind = VK; + } + + static ImplicitCastExpr *Create(ASTContext &Context, QualType T, + CastKind Kind, Expr *Operand, + const CXXCastPath *BasePath, + ExprValueKind Cat); + + static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); virtual SourceRange getSourceRange() const { return getSubExpr()->getSourceRange(); } - /// isLvalueCast - Whether this cast produces an lvalue. - bool isLvalueCast() const { return LvalueCast; } + /// getValueKind - The value kind that this cast produces. + ExprValueKind getValueKind() const { + return static_cast(ValueKind); + } - /// setLvalueCast - Set whether this cast produces an lvalue. - void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; } + /// setValueKind - Set the value kind this cast produces. + void setValueKind(ExprValueKind Cat) { ValueKind = Cat; } static bool classof(const Stmt *T) { return T->getStmtClass() == ImplicitCastExprClass; @@ -2098,8 +2142,8 @@ public: /// actual type of the expression as determined by semantic /// analysis. These types may differ slightly. For example, in C++ one /// can cast to a reference type, which indicates that the resulting -/// expression will be an lvalue. The reference type, however, will -/// not be used as the type of the expression. +/// expression will be an lvalue or xvalue. The reference type, however, +/// will not be used as the type of the expression. class ExplicitCastExpr : public CastExpr { /// TInfo - Source type info for the (written) type /// this expression is casting to. @@ -2107,13 +2151,12 @@ class ExplicitCastExpr : public CastExpr { protected: ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind, - Expr *op, CXXBaseSpecifierArray BasePath, - TypeSourceInfo *writtenTy) - : CastExpr(SC, exprTy, kind, op, BasePath), TInfo(writtenTy) {} + Expr *op, unsigned PathSize, TypeSourceInfo *writtenTy) + : CastExpr(SC, exprTy, kind, op, PathSize), TInfo(writtenTy) {} /// \brief Construct an empty explicit cast. - ExplicitCastExpr(StmtClass SC, EmptyShell Shell) - : CastExpr(SC, Shell) { } + ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) + : CastExpr(SC, Shell, PathSize) { } public: /// getTypeInfoAsWritten - Returns the type source info for the type @@ -2138,16 +2181,24 @@ public: class CStyleCastExpr : public ExplicitCastExpr { SourceLocation LPLoc; // the location of the left paren SourceLocation RPLoc; // the location of the right paren -public: + CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy, + unsigned PathSize, TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r) - : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, BasePath, + : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, PathSize, writtenTy), LPLoc(l), RPLoc(r) {} /// \brief Construct an empty C-style explicit cast. - explicit CStyleCastExpr(EmptyShell Shell) - : ExplicitCastExpr(CStyleCastExprClass, Shell) { } + explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) + : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } + +public: + static CStyleCastExpr *Create(ASTContext &Context, QualType T, CastKind K, + Expr *Op, const CXXCastPath *BasePath, + TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation R); + + static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize); SourceLocation getLParenLoc() const { return LPLoc; } void setLParenLoc(SourceLocation L) { LPLoc = L; } @@ -2184,33 +2235,14 @@ public: /// be used to express the computation. class BinaryOperator : public Expr { public: - enum Opcode { - // Operators listed in order of precedence. - // Note that additions to this should also update the StmtVisitor class. - PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators. - Mul, Div, Rem, // [C99 6.5.5] Multiplicative operators. - Add, Sub, // [C99 6.5.6] Additive operators. - Shl, Shr, // [C99 6.5.7] Bitwise shift operators. - LT, GT, LE, GE, // [C99 6.5.8] Relational operators. - EQ, NE, // [C99 6.5.9] Equality operators. - And, // [C99 6.5.10] Bitwise AND operator. - Xor, // [C99 6.5.11] Bitwise XOR operator. - Or, // [C99 6.5.12] Bitwise OR operator. - LAnd, // [C99 6.5.13] Logical AND operator. - LOr, // [C99 6.5.14] Logical OR operator. - Assign, MulAssign,// [C99 6.5.16] Assignment operators. - DivAssign, RemAssign, - AddAssign, SubAssign, - ShlAssign, ShrAssign, - AndAssign, XorAssign, - OrAssign, - Comma // [C99 6.5.17] Comma operator. - }; + typedef BinaryOperatorKind Opcode; + private: + unsigned Opc : 6; + SourceLocation OpLoc; + enum { LHS, RHS, END_EXPR }; Stmt* SubExprs[END_EXPR]; - Opcode Opc; - SourceLocation OpLoc; public: BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, @@ -2227,12 +2259,12 @@ public: /// \brief Construct an empty binary operator. explicit BinaryOperator(EmptyShell Empty) - : Expr(BinaryOperatorClass, Empty), Opc(Comma) { } + : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } SourceLocation getOperatorLoc() const { return OpLoc; } void setOperatorLoc(SourceLocation L) { OpLoc = L; } - Opcode getOpcode() const { return Opc; } + Opcode getOpcode() const { return static_cast(Opc); } void setOpcode(Opcode O) { Opc = O; } Expr *getLHS() const { return cast(SubExprs[LHS]); } @@ -2248,6 +2280,8 @@ public: /// corresponds to, e.g. "<<=". static const char *getOpcodeStr(Opcode Op); + const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); } + /// \brief Retrieve the binary opcode that corresponds to the given /// overloaded operator. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); @@ -2257,30 +2291,34 @@ public: static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); /// predicates to categorize the respective opcodes. - bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; } - static bool isAdditiveOp(Opcode Opc) { return Opc == Add || Opc == Sub; } - bool isAdditiveOp() const { return isAdditiveOp(Opc); } - static bool isShiftOp(Opcode Opc) { return Opc == Shl || Opc == Shr; } - bool isShiftOp() const { return isShiftOp(Opc); } + bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; } + static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } + bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } + static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } + bool isShiftOp() const { return isShiftOp(getOpcode()); } - static bool isBitwiseOp(Opcode Opc) { return Opc >= And && Opc <= Or; } - bool isBitwiseOp() const { return isBitwiseOp(Opc); } + static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } + bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } - static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; } - bool isRelationalOp() const { return isRelationalOp(Opc); } + static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } + bool isRelationalOp() const { return isRelationalOp(getOpcode()); } - static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; } - bool isEqualityOp() const { return isEqualityOp(Opc); } + static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } + bool isEqualityOp() const { return isEqualityOp(getOpcode()); } - static bool isComparisonOp(Opcode Opc) { return Opc >= LT && Opc <= NE; } - bool isComparisonOp() const { return isComparisonOp(Opc); } + static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } + bool isComparisonOp() const { return isComparisonOp(getOpcode()); } - static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; } - bool isLogicalOp() const { return isLogicalOp(Opc); } + static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } + bool isLogicalOp() const { return isLogicalOp(getOpcode()); } - bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; } - bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;} - bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; } + bool isAssignmentOp() const { return Opc >= BO_Assign && Opc <= BO_OrAssign; } + bool isCompoundAssignmentOp() const { + return Opc > BO_Assign && Opc <= BO_OrAssign; + } + bool isShiftAssignOp() const { + return Opc == BO_ShlAssign || Opc == BO_ShrAssign; + } static bool classof(const Stmt *S) { return S->getStmtClass() >= firstBinaryOperatorConstant && @@ -2304,7 +2342,7 @@ protected: } BinaryOperator(StmtClass SC, EmptyShell Empty) - : Expr(SC, Empty), Opc(MulAssign) { } + : Expr(SC, Empty), Opc(BO_MulAssign) { } }; /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep @@ -2353,10 +2391,11 @@ public: class ConditionalOperator : public Expr { enum { COND, LHS, RHS, END_EXPR }; Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. + Stmt* Save; SourceLocation QuestionLoc, ColonLoc; public: ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, - SourceLocation CLoc, Expr *rhs, QualType t) + SourceLocation CLoc, Expr *rhs, Expr *save, QualType t) : Expr(ConditionalOperatorClass, t, // FIXME: the type of the conditional operator doesn't // depend on the type of the conditional, but the standard @@ -2370,6 +2409,7 @@ public: SubExprs[COND] = cond; SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; + Save = save; } /// \brief Build an empty conditional operator. @@ -2382,25 +2422,31 @@ public: void setCond(Expr *E) { SubExprs[COND] = E; } // getTrueExpr - Return the subexpression representing the value of the ?: - // expression if the condition evaluates to true. In most cases this value - // will be the same as getLHS() except a GCC extension allows the left - // subexpression to be omitted, and instead of the condition be returned. - // e.g: x ?: y is shorthand for x ? x : y, except that the expression "x" - // is only evaluated once. + // expression if the condition evaluates to true. Expr *getTrueExpr() const { - return cast(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]); + return cast(!Save ? SubExprs[LHS] : SubExprs[COND]); } - // getTrueExpr - Return the subexpression representing the value of the ?: + // getFalseExpr - Return the subexpression representing the value of the ?: // expression if the condition evaluates to false. This is the same as getRHS. Expr *getFalseExpr() const { return cast(SubExprs[RHS]); } + + // getSaveExpr - In most cases this value will be null. Except a GCC extension + // allows the left subexpression to be omitted, and instead of that condition + // be returned. e.g: x ?: y is shorthand for x ? x : y, except that the + // expression "x" is only evaluated once. Under this senario, this function + // returns the original, non-converted condition expression for the ?:operator + Expr *getSaveExpr() const { return Save? cast(Save) : (Expr*)0; } - Expr *getLHS() const { return cast_or_null(SubExprs[LHS]); } + Expr *getLHS() const { return Save ? 0 : cast(SubExprs[LHS]); } void setLHS(Expr *E) { SubExprs[LHS] = E; } Expr *getRHS() const { return cast(SubExprs[RHS]); } void setRHS(Expr *E) { SubExprs[RHS] = E; } + Expr *getSAVE() const { return Save? cast(Save) : (Expr*)0; } + void setSAVE(Expr *E) { Save = E; } + SourceLocation getQuestionLoc() const { return QuestionLoc; } void setQuestionLoc(SourceLocation L) { QuestionLoc = L; } @@ -2500,23 +2546,27 @@ public: /// expressions) are compatible. The result of this built-in function can be /// used in integer constant expressions. class TypesCompatibleExpr : public Expr { - QualType Type1; - QualType Type2; + TypeSourceInfo *TInfo1; + TypeSourceInfo *TInfo2; SourceLocation BuiltinLoc, RParenLoc; public: TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc, - QualType t1, QualType t2, SourceLocation RP) : + TypeSourceInfo *tinfo1, TypeSourceInfo *tinfo2, + SourceLocation RP) : Expr(TypesCompatibleExprClass, ReturnType, false, false), - Type1(t1), Type2(t2), BuiltinLoc(BLoc), RParenLoc(RP) {} + TInfo1(tinfo1), TInfo2(tinfo2), BuiltinLoc(BLoc), RParenLoc(RP) {} /// \brief Build an empty __builtin_type_compatible_p expression. explicit TypesCompatibleExpr(EmptyShell Empty) : Expr(TypesCompatibleExprClass, Empty) { } - QualType getArgType1() const { return Type1; } - void setArgType1(QualType T) { Type1 = T; } - QualType getArgType2() const { return Type2; } - void setArgType2(QualType T) { Type2 = T; } + TypeSourceInfo *getArgTInfo1() const { return TInfo1; } + void setArgTInfo1(TypeSourceInfo *TInfo) { TInfo1 = TInfo; } + TypeSourceInfo *getArgTInfo2() const { return TInfo2; } + void setArgTInfo2(TypeSourceInfo *TInfo) { TInfo2 = TInfo; } + + QualType getArgType1() const { return TInfo1->getType(); } + QualType getArgType2() const { return TInfo2->getType(); } SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } @@ -2553,9 +2603,6 @@ class ShuffleVectorExpr : public Expr { Stmt **SubExprs; unsigned NumExprs; -protected: - virtual void DoDestroy(ASTContext &C); - public: // FIXME: Can a shufflevector be value-dependent? Does type-dependence need // to be computed differently? @@ -2588,8 +2635,6 @@ public: } static bool classof(const ShuffleVectorExpr *) { return true; } - ~ShuffleVectorExpr() {} - /// getNumSubExprs - Return the size of the SubExprs array. This includes the /// constant expression, the actual arguments passed in, and the function /// pointers. @@ -2716,11 +2761,13 @@ public: /// VAArgExpr, used for the builtin function __builtin_va_arg. class VAArgExpr : public Expr { Stmt *Val; + TypeSourceInfo *TInfo; SourceLocation BuiltinLoc, RParenLoc; public: - VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc) + VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo, + SourceLocation RPLoc, QualType t) : Expr(VAArgExprClass, t, t->isDependentType(), false), - Val(e), + Val(e), TInfo(TInfo), BuiltinLoc(BLoc), RParenLoc(RPLoc) { } @@ -2731,6 +2778,9 @@ public: Expr *getSubExpr() { return cast(Val); } void setSubExpr(Expr *E) { Val = E; } + TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; } + void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; } + SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } @@ -2896,12 +2946,18 @@ public: virtual child_iterator child_end(); typedef InitExprsTy::iterator iterator; + typedef InitExprsTy::const_iterator const_iterator; typedef InitExprsTy::reverse_iterator reverse_iterator; + typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; iterator begin() { return InitExprs.begin(); } + const_iterator begin() const { return InitExprs.begin(); } iterator end() { return InitExprs.end(); } + const_iterator end() const { return InitExprs.end(); } reverse_iterator rbegin() { return InitExprs.rbegin(); } + const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } reverse_iterator rend() { return InitExprs.rend(); } + const_reverse_iterator rend() const { return InitExprs.rend(); } }; /// @brief Represents a C99 designated initializer expression. @@ -2961,11 +3017,6 @@ private: : Expr(DesignatedInitExprClass, EmptyShell()), NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { } -protected: - virtual void DoDestroy(ASTContext &C); - - void DestroyDesignators(ASTContext &C); - public: /// A field designator, e.g., ".x". struct FieldDesignator { @@ -3233,15 +3284,10 @@ class ParenListExpr : public Expr { unsigned NumExprs; SourceLocation LParenLoc, RParenLoc; -protected: - virtual void DoDestroy(ASTContext& C); - public: ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs, unsigned numexprs, SourceLocation rparenloc); - ~ParenListExpr() {} - /// \brief Build an empty paren list. explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } @@ -3274,8 +3320,8 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); - friend class PCHStmtReader; - friend class PCHStmtWriter; + friend class ASTStmtReader; + friend class ASTStmtWriter; }; diff --git a/include/clang/AST/ExprCXX.h b/include/clang/AST/ExprCXX.h index b9553815d8e..0a9435479d9 100644 --- a/include/clang/AST/ExprCXX.h +++ b/include/clang/AST/ExprCXX.h @@ -121,12 +121,12 @@ private: protected: CXXNamedCastExpr(StmtClass SC, QualType ty, CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy, + unsigned PathSize, TypeSourceInfo *writtenTy, SourceLocation l) - : ExplicitCastExpr(SC, ty, kind, op, BasePath, writtenTy), Loc(l) {} + : ExplicitCastExpr(SC, ty, kind, op, PathSize, writtenTy), Loc(l) {} - explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell) - : ExplicitCastExpr(SC, Shell) { } + explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) + : ExplicitCastExpr(SC, Shell, PathSize) { } public: const char *getCastName() const; @@ -158,14 +158,22 @@ public: /// This expression node represents a C++ static cast, e.g., /// @c static_cast(1.0). class CXXStaticCastExpr : public CXXNamedCastExpr { -public: CXXStaticCastExpr(QualType ty, CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy, + unsigned pathSize, TypeSourceInfo *writtenTy, SourceLocation l) - : CXXNamedCastExpr(CXXStaticCastExprClass, ty, kind, op, BasePath, writtenTy, l) {} + : CXXNamedCastExpr(CXXStaticCastExprClass, ty, kind, op, pathSize, + writtenTy, l) {} - explicit CXXStaticCastExpr(EmptyShell Empty) - : CXXNamedCastExpr(CXXStaticCastExprClass, Empty) { } + explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize) + : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) { } + +public: + static CXXStaticCastExpr *Create(ASTContext &Context, QualType T, + CastKind K, Expr *Op, + const CXXCastPath *Path, + TypeSourceInfo *Written, SourceLocation L); + static CXXStaticCastExpr *CreateEmpty(ASTContext &Context, + unsigned PathSize); static bool classof(const Stmt *T) { return T->getStmtClass() == CXXStaticCastExprClass; @@ -180,15 +188,23 @@ public: /// This expression node represents a dynamic cast, e.g., /// @c dynamic_cast(BasePtr). class CXXDynamicCastExpr : public CXXNamedCastExpr { -public: CXXDynamicCastExpr(QualType ty, CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy, + unsigned pathSize, TypeSourceInfo *writtenTy, SourceLocation l) - : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, kind, op, BasePath, + : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, kind, op, pathSize, writtenTy, l) {} - explicit CXXDynamicCastExpr(EmptyShell Empty) - : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty) { } + explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize) + : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) { } + +public: + static CXXDynamicCastExpr *Create(ASTContext &Context, QualType T, + CastKind Kind, Expr *Op, + const CXXCastPath *Path, + TypeSourceInfo *Written, SourceLocation L); + + static CXXDynamicCastExpr *CreateEmpty(ASTContext &Context, + unsigned pathSize); static bool classof(const Stmt *T) { return T->getStmtClass() == CXXDynamicCastExprClass; @@ -203,15 +219,22 @@ public: /// This expression node represents a reinterpret cast, e.g., /// @c reinterpret_cast(VoidPtr). class CXXReinterpretCastExpr : public CXXNamedCastExpr { -public: CXXReinterpretCastExpr(QualType ty, CastKind kind, Expr *op, - CXXBaseSpecifierArray BasePath, + unsigned pathSize, TypeSourceInfo *writtenTy, SourceLocation l) - : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, kind, op, BasePath, + : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, kind, op, pathSize, writtenTy, l) {} - explicit CXXReinterpretCastExpr(EmptyShell Empty) - : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty) { } + CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize) + : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) { } + +public: + static CXXReinterpretCastExpr *Create(ASTContext &Context, QualType T, + CastKind Kind, Expr *Op, + const CXXCastPath *Path, + TypeSourceInfo *WrittenTy, SourceLocation L); + static CXXReinterpretCastExpr *CreateEmpty(ASTContext &Context, + unsigned pathSize); static bool classof(const Stmt *T) { return T->getStmtClass() == CXXReinterpretCastExprClass; @@ -225,14 +248,18 @@ public: /// This expression node represents a const cast, e.g., /// @c const_cast(PtrToConstChar). class CXXConstCastExpr : public CXXNamedCastExpr { -public: CXXConstCastExpr(QualType ty, Expr *op, TypeSourceInfo *writtenTy, SourceLocation l) : CXXNamedCastExpr(CXXConstCastExprClass, ty, CK_NoOp, op, - CXXBaseSpecifierArray(), writtenTy, l) {} + 0, writtenTy, l) {} explicit CXXConstCastExpr(EmptyShell Empty) - : CXXNamedCastExpr(CXXConstCastExprClass, Empty) { } + : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) { } + +public: + static CXXConstCastExpr *Create(ASTContext &Context, QualType T, Expr *Op, + TypeSourceInfo *WrittenTy, SourceLocation L); + static CXXConstCastExpr *CreateEmpty(ASTContext &Context); static bool classof(const Stmt *T) { return T->getStmtClass() == CXXConstCastExprClass; @@ -479,9 +506,6 @@ class CXXDefaultArgExpr : public Expr { *reinterpret_cast(this + 1) = SubExpr; } -protected: - virtual void DoDestroy(ASTContext &C); - public: CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {} @@ -535,8 +559,8 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); - friend class PCHStmtReader; - friend class PCHStmtWriter; + friend class ASTStmtReader; + friend class ASTStmtWriter; }; /// CXXTemporary - Represents a C++ temporary. @@ -546,14 +570,11 @@ class CXXTemporary { CXXTemporary(const CXXDestructorDecl *destructor) : Destructor(destructor) { } - ~CXXTemporary() { } public: static CXXTemporary *Create(ASTContext &C, const CXXDestructorDecl *Destructor); - void Destroy(ASTContext &Ctx); - const CXXDestructorDecl *getDestructor() const { return Destructor; } }; @@ -579,10 +600,6 @@ class CXXBindTemporaryExpr : public Expr { CXXBindTemporaryExpr(CXXTemporary *temp, Expr* subexpr) : Expr(CXXBindTemporaryExprClass, subexpr->getType(), false, false), Temp(temp), SubExpr(subexpr) { } - ~CXXBindTemporaryExpr() { } - -protected: - virtual void DoDestroy(ASTContext &C); public: CXXBindTemporaryExpr(EmptyShell Empty) @@ -614,73 +631,6 @@ public: virtual child_iterator child_end(); }; -/// CXXBindReferenceExpr - Represents binding an expression to a reference. -/// In the example: -/// -/// const int &i = 10; -/// -/// a bind reference expression is inserted to indicate that 10 is bound to -/// a reference, and that a temporary needs to be created to hold the -/// value. -class CXXBindReferenceExpr : public Expr { - // SubExpr - The expression being bound. - Stmt *SubExpr; - - // ExtendsLifetime - Whether binding this reference extends the lifetime of - // the expression being bound. FIXME: Add C++ reference. - bool ExtendsLifetime; - - /// RequiresTemporaryCopy - Whether binding the subexpression requires a - /// temporary copy. - bool RequiresTemporaryCopy; - - CXXBindReferenceExpr(Expr *subexpr, bool ExtendsLifetime, - bool RequiresTemporaryCopy) - : Expr(CXXBindReferenceExprClass, subexpr->getType(), false, false), - SubExpr(subexpr), ExtendsLifetime(ExtendsLifetime), - RequiresTemporaryCopy(RequiresTemporaryCopy) { } - ~CXXBindReferenceExpr() { } - -protected: - virtual void DoDestroy(ASTContext &C); - -public: - static CXXBindReferenceExpr *Create(ASTContext &C, Expr *SubExpr, - bool ExtendsLifetime, - bool RequiresTemporaryCopy); - - explicit CXXBindReferenceExpr(EmptyShell Empty) - : Expr(CXXBindReferenceExprClass, Empty) { } - - const Expr *getSubExpr() const { return cast(SubExpr); } - Expr *getSubExpr() { return cast(SubExpr); } - void setSubExpr(Expr *E) { SubExpr = E; } - - virtual SourceRange getSourceRange() const { - return SubExpr->getSourceRange(); - } - - /// requiresTemporaryCopy - Whether binding the subexpression requires a - /// temporary copy. - bool requiresTemporaryCopy() const { return RequiresTemporaryCopy; } - - // extendsLifetime - Whether binding this reference extends the lifetime of - // the expression being bound. FIXME: Add C++ reference. - bool extendsLifetime() const { return ExtendsLifetime; } - - // Implement isa/cast/dyncast/etc. - static bool classof(const Stmt *T) { - return T->getStmtClass() == CXXBindReferenceExprClass; - } - static bool classof(const CXXBindReferenceExpr *) { return true; } - - // Iterators - virtual child_iterator child_begin(); - virtual child_iterator child_end(); - - friend class PCHStmtReader; -}; - /// CXXConstructExpr - Represents a call to a C++ constructor. class CXXConstructExpr : public Expr { public: @@ -707,15 +657,12 @@ protected: Expr **args, unsigned numargs, bool ZeroInitialization = false, ConstructionKind ConstructKind = CK_Complete); - ~CXXConstructExpr() { } /// \brief Construct an empty C++ construction expression. CXXConstructExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty), Constructor(0), Elidable(0), ZeroInitialization(0), ConstructKind(0), Args(0), NumArgs(0) { } - virtual void DoDestroy(ASTContext &C); - public: /// \brief Construct an empty C++ construction expression. explicit CXXConstructExpr(EmptyShell Empty) @@ -796,7 +743,7 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); - friend class PCHStmtReader; + friend class ASTStmtReader; }; /// CXXFunctionalCastExpr - Represents an explicit C++ type conversion @@ -805,17 +752,27 @@ public: class CXXFunctionalCastExpr : public ExplicitCastExpr { SourceLocation TyBeginLoc; SourceLocation RParenLoc; -public: + CXXFunctionalCastExpr(QualType ty, TypeSourceInfo *writtenTy, SourceLocation tyBeginLoc, CastKind kind, - Expr *castExpr, CXXBaseSpecifierArray BasePath, + Expr *castExpr, unsigned pathSize, SourceLocation rParenLoc) : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, kind, castExpr, - BasePath, writtenTy), + pathSize, writtenTy), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {} - explicit CXXFunctionalCastExpr(EmptyShell Shell) - : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell) { } + explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize) + : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) { } + +public: + static CXXFunctionalCastExpr *Create(ASTContext &Context, QualType T, + TypeSourceInfo *Written, + SourceLocation TyBeginLoc, + CastKind Kind, Expr *Op, + const CXXCastPath *Path, + SourceLocation RPLoc); + static CXXFunctionalCastExpr *CreateEmpty(ASTContext &Context, + unsigned PathSize); SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } void setTypeBeginLoc(SourceLocation L) { TyBeginLoc = L; } @@ -859,8 +816,6 @@ public: explicit CXXTemporaryObjectExpr(EmptyShell Empty) : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty) { } - ~CXXTemporaryObjectExpr() { } - SourceLocation getTypeBeginLoc() const { return TyBeginLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } @@ -872,7 +827,7 @@ public: } static bool classof(const CXXTemporaryObjectExpr *) { return true; } - friend class PCHStmtReader; + friend class ASTStmtReader; }; /// CXXScalarValueInitExpr - [C++ 5.2.3p2] @@ -952,7 +907,7 @@ class CXXNewExpr : public Expr { SourceLocation StartLoc; SourceLocation EndLoc; - friend class PCHStmtReader; + friend class ASTStmtReader; public: CXXNewExpr(ASTContext &C, bool globalNew, FunctionDecl *operatorNew, Expr **placementArgs, unsigned numPlaceArgs, @@ -967,8 +922,6 @@ public: void AllocateArgsArray(ASTContext &C, bool isArray, unsigned numPlaceArgs, unsigned numConsArgs); - virtual void DoDestroy(ASTContext &C); - QualType getAllocatedType() const { assert(getType()->isPointerType()); return getType()->getAs()->getPointeeType(); @@ -1381,7 +1334,7 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); - friend class PCHStmtReader; + friend class ASTStmtReader; }; /// \brief A reference to an overloaded function set, either an @@ -1395,7 +1348,7 @@ class OverloadExpr : public Expr { unsigned NumResults; /// The common name of these declarations. - DeclarationName Name; + DeclarationNameInfo NameInfo; /// The scope specifier, if any. NestedNameSpecifier *Qualifier; @@ -1403,16 +1356,13 @@ class OverloadExpr : public Expr { /// The source range of the scope specifier. SourceRange QualifierRange; - /// The location of the name. - SourceLocation NameLoc; - protected: /// True if the name was a template-id. bool HasExplicitTemplateArgs; OverloadExpr(StmtClass K, ASTContext &C, QualType T, bool Dependent, NestedNameSpecifier *Qualifier, SourceRange QRange, - DeclarationName Name, SourceLocation NameLoc, + const DeclarationNameInfo &NameInfo, bool HasTemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End); @@ -1427,19 +1377,38 @@ public: UnresolvedSetIterator End, const TemplateArgumentListInfo *Args); + struct FindResult { + OverloadExpr *Expression; + bool IsAddressOfOperand; + bool HasFormOfMemberPointer; + }; + /// Finds the overloaded expression in the given expression of /// OverloadTy. /// - /// \return the expression (which must be there) and true if it is - /// within an address-of operator. - static llvm::PointerIntPair find(Expr *E) { + /// \return the expression (which must be there) and true if it has + /// the particular form of a member pointer expression + static FindResult find(Expr *E) { assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload)); - bool op = false; + FindResult Result; + E = E->IgnoreParens(); - if (isa(E)) - op = true, E = cast(E)->getSubExpr()->IgnoreParens(); - return llvm::PointerIntPair(cast(E), op); + if (isa(E)) { + assert(cast(E)->getOpcode() == UO_AddrOf); + E = cast(E)->getSubExpr(); + OverloadExpr *Ovl = cast(E->IgnoreParens()); + + Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier()); + Result.IsAddressOfOperand = true; + Result.Expression = Ovl; + } else { + Result.HasFormOfMemberPointer = false; + Result.IsAddressOfOperand = false; + Result.Expression = cast(E); + } + + return Result; } /// Gets the naming class of this lookup, if any. @@ -1457,13 +1426,17 @@ public: /// Gets the number of declarations in the unresolved set. unsigned getNumDecls() const { return NumResults; } + /// Gets the full name info. + const DeclarationNameInfo &getNameInfo() const { return NameInfo; } + void setNameInfo(const DeclarationNameInfo &N) { NameInfo = N; } + /// Gets the name looked up. - DeclarationName getName() const { return Name; } - void setName(DeclarationName N) { Name = N; } + DeclarationName getName() const { return NameInfo.getName(); } + void setName(DeclarationName N) { NameInfo.setName(N); } /// Gets the location of the name. - SourceLocation getNameLoc() const { return NameLoc; } - void setNameLoc(SourceLocation Loc) { NameLoc = Loc; } + SourceLocation getNameLoc() const { return NameInfo.getLoc(); } + void setNameLoc(SourceLocation Loc) { NameInfo.setLoc(Loc); } /// Fetches the nested-name qualifier, if one was given. NestedNameSpecifier *getQualifier() const { return Qualifier; } @@ -1483,10 +1456,12 @@ public: return const_cast(this)->getExplicitTemplateArgs(); } - ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() { - if (hasExplicitTemplateArgs()) - return &getExplicitTemplateArgs(); - return 0; + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); } static bool classof(const Stmt *T) { @@ -1526,11 +1501,11 @@ class UnresolvedLookupExpr : public OverloadExpr { UnresolvedLookupExpr(ASTContext &C, QualType T, bool Dependent, CXXRecordDecl *NamingClass, NestedNameSpecifier *Qualifier, SourceRange QRange, - DeclarationName Name, SourceLocation NameLoc, + const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, bool HasTemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End) : OverloadExpr(UnresolvedLookupExprClass, C, T, Dependent, Qualifier, - QRange, Name, NameLoc, HasTemplateArgs, Begin, End), + QRange, NameInfo, HasTemplateArgs, Begin, End), RequiresADL(RequiresADL), Overloaded(Overloaded), NamingClass(NamingClass) {} @@ -1545,16 +1520,15 @@ public: CXXRecordDecl *NamingClass, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - DeclarationName Name, - SourceLocation NameLoc, + const DeclarationNameInfo &NameInfo, bool ADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End) { return new(C) UnresolvedLookupExpr(C, Dependent ? C.DependentTy : C.OverloadTy, Dependent, NamingClass, - Qualifier, QualifierRange, - Name, NameLoc, ADL, Overloaded, false, + Qualifier, QualifierRange, NameInfo, + ADL, Overloaded, false, Begin, End); } @@ -1563,8 +1537,7 @@ public: CXXRecordDecl *NamingClass, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - DeclarationName Name, - SourceLocation NameLoc, + const DeclarationNameInfo &NameInfo, bool ADL, const TemplateArgumentListInfo &Args, UnresolvedSetIterator Begin, @@ -1603,6 +1576,14 @@ public: return *reinterpret_cast(this + 1); } + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); + } + /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { @@ -1626,7 +1607,7 @@ public: } virtual SourceRange getSourceRange() const { - SourceRange Range(getNameLoc()); + SourceRange Range(getNameInfo().getSourceRange()); if (getQualifier()) Range.setBegin(getQualifierRange().getBegin()); if (hasExplicitTemplateArgs()) Range.setEnd(getRAngleLoc()); return Range; @@ -1657,10 +1638,7 @@ public: /// declaration can be found. class DependentScopeDeclRefExpr : public Expr { /// The name of the entity we will be referencing. - DeclarationName Name; - - /// Location of the name of the declaration we're referencing. - SourceLocation Loc; + DeclarationNameInfo NameInfo; /// QualifierRange - The source range that covers the /// nested-name-specifier. @@ -1676,12 +1654,10 @@ class DependentScopeDeclRefExpr : public Expr { DependentScopeDeclRefExpr(QualType T, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - DeclarationName Name, - SourceLocation NameLoc, + const DeclarationNameInfo &NameInfo, bool HasExplicitTemplateArgs) : Expr(DependentScopeDeclRefExprClass, T, true, true), - Name(Name), Loc(NameLoc), - QualifierRange(QualifierRange), Qualifier(Qualifier), + NameInfo(NameInfo), QualifierRange(QualifierRange), Qualifier(Qualifier), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {} @@ -1689,20 +1665,23 @@ public: static DependentScopeDeclRefExpr *Create(ASTContext &C, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - DeclarationName Name, - SourceLocation NameLoc, + const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs = 0); static DependentScopeDeclRefExpr *CreateEmpty(ASTContext &C, unsigned NumTemplateArgs); /// \brief Retrieve the name that this expression refers to. - DeclarationName getDeclName() const { return Name; } - void setDeclName(DeclarationName N) { Name = N; } + const DeclarationNameInfo &getNameInfo() const { return NameInfo; } + void setNameInfo(const DeclarationNameInfo &N) { NameInfo = N; } + + /// \brief Retrieve the name that this expression refers to. + DeclarationName getDeclName() const { return NameInfo.getName(); } + void setDeclName(DeclarationName N) { NameInfo.setName(N); } /// \brief Retrieve the location of the name within the expression. - SourceLocation getLocation() const { return Loc; } - void setLocation(SourceLocation L) { Loc = L; } + SourceLocation getLocation() const { return NameInfo.getLoc(); } + void setLocation(SourceLocation L) { NameInfo.setLoc(L); } /// \brief Retrieve the source range of the nested-name-specifier. SourceRange getQualifierRange() const { return QualifierRange; } @@ -1731,6 +1710,14 @@ public: return *reinterpret_cast(this + 1); } + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); + } + /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { @@ -1777,10 +1764,6 @@ class CXXExprWithTemporaries : public Expr { CXXExprWithTemporaries(ASTContext &C, Expr *SubExpr, CXXTemporary **Temps, unsigned NumTemps); - ~CXXExprWithTemporaries(); - -protected: - virtual void DoDestroy(ASTContext &C); public: CXXExprWithTemporaries(EmptyShell Empty) @@ -1991,10 +1974,7 @@ class CXXDependentScopeMemberExpr : public Expr { /// \brief The member to which this member expression refers, which /// can be name, overloaded operator, or destructor. /// FIXME: could also be a template-id - DeclarationName Member; - - /// \brief The location of the member name. - SourceLocation MemberLoc; + DeclarationNameInfo MemberNameInfo; CXXDependentScopeMemberExpr(ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow, @@ -2002,8 +1982,7 @@ class CXXDependentScopeMemberExpr : public Expr { NestedNameSpecifier *Qualifier, SourceRange QualifierRange, NamedDecl *FirstQualifierFoundInScope, - DeclarationName Member, - SourceLocation MemberLoc, + DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs); public: @@ -2014,14 +1993,13 @@ public: NestedNameSpecifier *Qualifier, SourceRange QualifierRange, NamedDecl *FirstQualifierFoundInScope, - DeclarationName Member, - SourceLocation MemberLoc) + DeclarationNameInfo MemberNameInfo) : Expr(CXXDependentScopeMemberExprClass, C.DependentTy, true, true), Base(Base), BaseType(BaseType), IsArrow(IsArrow), HasExplicitTemplateArgs(false), OperatorLoc(OperatorLoc), Qualifier(Qualifier), QualifierRange(QualifierRange), FirstQualifierFoundInScope(FirstQualifierFoundInScope), - Member(Member), MemberLoc(MemberLoc) { } + MemberNameInfo(MemberNameInfo) { } static CXXDependentScopeMemberExpr * Create(ASTContext &C, @@ -2030,8 +2008,7 @@ public: NestedNameSpecifier *Qualifier, SourceRange QualifierRange, NamedDecl *FirstQualifierFoundInScope, - DeclarationName Member, - SourceLocation MemberLoc, + DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs); static CXXDependentScopeMemberExpr * @@ -2092,13 +2069,20 @@ public: /// \brief Retrieve the name of the member that this expression /// refers to. - DeclarationName getMember() const { return Member; } - void setMember(DeclarationName N) { Member = N; } + const DeclarationNameInfo &getMemberNameInfo() const { + return MemberNameInfo; + } + void setMemberNameInfo(const DeclarationNameInfo &N) { MemberNameInfo = N; } + + /// \brief Retrieve the name of the member that this expression + /// refers to. + DeclarationName getMember() const { return MemberNameInfo.getName(); } + void setMember(DeclarationName N) { MemberNameInfo.setName(N); } // \brief Retrieve the location of the name of the member that this // expression refers to. - SourceLocation getMemberLoc() const { return MemberLoc; } - void setMemberLoc(SourceLocation L) { MemberLoc = L; } + SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); } + void setMemberLoc(SourceLocation L) { MemberNameInfo.setLoc(L); } /// \brief Determines whether this member expression actually had a C++ /// template argument list explicitly specified, e.g., x.f. @@ -2108,57 +2092,59 @@ public: /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. - ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() { + ExplicitTemplateArgumentList &getExplicitTemplateArgs() { assert(HasExplicitTemplateArgs); - return reinterpret_cast(this + 1); + return *reinterpret_cast(this + 1); } /// \brief Retrieve the explicit template argument list that followed the /// member template name, if any. - const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const { + const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const { return const_cast(this) - ->getExplicitTemplateArgumentList(); + ->getExplicitTemplateArgs(); + } + + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); } /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { - assert(HasExplicitTemplateArgs); - getExplicitTemplateArgumentList()->copyInto(List); + getExplicitTemplateArgs().copyInto(List); } /// \brief Initializes the template arguments using the given structure. void initializeTemplateArgumentsFrom(const TemplateArgumentListInfo &List) { - assert(HasExplicitTemplateArgs); - getExplicitTemplateArgumentList()->initializeFrom(List); + getExplicitTemplateArgs().initializeFrom(List); } /// \brief Retrieve the location of the left angle bracket following the /// member name ('<'), if any. SourceLocation getLAngleLoc() const { - assert(HasExplicitTemplateArgs); - return getExplicitTemplateArgumentList()->LAngleLoc; + return getExplicitTemplateArgs().LAngleLoc; } /// \brief Retrieve the template arguments provided as part of this /// template-id. const TemplateArgumentLoc *getTemplateArgs() const { - assert(HasExplicitTemplateArgs); - return getExplicitTemplateArgumentList()->getTemplateArgs(); + return getExplicitTemplateArgs().getTemplateArgs(); } /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { - assert(HasExplicitTemplateArgs); - return getExplicitTemplateArgumentList()->NumTemplateArgs; + return getExplicitTemplateArgs().NumTemplateArgs; } /// \brief Retrieve the location of the right angle bracket following the /// template arguments ('>'). SourceLocation getRAngleLoc() const { - assert(HasExplicitTemplateArgs); - return getExplicitTemplateArgumentList()->RAngleLoc; + return getExplicitTemplateArgs().RAngleLoc; } virtual SourceRange getSourceRange() const { @@ -2168,12 +2154,12 @@ public: else if (getQualifier()) Range.setBegin(getQualifierRange().getBegin()); else - Range.setBegin(MemberLoc); + Range.setBegin(MemberNameInfo.getBeginLoc()); if (hasExplicitTemplateArgs()) Range.setEnd(getRAngleLoc()); else - Range.setEnd(MemberLoc); + Range.setEnd(MemberNameInfo.getEndLoc()); return Range; } @@ -2226,8 +2212,7 @@ class UnresolvedMemberExpr : public OverloadExpr { SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - DeclarationName Member, - SourceLocation MemberLoc, + const DeclarationNameInfo &MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End); @@ -2242,8 +2227,7 @@ public: SourceLocation OperatorLoc, NestedNameSpecifier *Qualifier, SourceRange QualifierRange, - DeclarationName Member, - SourceLocation MemberLoc, + const DeclarationNameInfo &MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End); @@ -2287,6 +2271,11 @@ public: /// \brief Retrieves the naming class of this lookup. CXXRecordDecl *getNamingClass() const; + /// \brief Retrieve the full name info for the member that this expression + /// refers to. + const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); } + void setMemberNameInfo(const DeclarationNameInfo &N) { setNameInfo(N); } + /// \brief Retrieve the name of the member that this expression /// refers to. DeclarationName getMemberName() const { return getName(); } @@ -2311,6 +2300,14 @@ public: return *reinterpret_cast(this + 1); } + /// \brief Retrieves the optional explicit template arguments. + /// This points to the same data as getExplicitTemplateArgs(), but + /// returns null if there are no explicit template arguments. + const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() { + if (!hasExplicitTemplateArgs()) return 0; + return &getExplicitTemplateArgs(); + } + /// \brief Copies the template arguments into the given structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { getExplicitTemplateArgs().copyInto(List); @@ -2341,18 +2338,14 @@ public: } virtual SourceRange getSourceRange() const { - SourceRange Range; + SourceRange Range = getMemberNameInfo().getSourceRange(); if (!isImplicitAccess()) Range.setBegin(Base->getSourceRange().getBegin()); else if (getQualifier()) Range.setBegin(getQualifierRange().getBegin()); - else - Range.setBegin(getMemberLoc()); if (hasExplicitTemplateArgs()) Range.setEnd(getRAngleLoc()); - else - Range.setEnd(getMemberLoc()); return Range; } diff --git a/include/clang/AST/ExternalASTSource.h b/include/clang/AST/ExternalASTSource.h index def9ced94c2..a8ef0053a44 100644 --- a/include/clang/AST/ExternalASTSource.h +++ b/include/clang/AST/ExternalASTSource.h @@ -14,31 +14,25 @@ #ifndef LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H #define LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H -#include "clang/AST/DeclarationName.h" -#include "clang/AST/Type.h" -#include "llvm/ADT/SmallVector.h" #include #include + +namespace llvm { +template class SmallVectorImpl; +} + namespace clang { class ASTConsumer; class Decl; class DeclContext; +class DeclContextLookupResult; +class DeclarationName; class ExternalSemaSource; // layering violation required for downcasting +class NamedDecl; +class Selector; class Stmt; -/// \brief The deserialized representation of a set of declarations -/// with the same name that are visible in a given context. -struct VisibleDeclaration { - /// \brief The name of the declarations. - DeclarationName Name; - - /// \brief The ID numbers of all of the declarations with this name. - /// - /// These declarations have not necessarily been de-serialized. - llvm::SmallVector Declarations; -}; - /// \brief Abstract interface for external sources of AST nodes. /// /// External AST sources provide AST nodes constructed from some @@ -58,6 +52,20 @@ public: virtual ~ExternalASTSource(); + /// \brief RAII class for safely pairing a StartedDeserializing call + /// with FinishedDeserializing. + class Deserializing { + ExternalASTSource *Source; + public: + explicit Deserializing(ExternalASTSource *source) : Source(source) { + assert(Source); + Source->StartedDeserializing(); + } + ~Deserializing() { + Source->FinishedDeserializing(); + } + }; + /// \brief Resolve a declaration ID into a declaration, potentially /// building a new declaration. /// @@ -89,10 +97,18 @@ public: /// Generally the final step of this method is either to call /// SetExternalVisibleDeclsForName or to recursively call lookup on /// the DeclContext after calling SetExternalVisibleDecls. - virtual DeclContext::lookup_result + virtual DeclContextLookupResult FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) = 0; + /// \brief Deserialize all the visible declarations from external storage. + /// + /// Name lookup deserializes visible declarations lazily, thus a DeclContext + /// may not have a complete name lookup table. This function deserializes + /// the rest of visible declarations from the external storage and completes + /// the name lookup table of the DeclContext. + virtual void MaterializeVisibleDecls(const DeclContext *DC) = 0; + /// \brief Finds all declarations lexically contained within the given /// DeclContext. /// @@ -100,6 +116,19 @@ public: virtual bool FindExternalLexicalDecls(const DeclContext *DC, llvm::SmallVectorImpl &Result) = 0; + /// \brief Notify ExternalASTSource that we started deserialization of + /// a decl or type so until FinishedDeserializing is called there may be + /// decls that are initializing. Must be paired with FinishedDeserializing. + /// + /// The default implementation of this method is a no-op. + virtual void StartedDeserializing() { } + + /// \brief Notify ExternalASTSource that we finished the deserialization of + /// a decl or type. Must be paired with StartedDeserializing. + /// + /// The default implementation of this method is a no-op. + virtual void FinishedDeserializing() { } + /// \brief Function that will be invoked when we begin parsing a new /// translation unit involving this external AST source. /// @@ -113,30 +142,18 @@ public: virtual void PrintStats(); protected: - /// \brief Initialize the context's lookup map with the given decls. - /// It is assumed that none of the declarations are redeclarations of - /// each other. - static void SetExternalVisibleDecls(const DeclContext *DC, - const llvm::SmallVectorImpl &Decls); - - /// \brief Initialize the context's lookup map with the given decls. - /// It is assumed that none of the declarations are redeclarations of - /// each other. - static void SetExternalVisibleDecls(const DeclContext *DC, - const llvm::SmallVectorImpl &Decls); - - static DeclContext::lookup_result - SetExternalVisibleDeclsForName(const DeclContext *DC, - const VisibleDeclaration &VD); - - static DeclContext::lookup_result + static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, llvm::SmallVectorImpl &Decls); - static DeclContext::lookup_result + static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name); + + void MaterializeVisibleDeclsForName(const DeclContext *DC, + DeclarationName Name, + llvm::SmallVectorImpl &Decls); }; /// \brief A lazy pointer to an AST node (of base type T) that resides @@ -145,7 +162,7 @@ protected: /// The AST node is identified within the external AST source by a /// 63-bit offset, and can be retrieved via an operation on the /// external AST source itself. -template +template struct LazyOffsetPtr { /// \brief Either a pointer to an AST node or the offset within the /// external AST source where the AST node can be found. @@ -203,9 +220,13 @@ public: }; /// \brief A lazy pointer to a statement. -typedef LazyOffsetPtr +typedef LazyOffsetPtr LazyDeclStmtPtr; +/// \brief A lazy pointer to a declaration. +typedef LazyOffsetPtr + LazyDeclPtr; + } // end namespace clang #endif // LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H diff --git a/include/clang/AST/FullExpr.h b/include/clang/AST/FullExpr.h index bb81bf0fe7c..6ceefed8a63 100644 --- a/include/clang/AST/FullExpr.h +++ b/include/clang/AST/FullExpr.h @@ -47,7 +47,6 @@ class FullExpr { public: static FullExpr Create(ASTContext &Context, Expr *SubExpr, CXXTemporary **Temps, unsigned NumTemps); - void Destroy(ASTContext &Context); Expr *getExpr() { if (Expr *E = SubExpr.dyn_cast()) diff --git a/include/clang/AST/Makefile b/include/clang/AST/Makefile index 00a1e1bf797..6ba6e897d18 100644 --- a/include/clang/AST/Makefile +++ b/include/clang/AST/Makefile @@ -1,6 +1,6 @@ CLANG_LEVEL := ../../.. TD_SRC_DIR = $(PROJ_SRC_DIR)/../Basic -BUILT_SOURCES = Attrs.inc StmtNodes.inc DeclNodes.inc +BUILT_SOURCES = Attrs.inc AttrImpl.inc StmtNodes.inc DeclNodes.inc TABLEGEN_INC_FILES_COMMON = 1 @@ -12,6 +12,12 @@ $(ObjDir)/Attrs.inc.tmp : $(TD_SRC_DIR)/Attr.td $(TBLGEN) \ $(Verb) $(TableGen) -gen-clang-attr-classes -o $(call SYSPATH, $@) \ -I $(PROJ_SRC_DIR)/../../ $< +$(ObjDir)/AttrImpl.inc.tmp : $(TD_SRC_DIR)/Attr.td $(TBLGEN) \ + $(ObjDir)/.dir + $(Echo) "Building Clang attribute implementations with tblgen" + $(Verb) $(TableGen) -gen-clang-attr-impl -o $(call SYSPATH, $@) \ + -I $(PROJ_SRC_DIR)/../../ $< + $(ObjDir)/StmtNodes.inc.tmp : $(TD_SRC_DIR)/StmtNodes.td $(TBLGEN) \ $(ObjDir)/.dir $(Echo) "Building Clang statement node tables with tblgen" diff --git a/include/clang/AST/NestedNameSpecifier.h b/include/clang/AST/NestedNameSpecifier.h index 1594b090fea..3b25f3bb403 100644 --- a/include/clang/AST/NestedNameSpecifier.h +++ b/include/clang/AST/NestedNameSpecifier.h @@ -181,8 +181,6 @@ public: ID.AddPointer(Specifier); } - void Destroy(ASTContext &Context); - /// \brief Dump the nested name specifier to standard output to aid /// in debugging. void dump(const LangOptions &LO); diff --git a/include/clang/AST/OperationKinds.h b/include/clang/AST/OperationKinds.h new file mode 100644 index 00000000000..80453119297 --- /dev/null +++ b/include/clang/AST/OperationKinds.h @@ -0,0 +1,158 @@ +//===- OperationKinds.h - Operation enums -----------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file enumerates the different kinds of operations that can be +// performed by various expressions. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_AST_OPERATION_KINDS_H +#define LLVM_CLANG_AST_OPERATION_KINDS_H + +namespace clang { + +/// CastKind - the kind of cast this represents. +enum CastKind { + /// CK_Unknown - Unknown cast kind. + /// FIXME: The goal is to get rid of this and make all casts have a + /// kind so that the AST client doesn't have to try to figure out what's + /// going on. + CK_Unknown, + + /// CK_BitCast - Used for reinterpret_cast. + CK_BitCast, + + /// CK_LValueBitCast - Used for reinterpret_cast of expressions to + /// a reference type. + CK_LValueBitCast, + + /// CK_NoOp - Used for const_cast. + CK_NoOp, + + /// CK_BaseToDerived - Base to derived class casts. + CK_BaseToDerived, + + /// CK_DerivedToBase - Derived to base class casts. + CK_DerivedToBase, + + /// CK_UncheckedDerivedToBase - Derived to base class casts that + /// assume that the derived pointer is not null. + CK_UncheckedDerivedToBase, + + /// CK_Dynamic - Dynamic cast. + CK_Dynamic, + + /// CK_ToUnion - Cast to union (GCC extension). + CK_ToUnion, + + /// CK_ArrayToPointerDecay - Array to pointer decay. + CK_ArrayToPointerDecay, + + // CK_FunctionToPointerDecay - Function to pointer decay. + CK_FunctionToPointerDecay, + + /// CK_NullToMemberPointer - Null pointer to member pointer. + CK_NullToMemberPointer, + + /// CK_BaseToDerivedMemberPointer - Member pointer in base class to + /// member pointer in derived class. + CK_BaseToDerivedMemberPointer, + + /// CK_DerivedToBaseMemberPointer - Member pointer in derived class to + /// member pointer in base class. + CK_DerivedToBaseMemberPointer, + + /// CK_UserDefinedConversion - Conversion using a user defined type + /// conversion function. + CK_UserDefinedConversion, + + /// CK_ConstructorConversion - Conversion by constructor + CK_ConstructorConversion, + + /// CK_IntegralToPointer - Integral to pointer + CK_IntegralToPointer, + + /// CK_PointerToIntegral - Pointer to integral + CK_PointerToIntegral, + + /// CK_ToVoid - Cast to void. + CK_ToVoid, + + /// CK_VectorSplat - Casting from an integer/floating type to an extended + /// vector type with the same element type as the src type. Splats the + /// src expression into the destination expression. + CK_VectorSplat, + + /// CK_IntegralCast - Casting between integral types of different size. + CK_IntegralCast, + + /// CK_IntegralToFloating - Integral to floating point. + CK_IntegralToFloating, + + /// CK_FloatingToIntegral - Floating point to integral. + CK_FloatingToIntegral, + + /// CK_FloatingCast - Casting between floating types of different size. + CK_FloatingCast, + + /// CK_MemberPointerToBoolean - Member pointer to boolean + CK_MemberPointerToBoolean, + + /// CK_AnyPointerToObjCPointerCast - Casting any pointer to objective-c + /// pointer + CK_AnyPointerToObjCPointerCast, + + /// CK_AnyPointerToBlockPointerCast - Casting any pointer to block + /// pointer + CK_AnyPointerToBlockPointerCast, + + /// \brief Converting between two Objective-C object types, which + /// can occur when performing reference binding to an Objective-C + /// object. + CK_ObjCObjectLValueCast +}; + + +enum BinaryOperatorKind { + // Operators listed in order of precedence. + // Note that additions to this should also update the StmtVisitor class. + BO_PtrMemD, BO_PtrMemI, // [C++ 5.5] Pointer-to-member operators. + BO_Mul, BO_Div, BO_Rem, // [C99 6.5.5] Multiplicative operators. + BO_Add, BO_Sub, // [C99 6.5.6] Additive operators. + BO_Shl, BO_Shr, // [C99 6.5.7] Bitwise shift operators. + BO_LT, BO_GT, BO_LE, BO_GE, // [C99 6.5.8] Relational operators. + BO_EQ, BO_NE, // [C99 6.5.9] Equality operators. + BO_And, // [C99 6.5.10] Bitwise AND operator. + BO_Xor, // [C99 6.5.11] Bitwise XOR operator. + BO_Or, // [C99 6.5.12] Bitwise OR operator. + BO_LAnd, // [C99 6.5.13] Logical AND operator. + BO_LOr, // [C99 6.5.14] Logical OR operator. + BO_Assign, BO_MulAssign, // [C99 6.5.16] Assignment operators. + BO_DivAssign, BO_RemAssign, + BO_AddAssign, BO_SubAssign, + BO_ShlAssign, BO_ShrAssign, + BO_AndAssign, BO_XorAssign, + BO_OrAssign, + BO_Comma // [C99 6.5.17] Comma operator. +}; + +enum UnaryOperatorKind { + // Note that additions to this should also update the StmtVisitor class. + UO_PostInc, UO_PostDec, // [C99 6.5.2.4] Postfix increment and decrement + UO_PreInc, UO_PreDec, // [C99 6.5.3.1] Prefix increment and decrement + UO_AddrOf, UO_Deref, // [C99 6.5.3.2] Address and indirection + UO_Plus, UO_Minus, // [C99 6.5.3.3] Unary arithmetic + UO_Not, UO_LNot, // [C99 6.5.3.3] Unary arithmetic + UO_Real, UO_Imag, // "__real expr"/"__imag expr" Extension. + UO_Extension // __extension__ marker. +}; + +} + +#endif diff --git a/include/clang/AST/RecursiveASTVisitor.h b/include/clang/AST/RecursiveASTVisitor.h index 0853dddbe9e..232e47b03ae 100644 --- a/include/clang/AST/RecursiveASTVisitor.h +++ b/include/clang/AST/RecursiveASTVisitor.h @@ -42,7 +42,7 @@ OPERATOR(Plus) OPERATOR(Minus) \ OPERATOR(Not) OPERATOR(LNot) \ OPERATOR(Real) OPERATOR(Imag) \ - OPERATOR(Extension) OPERATOR(OffsetOf) + OPERATOR(Extension) // All binary operators (excluding compound assign operators). #define BINOP_LIST() \ @@ -123,12 +123,27 @@ namespace clang { /// users may override Traverse* and WalkUpFrom* to implement custom /// traversal strategies. Returning false from one of these overridden /// functions will abort the entire traversal. +/// +/// By default, this visitor tries to visit every part of the explicit +/// source code exactly once. The default policy towards templates +/// is to descend into the 'pattern' class or function body, not any +/// explicit or implicit instantiations. Explicit specializations +/// are still visited, and the patterns of partial specializations +/// are visited separately. This behavior can be changed by +/// overriding shouldVisitTemplateInstantiations() in the derived class +/// to return true, in which case all known implicit and explicit +/// instantiations will be visited at the same time as the pattern +/// from which they were produced. template class RecursiveASTVisitor { public: /// \brief Return a reference to the derived class. Derived &getDerived() { return *static_cast(this); } + /// \brief Return whether this visitor should recurse into + /// template instantiations. + bool shouldVisitTemplateInstantiations() const { return false; } + /// \brief Recursively visit a statement or expression, by /// dispatching to Traverse*() based on the argument's dynamic type. /// @@ -351,8 +366,11 @@ public: private: // These are helper methods used by more than one Traverse* method. bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL); - bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL, + bool TraverseClassInstantiations(ClassTemplateDecl* D, Decl *Pattern); + bool TraverseFunctionInstantiations(FunctionTemplateDecl* D) ; + bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL, unsigned Count); + bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL); bool TraverseRecordHelper(RecordDecl *D); bool TraverseCXXRecordHelper(CXXRecordDecl *D); bool TraverseDeclaratorHelper(DeclaratorDecl *D); @@ -375,14 +393,14 @@ bool RecursiveASTVisitor::TraverseStmt(Stmt *S) { if (BinaryOperator *BinOp = dyn_cast(S)) { switch (BinOp->getOpcode()) { #define OPERATOR(NAME) \ - case BinaryOperator::NAME: DISPATCH(Bin##PtrMemD, BinaryOperator, S); + case BO_##NAME: DISPATCH(Bin##PtrMemD, BinaryOperator, S); BINOP_LIST() #undef OPERATOR #undef BINOP_LIST #define OPERATOR(NAME) \ - case BinaryOperator::NAME##Assign: \ + case BO_##NAME##Assign: \ DISPATCH(Bin##NAME##Assign, CompoundAssignOperator, S); CAO_LIST() @@ -392,7 +410,7 @@ bool RecursiveASTVisitor::TraverseStmt(Stmt *S) { } else if (UnaryOperator *UnOp = dyn_cast(S)) { switch (UnOp->getOpcode()) { #define OPERATOR(NAME) \ - case UnaryOperator::NAME: DISPATCH(Unary##NAME, UnaryOperator, S); + case UO_##NAME: DISPATCH(Unary##NAME, UnaryOperator, S); UNARYOP_LIST() #undef OPERATOR @@ -540,8 +558,11 @@ bool RecursiveASTVisitor::TraverseTemplateArgumentLoc( return true; case TemplateArgument::Type: { - TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo(); - return getDerived().TraverseTypeLoc(TSI->getTypeLoc()); + // FIXME: how can TSI ever be NULL? + if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo()) + return getDerived().TraverseTypeLoc(TSI->getTypeLoc()); + else + return true; } case TemplateArgument::Template: @@ -796,23 +817,31 @@ DEF_TRAVERSE_TYPELOC(MemberPointerType, { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); }) +template +bool RecursiveASTVisitor::TraverseArrayTypeLocHelper(ArrayTypeLoc TL) { + // This isn't available for ArrayType, but is for the ArrayTypeLoc. + TRY_TO(TraverseStmt(TL.getSizeExpr())); + return true; +} + DEF_TRAVERSE_TYPELOC(ConstantArrayType, { TRY_TO(TraverseTypeLoc(TL.getElementLoc())); + return TraverseArrayTypeLocHelper(TL); }) DEF_TRAVERSE_TYPELOC(IncompleteArrayType, { TRY_TO(TraverseTypeLoc(TL.getElementLoc())); + return TraverseArrayTypeLocHelper(TL); }) DEF_TRAVERSE_TYPELOC(VariableArrayType, { TRY_TO(TraverseTypeLoc(TL.getElementLoc())); - TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr())); + return TraverseArrayTypeLocHelper(TL); }) DEF_TRAVERSE_TYPELOC(DependentSizedArrayType, { TRY_TO(TraverseTypeLoc(TL.getElementLoc())); - if (TL.getTypePtr()->getSizeExpr()) - TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr())); + return TraverseArrayTypeLocHelper(TL); }) // FIXME: order? why not size expr first? @@ -1083,19 +1112,124 @@ bool RecursiveASTVisitor::TraverseTemplateParameterListHelper( return true; } +// A helper method for traversing the implicit instantiations of a +// class. +template +bool RecursiveASTVisitor::TraverseClassInstantiations( + ClassTemplateDecl* D, Decl *Pattern) { + assert(isa(Pattern) || + isa(Pattern)); + + ClassTemplateDecl::spec_iterator end = D->spec_end(); + for (ClassTemplateDecl::spec_iterator it = D->spec_begin(); it != end; ++it) { + ClassTemplateSpecializationDecl* SD = *it; + + switch (SD->getSpecializationKind()) { + // Visit the implicit instantiations with the requested pattern. + case TSK_ImplicitInstantiation: { + llvm::PointerUnion U + = SD->getInstantiatedFrom(); + + bool ShouldVisit; + if (U.is()) + ShouldVisit = (U.get() == Pattern); + else + ShouldVisit + = (U.get() == Pattern); + + if (ShouldVisit) + TRY_TO(TraverseClassTemplateSpecializationDecl(SD)); + break; + } + + // We don't need to do anything on an explicit instantiation + // or explicit specialization because there will be an explicit + // node for it elsewhere. + case TSK_ExplicitInstantiationDeclaration: + case TSK_ExplicitInstantiationDefinition: + case TSK_ExplicitSpecialization: + break; + + // We don't need to do anything for an uninstantiated + // specialization. + case TSK_Undeclared: + break; + } + } + + return true; +} + DEF_TRAVERSE_DECL(ClassTemplateDecl, { - TRY_TO(TraverseDecl(D->getTemplatedDecl())); + CXXRecordDecl* TempDecl = D->getTemplatedDecl(); + TRY_TO(TraverseDecl(TempDecl)); TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); - // We should not traverse the specializations/partial - // specializations. Those will show up in other contexts. - // getInstantiatedFromMemberTemplate() is just a link from a - // template instantiation back to the template from which it was - // instantiated, and thus should not be traversed either. + + // By default, we do not traverse the instantiations of + // class templates since they do not apprear in the user code. The + // following code optionally traverses them. + if (getDerived().shouldVisitTemplateInstantiations()) { + // If this is the definition of the primary template, visit + // instantiations which were formed from this pattern. + if (D->isThisDeclarationADefinition()) + TRY_TO(TraverseClassInstantiations(D, D)); + } + + // Note that getInstantiatedFromMemberTemplate() is just a link + // from a template instantiation back to the template from which + // it was instantiated, and thus should not be traversed. }) +// A helper method for traversing the instantiations of a +// function while skipping its specializations. +template +bool RecursiveASTVisitor::TraverseFunctionInstantiations( + FunctionTemplateDecl* D) { + FunctionTemplateDecl::spec_iterator end = D->spec_end(); + for (FunctionTemplateDecl::spec_iterator it = D->spec_begin(); it != end; ++it) { + FunctionDecl* FD = *it; + switch (FD->getTemplateSpecializationKind()) { + case TSK_ImplicitInstantiation: + // We don't know what kind of FunctionDecl this is. + TRY_TO(TraverseDecl(FD)); + break; + + // No need to visit explicit instantiations, we'll find the node + // eventually. + case TSK_ExplicitInstantiationDeclaration: + case TSK_ExplicitInstantiationDefinition: + break; + + case TSK_Undeclared: // Declaration of the template definition. + case TSK_ExplicitSpecialization: + break; + default: + assert(false && "Unknown specialization kind."); + } + } + + return true; +} + DEF_TRAVERSE_DECL(FunctionTemplateDecl, { TRY_TO(TraverseDecl(D->getTemplatedDecl())); TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); + + // By default, we do not traverse the instantiations of + // function templates since they do not apprear in the user code. The + // following code optionally traverses them. + if (getDerived().shouldVisitTemplateInstantiations()) { + // Explicit function specializations will be traversed from the + // context of their declaration. There is therefore no need to + // traverse them for here. + // + // In addition, we only traverse the function instantiations when + // the function template is a function template definition. + if (D->isThisDeclarationADefinition()) { + TRY_TO(TraverseFunctionInstantiations(D)); + } + } }) DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, { @@ -1110,10 +1244,10 @@ DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, { DEF_TRAVERSE_DECL(TemplateTypeParmDecl, { // D is the "T" in something like "template class vector;" - if (D->hasDefaultArgument()) - TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc())); if (D->getTypeForDecl()) TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0))); + if (D->hasDefaultArgument()) + TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc())); }) DEF_TRAVERSE_DECL(TypedefDecl, { @@ -1166,7 +1300,7 @@ bool RecursiveASTVisitor::TraverseCXXRecordHelper( for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), E = D->bases_end(); I != E; ++I) { - TRY_TO(TraverseType(I->getType())); + TRY_TO(TraverseTypeLoc(I->getTypeSourceInfo()->getTypeLoc())); } // We don't traverse the friends or the conversions, as they are // already in decls_begin()/decls_end(). @@ -1191,10 +1325,16 @@ DEF_TRAVERSE_DECL(ClassTemplateSpecializationDecl, { // ("template set;"), we do need a callback, since this // is the only callback that's made for this instantiation. // We use getTypeAsWritten() to distinguish. - // FIXME: see how we want to handle template specializations. if (TypeSourceInfo *TSI = D->getTypeAsWritten()) TRY_TO(TraverseTypeLoc(TSI->getTypeLoc())); - return true; + + if (!getDerived().shouldVisitTemplateInstantiations() && + D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) + // Returning from here skips traversing the + // declaration context of the ClassTemplateSpecializationDecl + // (embedded in the DEF_TRAVERSE_DECL() macro) + // which contains the instantiated members of the class. + return true; }) template @@ -1222,6 +1362,12 @@ DEF_TRAVERSE_DECL(ClassTemplatePartialSpecializationDecl, { // though that's our parent class -- we already visit all the // template args here. TRY_TO(TraverseCXXRecordHelper(D)); + + // If we're visiting instantiations, visit the instantiations of + // this template now. + if (getDerived().shouldVisitTemplateInstantiations() && + D->isThisDeclarationADefinition()) + TRY_TO(TraverseClassInstantiations(D->getSpecializedTemplate(), D)); }) DEF_TRAVERSE_DECL(EnumConstantDecl, { @@ -1304,7 +1450,45 @@ bool RecursiveASTVisitor::TraverseFunctionHelper(FunctionDecl *D) { } TRY_TO(TraverseType(D->getResultType())); - TRY_TO(TraverseDeclContextHelper(D)); // Parameters. + + // If we're an explicit template specialization, iterate over the + // template args that were explicitly specified. + if (const FunctionTemplateSpecializationInfo *FTSI = + D->getTemplateSpecializationInfo()) { + if (FTSI->getTemplateSpecializationKind() != TSK_Undeclared && + FTSI->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { + // A specialization might not have explicit template arguments if it has + // a templated return type and concrete arguments. + if (const TemplateArgumentListInfo *TALI = + FTSI->TemplateArgumentsAsWritten) { + TRY_TO(TraverseTemplateArgumentLocsHelper(TALI->getArgumentArray(), + TALI->size())); + } + } + } + + for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end(); + I != E; ++I) { + TRY_TO(TraverseDecl(*I)); + } + + if (FunctionProtoType *FuncProto = dyn_cast(FuncType)) { + if (D->isThisDeclarationADefinition()) { + // This would be visited if we called TraverseType(D->getType()) + // above, but we don't (at least, not in the + // declaration-is-a-definition case), in order to avoid duplicate + // visiting for parameters. (We need to check parameters here, + // rather than letting D->getType() do it, so we visit default + // parameter values). So we need to re-do some of the work the + // type would do. + for (FunctionProtoType::exception_iterator + E = FuncProto->exception_begin(), + EEnd = FuncProto->exception_end(); + E != EEnd; ++E) { + TRY_TO(TraverseType(*E)); + } + } + } if (CXXConstructorDecl *Ctor = dyn_cast(D)) { // Constructor initializers. @@ -1356,9 +1540,6 @@ DEF_TRAVERSE_DECL(CXXDestructorDecl, { template bool RecursiveASTVisitor::TraverseVarHelper(VarDecl *D) { TRY_TO(TraverseDeclaratorHelper(D)); - // FIXME: This often double-counts -- for instance, for all local - // vars, though not for global vars -- because the initializer is - // also captured when the var-decl is in a DeclStmt. TRY_TO(TraverseStmt(D->getInit())); return true; } @@ -1373,11 +1554,13 @@ DEF_TRAVERSE_DECL(ImplicitParamDecl, { DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, { // A non-type template parameter, e.g. "S" in template class Foo ... - TRY_TO(TraverseStmt(D->getDefaultArgument())); TRY_TO(TraverseVarHelper(D)); + TRY_TO(TraverseStmt(D->getDefaultArgument())); }) DEF_TRAVERSE_DECL(ParmVarDecl, { + TRY_TO(TraverseVarHelper(D)); + if (D->hasDefaultArg() && D->hasUninstantiatedDefaultArg() && !D->hasUnparsedDefaultArg()) @@ -1387,8 +1570,6 @@ DEF_TRAVERSE_DECL(ParmVarDecl, { !D->hasUninstantiatedDefaultArg() && !D->hasUnparsedDefaultArg()) TRY_TO(TraverseStmt(D->getDefaultArg())); - - TRY_TO(TraverseVarHelper(D)); }) #undef DEF_TRAVERSE_DECL @@ -1431,35 +1612,36 @@ DEF_TRAVERSE_STMT(AsmStmt, { }) DEF_TRAVERSE_STMT(CXXCatchStmt, { - // We don't traverse S->getCaughtType(), as we are already - // traversing the exception object, which has this type. + TRY_TO(TraverseDecl(S->getExceptionDecl())); // child_begin()/end() iterates over the handler block. }) -DEF_TRAVERSE_STMT(ForStmt, { - TRY_TO(TraverseDecl(S->getConditionVariable())); - // child_begin()/end() iterates over init, cond, inc, and body stmts. +DEF_TRAVERSE_STMT(DeclStmt, { + for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end(); + I != E; ++I) { + TRY_TO(TraverseDecl(*I)); + } + // Suppress the default iteration over child_begin/end by + // returning. Here's why: A DeclStmt looks like 'type var [= + // initializer]'. The decls above already traverse over the + // initializers, so we don't have to do it again (which + // child_begin/end would do). + return true; }) -DEF_TRAVERSE_STMT(IfStmt, { - TRY_TO(TraverseDecl(S->getConditionVariable())); - // child_begin()/end() iterates over cond, then, and else stmts. - }) - -DEF_TRAVERSE_STMT(WhileStmt, { - TRY_TO(TraverseDecl(S->getConditionVariable())); - // child_begin()/end() iterates over cond, then, and else stmts. - }) // These non-expr stmts (most of them), do not need any action except // iterating over the children. DEF_TRAVERSE_STMT(BreakStmt, { }) +DEF_TRAVERSE_STMT(CXXTryStmt, { }) +DEF_TRAVERSE_STMT(CaseStmt, { }) DEF_TRAVERSE_STMT(CompoundStmt, { }) DEF_TRAVERSE_STMT(ContinueStmt, { }) -DEF_TRAVERSE_STMT(CXXTryStmt, { }) -DEF_TRAVERSE_STMT(DeclStmt, { }) +DEF_TRAVERSE_STMT(DefaultStmt, { }) DEF_TRAVERSE_STMT(DoStmt, { }) +DEF_TRAVERSE_STMT(ForStmt, { }) DEF_TRAVERSE_STMT(GotoStmt, { }) +DEF_TRAVERSE_STMT(IfStmt, { }) DEF_TRAVERSE_STMT(IndirectGotoStmt, { }) DEF_TRAVERSE_STMT(LabelStmt, { }) DEF_TRAVERSE_STMT(NullStmt, { }) @@ -1470,10 +1652,10 @@ DEF_TRAVERSE_STMT(ObjCAtThrowStmt, { }) DEF_TRAVERSE_STMT(ObjCAtTryStmt, { }) DEF_TRAVERSE_STMT(ObjCForCollectionStmt, { }) DEF_TRAVERSE_STMT(ReturnStmt, { }) -DEF_TRAVERSE_STMT(SwitchStmt, { }) DEF_TRAVERSE_STMT(SwitchCase, { }) -DEF_TRAVERSE_STMT(CaseStmt, { }) -DEF_TRAVERSE_STMT(DefaultStmt, { }) +DEF_TRAVERSE_STMT(SwitchStmt, { }) +DEF_TRAVERSE_STMT(WhileStmt, { }) + DEF_TRAVERSE_STMT(CXXDependentScopeMemberExpr, { if (S->hasExplicitTemplateArgs()) { @@ -1565,6 +1747,37 @@ DEF_TRAVERSE_STMT(CXXNewExpr, { TRY_TO(TraverseType(S->getAllocatedType())); }) +DEF_TRAVERSE_STMT(OffsetOfExpr, { + // The child-iterator will pick up the expression representing + // the field. + // FIMXE: for code like offsetof(Foo, a.b.c), should we get + // making a MemberExpr callbacks for Foo.a, Foo.a.b, and Foo.a.b.c? + TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc())); + }) + +DEF_TRAVERSE_STMT(SizeOfAlignOfExpr, { + // The child-iterator will pick up the arg if it's an expression, + // but not if it's a type. + if (S->isArgumentType()) + TRY_TO(TraverseTypeLoc(S->getArgumentTypeInfo()->getTypeLoc())); + }) + +DEF_TRAVERSE_STMT(CXXTypeidExpr, { + // The child-iterator will pick up the arg if it's an expression, + // but not if it's a type. + if (S->isTypeOperand()) + TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc())); + }) + +DEF_TRAVERSE_STMT(TypesCompatibleExpr, { + TRY_TO(TraverseTypeLoc(S->getArgTInfo1()->getTypeLoc())); + TRY_TO(TraverseTypeLoc(S->getArgTInfo2()->getTypeLoc())); + }) + +DEF_TRAVERSE_STMT(UnaryTypeTraitExpr, { + TRY_TO(TraverseType(S->getQueriedType())); + }) + // These exprs (most of them), do not need any action except iterating // over the children. DEF_TRAVERSE_STMT(AddrLabelExpr, { }) @@ -1573,7 +1786,6 @@ DEF_TRAVERSE_STMT(BlockDeclRefExpr, { }) DEF_TRAVERSE_STMT(BlockExpr, { }) DEF_TRAVERSE_STMT(ChooseExpr, { }) DEF_TRAVERSE_STMT(CompoundLiteralExpr, { }) -DEF_TRAVERSE_STMT(CXXBindReferenceExpr, { }) DEF_TRAVERSE_STMT(CXXBindTemporaryExpr, { }) DEF_TRAVERSE_STMT(CXXBoolLiteralExpr, { }) DEF_TRAVERSE_STMT(CXXDefaultArgExpr, { }) @@ -1583,7 +1795,6 @@ DEF_TRAVERSE_STMT(CXXNullPtrLiteralExpr, { }) DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, { }) DEF_TRAVERSE_STMT(CXXThisExpr, { }) DEF_TRAVERSE_STMT(CXXThrowExpr, { }) -DEF_TRAVERSE_STMT(CXXTypeidExpr, { }) DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, { }) DEF_TRAVERSE_STMT(DesignatedInitExpr, { }) DEF_TRAVERSE_STMT(ExtVectorElementExpr, { }) @@ -1598,18 +1809,17 @@ DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, { }) DEF_TRAVERSE_STMT(ObjCProtocolExpr, { }) DEF_TRAVERSE_STMT(ObjCSelectorExpr, { }) DEF_TRAVERSE_STMT(ObjCSuperExpr, { }) -DEF_TRAVERSE_STMT(OffsetOfExpr, { }) DEF_TRAVERSE_STMT(ParenExpr, { }) DEF_TRAVERSE_STMT(ParenListExpr, { }) DEF_TRAVERSE_STMT(PredefinedExpr, { }) DEF_TRAVERSE_STMT(ShuffleVectorExpr, { }) -DEF_TRAVERSE_STMT(SizeOfAlignOfExpr, { }) DEF_TRAVERSE_STMT(StmtExpr, { }) -DEF_TRAVERSE_STMT(TypesCompatibleExpr, { }) -DEF_TRAVERSE_STMT(UnaryTypeTraitExpr, { }) DEF_TRAVERSE_STMT(UnresolvedLookupExpr, { }) DEF_TRAVERSE_STMT(UnresolvedMemberExpr, { }) -DEF_TRAVERSE_STMT(VAArgExpr, { }) +DEF_TRAVERSE_STMT(VAArgExpr, { + // The child-iterator will pick up the expression argument. + TRY_TO(TraverseTypeLoc(S->getWrittenTypeInfo()->getTypeLoc())); + }) DEF_TRAVERSE_STMT(CXXConstructExpr, { }) DEF_TRAVERSE_STMT(CXXTemporaryObjectExpr, { diff --git a/include/clang/AST/Redeclarable.h b/include/clang/AST/Redeclarable.h index 55e1f847799..ba778293ba2 100644 --- a/include/clang/AST/Redeclarable.h +++ b/include/clang/AST/Redeclarable.h @@ -177,6 +177,9 @@ public: static_cast(this))); } redecl_iterator redecls_end() const { return redecl_iterator(); } + + friend class ASTDeclReader; + friend class ASTDeclWriter; }; } diff --git a/include/clang/AST/Stmt.h b/include/clang/AST/Stmt.h index a0c95b1fce8..62a6b6463df 100644 --- a/include/clang/AST/Stmt.h +++ b/include/clang/AST/Stmt.h @@ -151,22 +151,11 @@ public: struct EmptyShell { }; protected: - /// DestroyChildren - Invoked by destructors of subclasses of Stmt to - /// recursively release child AST nodes. - void DestroyChildren(ASTContext& Ctx); - /// \brief Construct an empty statement. explicit Stmt(StmtClass SC, EmptyShell) : sClass(SC), RefCount(1) { if (Stmt::CollectingStats()) Stmt::addStmtClass(SC); } - /// \brief Virtual method that performs the actual destruction of - /// this statement. - /// - /// Subclasses should override this method (not Destroy()) to - /// provide class-specific destruction. - virtual void DoDestroy(ASTContext &Ctx); - public: Stmt(StmtClass SC) : sClass(SC), RefCount(1) { if (Stmt::CollectingStats()) Stmt::addStmtClass(SC); @@ -181,13 +170,6 @@ public: } #endif - /// \brief Destroy the current statement and its children. - void Destroy(ASTContext &Ctx) { - assert(RefCount >= 1); - if (--RefCount == 0) - DoDestroy(Ctx); - } - /// \brief Increases the reference count for this statement. /// /// Invoke the Retain() operation when this statement or expression @@ -221,6 +203,7 @@ public: /// This is useful in a debugger. void dump() const; void dump(SourceManager &SM) const; + void dump(llvm::raw_ostream &OS, SourceManager &SM) const; /// dumpAll - This does a dump of the specified AST fragment and all subtrees. void dumpAll() const; @@ -295,9 +278,6 @@ class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; -protected: - virtual void DoDestroy(ASTContext &Ctx); - public: DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), @@ -671,9 +651,6 @@ public: // over the initialization expression referenced by the condition variable. virtual child_iterator child_begin(); virtual child_iterator child_end(); - -protected: - virtual void DoDestroy(ASTContext &Ctx); }; /// SwitchStmt - This represents a 'switch' stmt. @@ -685,9 +662,6 @@ class SwitchStmt : public Stmt { SwitchCase *FirstCase; SourceLocation SwitchLoc; -protected: - virtual void DoDestroy(ASTContext &Ctx); - public: SwitchStmt(ASTContext &C, VarDecl *Var, Expr *cond); @@ -794,9 +768,6 @@ public: // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); - -protected: - virtual void DoDestroy(ASTContext &Ctx); }; /// DoStmt - This represents a 'do/while' stmt. @@ -910,9 +881,6 @@ public: // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); - -protected: - virtual void DoDestroy(ASTContext &Ctx); }; /// GotoStmt - This represents a direct goto. @@ -1113,9 +1081,6 @@ class AsmStmt : public Stmt { StringLiteral **Constraints; Stmt **Exprs; StringLiteral **Clobbers; - -protected: - virtual void DoDestroy(ASTContext &Ctx); public: AsmStmt(ASTContext &C, SourceLocation asmloc, bool issimple, bool isvolatile, diff --git a/include/clang/AST/StmtCXX.h b/include/clang/AST/StmtCXX.h index 4e87c2701c2..0508f35e48e 100644 --- a/include/clang/AST/StmtCXX.h +++ b/include/clang/AST/StmtCXX.h @@ -29,14 +29,14 @@ class CXXCatchStmt : public Stmt { /// The handler block. Stmt *HandlerBlock; -protected: - virtual void DoDestroy(ASTContext& Ctx); - public: CXXCatchStmt(SourceLocation catchLoc, VarDecl *exDecl, Stmt *handlerBlock) : Stmt(CXXCatchStmtClass), CatchLoc(catchLoc), ExceptionDecl(exDecl), HandlerBlock(handlerBlock) {} + CXXCatchStmt(EmptyShell Empty) + : Stmt(CXXCatchStmtClass), ExceptionDecl(0), HandlerBlock(0) {} + virtual SourceRange getSourceRange() const { return SourceRange(CatchLoc, HandlerBlock->getLocEnd()); } @@ -53,6 +53,8 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); + + friend class ASTStmtReader; }; /// CXXTryStmt - A C++ try block, including all handlers. @@ -64,38 +66,46 @@ class CXXTryStmt : public Stmt { CXXTryStmt(SourceLocation tryLoc, Stmt *tryBlock, Stmt **handlers, unsigned numHandlers); + CXXTryStmt(EmptyShell Empty, unsigned numHandlers) + : Stmt(CXXTryStmtClass), NumHandlers(numHandlers) { } + + Stmt const * const *getStmts() const { + return reinterpret_cast(this + 1); + } + Stmt **getStmts() { + return reinterpret_cast(this + 1); + } + public: static CXXTryStmt *Create(ASTContext &C, SourceLocation tryLoc, Stmt *tryBlock, Stmt **handlers, unsigned numHandlers); + static CXXTryStmt *Create(ASTContext &C, EmptyShell Empty, + unsigned numHandlers); + virtual SourceRange getSourceRange() const { return SourceRange(getTryLoc(), getEndLoc()); } SourceLocation getTryLoc() const { return TryLoc; } SourceLocation getEndLoc() const { - Stmt const * const*Stmts = reinterpret_cast(this + 1); - return Stmts[NumHandlers]->getLocEnd(); + return getStmts()[NumHandlers]->getLocEnd(); } CompoundStmt *getTryBlock() { - Stmt **Stmts = reinterpret_cast(this + 1); - return llvm::cast(Stmts[0]); + return llvm::cast(getStmts()[0]); } const CompoundStmt *getTryBlock() const { - Stmt const * const*Stmts = reinterpret_cast(this + 1); - return llvm::cast(Stmts[0]); + return llvm::cast(getStmts()[0]); } unsigned getNumHandlers() const { return NumHandlers; } CXXCatchStmt *getHandler(unsigned i) { - Stmt **Stmts = reinterpret_cast(this + 1); - return llvm::cast(Stmts[i + 1]); + return llvm::cast(getStmts()[i + 1]); } const CXXCatchStmt *getHandler(unsigned i) const { - Stmt const * const*Stmts = reinterpret_cast(this + 1); - return llvm::cast(Stmts[i + 1]); + return llvm::cast(getStmts()[i + 1]); } static bool classof(const Stmt *T) { @@ -105,6 +115,8 @@ public: virtual child_iterator child_begin(); virtual child_iterator child_end(); + + friend class ASTStmtReader; }; diff --git a/include/clang/AST/StmtVisitor.h b/include/clang/AST/StmtVisitor.h index 8078451fa31..b8c141d7ef8 100644 --- a/include/clang/AST/StmtVisitor.h +++ b/include/clang/AST/StmtVisitor.h @@ -37,68 +37,57 @@ public: if (BinaryOperator *BinOp = dyn_cast(S)) { switch (BinOp->getOpcode()) { default: assert(0 && "Unknown binary operator!"); - case BinaryOperator::PtrMemD: DISPATCH(BinPtrMemD, BinaryOperator); - case BinaryOperator::PtrMemI: DISPATCH(BinPtrMemI, BinaryOperator); - case BinaryOperator::Mul: DISPATCH(BinMul, BinaryOperator); - case BinaryOperator::Div: DISPATCH(BinDiv, BinaryOperator); - case BinaryOperator::Rem: DISPATCH(BinRem, BinaryOperator); - case BinaryOperator::Add: DISPATCH(BinAdd, BinaryOperator); - case BinaryOperator::Sub: DISPATCH(BinSub, BinaryOperator); - case BinaryOperator::Shl: DISPATCH(BinShl, BinaryOperator); - case BinaryOperator::Shr: DISPATCH(BinShr, BinaryOperator); + case BO_PtrMemD: DISPATCH(BinPtrMemD, BinaryOperator); + case BO_PtrMemI: DISPATCH(BinPtrMemI, BinaryOperator); + case BO_Mul: DISPATCH(BinMul, BinaryOperator); + case BO_Div: DISPATCH(BinDiv, BinaryOperator); + case BO_Rem: DISPATCH(BinRem, BinaryOperator); + case BO_Add: DISPATCH(BinAdd, BinaryOperator); + case BO_Sub: DISPATCH(BinSub, BinaryOperator); + case BO_Shl: DISPATCH(BinShl, BinaryOperator); + case BO_Shr: DISPATCH(BinShr, BinaryOperator); - case BinaryOperator::LT: DISPATCH(BinLT, BinaryOperator); - case BinaryOperator::GT: DISPATCH(BinGT, BinaryOperator); - case BinaryOperator::LE: DISPATCH(BinLE, BinaryOperator); - case BinaryOperator::GE: DISPATCH(BinGE, BinaryOperator); - case BinaryOperator::EQ: DISPATCH(BinEQ, BinaryOperator); - case BinaryOperator::NE: DISPATCH(BinNE, BinaryOperator); + case BO_LT: DISPATCH(BinLT, BinaryOperator); + case BO_GT: DISPATCH(BinGT, BinaryOperator); + case BO_LE: DISPATCH(BinLE, BinaryOperator); + case BO_GE: DISPATCH(BinGE, BinaryOperator); + case BO_EQ: DISPATCH(BinEQ, BinaryOperator); + case BO_NE: DISPATCH(BinNE, BinaryOperator); - case BinaryOperator::And: DISPATCH(BinAnd, BinaryOperator); - case BinaryOperator::Xor: DISPATCH(BinXor, BinaryOperator); - case BinaryOperator::Or : DISPATCH(BinOr, BinaryOperator); - case BinaryOperator::LAnd: DISPATCH(BinLAnd, BinaryOperator); - case BinaryOperator::LOr : DISPATCH(BinLOr, BinaryOperator); - case BinaryOperator::Assign: DISPATCH(BinAssign, BinaryOperator); - case BinaryOperator::MulAssign: - DISPATCH(BinMulAssign, CompoundAssignOperator); - case BinaryOperator::DivAssign: - DISPATCH(BinDivAssign, CompoundAssignOperator); - case BinaryOperator::RemAssign: - DISPATCH(BinRemAssign, CompoundAssignOperator); - case BinaryOperator::AddAssign: - DISPATCH(BinAddAssign, CompoundAssignOperator); - case BinaryOperator::SubAssign: - DISPATCH(BinSubAssign, CompoundAssignOperator); - case BinaryOperator::ShlAssign: - DISPATCH(BinShlAssign, CompoundAssignOperator); - case BinaryOperator::ShrAssign: - DISPATCH(BinShrAssign, CompoundAssignOperator); - case BinaryOperator::AndAssign: - DISPATCH(BinAndAssign, CompoundAssignOperator); - case BinaryOperator::OrAssign: - DISPATCH(BinOrAssign, CompoundAssignOperator); - case BinaryOperator::XorAssign: - DISPATCH(BinXorAssign, CompoundAssignOperator); - case BinaryOperator::Comma: DISPATCH(BinComma, BinaryOperator); + case BO_And: DISPATCH(BinAnd, BinaryOperator); + case BO_Xor: DISPATCH(BinXor, BinaryOperator); + case BO_Or : DISPATCH(BinOr, BinaryOperator); + case BO_LAnd: DISPATCH(BinLAnd, BinaryOperator); + case BO_LOr : DISPATCH(BinLOr, BinaryOperator); + case BO_Assign: DISPATCH(BinAssign, BinaryOperator); + case BO_MulAssign: DISPATCH(BinMulAssign, CompoundAssignOperator); + case BO_DivAssign: DISPATCH(BinDivAssign, CompoundAssignOperator); + case BO_RemAssign: DISPATCH(BinRemAssign, CompoundAssignOperator); + case BO_AddAssign: DISPATCH(BinAddAssign, CompoundAssignOperator); + case BO_SubAssign: DISPATCH(BinSubAssign, CompoundAssignOperator); + case BO_ShlAssign: DISPATCH(BinShlAssign, CompoundAssignOperator); + case BO_ShrAssign: DISPATCH(BinShrAssign, CompoundAssignOperator); + case BO_AndAssign: DISPATCH(BinAndAssign, CompoundAssignOperator); + case BO_OrAssign: DISPATCH(BinOrAssign, CompoundAssignOperator); + case BO_XorAssign: DISPATCH(BinXorAssign, CompoundAssignOperator); + case BO_Comma: DISPATCH(BinComma, BinaryOperator); } } else if (UnaryOperator *UnOp = dyn_cast(S)) { switch (UnOp->getOpcode()) { default: assert(0 && "Unknown unary operator!"); - case UnaryOperator::PostInc: DISPATCH(UnaryPostInc, UnaryOperator); - case UnaryOperator::PostDec: DISPATCH(UnaryPostDec, UnaryOperator); - case UnaryOperator::PreInc: DISPATCH(UnaryPreInc, UnaryOperator); - case UnaryOperator::PreDec: DISPATCH(UnaryPreDec, UnaryOperator); - case UnaryOperator::AddrOf: DISPATCH(UnaryAddrOf, UnaryOperator); - case UnaryOperator::Deref: DISPATCH(UnaryDeref, UnaryOperator); - case UnaryOperator::Plus: DISPATCH(UnaryPlus, UnaryOperator); - case UnaryOperator::Minus: DISPATCH(UnaryMinus, UnaryOperator); - case UnaryOperator::Not: DISPATCH(UnaryNot, UnaryOperator); - case UnaryOperator::LNot: DISPATCH(UnaryLNot, UnaryOperator); - case UnaryOperator::Real: DISPATCH(UnaryReal, UnaryOperator); - case UnaryOperator::Imag: DISPATCH(UnaryImag, UnaryOperator); - case UnaryOperator::Extension: DISPATCH(UnaryExtension, UnaryOperator); - case UnaryOperator::OffsetOf: DISPATCH(UnaryOffsetOf, UnaryOperator); + case UO_PostInc: DISPATCH(UnaryPostInc, UnaryOperator); + case UO_PostDec: DISPATCH(UnaryPostDec, UnaryOperator); + case UO_PreInc: DISPATCH(UnaryPreInc, UnaryOperator); + case UO_PreDec: DISPATCH(UnaryPreDec, UnaryOperator); + case UO_AddrOf: DISPATCH(UnaryAddrOf, UnaryOperator); + case UO_Deref: DISPATCH(UnaryDeref, UnaryOperator); + case UO_Plus: DISPATCH(UnaryPlus, UnaryOperator); + case UO_Minus: DISPATCH(UnaryMinus, UnaryOperator); + case UO_Not: DISPATCH(UnaryNot, UnaryOperator); + case UO_LNot: DISPATCH(UnaryLNot, UnaryOperator); + case UO_Real: DISPATCH(UnaryReal, UnaryOperator); + case UO_Imag: DISPATCH(UnaryImag, UnaryOperator); + case UO_Extension: DISPATCH(UnaryExtension, UnaryOperator); } } @@ -163,7 +152,7 @@ public: UNARYOP_FALLBACK(Plus) UNARYOP_FALLBACK(Minus) UNARYOP_FALLBACK(Not) UNARYOP_FALLBACK(LNot) UNARYOP_FALLBACK(Real) UNARYOP_FALLBACK(Imag) - UNARYOP_FALLBACK(Extension) UNARYOP_FALLBACK(OffsetOf) + UNARYOP_FALLBACK(Extension) #undef UNARYOP_FALLBACK // Base case, ignore it. :) diff --git a/include/clang/AST/Type.h b/include/clang/AST/Type.h index 4c148e8fa22..92e62a58d42 100644 --- a/include/clang/AST/Type.h +++ b/include/clang/AST/Type.h @@ -289,7 +289,18 @@ public: L += R; return L; } + + Qualifiers &operator-=(Qualifiers R) { + Mask = Mask & ~(R.Mask); + return *this; + } + /// \brief Compute the difference between two qualifier sets. + friend Qualifiers operator-(Qualifiers L, Qualifiers R) { + L -= R; + return L; + } + std::string getAsString() const; std::string getAsString(const PrintingPolicy &Policy) const { std::string Buffer; @@ -399,7 +410,8 @@ enum CallingConv { CC_C, // __attribute__((cdecl)) CC_X86StdCall, // __attribute__((stdcall)) CC_X86FastCall, // __attribute__((fastcall)) - CC_X86ThisCall // __attribute__((thiscall)) + CC_X86ThisCall, // __attribute__((thiscall)) + CC_X86Pascal // __attribute__((pascal)) }; @@ -787,12 +799,12 @@ private: /// \brief Linkage of this type. mutable unsigned CachedLinkage : 2; - /// \brief FromPCH - Whether this type comes from a PCH file. - mutable bool FromPCH : 1; + /// \brief FromAST - Whether this type comes from an AST file. + mutable bool FromAST : 1; - /// \brief Set whether this type comes from a PCH file. - void setFromPCH(bool V = true) const { - FromPCH = V; + /// \brief Set whether this type comes from an AST file. + void setFromAST(bool V = true) const { + FromAST = V; } protected: @@ -806,16 +818,15 @@ protected: Type(TypeClass tc, QualType Canonical, bool dependent) : CanonicalType(Canonical.isNull() ? QualType(this_(), 0) : Canonical), TC(tc), Dependent(dependent), LinkageKnown(false), - CachedLinkage(NoLinkage), FromPCH(false) {} - virtual ~Type() {} - virtual void Destroy(ASTContext& C); + CachedLinkage(NoLinkage), FromAST(false) {} + virtual ~Type(); friend class ASTContext; public: TypeClass getTypeClass() const { return static_cast(TC); } - /// \brief Whether this type comes from a PCH file. - bool isFromPCH() const { return FromPCH; } + /// \brief Whether this type comes from an AST file. + bool isFromAST() const { return FromAST; } bool isCanonicalUnqualified() const { return CanonicalType.getTypePtr() == this; @@ -824,14 +835,6 @@ public: /// Types are partitioned into 3 broad categories (C99 6.2.5p1): /// object types, function types, and incomplete types. - /// \brief Determines whether the type describes an object in memory. - /// - /// Note that this definition of object type corresponds to the C++ - /// definition of object type, which includes incomplete types, as - /// opposed to the C definition (which does not include incomplete - /// types). - bool isObjectType() const; - /// isIncompleteType - Return true if this is an incomplete type. /// A type that can describe objects, but which lacks information needed to /// determine its size (e.g. void, or a fwd declared struct). Clients of this @@ -906,6 +909,7 @@ public: bool isFunctionPointerType() const; bool isMemberPointerType() const; bool isMemberFunctionPointerType() const; + bool isMemberDataPointerType() const; bool isArrayType() const; bool isConstantArrayType() const; bool isIncompleteArrayType() const; @@ -926,6 +930,7 @@ public: bool isObjCQualifiedInterfaceType() const; // NSString bool isObjCQualifiedIdType() const; // id bool isObjCQualifiedClassType() const; // Class + bool isObjCObjectOrInterfaceType() const; bool isObjCIdType() const; // id bool isObjCClassType() const; // Class bool isObjCSelType() const; // Class @@ -952,10 +957,22 @@ public: /// an objective pointer type for the purpose of GC'ability bool hasObjCPointerRepresentation() const; + /// \brief Determine whether this type has an integer representation + /// of some sort, e.g., it is an integer type or a vector. + bool hasIntegerRepresentation() const; + + /// \brief Determine whether this type has an signed integer representation + /// of some sort, e.g., it is an signed integer type or a vector. + bool hasSignedIntegerRepresentation() const; + + /// \brief Determine whether this type has an unsigned integer representation + /// of some sort, e.g., it is an unsigned integer type or a vector. + bool hasUnsignedIntegerRepresentation() const; + /// \brief Determine whether this type has a floating-point representation /// of some sort, e.g., it is a floating-point type or a vector thereof. bool hasFloatingRepresentation() const; - + // Type Checking Functions: Check to see if this type is structurally the // specified type, ignoring typedefs and qualifiers, and return a pointer to // the best type we can. @@ -975,7 +992,8 @@ public: /// type of a class template or class template partial specialization. CXXRecordDecl *getAsCXXRecordDecl() const; - // Member-template getAs'. This scheme will eventually + // Member-template getAs'. Look through sugar for + // an instance of . This scheme will eventually // replace the specific getAsXXXX methods above. // // There are some specializations of this member template listed @@ -1035,8 +1053,8 @@ public: void dump() const; static bool classof(const Type *) { return true; } - friend class PCHReader; - friend class PCHWriter; + friend class ASTReader; + friend class ASTWriter; }; template <> inline const TypedefType *Type::getAs() const { @@ -1353,9 +1371,20 @@ protected: virtual Linkage getLinkageImpl() const; public: - QualType getPointeeType() const { return PointeeType; } + /// Returns true if the member type (i.e. the pointee type) is a + /// function type rather than a data-member type. + bool isMemberFunctionPointer() const { + return PointeeType->isFunctionProtoType(); + } + + /// Returns true if the member type (i.e. the pointee type) is a + /// data type rather than a function type. + bool isMemberDataPointer() const { + return !PointeeType->isFunctionProtoType(); + } + const Type *getClass() const { return Class; } bool isSugared() const { return false; } @@ -1454,6 +1483,17 @@ public: bool isSugared() const { return false; } QualType desugar() const { return QualType(this, 0); } + + /// \brief Determine the number of bits required to address a member of + // an array with the given element type and number of elements. + static unsigned getNumAddressingBits(ASTContext &Context, + QualType ElementType, + const llvm::APInt &NumElements); + + /// \brief Determine the maximum number of active bits that an array's size + /// can require, which limits the maximum size of the array. + static unsigned getMaxSizeBits(ASTContext &Context); + void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType(), getSize(), getSizeModifier(), getIndexTypeCVRQualifiers()); @@ -1533,7 +1573,6 @@ class VariableArrayType : public ArrayType { : ArrayType(VariableArray, et, can, sm, tq), SizeExpr((Stmt*) e), Brackets(brackets) {} friend class ASTContext; // ASTContext creates these. - virtual void Destroy(ASTContext& C); public: Expr *getSizeExpr() const { @@ -1592,7 +1631,6 @@ class DependentSizedArrayType : public ArrayType { : ArrayType(DependentSizedArray, et, can, sm, tq), Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {} friend class ASTContext; // ASTContext creates these. - virtual void Destroy(ASTContext& C); public: Expr *getSizeExpr() const { @@ -1646,7 +1684,6 @@ class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {} friend class ASTContext; - virtual void Destroy(ASTContext& C); public: Expr *getSizeExpr() const { return SizeExpr; } @@ -1844,13 +1881,13 @@ class FunctionType : public Type { // * FunctionNoProtoType::Profile // * FunctionProtoType::Profile // * TypePrinter::PrintFunctionProto - // * PCH read and write + // * AST read and write // * Codegen class ExtInfo { public: // Constructor with no defaults. Use this when you know that you - // have all the elements (when reading a PCH file for example). + // have all the elements (when reading an AST file for example). ExtInfo(bool noReturn, unsigned regParm, CallingConv cc) : NoReturn(noReturn), RegParm(regParm), CC(cc) {} @@ -1892,7 +1929,7 @@ class FunctionType : public Type { // The value passed to __attribute__((regparm(x))) unsigned RegParm; // The calling convention as specified via - // __attribute__((cdecl|stdcall|fastcall|thiscall)) + // __attribute__((cdecl|stdcall|fastcall|thiscall|pascal)) CallingConv CC; }; @@ -2259,14 +2296,9 @@ public: }; class TagType : public Type { - /// Stores the TagDecl associated with this type. The decl will - /// point to the TagDecl that actually defines the entity (or is a - /// definition in progress), if there is such a definition. The - /// single-bit value will be non-zero when this tag is in the - /// process of being defined. - mutable llvm::PointerIntPair decl; - friend class ASTContext; - friend class TagDecl; + /// Stores the TagDecl associated with this type. The decl may point to any + /// TagDecl that declares the entity. + TagDecl * decl; protected: TagType(TypeClass TC, const TagDecl *D, QualType can); @@ -2274,12 +2306,11 @@ protected: virtual Linkage getLinkageImpl() const; public: - TagDecl *getDecl() const { return decl.getPointer(); } + TagDecl *getDecl() const; /// @brief Determines whether this type is in the process of being /// defined. - bool isBeingDefined() const { return decl.getInt(); } - void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); } + bool isBeingDefined() const; static bool classof(const Type *T) { return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast; @@ -2468,8 +2499,6 @@ class TemplateSpecializationType const TemplateArgument *Args, unsigned NumArgs, QualType Canon); - virtual void Destroy(ASTContext& C); - friend class ASTContext; // ASTContext creates these public: @@ -2574,9 +2603,8 @@ class InjectedClassNameType : public Type { QualType InjectedType; friend class ASTContext; // ASTContext creates these. - friend class TagDecl; // TagDecl mutilates the Decl - friend class PCHReader; // FIXME: ASTContext::getInjectedClassNameType is not - // currently suitable for PCH reading, too much + friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not + // currently suitable for AST reading, too much // interdependencies. InjectedClassNameType(CXXRecordDecl *D, QualType TST) : Type(InjectedClassName, QualType(), true), @@ -2592,7 +2620,7 @@ public: return cast(InjectedType.getTypePtr()); } - CXXRecordDecl *getDecl() const { return Decl; } + CXXRecordDecl *getDecl() const; bool isSugared() const { return false; } QualType desugar() const { return QualType(this, 0); } @@ -2836,8 +2864,6 @@ class DependentTemplateSpecializationType : const TemplateArgument *Args, QualType Canon); - virtual void Destroy(ASTContext& C); - friend class ASTContext; // ASTContext creates these public: @@ -3014,8 +3040,6 @@ class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {} public: - void Destroy(ASTContext& C); // key function - void Profile(llvm::FoldingSetNodeID &ID); static void Profile(llvm::FoldingSetNodeID &ID, QualType Base, @@ -3049,8 +3073,6 @@ class ObjCInterfaceType : public ObjCObjectType { Decl(const_cast(D)) {} friend class ASTContext; // ASTContext creates these. public: - void Destroy(ASTContext& C); // key function - /// getDecl - Get the declaration of this interface. ObjCInterfaceDecl *getDecl() const { return Decl; } @@ -3103,8 +3125,6 @@ protected: virtual Linkage getLinkageImpl() const; public: - void Destroy(ASTContext& C); - /// getPointeeType - Gets the type pointed to by this ObjC pointer. /// The result will always be an ObjCObjectType or sugar thereof. QualType getPointeeType() const { return PointeeType; } @@ -3486,7 +3506,13 @@ inline bool Type::isMemberPointerType() const { } inline bool Type::isMemberFunctionPointerType() const { if (const MemberPointerType* T = getAs()) - return T->getPointeeType()->isFunctionType(); + return T->isMemberFunctionPointer(); + else + return false; +} +inline bool Type::isMemberDataPointerType() const { + if (const MemberPointerType* T = getAs()) + return T->isMemberDataPointer(); else return false; } @@ -3523,6 +3549,11 @@ inline bool Type::isObjCObjectPointerType() const { inline bool Type::isObjCObjectType() const { return isa(CanonicalType); } +inline bool Type::isObjCObjectOrInterfaceType() const { + return isa(CanonicalType) || + isa(CanonicalType); +} + inline bool Type::isObjCQualifiedIdType() const { if (const ObjCObjectPointerType *OPT = getAs()) return OPT->isObjCQualifiedIdType(); diff --git a/include/clang/AST/TypeLoc.h b/include/clang/AST/TypeLoc.h index 842c0687845..f1c64bd9597 100644 --- a/include/clang/AST/TypeLoc.h +++ b/include/clang/AST/TypeLoc.h @@ -341,6 +341,10 @@ private: template class InheritingConcreteTypeLoc : public Base { public: + static bool classofType(const Type *Ty) { + return TypeClass::classof(Ty); + } + static bool classof(const TypeLoc *TL) { return Derived::classofType(TL->getTypePtr()); } diff --git a/include/clang/AST/TypeOrdering.h b/include/clang/AST/TypeOrdering.h index 1a050d29c86..7cf0d5e999b 100644 --- a/include/clang/AST/TypeOrdering.h +++ b/include/clang/AST/TypeOrdering.h @@ -17,6 +17,7 @@ #define LLVM_CLANG_TYPE_ORDERING_H #include "clang/AST/Type.h" +#include "clang/AST/CanonicalType.h" #include namespace clang { @@ -51,6 +52,26 @@ namespace llvm { return LHS == RHS; } }; + + template<> struct DenseMapInfo { + static inline clang::CanQualType getEmptyKey() { + return clang::CanQualType(); + } + + static inline clang::CanQualType getTombstoneKey() { + using clang::CanQualType; + return CanQualType::getFromOpaquePtr(reinterpret_cast(-1)); + } + + static unsigned getHashValue(clang::CanQualType Val) { + return (unsigned)((uintptr_t)Val.getAsOpaquePtr()) ^ + ((unsigned)((uintptr_t)Val.getAsOpaquePtr() >> 9)); + } + + static bool isEqual(clang::CanQualType LHS, clang::CanQualType RHS) { + return LHS == RHS; + } + }; } #endif diff --git a/include/clang/Analysis/Analyses/FormatString.h b/include/clang/Analysis/Analyses/FormatString.h new file mode 100644 index 00000000000..280b1260ac2 --- /dev/null +++ b/include/clang/Analysis/Analyses/FormatString.h @@ -0,0 +1,595 @@ +//= FormatString.h - Analysis of printf/fprintf format strings --*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines APIs for analyzing the format strings of printf, fscanf, +// and friends. +// +// The structure of format strings for fprintf are described in C99 7.19.6.1. +// +// The structure of format strings for fscanf are described in C99 7.19.6.2. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_FORMAT_H +#define LLVM_CLANG_FORMAT_H + +#include "clang/AST/CanonicalType.h" + +namespace clang { + +//===----------------------------------------------------------------------===// +/// Common components of both fprintf and fscanf format strings. +namespace analyze_format_string { + +/// Class representing optional flags with location and representation +/// information. +class OptionalFlag { +public: + OptionalFlag(const char *Representation) + : representation(Representation), flag(false) {} + bool isSet() { return flag; } + void set() { flag = true; } + void clear() { flag = false; } + void setPosition(const char *position) { + assert(position); + this->position = position; + } + const char *getPosition() const { + assert(position); + return position; + } + const char *toString() const { return representation; } + + // Overloaded operators for bool like qualities + operator bool() const { return flag; } + OptionalFlag& operator=(const bool &rhs) { + flag = rhs; + return *this; // Return a reference to myself. + } +private: + const char *representation; + const char *position; + bool flag; +}; + +/// Represents the length modifier in a format string in scanf/printf. +class LengthModifier { +public: + enum Kind { + None, + AsChar, // 'hh' + AsShort, // 'h' + AsLong, // 'l' + AsLongLong, // 'll', 'q' (BSD, deprecated) + AsIntMax, // 'j' + AsSizeT, // 'z' + AsPtrDiff, // 't' + AsLongDouble, // 'L' + AsWideChar = AsLong // for '%ls', only makes sense for printf + }; + + LengthModifier() + : Position(0), kind(None) {} + LengthModifier(const char *pos, Kind k) + : Position(pos), kind(k) {} + + const char *getStart() const { + return Position; + } + + unsigned getLength() const { + switch (kind) { + default: + return 1; + case AsLongLong: + case AsChar: + return 2; + case None: + return 0; + } + } + + Kind getKind() const { return kind; } + void setKind(Kind k) { kind = k; } + + const char *toString() const; + +private: + const char *Position; + Kind kind; +}; + +class ConversionSpecifier { +public: + enum Kind { + InvalidSpecifier = 0, + // C99 conversion specifiers. + cArg, + dArg, + iArg, + IntArgBeg = cArg, IntArgEnd = iArg, + + oArg, + uArg, + xArg, + XArg, + UIntArgBeg = oArg, UIntArgEnd = XArg, + + fArg, + FArg, + eArg, + EArg, + gArg, + GArg, + aArg, + AArg, + DoubleArgBeg = fArg, DoubleArgEnd = AArg, + + sArg, + pArg, + nArg, + PercentArg, + CArg, + SArg, + + // ** Printf-specific ** + + // Objective-C specific specifiers. + ObjCObjArg, // '@' + ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg, + + // GlibC specific specifiers. + PrintErrno, // 'm' + + PrintfConvBeg = ObjCObjArg, PrintfConvEnd = PrintErrno, + + // ** Scanf-specific ** + ScanListArg, // '[' + ScanfConvBeg = ScanListArg, ScanfConvEnd = ScanListArg + }; + + ConversionSpecifier(bool isPrintf) + : IsPrintf(isPrintf), Position(0), EndScanList(0), kind(InvalidSpecifier) {} + + ConversionSpecifier(bool isPrintf, const char *pos, Kind k) + : IsPrintf(isPrintf), Position(pos), EndScanList(0), kind(k) {} + + const char *getStart() const { + return Position; + } + + llvm::StringRef getCharacters() const { + return llvm::StringRef(getStart(), getLength()); + } + + bool consumesDataArgument() const { + switch (kind) { + case PrintErrno: + assert(IsPrintf); + case PercentArg: + return false; + default: + return true; + } + } + + Kind getKind() const { return kind; } + void setKind(Kind k) { kind = k; } + unsigned getLength() const { + return EndScanList ? EndScanList - Position : 1; + } + + const char *toString() const; + + bool isPrintfKind() const { return IsPrintf; } + +protected: + bool IsPrintf; + const char *Position; + const char *EndScanList; + Kind kind; +}; + +class ArgTypeResult { +public: + enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy, + CStrTy, WCStrTy, WIntTy }; +private: + const Kind K; + QualType T; + ArgTypeResult(bool) : K(InvalidTy) {} +public: + ArgTypeResult(Kind k = UnknownTy) : K(k) {} + ArgTypeResult(QualType t) : K(SpecificTy), T(t) {} + ArgTypeResult(CanQualType t) : K(SpecificTy), T(t) {} + + static ArgTypeResult Invalid() { return ArgTypeResult(true); } + + bool isValid() const { return K != InvalidTy; } + + const QualType *getSpecificType() const { + return K == SpecificTy ? &T : 0; + } + + bool matchesType(ASTContext &C, QualType argTy) const; + + bool matchesAnyObjCObjectRef() const { return K == ObjCPointerTy; } + + QualType getRepresentativeType(ASTContext &C) const; +}; + +class OptionalAmount { +public: + enum HowSpecified { NotSpecified, Constant, Arg, Invalid }; + + OptionalAmount(HowSpecified howSpecified, + unsigned amount, + const char *amountStart, + unsigned amountLength, + bool usesPositionalArg) + : start(amountStart), length(amountLength), hs(howSpecified), amt(amount), + UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {} + + OptionalAmount(bool valid = true) + : start(0),length(0), hs(valid ? NotSpecified : Invalid), amt(0), + UsesPositionalArg(0), UsesDotPrefix(0) {} + + bool isInvalid() const { + return hs == Invalid; + } + + HowSpecified getHowSpecified() const { return hs; } + void setHowSpecified(HowSpecified h) { hs = h; } + + bool hasDataArgument() const { return hs == Arg; } + + unsigned getArgIndex() const { + assert(hasDataArgument()); + return amt; + } + + unsigned getConstantAmount() const { + assert(hs == Constant); + return amt; + } + + const char *getStart() const { + // We include the . character if it is given. + return start - UsesDotPrefix; + } + + unsigned getConstantLength() const { + assert(hs == Constant); + return length + UsesDotPrefix; + } + + ArgTypeResult getArgType(ASTContext &Ctx) const; + + void toString(llvm::raw_ostream &os) const; + + bool usesPositionalArg() const { return (bool) UsesPositionalArg; } + unsigned getPositionalArgIndex() const { + assert(hasDataArgument()); + return amt + 1; + } + + bool usesDotPrefix() const { return UsesDotPrefix; } + void setUsesDotPrefix() { UsesDotPrefix = true; } + +private: + const char *start; + unsigned length; + HowSpecified hs; + unsigned amt; + bool UsesPositionalArg : 1; + bool UsesDotPrefix; +}; + + +class FormatSpecifier { +protected: + LengthModifier LM; + OptionalAmount FieldWidth; + ConversionSpecifier CS; + /// Positional arguments, an IEEE extension: + /// IEEE Std 1003.1, 2004 Edition + /// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html + bool UsesPositionalArg; + unsigned argIndex; +public: + FormatSpecifier(bool isPrintf) + : CS(isPrintf), UsesPositionalArg(false), argIndex(0) {} + + void setLengthModifier(LengthModifier lm) { + LM = lm; + } + + void setUsesPositionalArg() { UsesPositionalArg = true; } + + void setArgIndex(unsigned i) { + argIndex = i; + } + + unsigned getArgIndex() const { + return argIndex; + } + + unsigned getPositionalArgIndex() const { + return argIndex + 1; + } + + const LengthModifier &getLengthModifier() const { + return LM; + } + + const OptionalAmount &getFieldWidth() const { + return FieldWidth; + } + + void setFieldWidth(const OptionalAmount &Amt) { + FieldWidth = Amt; + } + + bool usesPositionalArg() const { return UsesPositionalArg; } + + bool hasValidLengthModifier() const; +}; + +} // end analyze_format_string namespace + +//===----------------------------------------------------------------------===// +/// Pieces specific to fprintf format strings. + +namespace analyze_printf { + +class PrintfConversionSpecifier : + public analyze_format_string::ConversionSpecifier { +public: + PrintfConversionSpecifier() + : ConversionSpecifier(true, 0, InvalidSpecifier) {} + + PrintfConversionSpecifier(const char *pos, Kind k) + : ConversionSpecifier(true, pos, k) {} + + bool isObjCArg() const { return kind >= ObjCBeg && kind <= ObjCEnd; } + bool isIntArg() const { return kind >= IntArgBeg && kind <= IntArgEnd; } + bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; } + bool isDoubleArg() const { return kind >= DoubleArgBeg && + kind <= DoubleArgBeg; } + unsigned getLength() const { + // Conversion specifiers currently only are represented by + // single characters, but we be flexible. + return 1; + } + + static bool classof(const analyze_format_string::ConversionSpecifier *CS) { + return CS->isPrintfKind(); + } +}; + +using analyze_format_string::ArgTypeResult; +using analyze_format_string::LengthModifier; +using analyze_format_string::OptionalAmount; +using analyze_format_string::OptionalFlag; + +class PrintfSpecifier : public analyze_format_string::FormatSpecifier { + OptionalFlag IsLeftJustified; // '-' + OptionalFlag HasPlusPrefix; // '+' + OptionalFlag HasSpacePrefix; // ' ' + OptionalFlag HasAlternativeForm; // '#' + OptionalFlag HasLeadingZeroes; // '0' + OptionalAmount Precision; +public: + PrintfSpecifier() : + FormatSpecifier(/* isPrintf = */ true), + IsLeftJustified("-"), HasPlusPrefix("+"), HasSpacePrefix(" "), + HasAlternativeForm("#"), HasLeadingZeroes("0") {} + + static PrintfSpecifier Parse(const char *beg, const char *end); + + // Methods for incrementally constructing the PrintfSpecifier. + void setConversionSpecifier(const PrintfConversionSpecifier &cs) { + CS = cs; + } + void setIsLeftJustified(const char *position) { + IsLeftJustified = true; + IsLeftJustified.setPosition(position); + } + void setHasPlusPrefix(const char *position) { + HasPlusPrefix = true; + HasPlusPrefix.setPosition(position); + } + void setHasSpacePrefix(const char *position) { + HasSpacePrefix = true; + HasSpacePrefix.setPosition(position); + } + void setHasAlternativeForm(const char *position) { + HasAlternativeForm = true; + HasAlternativeForm.setPosition(position); + } + void setHasLeadingZeros(const char *position) { + HasLeadingZeroes = true; + HasLeadingZeroes.setPosition(position); + } + void setUsesPositionalArg() { UsesPositionalArg = true; } + + // Methods for querying the format specifier. + + const PrintfConversionSpecifier &getConversionSpecifier() const { + return cast(CS); + } + + void setPrecision(const OptionalAmount &Amt) { + Precision = Amt; + Precision.setUsesDotPrefix(); + } + + const OptionalAmount &getPrecision() const { + return Precision; + } + + bool consumesDataArgument() const { + return getConversionSpecifier().consumesDataArgument(); + } + + /// \brief Returns the builtin type that a data argument + /// paired with this format specifier should have. This method + /// will return null if the format specifier does not have + /// a matching data argument or the matching argument matches + /// more than one type. + ArgTypeResult getArgType(ASTContext &Ctx) const; + + const OptionalFlag &isLeftJustified() const { return IsLeftJustified; } + const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; } + const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; } + const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; } + const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; } + bool usesPositionalArg() const { return UsesPositionalArg; } + + /// Changes the specifier and length according to a QualType, retaining any + /// flags or options. Returns true on success, or false when a conversion + /// was not successful. + bool fixType(QualType QT); + + void toString(llvm::raw_ostream &os) const; + + // Validation methods - to check if any element results in undefined behavior + bool hasValidPlusPrefix() const; + bool hasValidAlternativeForm() const; + bool hasValidLeadingZeros() const; + bool hasValidSpacePrefix() const; + bool hasValidLeftJustified() const; + + bool hasValidPrecision() const; + bool hasValidFieldWidth() const; +}; +} // end analyze_printf namespace + +//===----------------------------------------------------------------------===// +/// Pieces specific to fscanf format strings. + +namespace analyze_scanf { + +class ScanfConversionSpecifier : + public analyze_format_string::ConversionSpecifier { +public: + ScanfConversionSpecifier() + : ConversionSpecifier(false, 0, InvalidSpecifier) {} + + ScanfConversionSpecifier(const char *pos, Kind k) + : ConversionSpecifier(false, pos, k) {} + + void setEndScanList(const char *pos) { EndScanList = pos; } + + static bool classof(const analyze_format_string::ConversionSpecifier *CS) { + return !CS->isPrintfKind(); + } +}; + +using analyze_format_string::LengthModifier; +using analyze_format_string::OptionalAmount; +using analyze_format_string::OptionalFlag; + +class ScanfSpecifier : public analyze_format_string::FormatSpecifier { + OptionalFlag SuppressAssignment; // '*' +public: + ScanfSpecifier() : + FormatSpecifier(/* isPrintf = */ false), + SuppressAssignment("*") {} + + void setSuppressAssignment(const char *position) { + SuppressAssignment = true; + SuppressAssignment.setPosition(position); + } + + const OptionalFlag &getSuppressAssignment() const { + return SuppressAssignment; + } + + void setConversionSpecifier(const ScanfConversionSpecifier &cs) { + CS = cs; + } + + const ScanfConversionSpecifier &getConversionSpecifier() const { + return cast(CS); + } + + bool consumesDataArgument() const { + return CS.consumesDataArgument() && !SuppressAssignment; + } + + static ScanfSpecifier Parse(const char *beg, const char *end); +}; + +} // end analyze_scanf namespace + +//===----------------------------------------------------------------------===// +// Parsing and processing of format strings (both fprintf and fscanf). + +namespace analyze_format_string { + +enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 }; + +class FormatStringHandler { +public: + FormatStringHandler() {} + virtual ~FormatStringHandler(); + + virtual void HandleNullChar(const char *nullCharacter) {} + + virtual void HandleInvalidPosition(const char *startPos, unsigned posLen, + PositionContext p) {} + + virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {} + + virtual void HandleIncompleteSpecifier(const char *startSpecifier, + unsigned specifierLen) {} + + // Printf-specific handlers. + + virtual bool HandleInvalidPrintfConversionSpecifier( + const analyze_printf::PrintfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + return true; + } + + virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + return true; + } + + // Scanf-specific handlers. + + virtual bool HandleInvalidScanfConversionSpecifier( + const analyze_scanf::ScanfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + return true; + } + + virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, + const char *startSpecifier, + unsigned specifierLen) { + return true; + } + + virtual void HandleIncompleteScanList(const char *start, const char *end) {} +}; + +bool ParsePrintfString(FormatStringHandler &H, + const char *beg, const char *end); + +bool ParseScanfString(FormatStringHandler &H, + const char *beg, const char *end); + +} // end analyze_format_string namespace +} // end clang namespace +#endif diff --git a/include/clang/Analysis/Analyses/LiveVariables.h b/include/clang/Analysis/Analyses/LiveVariables.h index 44ab080acbf..237fe14aed4 100644 --- a/include/clang/Analysis/Analyses/LiveVariables.h +++ b/include/clang/Analysis/Analyses/LiveVariables.h @@ -41,8 +41,9 @@ struct LiveVariables_ValueTypes { ObserverTy* Observer; ValTy AlwaysLive; AnalysisContext *AC; + bool killAtAssign; - AnalysisDataTy() : Observer(NULL), AC(NULL) {} + AnalysisDataTy() : Observer(NULL), AC(NULL), killAtAssign(true) {} }; //===-----------------------------------------------------===// @@ -68,7 +69,7 @@ class LiveVariables : public DataflowValues= ObjCBeg && kind <= ObjCEnd; } - bool isIntArg() const { return kind >= dArg && kind <= iArg; } - bool isUIntArg() const { return kind >= oArg && kind <= XArg; } - bool isDoubleArg() const { return kind >= fArg && kind <= AArg; } - Kind getKind() const { return kind; } - void setKind(Kind k) { kind = k; } - unsigned getLength() const { - // Conversion specifiers currently only are represented by - // single characters, but we be flexible. - return 1; - } - const char *toString() const; - -private: - const char *Position; - Kind kind; -}; - -class LengthModifier { -public: - enum Kind { - None, - AsChar, // 'hh' - AsShort, // 'h' - AsLong, // 'l' - AsLongLong, // 'll', 'q' (BSD, deprecated) - AsIntMax, // 'j' - AsSizeT, // 'z' - AsPtrDiff, // 't' - AsLongDouble, // 'L' - AsWideChar = AsLong // for '%ls' - }; - - LengthModifier() - : Position(0), kind(None) {} - LengthModifier(const char *pos, Kind k) - : Position(pos), kind(k) {} - - const char *getStart() const { - return Position; - } - - unsigned getLength() const { - switch (kind) { - default: - return 1; - case AsLongLong: - case AsChar: - return 2; - case None: - return 0; - } - } - - Kind getKind() const { return kind; } - void setKind(Kind k) { kind = k; } - - const char *toString() const; - -private: - const char *Position; - Kind kind; -}; - -class OptionalAmount { -public: - enum HowSpecified { NotSpecified, Constant, Arg, Invalid }; - - OptionalAmount(HowSpecified howSpecified, - unsigned amount, - const char *amountStart, - unsigned amountLength, - bool usesPositionalArg) - : start(amountStart), length(amountLength), hs(howSpecified), amt(amount), - UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {} - - OptionalAmount(bool valid = true) - : start(0),length(0), hs(valid ? NotSpecified : Invalid), amt(0), - UsesPositionalArg(0), UsesDotPrefix(0) {} - - bool isInvalid() const { - return hs == Invalid; - } - - HowSpecified getHowSpecified() const { return hs; } - void setHowSpecified(HowSpecified h) { hs = h; } - - bool hasDataArgument() const { return hs == Arg; } - - unsigned getArgIndex() const { - assert(hasDataArgument()); - return amt; - } - - unsigned getConstantAmount() const { - assert(hs == Constant); - return amt; - } - - const char *getStart() const { - // We include the . character if it is given. - return start - UsesDotPrefix; - } - - unsigned getConstantLength() const { - assert(hs == Constant); - return length + UsesDotPrefix; - } - - ArgTypeResult getArgType(ASTContext &Ctx) const; - - void toString(llvm::raw_ostream &os) const; - - bool usesPositionalArg() const { return (bool) UsesPositionalArg; } - unsigned getPositionalArgIndex() const { - assert(hasDataArgument()); - return amt + 1; - } - - bool usesDotPrefix() const { return UsesDotPrefix; } - void setUsesDotPrefix() { UsesDotPrefix = true; } - -private: - const char *start; - unsigned length; - HowSpecified hs; - unsigned amt; - bool UsesPositionalArg : 1; - bool UsesDotPrefix; -}; - -// Class representing optional flags with location and representation -// information. -class OptionalFlag { -public: - OptionalFlag(const char *Representation) - : representation(Representation), flag(false) {} - bool isSet() { return flag; } - void set() { flag = true; } - void clear() { flag = false; } - void setPosition(const char *position) { - assert(position); - this->position = position; - } - const char *getPosition() const { - assert(position); - return position; - } - const char *toString() const { return representation; } - - // Overloaded operators for bool like qualities - operator bool() const { return flag; } - OptionalFlag& operator=(const bool &rhs) { - flag = rhs; - return *this; // Return a reference to myself. - } -private: - const char *representation; - const char *position; - bool flag; -}; - -class FormatSpecifier { - LengthModifier LM; - OptionalFlag IsLeftJustified; // '-' - OptionalFlag HasPlusPrefix; // '+' - OptionalFlag HasSpacePrefix; // ' ' - OptionalFlag HasAlternativeForm; // '#' - OptionalFlag HasLeadingZeroes; // '0' - /// Positional arguments, an IEEE extension: - /// IEEE Std 1003.1, 2004 Edition - /// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html - bool UsesPositionalArg; - unsigned argIndex; - ConversionSpecifier CS; - OptionalAmount FieldWidth; - OptionalAmount Precision; -public: - FormatSpecifier() : - IsLeftJustified("-"), HasPlusPrefix("+"), HasSpacePrefix(" "), - HasAlternativeForm("#"), HasLeadingZeroes("0"), UsesPositionalArg(false), - argIndex(0) {} - - static FormatSpecifier Parse(const char *beg, const char *end); - - // Methods for incrementally constructing the FormatSpecifier. - void setConversionSpecifier(const ConversionSpecifier &cs) { - CS = cs; - } - void setLengthModifier(LengthModifier lm) { - LM = lm; - } - void setIsLeftJustified(const char *position) { - IsLeftJustified = true; - IsLeftJustified.setPosition(position); - } - void setHasPlusPrefix(const char *position) { - HasPlusPrefix = true; - HasPlusPrefix.setPosition(position); - } - void setHasSpacePrefix(const char *position) { - HasSpacePrefix = true; - HasSpacePrefix.setPosition(position); - } - void setHasAlternativeForm(const char *position) { - HasAlternativeForm = true; - HasAlternativeForm.setPosition(position); - } - void setHasLeadingZeros(const char *position) { - HasLeadingZeroes = true; - HasLeadingZeroes.setPosition(position); - } - void setUsesPositionalArg() { UsesPositionalArg = true; } - - void setArgIndex(unsigned i) { - assert(CS.consumesDataArgument()); - argIndex = i; - } - - unsigned getArgIndex() const { - assert(CS.consumesDataArgument()); - return argIndex; - } - - unsigned getPositionalArgIndex() const { - assert(CS.consumesDataArgument()); - return argIndex + 1; - } - - // Methods for querying the format specifier. - - const ConversionSpecifier &getConversionSpecifier() const { - return CS; - } - - const LengthModifier &getLengthModifier() const { - return LM; - } - - const OptionalAmount &getFieldWidth() const { - return FieldWidth; - } - - void setFieldWidth(const OptionalAmount &Amt) { - FieldWidth = Amt; - } - - void setPrecision(const OptionalAmount &Amt) { - Precision = Amt; - Precision.setUsesDotPrefix(); - } - - const OptionalAmount &getPrecision() const { - return Precision; - } - - /// \brief Returns the builtin type that a data argument - /// paired with this format specifier should have. This method - /// will return null if the format specifier does not have - /// a matching data argument or the matching argument matches - /// more than one type. - ArgTypeResult getArgType(ASTContext &Ctx) const; - - const OptionalFlag &isLeftJustified() const { return IsLeftJustified; } - const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; } - const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; } - const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; } - const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; } - bool usesPositionalArg() const { return UsesPositionalArg; } - - /// Changes the specifier and length according to a QualType, retaining any - /// flags or options. Returns true on success, or false when a conversion - /// was not successful. - bool fixType(QualType QT); - - void toString(llvm::raw_ostream &os) const; - - // Validation methods - to check if any element results in undefined behavior - bool hasValidPlusPrefix() const; - bool hasValidAlternativeForm() const; - bool hasValidLeadingZeros() const; - bool hasValidSpacePrefix() const; - bool hasValidLeftJustified() const; - - bool hasValidLengthModifier() const; - bool hasValidPrecision() const; - bool hasValidFieldWidth() const; -}; - -enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 }; - -class FormatStringHandler { -public: - FormatStringHandler() {} - virtual ~FormatStringHandler(); - - virtual void HandleIncompleteFormatSpecifier(const char *startSpecifier, - unsigned specifierLen) {} - - virtual void HandleNullChar(const char *nullCharacter) {} - - virtual void HandleInvalidPosition(const char *startPos, unsigned posLen, - PositionContext p) {} - - virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {} - - virtual bool - HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS, - const char *startSpecifier, - unsigned specifierLen) { return true; } - - virtual bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS, - const char *startSpecifier, - unsigned specifierLen) { - return true; - } -}; - -bool ParseFormatString(FormatStringHandler &H, - const char *beg, const char *end); - -} // end printf namespace -} // end clang namespace -#endif diff --git a/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h b/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h new file mode 100644 index 00000000000..cb73850b08c --- /dev/null +++ b/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h @@ -0,0 +1,45 @@ +//== PseudoConstantAnalysis.h - Find Pseudo-constants in the AST -*- C++ -*-==// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file tracks the usage of variables in a Decl body to see if they are +// never written to, implying that they constant. This is useful in static +// analysis to see if a developer might have intended a variable to be const. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_ANALYSIS_PSEUDOCONSTANTANALYSIS +#define LLVM_CLANG_ANALYSIS_PSEUDOCONSTANTANALYSIS + +#include "clang/AST/Stmt.h" + +namespace clang { + +class PseudoConstantAnalysis { +public: + PseudoConstantAnalysis(const Stmt *DeclBody); + ~PseudoConstantAnalysis(); + + bool isPseudoConstant(const VarDecl *VD); + bool wasReferenced(const VarDecl *VD); + +private: + void RunAnalysis(); + inline static const Decl *getDecl(const Expr *E); + + // for storing the result of analyzed ValueDecls + void *NonConstantsImpl; + void *UsedVarsImpl; + + const Stmt *DeclBody; + bool Analyzed; +}; + +} + +#endif diff --git a/include/clang/Analysis/AnalysisContext.h b/include/clang/Analysis/AnalysisContext.h index 9ebd93b75b3..7d4d25f8b0d 100644 --- a/include/clang/Analysis/AnalysisContext.h +++ b/include/clang/Analysis/AnalysisContext.h @@ -30,41 +30,67 @@ class CFG; class CFGBlock; class LiveVariables; class ParentMap; +class PseudoConstantAnalysis; class ImplicitParamDecl; class LocationContextManager; class StackFrameContext; +namespace idx { class TranslationUnit; } + /// AnalysisContext contains the context data for the function or method under /// analysis. class AnalysisContext { const Decl *D; + // TranslationUnit is NULL if we don't have multiple translation units. + idx::TranslationUnit *TU; + // AnalysisContext owns the following data. - CFG *cfg; - bool builtCFG; + CFG *cfg, *completeCFG; + bool builtCFG, builtCompleteCFG; LiveVariables *liveness; + LiveVariables *relaxedLiveness; ParentMap *PM; + PseudoConstantAnalysis *PCA; llvm::DenseMap *ReferencedBlockVars; llvm::BumpPtrAllocator A; + bool UseUnoptimizedCFG; bool AddEHEdges; public: - AnalysisContext(const Decl *d, bool addehedges = false) - : D(d), cfg(0), builtCFG(false), liveness(0), PM(0), - ReferencedBlockVars(0), AddEHEdges(addehedges) {} + AnalysisContext(const Decl *d, idx::TranslationUnit *tu, + bool useUnoptimizedCFG = false, + bool addehedges = false) + : D(d), TU(tu), cfg(0), completeCFG(0), + builtCFG(false), builtCompleteCFG(false), + liveness(0), relaxedLiveness(0), PM(0), PCA(0), + ReferencedBlockVars(0), UseUnoptimizedCFG(useUnoptimizedCFG), + AddEHEdges(addehedges) {} ~AnalysisContext(); ASTContext &getASTContext() { return D->getASTContext(); } - const Decl *getDecl() { return D; } + const Decl *getDecl() const { return D; } + + idx::TranslationUnit *getTranslationUnit() const { return TU; } + /// getAddEHEdges - Return true iff we are adding exceptional edges from /// callExprs. If this is false, then try/catch statements and blocks /// reachable from them can appear to be dead in the CFG, analysis passes must /// cope with that. bool getAddEHEdges() const { return AddEHEdges; } + + bool getUseUnoptimizedCFG() const { return UseUnoptimizedCFG; } + Stmt *getBody(); CFG *getCFG(); + + /// Return a version of the CFG without any edges pruned. + CFG *getUnoptimizedCFG(); + ParentMap &getParentMap(); + PseudoConstantAnalysis *getPseudoConstantAnalysis(); LiveVariables *getLiveVariables(); + LiveVariables *getRelaxedLiveVariables(); typedef const VarDecl * const * referenced_decls_iterator; @@ -79,10 +105,16 @@ public: class AnalysisContextManager { typedef llvm::DenseMap ContextMap; ContextMap Contexts; + bool UseUnoptimizedCFG; public: + AnalysisContextManager(bool useUnoptimizedCFG = false) + : UseUnoptimizedCFG(useUnoptimizedCFG) {} + ~AnalysisContextManager(); - AnalysisContext *getContext(const Decl *D); + AnalysisContext *getContext(const Decl *D, idx::TranslationUnit *TU = 0); + + bool getUseUnoptimizedCFG() const { return UseUnoptimizedCFG; } // Discard all previously created AnalysisContexts. void clear(); @@ -94,7 +126,10 @@ public: private: ContextKind Kind; + + // AnalysisContext can't be const since some methods may modify its member. AnalysisContext *Ctx; + const LocationContext *Parent; protected: @@ -109,6 +144,10 @@ public: AnalysisContext *getAnalysisContext() const { return Ctx; } + idx::TranslationUnit *getTranslationUnit() const { + return Ctx->getTranslationUnit(); + } + const LocationContext *getParent() const { return Parent; } bool isParentOf(const LocationContext *LC) const; diff --git a/include/clang/Analysis/CFG.h b/include/clang/Analysis/CFG.h index b7256c9dc3d..b7a8e115969 100644 --- a/include/clang/Analysis/CFG.h +++ b/include/clang/Analysis/CFG.h @@ -35,22 +35,6 @@ namespace clang { class LangOptions; class ASTContext; -namespace { -// An element of the CFG for implicit descructor calls implied by the language -// rules. -class Dtor { - // Statement that introduces the variable. - Stmt *S; - // A token which ends the scope, return, goto, throw, }. - SourceLocation Loc; -public: - Dtor(Stmt *s, SourceLocation l) : S(s), Loc(l) { - } - SourceLocation getLoc() { return Loc; } - Stmt *getStmt() { return S; } -}; -} - /// CFGElement - Represents a top-level expression in a basic block. class CFGElement { llvm::PointerIntPair Data; @@ -59,7 +43,6 @@ public: explicit CFGElement() {} CFGElement(Stmt *S, bool lvalue) : Data(S, lvalue ? 1 : 0) {} CFGElement(Stmt *S, Type t) : Data(S, t == StartScope ? 2 : 3) {} - // CFGElement(Dtor *S, Type t) : Data(reinterpret_cast(S), 4) {} Stmt *getStmt() const { return Data.getPointer(); } bool asLValue() const { return Data.getInt() == 1; } bool asStartScope() const { return Data.getInt() == 2; } @@ -67,7 +50,6 @@ public: bool asDtor() const { return Data.getInt() == 4; } operator Stmt*() const { return getStmt(); } operator bool() const { return getStmt() != 0; } - operator Dtor*() const { return reinterpret_cast(getStmt()); } }; /// CFGBlock - Represents a single basic block in a source-level CFG. @@ -285,6 +267,7 @@ public: /// buildCFG - Builds a CFG from an AST. The responsibility to free the /// constructed CFG belongs to the caller. static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C, + bool pruneTriviallyFalseEdges = true, bool AddEHEdges = false, bool AddScopes = false /* NOT FULLY IMPLEMENTED. NOT READY FOR GENERAL USE. */); diff --git a/include/clang/Analysis/CFGStmtMap.h b/include/clang/Analysis/CFGStmtMap.h new file mode 100644 index 00000000000..6e8e140afb2 --- /dev/null +++ b/include/clang/Analysis/CFGStmtMap.h @@ -0,0 +1,52 @@ +//===--- CFGStmtMap.h - Map from Stmt* to CFGBlock* -----------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines the CFGStmtMap class, which defines a mapping from +// Stmt* to CFGBlock* +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_CFGSTMTMAP_H +#define LLVM_CLANG_CFGSTMTMAP_H + +#include "clang/Analysis/CFG.h" + +namespace clang { + +class CFG; +class CFGBlock; +class ParentMap; +class Stmt; + +class CFGStmtMap { + ParentMap *PM; + void *M; + + CFGStmtMap(ParentMap *pm, void *m) : PM(pm), M(m) {} + +public: + ~CFGStmtMap(); + + /// Returns a new CFGMap for the given CFG. It is the caller's + /// responsibility to 'delete' this object when done using it. + static CFGStmtMap *Build(CFG* C, ParentMap *PM); + + /// Returns the CFGBlock the specified Stmt* appears in. For Stmt* that + /// are terminators, the CFGBlock is the block they appear as a terminator, + /// and not the block they appear as a block-level expression (e.g, '&&'). + /// CaseStmts and LabelStmts map to the CFGBlock they label. + CFGBlock *getBlock(Stmt * S); + + const CFGBlock *getBlock(const Stmt * S) const { + return const_cast(this)->getBlock(const_cast(S)); + } +}; + +} // end clang namespace +#endif diff --git a/include/clang/Analysis/FlowSensitive/DataflowSolver.h b/include/clang/Analysis/FlowSensitive/DataflowSolver.h index 3c762011a65..9375db06be7 100644 --- a/include/clang/Analysis/FlowSensitive/DataflowSolver.h +++ b/include/clang/Analysis/FlowSensitive/DataflowSolver.h @@ -231,7 +231,7 @@ private: EdgeDataMapTy& M = D.getEdgeDataMap(); bool firstMerge = true; - + bool noEdges = true; for (PrevBItr I=ItrTraits::PrevBegin(B),E=ItrTraits::PrevEnd(B); I!=E; ++I){ CFGBlock *PrevBlk = *I; @@ -243,6 +243,7 @@ private: M.find(ItrTraits::PrevEdge(B, PrevBlk)); if (EI != M.end()) { + noEdges = false; if (firstMerge) { firstMerge = false; V.copyValues(EI->second); @@ -252,8 +253,20 @@ private: } } + bool isInitialized = true; + typename BlockDataMapTy::iterator BI = D.getBlockDataMap().find(B); + if(BI == D.getBlockDataMap().end()) { + isInitialized = false; + BI = D.getBlockDataMap().insert( std::make_pair(B,ValTy()) ).first; + } + // If no edges have been found, it means this is the first time the solver + // has been called on block B, we copy the initialization values (if any) + // as current value for V (which will be used as edge data) + if(noEdges && isInitialized) + Merge(V, BI->second); + // Set the data for the block. - D.getBlockDataMap()[B].copyValues(V); + BI->second.copyValues(V); } /// ProcessBlock - Process the transfer functions for a given block. diff --git a/include/clang/Analysis/ProgramPoint.h b/include/clang/Analysis/ProgramPoint.h index 075838d45e5..ba303de7a8d 100644 --- a/include/clang/Analysis/ProgramPoint.h +++ b/include/clang/Analysis/ProgramPoint.h @@ -15,6 +15,7 @@ #ifndef LLVM_CLANG_ANALYSIS_PROGRAM_POINT #define LLVM_CLANG_ANALYSIS_PROGRAM_POINT +#include "clang/Analysis/AnalysisContext.h" #include "clang/Analysis/CFG.h" #include "llvm/System/DataTypes.h" #include "llvm/ADT/DenseMap.h" @@ -26,6 +27,7 @@ namespace clang { class LocationContext; +class AnalysisContext; class FunctionDecl; class ProgramPoint { @@ -45,7 +47,7 @@ public: CallEnterKind, CallExitKind, MinPostStmtKind = PostStmtKind, - MaxPostStmtKind = PostLValueKind }; + MaxPostStmtKind = CallExitKind }; private: std::pair Data; @@ -107,16 +109,16 @@ public: const void *tag = 0) : ProgramPoint(B, BlockEntranceKind, L, tag) {} - CFGBlock* getBlock() const { - return const_cast(reinterpret_cast(getData1())); + const CFGBlock* getBlock() const { + return reinterpret_cast(getData1()); } - CFGElement getFirstElement() const { + const CFGElement getFirstElement() const { const CFGBlock* B = getBlock(); return B->empty() ? CFGElement() : B->front(); } - Stmt *getFirstStmt() const { + const Stmt *getFirstStmt() const { return getFirstElement().getStmt(); } @@ -130,16 +132,16 @@ public: BlockExit(const CFGBlock* B, const LocationContext *L) : ProgramPoint(B, BlockExitKind, L) {} - CFGBlock* getBlock() const { - return const_cast(reinterpret_cast(getData1())); + const CFGBlock* getBlock() const { + return reinterpret_cast(getData1()); } - Stmt* getLastStmt() const { + const Stmt* getLastStmt() const { const CFGBlock* B = getBlock(); return B->empty() ? CFGElement() : B->back(); } - Stmt* getTerminator() const { + const Stmt* getTerminator() const { return getBlock()->getTerminator(); } @@ -298,12 +300,12 @@ public: BlockEdge(const CFGBlock* B1, const CFGBlock* B2, const LocationContext *L) : ProgramPoint(B1, B2, BlockEdgeKind, L) {} - CFGBlock* getSrc() const { - return const_cast(static_cast(getData1())); + const CFGBlock* getSrc() const { + return static_cast(getData1()); } - CFGBlock* getDst() const { - return const_cast(static_cast(getData2())); + const CFGBlock* getDst() const { + return static_cast(getData2()); } static bool classof(const ProgramPoint* Location) { @@ -313,16 +315,17 @@ public: class CallEnter : public StmtPoint { public: - // CallEnter uses the caller's location context. - CallEnter(const Stmt *S, const FunctionDecl *fd, const LocationContext *L) - : StmtPoint(S, fd, CallEnterKind, L, 0) {} + // L is caller's location context. AC is callee's AnalysisContext. + CallEnter(const Stmt *S, const AnalysisContext *AC, const LocationContext *L) + : StmtPoint(S, AC, CallEnterKind, L, 0) {} const Stmt *getCallExpr() const { return static_cast(getData1()); } - const FunctionDecl *getCallee() const { - return static_cast(getData2()); + AnalysisContext *getCalleeContext() const { + return const_cast( + static_cast(getData2())); } static bool classof(const ProgramPoint *Location) { diff --git a/include/clang/Analysis/Visitors/CFGStmtVisitor.h b/include/clang/Analysis/Visitors/CFGStmtVisitor.h index 8a85ec15cdc..6421f185ff7 100644 --- a/include/clang/Analysis/Visitors/CFGStmtVisitor.h +++ b/include/clang/Analysis/Visitors/CFGStmtVisitor.h @@ -86,7 +86,7 @@ public: BinaryOperator* B = cast(S); if (B->isLogicalOp()) return static_cast(this)->BlockStmt_VisitLogicalOp(B); - else if (B->getOpcode() == BinaryOperator::Comma) + else if (B->getOpcode() == BO_Comma) return static_cast(this)->BlockStmt_VisitComma(B); // Fall through. } @@ -149,7 +149,7 @@ public: case Stmt::BinaryOperatorClass: { BinaryOperator* B = cast(S); - if (B->getOpcode() != BinaryOperator::Comma) break; + if (B->getOpcode() != BO_Comma) break; static_cast(this)->Visit(B->getRHS()); return; } diff --git a/include/clang/Basic/Attr.td b/include/clang/Basic/Attr.td index 98871d26204..2f2267f7f79 100644 --- a/include/clang/Basic/Attr.td +++ b/include/clang/Basic/Attr.td @@ -33,8 +33,8 @@ class SubsetSubject // a possible subject. def NormalVar : SubsetSubjectgetStorageClass() != VarDecl::Register && - S->getKind() != Decl::ImplicitParam - S->getKind() != Decl::ParmVar + S->getKind() != Decl::ImplicitParam && + S->getKind() != Decl::ParmVar && S->getKind() != Decl::NonTypeTemplateParm}]>; def CXXVirtualMethod : SubsetSubjectisVirtual()}]>; @@ -51,18 +51,27 @@ class IntArgument : Argument; class StringArgument : Argument; class ExprArgument : Argument; class FunctionArgument : Argument; -class ObjCInterfaceArgument : Argument; -class UnsignedIntArgument : Argument; -class UnsignedIntOrTypeArgument : Argument; +class TypeArgument : Argument; +class UnsignedArgument : Argument; +class VariadicUnsignedArgument : Argument; + +// This one's a doozy, so it gets its own special type +// It can be an unsigned integer, or a type. Either can +// be dependent. +class AlignedArgument : Argument; // An integer argument with a default value class DefaultIntArgument : IntArgument { int Default = default; } -// Zero or more arguments of a type -class VariadicArgument : Argument { - Argument VariadicArg = arg; +// This argument is more complex, it includes the enumerator type name, +// a list of strings to accept, and a list of enumerators to map them to. +class EnumArgument values, + list enums> : Argument { + string Type = type; + list Values = values; + list Enums = enums; } class Attr { @@ -76,9 +85,8 @@ class Attr { // The attribute will not be permitted in C++0x attribute-specifiers if // this is empty; the empty string can be used as a namespace. list Namespaces = []; - // A temporary development bit to tell TableGen not to emit certain - // information about the attribute. - bit DoNotEmit = 1; + // Any additional text that should be included verbatim in the class. + code AdditionalMembers = [{}]; } // @@ -87,13 +95,13 @@ class Attr { def Alias : Attr { let Spellings = ["alias"]; - let Args = [StringArgument<"AliasName">]; + let Args = [StringArgument<"Aliasee">]; } def Aligned : Attr { let Spellings = ["align", "aligned"]; let Subjects = [NonBitField, NormalVar, Tag]; - let Args = [UnsignedIntOrTypeArgument<"Alignment">]; + let Args = [AlignedArgument<"Alignment">]; let Namespaces = ["", "std"]; } @@ -123,19 +131,17 @@ def BaseCheck : Attr { let Spellings = ["base_check"]; let Subjects = [CXXRecord]; let Namespaces = ["", "std"]; - let DoNotEmit = 0; } def Blocks : Attr { let Spellings = ["blocks"]; - let Args = [IdentifierArgument<"Type">]; + let Args = [EnumArgument<"Type", "BlockType", ["byref"], ["ByRef"]>]; } def CarriesDependency : Attr { let Spellings = ["carries_dependency"]; let Subjects = [ParmVar, Function]; let Namespaces = ["", "std"]; - let DoNotEmit = 0; } def CDecl : Attr { @@ -189,7 +195,6 @@ def Final : Attr { let Spellings = ["final"]; let Subjects = [CXXRecord, CXXVirtualMethod]; let Namespaces = ["", "std"]; - let DoNotEmit = 0; } def Format : Attr { @@ -211,7 +216,6 @@ def Hiding : Attr { let Spellings = ["hiding"]; let Subjects = [Field, CXXMethod]; let Namespaces = ["", "std"]; - let DoNotEmit = 0; } def IBAction : Attr { @@ -224,7 +228,7 @@ def IBOutlet : Attr { def IBOutletCollection : Attr { let Spellings = ["iboutletcollection"]; - let Args = [ObjCInterfaceArgument<"Class">]; + let Args = [TypeArgument<"Interface">]; } def Malloc : Attr { @@ -233,12 +237,12 @@ def Malloc : Attr { def MaxFieldAlignment : Attr { let Spellings = []; - let Args = [UnsignedIntArgument<"Alignment">]; + let Args = [UnsignedArgument<"Alignment">]; } def MSP430Interrupt : Attr { let Spellings = []; - let Args = [UnsignedIntArgument<"Number">]; + let Args = [UnsignedArgument<"Number">]; } def NoDebug : Attr { @@ -251,7 +255,15 @@ def NoInline : Attr { def NonNull : Attr { let Spellings = ["nonnull"]; - let Args = [VariadicArgument>]; + let Args = [VariadicUnsignedArgument<"Args">]; + let AdditionalMembers = +[{bool isNonNull(unsigned idx) const { + for (args_iterator i = args_begin(), e = args_end(); + i != e; ++i) + if (*i == idx) + return true; + return false; + } }]; } def NoReturn : Attr { @@ -290,13 +302,20 @@ def Override : Attr { let Spellings = ["override"]; let Subjects = [CXXVirtualMethod]; let Namespaces = ["", "std"]; - let DoNotEmit = 0; } def Overloadable : Attr { let Spellings = ["overloadable"]; } +def Ownership : Attr { + let Spellings = ["ownership_holds", "ownership_returns", "ownership_takes"]; + let Args = [EnumArgument<"OwnKind", "OwnershipKind", + ["ownership_holds", "ownership_returns", "ownership_takes"], + ["Holds", "Returns", "Takes"]>, + StringArgument<"Module">, VariadicUnsignedArgument<"Args">]; +} + def Packed : Attr { let Spellings = ["packed"]; } @@ -307,18 +326,18 @@ def Pure : Attr { def Regparm : Attr { let Spellings = ["regparm"]; - let Args = [UnsignedIntArgument<"NumParams">]; + let Args = [UnsignedArgument<"NumParams">]; } def ReqdWorkGroupSize : Attr { let Spellings = ["reqd_work_group_size"]; - let Args = [UnsignedIntArgument<"XDim">, UnsignedIntArgument<"YDim">, - UnsignedIntArgument<"ZDim">]; + let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">, + UnsignedArgument<"ZDim">]; } def InitPriority : Attr { let Spellings = ["init_priority"]; - let Args = [UnsignedIntArgument<"Priority">]; + let Args = [UnsignedArgument<"Priority">]; } def Section : Attr { @@ -328,8 +347,8 @@ def Section : Attr { def Sentinel : Attr { let Spellings = ["sentinel"]; - let Args = [DefaultIntArgument<"NulPos", 0>, - DefaultIntArgument<"Sentinel", 0>]; + let Args = [DefaultIntArgument<"Sentinel", 0>, + DefaultIntArgument<"NullPos", 0>]; } def StdCall : Attr { @@ -340,6 +359,10 @@ def ThisCall : Attr { let Spellings = ["thiscall", "__thiscall"]; } +def Pascal : Attr { + let Spellings = ["pascal", "__pascal"]; +} + def TransparentUnion : Attr { let Spellings = ["transparent_union"]; } @@ -358,7 +381,14 @@ def Used : Attr { def Visibility : Attr { let Spellings = ["visibility"]; - let Args = [StringArgument<"Visibility">]; + let Args = [EnumArgument<"Visibility", "VisibilityType", + ["default", "hidden", "internal", "protected"], + ["Default", "Hidden", "Hidden", "Protected"]>]; +} + +def VecReturn : Attr { + let Spellings = ["vecreturn"]; + let Subjects = [CXXRecord]; } def WarnUnusedResult : Attr { diff --git a/include/clang/Basic/Builtins.def b/include/clang/Basic/Builtins.def index eff4f5e6727..0da893899b0 100644 --- a/include/clang/Basic/Builtins.def +++ b/include/clang/Basic/Builtins.def @@ -66,6 +66,11 @@ // P:N: -> similar to the p:N: attribute, but the function is like vprintf // in that it accepts its arguments as a va_list rather than // through an ellipsis +// s:N: -> this is a scanf-like function whose Nth argument is the format +// string. +// S:N: -> similar to the s:N: attribute, but the function is like vscanf +// in that it accepts its arguments as a va_list rather than +// through an ellipsis // e -> const, but only when -fmath-errno=0 // FIXME: gcc has nonnull @@ -193,9 +198,9 @@ BUILTIN(__builtin_cexpl, "XLdXLd", "Fnc") BUILTIN(__builtin_cimag, "dXd", "Fnc") BUILTIN(__builtin_cimagf, "fXf", "Fnc") BUILTIN(__builtin_cimagl, "LdXLd", "Fnc") -BUILTIN(__builtin_conj, "dXd", "Fnc") -BUILTIN(__builtin_conjf, "fXf", "Fnc") -BUILTIN(__builtin_conjl, "LdXLd", "Fnc") +BUILTIN(__builtin_conj, "XdXd", "Fnc") +BUILTIN(__builtin_conjf, "XfXf", "Fnc") +BUILTIN(__builtin_conjl, "XLdXLd", "Fnc") BUILTIN(__builtin_clog, "XdXd", "Fnc") BUILTIN(__builtin_clogf, "XfXf", "Fnc") BUILTIN(__builtin_clogl, "XLdXLd", "Fnc") @@ -281,12 +286,14 @@ BUILTIN(__builtin_stdarg_start, "vA.", "n") BUILTIN(__builtin_bcmp, "iv*v*z", "n") BUILTIN(__builtin_bcopy, "vv*v*z", "n") BUILTIN(__builtin_bzero, "vv*z", "nF") +BUILTIN(__builtin_fprintf, "iP*cC*.", "Fp:1:") BUILTIN(__builtin_memchr, "v*vC*iz", "nF") BUILTIN(__builtin_memcmp, "ivC*vC*z", "nF") BUILTIN(__builtin_memcpy, "v*v*vC*z", "nF") BUILTIN(__builtin_memmove, "v*v*vC*z", "nF") BUILTIN(__builtin_mempcpy, "v*v*vC*z", "nF") BUILTIN(__builtin_memset, "v*v*iz", "nF") +BUILTIN(__builtin_printf, "icC*.", "Fp:0:") BUILTIN(__builtin_stpcpy, "c*c*cC*", "nF") BUILTIN(__builtin_stpncpy, "c*c*cC*z", "nF") BUILTIN(__builtin_strcasecmp, "icC*cC*", "nF") @@ -319,7 +326,7 @@ BUILTIN(__builtin_vsprintf, "ic*cC*a", "nFP:1:") BUILTIN(__builtin_vsnprintf, "ic*zcC*a", "nFP:2:") // GCC exception builtins -BUILTIN(__builtin_eh_return, "vzv*", "") // FIXME: Takes intptr_t, not size_t! +BUILTIN(__builtin_eh_return, "vzv*", "r") // FIXME: Takes intptr_t, not size_t! BUILTIN(__builtin_frob_return_addr, "v*v*", "n") BUILTIN(__builtin_dwarf_cfa, "v*", "n") BUILTIN(__builtin_init_dwarf_reg_size_table, "vv*", "n") @@ -363,75 +370,75 @@ BUILTIN(__builtin_alloca, "v*z" , "n") // long long -> i64. BUILTIN(__sync_fetch_and_add, "v.", "") -BUILTIN(__sync_fetch_and_add_1, "cc*c.", "n") -BUILTIN(__sync_fetch_and_add_2, "ss*s.", "n") -BUILTIN(__sync_fetch_and_add_4, "ii*i.", "n") -BUILTIN(__sync_fetch_and_add_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_fetch_and_add_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_fetch_and_add_1, "ccD*c.", "n") +BUILTIN(__sync_fetch_and_add_2, "ssD*s.", "n") +BUILTIN(__sync_fetch_and_add_4, "iiD*i.", "n") +BUILTIN(__sync_fetch_and_add_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_fetch_and_add_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_fetch_and_sub, "v.", "") -BUILTIN(__sync_fetch_and_sub_1, "cc*c.", "n") -BUILTIN(__sync_fetch_and_sub_2, "ss*s.", "n") -BUILTIN(__sync_fetch_and_sub_4, "ii*i.", "n") -BUILTIN(__sync_fetch_and_sub_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_fetch_and_sub_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_fetch_and_sub_1, "ccD*c.", "n") +BUILTIN(__sync_fetch_and_sub_2, "ssD*s.", "n") +BUILTIN(__sync_fetch_and_sub_4, "iiD*i.", "n") +BUILTIN(__sync_fetch_and_sub_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_fetch_and_sub_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_fetch_and_or, "v.", "") -BUILTIN(__sync_fetch_and_or_1, "cc*c.", "n") -BUILTIN(__sync_fetch_and_or_2, "ss*s.", "n") -BUILTIN(__sync_fetch_and_or_4, "ii*i.", "n") -BUILTIN(__sync_fetch_and_or_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_fetch_and_or_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_fetch_and_or_1, "ccD*c.", "n") +BUILTIN(__sync_fetch_and_or_2, "ssD*s.", "n") +BUILTIN(__sync_fetch_and_or_4, "iiD*i.", "n") +BUILTIN(__sync_fetch_and_or_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_fetch_and_or_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_fetch_and_and, "v.", "") -BUILTIN(__sync_fetch_and_and_1, "cc*c.", "n") -BUILTIN(__sync_fetch_and_and_2, "ss*s.", "n") -BUILTIN(__sync_fetch_and_and_4, "ii*i.", "n") -BUILTIN(__sync_fetch_and_and_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_fetch_and_and_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_fetch_and_and_1, "ccD*c.", "n") +BUILTIN(__sync_fetch_and_and_2, "ssD*s.", "n") +BUILTIN(__sync_fetch_and_and_4, "iiD*i.", "n") +BUILTIN(__sync_fetch_and_and_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_fetch_and_and_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_fetch_and_xor, "v.", "") -BUILTIN(__sync_fetch_and_xor_1, "cc*c.", "n") -BUILTIN(__sync_fetch_and_xor_2, "ss*s.", "n") -BUILTIN(__sync_fetch_and_xor_4, "ii*i.", "n") -BUILTIN(__sync_fetch_and_xor_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_fetch_and_xor_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_fetch_and_xor_1, "ccD*c.", "n") +BUILTIN(__sync_fetch_and_xor_2, "ssD*s.", "n") +BUILTIN(__sync_fetch_and_xor_4, "iiD*i.", "n") +BUILTIN(__sync_fetch_and_xor_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_fetch_and_xor_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_add_and_fetch, "v.", "") -BUILTIN(__sync_add_and_fetch_1, "cc*c.", "n") -BUILTIN(__sync_add_and_fetch_2, "ss*s.", "n") -BUILTIN(__sync_add_and_fetch_4, "ii*i.", "n") -BUILTIN(__sync_add_and_fetch_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_add_and_fetch_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_add_and_fetch_1, "ccD*c.", "n") +BUILTIN(__sync_add_and_fetch_2, "ssD*s.", "n") +BUILTIN(__sync_add_and_fetch_4, "iiD*i.", "n") +BUILTIN(__sync_add_and_fetch_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_add_and_fetch_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_sub_and_fetch, "v.", "") -BUILTIN(__sync_sub_and_fetch_1, "cc*c.", "n") -BUILTIN(__sync_sub_and_fetch_2, "ss*s.", "n") -BUILTIN(__sync_sub_and_fetch_4, "ii*i.", "n") -BUILTIN(__sync_sub_and_fetch_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_sub_and_fetch_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_sub_and_fetch_1, "ccD*c.", "n") +BUILTIN(__sync_sub_and_fetch_2, "ssD*s.", "n") +BUILTIN(__sync_sub_and_fetch_4, "iiD*i.", "n") +BUILTIN(__sync_sub_and_fetch_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_sub_and_fetch_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_or_and_fetch, "v.", "") -BUILTIN(__sync_or_and_fetch_1, "cc*c.", "n") -BUILTIN(__sync_or_and_fetch_2, "ss*s.", "n") -BUILTIN(__sync_or_and_fetch_4, "ii*i.", "n") -BUILTIN(__sync_or_and_fetch_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_or_and_fetch_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_or_and_fetch_1, "ccD*c.", "n") +BUILTIN(__sync_or_and_fetch_2, "ssD*s.", "n") +BUILTIN(__sync_or_and_fetch_4, "iiD*i.", "n") +BUILTIN(__sync_or_and_fetch_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_or_and_fetch_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_and_and_fetch, "v.", "") -BUILTIN(__sync_and_and_fetch_1, "cc*c.", "n") -BUILTIN(__sync_and_and_fetch_2, "ss*s.", "n") -BUILTIN(__sync_and_and_fetch_4, "ii*i.", "n") -BUILTIN(__sync_and_and_fetch_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_and_and_fetch_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_and_and_fetch_1, "ccD*c.", "n") +BUILTIN(__sync_and_and_fetch_2, "ssD*s.", "n") +BUILTIN(__sync_and_and_fetch_4, "iiD*i.", "n") +BUILTIN(__sync_and_and_fetch_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_and_and_fetch_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_xor_and_fetch, "v.", "") -BUILTIN(__sync_xor_and_fetch_1, "cc*c.", "n") -BUILTIN(__sync_xor_and_fetch_2, "ss*s.", "n") -BUILTIN(__sync_xor_and_fetch_4, "ii*i.", "n") -BUILTIN(__sync_xor_and_fetch_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_xor_and_fetch_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_xor_and_fetch_1, "ccD*c.", "n") +BUILTIN(__sync_xor_and_fetch_2, "ssD*s.", "n") +BUILTIN(__sync_xor_and_fetch_4, "iiD*i.", "n") +BUILTIN(__sync_xor_and_fetch_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_xor_and_fetch_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_bool_compare_and_swap, "v.", "") BUILTIN(__sync_bool_compare_and_swap_1, "bcD*cc.", "n") @@ -448,18 +455,18 @@ BUILTIN(__sync_val_compare_and_swap_8, "LLiLLiD*LLiLLi.", "n") BUILTIN(__sync_val_compare_and_swap_16, "LLLiLLLiD*LLLiLLLi.", "n") BUILTIN(__sync_lock_test_and_set, "v.", "") -BUILTIN(__sync_lock_test_and_set_1, "cc*c.", "n") -BUILTIN(__sync_lock_test_and_set_2, "ss*s.", "n") -BUILTIN(__sync_lock_test_and_set_4, "ii*i.", "n") -BUILTIN(__sync_lock_test_and_set_8, "LLiLLi*LLi.", "n") -BUILTIN(__sync_lock_test_and_set_16, "LLLiLLLi*LLLi.", "n") +BUILTIN(__sync_lock_test_and_set_1, "ccD*c.", "n") +BUILTIN(__sync_lock_test_and_set_2, "ssD*s.", "n") +BUILTIN(__sync_lock_test_and_set_4, "iiD*i.", "n") +BUILTIN(__sync_lock_test_and_set_8, "LLiLLiD*LLi.", "n") +BUILTIN(__sync_lock_test_and_set_16, "LLLiLLLiD*LLLi.", "n") BUILTIN(__sync_lock_release, "v.", "") -BUILTIN(__sync_lock_release_1, "vc*.", "n") -BUILTIN(__sync_lock_release_2, "vs*.", "n") -BUILTIN(__sync_lock_release_4, "vi*.", "n") -BUILTIN(__sync_lock_release_8, "vLLi*.", "n") -BUILTIN(__sync_lock_release_16, "vLLLi*.", "n") +BUILTIN(__sync_lock_release_1, "vcD*.", "n") +BUILTIN(__sync_lock_release_2, "vsD*.", "n") +BUILTIN(__sync_lock_release_4, "viD*.", "n") +BUILTIN(__sync_lock_release_8, "vLLiD*.", "n") +BUILTIN(__sync_lock_release_16, "vLLLiD*.", "n") @@ -468,10 +475,10 @@ BUILTIN(__sync_synchronize, "v.", "n") // LLVM instruction builtin [Clang extension]. BUILTIN(__builtin_llvm_memory_barrier,"vbbbbb", "n") // GCC does not support these, they are a Clang extension. -BUILTIN(__sync_fetch_and_min, "ii*i", "n") -BUILTIN(__sync_fetch_and_max, "ii*i", "n") -BUILTIN(__sync_fetch_and_umin, "UiUi*Ui", "n") -BUILTIN(__sync_fetch_and_umax, "UiUi*Ui", "n") +BUILTIN(__sync_fetch_and_min, "iiD*i", "n") +BUILTIN(__sync_fetch_and_max, "iiD*i", "n") +BUILTIN(__sync_fetch_and_umin, "UiUiD*Ui", "n") +BUILTIN(__sync_fetch_and_umax, "UiUiD*Ui", "n") // Random libc builtins. BUILTIN(__builtin_abort, "v", "Fnr") @@ -516,6 +523,7 @@ LIBBUILTIN(vprintf, "icC*a", "fP:0:", "stdio.h") LIBBUILTIN(vfprintf, "i.", "fP:1:", "stdio.h") LIBBUILTIN(vsnprintf, "ic*zcC*a", "fP:2:", "stdio.h") LIBBUILTIN(vsprintf, "ic*cC*a", "fP:1:", "stdio.h") +LIBBUILTIN(scanf, "icC*.", "fs:0:", "stdio.h") // C99 LIBBUILTIN(longjmp, "vJi", "fr", "setjmp.h") @@ -560,5 +568,10 @@ LIBBUILTIN(cos, "dd", "fe", "math.h") LIBBUILTIN(cosl, "LdLd", "fe", "math.h") LIBBUILTIN(cosf, "ff", "fe", "math.h") +// Blocks runtime Builtin math library functions +LIBBUILTIN(_Block_object_assign, "vv*vC*iC", "f", "Blocks.h") +LIBBUILTIN(_Block_object_dispose, "vvC*iC", "f", "Blocks.h") +// FIXME: Also declare NSConcreteGlobalBlock and NSConcreteStackBlock. + #undef BUILTIN #undef LIBBUILTIN diff --git a/include/clang/Basic/Builtins.h b/include/clang/Basic/Builtins.h index 07f091a58a4..94d5e6955a2 100644 --- a/include/clang/Basic/Builtins.h +++ b/include/clang/Basic/Builtins.h @@ -119,6 +119,11 @@ public: /// argument and whether this function as a va_list argument. bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg); + /// \brief Determine whether this builtin is like scanf in its + /// formatting rules and, if so, set the index to the format string + /// argument and whether this function as a va_list argument. + bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg); + /// hasVAListUse - Return true of the specified builtin uses __builtin_va_list /// as an operand or return type. bool hasVAListUse(unsigned ID) const { diff --git a/include/clang/Basic/BuiltinsARM.def b/include/clang/Basic/BuiltinsARM.def index 54e4c2b2083..080d17fa1e3 100644 --- a/include/clang/Basic/BuiltinsARM.def +++ b/include/clang/Basic/BuiltinsARM.def @@ -15,9 +15,21 @@ // The format of this database matches clang/Basic/Builtins.def. // In libgcc -BUILTIN(__clear_cache, "vc*c*", "") +BUILTIN(__clear_cache, "v.", "") BUILTIN(__builtin_thread_pointer, "v*", "") +// Saturating arithmetic +BUILTIN(__builtin_arm_qadd, "iii", "nc") +BUILTIN(__builtin_arm_qsub, "iii", "nc") +BUILTIN(__builtin_arm_ssat, "iiUi", "nc") +BUILTIN(__builtin_arm_usat, "UiUiUi", "nc") + +// VFP +BUILTIN(__builtin_arm_get_fpscr, "Ui", "nc") +BUILTIN(__builtin_arm_set_fpscr, "vUi", "nc") +BUILTIN(__builtin_arm_vcvtr_f, "ffi", "nc") +BUILTIN(__builtin_arm_vcvtr_d, "fdi", "nc") + // NEON #define GET_NEON_BUILTINS #include "clang/Basic/arm_neon.inc" diff --git a/include/clang/Basic/BuiltinsX86.def b/include/clang/Basic/BuiltinsX86.def index a878dd1bd1a..5ad64b9b49d 100644 --- a/include/clang/Basic/BuiltinsX86.def +++ b/include/clang/Basic/BuiltinsX86.def @@ -22,10 +22,81 @@ // definition anyway, since code generation will lower to the // intrinsic if one exists. -BUILTIN(__builtin_ia32_emms , "v", "") - // FIXME: Are these nothrow/const? +// MMX +BUILTIN(__builtin_ia32_emms, "v", "") +BUILTIN(__builtin_ia32_femms, "v", "") +BUILTIN(__builtin_ia32_paddb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_paddw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_paddd, "V2iV2iV2i", "") +BUILTIN(__builtin_ia32_paddsb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_paddsw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_paddusb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_paddusw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_psubb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_psubw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_psubd, "V2iV2iV2i", "") +BUILTIN(__builtin_ia32_psubsb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_psubsw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_psubusb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_psubusw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pmulhw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pmullw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pmulhuw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pmuludq, "V1LLiV2iV2i", "") +BUILTIN(__builtin_ia32_pmaddwd, "V2iV4sV4s", "") +BUILTIN(__builtin_ia32_pand, "V1LLiV1LLiV1LLi", "") +BUILTIN(__builtin_ia32_pandn, "V1LLiV1LLiV1LLi", "") +BUILTIN(__builtin_ia32_por, "V1LLiV1LLiV1LLi", "") +BUILTIN(__builtin_ia32_pxor, "V1LLiV1LLiV1LLi", "") +BUILTIN(__builtin_ia32_pavgb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_pavgw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pmaxub, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_pmaxsw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pminub, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_pminsw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_psadbw, "V4sV8cV8c", "") +BUILTIN(__builtin_ia32_psllw, "V4sV4sV1LLi", "") +BUILTIN(__builtin_ia32_pslld, "V2iV2iV1LLi", "") +BUILTIN(__builtin_ia32_psllq, "V1LLiV1LLiV1LLi", "") +BUILTIN(__builtin_ia32_psrlw, "V4sV4sV1LLi", "") +BUILTIN(__builtin_ia32_psrld, "V2iV2iV1LLi", "") +BUILTIN(__builtin_ia32_psrlq, "V1LLiV1LLiV1LLi", "") +BUILTIN(__builtin_ia32_psraw, "V4sV4sV1LLi", "") +BUILTIN(__builtin_ia32_psrad, "V2iV2iV1LLi", "") +BUILTIN(__builtin_ia32_psllwi, "V4sV4si", "") +BUILTIN(__builtin_ia32_pslldi, "V2iV2ii", "") +BUILTIN(__builtin_ia32_psllqi, "V1LLiV1LLii", "") +BUILTIN(__builtin_ia32_psrlwi, "V4sV4si", "") +BUILTIN(__builtin_ia32_psrldi, "V2iV2ii", "") +BUILTIN(__builtin_ia32_psrlqi, "V1LLiV1LLii", "") +BUILTIN(__builtin_ia32_psrawi, "V4sV4si", "") +BUILTIN(__builtin_ia32_psradi, "V2iV2ii", "") +BUILTIN(__builtin_ia32_packsswb, "V8cV4sV4s", "") +BUILTIN(__builtin_ia32_packssdw, "V4sV2iV2i", "") +BUILTIN(__builtin_ia32_packuswb, "V8cV4sV4s", "") +BUILTIN(__builtin_ia32_punpckhbw, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_punpckhwd, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_punpckhdq, "V2iV2iV2i", "") +BUILTIN(__builtin_ia32_punpcklbw, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_punpcklwd, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_punpckldq, "V2iV2iV2i", "") +BUILTIN(__builtin_ia32_pcmpeqb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_pcmpeqw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pcmpeqd, "V2iV2iV2i", "") +BUILTIN(__builtin_ia32_pcmpgtb, "V8cV8cV8c", "") +BUILTIN(__builtin_ia32_pcmpgtw, "V4sV4sV4s", "") +BUILTIN(__builtin_ia32_pcmpgtd, "V2iV2iV2i", "") +BUILTIN(__builtin_ia32_maskmovq, "vV8cV8cc*", "") +BUILTIN(__builtin_ia32_pmovmskb, "iV8c", "") +BUILTIN(__builtin_ia32_movntq, "vV1LLi*V1LLi", "") +BUILTIN(__builtin_ia32_palignr, "V8cV8cV8cc", "") // FIXME: Correct type? +BUILTIN(__builtin_ia32_vec_init_v2si, "V2iii", "") +BUILTIN(__builtin_ia32_vec_init_v4hi, "V4sssss", "") +BUILTIN(__builtin_ia32_vec_init_v8qi, "V8ccccccccc", "") +BUILTIN(__builtin_ia32_vec_ext_v2si, "iV2ii", "") + // SSE intrinsics. BUILTIN(__builtin_ia32_comieq, "iV4fV4f", "") BUILTIN(__builtin_ia32_comilt, "iV4fV4f", "") @@ -57,29 +128,6 @@ BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "") -BUILTIN(__builtin_ia32_paddsb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_paddsw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_psubsb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_psubsw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_paddusb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_paddusw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_psubusb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_psubusw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pmulhw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pmulhuw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pavgb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_pavgw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pcmpeqb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_pcmpeqw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pcmpeqd, "V2iV2iV2i", "") -BUILTIN(__builtin_ia32_pcmpgtb, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_pcmpgtw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pcmpgtd, "V2iV2iV2i", "") -BUILTIN(__builtin_ia32_pmaxub, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_pmaxsw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_pminub, "V8cV8cV8c", "") -BUILTIN(__builtin_ia32_pminsw, "V4sV4sV4s", "") -BUILTIN(__builtin_ia32_punpcklwd, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dc", "") BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dc", "") BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "") @@ -147,18 +195,6 @@ BUILTIN(__builtin_ia32_pabsw128, "V8sV8s", "") BUILTIN(__builtin_ia32_pabsw, "V4sV4s", "") BUILTIN(__builtin_ia32_pabsd128, "V4iV4i", "") BUILTIN(__builtin_ia32_pabsd, "V2iV2i", "") -BUILTIN(__builtin_ia32_psllw, "V4sV4sV1LLi", "") -BUILTIN(__builtin_ia32_pslld, "V2iV2iV1LLi", "") -BUILTIN(__builtin_ia32_psllq, "V1LLiV1LLiV1LLi", "") -BUILTIN(__builtin_ia32_psrlw, "V4sV4sV1LLi", "") -BUILTIN(__builtin_ia32_psrld, "V2iV2iV1LLi", "") -BUILTIN(__builtin_ia32_psrlq, "V1LLiV1LLiV1LLi", "") -BUILTIN(__builtin_ia32_psraw, "V4sV4sV1LLi", "") -BUILTIN(__builtin_ia32_psrad, "V2iV2iV1LLi", "") -BUILTIN(__builtin_ia32_pmaddwd, "V2iV4sV4s", "") -BUILTIN(__builtin_ia32_packsswb, "V8cV4sV4s", "") -BUILTIN(__builtin_ia32_packssdw, "V4sV2iV2i", "") -BUILTIN(__builtin_ia32_packuswb, "V8cV4sV4s", "") BUILTIN(__builtin_ia32_ldmxcsr, "vUi", "") BUILTIN(__builtin_ia32_stmxcsr, "Ui", "") BUILTIN(__builtin_ia32_cvtpi2ps, "V4fV4fV2i", "") @@ -166,17 +202,13 @@ BUILTIN(__builtin_ia32_cvtps2pi, "V2iV4f", "") BUILTIN(__builtin_ia32_cvtss2si, "iV4f", "") BUILTIN(__builtin_ia32_cvtss2si64, "LLiV4f", "") BUILTIN(__builtin_ia32_cvttps2pi, "V2iV4f", "") -BUILTIN(__builtin_ia32_maskmovq, "vV8cV8cc*", "") BUILTIN(__builtin_ia32_loadups, "V4ffC*", "") BUILTIN(__builtin_ia32_storeups, "vf*V4f", "") BUILTIN(__builtin_ia32_storehps, "vV2i*V4f", "") BUILTIN(__builtin_ia32_storelps, "vV2i*V4f", "") BUILTIN(__builtin_ia32_movmskps, "iV4f", "") -BUILTIN(__builtin_ia32_pmovmskb, "iV8c", "") BUILTIN(__builtin_ia32_movntps, "vf*V4f", "") -BUILTIN(__builtin_ia32_movntq, "vV1LLi*V1LLi", "") BUILTIN(__builtin_ia32_sfence, "v", "") -BUILTIN(__builtin_ia32_psadbw, "V4sV8cV8c", "") BUILTIN(__builtin_ia32_rcpps, "V4fV4f", "") BUILTIN(__builtin_ia32_rcpss, "V4fV4f", "") BUILTIN(__builtin_ia32_rsqrtps, "V4fV4f", "") @@ -212,15 +244,6 @@ BUILTIN(__builtin_ia32_lfence, "v", "") BUILTIN(__builtin_ia32_mfence, "v", "") BUILTIN(__builtin_ia32_loaddqu, "V16ccC*", "") BUILTIN(__builtin_ia32_storedqu, "vc*V16c", "") -BUILTIN(__builtin_ia32_psllwi, "V4sV4si", "") -BUILTIN(__builtin_ia32_pslldi, "V2iV2ii", "") -BUILTIN(__builtin_ia32_psllqi, "V1LLiV1LLii", "") -BUILTIN(__builtin_ia32_psrawi, "V4sV4si", "") -BUILTIN(__builtin_ia32_psradi, "V2iV2ii", "") -BUILTIN(__builtin_ia32_psrlwi, "V4sV4si", "") -BUILTIN(__builtin_ia32_psrldi, "V2iV2ii", "") -BUILTIN(__builtin_ia32_psrlqi, "V1LLiV1LLii", "") -BUILTIN(__builtin_ia32_pmuludq, "V1LLiV2iV2i", "") BUILTIN(__builtin_ia32_pmuludq128, "V2LLiV4iV4i", "") BUILTIN(__builtin_ia32_psraw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psrad128, "V4iV4iV4i", "") @@ -244,8 +267,7 @@ BUILTIN(__builtin_ia32_pmaddwd128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_monitor, "vv*UiUi", "") BUILTIN(__builtin_ia32_mwait, "vUiUi", "") BUILTIN(__builtin_ia32_lddqu, "V16ccC*", "") -BUILTIN(__builtin_ia32_palignr128, "V16cV16cV16cc", "") -BUILTIN(__builtin_ia32_palignr, "V8cV8cV8cc", "") +BUILTIN(__builtin_ia32_palignr128, "V16cV16cV16cc", "") // FIXME: Correct type? BUILTIN(__builtin_ia32_insertps128, "V4fV4fV4fi", "") BUILTIN(__builtin_ia32_storelv4si, "vV2i*V2LLi", "") @@ -324,5 +346,98 @@ BUILTIN(__builtin_ia32_aesenclast128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_aesdec128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_aesdeclast128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_aesimc128, "V2LLiV2LLi", "") -BUILTIN(__builtin_ia32_aeskeygenassist128, "V2LLiV2LLii", "") +BUILTIN(__builtin_ia32_aeskeygenassist128, "V2LLiV2LLic", "") + +// AVX +BUILTIN(__builtin_ia32_addsubpd256, "V4dV4dV4d", "") +BUILTIN(__builtin_ia32_addsubps256, "V8fV8fV8f", "") +BUILTIN(__builtin_ia32_haddpd256, "V4dV4dV4d", "") +BUILTIN(__builtin_ia32_hsubps256, "V8fV8fV8f", "") +BUILTIN(__builtin_ia32_hsubpd256, "V4dV4dV4d", "") +BUILTIN(__builtin_ia32_haddps256, "V8fV8fV8f", "") +BUILTIN(__builtin_ia32_maxpd256, "V4dV4dV4d", "") +BUILTIN(__builtin_ia32_maxps256, "V8fV8fV8f", "") +BUILTIN(__builtin_ia32_minpd256, "V4dV4dV4d", "") +BUILTIN(__builtin_ia32_minps256, "V8fV8fV8f", "") +BUILTIN(__builtin_ia32_vpermilvarpd, "V2dV2dV2LLi", "") +BUILTIN(__builtin_ia32_vpermilvarps, "V4fV4fV4i", "") +BUILTIN(__builtin_ia32_vpermilvarpd256, "V4dV4dV4LLi", "") +BUILTIN(__builtin_ia32_vpermilvarps256, "V8fV8fV8i", "") +BUILTIN(__builtin_ia32_blendpd256, "V4dV4dV4di", "") +BUILTIN(__builtin_ia32_blendps256, "V8fV8fV8fi", "") +BUILTIN(__builtin_ia32_blendvpd256, "V4dV4dV4dV4d", "") +BUILTIN(__builtin_ia32_blendvps256, "V8fV8fV8fV8f", "") +BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fi", "") +BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dc", "") +BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fc", "") +BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dc", "") +BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fc", "") +BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8ic", "") +BUILTIN(__builtin_ia32_cvtdq2pd256, "V4dV4i", "") +BUILTIN(__builtin_ia32_cvtdq2ps256, "V8fV8i", "") +BUILTIN(__builtin_ia32_cvtpd2ps256, "V4fV4d", "") +BUILTIN(__builtin_ia32_cvtps2dq256, "V8iV8f", "") +BUILTIN(__builtin_ia32_cvtps2pd256, "V4dV4f", "") +BUILTIN(__builtin_ia32_cvttpd2dq256, "V4iV4d", "") +BUILTIN(__builtin_ia32_cvtpd2dq256, "V4iV4d", "") +BUILTIN(__builtin_ia32_cvttps2dq256, "V8iV8f", "") +BUILTIN(__builtin_ia32_vperm2f128_pd256, "V4dV4dV4dc", "") +BUILTIN(__builtin_ia32_vperm2f128_ps256, "V8fV8fV8fc", "") +BUILTIN(__builtin_ia32_vperm2f128_si256, "V8iV8iV8ic", "") +BUILTIN(__builtin_ia32_vpermilpd, "V2dV2dc", "") +BUILTIN(__builtin_ia32_vpermilps, "V4fV4fc", "") +BUILTIN(__builtin_ia32_vpermilpd256, "V4dV4dc", "") +BUILTIN(__builtin_ia32_vpermilps256, "V8fV8fc", "") +BUILTIN(__builtin_ia32_vinsertf128_pd256, "V4dV4dV2dc", "") +BUILTIN(__builtin_ia32_vinsertf128_ps256, "V8fV8fV4fc", "") +BUILTIN(__builtin_ia32_vinsertf128_si256, "V8iV8iV4ic", "") +BUILTIN(__builtin_ia32_sqrtpd256, "V4dV4d", "") +BUILTIN(__builtin_ia32_sqrtps256, "V8fV8f", "") +BUILTIN(__builtin_ia32_rsqrtps256, "V8fV8f", "") +BUILTIN(__builtin_ia32_rcpps256, "V8fV8f", "") +BUILTIN(__builtin_ia32_roundpd256, "V4dV4di", "") +BUILTIN(__builtin_ia32_roundps256, "V8fV8fi", "") +BUILTIN(__builtin_ia32_vtestzpd, "iV2dV2d", "") +BUILTIN(__builtin_ia32_vtestcpd, "iV2dV2d", "") +BUILTIN(__builtin_ia32_vtestnzcpd, "iV2dV2d", "") +BUILTIN(__builtin_ia32_vtestzps, "iV4fV4f", "") +BUILTIN(__builtin_ia32_vtestcps, "iV4fV4f", "") +BUILTIN(__builtin_ia32_vtestnzcps, "iV4fV4f", "") +BUILTIN(__builtin_ia32_vtestzpd256, "iV4dV4d", "") +BUILTIN(__builtin_ia32_vtestcpd256, "iV4dV4d", "") +BUILTIN(__builtin_ia32_vtestnzcpd256, "iV4dV4d", "") +BUILTIN(__builtin_ia32_vtestzps256, "iV8fV8f", "") +BUILTIN(__builtin_ia32_vtestcps256, "iV8fV8f", "") +BUILTIN(__builtin_ia32_vtestnzcps256, "iV8fV8f", "") +BUILTIN(__builtin_ia32_ptestz256, "iV4LLiV4LLi", "") +BUILTIN(__builtin_ia32_ptestc256, "iV4LLiV4LLi", "") +BUILTIN(__builtin_ia32_ptestnzc256, "iV4LLiV4LLi", "") +BUILTIN(__builtin_ia32_movmskpd256, "iV4d", "") +BUILTIN(__builtin_ia32_movmskps256, "iV8f", "") +BUILTIN(__builtin_ia32_vzeroall, "v", "") +BUILTIN(__builtin_ia32_vzeroupper, "v", "") +BUILTIN(__builtin_ia32_vbroadcastss, "V4ffC*", "") +BUILTIN(__builtin_ia32_vbroadcastsd256, "V4ddC*", "") +BUILTIN(__builtin_ia32_vbroadcastss256, "V8ffC*", "") +BUILTIN(__builtin_ia32_vbroadcastf128_pd256, "V4dV2dC*", "") +BUILTIN(__builtin_ia32_vbroadcastf128_ps256, "V8fV4fC*", "") +BUILTIN(__builtin_ia32_loadupd256, "V4ddC*", "") +BUILTIN(__builtin_ia32_loadups256, "V8ffC*", "") +BUILTIN(__builtin_ia32_storeupd256, "vd*V4d", "") +BUILTIN(__builtin_ia32_storeups256, "vf*V8f", "") +BUILTIN(__builtin_ia32_loaddqu256, "V32ccC*", "") +BUILTIN(__builtin_ia32_storedqu256, "vc*V32c", "") +BUILTIN(__builtin_ia32_lddqu256, "V32ccC*", "") +BUILTIN(__builtin_ia32_movntdq256, "vV4LLi*V4LLi", "") +BUILTIN(__builtin_ia32_movntpd256, "vd*V4d", "") +BUILTIN(__builtin_ia32_movntps256, "vf*V8f", "") +BUILTIN(__builtin_ia32_maskloadpd, "V2dV2dC*V2d", "") +BUILTIN(__builtin_ia32_maskloadps, "V4fV4fC*V4f", "") +BUILTIN(__builtin_ia32_maskloadpd256, "V4dV4dC*V4d", "") +BUILTIN(__builtin_ia32_maskloadps256, "V8fV8fC*V8f", "") +BUILTIN(__builtin_ia32_maskstorepd, "vV2d*V2dV2d", "") +BUILTIN(__builtin_ia32_maskstoreps, "vV4f*V4fV4f", "") +BUILTIN(__builtin_ia32_maskstorepd256, "vV4d*V4dV4d", "") +BUILTIN(__builtin_ia32_maskstoreps256, "vV8f*V8fV8f", "") + #undef BUILTIN diff --git a/include/clang/Basic/DeclNodes.td b/include/clang/Basic/DeclNodes.td index 203fb451e38..e2f93e02c52 100644 --- a/include/clang/Basic/DeclNodes.td +++ b/include/clang/Basic/DeclNodes.td @@ -43,8 +43,9 @@ def Named : Decl<1>; def ParmVar : DDecl; def NonTypeTemplateParm : DDecl; def Template : DDecl; - def FunctionTemplate : DDecl